Initialize keyword arguments from js ARGUMENTS, allowing keywords to also be passed...
[clinton/parenscript.git] / src / special-forms.lisp
1 (in-package :parenscript)
2
3 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4 ;;; literals
5 (defmacro defpsliteral (name string)
6 `(progn
7 (add-ps-literal ',name)
8 (define-ps-special-form ,name ()
9 (list 'js-literal ,string))))
10
11 (defpsliteral this "this")
12 (defpsliteral t "true")
13 (defpsliteral true "true")
14 (defpsliteral false "false")
15 (defpsliteral f "false")
16 (defpsliteral nil "null")
17 (defpsliteral undefined "undefined")
18
19 (macrolet ((def-for-literal (name printer)
20 `(progn
21 (add-ps-literal ',name)
22 (define-ps-special-form ,name (&optional label)
23 (list ',printer label)))))
24 (def-for-literal break js-break)
25 (def-for-literal continue js-continue))
26
27 (defpsmacro quote (x)
28 (typecase x
29 (cons (cons 'array (mapcar (lambda (x) `',x) x)))
30 (null '(make-array))
31 (symbol (symbol-to-js-string x))
32 (number x)
33 (string x)))
34
35 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
36 ;;; unary operators
37 (macrolet ((def-unary-ops (&rest ops)
38 `(progn ,@(mapcar (lambda (op)
39 (let ((op (if (listp op) (car op) op))
40 (spacep (if (listp op) (second op) nil)))
41 `(define-ps-special-form ,op (x)
42 (list 'unary-operator ',op
43 (compile-parenscript-form x :expecting :expression)
44 :prefix t :space ,spacep))))
45 ops))))
46 (def-unary-ops ~ ! (new t) (delete t) (void t) (typeof t)))
47
48 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
49 ;;; statements
50 (define-ps-special-form return (&optional value)
51 (list 'js-return (compile-parenscript-form value :expecting :expression)))
52
53 (define-ps-special-form throw (value)
54 (list 'js-throw (compile-parenscript-form value :expecting :expression)))
55
56 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
57 ;;; arrays
58 (define-ps-special-form array (&rest values)
59 (cons 'array-literal (mapcar (lambda (form) (compile-parenscript-form form :expecting :expression))
60 values)))
61
62 (define-ps-special-form aref (array &rest coords)
63 (list 'js-aref (compile-parenscript-form array :expecting :expression)
64 (mapcar (lambda (form)
65 (compile-parenscript-form form :expecting :expression))
66 coords)))
67
68 (defpsmacro list (&rest values)
69 `(array ,@values))
70
71 (defpsmacro make-array (&rest initial-values)
72 `(new (*array ,@initial-values)))
73
74 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
75 ;;; operators
76 (define-ps-special-form incf (x &optional (delta 1))
77 (if (equal delta 1)
78 (list 'unary-operator '++ (compile-parenscript-form x :expecting :expression) :prefix t)
79 (list 'operator '+= (list (compile-parenscript-form x :expecting :expression)
80 (compile-parenscript-form delta :expecting :expression)))))
81
82 (define-ps-special-form decf (x &optional (delta 1))
83 (if (equal delta 1)
84 (list 'unary-operator '-- (compile-parenscript-form x :expecting :expression) :prefix t)
85 (list 'operator '-= (list (compile-parenscript-form x :expecting :expression)
86 (compile-parenscript-form delta :expecting :expression)))))
87
88 (define-ps-special-form - (first &rest rest)
89 (if (null rest)
90 (list 'unary-operator '- (compile-parenscript-form first :expecting :expression) :prefix t)
91 (list 'operator '- (mapcar (lambda (val) (compile-parenscript-form val :expecting :expression))
92 (cons first rest)))))
93
94 (define-ps-special-form not (x)
95 (let ((form (compile-parenscript-form x :expecting :expression))
96 (not-op nil))
97 (if (and (eql (first form) 'operator)
98 (= (length (third form)) 2)
99 (setf not-op (case (second form)
100 (== '!=)
101 (< '>=)
102 (> '<=)
103 (<= '>)
104 (>= '<)
105 (!= '==)
106 (=== '!==)
107 (!== '===)
108 (t nil))))
109 (list 'operator not-op (third form))
110 (list 'unary-operator '! form :prefix t))))
111
112 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
113 ;;; control structures
114 (defun flatten-blocks (body)
115 (when body
116 (if (and (listp (car body))
117 (eql 'js-block (caar body)))
118 (append (third (car body)) (flatten-blocks (cdr body)))
119 (cons (car body) (flatten-blocks (cdr body))))))
120
121 (defun constant-literal-form-p (form)
122 (or (numberp form)
123 (stringp form)
124 (and (listp form)
125 (eql 'js-literal (car form)))))
126
127 (define-ps-special-form progn (&rest body)
128 (if (and (eq expecting :expression) (= 1 (length body)))
129 (compile-parenscript-form (car body) :expecting :expression)
130 (list 'js-block
131 expecting
132 (let* ((block (mapcar (lambda (form)
133 (compile-parenscript-form form :expecting expecting))
134 body))
135 (clean-block (remove nil block))
136 (flat-block (flatten-blocks clean-block))
137 (reachable-block (append (remove-if #'constant-literal-form-p (butlast flat-block))
138 (last flat-block))))
139 reachable-block))))
140
141 (define-ps-special-form cond (&rest clauses)
142 (ecase expecting
143 (:statement (list 'js-cond-statement
144 (mapcar (lambda (clause)
145 (destructuring-bind (test &rest body)
146 clause
147 (list (compile-parenscript-form test :expecting :expression)
148 (compile-parenscript-form `(progn ,@body) :expecting :statement))))
149 clauses)))
150 (:expression (make-cond-clauses-into-nested-ifs clauses))))
151
152 (defun make-cond-clauses-into-nested-ifs (clauses)
153 (if clauses
154 (destructuring-bind (test &rest body)
155 (car clauses)
156 (if (eq t test)
157 (compile-parenscript-form `(progn ,@body) :expecting :expression)
158 `(js:? ,(compile-parenscript-form test :expecting :expression)
159 ,(compile-parenscript-form `(progn ,@body) :expecting :expression)
160 ,(make-cond-clauses-into-nested-ifs (cdr clauses)))))
161 (compile-parenscript-form nil :expecting :expression)))
162
163 (define-ps-special-form if (test then &optional else)
164 (ecase expecting
165 (:statement `(js:if ,(compile-parenscript-form test :expecting :expression)
166 ,(compile-parenscript-form `(progn ,then))
167 ,(when else (compile-parenscript-form `(progn ,else)))))
168 (:expression `(js:? ,(compile-parenscript-form test :expecting :expression)
169 ,(compile-parenscript-form then :expecting :expression)
170 ,(compile-parenscript-form else :expecting :expression)))))
171
172 (define-ps-special-form switch (test-expr &rest clauses)
173 (let ((clauses (mapcar (lambda (clause)
174 (let ((val (car clause))
175 (body (cdr clause)))
176 (cons (if (and (symbolp val)
177 (eq (ensure-ps-symbol val) 'default))
178 'default
179 (compile-parenscript-form val :expecting :expression))
180 (mapcar (lambda (statement) (compile-parenscript-form statement :expecting :statement))
181 body))))
182 clauses))
183 (expr (compile-parenscript-form test-expr :expecting :expression)))
184 (list 'js-switch expr clauses)))
185
186 (defpsmacro case (value &rest clauses)
187 (labels ((make-clause (val body more)
188 (cond ((and (listp val) (not (eq (car val) 'quote)))
189 (append (mapcar #'list (butlast val))
190 (make-clause (first (last val)) body more)))
191 ((member val '(t otherwise))
192 (make-clause 'default body more))
193 (more `((,val ,@body break)))
194 (t `((,val ,@body))))))
195 `(switch ,value ,@(mapcon (lambda (clause)
196 (make-clause (car (first clause))
197 (cdr (first clause))
198 (rest clause)))
199 clauses))))
200
201 (defpsmacro when (test &rest body)
202 `(if ,test (progn ,@body)))
203
204 (defpsmacro unless (test &rest body)
205 `(if (not ,test) (progn ,@body)))
206
207 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
208 ;;; function definition
209 (defun compile-function-definition (args body)
210 (list (mapcar (lambda (arg) (compile-parenscript-form arg :expecting :symbol)) args)
211 (let ((*enclosing-lexical-block-declarations* ()))
212 ;; the first compilation will produce a list of variables we need to declare in the function body
213 (compile-parenscript-form `(progn ,@body) :expecting :statement)
214 ;; now declare and compile
215 (compile-parenscript-form `(progn ,@(loop for var in *enclosing-lexical-block-declarations* collect `(var ,var))
216 ,@body) :expecting :statement))))
217
218 (define-ps-special-form %js-lambda (args &rest body)
219 (cons 'js-lambda (compile-function-definition args body)))
220
221 (define-ps-special-form %js-defun (name args &rest body)
222 (append (list 'js-defun name) (compile-function-definition args body)))
223
224 (defun parse-function-body (body)
225 (let* ((docstring
226 (when (stringp (first body))
227 (first body)))
228 (body-forms (if docstring (rest body) body)))
229 (values body-forms docstring)))
230
231 (defun parse-key-spec (key-spec)
232 "parses an &key parameter. Returns 5 values:
233 var, init-form, keyword-name, supplied-p-var, init-form-supplied-p.
234
235 Syntax of key spec:
236 [&key {var | ({var | (keyword-name var)} [init-form [supplied-p-parameter]])}*
237 "
238 (let* ((var (cond ((symbolp key-spec) key-spec)
239 ((and (listp key-spec) (symbolp (first key-spec))) (first key-spec))
240 ((and (listp key-spec) (listp (first key-spec))) (second key-spec))))
241 (keyword-name (if (and (listp key-spec) (listp (first key-spec)))
242 (first (first key-spec))
243 (intern (string var) :keyword)))
244 (init-form (if (listp key-spec) (second key-spec) nil))
245 (init-form-supplied-p (if (listp key-spec) t nil))
246 (supplied-p-var (if (listp key-spec) (third key-spec) nil)))
247 (values var init-form keyword-name supplied-p-var init-form-supplied-p)))
248
249 (defun parse-optional-spec (spec)
250 "Parses an &optional parameter. Returns 3 values: var, init-form, supplied-p-var.
251 [&optional {var | (var [init-form [supplied-p-parameter]])}*] "
252 (let* ((var (cond ((symbolp spec) spec)
253 ((and (listp spec) (first spec)))))
254 (init-form (if (listp spec) (second spec)))
255 (supplied-p-var (if (listp spec) (third spec))))
256 (values var init-form supplied-p-var)))
257
258 (defun parse-aux-spec (spec)
259 "Returns two values: variable and init-form"
260 ;; [&aux {var | (var [init-form])}*])
261 (values (if (symbolp spec) spec (first spec))
262 (when (listp spec) (second spec))))
263
264 (defpsmacro defaultf (place value)
265 `(when (=== ,place undefined)
266 (setf ,place ,value)))
267
268 (defun parse-extended-function (lambda-list body &optional name)
269 "Returns two values: the effective arguments and body for a function with
270 the given lambda-list and body."
271
272 ;; The lambda list is transformed as follows, since a javascript lambda list is just a
273 ;; list of variable names, and you have access to the arguments variable inside the function:
274 ;; * standard variables are the mapped directly into the js-lambda list
275 ;; * optional variables' variable names are mapped directly into the lambda list,
276 ;; and for each optional variable with name v and default value d, a form is produced
277 ;; (defaultf v d)
278 ;; * keyword variables are not included in the js-lambda list, but instead are
279 ;; obtained from the magic js ARGUMENTS pseudo-array. Code assigning values to
280 ;; keyword vars is prepended to the body of the function.
281 (declare (ignore name))
282 (multiple-value-bind (requireds optionals rest? rest keys? keys allow? aux? aux
283 more? more-context more-count key-object)
284 (parse-lambda-list lambda-list)
285 (declare (ignore allow? aux? aux more? more-context more-count key-object))
286 (let* (;; optionals are of form (var default-value)
287 (effective-args
288 (remove-if
289 #'null
290 (append requireds
291 (mapcar #'parse-optional-spec optionals))))
292 (opt-forms
293 (mapcar #'(lambda (opt-spec)
294 (multiple-value-bind (var val) (parse-optional-spec opt-spec)
295 `(defaultf ,var ,val)))
296 optionals))
297 (key-forms
298 (when keys?
299 (with-ps-gensyms (n)
300 (let ((decls nil) (assigns nil) (defaults nil))
301 (mapc (lambda (k)
302 (multiple-value-bind (var init-form keyword)
303 (parse-key-spec k)
304 (push (list 'var var) decls)
305 (push `(,keyword (setf ,var (aref arguments (1+ ,n)))) assigns)
306 (push (list 'defaultf var init-form) defaults)))
307 (reverse keys))
308 `(,@decls
309 (loop :for ,n :from ,(length requireds)
310 :below (length arguments) :by 2 :do
311 (case (aref arguments ,n) ,@assigns))
312 ,@defaults)))))
313 (rest-form
314 (if rest?
315 (with-ps-gensyms (i)
316 `(progn (var ,rest (array))
317 (dotimes (,i (- arguments.length ,(length effective-args)))
318 (setf (aref ,rest ,i) (aref arguments (+ ,i ,(length effective-args)))))))
319 `(progn)))
320 (body-paren-forms (parse-function-body body)) ; remove documentation
321 (effective-body (append opt-forms key-forms (list rest-form) body-paren-forms)))
322 (values effective-args effective-body))))
323
324 (defpsmacro defun (name lambda-list &body body)
325 "An extended defun macro that allows cool things like keyword arguments.
326 lambda-list::=
327 (var*
328 [&optional {var | (var [init-form [supplied-p-parameter]])}*]
329 [&rest var]
330 [&key {var | ({var | (keyword-name var)} [init-form [supplied-p-parameter]])}* [&allow-other-keys]]
331 [&aux {var | (var [init-form])}*])"
332 (if (symbolp name)
333 `(defun-function ,name ,lambda-list ,@body)
334 (progn (assert (and (= (length name) 2) (eq 'setf (ensure-ps-symbol (car name)))) ()
335 "(defun ~s ~s ...) needs to have a symbol or (setf symbol) for a name." name lambda-list)
336 `(defun-setf ,name ,lambda-list ,@body))))
337
338 (defpsmacro defun-function (name lambda-list &body body)
339 (multiple-value-bind (effective-args effective-body)
340 (parse-extended-function lambda-list body name)
341 `(%js-defun ,name ,effective-args
342 ,@effective-body)))
343
344 (defvar *defun-setf-name-prefix* "__setf_")
345
346 (defpsmacro defun-setf (setf-name lambda-list &body body)
347 (let ((mangled-function-name (intern (concatenate 'string *defun-setf-name-prefix* (symbol-name (second setf-name)))
348 (symbol-package (second setf-name))))
349 (function-args (cdr (ordered-set-difference lambda-list lambda-list-keywords))))
350 `(progn (defsetf ,(second setf-name) ,(cdr lambda-list) (store-var)
351 `(,',mangled-function-name ,store-var ,@(list ,@function-args)))
352 (defun ,mangled-function-name ,lambda-list ,@body))))
353
354 (defpsmacro lambda (lambda-list &body body)
355 "An extended defun macro that allows cool things like keyword arguments.
356 lambda-list::=
357 (var*
358 [&optional {var | (var [init-form [supplied-p-parameter]])}*]
359 [&rest var]
360 [&key {var | ({var | (keyword-name var)} [init-form [supplied-p-parameter]])}* [&allow-other-keys]]
361 [&aux {var | (var [init-form])}*])"
362 (multiple-value-bind (effective-args effective-body)
363 (parse-extended-function lambda-list body)
364 `(%js-lambda ,effective-args
365 ,@effective-body)))
366
367 (defpsmacro flet (fn-defs &rest body)
368 (flet ((process-fn-def (def)
369 `(var ,(car def) (lambda ,@(cdr def)))))
370 `(progn ,@(mapcar #'process-fn-def fn-defs) ,@body)))
371
372 (defpsmacro labels (fn-defs &rest body)
373 (flet ((process-fn-def (def)
374 `(var ,(car def) (defun ,(car def) ,@(cdr def)))))
375 `(progn ,@(mapcar #'process-fn-def fn-defs) ,@body)))
376
377 (defpsmacro defsetf-long (access-fn lambda-list (store-var) form)
378 (setf (get-macro-spec access-fn *ps-setf-expanders*)
379 (compile nil
380 (let ((var-bindings (ordered-set-difference lambda-list lambda-list-keywords)))
381 `(lambda (access-fn-args store-form)
382 (destructuring-bind ,lambda-list
383 access-fn-args
384 (let* ((,store-var (ps-gensym))
385 (gensymed-names (loop repeat ,(length var-bindings) collecting (ps-gensym)))
386 (gensymed-arg-bindings (mapcar #'list gensymed-names (list ,@var-bindings))))
387 (destructuring-bind ,var-bindings
388 gensymed-names
389 `(let* (,@gensymed-arg-bindings
390 (,,store-var ,store-form))
391 ,,form))))))))
392 nil)
393
394 (defpsmacro defsetf-short (access-fn update-fn &optional docstring)
395 (declare (ignore docstring))
396 (setf (get-macro-spec access-fn *ps-setf-expanders*)
397 (lambda (access-fn-args store-form)
398 `(,update-fn ,@access-fn-args ,store-form)))
399 nil)
400
401 (defpsmacro defsetf (access-fn &rest args)
402 `(,(if (= (length args) 3) 'defsetf-long 'defsetf-short) ,access-fn ,@args))
403
404 (defpsmacro funcall (&rest arg-form)
405 arg-form)
406
407 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
408 ;;; macros
409 (defmacro with-temp-macro-environment ((var) &body body)
410 `(let* ((,var (make-macro-env-dictionary))
411 (*ps-macro-env* (cons ,var *ps-macro-env*)))
412 ,@body))
413
414 (define-ps-special-form macrolet (macros &body body)
415 (with-temp-macro-environment (macro-env-dict)
416 (dolist (macro macros)
417 (destructuring-bind (name arglist &body body)
418 macro
419 (setf (get-macro-spec name macro-env-dict)
420 (cons nil (eval (make-ps-macro-function arglist body))))))
421 (compile-parenscript-form `(progn ,@body))))
422
423 (define-ps-special-form symbol-macrolet (symbol-macros &body body)
424 (with-temp-macro-environment (macro-env-dict)
425 (dolist (macro symbol-macros)
426 (destructuring-bind (name expansion)
427 macro
428 (setf (get-macro-spec name macro-env-dict)
429 (cons t (lambda (x) (declare (ignore x)) expansion)))))
430 (compile-parenscript-form `(progn ,@body))))
431
432 (define-ps-special-form defmacro (name args &body body)
433 (eval `(defpsmacro ,name ,args ,@body))
434 nil)
435
436 (define-ps-special-form define-symbol-macro (name expansion)
437 (eval `(define-ps-symbol-macro ,name ,expansion))
438 nil)
439
440 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
441 ;;; objects
442 (add-ps-literal '{})
443 (define-ps-symbol-macro {} (create))
444
445 (define-ps-special-form create (&rest arrows)
446 (list 'js-object (loop for (key-expr val-expr) on arrows by #'cddr collecting
447 (let ((key (compile-parenscript-form key-expr :expecting :expression)))
448 (when (keywordp key)
449 (setf key (list 'js-variable key)))
450 (assert (or (stringp key)
451 (numberp key)
452 (and (listp key)
453 (or (eq 'js-variable (car key))
454 (eq 'quote (car key)))))
455 ()
456 "Slot key ~s is not one of js-variable, keyword, string or number." key)
457 (cons key (compile-parenscript-form val-expr :expecting :expression))))))
458
459 (define-ps-special-form %js-slot-value (obj slot)
460 (list 'js-slot-value (compile-parenscript-form obj :expecting :expression)
461 (if (and (listp slot) (eq 'quote (car slot)))
462 (second slot) ;; assume we're quoting a symbol
463 (compile-parenscript-form slot))))
464
465 (define-ps-special-form instanceof (value type)
466 (list 'js-instanceof (compile-parenscript-form value :expecting :expression)
467 (compile-parenscript-form type :expecting :expression)))
468
469 (defpsmacro slot-value (obj &rest slots)
470 (if (null (rest slots))
471 `(%js-slot-value ,obj ,(first slots))
472 `(slot-value (slot-value ,obj ,(first slots)) ,@(rest slots))))
473
474 (defpsmacro with-slots (slots object &rest body)
475 (flet ((slot-var (slot) (if (listp slot) (first slot) slot))
476 (slot-symbol (slot) (if (listp slot) (second slot) slot)))
477 `(symbol-macrolet ,(mapcar #'(lambda (slot)
478 `(,(slot-var slot) (slot-value ,object ',(slot-symbol slot))))
479 slots)
480 ,@body)))
481
482 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
483 ;;; assignment and binding
484 (defun assignment-op (op)
485 (case op
486 (+ '+=)
487 (~ '~=)
488 (\& '\&=)
489 (\| '\|=)
490 (- '-=)
491 (* '*=)
492 (% '%=)
493 (>> '>>=)
494 (^ '^=)
495 (<< '<<=)
496 (>>> '>>>=)
497 (/ '/=)
498 (t nil)))
499
500 (defun smart-setf (lhs rhs)
501 (if (and (listp rhs)
502 (eql 'operator (car rhs))
503 (member lhs (third rhs) :test #'equalp))
504 (let ((args-without-first (remove lhs (third rhs) :count 1 :end 1 :test #'equalp)))
505 (cond ((and (assignment-op (second rhs))
506 (member (second rhs) '(+ *))
507 (equalp lhs (first (third rhs))))
508 (list 'operator (assignment-op (second rhs))
509 (list lhs (list 'operator (second rhs) args-without-first))))
510 (t (list 'js-assign lhs rhs))))
511 (list 'js-assign lhs rhs)))
512
513 (define-ps-special-form setf1% (lhs rhs)
514 (smart-setf (compile-parenscript-form lhs :expecting :expression) (compile-parenscript-form rhs :expecting :expression)))
515
516 (defpsmacro setf (&rest args)
517 (flet ((process-setf-clause (place value-form)
518 (if (and (listp place) (get-macro-spec (car place) *ps-setf-expanders*))
519 (funcall (get-macro-spec (car place) *ps-setf-expanders*) (cdr place) value-form)
520 (let ((exp-place (ps-macroexpand place)))
521 (if (and (listp exp-place) (get-macro-spec (car exp-place) *ps-setf-expanders*))
522 (funcall (get-macro-spec (car exp-place) *ps-setf-expanders*) (cdr exp-place) value-form)
523 `(setf1% ,exp-place ,value-form))))))
524 (assert (evenp (length args)) ()
525 "~s does not have an even number of arguments." (cons 'setf args))
526 `(progn ,@(loop for (place value) on args by #'cddr collect (process-setf-clause place value)))))
527
528 (defpsmacro psetf (&rest args)
529 (let ((vars (loop for x in args by #'cddr collect x))
530 (vals (loop for x in (cdr args) by #'cddr collect x)))
531 (let ((gensyms (mapcar (lambda (x) (declare (ignore x)) (ps-gensym)) vars)))
532 `(simple-let* ,(mapcar #'list gensyms vals)
533 (setf ,@(mapcan #'list vars gensyms))))))
534
535 (defun check-setq-args (args)
536 (let ((vars (loop for x in args by #'cddr collect x)))
537 (let ((non-var (find-if (complement #'symbolp) vars)))
538 (when non-var
539 (error 'type-error :datum non-var :expected-type 'symbol)))))
540
541 (defpsmacro setq (&rest args)
542 (check-setq-args args)
543 `(setf ,@args))
544
545 (defpsmacro psetq (&rest args)
546 (check-setq-args args)
547 `(psetf ,@args))
548
549 (define-ps-special-form var (name &rest value)
550 (append (list 'js-var name)
551 (when value
552 (assert (= (length value) 1) () "Wrong number of arguments to var: ~s" `(var ,name ,@value))
553 (list (compile-parenscript-form (car value) :expecting :expression)))))
554
555 (defpsmacro defvar (name &rest value)
556 "Note: this must be used as a top-level form, otherwise the result will be undefined behavior."
557 (pushnew name *ps-special-variables*)
558 (assert (or (null value) (= (length value) 1)) () "Wrong number of arguments to defvar: ~s" `(defvar ,name ,@value))
559 `(var ,name ,@value))
560
561 (defun make-let-vars (bindings)
562 (mapcar (lambda (x) (if (listp x) (car x) x)) bindings))
563
564 (defun make-let-vals (bindings)
565 (mapcar (lambda (x) (if (or (atom x) (endp (cdr x))) nil (second x))) bindings))
566
567 (defpsmacro lexical-let* (bindings &body body)
568 `((lambda ()
569 (let* ,bindings
570 ,@body))))
571
572 (defpsmacro lexical-let (bindings &body body)
573 `((lambda ,(make-let-vars bindings)
574 ,@body)
575 ,@(make-let-vals bindings)))
576
577 (defpsmacro simple-let* (bindings &body body)
578 (if bindings
579 (let ((var (if (listp (car bindings)) (caar bindings) (car bindings))))
580 `(,(if (member var *ps-special-variables*) 'let1-dynamic 'let1) ,(car bindings)
581 (simple-let* ,(cdr bindings) ,@body)))
582 `(progn ,@body)))
583
584 (defpsmacro simple-let (bindings &body body)
585 (let ((vars (mapcar (lambda (x) (if (atom x) x (first x))) bindings))
586 (vals (mapcar (lambda (x) (if (or (atom x) (endp (cdr x))) nil (second x))) bindings)))
587 (let ((gensyms (mapcar (lambda (x) (ps-gensym (format nil "_js_~a" x))) vars)))
588 `(simple-let* ,(mapcar #'list gensyms vals)
589 (simple-let* ,(mapcar #'list vars gensyms)
590 ,@(mapcar (lambda (x) `(delete ,x)) gensyms)
591 ,@body)))))
592
593 (defpsmacro let* (bindings &body body)
594 `(simple-let* ,bindings ,@body))
595
596 (defpsmacro let (bindings &body body)
597 `(,(if (= 1 (length bindings)) 'simple-let* 'simple-let) ,bindings ,@body))
598
599 (define-ps-special-form let1 (binding &rest body)
600 (ecase expecting
601 (:statement
602 (compile-parenscript-form `(progn ,(if (atom binding) `(var ,binding) `(var ,@binding)) ,@body) :expecting :statement))
603 (:expression
604 (let ((var (if (atom binding) binding (car binding)))
605 (variable-assignment (when (listp binding) (cons 'setf binding))))
606 (push var *enclosing-lexical-block-declarations*)
607 (compile-parenscript-form `(progn ,variable-assignment ,@body) :expecting :expression)))))
608
609 (defpsmacro let1-dynamic ((var value) &rest body)
610 (with-ps-gensyms (temp-stack-var)
611 `(progn (var ,temp-stack-var)
612 (try (progn (setf ,temp-stack-var ,var)
613 (setf ,var ,value)
614 ,@body)
615 (:finally
616 (setf ,var ,temp-stack-var)
617 (delete ,temp-stack-var))))))
618
619 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
620 ;;; iteration
621 (defun make-for-vars/inits (init-forms)
622 (mapcar (lambda (x)
623 (cons (compile-parenscript-form (if (atom x) x (first x)) :expecting :symbol)
624 (compile-parenscript-form (if (atom x) nil (second x)) :expecting :expression)))
625 init-forms))
626
627 (define-ps-special-form labeled-for (label init-forms cond-forms step-forms &rest body)
628 (let ((vars (make-for-vars/inits init-forms))
629 (steps (mapcar (lambda (x) (compile-parenscript-form x :expecting :expression)) step-forms))
630 (tests (mapcar (lambda (x) (compile-parenscript-form x :expecting :expression)) cond-forms))
631 (body (compile-parenscript-form `(progn ,@body))))
632 (list 'js-for label vars tests steps body)))
633
634 (defpsmacro for (init-forms cond-forms step-forms &body body)
635 `(labeled-for nil ,init-forms ,cond-forms ,step-forms ,@body))
636
637 (defun do-make-let-bindings (decls)
638 (mapcar (lambda (x)
639 (if (atom x) x
640 (if (endp (cdr x)) (list (car x))
641 (subseq x 0 2))))
642 decls))
643
644 (defun do-make-init-vars (decls)
645 (mapcar (lambda (x) (if (atom x) x (first x))) decls))
646
647 (defun do-make-init-vals (decls)
648 (mapcar (lambda (x) (if (or (atom x) (endp (cdr x))) nil (second x))) decls))
649
650 (defun do-make-for-vars/init (decls)
651 (mapcar (lambda (x)
652 (if (atom x) x
653 (if (endp (cdr x)) x
654 (subseq x 0 2))))
655 decls))
656
657 (defun do-make-for-steps (decls)
658 (mapcar (lambda (x)
659 `(setf ,(first x) ,(third x)))
660 (remove-if (lambda (x) (or (atom x) (< (length x) 3))) decls)))
661
662 (defun do-make-iter-psteps (decls)
663 `(psetq
664 ,@(mapcan (lambda (x) (list (first x) (third x)))
665 (remove-if (lambda (x) (or (atom x) (< (length x) 3))) decls))))
666
667 (defpsmacro do* (decls (termination &optional (result nil result?)) &body body)
668 (if result?
669 `((lambda ()
670 (for ,(do-make-for-vars/init decls) ((not ,termination)) ,(do-make-for-steps decls)
671 ,@body)
672 (return ,result)))
673 `(progn
674 (for ,(do-make-for-vars/init decls) ((not ,termination)) ,(do-make-for-steps decls)
675 ,@body))))
676
677 (defpsmacro do (decls (termination &optional (result nil result?)) &body body)
678 (if result?
679 `((lambda ,(do-make-init-vars decls)
680 (for () ((not ,termination)) ()
681 ,@body
682 ,(do-make-iter-psteps decls))
683 (return ,result))
684 ,@(do-make-init-vals decls))
685 `(let ,(do-make-let-bindings decls)
686 (for () ((not ,termination)) ()
687 ,@body
688 ,(do-make-iter-psteps decls)))))
689
690 (define-ps-special-form for-in (decl &rest body)
691 (list 'js-for-in
692 (compile-parenscript-form (first decl) :expecting :expression)
693 (compile-parenscript-form (second decl) :expecting :expression)
694 (compile-parenscript-form `(progn ,@body))))
695
696 (defpsmacro doeach ((var array &optional (result (values) result?)) &body body)
697 "Iterates over `array'. If `var' is a symbol, binds `var' to each
698 element key. If `var' is a list, it must be a list of two
699 symbols, (key value), which will be bound to each successive key/value
700 pair in `array'."
701 (if result?
702 (if (consp var)
703 (destructuring-bind (key val) var
704 `((lambda ()
705 (let* (,val)
706 (for-in ((var ,key) ,array)
707 (setf ,val (aref ,array ,key))
708 ,@body)
709 (return ,result)))))
710 `((lambda ()
711 (for-in ((var ,var) ,array)
712 ,@body)
713 (return ,result))))
714 (if (consp var)
715 (destructuring-bind (key val) var
716 `(progn
717 (let* (,val)
718 (for-in ((var ,key) ,array)
719 (setf ,val (aref ,array ,key))
720 ,@body))))
721 `(progn
722 (for-in ((var ,var) ,array) ,@body)))))
723
724 (define-ps-special-form while (test &rest body)
725 (list 'js-while (compile-parenscript-form test :expecting :expression)
726 (compile-parenscript-form `(progn ,@body))))
727
728 (defpsmacro dotimes ((var count &optional (result nil result?)) &rest body)
729 `(do* ((,var 0 (1+ ,var)))
730 ((>= ,var ,count) ,@(when result? (list result)))
731 ,@body))
732
733 (defpsmacro dolist ((var array &optional (result nil result?)) &body body)
734 (let ((idx (ps-gensym "_js_idx"))
735 (arrvar (ps-gensym "_js_arrvar")))
736 `(do* (,var
737 (,arrvar ,array)
738 (,idx 0 (1+ ,idx)))
739 ((>= ,idx (slot-value ,arrvar 'length))
740 ,@(when result? (list result)))
741 (setq ,var (aref ,arrvar ,idx))
742 ,@body)))
743
744 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
745 ;;; misc
746 (define-ps-special-form with (expression &rest body)
747 (list 'js-with (compile-parenscript-form expression :expecting :expression)
748 (compile-parenscript-form `(progn ,@body))))
749
750 (define-ps-special-form try (form &rest clauses)
751 (let ((catch (cdr (assoc :catch clauses)))
752 (finally (cdr (assoc :finally clauses))))
753 (assert (not (cdar catch)) nil "Sorry, currently only simple catch forms are supported.")
754 (assert (or catch finally) ()
755 "Try form should have either a catch or a finally clause or both.")
756 (list 'js-try (compile-parenscript-form `(progn ,form))
757 :catch (when catch (list (compile-parenscript-form (caar catch) :expecting :symbol)
758 (compile-parenscript-form `(progn ,@(cdr catch)))))
759 :finally (when finally (compile-parenscript-form `(progn ,@finally))))))
760
761 (define-ps-special-form cc-if (test &rest body)
762 (list 'cc-if test (mapcar #'compile-parenscript-form body)))
763
764 (define-ps-special-form regex (regex)
765 (list 'js-regex (string regex)))
766
767 (define-ps-special-form lisp (lisp-form)
768 ;; (ps (foo (lisp bar))) is in effect equivalent to (ps* `(foo ,bar))
769 ;; when called from inside of ps*, lisp-form has access only to the dynamic environment (like for eval)
770 (list 'js-escape lisp-form))