ob-java.el 18 KB

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