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