dotemacs

My Emacs configuration
git clone git://git.entf.net/dotemacs
Log | Files | Refs | LICENSE

ob-java.el (20586B)


      1 ;;; ob-java.el --- org-babel functions for java evaluation -*- lexical-binding: t -*-
      2 
      3 ;; Copyright (C) 2011-2023 Free Software Foundation, Inc.
      4 
      5 ;; Authors: Eric Schulte
      6 ;;          Dan Davison
      7 ;; Maintainer: Ian Martins <ianxm@jhu.edu>
      8 ;; Keywords: literate programming, reproducible research
      9 ;; URL: https://orgmode.org
     10 
     11 ;; This file is part of GNU Emacs.
     12 
     13 ;; GNU Emacs is free software: you can redistribute it and/or modify
     14 ;; it under the terms of the GNU General Public License as published by
     15 ;; the Free Software Foundation, either version 3 of the License, or
     16 ;; (at your option) any later version.
     17 
     18 ;; GNU Emacs is distributed in the hope that it will be useful,
     19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
     20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     21 ;; GNU General Public License for more details.
     22 
     23 ;; You should have received a copy of the GNU General Public License
     24 ;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
     25 
     26 ;;; Commentary:
     27 
     28 ;; Org-Babel support for evaluating java source code.
     29 
     30 ;;; Code:
     31 
     32 (require 'org-macs)
     33 (org-assert-version)
     34 
     35 (require 'ob)
     36 
     37 (defvar org-babel-tangle-lang-exts)
     38 (add-to-list 'org-babel-tangle-lang-exts '("java" . "java"))
     39 
     40 (defvar org-babel-temporary-directory) ; from ob-core
     41 
     42 (defvar org-babel-default-header-args:java '((:results . "output")
     43 					     (:dir . "."))
     44   "Default header args for java source blocks.
     45 The docs say functional mode should be the default [1], but
     46 ob-java didn't originally support functional mode, so we keep
     47 scripting mode as the default for now to maintain previous
     48 behavior.
     49 
     50 Most languages write tempfiles to babel's temporary directory,
     51 but ob-java originally had to write them to the current
     52 directory, so we keep that as the default behavior.
     53 
     54 [1] https://orgmode.org/manual/Results-of-Evaluation.html")
     55 
     56 (defconst org-babel-header-args:java
     57   '((dir       . :any)
     58     (classname . :any)
     59     (imports   . :any)
     60     (cmpflag   . :any)
     61     (cmdline   . :any)
     62     (cmdarg    . :any))
     63   "Java-specific header arguments.")
     64 
     65 (defcustom org-babel-java-command "java"
     66   "Name of the java command.
     67 May be either a command in the path, like java or an absolute
     68 path name, like /usr/local/bin/java.  Parameters may be used,
     69 like java -verbose."
     70   :group 'org-babel
     71   :package-version '(Org . "9.5")
     72   :type 'string)
     73 
     74 (defcustom org-babel-java-compiler "javac"
     75   "Name of the java compiler.
     76 May be either a command in the path, like javac or an absolute
     77 path name, like /usr/local/bin/javac.  Parameters may be used,
     78 like javac -verbose."
     79   :group 'org-babel
     80   :package-version '(Org . "9.5")
     81   :type 'string)
     82 
     83 (defcustom org-babel-java-hline-to "null"
     84   "Replace hlines in incoming tables with this when translating to java."
     85   :group 'org-babel
     86   :package-version '(Org . "9.5")
     87   :type 'string)
     88 
     89 (defcustom org-babel-java-null-to 'hline
     90   "Replace `null' in java tables with this before returning."
     91   :group 'org-babel
     92   :package-version '(Org . "9.5")
     93   :type 'symbol)
     94 
     95 (defconst org-babel-java--package-re (rx line-start (0+ space) "package"
     96 					 (1+ space) (group (1+ (in alnum ?_ ?.))) ; capture the package name
     97 					 (0+ space) ?\; line-end)
     98   "Regexp for the package statement.")
     99 (defconst org-babel-java--imports-re (rx line-start (0+ space) "import"
    100                                          (opt (1+ space) "static")
    101 					 (1+ space) (group (1+ (in alnum ?_ ?. ?*))) ; capture the fully qualified class name
    102 					 (0+ space) ?\; line-end)
    103   "Regexp for import statements.")
    104 (defconst org-babel-java--class-re (rx line-start (0+ space) (opt (seq "public" (1+ space)))
    105 				       "class" (1+ space)
    106 				       (group (1+ (in alnum ?_))) ; capture the class name
    107 				       (0+ space) ?{)
    108   "Regexp for the class declaration.")
    109 (defconst org-babel-java--main-re
    110   (rx line-start (0+ space) "public"
    111       (1+ space) "static"
    112       (1+ space) "void"
    113       (1+ space) "main"
    114       (0+ space) ?\(
    115       (0+ space) "String"
    116       (1+ (in alnum ?_ ?\[ ?\] space)) ; "[] args" or "args[]"
    117       ?\)
    118       (0+ space) (opt "throws" (1+ (in alnum ?_ ?, ?. space)))
    119       ?{)
    120   "Regexp for the main method declaration.")
    121 (defconst org-babel-java--any-method-re
    122   (rx line-start
    123       (0+ space) (opt (seq (1+ alnum) (1+ space)))   ; visibility
    124       (opt (seq "static" (1+ space)))                ; binding
    125       (1+ (in alnum ?_ ?\[ ?\]))                     ; return type
    126       (1+ space) (1+ (in alnum ?_))                  ; method name
    127       (0+ space) ?\(
    128       (0+ (in alnum ?_ ?\[ ?\] ?, space)) ; params
    129       ?\)
    130       (0+ space) (opt "throws" (1+ (in alnum ?_ ?, ?. space)))
    131       ?{)
    132   "Regexp for any method.")
    133 (defconst org-babel-java--result-wrapper "\n    public static String __toString(Object val) {
    134         if (val instanceof String) {
    135             return \"\\\"\" + val + \"\\\"\";
    136         } else if (val == null) {
    137             return \"null\";
    138         } else if (val.getClass().isArray()) {
    139             StringBuffer sb = new StringBuffer();
    140             Object[] vals = (Object[])val;
    141             sb.append(\"[\");
    142             for (int ii=0; ii<vals.length; ii++) {
    143                 sb.append(__toString(vals[ii]));
    144                 if (ii<vals.length-1)
    145                     sb.append(\",\");
    146             }
    147             sb.append(\"]\");
    148             return sb.toString();
    149         } else if (val instanceof List) {
    150             StringBuffer sb = new StringBuffer();
    151             List vals = (List)val;
    152             sb.append(\"[\");
    153             for (int ii=0; ii<vals.size(); ii++) {
    154                 sb.append(__toString(vals.get(ii)));
    155                 if (ii<vals.size()-1)
    156                     sb.append(\",\");
    157             }
    158             sb.append(\"]\");
    159             return sb.toString();
    160         } else {
    161             return String.valueOf(val);
    162         }
    163     }
    164 
    165     public static void main(String[] args) throws IOException {
    166         BufferedWriter output = new BufferedWriter(new FileWriter(\"%s\"));
    167         output.write(__toString(_main(args)));
    168         output.close();
    169     }"
    170   "Code to inject into a class so that we can capture the value it returns.
    171 This implementation was inspired by ob-python, although not as
    172 elegant.  This modified the source block to write out the value
    173 it wants to return to a temporary file so that ob-java can read
    174 it back.  The name of the temporary file to write must be
    175 replaced in this string.")
    176 
    177 (defun org-babel-execute:java (body params)
    178   "Execute a java source block with BODY code and PARAMS params."
    179   (let* (;; allow header overrides
    180          (org-babel-java-compiler
    181           (or (cdr (assq :javac params))
    182               org-babel-java-compiler))
    183          (org-babel-java-command
    184           (or (cdr (assq :java params))
    185               org-babel-java-command))
    186          ;; if true, run from babel temp directory
    187          (run-from-temp (not (cdr (assq :dir params))))
    188          ;; class and package
    189          (fullclassname (or (cdr (assq :classname params))
    190                             (org-babel-java-find-classname body)))
    191          ;; just the class name
    192          (classname (car (last (split-string fullclassname "\\."))))
    193          ;; just the package name
    194          (packagename (if (string-match-p "\\." fullclassname)
    195                           (file-name-base fullclassname)))
    196          ;; the base dir that contains the top level package dir
    197          (basedir (file-name-as-directory
    198                    (if run-from-temp
    199                        (org-babel-temp-directory)
    200                      default-directory)))
    201          ;; the dir to write the source file
    202          (packagedir (if (and (not run-from-temp) packagename)
    203                          (file-name-as-directory
    204                           (concat basedir (replace-regexp-in-string "\\." "/" packagename)))
    205                        basedir))
    206          ;; the filename of the source file
    207          (src-file (concat packagedir classname ".java"))
    208          ;; compiler flags
    209          (cmpflag (or (cdr (assq :cmpflag params)) ""))
    210          ;; runtime flags
    211          (cmdline (or (cdr (assq :cmdline params)) ""))
    212          ;; command line args
    213          (cmdargs (or (cdr (assq :cmdargs params)) ""))
    214          ;; the command to compile and run
    215          (cmd (concat org-babel-java-compiler " " cmpflag " "
    216                       (org-babel-process-file-name src-file 'noquote)
    217                       " && " org-babel-java-command
    218                       " -cp " (org-babel-process-file-name basedir 'noquote)
    219                       " " cmdline " " (if run-from-temp classname fullclassname)
    220                       " " cmdargs))
    221          ;; header args for result processing
    222          (result-type (cdr (assq :result-type params)))
    223          (result-params (cdr (assq :result-params params)))
    224          (result-file (and (eq result-type 'value)
    225                            (org-babel-temp-file "java-")))
    226          ;; the expanded body of the source block
    227          (full-body (org-babel-expand-body:java body params)))
    228 
    229     ;; created package-name directories if missing
    230     (unless (or (not packagedir) (file-exists-p packagedir))
    231       (make-directory packagedir 'parents))
    232 
    233     ;; write the source file
    234     (setq full-body (org-babel-java--expand-for-evaluation
    235                      full-body run-from-temp result-type result-file))
    236     (with-temp-file src-file (insert full-body))
    237 
    238     ;; compile, run, process result
    239     (org-babel-reassemble-table
    240      (org-babel-java-evaluate cmd result-type result-params result-file)
    241      (org-babel-pick-name
    242       (cdr (assoc :colname-names params)) (cdr (assoc :colnames params)))
    243      (org-babel-pick-name
    244       (cdr (assoc :rowname-names params)) (cdr (assoc :rownames params))))))
    245 
    246 ;; helper functions
    247 
    248 (defun org-babel-java-find-classname (body)
    249   "Try to find fully qualified class name in BODY.
    250 Look through BODY for the package and class.  If found, put them
    251 together into a fully qualified class name and return.  Else just
    252 return class name.  If that isn't found either, default to Main."
    253   (let ((package (if (string-match org-babel-java--package-re body)
    254                      (match-string 1 body)))
    255         (class (if (string-match org-babel-java--class-re body)
    256                    (match-string 1 body))))
    257     (or (and package class (concat package "." class))
    258         (and class class)
    259         (and package (concat package ".Main"))
    260         "Main")))
    261 
    262 (defun org-babel-java--expand-for-evaluation (body suppress-package-p result-type result-file)
    263   "Expand source block for evaluation.
    264 In order to return a value we have to add a __toString method.
    265 In order to prevent classes without main methods from erroring we
    266 add a dummy main method if one is not provided.  These
    267 manipulations are done outside of `org-babel--expand-body' so
    268 that they are hidden from tangles.
    269 
    270 BODY is the file content before instrumentation.
    271 
    272 SUPPRESS-PACKAGE-P if true, suppress the package statement.
    273 
    274 RESULT-TYPE is taken from params.
    275 
    276 RESULT-FILE is the temp file to write the result."
    277   (with-temp-buffer
    278     (insert body)
    279 
    280     ;; suppress package statement
    281     (goto-char (point-min))
    282     (when (and suppress-package-p
    283                (re-search-forward org-babel-java--package-re nil t))
    284       (replace-match ""))
    285 
    286     ;; add a dummy main method if needed
    287     (goto-char (point-min))
    288     (when (not (re-search-forward org-babel-java--main-re nil t))
    289       (org-babel-java--move-past org-babel-java--class-re)
    290       (insert "\n    public static void main(String[] args) {
    291         System.out.print(\"success\");
    292     }\n\n"))
    293 
    294     ;; special handling to return value
    295     (when (eq result-type 'value)
    296       (goto-char (point-min))
    297       (org-babel-java--move-past org-babel-java--class-re)
    298       (insert (format org-babel-java--result-wrapper
    299                       (org-babel-process-file-name result-file 'noquote)))
    300       (search-forward "public static void main(") ; rename existing main
    301       (replace-match "public static Object _main("))
    302 
    303     ;; add imports
    304     (org-babel-java--import-maybe "java.util" "List")
    305     (org-babel-java--import-maybe "java.util" "Arrays")
    306     (org-babel-java--import-maybe "java.io" "BufferedWriter")
    307     (org-babel-java--import-maybe "java.io" "FileWriter")
    308     (org-babel-java--import-maybe "java.io" "IOException")
    309 
    310     (buffer-string)))
    311 
    312 (defun org-babel-java--move-past (re)
    313   "Move point past the first occurrence of the given regexp RE."
    314   (while (re-search-forward re nil t)
    315     (goto-char (1+ (match-end 0)))))
    316 
    317 (defun org-babel-java--import-maybe (package class)
    318   "Import from PACKAGE the given CLASS if it is used and not already imported."
    319   (let (class-found import-found)
    320     (goto-char (point-min))
    321     (setq class-found (re-search-forward class nil t))
    322     (goto-char (point-min))
    323     (setq import-found
    324           (re-search-forward (concat "^import .*" package ".*\\(?:\\*\\|" class "\\);") nil t))
    325     (when (and class-found (not import-found))
    326       (org-babel-java--move-past org-babel-java--package-re)
    327       (insert (concat "import " package "." class ";\n")))))
    328 
    329 (defun org-babel-expand-body:java (body params)
    330   "Expand BODY with PARAMS.
    331 BODY could be a few statements, or could include a full class
    332 definition specifying package, imports, and class.  Because we
    333 allow this flexibility in what the source block can contain, it
    334 is simplest to expand the code block from the inside out."
    335   (let* ((fullclassname (or (cdr (assq :classname params)) ; class and package
    336                             (org-babel-java-find-classname body)))
    337          (classname (car (last (split-string fullclassname "\\.")))) ; just class name
    338          (packagename (if (string-match-p "\\." fullclassname)       ; just package name
    339                           (file-name-base fullclassname)))
    340          (var-lines (org-babel-variable-assignments:java params))
    341          (imports-val (assq :imports params))
    342          (imports (if imports-val
    343                       (split-string (org-babel-read (cdr imports-val) nil) " ")
    344                     nil)))
    345     (with-temp-buffer
    346       (insert body)
    347 
    348       ;; wrap main.  If there are methods defined, but no main method
    349       ;; and no class, wrap everything in a generic main method.
    350       (goto-char (point-min))
    351       (when (and (not (re-search-forward org-babel-java--main-re nil t))
    352                  (not (re-search-forward org-babel-java--any-method-re nil t)))
    353         (org-babel-java--move-past org-babel-java--package-re) ; if package is defined, move past it
    354         (org-babel-java--move-past org-babel-java--imports-re) ; if imports are defined, move past them
    355         (insert "public static void main(String[] args) {\n")
    356         (indent-code-rigidly (point) (point-max) 4)
    357         (goto-char (point-max))
    358         (insert "\n}"))
    359 
    360       ;; wrap class.  If there's no class, wrap everything in a
    361       ;; generic class.
    362       (goto-char (point-min))
    363       (when (not (re-search-forward org-babel-java--class-re nil t))
    364         (org-babel-java--move-past org-babel-java--package-re) ; if package is defined, move past it
    365         (org-babel-java--move-past org-babel-java--imports-re) ; if imports are defined, move past them
    366         (insert (concat "\npublic class " (file-name-base classname) " {\n"))
    367         (indent-code-rigidly (point) (point-max) 4)
    368         (goto-char (point-max))
    369         (insert "\n}"))
    370       (goto-char (point-min))
    371 
    372       ;; insert variables from source block headers
    373       (when var-lines
    374         (goto-char (point-min))
    375         (org-babel-java--move-past org-babel-java--class-re)   ; move inside class
    376         (insert (mapconcat 'identity var-lines "\n"))
    377         (insert "\n"))
    378 
    379       ;; add imports from source block headers
    380       (when imports
    381         (goto-char (point-min))
    382         (org-babel-java--move-past org-babel-java--package-re) ; if package is defined, move past it
    383         (insert (mapconcat (lambda (package) (concat "import " package ";")) imports "\n") "\n"))
    384 
    385       ;; add package at the top
    386       (goto-char (point-min))
    387       (when (and packagename (not (re-search-forward org-babel-java--package-re nil t)))
    388         (insert (concat "package " packagename ";\n")))
    389 
    390       ;; return expanded body
    391       (buffer-string))))
    392 
    393 (defun org-babel-variable-assignments:java (params)
    394   "Return a list of java statements assigning the block's variables.
    395 variables are contained in PARAMS."
    396   (mapcar
    397    (lambda (pair)
    398      (let* ((type-data (org-babel-java-val-to-type (cdr pair)))
    399             (basetype (car type-data))
    400             (var-to-java (lambda (var) (funcall #'org-babel-java-var-to-java var basetype))))
    401        (format "    static %s %s = %s;"
    402                (cdr type-data)                     ; type
    403                (car pair)                          ; name
    404                (funcall var-to-java (cdr pair))))) ; value
    405    (org-babel--get-vars params)))
    406 
    407 (defun org-babel-java-var-to-java (var basetype)
    408   "Convert an elisp value to a java variable.
    409 Convert an elisp value, VAR, of type BASETYPE into a string of
    410 java source code specifying a variable of the same value."
    411   (cond ((and (sequencep var) (not (stringp var)))
    412          (let ((var-to-java (lambda (var) (funcall #'org-babel-java-var-to-java var basetype))))
    413            (concat "Arrays.asList(" (mapconcat var-to-java var ", ") ")")))
    414         ((eq var 'hline) org-babel-java-hline-to)
    415         ((eq basetype 'integerp) (format "%d" var))
    416         ((eq basetype 'floatp) (format "%f" var))
    417         ((eq basetype 'stringp) (if (and (stringp var) (string-match-p ".\n+." var))
    418                                     (error "Java does not support multiline string literals")
    419                                   (format "\"%s\"" var)))))
    420 
    421 (defun org-babel-java-val-to-type (val)
    422   "Determine the type of VAL.
    423 Return (BASETYPE . LISTTYPE), where BASETYPE is a symbol
    424 representing the type of the individual items in VAL, and
    425 LISTTYPE is a string name of the type parameter for a container
    426 for BASETYPE items."
    427   (let* ((basetype (org-babel-java-val-to-base-type val))
    428          (basetype-str (pcase basetype
    429                          (`integerp "Integer")
    430                          (`floatp "Double")
    431                          (`stringp "String")
    432                          (_ (error "Unknown type %S" basetype)))))
    433     (cond
    434      ((and (listp val) (listp (car val))) ; a table
    435       (cons basetype (format "List<List<%s>>" basetype-str)))
    436      ((or (listp val) (vectorp val))      ; a list declared in the source block header
    437       (cons basetype (format "List<%s>" basetype-str)))
    438      (t                                   ; return base type
    439       (cons basetype basetype-str)))))
    440 
    441 (defun org-babel-java-val-to-base-type (val)
    442   "Determine the base type of VAL.
    443 VAL may be
    444 `integerp' if all base values are integers
    445 `floatp' if all base values are either floating points or integers
    446 `stringp' otherwise."
    447   (cond
    448    ((integerp val) 'integerp)
    449    ((floatp val) 'floatp)
    450    ((or (listp val) (vectorp val))
    451     (let ((type nil))
    452       (mapc (lambda (v)
    453               (pcase (org-babel-java-val-to-base-type v)
    454                 (`stringp (setq type 'stringp))
    455                 (`floatp
    456                  (when (or (not type) (eq type 'integerp))
    457                    (setq type 'floatp)))
    458                 (`integerp
    459                  (unless type (setq type 'integerp)))))
    460             val)
    461       type))
    462    (t 'stringp)))
    463 
    464 (defun org-babel-java-table-or-string (results)
    465   "Convert RESULTS into an appropriate elisp value.
    466 If the results look like a list or vector, then convert them into an
    467 Emacs-lisp table, otherwise return the results as a string."
    468   (let ((res (org-babel-script-escape results)))
    469     (if (listp res)
    470         (mapcar (lambda (el) (if (eq 'null el)
    471                                  org-babel-java-null-to
    472                                el))
    473                 res)
    474       res)))
    475 
    476 (defun org-babel-java-evaluate (cmd result-type result-params result-file)
    477   "Evaluate using an external java process.
    478 CMD the command to execute.
    479 
    480 If RESULT-TYPE equals `output' then return standard output as a
    481 string.  If RESULT-TYPE equals `value' then return the value
    482 returned by the source block, as elisp.
    483 
    484 RESULT-PARAMS input params used to format the response.
    485 
    486 RESULT-FILE filename of the tempfile to store the returned value in
    487 for `value' RESULT-TYPE.  Not used for `output' RESULT-TYPE."
    488   (let ((raw (pcase result-type
    489                (`output (org-babel-eval cmd ""))
    490                (`value (org-babel-eval cmd "")
    491                        (org-babel-eval-read-file result-file)))))
    492     (org-babel-result-cond result-params raw
    493                            (org-babel-java-table-or-string raw))))
    494 
    495 (provide 'ob-java)
    496 
    497 ;;; ob-java.el ends here