ob-C.el 17 KB

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