ob-C.el 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. ;;; ob-C.el --- Babel Functions for C and Similar Languages -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2010-2015 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte
  4. ;; Thierry Banel
  5. ;; Keywords: literate programming, reproducible research
  6. ;; Homepage: http://orgmode.org
  7. ;; This file is part of GNU Emacs.
  8. ;; GNU Emacs is free software: you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation, either version 3 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;; Org-Babel support for evaluating C, C++, D code.
  20. ;;
  21. ;; very limited implementation:
  22. ;; - currently only support :results output
  23. ;; - not much in the way of error feedback
  24. ;;; Code:
  25. (require 'ob)
  26. (require 'cc-mode)
  27. (declare-function org-entry-get "org"
  28. (pom property &optional inherit literal-nil))
  29. (declare-function org-remove-indentation "org" (code &optional n))
  30. (defvar org-babel-tangle-lang-exts)
  31. (add-to-list 'org-babel-tangle-lang-exts '("C++" . "cpp"))
  32. (add-to-list 'org-babel-tangle-lang-exts '("D" . "d"))
  33. (defvar org-babel-default-header-args:C '())
  34. (defcustom org-babel-C-compiler "gcc"
  35. "Command used to compile a C source code file into an executable.
  36. May be either a command in the path, like gcc
  37. or an absolute path name, like /usr/local/bin/gcc
  38. parameter may be used, like gcc -v"
  39. :group 'org-babel
  40. :version "24.3"
  41. :type 'string)
  42. (defcustom org-babel-C++-compiler "g++"
  43. "Command used to compile a C++ source code file into an executable.
  44. May be either a command in the path, like g++
  45. or an absolute path name, like /usr/local/bin/g++
  46. parameter may be used, like g++ -v"
  47. :group 'org-babel
  48. :version "24.3"
  49. :type 'string)
  50. (defcustom org-babel-D-compiler "rdmd"
  51. "Command used to compile and execute a D source code file.
  52. May be either a command in the path, like rdmd
  53. or an absolute path name, like /usr/local/bin/rdmd
  54. parameter may be used, like rdmd --chatty"
  55. :group 'org-babel
  56. :version "24.3"
  57. :type 'string)
  58. (defvar org-babel-c-variant nil
  59. "Internal variable used to hold which type of C (e.g. C or C++ or D)
  60. is currently being evaluated.")
  61. (defun org-babel-execute:cpp (body params)
  62. "Execute BODY according to PARAMS.
  63. This function calls `org-babel-execute:C++'."
  64. (org-babel-execute:C++ body params))
  65. (defun org-babel-expand-body:cpp (body params)
  66. "Expand a block of C++ code with org-babel according to it's
  67. header arguments."
  68. (org-babel-expand-body:C++ body params))
  69. (defun org-babel-execute:C++ (body params)
  70. "Execute a block of C++ code with org-babel.
  71. This function is called by `org-babel-execute-src-block'."
  72. (let ((org-babel-c-variant 'cpp)) (org-babel-C-execute body params)))
  73. (defun org-babel-expand-body:C++ (body params)
  74. "Expand a block of C++ code with org-babel according to it's
  75. header arguments."
  76. (let ((org-babel-c-variant 'cpp)) (org-babel-C-expand-C++ body params)))
  77. (defun org-babel-execute:D (body params)
  78. "Execute a block of D code with org-babel.
  79. This function is called by `org-babel-execute-src-block'."
  80. (let ((org-babel-c-variant 'd)) (org-babel-C-execute body params)))
  81. (defun org-babel-expand-body:D (body params)
  82. "Expand a block of D code with org-babel according to it's
  83. header arguments."
  84. (let ((org-babel-c-variant 'd)) (org-babel-C-expand-D body params)))
  85. (defun org-babel-execute:C (body params)
  86. "Execute a block of C code with org-babel.
  87. This function is called by `org-babel-execute-src-block'."
  88. (let ((org-babel-c-variant 'c)) (org-babel-C-execute body params)))
  89. (defun org-babel-expand-body:C (body params)
  90. "Expand a block of C code with org-babel according to it's
  91. header arguments."
  92. (let ((org-babel-c-variant 'c)) (org-babel-C-expand-C body params)))
  93. (defun org-babel-C-execute (body params)
  94. "This function should only be called by `org-babel-execute:C'
  95. or `org-babel-execute:C++' or `org-babel-execute:D'."
  96. (let* ((tmp-src-file (org-babel-temp-file
  97. "C-src-"
  98. (case org-babel-c-variant
  99. (c ".c" )
  100. (cpp ".cpp")
  101. (d ".d" ))))
  102. (tmp-bin-file (org-babel-temp-file "C-bin-" org-babel-exeext)) ;; not used for D
  103. (cmdline (cdr (assoc :cmdline params)))
  104. (cmdline (if cmdline (concat " " cmdline) ""))
  105. (flags (cdr (assoc :flags params)))
  106. (flags (mapconcat 'identity
  107. (if (listp flags) flags (list flags)) " "))
  108. (full-body
  109. (case org-babel-c-variant
  110. (c (org-babel-C-expand-C body params))
  111. (cpp (org-babel-C-expand-C++ body params))
  112. (d (org-babel-C-expand-D body params)))))
  113. (with-temp-file tmp-src-file (insert full-body))
  114. (case org-babel-c-variant
  115. ((c cpp)
  116. (org-babel-eval
  117. (format "%s -o %s %s %s"
  118. (case org-babel-c-variant
  119. (c org-babel-C-compiler)
  120. (cpp org-babel-C++-compiler))
  121. (org-babel-process-file-name tmp-bin-file)
  122. flags
  123. (org-babel-process-file-name tmp-src-file)) ""))
  124. (d nil)) ;; no separate compilation for D
  125. (let ((results
  126. (org-babel-eval
  127. (case org-babel-c-variant
  128. ((c cpp)
  129. (concat tmp-bin-file cmdline))
  130. (d
  131. (format "%s %s %s %s"
  132. org-babel-D-compiler
  133. flags
  134. (org-babel-process-file-name tmp-src-file)
  135. cmdline)))
  136. "")))
  137. (when results
  138. (setq results (org-babel-trim (org-remove-indentation results)))
  139. (org-babel-reassemble-table
  140. (org-babel-result-cond (cdr (assoc :result-params params))
  141. (org-babel-read results t)
  142. (let ((tmp-file (org-babel-temp-file "c-")))
  143. (with-temp-file tmp-file (insert results))
  144. (org-babel-import-elisp-from-file tmp-file)))
  145. (org-babel-pick-name
  146. (cdr (assoc :colname-names params)) (cdr (assoc :colnames params)))
  147. (org-babel-pick-name
  148. (cdr (assoc :rowname-names params)) (cdr (assoc :rownames params)))))
  149. )))
  150. (defun org-babel-C-expand-C++ (body params)
  151. "Expand a block of C or C++ code with org-babel according to
  152. it's header arguments."
  153. (org-babel-C-expand-C body params))
  154. (defun org-babel-C-expand-C (body params)
  155. "Expand a block of C or C++ code with org-babel according to
  156. it's header arguments."
  157. (let ((vars (mapcar #'cdr (org-babel-get-header params :var)))
  158. (colnames (cdar (org-babel-get-header params :colname-names)))
  159. (main-p (not (string= (cdr (assoc :main params)) "no")))
  160. (includes (org-babel-read
  161. (or (cdr (assoc :includes params))
  162. (org-entry-get nil "includes" t))
  163. nil))
  164. (defines (org-babel-read
  165. (or (cdr (assoc :defines params))
  166. (org-entry-get nil "defines" t))
  167. nil)))
  168. (when (stringp includes)
  169. (setq includes (split-string includes)))
  170. (when (stringp defines)
  171. (let ((y nil)
  172. (result (list t)))
  173. (dolist (x (split-string defines))
  174. (if (null y)
  175. (setq y x)
  176. (nconc result (list (concat y " " x)))
  177. (setq y nil)))
  178. (setq defines (cdr result))))
  179. (mapconcat 'identity
  180. (list
  181. ;; includes
  182. (mapconcat
  183. (lambda (inc) (format "#include %s" inc))
  184. includes "\n")
  185. ;; defines
  186. (mapconcat
  187. (lambda (inc) (format "#define %s" inc))
  188. (if (listp defines) defines (list defines)) "\n")
  189. ;; variables
  190. (mapconcat 'org-babel-C-var-to-C vars "\n")
  191. ;; table sizes
  192. (mapconcat 'org-babel-C-table-sizes-to-C vars "\n")
  193. ;; tables headers utility
  194. (when colnames
  195. (org-babel-C-utility-header-to-C))
  196. ;; tables headers
  197. (mapconcat 'org-babel-C-header-to-C colnames "\n")
  198. ;; body
  199. (if main-p
  200. (org-babel-C-ensure-main-wrap body)
  201. body) "\n") "\n")))
  202. (defun org-babel-C-expand-D (body params)
  203. "Expand a block of D code with org-babel according to
  204. it's header arguments."
  205. (let ((vars (mapcar #'cdr (org-babel-get-header params :var)))
  206. (colnames (cdar (org-babel-get-header params :colname-names)))
  207. (main-p (not (string= (cdr (assoc :main params)) "no")))
  208. (imports (or (cdr (assoc :imports params))
  209. (org-babel-read (org-entry-get nil "imports" t)))))
  210. (when (stringp imports)
  211. (setq imports (split-string imports)))
  212. (setq imports (append imports '("std.stdio" "std.conv")))
  213. (mapconcat 'identity
  214. (list
  215. "module mmm;"
  216. ;; imports
  217. (mapconcat
  218. (lambda (inc) (format "import %s;" inc))
  219. imports "\n")
  220. ;; variables
  221. (mapconcat 'org-babel-C-var-to-C vars "\n")
  222. ;; table sizes
  223. (mapconcat 'org-babel-C-table-sizes-to-C vars "\n")
  224. ;; tables headers utility
  225. (when colnames
  226. (org-babel-C-utility-header-to-C))
  227. ;; tables headers
  228. (mapconcat 'org-babel-C-header-to-C colnames "\n")
  229. ;; body
  230. (if main-p
  231. (org-babel-C-ensure-main-wrap body)
  232. body) "\n") "\n")))
  233. (defun org-babel-C-ensure-main-wrap (body)
  234. "Wrap BODY in a \"main\" function call if none exists."
  235. (if (string-match "^[ \t]*[intvod]+[ \t\n\r]*main[ \t]*(.*)" body)
  236. body
  237. (format "int main() {\n%s\nreturn 0;\n}\n" body)))
  238. (defun org-babel-prep-session:C (_session _params)
  239. "This function does nothing as C is a compiled language with no
  240. support for sessions"
  241. (error "C is a compiled languages -- no support for sessions"))
  242. (defun org-babel-load-session:C (_session _body _params)
  243. "This function does nothing as C is a compiled language with no
  244. support for sessions"
  245. (error "C is a compiled languages -- no support for sessions"))
  246. ;; helper functions
  247. (defun org-babel-C-format-val (type val)
  248. "Handle the FORMAT part of TYPE with the data from VAL."
  249. (let ((format-data (cadr type)))
  250. (if (stringp format-data)
  251. (cons "" (format format-data val))
  252. (funcall format-data val))))
  253. (defun org-babel-C-val-to-C-type (val)
  254. "Determine the type of VAL.
  255. Return a list (TYPE-NAME FORMAT). TYPE-NAME should be the name of the type.
  256. FORMAT can be either a format string or a function which is called with VAL."
  257. (let* ((basetype (org-babel-C-val-to-base-type val))
  258. (type
  259. (case basetype
  260. (integerp '("int" "%d"))
  261. (floatp '("double" "%f"))
  262. (stringp
  263. (list
  264. (if (equal org-babel-c-variant 'd) "string" "const char*")
  265. "\"%s\""))
  266. (t (error "unknown type %S" basetype)))))
  267. (cond
  268. ((integerp val) type) ;; an integer declared in the #+begin_src line
  269. ((floatp val) type) ;; a numeric declared in the #+begin_src line
  270. ((and (listp val) (listp (car val))) ;; a table
  271. `(,(car type)
  272. (lambda (val)
  273. (cons
  274. (format "[%d][%d]" (length val) (length (car val)))
  275. (concat
  276. (if (equal org-babel-c-variant 'd) "[\n" "{\n")
  277. (mapconcat
  278. (lambda (v)
  279. (concat
  280. (if (equal org-babel-c-variant 'd) " [" " {")
  281. (mapconcat (lambda (w) (format ,(cadr type) w)) v ",")
  282. (if (equal org-babel-c-variant 'd) "]" "}")))
  283. val
  284. ",\n")
  285. (if (equal org-babel-c-variant 'd) "\n]" "\n}"))))))
  286. ((or (listp val) (vectorp val)) ;; a list declared in the #+begin_src line
  287. `(,(car type)
  288. (lambda (val)
  289. (cons
  290. (format "[%d]" (length val))
  291. (concat
  292. (if (equal org-babel-c-variant 'd) "[" "{")
  293. (mapconcat (lambda (v) (format ,(cadr type) v)) val ",")
  294. (if (equal org-babel-c-variant 'd) "]" "}"))))))
  295. (t ;; treat unknown types as string
  296. type))))
  297. (defun org-babel-C-val-to-base-type (val)
  298. "Determine the base type of VAL which may be
  299. `integerp' if all base values are integers
  300. `floatp' if all base values are either floating points or integers
  301. `stringp' otherwise."
  302. (cond
  303. ((integerp val) 'integerp)
  304. ((floatp val) 'floatp)
  305. ((or (listp val) (vectorp val))
  306. (let ((type nil))
  307. (mapc (lambda (v)
  308. (case (org-babel-C-val-to-base-type v)
  309. (stringp (setq type 'stringp))
  310. (floatp
  311. (if (or (not type) (eq type 'integerp))
  312. (setq type 'floatp)))
  313. (integerp
  314. (unless type (setq type 'integerp)))))
  315. val)
  316. type))
  317. (t 'stringp)))
  318. (defun org-babel-C-var-to-C (pair)
  319. "Convert an elisp val into a string of C code specifying a var
  320. of the same value."
  321. ;; TODO list support
  322. (let ((var (car pair))
  323. (val (cdr pair)))
  324. (when (symbolp val)
  325. (setq val (symbol-name val))
  326. (when (= (length val) 1)
  327. (setq val (string-to-char val))))
  328. (let* ((type-data (org-babel-C-val-to-C-type val))
  329. (type (car type-data))
  330. (formated (org-babel-C-format-val type-data val))
  331. (suffix (car formated))
  332. (data (cdr formated)))
  333. (format "%s %s%s = %s;"
  334. type
  335. var
  336. suffix
  337. data))))
  338. (defun org-babel-C-table-sizes-to-C (pair)
  339. "Create constants of table dimensions, if PAIR is a table."
  340. (when (listp (cdr pair))
  341. (cond
  342. ((listp (cadr pair)) ;; a table
  343. (concat
  344. (format "const int %s_rows = %d;" (car pair) (length (cdr pair)))
  345. "\n"
  346. (format "const int %s_cols = %d;" (car pair) (length (cadr pair)))))
  347. (t ;; a list declared in the #+begin_src line
  348. (format "const int %s_cols = %d;" (car pair) (length (cdr pair)))))))
  349. (defun org-babel-C-utility-header-to-C ()
  350. "Generate a utility function to convert a column name
  351. into a column number."
  352. (case org-babel-c-variant
  353. ((c cpp)
  354. "int get_column_num (int nbcols, const char** header, const char* column)
  355. {
  356. int c;
  357. for (c=0; c<nbcols; c++)
  358. if (strcmp(header[c],column)==0)
  359. return c;
  360. return -1;
  361. }
  362. "
  363. )
  364. (d
  365. "int get_column_num (string[] header, string column)
  366. {
  367. foreach (c, h; header)
  368. if (h==column)
  369. return to!int(c);
  370. return -1;
  371. }
  372. "
  373. )))
  374. (defun org-babel-C-header-to-C (head)
  375. "Convert an elisp list of header table into a C or D vector
  376. specifying a variable with the name of the table."
  377. (let ((table (car head))
  378. (headers (cdr head)))
  379. (concat
  380. (format
  381. (case org-babel-c-variant
  382. ((c cpp) "const char* %s_header[%d] = {%s};")
  383. (d "string %s_header[%d] = [%s];"))
  384. table
  385. (length headers)
  386. (mapconcat (lambda (h) (format "%S" h)) headers ","))
  387. "\n"
  388. (case org-babel-c-variant
  389. ((c cpp)
  390. (format
  391. "const char* %s_h (int row, const char* col) { return %s[row][get_column_num(%d,%s_header,col)]; }"
  392. table table (length headers) table))
  393. (d
  394. (format
  395. "string %s_h (ulong row, string col) { return %s[row][get_column_num(%s_header,col)]; }"
  396. table table table))))))
  397. (provide 'ob-C)
  398. ;;; ob-C.el ends here