1 ;;; ob-C.el --- Babel Functions for C and Similar Languages -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2010-2019 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte
7 ;; Keywords: literate programming, reproducible research
8 ;; Homepage: https://orgmode.org
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
27 ;; Org-Babel support for evaluating C, C++, D code.
29 ;; very limited implementation:
30 ;; - currently only support :results output
31 ;; - not much in the way of error feedback
39 (declare-function org-entry-get
"org" (pom property
&optional inherit literal-nil
))
41 (defvar org-babel-tangle-lang-exts
)
42 (add-to-list 'org-babel-tangle-lang-exts
'("C++" .
"cpp"))
43 (add-to-list 'org-babel-tangle-lang-exts
'("D" .
"d"))
45 (defvar org-babel-default-header-args
:C
'())
47 (defconst org-babel-header-args
:C
'((includes .
:any
)
53 "C/C++-specific header arguments.")
55 (defconst org-babel-header-args
:C
++
56 (append '((namespaces .
:any
))
57 org-babel-header-args
:C
)
58 "C++-specific header arguments.")
60 (defcustom org-babel-C-compiler
"gcc"
61 "Command used to compile a C source code file into an executable.
62 May be either a command in the path, like gcc
63 or an absolute path name, like /usr/local/bin/gcc
64 parameter may be used, like gcc -v"
69 (defcustom org-babel-C
++-compiler
"g++"
70 "Command used to compile a C++ source code file into an executable.
71 May be either a command in the path, like g++
72 or an absolute path name, like /usr/local/bin/g++
73 parameter may be used, like g++ -v"
78 (defcustom org-babel-D-compiler
"rdmd"
79 "Command used to compile and execute a D source code file.
80 May be either a command in the path, like rdmd
81 or an absolute path name, like /usr/local/bin/rdmd
82 parameter may be used, like rdmd --chatty"
87 (defvar org-babel-c-variant nil
88 "Internal variable used to hold which type of C (e.g. C or C++ or D)
89 is currently being evaluated.")
91 (defun org-babel-execute:cpp
(body params
)
92 "Execute BODY according to PARAMS.
93 This function calls `org-babel-execute:C++'."
94 (org-babel-execute:C
++ body params
))
96 (defun org-babel-expand-body:cpp
(body params
)
97 "Expand a block of C++ code with org-babel according to its
99 (org-babel-expand-body:C
++ body params
))
101 (defun org-babel-execute:C
++ (body params
)
102 "Execute a block of C++ code with org-babel.
103 This function is called by `org-babel-execute-src-block'."
104 (let ((org-babel-c-variant 'cpp
)) (org-babel-C-execute body params
)))
106 (defun org-babel-expand-body:C
++ (body params
)
107 "Expand a block of C++ code with org-babel according to its
109 (let ((org-babel-c-variant 'cpp
)) (org-babel-C-expand-C++ body params
)))
111 (defun org-babel-execute:D
(body params
)
112 "Execute a block of D code with org-babel.
113 This function is called by `org-babel-execute-src-block'."
114 (let ((org-babel-c-variant 'd
)) (org-babel-C-execute body params
)))
116 (defun org-babel-expand-body:D
(body params
)
117 "Expand a block of D code with org-babel according to its
119 (let ((org-babel-c-variant 'd
)) (org-babel-C-expand-D body params
)))
121 (defun org-babel-execute:C
(body params
)
122 "Execute a block of C code with org-babel.
123 This function is called by `org-babel-execute-src-block'."
124 (let ((org-babel-c-variant 'c
)) (org-babel-C-execute body params
)))
126 (defun org-babel-expand-body:C
(body params
)
127 "Expand a block of C code with org-babel according to its
129 (let ((org-babel-c-variant 'c
)) (org-babel-C-expand-C body params
)))
131 (defun org-babel-C-execute (body params
)
132 "This function should only be called by `org-babel-execute:C'
133 or `org-babel-execute:C++' or `org-babel-execute:D'."
134 (let* ((tmp-src-file (org-babel-temp-file
136 (pcase org-babel-c-variant
137 (`c
".c") (`cpp
".cpp") (`d
".d"))))
138 (tmp-bin-file ;not used for D
139 (org-babel-process-file-name
140 (org-babel-temp-file "C-bin-" org-babel-exeext
)))
141 (cmdline (cdr (assq :cmdline params
)))
142 (cmdline (if cmdline
(concat " " cmdline
) ""))
143 (flags (cdr (assq :flags params
)))
144 (flags (mapconcat 'identity
145 (if (listp flags
) flags
(list flags
)) " "))
146 (libs (org-babel-read
147 (or (cdr (assq :libs params
))
148 (org-entry-get nil
"libs" t
))
150 (libs (mapconcat #'identity
151 (if (listp libs
) libs
(list libs
))
154 (pcase org-babel-c-variant
155 (`c
(org-babel-C-expand-C body params
))
156 (`cpp
(org-babel-C-expand-C++ body params
))
157 (`d
(org-babel-C-expand-D body params
)))))
158 (with-temp-file tmp-src-file
(insert full-body
))
159 (pcase org-babel-c-variant
162 (format "%s -o %s %s %s %s"
163 (pcase org-babel-c-variant
164 (`c org-babel-C-compiler
)
165 (`cpp org-babel-C
++-compiler
))
168 (org-babel-process-file-name tmp-src-file
)
171 (`d nil
)) ;; no separate compilation for D
174 (pcase org-babel-c-variant
176 (concat tmp-bin-file cmdline
))
178 (format "%s %s %s %s"
181 (org-babel-process-file-name tmp-src-file
)
185 (setq results
(org-trim (org-remove-indentation results
)))
186 (org-babel-reassemble-table
187 (org-babel-result-cond (cdr (assq :result-params params
))
188 (org-babel-read results t
)
189 (let ((tmp-file (org-babel-temp-file "c-")))
190 (with-temp-file tmp-file
(insert results
))
191 (org-babel-import-elisp-from-file tmp-file
)))
193 (cdr (assq :colname-names params
)) (cdr (assq :colnames params
)))
195 (cdr (assq :rowname-names params
)) (cdr (assq :rownames params
)))))
198 (defun org-babel-C-expand-C++ (body params
)
199 "Expand a block of C or C++ code with org-babel according to
200 its header arguments."
201 (org-babel-C-expand-C body params
))
203 (defun org-babel-C-expand-C (body params
)
204 "Expand a block of C or C++ code with org-babel according to
205 its header arguments."
206 (let ((vars (org-babel--get-vars params
))
207 (colnames (cdr (assq :colname-names params
)))
208 (main-p (not (string= (cdr (assq :main params
)) "no")))
209 (includes (org-babel-read
210 (cdr (assq :includes params
))
212 (defines (org-babel-read
213 (cdr (assq :defines params
))
215 (namespaces (org-babel-read
216 (cdr (assq :namespaces params
))
218 (when (stringp includes
)
219 (setq includes
(split-string includes
)))
220 (when (stringp namespaces
)
221 (setq namespaces
(split-string namespaces
)))
222 (when (stringp defines
)
225 (dolist (x (split-string defines
))
228 (nconc result
(list (concat y
" " x
)))
230 (setq defines
(cdr result
))))
235 (lambda (inc) (format "#include %s" inc
))
239 (lambda (inc) (format "#define %s" inc
))
240 (if (listp defines
) defines
(list defines
)) "\n")
243 (lambda (inc) (format "using namespace %s;" inc
))
247 (mapconcat 'org-babel-C-var-to-C vars
"\n")
249 (mapconcat 'org-babel-C-table-sizes-to-C vars
"\n")
250 ;; tables headers utility
252 (org-babel-C-utility-header-to-C))
254 (mapconcat 'org-babel-C-header-to-C colnames
"\n")
257 (org-babel-C-ensure-main-wrap body
)
260 (defun org-babel-C-expand-D (body params
)
261 "Expand a block of D code with org-babel according to
262 its header arguments."
263 (let ((vars (org-babel--get-vars params
))
264 (colnames (cdr (assq :colname-names params
)))
265 (main-p (not (string= (cdr (assq :main params
)) "no")))
266 (imports (or (cdr (assq :imports params
))
267 (org-babel-read (org-entry-get nil
"imports" t
)))))
268 (when (stringp imports
)
269 (setq imports
(split-string imports
)))
270 (setq imports
(append imports
'("std.stdio" "std.conv")))
276 (lambda (inc) (format "import %s;" inc
))
279 (mapconcat 'org-babel-C-var-to-C vars
"\n")
281 (mapconcat 'org-babel-C-table-sizes-to-C vars
"\n")
282 ;; tables headers utility
284 (org-babel-C-utility-header-to-C))
286 (mapconcat 'org-babel-C-header-to-C colnames
"\n")
289 (org-babel-C-ensure-main-wrap body
)
292 (defun org-babel-C-ensure-main-wrap (body)
293 "Wrap BODY in a \"main\" function call if none exists."
294 (if (string-match "^[ \t]*[intvod]+[ \t\n\r]*main[ \t]*(.*)" body
)
296 (format "int main() {\n%s\nreturn 0;\n}\n" body
)))
298 (defun org-babel-prep-session:C
(_session _params
)
299 "This function does nothing as C is a compiled language with no
300 support for sessions"
301 (error "C is a compiled language -- no support for sessions"))
303 (defun org-babel-load-session:C
(_session _body _params
)
304 "This function does nothing as C is a compiled language with no
305 support for sessions"
306 (error "C is a compiled language -- no support for sessions"))
310 (defun org-babel-C-format-val (type val
)
311 "Handle the FORMAT part of TYPE with the data from VAL."
312 (let ((format-data (cadr type
)))
313 (if (stringp format-data
)
314 (cons "" (format format-data val
))
315 (funcall format-data val
))))
317 (defun org-babel-C-val-to-C-type (val)
318 "Determine the type of VAL.
319 Return a list (TYPE-NAME FORMAT). TYPE-NAME should be the name of the type.
320 FORMAT can be either a format string or a function which is called with VAL."
321 (let* ((basetype (org-babel-C-val-to-base-type val
))
324 (`integerp
'("int" "%d"))
325 (`floatp
'("double" "%f"))
328 (if (eq org-babel-c-variant
'd
) "string" "const char*")
330 (_ (error "unknown type %S" basetype
)))))
332 ((integerp val
) type
) ;; an integer declared in the #+begin_src line
333 ((floatp val
) type
) ;; a numeric declared in the #+begin_src line
334 ((and (listp val
) (listp (car val
))) ;; a table
338 (format "[%d][%d]" (length val
) (length (car val
)))
340 (if (eq org-babel-c-variant
'd
) "[\n" "{\n")
344 (if (eq org-babel-c-variant
'd
) " [" " {")
345 (mapconcat (lambda (w) (format ,(cadr type
) w
)) v
",")
346 (if (eq org-babel-c-variant
'd
) "]" "}")))
349 (if (eq org-babel-c-variant
'd
) "\n]" "\n}"))))))
350 ((or (listp val
) (vectorp val
)) ;; a list declared in the #+begin_src line
354 (format "[%d]" (length val
))
356 (if (eq org-babel-c-variant
'd
) "[" "{")
357 (mapconcat (lambda (v) (format ,(cadr type
) v
)) val
",")
358 (if (eq org-babel-c-variant
'd
) "]" "}"))))))
359 (t ;; treat unknown types as string
362 (defun org-babel-C-val-to-base-type (val)
363 "Determine the base type of VAL which may be
364 `integerp' if all base values are integers
365 `floatp' if all base values are either floating points or integers
366 `stringp' otherwise."
368 ((integerp val
) 'integerp
)
369 ((floatp val
) 'floatp
)
370 ((or (listp val
) (vectorp val
))
373 (pcase (org-babel-C-val-to-base-type v
)
374 (`stringp
(setq type
'stringp
))
376 (when (or (not type
) (eq type
'integerp
))
377 (setq type
'floatp
)))
379 (unless type
(setq type
'integerp
)))))
384 (defun org-babel-C-var-to-C (pair)
385 "Convert an elisp val into a string of C code specifying a var
388 (let ((var (car pair
))
391 (setq val
(symbol-name val
))
392 (when (= (length val
) 1)
393 (setq val
(string-to-char val
))))
394 (let* ((type-data (org-babel-C-val-to-C-type val
))
395 (type (car type-data
))
396 (formated (org-babel-C-format-val type-data val
))
397 (suffix (car formated
))
398 (data (cdr formated
)))
399 (format "%s %s%s = %s;"
405 (defun org-babel-C-table-sizes-to-C (pair)
406 "Create constants of table dimensions, if PAIR is a table."
407 (when (listp (cdr pair
))
409 ((listp (cadr pair
)) ;; a table
411 (format "const int %s_rows = %d;" (car pair
) (length (cdr pair
)))
413 (format "const int %s_cols = %d;" (car pair
) (length (cadr pair
)))))
414 (t ;; a list declared in the #+begin_src line
415 (format "const int %s_cols = %d;" (car pair
) (length (cdr pair
)))))))
417 (defun org-babel-C-utility-header-to-C ()
418 "Generate a utility function to convert a column name
419 into a column number."
420 (pcase org-babel-c-variant
422 "int get_column_num (int nbcols, const char** header, const char* column)
425 for (c=0; c<nbcols; c++)
426 if (strcmp(header[c],column)==0)
432 "int get_column_num (string[] header, string column)
434 foreach (c, h; header)
441 (defun org-babel-C-header-to-C (head)
442 "Convert an elisp list of header table into a C or D vector
443 specifying a variable with the name of the table."
444 (let ((table (car head
))
445 (headers (cdr head
)))
448 (pcase org-babel-c-variant
449 ((or `c
`cpp
) "const char* %s_header[%d] = {%s};")
450 (`d
"string %s_header[%d] = [%s];"))
453 (mapconcat (lambda (h) (format "%S" h
)) headers
","))
455 (pcase org-babel-c-variant
458 "const char* %s_h (int row, const char* col) { return %s[row][get_column_num(%d,%s_header,col)]; }"
459 table table
(length headers
) table
))
462 "string %s_h (size_t row, string col) { return %s[row][get_column_num(%s_header,col)]; }"
463 table table table
))))))
467 ;;; ob-C.el ends here