config

Personal configuration.
git clone git://code.dwrz.net/config
Log | Files | Refs

ob-java.el (20776B)


      1 ;;; ob-java.el --- org-babel functions for java evaluation -*- lexical-binding: t -*-
      2 
      3 ;; Copyright (C) 2011-2024 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          (prologue (cdr (assq :prologue params)))
    346          (epilogue (cdr (assq :epilogue params))))
    347     (with-temp-buffer
    348       (when prologue (insert prologue "\n"))
    349       (insert body)
    350       (when epilogue (insert "\n" epilogue))
    351 
    352       ;; wrap main.  If there are methods defined, but no main method
    353       ;; and no class, wrap everything in a generic main method.
    354       (goto-char (point-min))
    355       (when (and (not (re-search-forward org-babel-java--main-re nil t))
    356                  (not (re-search-forward org-babel-java--any-method-re nil t)))
    357         (org-babel-java--move-past org-babel-java--package-re) ; if package is defined, move past it
    358         (org-babel-java--move-past org-babel-java--imports-re) ; if imports are defined, move past them
    359         (insert "public static void main(String[] args) {\n")
    360         (indent-code-rigidly (point) (point-max) 4)
    361         (goto-char (point-max))
    362         (insert "\n}"))
    363 
    364       ;; wrap class.  If there's no class, wrap everything in a
    365       ;; generic class.
    366       (goto-char (point-min))
    367       (when (not (re-search-forward org-babel-java--class-re nil t))
    368         (org-babel-java--move-past org-babel-java--package-re) ; if package is defined, move past it
    369         (org-babel-java--move-past org-babel-java--imports-re) ; if imports are defined, move past them
    370         (insert (concat "\npublic class " (file-name-base classname) " {\n"))
    371         (indent-code-rigidly (point) (point-max) 4)
    372         (goto-char (point-max))
    373         (insert "\n}"))
    374       (goto-char (point-min))
    375 
    376       ;; insert variables from source block headers
    377       (when var-lines
    378         (goto-char (point-min))
    379         (org-babel-java--move-past org-babel-java--class-re)   ; move inside class
    380         (insert (mapconcat 'identity var-lines "\n"))
    381         (insert "\n"))
    382 
    383       ;; add imports from source block headers
    384       (when imports
    385         (goto-char (point-min))
    386         (org-babel-java--move-past org-babel-java--package-re) ; if package is defined, move past it
    387         (insert (mapconcat (lambda (package) (concat "import " package ";")) imports "\n") "\n"))
    388 
    389       ;; add package at the top
    390       (goto-char (point-min))
    391       (when (and packagename (not (re-search-forward org-babel-java--package-re nil t)))
    392         (insert (concat "package " packagename ";\n")))
    393 
    394       ;; return expanded body
    395       (buffer-string))))
    396 
    397 (defun org-babel-variable-assignments:java (params)
    398   "Return a list of java statements assigning the block's variables.
    399 variables are contained in PARAMS."
    400   (mapcar
    401    (lambda (pair)
    402      (let* ((type-data (org-babel-java-val-to-type (cdr pair)))
    403             (basetype (car type-data))
    404             (var-to-java (lambda (var) (funcall #'org-babel-java-var-to-java var basetype))))
    405        (format "    static %s %s = %s;"
    406                (cdr type-data)                     ; type
    407                (car pair)                          ; name
    408                (funcall var-to-java (cdr pair))))) ; value
    409    (org-babel--get-vars params)))
    410 
    411 (defun org-babel-java-var-to-java (var basetype)
    412   "Convert an elisp value to a java variable.
    413 Convert an elisp value, VAR, of type BASETYPE into a string of
    414 java source code specifying a variable of the same value."
    415   (cond ((and (sequencep var) (not (stringp var)))
    416          (let ((var-to-java (lambda (var) (funcall #'org-babel-java-var-to-java var basetype))))
    417            (concat "Arrays.asList(" (mapconcat var-to-java var ", ") ")")))
    418         ((eq var 'hline) org-babel-java-hline-to)
    419         ((eq basetype 'integerp) (format "%d" var))
    420         ((eq basetype 'floatp) (format "%f" var))
    421         ((eq basetype 'stringp) (if (and (stringp var) (string-match-p ".\n+." var))
    422                                     (error "Java does not support multiline string literals")
    423                                   (format "\"%s\"" var)))))
    424 
    425 (defun org-babel-java-val-to-type (val)
    426   "Determine the type of VAL.
    427 Return (BASETYPE . LISTTYPE), where BASETYPE is a symbol
    428 representing the type of the individual items in VAL, and
    429 LISTTYPE is a string name of the type parameter for a container
    430 for BASETYPE items."
    431   (let* ((basetype (org-babel-java-val-to-base-type val))
    432          (basetype-str (pcase basetype
    433                          (`integerp "Integer")
    434                          (`floatp "Double")
    435                          (`stringp "String")
    436                          (_ (error "Unknown type %S" basetype)))))
    437     (cond
    438      ((and (listp val) (listp (car val))) ; a table
    439       (cons basetype (format "List<List<%s>>" basetype-str)))
    440      ((or (listp val) (vectorp val))      ; a list declared in the source block header
    441       (cons basetype (format "List<%s>" basetype-str)))
    442      (t                                   ; return base type
    443       (cons basetype basetype-str)))))
    444 
    445 (defun org-babel-java-val-to-base-type (val)
    446   "Determine the base type of VAL.
    447 VAL may be
    448 `integerp' if all base values are integers
    449 `floatp' if all base values are either floating points or integers
    450 `stringp' otherwise."
    451   (cond
    452    ((integerp val) 'integerp)
    453    ((floatp val) 'floatp)
    454    ((or (listp val) (vectorp val))
    455     (let ((type nil))
    456       (mapc (lambda (v)
    457               (pcase (org-babel-java-val-to-base-type v)
    458                 (`stringp (setq type 'stringp))
    459                 (`floatp
    460                  (when (or (not type) (eq type 'integerp))
    461                    (setq type 'floatp)))
    462                 (`integerp
    463                  (unless type (setq type 'integerp)))))
    464             val)
    465       type))
    466    (t 'stringp)))
    467 
    468 (defun org-babel-java-table-or-string (results)
    469   "Convert RESULTS into an appropriate elisp value.
    470 If the results look like a list or vector, then convert them into an
    471 Emacs-lisp table, otherwise return the results as a string."
    472   (let ((res (org-babel-script-escape results)))
    473     (if (listp res)
    474         (mapcar (lambda (el) (if (eq 'null el)
    475                                  org-babel-java-null-to
    476                                el))
    477                 res)
    478       res)))
    479 
    480 (defun org-babel-java-evaluate (cmd result-type result-params result-file)
    481   "Evaluate using an external java process.
    482 CMD the command to execute.
    483 
    484 If RESULT-TYPE equals `output' then return standard output as a
    485 string.  If RESULT-TYPE equals `value' then return the value
    486 returned by the source block, as elisp.
    487 
    488 RESULT-PARAMS input params used to format the response.
    489 
    490 RESULT-FILE filename of the tempfile to store the returned value in
    491 for `value' RESULT-TYPE.  Not used for `output' RESULT-TYPE."
    492   (let ((raw (pcase result-type
    493                (`output (org-babel-eval cmd ""))
    494                (`value (org-babel-eval cmd "")
    495                        (org-babel-eval-read-file result-file)))))
    496     (org-babel-result-cond result-params raw
    497                            (org-babel-java-table-or-string raw))))
    498 
    499 (provide 'ob-java)
    500 
    501 ;;; ob-java.el ends here