3 ;; Copyright (C) 2012, 2013 David Vazquez
4 ;; Copyright (C) 2012 Raimon Grau
6 ;; JSCL is free software: you can redistribute it and/or
7 ;; modify it under the terms of the GNU General Public License as
8 ;; published by the Free Software Foundation, either version 3 of the
9 ;; License, or (at your option) any later version.
11 ;; JSCL is distributed in the hope that it will be useful, but
12 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ;; General Public License for more details.
16 ;; You should have received a copy of the GNU General Public License
17 ;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
21 (/debug "loading compiler.lisp!")
23 (define-js-macro selfcall (&body body)
24 `(call (function () ,@body)))
26 (define-js-macro bool (expr)
27 `(if ,expr ,(convert t) ,(convert nil)))
29 ;;; Translate the Lisp code to Javascript. It will compile the special
30 ;;; forms. Some primitive functions are compiled as special forms
31 ;;; too. The respective real functions are defined in the target (see
32 ;;; the beginning of this file) as well as some primitive functions.
34 (defun interleave (list element &optional after-last-p)
38 (dolist (x (cdr list))
44 ;;; Like CODE, but prefix each line with four spaces. Two versions
45 ;;; of this function are available, because the Ecmalisp version is
46 ;;; very slow and bootstraping was annoying.
48 ;;; A Form can return a multiple values object calling VALUES, like
49 ;;; values(arg1, arg2, ...). It will work in any context, as well as
50 ;;; returning an individual object. However, if the special variable
51 ;;; `*multiple-value-p*' is NIL, is granted that only the primary
52 ;;; value will be used, so we can optimize to avoid the VALUES
54 (defvar *multiple-value-p* nil)
70 (defun lookup-in-lexenv (name lexenv namespace)
71 (find name (ecase namespace
72 (variable (lexenv-variable lexenv))
73 (function (lexenv-function lexenv))
74 (block (lexenv-block lexenv))
75 (gotag (lexenv-gotag lexenv)))
78 (defun push-to-lexenv (binding lexenv namespace)
80 (variable (push binding (lexenv-variable lexenv)))
81 (function (push binding (lexenv-function lexenv)))
82 (block (push binding (lexenv-block lexenv)))
83 (gotag (push binding (lexenv-gotag lexenv)))))
85 (defun extend-lexenv (bindings lexenv namespace)
86 (let ((env (copy-lexenv lexenv)))
87 (dolist (binding (reverse bindings) env)
88 (push-to-lexenv binding env namespace))))
91 (defvar *environment* (make-lexenv))
92 (defvar *variable-counter* 0)
94 (defun gvarname (symbol)
95 (declare (ignore symbol))
96 (incf *variable-counter*)
97 (make-symbol (concat "v" (integer-to-string *variable-counter*))))
99 (defun translate-variable (symbol)
100 (awhen (lookup-in-lexenv symbol *environment* 'variable)
103 (defun extend-local-env (args)
104 (let ((new (copy-lexenv *environment*)))
105 (dolist (symbol args new)
106 (let ((b (make-binding :name symbol :type 'variable :value (gvarname symbol))))
107 (push-to-lexenv b new 'variable)))))
109 ;;; Toplevel compilations
110 (defvar *toplevel-compilations* nil)
112 (defun toplevel-compilation (string)
113 (push string *toplevel-compilations*))
115 (defun get-toplevel-compilations ()
116 (reverse *toplevel-compilations*))
118 (defun %compile-defmacro (name lambda)
119 (toplevel-compilation (convert `',name))
120 (let ((binding (make-binding :name name :type 'macro :value lambda)))
121 (push-to-lexenv binding *environment* 'function))
124 (defun global-binding (name type namespace)
125 (or (lookup-in-lexenv name *environment* namespace)
126 (let ((b (make-binding :name name :type type :value nil)))
127 (push-to-lexenv b *environment* namespace)
130 (defun claimp (symbol namespace claim)
131 (let ((b (lookup-in-lexenv symbol *environment* namespace)))
132 (and b (member claim (binding-declarations b)))))
134 (defun !proclaim (decl)
137 (dolist (name (cdr decl))
138 (let ((b (global-binding name 'variable 'variable)))
139 (push 'special (binding-declarations b)))))
141 (dolist (name (cdr decl))
142 (let ((b (global-binding name 'function 'function)))
143 (push 'notinline (binding-declarations b)))))
145 (dolist (name (cdr decl))
146 (let ((b (global-binding name 'variable 'variable)))
147 (push 'constant (binding-declarations b)))))))
150 (fset 'proclaim #'!proclaim)
152 (defun %define-symbol-macro (name expansion)
153 (let ((b (make-binding :name name :type 'macro :value expansion)))
154 (push-to-lexenv b *environment* 'variable)
158 (defmacro define-symbol-macro (name expansion)
159 `(%define-symbol-macro ',name ',expansion))
164 (defvar *compilations* nil)
166 (defmacro define-compilation (name args &body body)
167 ;; Creates a new primitive `name' with parameters args and
168 ;; @body. The body can access to the local environment through the
169 ;; variable *ENVIRONMENT*.
170 `(push (list ',name (lambda ,args (block ,name ,@body)))
173 (define-compilation if (condition true &optional false)
174 `(if (!== ,(convert condition) ,(convert nil))
175 ,(convert true *multiple-value-p*)
176 ,(convert false *multiple-value-p*)))
178 (defvar *ll-keywords* '(&optional &rest &key))
180 (defun list-until-keyword (list)
181 (if (or (null list) (member (car list) *ll-keywords*))
183 (cons (car list) (list-until-keyword (cdr list)))))
185 (defun ll-section (keyword ll)
186 (list-until-keyword (cdr (member keyword ll))))
188 (defun ll-required-arguments (ll)
189 (list-until-keyword ll))
191 (defun ll-optional-arguments-canonical (ll)
192 (mapcar #'ensure-list (ll-section '&optional ll)))
194 (defun ll-optional-arguments (ll)
195 (mapcar #'car (ll-optional-arguments-canonical ll)))
197 (defun ll-rest-argument (ll)
198 (let ((rest (ll-section '&rest ll)))
200 (error "Bad lambda-list `~S'." ll))
203 (defun ll-keyword-arguments-canonical (ll)
204 (flet ((canonicalize (keyarg)
205 ;; Build a canonical keyword argument descriptor, filling
206 ;; the optional fields. The result is a list of the form
207 ;; ((keyword-name var) init-form svar).
208 (let ((arg (ensure-list keyarg)))
209 (cons (if (listp (car arg))
211 (list (intern (symbol-name (car arg)) "KEYWORD") (car arg)))
213 (mapcar #'canonicalize (ll-section '&key ll))))
215 (defun ll-keyword-arguments (ll)
216 (mapcar (lambda (keyarg) (second (first keyarg)))
217 (ll-keyword-arguments-canonical ll)))
219 (defun ll-svars (lambda-list)
222 (ll-keyword-arguments-canonical lambda-list)
223 (ll-optional-arguments-canonical lambda-list))))
224 (remove nil (mapcar #'third args))))
226 (defun lambda-name/docstring-wrapper (name docstring code)
227 (if (or name docstring)
230 ,(when name `(= (get func "fname") ,name))
231 ,(when docstring `(= (get func "docstring") ,docstring))
235 (defun lambda-check-argument-count
236 (n-required-arguments n-optional-arguments rest-p)
237 ;; Note: Remember that we assume that the number of arguments of a
238 ;; call is at least 1 (the values argument).
239 (let ((min n-required-arguments)
240 (max (if rest-p 'n/a (+ n-required-arguments n-optional-arguments))))
242 ;; Special case: a positive exact number of arguments.
243 (when (and (< 0 min) (eql min max))
244 (return `(call |checkArgs| |nargs| ,min)))
247 ,(when (< 0 min) `(call |checkArgsAtLeast| |nargs| ,min))
248 ,(when (numberp max) `(call |checkArgsAtMost| |nargs| ,max))))))
250 (defun compile-lambda-optional (ll)
251 (let* ((optional-arguments (ll-optional-arguments-canonical ll))
252 (n-required-arguments (length (ll-required-arguments ll)))
253 (n-optional-arguments (length optional-arguments)))
254 (when optional-arguments
257 (dotimes (idx n-optional-arguments)
258 (let ((arg (nth idx optional-arguments)))
259 (collect `(case ,(+ idx n-required-arguments)))
260 (collect `(= ,(translate-variable (car arg))
261 ,(convert (cadr arg))))
262 (collect (when (third arg)
263 `(= ,(translate-variable (third arg))
266 (collect '(break)))))))
268 (defun compile-lambda-rest (ll)
269 (let ((n-required-arguments (length (ll-required-arguments ll)))
270 (n-optional-arguments (length (ll-optional-arguments ll)))
271 (rest-argument (ll-rest-argument ll)))
273 (let ((js!rest (translate-variable rest-argument)))
275 (var (,js!rest ,(convert nil)))
277 (for ((= i (- |nargs| 1))
278 (>= i ,(+ n-required-arguments n-optional-arguments))
280 (= ,js!rest (object "car" (property |arguments| (+ i 2))
281 "cdr" ,js!rest))))))))
283 (defun compile-lambda-parse-keywords (ll)
284 (let ((n-required-arguments
285 (length (ll-required-arguments ll)))
286 (n-optional-arguments
287 (length (ll-optional-arguments ll)))
289 (ll-keyword-arguments-canonical ll)))
293 (dolist (keyword-argument keyword-arguments)
294 (destructuring-bind ((keyword-name var) &optional initform svar)
296 (declare (ignore keyword-name initform))
297 (collect `(var ,(translate-variable var)))
300 `(var (,(translate-variable svar)
301 ,(convert nil))))))))
304 ,(flet ((parse-keyword (keyarg)
305 (destructuring-bind ((keyword-name var) &optional initform svar) keyarg
306 ;; ((keyword-name var) init-form svar)
308 (for ((= i ,(+ n-required-arguments n-optional-arguments))
312 (if (=== (property |arguments| (+ i 2))
313 ,(convert keyword-name))
315 (= ,(translate-variable var)
316 (property |arguments| (+ i 3)))
317 ,(when svar `(= ,(translate-variable svar)
321 (= ,(translate-variable var) ,(convert initform)))))))
322 (when keyword-arguments
325 ,@(mapcar #'parse-keyword keyword-arguments))))
327 ;; Check for unknown keywords
328 ,(when keyword-arguments
330 (var (start ,(+ n-required-arguments n-optional-arguments)))
331 (if (== (% (- |nargs| start) 2) 1)
332 (throw "Odd number of keyword arguments."))
333 (for ((= i start) (< i |nargs|) (+= i 2))
334 (if (and ,@(mapcar (lambda (keyword-argument)
335 (destructuring-bind ((keyword-name var) &optional initform svar)
337 (declare (ignore var initform svar))
338 `(!== (property |arguments| (+ i 2)) ,(convert keyword-name))))
340 (throw (+ "Unknown keyword argument "
343 (property |arguments| (+ i 2))
346 (defun parse-lambda-list (ll)
347 (values (ll-required-arguments ll)
348 (ll-optional-arguments ll)
349 (ll-keyword-arguments ll)
350 (ll-rest-argument ll)))
352 ;;; Process BODY for declarations and/or docstrings. Return as
353 ;;; multiple values the BODY without docstrings or declarations, the
354 ;;; list of declaration forms and the docstring.
355 (defun parse-body (body &key declarations docstring)
356 (let ((value-declarations)
358 ;; Parse declarations
360 (do* ((rest body (cdr rest))
361 (form (car rest) (car rest)))
362 ((or (atom form) (not (eq (car form) 'declare)))
364 (push form value-declarations)))
368 (not (null (cdr body))))
369 (setq value-docstring (car body))
370 (setq body (cdr body)))
371 (values body value-declarations value-docstring)))
373 ;;; Compile a lambda function with lambda list LL and body BODY. If
374 ;;; NAME is given, it should be a constant string and it will become
375 ;;; the name of the function. If BLOCK is non-NIL, a named block is
376 ;;; created around the body. NOTE: No block (even anonymous) is
377 ;;; created if BLOCk is NIL.
378 (defun compile-lambda (ll body &key name block)
379 (multiple-value-bind (required-arguments
383 (parse-lambda-list ll)
384 (multiple-value-bind (body decls documentation)
385 (parse-body body :declarations t :docstring t)
386 (declare (ignore decls))
387 (let ((n-required-arguments (length required-arguments))
388 (n-optional-arguments (length optional-arguments))
389 (*environment* (extend-local-env
390 (append (ensure-list rest-argument)
395 (lambda-name/docstring-wrapper name documentation
396 `(function (|values| |nargs| ,@(mapcar (lambda (x)
397 (translate-variable x))
398 (append required-arguments optional-arguments)))
399 ;; Check number of arguments
400 ,(lambda-check-argument-count n-required-arguments
402 (or rest-argument keyword-arguments))
403 ,(compile-lambda-optional ll)
404 ,(compile-lambda-rest ll)
405 ,(compile-lambda-parse-keywords ll)
407 ,(let ((*multiple-value-p* t))
409 (convert-block `((block ,block ,@body)) t)
410 (convert-block body t)))))))))
413 (defun setq-pair (var val)
414 (let ((b (lookup-in-lexenv var *environment* 'variable)))
417 (eq (binding-type b) 'variable)
418 (not (member 'special (binding-declarations b)))
419 (not (member 'constant (binding-declarations b))))
420 ;; TODO: Unnecesary make-symbol when codegen migration is
422 `(= ,(binding-value b) ,(convert val)))
423 ((and b (eq (binding-type b) 'macro))
424 (convert `(setf ,var ,val)))
426 (convert `(set ',var ,val))))))
429 (define-compilation setq (&rest pairs)
432 (return-from setq (convert nil)))
438 (error "Odd pairs in SETQ"))
440 (push `,(setq-pair (car pairs) (cadr pairs)) result)
441 (setq pairs (cddr pairs)))))
442 `(progn ,@(reverse result))))
445 ;;; Compilation of literals an object dumping
447 ;;; BOOTSTRAP MAGIC: We record the macro definitions as lists during
448 ;;; the bootstrap. Once everything is compiled, we want to dump the
449 ;;; whole global environment to the output file to reproduce it in the
450 ;;; run-time. However, the environment must contain expander functions
451 ;;; rather than lists. We do not know how to dump function objects
452 ;;; itself, so we mark the list definitions with this object and the
453 ;;; compiler will be called when this object has to be dumped.
454 ;;; Backquote/unquote does a similar magic, but this use is exclusive.
456 ;;; Indeed, perhaps to compile the object other macros need to be
457 ;;; evaluated. For this reason we define a valid macro-function for
459 (defvar *magic-unquote-marker* (gensym "MAGIC-UNQUOTE"))
462 (setf (macro-function *magic-unquote-marker*)
463 (lambda (form &optional environment)
464 (declare (ignore environment))
467 (defvar *literal-table* nil)
468 (defvar *literal-counter* 0)
471 (incf *literal-counter*)
472 (make-symbol (concat "l" (integer-to-string *literal-counter*))))
474 (defun dump-symbol (symbol)
476 (let ((package (symbol-package symbol)))
477 (if (eq package (find-package "KEYWORD"))
478 `(new (call |Symbol| ,(dump-string (symbol-name symbol)) ,(dump-string (package-name package))))
479 `(new (call |Symbol| ,(dump-string (symbol-name symbol))))))
481 (let ((package (symbol-package symbol)))
483 `(new (call |Symbol| ,(dump-string (symbol-name symbol))))
484 (convert `(intern ,(symbol-name symbol) ,(package-name package))))))
486 (defun dump-cons (cons)
487 (let ((head (butlast cons))
490 ,@(mapcar (lambda (x) (literal x t)) head)
491 ,(literal (car tail) t)
492 ,(literal (cdr tail) t))))
494 (defun dump-array (array)
495 (let ((elements (vector-to-list array)))
496 (list-to-vector (mapcar #'literal elements))))
498 (defun dump-string (string)
499 `(call |make_lisp_string| ,string))
501 (defun literal (sexp &optional recursive)
503 ((integerp sexp) sexp)
506 ;; TODO: Remove selfcall after migration
507 `(selfcall (return ,(string sexp))))
509 (or (cdr (assoc sexp *literal-table* :test #'eql))
510 (let ((dumped (typecase sexp
511 (symbol (dump-symbol sexp))
512 (string (dump-string sexp))
514 ;; BOOTSTRAP MAGIC: See the root file
515 ;; jscl.lisp and the function
516 ;; `dump-global-environment' for futher
518 (if (eq (car sexp) *magic-unquote-marker*)
519 (convert (second sexp))
521 (array (dump-array sexp)))))
522 (if (and recursive (not (symbolp sexp)))
524 (let ((jsvar (genlit)))
525 (push (cons sexp jsvar) *literal-table*)
526 (toplevel-compilation `(var (,jsvar ,dumped)))
527 (when (keywordp sexp)
528 (toplevel-compilation `(= ,(get jsvar "value") ,jsvar)))
532 (define-compilation quote (sexp)
535 (define-compilation %while (pred &rest body)
537 (while (!== ,(convert pred) ,(convert nil))
539 ; braces. Unnecesary when code
541 ,(convert-block body))
542 (return ,(convert nil))))
544 (define-compilation function (x)
546 ((and (listp x) (eq (car x) 'lambda))
547 (compile-lambda (cadr x) (cddr x)))
548 ((and (listp x) (eq (car x) 'named-lambda))
549 (destructuring-bind (name ll &rest body) (cdr x)
550 (compile-lambda ll body
551 :name (symbol-name name)
554 (let ((b (lookup-in-lexenv x *environment* 'function)))
557 (convert `(symbol-function ',x)))))))
559 (defun make-function-binding (fname)
560 (make-binding :name fname :type 'function :value (gvarname fname)))
562 (defun compile-function-definition (list)
563 (compile-lambda (car list) (cdr list)))
565 (defun translate-function (name)
566 (let ((b (lookup-in-lexenv name *environment* 'function)))
567 (and b (binding-value b))))
569 (define-compilation flet (definitions &rest body)
570 (let* ((fnames (mapcar #'car definitions))
571 (cfuncs (mapcar (lambda (def)
572 (compile-lambda (cadr def)
577 (extend-lexenv (mapcar #'make-function-binding fnames)
580 `(call (function ,(mapcar #'translate-function fnames)
581 ,(convert-block body t))
584 (define-compilation labels (definitions &rest body)
585 (let* ((fnames (mapcar #'car definitions))
587 (extend-lexenv (mapcar #'make-function-binding fnames)
591 ,@(mapcar (lambda (func)
592 `(var (,(translate-function (car func))
593 ,(compile-lambda (cadr func)
594 `((block ,(car func) ,@(cddr func)))))))
596 ,(convert-block body t))))
599 (defvar *compiling-file* nil)
600 (define-compilation eval-when-compile (&rest body)
603 (eval (cons 'progn body))
605 (convert `(progn ,@body))))
607 (defmacro define-transformation (name args form)
608 `(define-compilation ,name ,args
611 (define-compilation progn (&rest body)
612 (if (null (cdr body))
613 (convert (car body) *multiple-value-p*)
615 ,@(append (mapcar #'convert (butlast body))
616 (list (convert (car (last body)) t))))))
618 (define-compilation macrolet (definitions &rest body)
619 (let ((*environment* (copy-lexenv *environment*)))
620 (dolist (def definitions)
621 (destructuring-bind (name lambda-list &body body) def
622 (let ((binding (make-binding :name name :type 'macro :value
623 (let ((g!form (gensym)))
625 (destructuring-bind ,lambda-list ,g!form
627 (push-to-lexenv binding *environment* 'function))))
628 (convert `(progn ,@body) *multiple-value-p*)))
631 (defun special-variable-p (x)
632 (and (claimp x 'variable 'special) t))
634 ;;; Wrap CODE to restore the symbol values of the dynamic
635 ;;; bindings. BINDINGS is a list of pairs of the form
636 ;;; (SYMBOL . PLACE), where PLACE is a Javascript variable
637 ;;; name to initialize the symbol value and where to stored
639 (defun let-binding-wrapper (bindings body)
640 (when (null bindings)
641 (return-from let-binding-wrapper body))
646 (let ((s (convert `',(car b))))
647 (collect `(= tmp (get ,s "value")))
648 (collect `(= (get ,s "value") ,(cdr b)))
649 (collect `(= ,(cdr b) tmp)))))
654 (let ((s (convert `(quote ,(car b)))))
655 (collect `(= (get ,s "value") ,(cdr b)))))))))
657 (define-compilation let (bindings &rest body)
658 (let* ((bindings (mapcar #'ensure-list bindings))
659 (variables (mapcar #'first bindings))
660 (cvalues (mapcar #'convert (mapcar #'second bindings)))
661 (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
663 `(call (function ,(mapcar (lambda (x)
664 (if (special-variable-p x)
665 (let ((v (gvarname x)))
666 (push (cons x v) dynamic-bindings)
668 (translate-variable x)))
670 ,(let ((body (convert-block body t t)))
671 `,(let-binding-wrapper dynamic-bindings body)))
675 ;;; Return the code to initialize BINDING, and push it extending the
676 ;;; current lexical environment if the variable is not special.
677 (defun let*-initialize-value (binding)
678 (let ((var (first binding))
679 (value (second binding)))
680 (if (special-variable-p var)
681 (convert `(setq ,var ,value))
682 (let* ((v (gvarname var))
683 (b (make-binding :name var :type 'variable :value v)))
684 (prog1 `(var (,v ,(convert value)))
685 (push-to-lexenv b *environment* 'variable))))))
687 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
688 ;;; DOES NOT generate code to initialize the value of the symbols,
689 ;;; unlike let-binding-wrapper.
690 (defun let*-binding-wrapper (symbols body)
692 (return-from let*-binding-wrapper body))
693 (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
694 (remove-if-not #'special-variable-p symbols))))
697 ,@(mapcar (lambda (b)
698 (let ((s (convert `(quote ,(car b)))))
699 `(var (,(cdr b) (get ,s "value")))))
703 ,@(mapcar (lambda (b)
704 (let ((s (convert `(quote ,(car b)))))
705 `(= (get ,s "value") ,(cdr b))))
708 (define-compilation let* (bindings &rest body)
709 (let ((bindings (mapcar #'ensure-list bindings))
710 (*environment* (copy-lexenv *environment*)))
711 (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
713 ,@(mapcar #'let*-initialize-value bindings)
714 ,(convert-block body t t))))
715 `(selfcall ,(let*-binding-wrapper specials body)))))
718 (define-compilation block (name &rest body)
719 ;; We use Javascript exceptions to implement non local control
720 ;; transfer. Exceptions has dynamic scoping, so we use a uniquely
721 ;; generated object to identify the block. The instance of a empty
722 ;; array is used to distinguish between nested dynamic Javascript
723 ;; exceptions. See https://github.com/davazp/jscl/issues/64 for
725 (let* ((idvar (gvarname name))
726 (b (make-binding :name name :type 'block :value idvar)))
727 (when *multiple-value-p*
728 (push 'multiple-value (binding-declarations b)))
729 (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
730 (cbody (convert-block body t)))
731 (if (member 'used (binding-declarations b))
737 (if (and (== (get cf "type") "block")
738 (== (get cf "id") ,idvar))
739 ,(if *multiple-value-p*
740 `(return (call (get |values| "apply") this (call |forcemv| (get cf "values"))))
741 `(return (get cf "values")))
743 ;; TODO: is selfcall necessary here?
744 `(selfcall ,cbody)))))
746 (define-compilation return-from (name &optional value)
747 (let* ((b (lookup-in-lexenv name *environment* 'block))
748 (multiple-value-p (member 'multiple-value (binding-declarations b))))
750 (error "Return from unknown block `~S'." (symbol-name name)))
751 (push 'used (binding-declarations b))
752 ;; The binding value is the name of a variable, whose value is the
753 ;; unique identifier of the block as exception. We can't use the
754 ;; variable name itself, because it could not to be unique, so we
755 ;; capture it in a closure.
757 ,(when multiple-value-p `(var (|values| |mv|)))
761 "id" ,(binding-value b)
762 "values" ,(convert value multiple-value-p)
763 "message" ,(concat "Return from unknown block '" (symbol-name name) "'."))))))
765 (define-compilation catch (id &rest body)
767 (var (|id| ,(convert id)))
769 ,(convert-block body t))
771 (if (and (== (get |cf| "type") "catch")
772 (== (get |cf| "id") |id|))
773 ,(if *multiple-value-p*
774 `(return (call (get |values| "apply")
776 (call |forcemv| (get |cf| "values"))))
777 `(return (call (get |pv| "apply")
779 (call |forcemv| (get |cf| "values")))))
782 (define-compilation throw (id value)
784 (var (|values| |mv|))
788 |values| ,(convert value t)
789 |message| "Throw uncatched."))))
792 (or (integerp x) (symbolp x)))
794 (defun declare-tagbody-tags (tbidx body)
795 (let* ((go-tag-counter 0)
797 (mapcar (lambda (label)
798 (let ((tagidx (incf go-tag-counter)))
799 (make-binding :name label :type 'gotag :value (list tbidx tagidx))))
800 (remove-if-not #'go-tag-p body))))
801 (extend-lexenv bindings *environment* 'gotag)))
803 (define-compilation tagbody (&rest body)
804 ;; Ignore the tagbody if it does not contain any go-tag. We do this
805 ;; because 1) it is easy and 2) many built-in forms expand to a
806 ;; implicit tagbody, so we save some space.
807 (unless (some #'go-tag-p body)
808 (return-from tagbody (convert `(progn ,@body nil))))
809 ;; The translation assumes the first form in BODY is a label
810 (unless (go-tag-p (car body))
811 (push (gensym "START") body))
812 ;; Tagbody compilation
813 (let ((branch (gvarname 'branch))
814 (tbidx (gvarname 'tbidx)))
815 (let ((*environment* (declare-tagbody-tags tbidx body))
817 (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
818 (setq initag (second (binding-value b))))
820 ;; TAGBODY branch to take
821 (var (,branch ,initag))
828 (collect `(case ,initag))
829 (dolist (form (cdr body))
831 (let ((b (lookup-in-lexenv form *environment* 'gotag)))
832 (collect `(case ,(second (binding-value b)))))
833 (collect (convert form)))))
837 (if (and (== (get jump "type") "tagbody")
838 (== (get jump "id") ,tbidx))
839 (= ,branch (get jump "label"))
841 (return ,(convert nil))))))
843 (define-compilation go (label)
844 (let ((b (lookup-in-lexenv label *environment* 'gotag))
846 ((symbolp label) (symbol-name label))
847 ((integerp label) (integer-to-string label)))))
849 (error "Unknown tag `~S'" label))
854 "id" ,(first (binding-value b))
855 "label" ,(second (binding-value b))
856 "message" ,(concat "Attempt to GO to non-existing tag " n))))))
858 (define-compilation unwind-protect (form &rest clean-up)
860 (var (|ret| ,(convert nil)))
862 (= |ret| ,(convert form)))
864 ,(convert-block clean-up))
867 (define-compilation multiple-value-call (func-form &rest forms)
869 (var (func ,(convert func-form)))
870 (var (args ,(vector (if *multiple-value-p* '|values| '|pv|) 0)))
873 (var (|values| |mv|))
878 (collect `(= vs ,(convert form t)))
879 (collect `(if (and (=== (typeof vs) "object")
880 (in "multiple-value" vs))
881 (= args (call (get args "concat") vs))
882 (call (get args "push") vs))))))
883 (= (property args 1) (- (property args "length") 2))
884 (return (call (get func "apply") |window| args))))))
886 (define-compilation multiple-value-prog1 (first-form &rest forms)
888 (var (args ,(convert first-form *multiple-value-p*)))
889 ;; TODO: Interleave is temporal
890 (progn ,@(mapcar #'convert forms))
893 (define-transformation backquote (form)
894 (bq-completely-process form))
899 (defvar *builtins* nil)
901 (defmacro define-raw-builtin (name args &body body)
902 ;; Creates a new primitive function `name' with parameters args and
903 ;; @body. The body can access to the local environment through the
904 ;; variable *ENVIRONMENT*.
905 `(push (list ',name (lambda ,args (block ,name ,@body)))
908 (defmacro define-builtin (name args &body body)
909 `(define-raw-builtin ,name ,args
910 (let ,(mapcar (lambda (arg) `(,arg (convert ,arg))) args)
913 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
914 ;;; a variable which holds a list of forms. It will compile them and
915 ;;; store the result in some Javascript variables. BODY is evaluated
916 ;;; with ARGS bound to the list of these variables to generate the
917 ;;; code which performs the transformation on these variables.
918 (defun variable-arity-call (args function)
920 (error "ARGS must be a non-empty list"))
925 (if (or (floatp x) (numberp x))
927 (let ((v (make-symbol (concat "x" (integer-to-string (incf counter))))))
929 (push `(var (,v ,(convert x)))
931 (push `(if (!= (typeof ,v) "number")
932 (throw "Not a number!"))
935 (progn ,@(reverse prelude))
936 ,(funcall function (reverse fargs)))))
939 (defmacro variable-arity (args &body body)
940 (unless (symbolp args)
941 (error "`~S' is not a symbol." args))
942 `(variable-arity-call ,args (lambda (,args) `(return ,,@body))))
944 (define-raw-builtin + (&rest numbers)
947 (variable-arity numbers
950 (define-raw-builtin - (x &rest others)
951 (let ((args (cons x others)))
952 (variable-arity args `(- ,@args))))
954 (define-raw-builtin * (&rest numbers)
957 (variable-arity numbers `(* ,@numbers))))
959 (define-raw-builtin / (x &rest others)
960 (let ((args (cons x others)))
964 (reduce (lambda (x y) `(/ ,x ,y))
967 (define-builtin mod (x y)
971 (defun comparison-conjuntion (vars op)
976 `(,op ,(car vars) ,(cadr vars)))
978 `(and (,op ,(car vars) ,(cadr vars))
979 ,(comparison-conjuntion (cdr vars) op)))))
981 (defmacro define-builtin-comparison (op sym)
982 `(define-raw-builtin ,op (x &rest args)
983 (let ((args (cons x args)))
985 `(bool ,(comparison-conjuntion args ',sym))))))
987 (define-builtin-comparison > >)
988 (define-builtin-comparison < <)
989 (define-builtin-comparison >= >=)
990 (define-builtin-comparison <= <=)
991 (define-builtin-comparison = ==)
992 (define-builtin-comparison /= !=)
994 (define-builtin numberp (x)
995 `(bool (== (typeof ,x) "number")))
997 (define-builtin floor (x)
998 `(call (get |Math| |floor|) ,x))
1000 (define-builtin expt (x y)
1001 `(call (get |Math| |pow|) ,x ,y))
1003 (define-builtin float-to-string (x)
1004 `(call |make_lisp_string| (call (get ,x |toString|))))
1006 (define-builtin cons (x y)
1007 `(object "car" ,x "cdr" ,y))
1009 (define-builtin consp (x)
1012 (return (bool (and (== (typeof tmp) "object")
1015 (define-builtin car (x)
1018 (return (if (=== tmp ,(convert nil))
1022 (define-builtin cdr (x)
1025 (return (if (=== tmp ,(convert nil))
1029 (define-builtin rplaca (x new)
1030 `(= (get ,x "car") ,new))
1032 (define-builtin rplacd (x new)
1033 `(= (get ,x "cdr") ,new))
1035 (define-builtin symbolp (x)
1036 `(bool (instanceof ,x |Symbol|)))
1038 (define-builtin make-symbol (name)
1039 `(new (call |Symbol| ,name)))
1041 (define-builtin symbol-name (x)
1044 (define-builtin set (symbol value)
1045 `(= (get ,symbol "value") ,value))
1047 (define-builtin fset (symbol value)
1048 `(= (get ,symbol "fvalue") ,value))
1050 (define-builtin boundp (x)
1051 `(bool (!== (get ,x "value") undefined)))
1053 (define-builtin fboundp (x)
1054 `(bool (!== (get ,x "fvalue") undefined)))
1056 (define-builtin symbol-value (x)
1059 (value (get symbol "value")))
1060 (if (=== value undefined)
1061 (throw (+ "Variable `" (call |xstring| (get symbol "name")) "' is unbound.")))
1064 (define-builtin symbol-function (x)
1067 (func (get symbol "fvalue")))
1068 (if (=== func undefined)
1069 (throw (+ "Function `" (call |xstring| (get symbol "name")) "' is undefined.")))
1072 (define-builtin symbol-plist (x)
1073 `(or (get ,x "plist") ,(convert nil)))
1075 (define-builtin lambda-code (x)
1076 `(call |make_lisp_string| (call (get ,x "toString"))))
1078 (define-builtin eq (x y)
1079 `(bool (=== ,x ,y)))
1081 (define-builtin char-code (x)
1082 `(call |char_to_codepoint| ,x))
1084 (define-builtin code-char (x)
1085 `(call |char_from_codepoint| ,x))
1087 (define-builtin characterp (x)
1091 (and (== (typeof x) "string")
1092 (or (== (get x "length") 1)
1093 (== (get x "length") 2)))))))
1095 (define-builtin char-upcase (x)
1096 `(call |safe_char_upcase| ,x))
1098 (define-builtin char-downcase (x)
1099 `(call |safe_char_downcase| ,x))
1101 (define-builtin stringp (x)
1105 (and (and (===(typeof x) "object")
1107 (== (get x "stringp") 1))))))
1109 (define-raw-builtin funcall (func &rest args)
1111 (var (f ,(convert func)))
1112 (return (call (if (=== (typeof f) "function")
1115 ,@(list* (if *multiple-value-p* '|values| '|pv|)
1117 (mapcar #'convert args))))))
1119 (define-raw-builtin apply (func &rest args)
1122 (let ((args (butlast args))
1123 (last (car (last args))))
1125 (var (f ,(convert func)))
1126 (var (args ,(list-to-vector
1127 (list* (if *multiple-value-p* '|values| '|pv|)
1129 (mapcar #'convert args)))))
1130 (var (tail ,(convert last)))
1131 (while (!= tail ,(convert nil))
1132 (call (get args "push") (get tail "car"))
1133 (post++ (property args 1))
1134 (= tail (get tail "cdr")))
1135 (return (call (get (if (=== (typeof f) "function")
1142 (define-builtin js-eval (string)
1143 (if *multiple-value-p*
1145 (var (v (call |globalEval| (call |xstring| ,string))))
1146 (return (call (get |values| "apply") this (call |forcemv| v))))
1147 `(call |globalEval| (call |xstring| ,string))))
1149 (define-builtin %throw (string)
1150 `(selfcall (throw ,string)))
1152 (define-builtin functionp (x)
1153 `(bool (=== (typeof ,x) "function")))
1155 (define-builtin %write-string (x)
1156 `(call (get |lisp| "write") ,x))
1158 (define-builtin /debug (x)
1159 `(call (get |console| "log") (call |xstring| ,x)))
1162 ;;; Storage vectors. They are used to implement arrays and (in the
1163 ;;; future) structures.
1165 (define-builtin storage-vector-p (x)
1168 (return (bool (and (=== (typeof x) "object") (in "length" x))))))
1170 (define-builtin make-storage-vector (n)
1173 (= (get r "length") ,n)
1176 (define-builtin storage-vector-size (x)
1179 (define-builtin resize-storage-vector (vector new-size)
1180 `(= (get ,vector "length") ,new-size))
1182 (define-builtin storage-vector-ref (vector n)
1184 (var (x (property ,vector ,n)))
1185 (if (=== x undefined) (throw "Out of range."))
1188 (define-builtin storage-vector-set (vector n value)
1192 (if (or (< i 0) (>= i (get x "length")))
1193 (throw "Out of range."))
1194 (return (= (property x i) ,value))))
1196 (define-builtin concatenate-storage-vector (sv1 sv2)
1199 (var (r (call (get sv1 "concat") ,sv2)))
1200 (= (get r "type") (get sv1 "type"))
1201 (= (get r "stringp") (get sv1 "stringp"))
1204 (define-builtin get-internal-real-time ()
1205 `(call (get (new (call |Date|)) "getTime")))
1207 (define-builtin values-array (array)
1208 (if *multiple-value-p*
1209 `(call (get |values| "apply") this ,array)
1210 `(call (get |pv| "apply") this ,array)))
1212 (define-raw-builtin values (&rest args)
1213 (if *multiple-value-p*
1214 `(call |values| ,@(mapcar #'convert args))
1215 `(call |pv| ,@(mapcar #'convert args))))
1219 (define-builtin new ()
1222 (define-raw-builtin oget* (object key &rest keys)
1225 (var (tmp (property ,(convert object) (call |xstring| ,(convert key)))))
1226 ,@(mapcar (lambda (key)
1228 (if (=== tmp undefined) (return ,(convert nil)))
1229 (= tmp (property tmp (call |xstring| ,(convert key))))))
1231 (return (if (=== tmp undefined) ,(convert nil) tmp))))
1233 (define-raw-builtin oset* (value object key &rest keys)
1234 (let ((keys (cons key keys)))
1237 (var (obj ,(convert object)))
1238 ,@(mapcar (lambda (key)
1240 (= obj (property obj (call |xstring| ,(convert key))))
1241 (if (=== object undefined)
1242 (throw "Impossible to set object property."))))
1245 (= (property obj (call |xstring| ,(convert (car (last keys)))))
1247 (return (if (=== tmp undefined)
1251 (define-raw-builtin oget (object key &rest keys)
1252 `(call |js_to_lisp| ,(convert `(oget* ,object ,key ,@keys))))
1254 (define-raw-builtin oset (value object key &rest keys)
1255 (convert `(oset* (lisp-to-js ,value) ,object ,key ,@keys)))
1257 (define-builtin objectp (x)
1258 `(bool (=== (typeof ,x) "object")))
1260 (define-builtin lisp-to-js (x) `(call |lisp_to_js| ,x))
1261 (define-builtin js-to-lisp (x) `(call |js_to_lisp| ,x))
1264 (define-builtin in (key object)
1265 `(bool (in (call |xstring| ,key) ,object)))
1267 (define-builtin map-for-in (function object)
1270 (g (if (=== (typeof f) "function") f (get f "fvalue")))
1273 (call g ,(if *multiple-value-p* '|values| '|pv|) 1 (get o "key")))
1274 (return ,(convert nil))))
1276 (define-compilation %js-vref (var)
1277 `(call |js_to_lisp| ,(make-symbol var)))
1279 (define-compilation %js-vset (var val)
1280 `(= ,(make-symbol var) (call |lisp_to_js| ,(convert val))))
1282 (define-setf-expander %js-vref (var)
1283 (let ((new-value (gensym)))
1284 (unless (stringp var)
1285 (error "`~S' is not a string." var))
1289 `(%js-vset ,var ,new-value)
1294 (defvar *macroexpander-cache*
1295 (make-hash-table :test #'eq))
1297 (defun !macro-function (symbol)
1298 (unless (symbolp symbol)
1299 (error "`~S' is not a symbol." symbol))
1300 (let ((b (lookup-in-lexenv symbol *environment* 'function)))
1301 (if (and b (eq (binding-type b) 'macro))
1302 (let ((expander (binding-value b)))
1305 ((gethash b *macroexpander-cache*)
1306 (setq expander (gethash b *macroexpander-cache*)))
1308 (let ((compiled (eval expander)))
1309 ;; The list representation are useful while
1310 ;; bootstrapping, as we can dump the definition of the
1311 ;; macros easily, but they are slow because we have to
1312 ;; evaluate them and compile them now and again. So, let
1313 ;; us replace the list representation version of the
1314 ;; function with the compiled one.
1316 #+jscl (setf (binding-value b) compiled)
1317 #-jscl (setf (gethash b *macroexpander-cache*) compiled)
1318 (setq expander compiled))))
1322 (defun !macroexpand-1 (form)
1325 (let ((b (lookup-in-lexenv form *environment* 'variable)))
1326 (if (and b (eq (binding-type b) 'macro))
1327 (values (binding-value b) t)
1328 (values form nil))))
1329 ((and (consp form) (symbolp (car form)))
1330 (let ((macrofun (!macro-function (car form))))
1332 (values (funcall macrofun (cdr form)) t)
1333 (values form nil))))
1335 (values form nil))))
1337 (defun compile-funcall (function args)
1338 (let* ((arglist (list* (if *multiple-value-p* '|values| '|pv|)
1340 (mapcar #'convert args))))
1341 (unless (or (symbolp function)
1342 (and (consp function)
1343 (member (car function) '(lambda oget))))
1344 (error "Bad function designator `~S'" function))
1346 ((translate-function function)
1347 `(call ,(translate-function function) ,@arglist))
1348 ((and (symbolp function)
1349 #+jscl (eq (symbol-package function) (find-package "COMMON-LISP"))
1351 `(call (get ,(convert `',function) "fvalue") ,@arglist))
1352 #+jscl((symbolp function)
1353 `(call ,(convert `#',function) ,@arglist))
1354 ((and (consp function) (eq (car function) 'lambda))
1355 `(call ,(convert `#',function) ,@arglist))
1356 ((and (consp function) (eq (car function) 'oget))
1357 `(call ,(convert function) ,@arglist))
1359 (error "Bad function descriptor")))))
1361 (defun convert-block (sexps &optional return-last-p decls-allowed-p)
1362 (multiple-value-bind (sexps decls)
1363 (parse-body sexps :declarations decls-allowed-p)
1364 (declare (ignore decls))
1367 ,@(mapcar #'convert (butlast sexps))
1368 (return ,(convert (car (last sexps)) *multiple-value-p*)))
1369 `(progn ,@(mapcar #'convert sexps)))))
1371 (defun convert* (sexp &optional multiple-value-p)
1372 (multiple-value-bind (sexp expandedp) (!macroexpand-1 sexp)
1374 (return-from convert* (convert sexp multiple-value-p)))
1375 ;; The expression has been macroexpanded. Now compile it!
1376 (let ((*multiple-value-p* multiple-value-p))
1379 (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1381 ((and b (not (member 'special (binding-declarations b))))
1383 ((or (keywordp sexp)
1384 (and b (member 'constant (binding-declarations b))))
1385 `(get ,(convert `',sexp) "value"))
1387 (convert `(symbol-value ',sexp))))))
1388 ((or (integerp sexp) (floatp sexp) (characterp sexp) (stringp sexp) (arrayp sexp))
1391 (let ((name (car sexp))
1395 ((assoc name *compilations*)
1396 (let ((comp (second (assoc name *compilations*))))
1398 ;; Built-in functions
1399 ((and (assoc name *builtins*)
1400 (not (claimp name 'function 'notinline)))
1401 (let ((comp (second (assoc name *builtins*))))
1404 (compile-funcall name args)))))
1406 (error "How should I compile `~S'?" sexp))))))
1408 (defun convert (sexp &optional multiple-value-p)
1409 (convert* sexp multiple-value-p))
1412 (defvar *compile-print-toplevels* nil)
1414 (defun truncate-string (string &optional (width 60))
1415 (let ((n (or (position #\newline string)
1416 (min width (length string)))))
1417 (subseq string 0 n)))
1419 (defun convert-toplevel (sexp &optional multiple-value-p)
1420 (let ((*toplevel-compilations* nil))
1422 ;; Non-empty toplevel progn
1424 (eq (car sexp) 'progn)
1427 ,@(mapcar (lambda (s) (convert-toplevel s t))
1430 (when *compile-print-toplevels*
1431 (let ((form-string (prin1-to-string sexp)))
1432 (format t "Compiling ~a..." (truncate-string form-string))))
1433 (let ((code (convert sexp multiple-value-p)))
1435 ,@(get-toplevel-compilations)
1438 (defun compile-toplevel (sexp &optional multiple-value-p)
1439 (with-output-to-string (*standard-output*)
1440 (js (convert-toplevel sexp multiple-value-p))))