ob-java.el 20 KB

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