ob-java.el 20 KB

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