ob-C.el 14 KB

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