ob-java.el 20 KB

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