ob-C: Fix command to perform on remote host
[org-mode.git] / lisp / ob-C.el
blob2bdda68d5835fbe1504625e847db5aed22768eb9
1 ;;; ob-C.el --- Babel Functions for C and Similar Languages -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2010-2017 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:
35 (require 'cc-mode)
36 (require 'ob)
39 (declare-function org-entry-get "org" (pom property &optional inherit literal-nil))
40 (declare-function org-remove-indentation "org" (code &optional n))
41 (declare-function org-trim "org" (s &optional keep-lead))
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 its
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 its
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 its
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 its
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 (pcase org-babel-c-variant
126 (`c ".c") (`cpp ".cpp") (`d ".d"))))
127 (tmp-bin-file ;not used for D
128 (org-babel-process-file-name
129 (org-babel-temp-file "C-bin-" org-babel-exeext)))
130 (cmdline (cdr (assq :cmdline params)))
131 (cmdline (if cmdline (concat " " cmdline) ""))
132 (flags (cdr (assq :flags params)))
133 (flags (mapconcat 'identity
134 (if (listp flags) flags (list flags)) " "))
135 (libs (org-babel-read
136 (or (cdr (assq :libs params))
137 (org-entry-get nil "libs" t))
138 nil))
139 (libs (mapconcat #'identity
140 (if (listp libs) libs (list libs))
141 " "))
142 (full-body
143 (pcase org-babel-c-variant
144 (`c (org-babel-C-expand-C body params))
145 (`cpp (org-babel-C-expand-C++ body params))
146 (`d (org-babel-C-expand-D body params)))))
147 (with-temp-file tmp-src-file (insert full-body))
148 (pcase org-babel-c-variant
149 ((or `c `cpp)
150 (org-babel-eval
151 (format "%s -o %s %s %s %s"
152 (pcase org-babel-c-variant
153 (`c org-babel-C-compiler)
154 (`cpp org-babel-C++-compiler))
155 tmp-bin-file
156 flags
157 (org-babel-process-file-name tmp-src-file)
158 libs)
159 ""))
160 (`d nil)) ;; no separate compilation for D
161 (let ((results
162 (org-babel-eval
163 (pcase org-babel-c-variant
164 ((or `c `cpp)
165 (concat tmp-bin-file cmdline))
167 (format "%s %s %s %s"
168 org-babel-D-compiler
169 flags
170 (org-babel-process-file-name tmp-src-file)
171 cmdline)))
172 "")))
173 (when results
174 (setq results (org-trim (org-remove-indentation results)))
175 (org-babel-reassemble-table
176 (org-babel-result-cond (cdr (assq :result-params params))
177 (org-babel-read results t)
178 (let ((tmp-file (org-babel-temp-file "c-")))
179 (with-temp-file tmp-file (insert results))
180 (org-babel-import-elisp-from-file tmp-file)))
181 (org-babel-pick-name
182 (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
183 (org-babel-pick-name
184 (cdr (assq :rowname-names params)) (cdr (assq :rownames params)))))
187 (defun org-babel-C-expand-C++ (body params)
188 "Expand a block of C or C++ code with org-babel according to
189 its header arguments."
190 (org-babel-C-expand-C body params))
192 (defun org-babel-C-expand-C (body params)
193 "Expand a block of C or C++ code with org-babel according to
194 its header arguments."
195 (let ((vars (org-babel--get-vars params))
196 (colnames (cdr (assq :colname-names params)))
197 (main-p (not (string= (cdr (assq :main params)) "no")))
198 (includes (org-babel-read
199 (or (cdr (assq :includes params))
200 (org-entry-get nil "includes" t))
201 nil))
202 (defines (org-babel-read
203 (or (cdr (assq :defines params))
204 (org-entry-get nil "defines" t))
205 nil)))
206 (when (stringp includes)
207 (setq includes (split-string includes)))
208 (when (stringp defines)
209 (let ((y nil)
210 (result (list t)))
211 (dolist (x (split-string defines))
212 (if (null y)
213 (setq y x)
214 (nconc result (list (concat y " " x)))
215 (setq y nil)))
216 (setq defines (cdr result))))
217 (mapconcat 'identity
218 (list
219 ;; includes
220 (mapconcat
221 (lambda (inc) (format "#include %s" inc))
222 includes "\n")
223 ;; defines
224 (mapconcat
225 (lambda (inc) (format "#define %s" inc))
226 (if (listp defines) defines (list defines)) "\n")
227 ;; variables
228 (mapconcat 'org-babel-C-var-to-C vars "\n")
229 ;; table sizes
230 (mapconcat 'org-babel-C-table-sizes-to-C vars "\n")
231 ;; tables headers utility
232 (when colnames
233 (org-babel-C-utility-header-to-C))
234 ;; tables headers
235 (mapconcat 'org-babel-C-header-to-C colnames "\n")
236 ;; body
237 (if main-p
238 (org-babel-C-ensure-main-wrap body)
239 body) "\n") "\n")))
241 (defun org-babel-C-expand-D (body params)
242 "Expand a block of D code with org-babel according to
243 its header arguments."
244 (let ((vars (org-babel--get-vars params))
245 (colnames (cdr (assq :colname-names params)))
246 (main-p (not (string= (cdr (assq :main params)) "no")))
247 (imports (or (cdr (assq :imports params))
248 (org-babel-read (org-entry-get nil "imports" t)))))
249 (when (stringp imports)
250 (setq imports (split-string imports)))
251 (setq imports (append imports '("std.stdio" "std.conv")))
252 (mapconcat 'identity
253 (list
254 "module mmm;"
255 ;; imports
256 (mapconcat
257 (lambda (inc) (format "import %s;" inc))
258 imports "\n")
259 ;; variables
260 (mapconcat 'org-babel-C-var-to-C vars "\n")
261 ;; table sizes
262 (mapconcat 'org-babel-C-table-sizes-to-C vars "\n")
263 ;; tables headers utility
264 (when colnames
265 (org-babel-C-utility-header-to-C))
266 ;; tables headers
267 (mapconcat 'org-babel-C-header-to-C colnames "\n")
268 ;; body
269 (if main-p
270 (org-babel-C-ensure-main-wrap body)
271 body) "\n") "\n")))
273 (defun org-babel-C-ensure-main-wrap (body)
274 "Wrap BODY in a \"main\" function call if none exists."
275 (if (string-match "^[ \t]*[intvod]+[ \t\n\r]*main[ \t]*(.*)" body)
276 body
277 (format "int main() {\n%s\nreturn 0;\n}\n" body)))
279 (defun org-babel-prep-session:C (_session _params)
280 "This function does nothing as C is a compiled language with no
281 support for sessions"
282 (error "C is a compiled language -- no support for sessions"))
284 (defun org-babel-load-session:C (_session _body _params)
285 "This function does nothing as C is a compiled language with no
286 support for sessions"
287 (error "C is a compiled language -- no support for sessions"))
289 ;; helper functions
291 (defun org-babel-C-format-val (type val)
292 "Handle the FORMAT part of TYPE with the data from VAL."
293 (let ((format-data (cadr type)))
294 (if (stringp format-data)
295 (cons "" (format format-data val))
296 (funcall format-data val))))
298 (defun org-babel-C-val-to-C-type (val)
299 "Determine the type of VAL.
300 Return a list (TYPE-NAME FORMAT). TYPE-NAME should be the name of the type.
301 FORMAT can be either a format string or a function which is called with VAL."
302 (let* ((basetype (org-babel-C-val-to-base-type val))
303 (type
304 (pcase basetype
305 (`integerp '("int" "%d"))
306 (`floatp '("double" "%f"))
307 (`stringp
308 (list
309 (if (eq org-babel-c-variant 'd) "string" "const char*")
310 "\"%s\""))
311 (_ (error "unknown type %S" basetype)))))
312 (cond
313 ((integerp val) type) ;; an integer declared in the #+begin_src line
314 ((floatp val) type) ;; a numeric declared in the #+begin_src line
315 ((and (listp val) (listp (car val))) ;; a table
316 `(,(car type)
317 (lambda (val)
318 (cons
319 (format "[%d][%d]" (length val) (length (car val)))
320 (concat
321 (if (eq org-babel-c-variant 'd) "[\n" "{\n")
322 (mapconcat
323 (lambda (v)
324 (concat
325 (if (eq org-babel-c-variant 'd) " [" " {")
326 (mapconcat (lambda (w) (format ,(cadr type) w)) v ",")
327 (if (eq org-babel-c-variant 'd) "]" "}")))
329 ",\n")
330 (if (eq org-babel-c-variant 'd) "\n]" "\n}"))))))
331 ((or (listp val) (vectorp val)) ;; a list declared in the #+begin_src line
332 `(,(car type)
333 (lambda (val)
334 (cons
335 (format "[%d]" (length val))
336 (concat
337 (if (eq org-babel-c-variant 'd) "[" "{")
338 (mapconcat (lambda (v) (format ,(cadr type) v)) val ",")
339 (if (eq org-babel-c-variant 'd) "]" "}"))))))
340 (t ;; treat unknown types as string
341 type))))
343 (defun org-babel-C-val-to-base-type (val)
344 "Determine the base type of VAL which may be
345 `integerp' if all base values are integers
346 `floatp' if all base values are either floating points or integers
347 `stringp' otherwise."
348 (cond
349 ((integerp val) 'integerp)
350 ((floatp val) 'floatp)
351 ((or (listp val) (vectorp val))
352 (let ((type nil))
353 (mapc (lambda (v)
354 (pcase (org-babel-C-val-to-base-type v)
355 (`stringp (setq type 'stringp))
356 (`floatp
357 (if (or (not type) (eq type 'integerp))
358 (setq type 'floatp)))
359 (`integerp
360 (unless type (setq type 'integerp)))))
361 val)
362 type))
363 (t 'stringp)))
365 (defun org-babel-C-var-to-C (pair)
366 "Convert an elisp val into a string of C code specifying a var
367 of the same value."
368 ;; TODO list support
369 (let ((var (car pair))
370 (val (cdr pair)))
371 (when (symbolp val)
372 (setq val (symbol-name val))
373 (when (= (length val) 1)
374 (setq val (string-to-char val))))
375 (let* ((type-data (org-babel-C-val-to-C-type val))
376 (type (car type-data))
377 (formated (org-babel-C-format-val type-data val))
378 (suffix (car formated))
379 (data (cdr formated)))
380 (format "%s %s%s = %s;"
381 type
383 suffix
384 data))))
386 (defun org-babel-C-table-sizes-to-C (pair)
387 "Create constants of table dimensions, if PAIR is a table."
388 (when (listp (cdr pair))
389 (cond
390 ((listp (cadr pair)) ;; a table
391 (concat
392 (format "const int %s_rows = %d;" (car pair) (length (cdr pair)))
393 "\n"
394 (format "const int %s_cols = %d;" (car pair) (length (cadr pair)))))
395 (t ;; a list declared in the #+begin_src line
396 (format "const int %s_cols = %d;" (car pair) (length (cdr pair)))))))
398 (defun org-babel-C-utility-header-to-C ()
399 "Generate a utility function to convert a column name
400 into a column number."
401 (pcase org-babel-c-variant
402 ((or `c `cpp)
403 "int get_column_num (int nbcols, const char** header, const char* column)
405 int c;
406 for (c=0; c<nbcols; c++)
407 if (strcmp(header[c],column)==0)
408 return c;
409 return -1;
413 "int get_column_num (string[] header, string column)
415 foreach (c, h; header)
416 if (h==column)
417 return to!int(c);
418 return -1;
420 ")))
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 (pcase org-babel-c-variant
430 ((or `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 (pcase org-babel-c-variant
437 ((or `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