ob-C.el 15 KB

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