fix bug in ob-C
[org-mode/org-kjn.git] / lisp / ob-C.el
bloba794e2a8daef3007572a36b06ee529c765fec9ec
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, Thierry Banel
6 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: http://orgmode.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; Org-Babel support for evaluating C, C++, D code.
28 ;; very limited implementation:
29 ;; - currently only support :results output
30 ;; - not much in the way of error feedback
32 ;;; Code:
33 (eval-when-compile
34 (require 'cl))
35 (require 'ob)
36 (require 'cc-mode)
38 (declare-function org-entry-get "org"
39 (pom property &optional inherit literal-nil))
40 (declare-function org-remove-indentation "org" (code &optional n))
42 (defvar org-babel-tangle-lang-exts)
43 (add-to-list 'org-babel-tangle-lang-exts '("C++" . "cpp"))
44 (add-to-list 'org-babel-tangle-lang-exts '("D" . "d"))
46 (defvar org-babel-default-header-args:C '())
48 (defvar org-babel-C-compiler "gcc"
49 "Command used to compile a C source code file into an
50 executable.")
52 (defvar org-babel-C++-compiler "g++"
53 "Command used to compile a C++ source code file into an
54 executable.")
56 (defvar org-babel-D-compiler "rdmd"
57 "Command used to compile and execute a D source code file.")
59 (defvar org-babel-c-variant nil
60 "Internal variable used to hold which type of C (e.g. C or C++ or D)
61 is currently being evaluated.")
63 (defun org-babel-execute:cpp (body params)
64 "Execute BODY according to PARAMS.
65 This function calls `org-babel-execute:C++'."
66 (org-babel-execute:C++ body params))
68 (defun org-babel-execute:C++ (body params)
69 "Execute a block of C++ code with org-babel.
70 This function is called by `org-babel-execute-src-block'."
71 (let ((org-babel-c-variant 'cpp)) (org-babel-C-execute body params)))
73 (defun org-babel-expand-body:C++ (body params)
74 "Expand a block of C++ code with org-babel according to it's
75 header arguments."
76 (let ((org-babel-c-variant 'cpp)) (org-babel-C-expand-C++ body params)))
78 (defun org-babel-execute:D (body params)
79 "Execute a block of D code with org-babel.
80 This function is called by `org-babel-execute-src-block'."
81 (let ((org-babel-c-variant 'd)) (org-babel-C-execute body params)))
83 (defun org-babel-expand-body:D (body params)
84 "Expand a block of D code with org-babel according to it's
85 header arguments."
86 (let ((org-babel-c-variant 'd)) (org-babel-C-expand-D 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 'c)) (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 it's
95 header arguments."
96 (let ((org-babel-c-variant 'c)) (org-babel-C-expand-C body params)))
98 (defun org-babel-C-execute (body params)
99 "This function should only be called by `org-babel-execute:C'
100 or `org-babel-execute:C++' or `org-babel-execute:D'."
101 (let* ((tmp-src-file (org-babel-temp-file
102 "C-src-"
103 (case org-babel-c-variant
104 (c ".c" )
105 (cpp ".cpp")
106 (d ".d" ))))
107 (tmp-bin-file (org-babel-temp-file "C-bin-" org-babel-exeext)) ;; not used for D
108 (cmdline (cdr (assoc :cmdline params)))
109 (cmdline (if cmdline (concat " " cmdline) ""))
110 (flags (cdr (assoc :flags params)))
111 (flags (mapconcat 'identity
112 (if (listp flags) flags (list flags)) " "))
113 (full-body
114 (case org-babel-c-variant
115 (c (org-babel-C-expand-C body params))
116 (cpp (org-babel-C-expand-C++ body params))
117 (d (org-babel-C-expand-D body params)))))
118 (with-temp-file tmp-src-file (insert full-body))
119 (case org-babel-c-variant
120 ((c cpp)
121 (org-babel-eval
122 (format "%s -o %s %s %s"
123 (case org-babel-c-variant
124 (c org-babel-C-compiler)
125 (cpp org-babel-C++-compiler))
126 (org-babel-process-file-name tmp-bin-file)
127 flags
128 (org-babel-process-file-name tmp-src-file)) ""))
129 (d nil)) ;; no separate compilation for D
130 (let ((results
131 (org-babel-eval
132 (case org-babel-c-variant
133 ((c cpp)
134 (concat tmp-bin-file cmdline))
136 (format "%s %s %s %s"
137 org-babel-D-compiler
138 flags
139 (org-babel-process-file-name tmp-src-file)
140 cmdline)))
141 "")))
142 (when results
143 (setq results (org-babel-trim (org-remove-indentation results)))
144 (org-babel-reassemble-table
145 (org-babel-result-cond (cdr (assoc :result-params params))
146 (org-babel-read results t)
147 (let ((tmp-file (org-babel-temp-file "c-")))
148 (with-temp-file tmp-file (insert results))
149 (org-babel-import-elisp-from-file tmp-file)))
150 (org-babel-pick-name
151 (cdr (assoc :colname-names params)) (cdr (assoc :colnames params)))
152 (org-babel-pick-name
153 (cdr (assoc :rowname-names params)) (cdr (assoc :rownames params)))))
156 (defun org-babel-C-expand-C++ (body params)
157 "Expand a block of C or C++ code with org-babel according to
158 it's header arguments."
159 (org-babel-C-expand-C body params))
161 (defun org-babel-C-expand-C (body params)
162 "Expand a block of C or C++ code with org-babel according to
163 it's header arguments."
164 (let ((vars (mapcar #'cdr (org-babel-get-header params :var)))
165 (colnames (cdar (org-babel-get-header params :colname-names)))
166 (main-p (not (string= (cdr (assoc :main params)) "no")))
167 (includes (or (cdr (assoc :includes params))
168 (org-babel-read (org-entry-get nil "includes" t))))
169 (defines (org-babel-read
170 (or (cdr (assoc :defines params))
171 (org-babel-read (org-entry-get nil "defines" t))))))
172 (unless (listp includes) (setq includes (list includes)))
173 (setq includes (append includes '("<string.h>" "<stdio.h>" "<stdlib.h>")))
174 (mapconcat 'identity
175 (list
176 ;; includes
177 (mapconcat
178 (lambda (inc) (format "#include %s" inc))
179 includes "\n")
180 ;; defines
181 (mapconcat
182 (lambda (inc) (format "#define %s" inc))
183 (if (listp defines) defines (list defines)) "\n")
184 ;; variables
185 (mapconcat 'org-babel-C-var-to-C vars "\n")
186 ;; table sizes
187 (mapconcat 'org-babel-C-table-sizes-to-C vars "\n")
188 ;; tables headers utility
189 (when colnames
190 (org-babel-C-utility-header-to-C))
191 ;; tables headers
192 (mapconcat 'org-babel-C-header-to-C colnames "\n")
193 ;; body
194 (if main-p
195 (org-babel-C-ensure-main-wrap body)
196 body) "\n") "\n")))
198 (defun org-babel-C-expand-D (body params)
199 "Expand a block of D code with org-babel according to
200 it's header arguments."
201 (let ((vars (mapcar #'cdr (org-babel-get-header params :var)))
202 (colnames (cdar (org-babel-get-header params :colname-names)))
203 (main-p (not (string= (cdr (assoc :main params)) "no")))
204 (imports (or (cdr (assoc :imports params))
205 (org-babel-read (org-entry-get nil "imports" t)))))
206 (unless (listp imports) (setq imports (list imports)))
207 (setq imports (append imports '("std.stdio" "std.conv")))
208 (mapconcat 'identity
209 (list
210 "module mmm;"
211 ;; imports
212 (mapconcat
213 (lambda (inc) (format "import %s;" inc))
214 imports "\n")
215 ;; variables
216 (mapconcat 'org-babel-C-var-to-C vars "\n")
217 ;; table sizes
218 (mapconcat 'org-babel-C-table-sizes-to-C vars "\n")
219 ;; tables headers utility
220 (when colnames
221 (org-babel-C-utility-header-to-C))
222 ;; tables headers
223 (mapconcat 'org-babel-C-header-to-C colnames "\n")
224 ;; body
225 (if main-p
226 (org-babel-C-ensure-main-wrap body)
227 body) "\n") "\n")))
229 (defun org-babel-C-ensure-main-wrap (body)
230 "Wrap BODY in a \"main\" function call if none exists."
231 (if (string-match "^[ \t]*[intvod]+[ \t\n\r]*main[ \t]*(.*)" body)
232 body
233 (format "int main() {\n%s\nreturn 0;\n}\n" body)))
235 (defun org-babel-prep-session:C (session params)
236 "This function does nothing as C is a compiled language with no
237 support for sessions"
238 (error "C is a compiled languages -- no support for sessions"))
240 (defun org-babel-load-session:C (session body params)
241 "This function does nothing as C is a compiled language with no
242 support for sessions"
243 (error "C is a compiled languages -- no support for sessions"))
245 ;; helper functions
247 (defun org-babel-C-format-val (type val)
248 "Handle the FORMAT part of TYPE with the data from VAL."
249 (let ((format-data (cadr type)))
250 (if (stringp format-data)
251 (cons "" (format format-data val))
252 (funcall format-data val))))
254 (defun org-babel-C-val-to-C-type (val)
255 "Determine the type of VAL.
256 Return a list (TYPE-NAME FORMAT). TYPE-NAME should be the name of the type.
257 FORMAT can be either a format string or a function which is called with VAL."
258 (let* ((basetype (org-babel-C-val-to-base-type val))
259 (type
260 (case basetype
261 (integerp '("int" "%d"))
262 (floatp '("double" "%f"))
263 (stringp
264 (list
265 (if (equal org-babel-c-variant 'd) "string" "const char*")
266 "\"%s\""))
267 (t (error "unknown type %S" basetype)))))
268 (cond
269 ((integerp val) type) ;; an integer declared in the #+begin_src line
270 ((floatp val) type) ;; a numeric declared in the #+begin_src line
271 ((and (listp val) (listp (car val))) ;; a table
272 `(,(car type)
273 (lambda (val)
274 (cons
275 (format "[%d][%d]" (length val) (length (car val)))
276 (concat
277 (if (equal org-babel-c-variant 'd) "[\n" "{\n")
278 (mapconcat
279 (lambda (v)
280 (concat
281 (if (equal org-babel-c-variant 'd) " [" " {")
282 (mapconcat (lambda (w) (format ,(cadr type) w)) v ",")
283 (if (equal org-babel-c-variant 'd) "]" "}")))
285 ",\n")
286 (if (equal org-babel-c-variant 'd) "\n]" "\n}"))))))
287 ((or (listp val) (vectorp val)) ;; a list declared in the #+begin_src line
288 `(,(car type)
289 (lambda (val)
290 (cons
291 (format "[%d]" (length val))
292 (concat
293 (if (equal org-babel-c-variant 'd) "[" "{")
294 (mapconcat (lambda (v) (format ,(cadr type) v)) val ",")
295 (if (equal org-babel-c-variant 'd) "]" "}"))))))
296 (t ;; treat unknown types as string
297 type))))
299 (defun org-babel-C-val-to-base-type (val)
300 "Determine the base type of VAL which may be
301 'integerp if all base values are integers
302 'floatp if all base values are either floating points or integers
303 'stringp otherwise."
304 (cond
305 ((integerp val) 'integerp)
306 ((floatp val) 'floatp)
307 ((or (listp val) (vectorp val))
308 (let ((type nil))
309 (mapc (lambda (v)
310 (case (org-babel-C-val-to-base-type v)
311 (stringp (setq type 'stringp))
312 (floatp
313 (if (or (not type) (eq type 'integerp))
314 (setq type 'floatp)))
315 (integerp
316 (unless type (setq type 'integerp)))))
317 val)
318 type))
319 (t 'stringp)))
321 (defun org-babel-C-var-to-C (pair)
322 "Convert an elisp val into a string of C code specifying a var
323 of the same value."
324 ;; TODO list support
325 (let ((var (car pair))
326 (val (cdr pair)))
327 (when (symbolp val)
328 (setq val (symbol-name val))
329 (when (= (length val) 1)
330 (setq val (string-to-char val))))
331 (let* ((type-data (org-babel-C-val-to-C-type val))
332 (type (car type-data))
333 (formated (org-babel-C-format-val type-data val))
334 (suffix (car formated))
335 (data (cdr formated)))
336 (format "%s %s%s = %s;"
337 type
339 suffix
340 data))))
342 (defun org-babel-C-table-sizes-to-C (pair)
343 "Create constants of table dimensions, if PAIR is a table."
344 (when (listp (cdr pair))
345 (cond
346 ((listp (cadr pair)) ;; a table
347 (concat
348 (format "const int %s_rows = %d;" (car pair) (length (cdr pair)))
349 "\n"
350 (format "const int %s_cols = %d;" (car pair) (length (cadr pair)))))
351 (t ;; a list declared in the #+begin_src line
352 (format "const int %s_cols = %d;" (car pair) (length (cdr pair)))))))
354 (defun org-babel-C-utility-header-to-C ()
355 "Generate a utility function to convert a column name
356 into a column number."
357 (case org-babel-c-variant
358 ((c cpp)
359 "int get_column_num (int nbcols, const char** header, const char* column)
361 int c;
362 for (c=0; c<nbcols; c++)
363 if (strcmp(header[c],column)==0)
364 return c;
365 return -1;
370 "int get_column_num (string[] header, string column)
372 foreach (c, h; header)
373 if (h==column)
374 return to!int(c);
375 return -1;
380 (defun org-babel-C-header-to-C (head)
381 "Convert an elisp list of header table into a C or D vector
382 specifying a variable with the name of the table."
383 (let ((table (car head))
384 (headers (cdr head)))
385 (concat
386 (format
387 (case org-babel-c-variant
388 ((c cpp) "const char* %s_header[%d] = {%s};")
389 (d "string %s_header[%d] = [%s];"))
390 table
391 (length headers)
392 (mapconcat (lambda (h) (format "%S" h)) headers ","))
393 "\n"
394 (case org-babel-c-variant
395 ((c cpp)
396 (format
397 "const char* %s_h (int row, const char* col) { return %s[row][get_column_num(%d,%s_header,col)]; }"
398 table table (length headers) table))
400 (format
401 "string %s_h (ulong row, string col) { return %s[row][get_column_num(%s_header,col)]; }"
402 table table table))))))
404 (provide 'ob-C)
406 ;;; ob-C.el ends here