7780eec8125691e5f01c93a16d12fb6a9ade8e86
[clinton/parenscript.git] / src / compilation-interface.lisp
1 (in-package :parenscript)
2
3 (defun translate-ast (compiled-expr &key (output-stream *standard-output*) (output-spec :javascript) (pretty-print t))
4 "Translates a compiled Parenscript program (compiled with COMPILE-PAREN-FORM)
5 to a Javascript string. Outputs to the stream OUTPUT-STREAM in the language given
6 by OUTPUT-SPEC, pretty printing if PRETTY-PRINT is non-null.
7
8 OUTPUT-SPEC must be :javascript at the moment."
9 (when (not (eql :javascript output-spec))
10 (error "Unsupported output-spec for translation: ~A" output-spec))
11 (write-string (string-join (ps-print compiled-expr 0)
12 (string #\Newline))
13 output-stream))
14
15 (defun compile-script (script-form &key (output-spec :javascript) (pretty-print t) (output-stream nil) (toplevel-p t))
16 "Compiles the Parenscript form SCRIPT-FORM into the language specified by OUTPUT-SPEC.
17 Non-null PRETTY-PRINT values result in a pretty-printed output code. If OUTPUT-STREAM
18 is NIL, then the result is a string; otherwise code is output to the OUTPUT-STREAM stream.
19
20 This is the main function used by Parenscript users to compile their code to Javascript (and
21 potentially other languages)."
22 (macrolet ((with-output-stream ((var) &body body)
23 `(if (null output-stream)
24 (with-output-to-string (,var)
25 ,@body)
26 (let ((,var output-stream))
27 ,@body))))
28 (with-output-stream (stream)
29 (translate-ast (compile-parenscript-form script-form)
30 :output-stream stream
31 :output-spec output-spec
32 :pretty-print pretty-print))))
33
34 (defun ps-to-string (expr)
35 (string-join (ps-print (compile-parenscript-form expr) 0) (string #\Newline)))
36
37 (defmacro ps (&body body)
38 "A macro that returns a Javascript string of the supplied Parenscript forms."
39 `(ps* '(progn ,@body)))
40
41 (defun ps* (&rest body)
42 "Return the javascript string representing BODY.
43 Body is evaluated."
44 (compile-script `(progn ,@body)))