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 ;;; Translate the Lisp code to Javascript. It will compile the special
24 ;;; forms. Some primitive functions are compiled as special forms
25 ;;; too. The respective real functions are defined in the target (see
26 ;;; the beginning of this file) as well as some primitive functions.
28 (defun interleave (list element &optional after-last-p)
32 (dolist (x (cdr list))
38 (defun code (&rest args)
39 (mapconcat (lambda (arg)
42 ((integerp arg) (integer-to-string arg))
43 ((floatp arg) (float-to-string arg))
46 (with-output-to-string (*standard-output*)
50 ;;; Wrap X with a Javascript code to convert the result from
51 ;;; Javascript generalized booleans to T or NIL.
53 `(if ,x ,(ls-compile t) ,(ls-compile nil)))
55 ;;; Concatenate the arguments and wrap them with a self-calling
56 ;;; Javascript anonymous function. It is used to make some Javascript
57 ;;; statements valid expressions and provide a private scope as well.
58 ;;; It could be defined as function, but we could do some
59 ;;; preprocessing in the future.
60 (defmacro js!selfcall (&body body)
61 ``(call (function nil (code ,,@body))))
63 (defmacro js!selfcall* (&body body)
64 ``(call (function nil ,,@body)))
67 ;;; Like CODE, but prefix each line with four spaces. Two versions
68 ;;; of this function are available, because the Ecmalisp version is
69 ;;; very slow and bootstraping was annoying.
71 ;;; A Form can return a multiple values object calling VALUES, like
72 ;;; values(arg1, arg2, ...). It will work in any context, as well as
73 ;;; returning an individual object. However, if the special variable
74 ;;; `*multiple-value-p*' is NIL, is granted that only the primary
75 ;;; value will be used, so we can optimize to avoid the VALUES
77 (defvar *multiple-value-p* nil)
93 (defun lookup-in-lexenv (name lexenv namespace)
94 (find name (ecase namespace
95 (variable (lexenv-variable lexenv))
96 (function (lexenv-function lexenv))
97 (block (lexenv-block lexenv))
98 (gotag (lexenv-gotag lexenv)))
101 (defun push-to-lexenv (binding lexenv namespace)
103 (variable (push binding (lexenv-variable lexenv)))
104 (function (push binding (lexenv-function lexenv)))
105 (block (push binding (lexenv-block lexenv)))
106 (gotag (push binding (lexenv-gotag lexenv)))))
108 (defun extend-lexenv (bindings lexenv namespace)
109 (let ((env (copy-lexenv lexenv)))
110 (dolist (binding (reverse bindings) env)
111 (push-to-lexenv binding env namespace))))
114 (defvar *environment* (make-lexenv))
116 (defvar *variable-counter* 0)
118 (defun gvarname (symbol)
119 (declare (ignore symbol))
120 (incf *variable-counter*)
121 (concat "v" (integer-to-string *variable-counter*)))
123 (defun translate-variable (symbol)
124 (awhen (lookup-in-lexenv symbol *environment* 'variable)
127 (defun extend-local-env (args)
128 (let ((new (copy-lexenv *environment*)))
129 (dolist (symbol args new)
130 (let ((b (make-binding :name symbol :type 'variable :value (gvarname symbol))))
131 (push-to-lexenv b new 'variable)))))
133 ;;; Toplevel compilations
134 (defvar *toplevel-compilations* nil)
136 (defun toplevel-compilation (string)
137 (push string *toplevel-compilations*))
139 (defun get-toplevel-compilations ()
140 (reverse *toplevel-compilations*))
142 (defun %compile-defmacro (name lambda)
143 (toplevel-compilation (ls-compile `',name))
144 (let ((binding (make-binding :name name :type 'macro :value lambda)))
145 (push-to-lexenv binding *environment* 'function))
148 (defun global-binding (name type namespace)
149 (or (lookup-in-lexenv name *environment* namespace)
150 (let ((b (make-binding :name name :type type :value nil)))
151 (push-to-lexenv b *environment* namespace)
154 (defun claimp (symbol namespace claim)
155 (let ((b (lookup-in-lexenv symbol *environment* namespace)))
156 (and b (member claim (binding-declarations b)))))
158 (defun !proclaim (decl)
161 (dolist (name (cdr decl))
162 (let ((b (global-binding name 'variable 'variable)))
163 (push 'special (binding-declarations b)))))
165 (dolist (name (cdr decl))
166 (let ((b (global-binding name 'function 'function)))
167 (push 'notinline (binding-declarations b)))))
169 (dolist (name (cdr decl))
170 (let ((b (global-binding name 'variable 'variable)))
171 (push 'constant (binding-declarations b)))))))
174 (fset 'proclaim #'!proclaim)
176 (defun %define-symbol-macro (name expansion)
177 (let ((b (make-binding :name name :type 'macro :value expansion)))
178 (push-to-lexenv b *environment* 'variable)
182 (defmacro define-symbol-macro (name expansion)
183 `(%define-symbol-macro ',name ',expansion))
188 (defvar *compilations* nil)
190 (defmacro define-compilation (name args &body body)
191 ;; Creates a new primitive `name' with parameters args and
192 ;; @body. The body can access to the local environment through the
193 ;; variable *ENVIRONMENT*.
194 `(push (list ',name (lambda ,args (block ,name ,@body)))
197 (define-compilation if (condition true &optional false)
198 `(if (!== ,(ls-compile condition) ,(ls-compile nil))
199 ,(ls-compile true *multiple-value-p*)
200 ,(ls-compile false *multiple-value-p*)))
202 (defvar *ll-keywords* '(&optional &rest &key))
204 (defun list-until-keyword (list)
205 (if (or (null list) (member (car list) *ll-keywords*))
207 (cons (car list) (list-until-keyword (cdr list)))))
209 (defun ll-section (keyword ll)
210 (list-until-keyword (cdr (member keyword ll))))
212 (defun ll-required-arguments (ll)
213 (list-until-keyword ll))
215 (defun ll-optional-arguments-canonical (ll)
216 (mapcar #'ensure-list (ll-section '&optional ll)))
218 (defun ll-optional-arguments (ll)
219 (mapcar #'car (ll-optional-arguments-canonical ll)))
221 (defun ll-rest-argument (ll)
222 (let ((rest (ll-section '&rest ll)))
224 (error "Bad lambda-list `~S'." ll))
227 (defun ll-keyword-arguments-canonical (ll)
228 (flet ((canonicalize (keyarg)
229 ;; Build a canonical keyword argument descriptor, filling
230 ;; the optional fields. The result is a list of the form
231 ;; ((keyword-name var) init-form).
232 (let ((arg (ensure-list keyarg)))
233 (cons (if (listp (car arg))
235 (list (intern (symbol-name (car arg)) "KEYWORD") (car arg)))
237 (mapcar #'canonicalize (ll-section '&key ll))))
239 (defun ll-keyword-arguments (ll)
240 (mapcar (lambda (keyarg) (second (first keyarg)))
241 (ll-keyword-arguments-canonical ll)))
243 (defun ll-svars (lambda-list)
246 (ll-keyword-arguments-canonical lambda-list)
247 (ll-optional-arguments-canonical lambda-list))))
248 (remove nil (mapcar #'third args))))
250 (defun lambda-name/docstring-wrapper (name docstring code)
251 (if (or name docstring)
254 (when name `(= (get func "fname") ,name))
255 (when docstring `(= (get func "docstring") ,docstring))
259 (defun lambda-check-argument-count
260 (n-required-arguments n-optional-arguments rest-p)
261 ;; Note: Remember that we assume that the number of arguments of a
262 ;; call is at least 1 (the values argument).
263 (let ((min n-required-arguments)
264 (max (if rest-p 'n/a (+ n-required-arguments n-optional-arguments))))
266 ;; Special case: a positive exact number of arguments.
267 (when (and (< 0 min) (eql min max))
268 (return `(code "checkArgs(nargs, " ,min ");")))
272 `(code "checkArgsAtLeast(nargs, " ,min ");"))
274 `(code "checkArgsAtMost(nargs, " ,max ");"))))))
276 (defun compile-lambda-optional (ll)
277 (let* ((optional-arguments (ll-optional-arguments-canonical ll))
278 (n-required-arguments (length (ll-required-arguments ll)))
279 (n-optional-arguments (length optional-arguments)))
280 (when optional-arguments
281 `(code "switch(nargs){"
285 (while (< idx n-optional-arguments)
286 (let ((arg (nth idx optional-arguments)))
287 (push `(code "case " ,(+ idx n-required-arguments) ":"
288 (code ,(translate-variable (car arg))
290 ,(ls-compile (cadr arg)) ";")
292 `(code ,(translate-variable (third arg))
298 (push `(code "default: break;") cases)
299 `(code ,@(reverse cases))))
302 (defun compile-lambda-rest (ll)
303 (let ((n-required-arguments (length (ll-required-arguments ll)))
304 (n-optional-arguments (length (ll-optional-arguments ll)))
305 (rest-argument (ll-rest-argument ll)))
307 (let ((js!rest (translate-variable rest-argument)))
308 `(code "var " ,js!rest "= " ,(ls-compile nil) ";"
309 "for (var i = nargs-1; i>=" ,(+ n-required-arguments n-optional-arguments)
311 (code ,js!rest " = {car: arguments[i+2], cdr: " ,js!rest "};"))))))
313 (defun compile-lambda-parse-keywords (ll)
314 (let ((n-required-arguments
315 (length (ll-required-arguments ll)))
316 (n-optional-arguments
317 (length (ll-optional-arguments ll)))
319 (ll-keyword-arguments-canonical ll)))
322 ,@(mapcar (lambda (arg)
323 (let ((var (second (car arg))))
324 `(code "var " ,(translate-variable var) "; "
326 `(code "var " ,(translate-variable (third arg))
327 " = " ,(ls-compile nil)
331 ,(flet ((parse-keyword (keyarg)
332 ;; ((keyword-name var) init-form)
333 `(code "for (i=" ,(+ n-required-arguments n-optional-arguments)
335 "if (arguments[i+2] === " ,(ls-compile (caar keyarg)) "){"
336 ,(translate-variable (cadr (car keyarg)))
338 ,(let ((svar (third keyarg)))
340 `(code ,(translate-variable svar) " = " ,(ls-compile t) ";" )))
346 ,(translate-variable (cadr (car keyarg)))
348 ,(ls-compile (cadr keyarg))
351 (when keyword-arguments
353 ,@(mapcar #'parse-keyword keyword-arguments))))
354 ;; Check for unknown keywords
355 ,(when keyword-arguments
356 `(code "var start = " ,(+ n-required-arguments n-optional-arguments) ";"
357 "if ((nargs - start) % 2 == 1){"
358 "throw 'Odd number of keyword arguments';"
360 "for (i = start; i<nargs; i+=2){"
362 ,@(interleave (mapcar (lambda (x)
363 `(code "arguments[i+2] !== " ,(ls-compile (caar x))))
367 "throw 'Unknown keyword argument ' + xstring(arguments[i+2].name);"
370 (defun parse-lambda-list (ll)
371 (values (ll-required-arguments ll)
372 (ll-optional-arguments ll)
373 (ll-keyword-arguments ll)
374 (ll-rest-argument ll)))
376 ;;; Process BODY for declarations and/or docstrings. Return as
377 ;;; multiple values the BODY without docstrings or declarations, the
378 ;;; list of declaration forms and the docstring.
379 (defun parse-body (body &key declarations docstring)
380 (let ((value-declarations)
382 ;; Parse declarations
384 (do* ((rest body (cdr rest))
385 (form (car rest) (car rest)))
386 ((or (atom form) (not (eq (car form) 'declare)))
388 (push form value-declarations)))
392 (not (null (cdr body))))
393 (setq value-docstring (car body))
394 (setq body (cdr body)))
395 (values body value-declarations value-docstring)))
397 ;;; Compile a lambda function with lambda list LL and body BODY. If
398 ;;; NAME is given, it should be a constant string and it will become
399 ;;; the name of the function. If BLOCK is non-NIL, a named block is
400 ;;; created around the body. NOTE: No block (even anonymous) is
401 ;;; created if BLOCk is NIL.
402 (defun compile-lambda (ll body &key name block)
403 (multiple-value-bind (required-arguments
407 (parse-lambda-list ll)
408 (multiple-value-bind (body decls documentation)
409 (parse-body body :declarations t :docstring t)
410 (declare (ignore decls))
411 (let ((n-required-arguments (length required-arguments))
412 (n-optional-arguments (length optional-arguments))
413 (*environment* (extend-local-env
414 (append (ensure-list rest-argument)
419 (lambda-name/docstring-wrapper name documentation
422 ,(join (list* "values"
424 (mapcar #'translate-variable
425 (append required-arguments optional-arguments)))
428 ;; Check number of arguments
429 ,(lambda-check-argument-count n-required-arguments
431 (or rest-argument keyword-arguments))
432 ,(compile-lambda-optional ll)
433 ,(compile-lambda-rest ll)
434 ,(compile-lambda-parse-keywords ll)
435 ,(let ((*multiple-value-p* t))
437 (ls-compile-block `((block ,block ,@body)) t)
438 (ls-compile-block body t)))
442 (defun setq-pair (var val)
443 (let ((b (lookup-in-lexenv var *environment* 'variable)))
446 (eq (binding-type b) 'variable)
447 (not (member 'special (binding-declarations b)))
448 (not (member 'constant (binding-declarations b))))
449 ;; TODO: Unnecesary make-symbol when codegen migration is
451 `(= ,(make-symbol (binding-value b)) ,(ls-compile val)))
452 ((and b (eq (binding-type b) 'macro))
453 (ls-compile `(setf ,var ,val)))
455 (ls-compile `(set ',var ,val))))))
458 (define-compilation setq (&rest pairs)
461 (return-from setq (ls-compile nil)))
467 (error "Odd pairs in SETQ"))
469 (push `,(setq-pair (car pairs) (cadr pairs)) result)
470 (setq pairs (cddr pairs)))))
471 `(progn ,@(reverse result))))
474 ;;; Compilation of literals an object dumping
476 ;;; BOOTSTRAP MAGIC: We record the macro definitions as lists during
477 ;;; the bootstrap. Once everything is compiled, we want to dump the
478 ;;; whole global environment to the output file to reproduce it in the
479 ;;; run-time. However, the environment must contain expander functions
480 ;;; rather than lists. We do not know how to dump function objects
481 ;;; itself, so we mark the list definitions with this object and the
482 ;;; compiler will be called when this object has to be dumped.
483 ;;; Backquote/unquote does a similar magic, but this use is exclusive.
485 ;;; Indeed, perhaps to compile the object other macros need to be
486 ;;; evaluated. For this reason we define a valid macro-function for
488 (defvar *magic-unquote-marker* (gensym "MAGIC-UNQUOTE"))
490 (setf (macro-function *magic-unquote-marker*)
491 (lambda (form &optional environment)
492 (declare (ignore environment))
495 (defvar *literal-table* nil)
496 (defvar *literal-counter* 0)
499 (incf *literal-counter*)
500 (concat "l" (integer-to-string *literal-counter*)))
502 (defun dump-symbol (symbol)
504 (let ((package (symbol-package symbol)))
505 (if (eq package (find-package "KEYWORD"))
506 `(new (call |Symbol| ,(dump-string (symbol-name symbol)) ,(dump-string (package-name package))))
507 `(new (call |Symbol| ,(dump-string (symbol-name symbol))))))
509 (let ((package (symbol-package symbol)))
511 `(new (call |Symbol| ,(dump-string (symbol-name symbol))))
512 (ls-compile `(intern ,(symbol-name symbol) ,(package-name package))))))
514 (defun dump-cons (cons)
515 (let ((head (butlast cons))
518 ,@(mapcar (lambda (x) `(code ,(literal x t))) head)
519 (code ,(literal (car tail) t))
520 (code ,(literal (cdr tail) t)))))
522 (defun dump-array (array)
523 (let ((elements (vector-to-list array)))
524 (list-to-vector (mapcar (lambda (x) `(code ,(literal x)))
527 (defun dump-string (string)
528 `(call |make_lisp_string| ,string))
530 (defun literal (sexp &optional recursive)
532 ((integerp sexp) (integer-to-string sexp))
533 ((floatp sexp) (float-to-string sexp))
534 ((characterp sexp) (js-escape-string (string sexp)))
536 (or (cdr (assoc sexp *literal-table* :test #'eql))
537 (let ((dumped (typecase sexp
538 (symbol (dump-symbol sexp))
539 (string (dump-string sexp))
541 ;; BOOTSTRAP MAGIC: See the root file
542 ;; jscl.lisp and the function
543 ;; `dump-global-environment' for futher
545 (if (eq (car sexp) *magic-unquote-marker*)
546 (ls-compile (second sexp))
548 (array (dump-array sexp)))))
549 (if (and recursive (not (symbolp sexp)))
551 (let ((jsvar (genlit)))
552 (push (cons sexp jsvar) *literal-table*)
553 (toplevel-compilation `(code "var " ,jsvar " = " ,dumped))
554 (when (keywordp sexp)
555 (toplevel-compilation `(code ,jsvar ".value = " ,jsvar)))
559 (define-compilation quote (sexp)
562 (define-compilation %while (pred &rest body)
564 `(while (!== ,(ls-compile pred) ,(ls-compile nil))
566 ; braces. Unnecesary when code
568 ,(ls-compile-block body))
569 `(return ,(ls-compile nil))))
571 (define-compilation function (x)
573 ((and (listp x) (eq (car x) 'lambda))
574 (compile-lambda (cadr x) (cddr x)))
575 ((and (listp x) (eq (car x) 'named-lambda))
576 (destructuring-bind (name ll &rest body) (cdr x)
577 (compile-lambda ll body
578 :name (symbol-name name)
581 (let ((b (lookup-in-lexenv x *environment* 'function)))
584 (ls-compile `(symbol-function ',x)))))))
587 (defun make-function-binding (fname)
588 (make-binding :name fname :type 'function :value (gvarname fname)))
590 (defun compile-function-definition (list)
591 (compile-lambda (car list) (cdr list)))
593 (defun translate-function (name)
594 (let ((b (lookup-in-lexenv name *environment* 'function)))
595 (and b (binding-value b))))
597 (define-compilation flet (definitions &rest body)
598 (let* ((fnames (mapcar #'car definitions))
599 (cfuncs (mapcar (lambda (def)
600 (compile-lambda (cadr def)
605 (extend-lexenv (mapcar #'make-function-binding fnames)
608 `(call (function ,(mapcar #'make-symbol (mapcar #'translate-function fnames))
609 ,(ls-compile-block body t))
612 (define-compilation labels (definitions &rest body)
613 (let* ((fnames (mapcar #'car definitions))
615 (extend-lexenv (mapcar #'make-function-binding fnames)
620 ,@(mapcar (lambda (func)
621 `(var (,(make-symbol (translate-function (car func)))
622 ,(compile-lambda (cadr func)
623 `((block ,(car func) ,@(cddr func)))))))
625 (ls-compile-block body t))))
628 (defvar *compiling-file* nil)
629 (define-compilation eval-when-compile (&rest body)
632 (eval (cons 'progn body))
634 (ls-compile `(progn ,@body))))
636 (defmacro define-transformation (name args form)
637 `(define-compilation ,name ,args
640 (define-compilation progn (&rest body)
641 (if (null (cdr body))
642 (ls-compile (car body) *multiple-value-p*)
644 ,@(append (mapcar #'ls-compile (butlast body))
645 (list (ls-compile (car (last body)) t))))))
647 (define-compilation macrolet (definitions &rest body)
648 (let ((*environment* (copy-lexenv *environment*)))
649 (dolist (def definitions)
650 (destructuring-bind (name lambda-list &body body) def
651 (let ((binding (make-binding :name name :type 'macro :value
652 (let ((g!form (gensym)))
654 (destructuring-bind ,lambda-list ,g!form
656 (push-to-lexenv binding *environment* 'function))))
657 (ls-compile `(progn ,@body) *multiple-value-p*)))
660 (defun special-variable-p (x)
661 (and (claimp x 'variable 'special) t))
663 ;;; Wrap CODE to restore the symbol values of the dynamic
664 ;;; bindings. BINDINGS is a list of pairs of the form
665 ;;; (SYMBOL . PLACE), where PLACE is a Javascript variable
666 ;;; name to initialize the symbol value and where to stored
668 (defun let-binding-wrapper (bindings body)
669 (when (null bindings)
670 (return-from let-binding-wrapper body))
676 (let ((s (ls-compile `(quote ,(car b)))))
677 `(code "tmp = " ,s ".value;"
678 ,s ".value = " ,(cdr b) ";"
679 ,(cdr b) " = tmp;" )))
686 ,@(mapcar (lambda (b)
687 (let ((s (ls-compile `(quote ,(car b)))))
688 `(code ,s ".value" " = " ,(cdr b) ";" )))
692 (define-compilation let (bindings &rest body)
693 (let* ((bindings (mapcar #'ensure-list bindings))
694 (variables (mapcar #'first bindings))
695 (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
696 (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
698 `(call (function ,(mapcar (lambda (x)
699 (if (special-variable-p x)
700 (let ((v (gvarname x)))
701 (push (cons x v) dynamic-bindings)
703 (make-symbol (translate-variable x))))
705 ,(let ((body (ls-compile-block body t t)))
706 `(code ,(let-binding-wrapper dynamic-bindings body))))
710 ;;; Return the code to initialize BINDING, and push it extending the
711 ;;; current lexical environment if the variable is not special.
712 (defun let*-initialize-value (binding)
713 (let ((var (first binding))
714 (value (second binding)))
715 (if (special-variable-p var)
716 `(code ,(ls-compile `(setq ,var ,value)) ";" )
717 (let* ((v (gvarname var))
718 (b (make-binding :name var :type 'variable :value v)))
719 (prog1 `(code "var " ,v " = " ,(ls-compile value) ";" )
720 (push-to-lexenv b *environment* 'variable))))))
722 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
723 ;;; DOES NOT generate code to initialize the value of the symbols,
724 ;;; unlike let-binding-wrapper.
725 (defun let*-binding-wrapper (symbols body)
727 (return-from let*-binding-wrapper body))
728 (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
729 (remove-if-not #'special-variable-p symbols))))
733 ,@(mapcar (lambda (b)
734 (let ((s (ls-compile `(quote ,(car b)))))
735 `(code "var " ,(cdr b) " = " ,s ".value;" )))
741 ,@(mapcar (lambda (b)
742 (let ((s (ls-compile `(quote ,(car b)))))
743 `(code ,s ".value" " = " ,(cdr b) ";" )))
747 (define-compilation let* (bindings &rest body)
748 (let ((bindings (mapcar #'ensure-list bindings))
749 (*environment* (copy-lexenv *environment*)))
751 (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
752 (body `(code ,@(mapcar #'let*-initialize-value bindings)
753 ,(ls-compile-block body t t))))
754 (let*-binding-wrapper specials body)))))
757 (define-compilation block (name &rest body)
758 ;; We use Javascript exceptions to implement non local control
759 ;; transfer. Exceptions has dynamic scoping, so we use a uniquely
760 ;; generated object to identify the block. The instance of a empty
761 ;; array is used to distinguish between nested dynamic Javascript
762 ;; exceptions. See https://github.com/davazp/jscl/issues/64 for
764 (let* ((idvar (gvarname name))
765 (b (make-binding :name name :type 'block :value idvar)))
766 (when *multiple-value-p*
767 (push 'multiple-value (binding-declarations b)))
768 (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
769 (cbody (ls-compile-block body t)))
770 (if (member 'used (binding-declarations b))
773 "var " idvar " = [];"
777 " if (cf.type == 'block' && cf.id == " idvar ")"
778 (if *multiple-value-p*
779 " return values.apply(this, forcemv(cf.values));"
780 " return cf.values;")
785 (js!selfcall cbody)))))
787 (define-compilation return-from (name &optional value)
788 (let* ((b (lookup-in-lexenv name *environment* 'block))
789 (multiple-value-p (member 'multiple-value (binding-declarations b))))
791 (error "Return from unknown block `~S'." (symbol-name name)))
792 (push 'used (binding-declarations b))
793 ;; The binding value is the name of a variable, whose value is the
794 ;; unique identifier of the block as exception. We can't use the
795 ;; variable name itself, because it could not to be unique, so we
796 ;; capture it in a closure.
798 (when multiple-value-p `(code "var values = mv;" ))
801 "id: " (binding-value b) ", "
802 "values: " (ls-compile value multiple-value-p) ", "
803 "message: 'Return from unknown block " (symbol-name name) ".'"
806 (define-compilation catch (id &rest body)
808 `(var (|id| ,(ls-compile id)))
810 ,(ls-compile-block body t))
812 (if (and (== (get |cf| "type") "catch")
813 (== (get |cf| "id") |id|))
814 ,(if *multiple-value-p*
815 `(return (call (get |values| "apply")
817 (call |forcemv| (get |cf| "values"))))
818 `(return (call (get |pv| "apply")
820 (call |forcemv| (get |cf| "values")))))
823 (define-compilation throw (id value)
825 `(var (|values| |mv|))
828 |id| ,(ls-compile id)
829 |values| ,(ls-compile value t)
830 |message| "Throw uncatched."))))
833 (or (integerp x) (symbolp x)))
835 (defun declare-tagbody-tags (tbidx body)
836 (let* ((go-tag-counter 0)
838 (mapcar (lambda (label)
839 (let ((tagidx (integer-to-string (incf go-tag-counter))))
840 (make-binding :name label :type 'gotag :value (list tbidx tagidx))))
841 (remove-if-not #'go-tag-p body))))
842 (extend-lexenv bindings *environment* 'gotag)))
844 (define-compilation tagbody (&rest body)
845 ;; Ignore the tagbody if it does not contain any go-tag. We do this
846 ;; because 1) it is easy and 2) many built-in forms expand to a
847 ;; implicit tagbody, so we save some space.
848 (unless (some #'go-tag-p body)
849 (return-from tagbody (ls-compile `(progn ,@body nil))))
850 ;; The translation assumes the first form in BODY is a label
851 (unless (go-tag-p (car body))
852 (push (gensym "START") body))
853 ;; Tagbody compilation
854 (let ((branch (gvarname 'branch))
855 (tbidx (gvarname 'tbidx)))
856 (let ((*environment* (declare-tagbody-tags tbidx body))
858 (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
859 (setq initag (second (binding-value b))))
861 ;; TAGBODY branch to take
862 "var " branch " = " initag ";"
863 "var " tbidx " = [];"
867 ,(let ((content nil))
868 `(code "switch(" ,branch "){"
870 ,@(dolist (form (cdr body) (reverse content))
871 (push (if (not (go-tag-p form))
872 `(code ,(ls-compile form) ";" )
873 (let ((b (lookup-in-lexenv form *environment* 'gotag)))
874 `(code "case " ,(second (binding-value b)) ":" )))
881 " if (jump.type == 'tagbody' && jump.id == " ,tbidx ")"
882 " " ,branch " = jump.label;"
887 "return " (ls-compile nil) ";" ))))
889 (define-compilation go (label)
890 (let ((b (lookup-in-lexenv label *environment* 'gotag))
892 ((symbolp label) (symbol-name label))
893 ((integerp label) (integer-to-string label)))))
895 (error "Unknown tag `~S'" label))
899 "id: " (first (binding-value b)) ", "
900 "label: " (second (binding-value b)) ", "
901 "message: 'Attempt to GO to non-existing tag " n "'"
904 (define-compilation unwind-protect (form &rest clean-up)
906 `(var (|ret| ,(ls-compile nil)))
908 (= |ret| ,(ls-compile form)))
910 ,(ls-compile-block clean-up))
913 (define-compilation multiple-value-call (func-form &rest forms)
915 "var func = " (ls-compile func-form) ";"
916 "var args = [" (if *multiple-value-p* "values" "pv") ", 0];"
922 ,@(mapcar (lambda (form)
923 `(code "vs = " ,(ls-compile form t) ";"
924 "if (typeof vs === 'object' && 'multiple-value' in vs)"
925 (code " args = args.concat(vs);" )
927 (code "args.push(vs);" )))
929 "args[1] = args.length-2;"
930 "return func.apply(window, args);" ) ";" ))
932 (define-compilation multiple-value-prog1 (first-form &rest forms)
934 "var args = " (ls-compile first-form *multiple-value-p*) ";"
935 (ls-compile-block forms)
938 (define-transformation backquote (form)
939 (bq-completely-process form))
944 (defvar *builtins* nil)
946 (defmacro define-raw-builtin (name args &body body)
947 ;; Creates a new primitive function `name' with parameters args and
948 ;; @body. The body can access to the local environment through the
949 ;; variable *ENVIRONMENT*.
950 `(push (list ',name (lambda ,args (block ,name ,@body)))
953 (defmacro define-builtin (name args &body body)
954 `(define-raw-builtin ,name ,args
955 (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
958 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
959 (defmacro type-check (decls &body body)
961 ,@(mapcar (lambda (decl)
962 `(let ((name ,(first decl))
963 (value ,(third decl)))
964 `(code "var " ,name " = " ,value ";" )))
966 ,@(mapcar (lambda (decl)
967 `(let ((name ,(first decl))
968 (type ,(second decl)))
969 `(code "if (typeof " ,name " != '" ,type "')"
970 (code "throw 'The value ' + "
972 " + ' is not a type "
977 `(code "return " ,,@body ";" )))
979 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
980 ;;; a variable which holds a list of forms. It will compile them and
981 ;;; store the result in some Javascript variables. BODY is evaluated
982 ;;; with ARGS bound to the list of these variables to generate the
983 ;;; code which performs the transformation on these variables.
985 (defun variable-arity-call (args function)
987 (error "ARGS must be a non-empty list"))
993 ((or (floatp x) (numberp x)) (push x fargs))
994 (t (let ((v (make-symbol (code "x" (incf counter)))))
996 (push `(code "var " ,v " = " ,(ls-compile x) ";"
997 "if (typeof " ,v " !== 'number') throw 'Not a number!';")
1000 `(code ,@(reverse prelude))
1001 (funcall function (reverse fargs)))))
1004 (defmacro variable-arity (args &body body)
1005 (unless (symbolp args)
1006 (error "`~S' is not a symbol." args))
1007 `(variable-arity-call ,args
1009 `(code "return " ,,@body ";" ))))
1011 (defun num-op-num (x op y)
1012 (type-check (("x" "number" x) ("y" "number" y))
1013 `(code "x" ,op "y")))
1015 (define-raw-builtin + (&rest numbers)
1018 (variable-arity numbers
1021 (define-raw-builtin - (x &rest others)
1022 (let ((args (cons x others)))
1023 (variable-arity args `(- ,@args))))
1025 (define-raw-builtin * (&rest numbers)
1028 (variable-arity numbers `(* ,@numbers))))
1030 (define-raw-builtin / (x &rest others)
1031 (let ((args (cons x others)))
1032 (variable-arity args
1035 (reduce (lambda (x y) `(/ ,x ,y))
1038 (define-builtin mod (x y) (num-op-num x "%" y))
1041 (defun comparison-conjuntion (vars op)
1046 `(,op ,(car vars) ,(cadr vars)))
1048 `(and (,op ,(car vars) ,(cadr vars))
1049 ,(comparison-conjuntion (cdr vars) op)))))
1051 (defmacro define-builtin-comparison (op sym)
1052 `(define-raw-builtin ,op (x &rest args)
1053 (let ((args (cons x args)))
1054 (variable-arity args
1055 (js!bool (comparison-conjuntion args ',sym))))))
1057 (define-builtin-comparison > >)
1058 (define-builtin-comparison < <)
1059 (define-builtin-comparison >= >=)
1060 (define-builtin-comparison <= <=)
1061 (define-builtin-comparison = ==)
1062 (define-builtin-comparison /= !=)
1064 (define-builtin numberp (x)
1065 (js!bool `(== (typeof ,x) "number")))
1067 (define-builtin floor (x)
1068 (type-check (("x" "number" x))
1071 (define-builtin expt (x y)
1072 (type-check (("x" "number" x)
1076 (define-builtin float-to-string (x)
1077 (type-check (("x" "number" x))
1078 "make_lisp_string(x.toString())"))
1080 (define-builtin cons (x y)
1081 `(object "car" ,x "cdr" ,y))
1083 (define-builtin consp (x)
1087 "return (typeof tmp == 'object' && 'car' in tmp);" )))
1089 (define-builtin car (x)
1092 `(return (if (=== tmp ,(ls-compile nil))
1096 (define-builtin cdr (x)
1099 `(return (if (=== tmp ,(ls-compile nil))
1103 (define-builtin rplaca (x new)
1104 (type-check (("x" "object" x))
1105 `(code "(x.car = " ,new ", x)")))
1107 (define-builtin rplacd (x new)
1108 (type-check (("x" "object" x))
1109 `(code "(x.cdr = " ,new ", x)")))
1111 (define-builtin symbolp (x)
1112 (js!bool `(instanceof ,x |Symbol|)))
1114 (define-builtin make-symbol (name)
1115 `(new (call |Symbol| ,name)))
1117 (define-builtin symbol-name (x)
1120 (define-builtin set (symbol value)
1121 `(= (get ,symbol "value") ,value))
1123 (define-builtin fset (symbol value)
1124 `(= (get ,symbol "fvalue") ,value))
1126 (define-builtin boundp (x)
1127 (js!bool `(!== (get ,x "value") undefined)))
1129 (define-builtin fboundp (x)
1130 (js!bool `(!== (get ,x "fvalue") undefined)))
1132 (define-builtin symbol-value (x)
1135 (value (get symbol "value")))
1136 `(if (=== value undefined)
1137 (throw (+ "Variable `" (call |xstring| (get symbol "name")) "' is unbound.")))
1140 (define-builtin symbol-function (x)
1143 (func (get symbol "fvalue")))
1144 `(if (=== func undefined)
1145 (throw (+ "Function `" (call |xstring| (get symbol "name")) "' is undefined.")))
1148 (define-builtin symbol-plist (x)
1149 `(or (get ,x "plist") ,(ls-compile nil)))
1151 (define-builtin lambda-code (x)
1152 `(call |make_lisp_string| (call (get ,x "toString"))))
1154 (define-builtin eq (x y)
1155 (js!bool `(=== ,x ,y)))
1157 (define-builtin char-code (x)
1158 (type-check (("x" "string" x))
1159 "char_to_codepoint(x)"))
1161 (define-builtin code-char (x)
1162 (type-check (("x" "number" x))
1163 "char_from_codepoint(x)"))
1165 (define-builtin characterp (x)
1169 `(return (and (== (typeof x) "string")
1170 (or (== (get x "length") 1)
1171 (== (get x "length") 2)))))))
1173 (define-builtin char-upcase (x)
1174 `(call |safe_char_upcase| ,x))
1176 (define-builtin char-downcase (x)
1177 `(call |safe_char_downcase| ,x))
1179 (define-builtin stringp (x)
1183 `(return (and (and (===(typeof x) "object")
1185 (== (get x "stringp") 1))))))
1187 (define-raw-builtin funcall (func &rest args)
1189 `(var (f ,(ls-compile func)))
1190 `(return (call (if (=== (typeof f) "function")
1193 ,@(list* (if *multiple-value-p* '|values| '|pv|)
1195 (mapcar #'ls-compile args))))))
1197 (define-raw-builtin apply (func &rest args)
1199 `(code "(" ,(ls-compile func) ")()")
1200 (let ((args (butlast args))
1201 (last (car (last args))))
1203 "var f = " (ls-compile func) ";"
1204 "var args = [" `(code
1205 ,@(interleave (list* (if *multiple-value-p* "values" "pv")
1206 (integer-to-string (length args))
1207 (mapcar #'ls-compile args))
1210 "var tail = (" (ls-compile last) ");"
1211 "while (tail != " (ls-compile nil) "){"
1212 " args.push(tail.car);"
1216 "return (typeof f === 'function'? f : f.fvalue).apply(this, args);" ))))
1218 (define-builtin js-eval (string)
1219 (if *multiple-value-p*
1221 `(var (v (call |globalEval| (call |xstring| ,string))))
1222 `(return (call (get |values| "apply") this (call |forcemv| v))))
1223 `(call |globalEval| (call |xstring| ,string))))
1225 (define-builtin %throw (string)
1226 (js!selfcall* `(throw ,string)))
1228 (define-builtin functionp (x)
1229 (js!bool `(=== (typeof ,x) "function")))
1231 (define-builtin %write-string (x)
1232 `(call (get |lisp| "write") ,x))
1234 (define-builtin /debug (x)
1235 `(call (get |console| "log") (call |xstring| ,x)))
1238 ;;; Storage vectors. They are used to implement arrays and (in the
1239 ;;; future) structures.
1241 (define-builtin storage-vector-p (x)
1245 `(return (and (=== (typeof x) "object") (in "length" x))))))
1247 (define-builtin make-storage-vector (n)
1250 `(= (get r "length") ,n)
1253 (define-builtin storage-vector-size (x)
1256 (define-builtin resize-storage-vector (vector new-size)
1257 `(= (get ,vector "length") ,new-size))
1259 (define-builtin storage-vector-ref (vector n)
1261 `(var (x (property ,vector ,n)))
1262 `(if (=== x undefined) (throw "Out of range."))
1265 (define-builtin storage-vector-set (vector n value)
1269 `(if (or (< i 0) (>= i (get x "length")))
1270 (throw "Out of range."))
1271 `(return (= (property x i) ,value))))
1273 (define-builtin concatenate-storage-vector (sv1 sv2)
1276 `(var (r (call (get sv1 "concat") ,sv2)))
1277 `(= (get r "type") (get sv1 "type"))
1278 `(= (get r "stringp") (get sv1 "stringp"))
1281 (define-builtin get-internal-real-time ()
1282 `(call (get (new (call |Date|)) "getTime")))
1284 (define-builtin values-array (array)
1285 (if *multiple-value-p*
1286 `(call (get |values| "apply") this ,array)
1287 `(call (get |pv| "apply") this ,array)))
1289 (define-raw-builtin values (&rest args)
1290 (if *multiple-value-p*
1291 `(call |values| ,@(mapcar #'ls-compile args))
1292 `(call |pv| ,@(mapcar #'ls-compile args))))
1296 (define-builtin new ()
1299 (define-raw-builtin oget* (object key &rest keys)
1302 (var (tmp (property ,(ls-compile object) (call |xstring| ,(ls-compile key)))))
1303 ,@(mapcar (lambda (key)
1305 (if (=== tmp undefined) (return ,(ls-compile nil)))
1306 (= tmp (property tmp (call |xstring| ,(ls-compile key))))))
1308 `(return (if (=== tmp undefined) ,(ls-compile nil) tmp))))
1310 (define-raw-builtin oset* (value object key &rest keys)
1311 (let ((keys (cons key keys)))
1314 (var (obj ,(ls-compile object)))
1315 ,@(mapcar (lambda (key)
1317 (= obj (property obj (call |xstring| ,(ls-compile key))))
1318 (if (=== object undefined)
1319 (throw "Impossible to set object property."))))
1322 (= (property obj (call |xstring| ,(ls-compile (car (last keys)))))
1323 ,(ls-compile value))))
1324 (return (if (=== tmp undefined)
1328 (define-raw-builtin oget (object key &rest keys)
1329 `(call |js_to_lisp| ,(ls-compile `(oget* ,object ,key ,@keys))))
1331 (define-raw-builtin oset (value object key &rest keys)
1332 (ls-compile `(oset* (lisp-to-js ,value) ,object ,key ,@keys)))
1334 (define-builtin objectp (x)
1335 (js!bool `(=== (typeof ,x) "object")))
1337 (define-builtin lisp-to-js (x) `(call |lisp_to_js| ,x))
1338 (define-builtin js-to-lisp (x) `(call |js_to_lisp| ,x))
1341 (define-builtin in (key object)
1342 (js!bool `(in (call |xstring| ,key) ,object)))
1344 (define-builtin map-for-in (function object)
1347 (g (if (=== (typeof f) "function") f (get f "fvalue")))
1350 (call g ,(if *multiple-value-p* '|values| '|pv|) 1 (get o "key")))
1351 `(return ,(ls-compile nil))))
1353 (define-compilation %js-vref (var)
1354 `(call |js_to_lisp| ,(make-symbol var)))
1356 (define-compilation %js-vset (var val)
1357 `(= ,(make-symbol var) (call |lisp_to_js| ,(ls-compile val))))
1359 (define-setf-expander %js-vref (var)
1360 (let ((new-value (gensym)))
1361 (unless (stringp var)
1362 (error "`~S' is not a string." var))
1366 `(%js-vset ,var ,new-value)
1371 (defvar *macroexpander-cache*
1372 (make-hash-table :test #'eq))
1374 (defun !macro-function (symbol)
1375 (unless (symbolp symbol)
1376 (error "`~S' is not a symbol." symbol))
1377 (let ((b (lookup-in-lexenv symbol *environment* 'function)))
1378 (if (and b (eq (binding-type b) 'macro))
1379 (let ((expander (binding-value b)))
1382 ((gethash b *macroexpander-cache*)
1383 (setq expander (gethash b *macroexpander-cache*)))
1385 (let ((compiled (eval expander)))
1386 ;; The list representation are useful while
1387 ;; bootstrapping, as we can dump the definition of the
1388 ;; macros easily, but they are slow because we have to
1389 ;; evaluate them and compile them now and again. So, let
1390 ;; us replace the list representation version of the
1391 ;; function with the compiled one.
1393 #+jscl (setf (binding-value b) compiled)
1394 #-jscl (setf (gethash b *macroexpander-cache*) compiled)
1395 (setq expander compiled))))
1399 (defun !macroexpand-1 (form)
1402 (let ((b (lookup-in-lexenv form *environment* 'variable)))
1403 (if (and b (eq (binding-type b) 'macro))
1404 (values (binding-value b) t)
1405 (values form nil))))
1406 ((and (consp form) (symbolp (car form)))
1407 (let ((macrofun (!macro-function (car form))))
1409 (values (funcall macrofun (cdr form)) t)
1410 (values form nil))))
1412 (values form nil))))
1414 (defun compile-funcall (function args)
1415 (let* ((values-funcs (if *multiple-value-p* "values" "pv"))
1416 (arglist `(code "(" ,@(interleave (list* values-funcs
1417 (integer-to-string (length args))
1418 (mapcar #'ls-compile args))
1421 (unless (or (symbolp function)
1422 (and (consp function)
1423 (member (car function) '(lambda oget))))
1424 (error "Bad function designator `~S'" function))
1426 ((translate-function function)
1427 `(code ,(translate-function function) ,arglist))
1428 ((and (symbolp function)
1429 #+jscl (eq (symbol-package function) (find-package "COMMON-LISP"))
1431 `(code ,(ls-compile `',function) ".fvalue" ,arglist))
1432 #+jscl((symbolp function)
1433 `(code ,(ls-compile `#',function) ,arglist))
1434 ((and (consp function) (eq (car function) 'lambda))
1435 `(code ,(ls-compile `#',function) ,arglist))
1436 ((and (consp function) (eq (car function) 'oget))
1437 `(code ,(ls-compile function) ,arglist))
1439 (error "Bad function descriptor")))))
1441 (defun ls-compile-block (sexps &optional return-last-p decls-allowed-p)
1442 (multiple-value-bind (sexps decls)
1443 (parse-body sexps :declarations decls-allowed-p)
1444 (declare (ignore decls))
1446 `(code ,(ls-compile-block (butlast sexps) nil decls-allowed-p)
1447 "return " ,(ls-compile (car (last sexps)) *multiple-value-p*) ";")
1449 ,@(interleave (mapcar #'ls-compile sexps) ";
1453 (defun ls-compile* (sexp &optional multiple-value-p)
1454 (multiple-value-bind (sexp expandedp) (!macroexpand-1 sexp)
1456 (return-from ls-compile* (ls-compile sexp multiple-value-p)))
1457 ;; The expression has been macroexpanded. Now compile it!
1458 (let ((*multiple-value-p* multiple-value-p))
1461 (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1463 ((and b (not (member 'special (binding-declarations b))))
1465 ((or (keywordp sexp)
1466 (and b (member 'constant (binding-declarations b))))
1467 `(code ,(ls-compile `',sexp) ".value"))
1469 (ls-compile `(symbol-value ',sexp))))))
1470 ((or (integerp sexp) (floatp sexp) (characterp sexp) (stringp sexp) (arrayp sexp))
1473 (let ((name (car sexp))
1477 ((assoc name *compilations*)
1478 (let ((comp (second (assoc name *compilations*))))
1480 ;; Built-in functions
1481 ((and (assoc name *builtins*)
1482 (not (claimp name 'function 'notinline)))
1483 (let ((comp (second (assoc name *builtins*))))
1486 (compile-funcall name args)))))
1488 (error "How should I compile `~S'?" sexp))))))
1490 (defun ls-compile (sexp &optional multiple-value-p)
1491 `(code "(" ,(ls-compile* sexp multiple-value-p) ")"))
1494 (defvar *compile-print-toplevels* nil)
1496 (defun truncate-string (string &optional (width 60))
1497 (let ((n (or (position #\newline string)
1498 (min width (length string)))))
1499 (subseq string 0 n)))
1501 (defun convert-toplevel (sexp &optional multiple-value-p)
1502 (let ((*toplevel-compilations* nil))
1504 ;; Non-empty toplevel progn
1506 (eq (car sexp) 'progn)
1509 ,@(mapcar (lambda (s) (convert-toplevel s t))
1512 (when *compile-print-toplevels*
1513 (let ((form-string (prin1-to-string sexp)))
1514 (format t "Compiling ~a..." (truncate-string form-string))))
1515 (let ((code (ls-compile sexp multiple-value-p)))
1517 ,@(interleave (get-toplevel-compilations) ";
1520 `(code ,code ";"))))))))
1522 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
1523 (with-output-to-string (*standard-output*)
1524 (js (convert-toplevel sexp multiple-value-p))))