ob-java.el 20 KB

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