cb97cf30b0936cbe456ea5124d118dd9c0fff8ed
[clinton/parenscript.git] / src / compilation-interface.lisp
1 (in-package "PARENSCRIPT")
2
3 (defparameter *js-target-version* 1.3)
4
5 (defmacro ps (&body body)
6 "Given Parenscript forms (an implicit progn), compiles those forms
7 to a JavaScript string at macro-expansion time."
8 `(concatenate 'string ,@(parenscript-print (compile-parenscript-form `(progn ,@body) :expecting :statement))))
9
10 (defun ps* (&rest body)
11 "Compiles BODY to a JavaScript string.
12 Body is evaluated."
13 (compiled-form-to-string (compile-parenscript-form `(progn ,@body) :expecting :statement)))
14
15 (defmacro ps-doc (&body body)
16 "Expands Parenscript forms in a clean environment."
17 (let ((*ps-gensym-counter* 0)
18 (*ps-special-variables* nil))
19 (macroexpand-1 `(ps ,@body))))
20
21 (defun ps-doc* (ps-form)
22 (let ((*ps-gensym-counter* 0)
23 (*ps-special-variables* nil))
24 (ps* ps-form)))
25
26 (defun compiled-form-to-string (ps-compiled-form)
27 (with-output-to-string (s)
28 (dolist (x (parenscript-print ps-compiled-form))
29 (write-string (if (stringp x) x (eval x)) s))))
30
31 (defvar *js-inline-string-delimiter* #\"
32 "Controls the string delimiter char used when compiling Parenscript in ps-inline.")
33
34 (defun ps-inline* (form &optional (*js-string-delimiter* *js-inline-string-delimiter*))
35 (concatenate 'string "javascript:" (ps* form)))
36
37 (defmacro/ps ps-inline (form &optional (string-delimiter *js-inline-string-delimiter*))
38 `(concatenate 'string "javascript:"
39 ,@(let ((*js-string-delimiter* string-delimiter))
40 (parenscript-print (compile-parenscript-form form :expecting :statement)))))
41
42 (defvar *ps-read-function* #'read
43 "This should be a function that takes the same inputs and returns the same
44 outputs as the common lisp read function. We declare it as a variable to allow
45 a user-supplied reader instead of the default lisp reader.")
46
47 (defun ps-compile-stream (stream)
48 "Compiles a source stream as if it were a file. Outputs a Javascript string."
49 (let ((*ps-compilation-level* :toplevel)
50 (*package* *package*)
51 (end-read-form '#:unique))
52 (flet ((read-form () (funcall *ps-read-function* stream nil end-read-form)))
53 (let* ((js-string
54 ;; cons up the forms, compiling as we go, and print the result
55 (do ((form (read-form) (read-form))
56 (compiled-forms nil))
57 ((eql form end-read-form)
58 (format nil "~{~A~^;~%~}"
59 (remove-if
60 #'(lambda (x) (or (null x) (= 0 (length x))))
61 (mapcar 'compiled-form-to-string (nreverse compiled-forms)))))
62 (push (compile-parenscript-form form :expecting :statement) compiled-forms))))
63 js-string))))
64
65 (defun ps-compile-file (source-file)
66 "Compiles the given Parenscript source file and returns a Javascript string."
67 (with-open-file (stream source-file :direction :input)
68 (ps-compile-stream stream)))