ob-C.el 17 KB

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