2281ab3e49cb63a06cdc91381baf93d77cb6f016
[clinton/parenscript.git] / src / compiler.lisp
1 (in-package "PARENSCRIPT")
2
3 ;;; reserved symbols/literals
4
5 (defvar *ps-reserved-symbol-names* ()) ;; symbol names reserved for PS/JS literals
6
7 (defun add-ps-literal (name)
8 (push (symbol-name name) *ps-reserved-symbol-names*))
9
10 (defun ps-literal-p (symbol)
11 (find (symbol-name symbol) *ps-reserved-symbol-names* :test #'equalp))
12
13 ;;; special forms
14
15 (defvar *ps-special-forms* (make-hash-table :test 'eq))
16
17 (defun get-ps-special-form (name)
18 (gethash name *ps-special-forms*))
19
20 (defmacro define-ps-special-form (name lambda-list &rest body)
21 "Define a special form NAME. The first argument (an anaphor called
22 'expecting' automatically added to the arglist) to the special form is
23 a keyword indicating whether the form is expected to produce
24 an :expression or a :statement."
25 (let ((args (gensym "ps-arglist-")))
26 `(setf (gethash ',name *ps-special-forms*)
27 (lambda (&rest ,args)
28 (destructuring-bind ,(cons 'expecting lambda-list)
29 ,args
30 (declare (ignorable expecting))
31 ,@body)))))
32
33 (defun undefine-ps-special-form (name)
34 (remhash name *ps-special-forms*))
35
36 (defun ps-special-form-p (form)
37 (and (consp form)
38 (symbolp (car form))
39 (gethash (car form) *ps-special-forms*)))
40
41 ;;; scoping
42
43 (defvar *enclosing-lexical-block-declarations* ()
44 "This special variable is expected to be bound to a fresh list by
45 special forms that introduce a new JavaScript lexical block (currently
46 function definitions and lambdas). Enclosed special forms are expected
47 to push variable declarations onto the list when the variables
48 declaration cannot be made by the enclosed form \(for example, a
49 \(x,y,z\) expression progn\). It is then the responsibility of the
50 enclosing special form to introduce the variable bindings in its
51 lexical block.")
52
53 (defvar *ps-special-variables* ())
54
55 ;;; form predicates
56
57 (defun op-form-p (form)
58 (and (listp form)
59 (not (ps-special-form-p form))
60 (not (null (op-precedence (first form))))))
61
62 (defun funcall-form-p (form)
63 (and (listp form)
64 (not (op-form-p form))
65 (not (ps-special-form-p form))))
66
67 ;;; macro expansion
68 (eval-when (:compile-toplevel :load-toplevel :execute)
69 (defun make-macro-env-dictionary ()
70 (make-hash-table :test 'eq))
71 (defvar *ps-macro-toplevel* (make-macro-env-dictionary)
72 "Toplevel macro environment dictionary. Key is the symbol name of
73 the macro, value is (symbol-macro-p . expansion-function).")
74
75 (defvar *ps-macro-env* (list *ps-macro-toplevel*)
76 "Current macro environment.")
77
78 (defvar *ps-setf-expanders* (make-macro-env-dictionary)
79 "Setf expander dictionary. Key is the symbol of the access
80 function of the place, value is an expansion function that takes the
81 arguments of the access functions as a first value and the form to be
82 stored as the second value.")
83
84 (defparameter *toplevel-compilation-level* :toplevel
85 "This value takes on the following values:
86 :toplevel indicates that we are traversing toplevel forms.
87 :inside-toplevel-form indicates that we are inside a call to compile-parenscript-form
88 nil indicates we are no longer toplevel-related.")
89
90 (defun get-macro-spec (name env-dict)
91 "Retrieves the macro spec of the given name with the given environment dictionary.
92 SPEC is of the form (symbol-macro-p . expansion-function)."
93 (gethash name env-dict))
94 (defsetf get-macro-spec (name env-dict)
95 (spec)
96 `(setf (gethash ,name ,env-dict) ,spec)))
97
98 (defun lookup-macro-spec (name &optional (environment *ps-macro-env*))
99 "Looks up the macro spec associated with NAME in the given environment. A
100 macro spec is of the form (symbol-macro-p . function). Returns two values:
101 the SPEC and the parent macro environment.
102
103 NAME must be a symbol."
104 (when (symbolp name)
105 (do ((env environment (cdr env)))
106 ((null env) nil)
107 (let ((val (get-macro-spec name (car env))))
108 (when val
109 (return-from lookup-macro-spec
110 (values val (or (cdr env)
111 (list *ps-macro-toplevel*)))))))))
112
113 (defun ps-symbol-macro-p (name &optional (environment *ps-macro-env*))
114 "True if there is a Parenscript symbol macro named by the symbol NAME."
115 (and (symbolp name) (car (lookup-macro-spec name environment))))
116
117 (defun ps-macro-p (name &optional (environment *ps-macro-env*))
118 "True if there is a Parenscript macro named by the symbol NAME."
119 (and (symbolp name)
120 (let ((macro-spec (lookup-macro-spec name environment)))
121 (and macro-spec (not (car macro-spec))))))
122
123 (defun lookup-macro-expansion-function (name &optional (environment *ps-macro-env*))
124 "Lookup NAME in the given macro expansion environment (which
125 defaults to the current macro environment). Returns the expansion
126 function and the parent macro environment of the macro."
127 (multiple-value-bind (macro-spec parent-env)
128 (lookup-macro-spec name environment)
129 (values (cdr macro-spec) parent-env)))
130
131 (defun make-ps-macro-function (args body)
132 (let* ((whole-var (when (eql '&whole (first args)) (second args)))
133 (effective-lambda-list (if whole-var (cddr args) args))
134 (whole-arg (or whole-var (gensym "ps-macro-form-arg-"))))
135 `(lambda (,whole-arg)
136 (destructuring-bind ,effective-lambda-list
137 (cdr ,whole-arg)
138 ,@body))))
139
140 (defmacro defpsmacro (name args &body body)
141 `(progn (undefine-ps-special-form ',name)
142 (setf (get-macro-spec ',name *ps-macro-toplevel*)
143 (cons nil ,(make-ps-macro-function args body)))
144 ',name))
145
146 (defmacro define-ps-symbol-macro (symbol expansion)
147 (let ((x (gensym)))
148 `(progn (undefine-ps-special-form ',symbol)
149 (setf (get-macro-spec ',symbol *ps-macro-toplevel*) (cons t (lambda (,x) (declare (ignore ,x)) ',expansion)))
150 ',symbol)))
151
152 (defun import-macros-from-lisp (&rest names)
153 "Import the named Lisp macros into the ParenScript macro
154 environment. When the imported macro is macroexpanded by ParenScript,
155 it is first fully macroexpanded in the Lisp macro environment, and
156 then that expansion is further expanded by ParenScript."
157 (dolist (name names)
158 (eval `(defpsmacro ,name (&rest args)
159 (macroexpand `(,',name ,@args))))))
160
161 (defmacro defmacro/ps (name args &body body)
162 "Define a Lisp macro and import it into the ParenScript macro environment."
163 `(progn (defmacro ,name ,args ,@body)
164 (import-macros-from-lisp ',name)))
165
166 (defmacro defmacro+ps (name args &body body)
167 "Define a Lisp macro and a ParenScript macro with the same macro
168 function (ie - the same result from macroexpand-1), for cases when the
169 two have different full macroexpansions (for example if the CL macro
170 contains implementation-specific code when macroexpanded fully in the
171 CL environment)."
172 `(progn (defmacro ,name ,args ,@body)
173 (defpsmacro ,name ,args ,@body)))
174
175 (defun ps-macroexpand (form)
176 "Recursively macroexpands ParenScript macros and symbol-macros in
177 the given ParenScript form. Returns two values: the expanded form, and
178 whether any expansion was performed on the form or not."
179 (let ((macro-function (cond ((ps-symbol-macro-p form) form)
180 ((and (consp form) (ps-macro-p (car form))) (car form)))))
181 (if macro-function
182 (values (ps-macroexpand (funcall (lookup-macro-expansion-function macro-function) form)) t)
183 (values form nil))))
184
185 ;;;; compiler interface
186 (defgeneric compile-parenscript-form (form &key expecting)
187 (:documentation "Compiles a ParenScript form to the intermediate
188 ParenScript representation. :expecting determines whether the form is
189 compiled to an :expression (the default), a :statement, or a
190 :symbol."))
191
192 (defun adjust-toplevel-compilation-level (form level)
193 (let ((default-level (if (eql :toplevel level)
194 :inside-toplevel-form
195 nil)))
196 (if (consp form)
197 (case (car form)
198 ('progn level)
199 (t default-level))
200 default-level)))
201
202 (defmethod compile-parenscript-form :around (form &key expecting)
203 (assert (if expecting (member expecting '(:expression :statement :symbol)) t))
204 (if (eql expecting :symbol)
205 (compile-to-symbol form)
206 (multiple-value-bind (expanded-form expanded-p)
207 (ps-macroexpand form)
208 (if expanded-p
209 (compile-parenscript-form expanded-form :expecting expecting)
210 (let ((*toplevel-compilation-level*
211 (progn
212 (adjust-toplevel-compilation-level form *toplevel-compilation-level*))))
213 (call-next-method))))))
214
215 (defun compile-to-symbol (form)
216 "Compiles the given Parenscript form and guarantees that the
217 resultant symbol has an associated script-package. Raises an error if
218 the form cannot be compiled to a symbol."
219 (let ((exp (compile-parenscript-form form)))
220 (when (eq (first exp) 'js:variable)
221 (setf exp (second exp)))
222 (assert (symbolp exp) ()
223 "~a is expected to be a symbol, but compiles to ~a (the ParenScript output for ~a alone is \"~a\"). This could be due to ~a being a special form." form exp form (ps* form) form)
224 exp))
225
226 (defmethod compile-parenscript-form (form &key expecting)
227 (declare (ignore expecting))
228 (error "The object ~S cannot be compiled by ParenScript." form))
229
230 (defmethod compile-parenscript-form ((form number) &key expecting)
231 (declare (ignore expecting))
232 form)
233
234 (defmethod compile-parenscript-form ((form string) &key expecting)
235 (declare (ignore expecting))
236 form)
237
238 (defmethod compile-parenscript-form ((form character) &key expecting)
239 (declare (ignore expecting))
240 (compile-parenscript-form (string form)))
241
242 (defmethod compile-parenscript-form ((symbol symbol) &key expecting)
243 (declare (ignore expecting))
244 (cond ((keywordp symbol) symbol)
245 ((ps-special-form-p (list symbol))
246 (if (ps-literal-p symbol)
247 (funcall (get-ps-special-form symbol) :symbol)
248 (error "Attempting to use Parenscript special form ~a as variable" symbol)))
249 (t `(js:variable ,symbol))))
250
251 (defun ps-convert-op-name (op)
252 (case op
253 (and '\&\&)
254 (or '\|\|)
255 (not '!)
256 (eql '\=\=)
257 (= '\=\=)
258 (t op)))
259
260 (defmethod compile-parenscript-form ((form cons) &key (expecting :statement))
261 (let* ((name (car form))
262 (args (cdr form)))
263 (cond ((ps-special-form-p form) (apply (get-ps-special-form name) (cons expecting args)))
264 ((op-form-p form)
265 `(js:operator
266 ,(ps-convert-op-name (compile-parenscript-form (first form) :expecting :symbol))
267 ,@(mapcar (lambda (form) (compile-parenscript-form form :expecting :expression)) (rest form))))
268 ((funcall-form-p form)
269 `(js:funcall ,(compile-parenscript-form name :expecting :expression)
270 ,@(mapcar (lambda (arg) (compile-parenscript-form arg :expecting :expression)) args)))
271 (t (error "Cannot compile ~S to a ParenScript form." form)))))
272
273 (defvar *ps-gensym-counter* 0)
274
275 (defun ps-gensym (&optional (prefix "_js"))
276 (make-symbol (format nil "~A~A" prefix (incf *ps-gensym-counter*))))
277
278 (defmacro with-ps-gensyms (symbols &body body)
279 "Evaluate BODY with SYMBOLS bound to unique ParenScript identifiers.
280
281 Each element of SYMBOLS is either a symbol or a list of (symbol
282 gensym-prefix-string)."
283 `(let* ,(mapcar (lambda (symbol)
284 (destructuring-bind (symbol &optional prefix)
285 (if (consp symbol)
286 symbol
287 (list symbol))
288 (if prefix
289 `(,symbol (ps-gensym ,prefix))
290 `(,symbol (ps-gensym ,(symbol-to-js-string symbol))))))
291 symbols)
292 ,@body))
293
294 (defun %check-once-only-vars (vars)
295 (let ((bad-var (find-if (lambda (x) (or (not (symbolp x)) (keywordp x))) vars)))
296 (when bad-var
297 (error "PS-ONLY-ONCE expected a non-keyword symbol but got ~s" bad-var))))
298
299 (defmacro ps-once-only ((&rest vars) &body body)
300 (%check-once-only-vars vars)
301 (let ((gensyms (mapcar (lambda (x) (ps-gensym (string x))) vars)))
302 `(let ,(mapcar (lambda (g v) `(,g (ps-gensym ,(string v)))) gensyms vars)
303 `(let* (,,@(mapcar (lambda (g v) ``(,,g ,,v)) gensyms vars))
304 ,(let ,(mapcar (lambda (g v) `(,v ,g)) gensyms vars)
305 ,@body)))))
306
307 (defvar *read-function* #'read
308 "This should be a function that takes the same inputs and returns the same
309 outputs as the common lisp read function. We declare it as a variable to allow
310 a user-supplied reader instead of the default lisp reader.")
311
312 (defun ps-compile-stream (stream)
313 "Compiles a source stream as if it were a file. Outputs a Javascript string."
314
315 (let ((*toplevel-compilation-level* :toplevel)
316 (*package* *package*)
317 (end-read-form '#:unique))
318 (flet ((read-form () (funcall *read-function* stream nil end-read-form)))
319 (let* ((js-string
320 ;; cons up the forms, compiling as we go, and print the result
321 (do ((form (read-form) (read-form))
322 (compiled-forms nil))
323 ((eql form end-read-form)
324 (format nil "~{~A~^;~%~}"
325 (remove-if
326 #'(lambda (x) (or (null x) (= 0 (length x))))
327 (mapcar 'compiled-form-to-string (nreverse compiled-forms)))))
328 (push (compile-parenscript-form form :expecting :statement) compiled-forms))))
329 js-string))))
330
331
332 (defun ps-compile-file (source-file)
333 "Compiles the given Parenscript source file and returns a Javascript string."
334 (with-open-file (stream source-file :direction :input)
335 (ps-compile-stream stream)))
336