ob-java.el 20 KB

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