ob-java.el 20 KB

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