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