lisp/org-table.el: fix table alignment
[org-mode/org-tableheadings.git] / lisp / ob-C.el
blob92d034fa65fa9e0b8ee5fa742596379dfa964d40
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
6 ;; Thierry Banel
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/>.
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:
35 (require 'cc-mode)
36 (require 'ob)
37 (require 'org-macs)
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)
48 (defines . :any)
49 (main . :any)
50 (flags . :any)
51 (cmdline . :any)
52 (libs . :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"
65 :group 'org-babel
66 :version "24.3"
67 :type 'string)
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"
74 :group 'org-babel
75 :version "24.3"
76 :type 'string)
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"
83 :group 'org-babel
84 :version "24.3"
85 :type 'string)
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
98 header arguments."
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
108 header arguments."
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
118 header arguments."
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
128 header arguments."
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
135 "C-src-"
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))
149 nil))
150 (libs (mapconcat #'identity
151 (if (listp libs) libs (list libs))
152 " "))
153 (full-body
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
160 ((or `c `cpp)
161 (org-babel-eval
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))
166 tmp-bin-file
167 flags
168 (org-babel-process-file-name tmp-src-file)
169 libs)
170 ""))
171 (`d nil)) ;; no separate compilation for D
172 (let ((results
173 (org-babel-eval
174 (pcase org-babel-c-variant
175 ((or `c `cpp)
176 (concat tmp-bin-file cmdline))
178 (format "%s %s %s %s"
179 org-babel-D-compiler
180 flags
181 (org-babel-process-file-name tmp-src-file)
182 cmdline)))
183 "")))
184 (when results
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)))
192 (org-babel-pick-name
193 (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
194 (org-babel-pick-name
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))
211 nil))
212 (defines (org-babel-read
213 (cdr (assq :defines params))
214 nil))
215 (namespaces (org-babel-read
216 (cdr (assq :namespaces params))
217 nil)))
218 (when (stringp includes)
219 (setq includes (split-string includes)))
220 (when (stringp namespaces)
221 (setq namespaces (split-string namespaces)))
222 (when (stringp defines)
223 (let ((y nil)
224 (result (list t)))
225 (dolist (x (split-string defines))
226 (if (null y)
227 (setq y x)
228 (nconc result (list (concat y " " x)))
229 (setq y nil)))
230 (setq defines (cdr result))))
231 (mapconcat 'identity
232 (list
233 ;; includes
234 (mapconcat
235 (lambda (inc) (format "#include %s" inc))
236 includes "\n")
237 ;; defines
238 (mapconcat
239 (lambda (inc) (format "#define %s" inc))
240 (if (listp defines) defines (list defines)) "\n")
241 ;; namespaces
242 (mapconcat
243 (lambda (inc) (format "using namespace %s;" inc))
244 namespaces
245 "\n")
246 ;; variables
247 (mapconcat 'org-babel-C-var-to-C vars "\n")
248 ;; table sizes
249 (mapconcat 'org-babel-C-table-sizes-to-C vars "\n")
250 ;; tables headers utility
251 (when colnames
252 (org-babel-C-utility-header-to-C))
253 ;; tables headers
254 (mapconcat 'org-babel-C-header-to-C colnames "\n")
255 ;; body
256 (if main-p
257 (org-babel-C-ensure-main-wrap body)
258 body) "\n") "\n")))
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")))
271 (mapconcat 'identity
272 (list
273 "module mmm;"
274 ;; imports
275 (mapconcat
276 (lambda (inc) (format "import %s;" inc))
277 imports "\n")
278 ;; variables
279 (mapconcat 'org-babel-C-var-to-C vars "\n")
280 ;; table sizes
281 (mapconcat 'org-babel-C-table-sizes-to-C vars "\n")
282 ;; tables headers utility
283 (when colnames
284 (org-babel-C-utility-header-to-C))
285 ;; tables headers
286 (mapconcat 'org-babel-C-header-to-C colnames "\n")
287 ;; body
288 (if main-p
289 (org-babel-C-ensure-main-wrap body)
290 body) "\n") "\n")))
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)
295 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"))
308 ;; helper functions
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))
322 (type
323 (pcase basetype
324 (`integerp '("int" "%d"))
325 (`floatp '("double" "%f"))
326 (`stringp
327 (list
328 (if (eq org-babel-c-variant 'd) "string" "const char*")
329 "\"%s\""))
330 (_ (error "unknown type %S" basetype)))))
331 (cond
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
335 `(,(car type)
336 (lambda (val)
337 (cons
338 (format "[%d][%d]" (length val) (length (car val)))
339 (concat
340 (if (eq org-babel-c-variant 'd) "[\n" "{\n")
341 (mapconcat
342 (lambda (v)
343 (concat
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) "]" "}")))
348 ",\n")
349 (if (eq org-babel-c-variant 'd) "\n]" "\n}"))))))
350 ((or (listp val) (vectorp val)) ;; a list declared in the #+begin_src line
351 `(,(car type)
352 (lambda (val)
353 (cons
354 (format "[%d]" (length val))
355 (concat
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
360 type))))
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."
367 (cond
368 ((integerp val) 'integerp)
369 ((floatp val) 'floatp)
370 ((or (listp val) (vectorp val))
371 (let ((type nil))
372 (mapc (lambda (v)
373 (pcase (org-babel-C-val-to-base-type v)
374 (`stringp (setq type 'stringp))
375 (`floatp
376 (when (or (not type) (eq type 'integerp))
377 (setq type 'floatp)))
378 (`integerp
379 (unless type (setq type 'integerp)))))
380 val)
381 type))
382 (t 'stringp)))
384 (defun org-babel-C-var-to-C (pair)
385 "Convert an elisp val into a string of C code specifying a var
386 of the same value."
387 ;; TODO list support
388 (let ((var (car pair))
389 (val (cdr pair)))
390 (when (symbolp val)
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;"
400 type
402 suffix
403 data))))
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))
408 (cond
409 ((listp (cadr pair)) ;; a table
410 (concat
411 (format "const int %s_rows = %d;" (car pair) (length (cdr pair)))
412 "\n"
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
421 ((or `c `cpp)
422 "int get_column_num (int nbcols, const char** header, const char* column)
424 int c;
425 for (c=0; c<nbcols; c++)
426 if (strcmp(header[c],column)==0)
427 return c;
428 return -1;
432 "int get_column_num (string[] header, string column)
434 foreach (c, h; header)
435 if (h==column)
436 return to!int(c);
437 return -1;
439 ")))
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)))
446 (concat
447 (format
448 (pcase org-babel-c-variant
449 ((or `c `cpp) "const char* %s_header[%d] = {%s};")
450 (`d "string %s_header[%d] = [%s];"))
451 table
452 (length headers)
453 (mapconcat (lambda (h) (format "%S" h)) headers ","))
454 "\n"
455 (pcase org-babel-c-variant
456 ((or `c `cpp)
457 (format
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))
461 (format
462 "string %s_h (size_t row, string col) { return %s[row][get_column_num(%s_header,col)]; }"
463 table table table))))))
465 (provide 'ob-C)
467 ;;; ob-C.el ends here