ob-java.el 19 KB

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