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 (code "v" (incf *variable-counter*)))
122 (defun translate-variable (symbol)
123 (awhen (lookup-in-lexenv symbol *environment* 'variable)
126 (defun extend-local-env (args)
127 (let ((new (copy-lexenv *environment*)))
128 (dolist (symbol args new)
129 (let ((b (make-binding :name symbol :type 'variable :value (gvarname symbol))))
130 (push-to-lexenv b new 'variable)))))
132 ;;; Toplevel compilations
133 (defvar *toplevel-compilations* nil)
135 (defun toplevel-compilation (string)
136 (push string *toplevel-compilations*))
138 (defun get-toplevel-compilations ()
139 (reverse *toplevel-compilations*))
141 (defun %compile-defmacro (name lambda)
142 (toplevel-compilation (ls-compile `',name))
143 (let ((binding (make-binding :name name :type 'macro :value lambda)))
144 (push-to-lexenv binding *environment* 'function))
147 (defun global-binding (name type namespace)
148 (or (lookup-in-lexenv name *environment* namespace)
149 (let ((b (make-binding :name name :type type :value nil)))
150 (push-to-lexenv b *environment* namespace)
153 (defun claimp (symbol namespace claim)
154 (let ((b (lookup-in-lexenv symbol *environment* namespace)))
155 (and b (member claim (binding-declarations b)))))
157 (defun !proclaim (decl)
160 (dolist (name (cdr decl))
161 (let ((b (global-binding name 'variable 'variable)))
162 (push 'special (binding-declarations b)))))
164 (dolist (name (cdr decl))
165 (let ((b (global-binding name 'function 'function)))
166 (push 'notinline (binding-declarations b)))))
168 (dolist (name (cdr decl))
169 (let ((b (global-binding name 'variable 'variable)))
170 (push 'constant (binding-declarations b)))))))
173 (fset 'proclaim #'!proclaim)
175 (defun %define-symbol-macro (name expansion)
176 (let ((b (make-binding :name name :type 'macro :value expansion)))
177 (push-to-lexenv b *environment* 'variable)
181 (defmacro define-symbol-macro (name expansion)
182 `(%define-symbol-macro ',name ',expansion))
187 (defvar *compilations* nil)
189 (defmacro define-compilation (name args &body body)
190 ;; Creates a new primitive `name' with parameters args and
191 ;; @body. The body can access to the local environment through the
192 ;; variable *ENVIRONMENT*.
193 `(push (list ',name (lambda ,args (block ,name ,@body)))
196 (define-compilation if (condition true &optional false)
197 `(if (!== ,(ls-compile condition) ,(ls-compile nil))
198 ,(ls-compile true *multiple-value-p*)
199 ,(ls-compile false *multiple-value-p*)))
201 (defvar *ll-keywords* '(&optional &rest &key))
203 (defun list-until-keyword (list)
204 (if (or (null list) (member (car list) *ll-keywords*))
206 (cons (car list) (list-until-keyword (cdr list)))))
208 (defun ll-section (keyword ll)
209 (list-until-keyword (cdr (member keyword ll))))
211 (defun ll-required-arguments (ll)
212 (list-until-keyword ll))
214 (defun ll-optional-arguments-canonical (ll)
215 (mapcar #'ensure-list (ll-section '&optional ll)))
217 (defun ll-optional-arguments (ll)
218 (mapcar #'car (ll-optional-arguments-canonical ll)))
220 (defun ll-rest-argument (ll)
221 (let ((rest (ll-section '&rest ll)))
223 (error "Bad lambda-list `~S'." ll))
226 (defun ll-keyword-arguments-canonical (ll)
227 (flet ((canonicalize (keyarg)
228 ;; Build a canonical keyword argument descriptor, filling
229 ;; the optional fields. The result is a list of the form
230 ;; ((keyword-name var) init-form).
231 (let ((arg (ensure-list keyarg)))
232 (cons (if (listp (car arg))
234 (list (intern (symbol-name (car arg)) "KEYWORD") (car arg)))
236 (mapcar #'canonicalize (ll-section '&key ll))))
238 (defun ll-keyword-arguments (ll)
239 (mapcar (lambda (keyarg) (second (first keyarg)))
240 (ll-keyword-arguments-canonical ll)))
242 (defun ll-svars (lambda-list)
245 (ll-keyword-arguments-canonical lambda-list)
246 (ll-optional-arguments-canonical lambda-list))))
247 (remove nil (mapcar #'third args))))
249 (defun lambda-name/docstring-wrapper (name docstring code)
250 (if (or name docstring)
253 (when name `(= (get func |fname|) ,name))
254 (when docstring `(= (get func |docstring|) ,docstring))
258 (defun lambda-check-argument-count
259 (n-required-arguments n-optional-arguments rest-p)
260 ;; Note: Remember that we assume that the number of arguments of a
261 ;; call is at least 1 (the values argument).
262 (let ((min n-required-arguments)
263 (max (if rest-p 'n/a (+ n-required-arguments n-optional-arguments))))
265 ;; Special case: a positive exact number of arguments.
266 (when (and (< 0 min) (eql min max))
267 (return `(code "checkArgs(nargs, " ,min ");")))
271 `(code "checkArgsAtLeast(nargs, " ,min ");"))
273 `(code "checkArgsAtMost(nargs, " ,max ");"))))))
275 (defun compile-lambda-optional (ll)
276 (let* ((optional-arguments (ll-optional-arguments-canonical ll))
277 (n-required-arguments (length (ll-required-arguments ll)))
278 (n-optional-arguments (length optional-arguments)))
279 (when optional-arguments
280 `(code "switch(nargs){"
284 (while (< idx n-optional-arguments)
285 (let ((arg (nth idx optional-arguments)))
286 (push `(code "case " ,(+ idx n-required-arguments) ":"
287 (code ,(translate-variable (car arg))
289 ,(ls-compile (cadr arg)) ";")
291 `(code ,(translate-variable (third arg))
297 (push `(code "default: break;") cases)
298 `(code ,@(reverse cases))))
301 (defun compile-lambda-rest (ll)
302 (let ((n-required-arguments (length (ll-required-arguments ll)))
303 (n-optional-arguments (length (ll-optional-arguments ll)))
304 (rest-argument (ll-rest-argument ll)))
306 (let ((js!rest (translate-variable rest-argument)))
307 `(code "var " ,js!rest "= " ,(ls-compile nil) ";"
308 "for (var i = nargs-1; i>=" ,(+ n-required-arguments n-optional-arguments)
310 (code ,js!rest " = {car: arguments[i+2], cdr: " ,js!rest "};"))))))
312 (defun compile-lambda-parse-keywords (ll)
313 (let ((n-required-arguments
314 (length (ll-required-arguments ll)))
315 (n-optional-arguments
316 (length (ll-optional-arguments ll)))
318 (ll-keyword-arguments-canonical ll)))
321 ,@(mapcar (lambda (arg)
322 (let ((var (second (car arg))))
323 `(code "var " ,(translate-variable var) "; "
325 `(code "var " ,(translate-variable (third arg))
326 " = " ,(ls-compile nil)
330 ,(flet ((parse-keyword (keyarg)
331 ;; ((keyword-name var) init-form)
332 `(code "for (i=" ,(+ n-required-arguments n-optional-arguments)
334 "if (arguments[i+2] === " ,(ls-compile (caar keyarg)) "){"
335 ,(translate-variable (cadr (car keyarg)))
337 ,(let ((svar (third keyarg)))
339 `(code ,(translate-variable svar) " = " ,(ls-compile t) ";" )))
345 ,(translate-variable (cadr (car keyarg)))
347 ,(ls-compile (cadr keyarg))
350 (when keyword-arguments
352 ,@(mapcar #'parse-keyword keyword-arguments))))
353 ;; Check for unknown keywords
354 ,(when keyword-arguments
355 `(code "var start = " ,(+ n-required-arguments n-optional-arguments) ";"
356 "if ((nargs - start) % 2 == 1){"
357 "throw 'Odd number of keyword arguments';"
359 "for (i = start; i<nargs; i+=2){"
361 ,@(interleave (mapcar (lambda (x)
362 `(code "arguments[i+2] !== " ,(ls-compile (caar x))))
366 "throw 'Unknown keyword argument ' + xstring(arguments[i+2].name);"
369 (defun parse-lambda-list (ll)
370 (values (ll-required-arguments ll)
371 (ll-optional-arguments ll)
372 (ll-keyword-arguments ll)
373 (ll-rest-argument ll)))
375 ;;; Process BODY for declarations and/or docstrings. Return as
376 ;;; multiple values the BODY without docstrings or declarations, the
377 ;;; list of declaration forms and the docstring.
378 (defun parse-body (body &key declarations docstring)
379 (let ((value-declarations)
381 ;; Parse declarations
383 (do* ((rest body (cdr rest))
384 (form (car rest) (car rest)))
385 ((or (atom form) (not (eq (car form) 'declare)))
387 (push form value-declarations)))
391 (not (null (cdr body))))
392 (setq value-docstring (car body))
393 (setq body (cdr body)))
394 (values body value-declarations value-docstring)))
396 ;;; Compile a lambda function with lambda list LL and body BODY. If
397 ;;; NAME is given, it should be a constant string and it will become
398 ;;; the name of the function. If BLOCK is non-NIL, a named block is
399 ;;; created around the body. NOTE: No block (even anonymous) is
400 ;;; created if BLOCk is NIL.
401 (defun compile-lambda (ll body &key name block)
402 (multiple-value-bind (required-arguments
406 (parse-lambda-list ll)
407 (multiple-value-bind (body decls documentation)
408 (parse-body body :declarations t :docstring t)
409 (declare (ignore decls))
410 (let ((n-required-arguments (length required-arguments))
411 (n-optional-arguments (length optional-arguments))
412 (*environment* (extend-local-env
413 (append (ensure-list rest-argument)
418 (lambda-name/docstring-wrapper name documentation
421 ,(join (list* "values"
423 (mapcar #'translate-variable
424 (append required-arguments optional-arguments)))
427 ;; Check number of arguments
428 ,(lambda-check-argument-count n-required-arguments
430 (or rest-argument keyword-arguments))
431 ,(compile-lambda-optional ll)
432 ,(compile-lambda-rest ll)
433 ,(compile-lambda-parse-keywords ll)
434 ,(let ((*multiple-value-p* t))
436 (ls-compile-block `((block ,block ,@body)) t)
437 (ls-compile-block body t)))
441 (defun setq-pair (var val)
442 (let ((b (lookup-in-lexenv var *environment* 'variable)))
445 (eq (binding-type b) 'variable)
446 (not (member 'special (binding-declarations b)))
447 (not (member 'constant (binding-declarations b))))
448 `(code ,(binding-value b) " = " ,(ls-compile val)))
449 ((and b (eq (binding-type b) 'macro))
450 (ls-compile `(setf ,var ,val)))
452 (ls-compile `(set ',var ,val))))))
455 (define-compilation setq (&rest pairs)
458 (return-from setq (ls-compile nil)))
464 (error "Odd pairs in SETQ"))
466 (push `(code ,(setq-pair (car pairs) (cadr pairs))
467 ,(if (null (cddr pairs)) "" ", "))
469 (setq pairs (cddr pairs)))))
470 `(code "(" ,@(reverse result) ")")))
473 ;;; Compilation of literals an object dumping
475 ;;; BOOTSTRAP MAGIC: We record the macro definitions as lists during
476 ;;; the bootstrap. Once everything is compiled, we want to dump the
477 ;;; whole global environment to the output file to reproduce it in the
478 ;;; run-time. However, the environment must contain expander functions
479 ;;; rather than lists. We do not know how to dump function objects
480 ;;; itself, so we mark the list definitions with this object and the
481 ;;; compiler will be called when this object has to be dumped.
482 ;;; Backquote/unquote does a similar magic, but this use is exclusive.
484 ;;; Indeed, perhaps to compile the object other macros need to be
485 ;;; evaluated. For this reason we define a valid macro-function for
487 (defvar *magic-unquote-marker* (gensym "MAGIC-UNQUOTE"))
489 (setf (macro-function *magic-unquote-marker*)
490 (lambda (form &optional environment)
491 (declare (ignore environment))
494 (defvar *literal-table* nil)
495 (defvar *literal-counter* 0)
498 (code "l" (incf *literal-counter*)))
500 (defun dump-symbol (symbol)
502 (let ((package (symbol-package symbol)))
503 (if (eq package (find-package "KEYWORD"))
504 `(new (call |Symbol| ,(dump-string (symbol-name symbol)) ,(dump-string (package-name package))))
505 `(new (call |Symbol| ,(dump-string (symbol-name symbol))))))
507 (let ((package (symbol-package symbol)))
509 `(new (call |Symbol| ,(dump-string (symbol-name symbol))))
510 (ls-compile `(intern ,(symbol-name symbol) ,(package-name package))))))
512 (defun dump-cons (cons)
513 (let ((head (butlast cons))
516 ,@(interleave (mapcar (lambda (x) (literal x t)) head) "," t)
517 ,(literal (car tail) t)
519 ,(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 (code ,(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 ;; TODO: destructuring-bind now! Do error checking manually is
578 (let ((name (cadr x))
581 (compile-lambda ll body
582 :name (symbol-name name)
585 (let ((b (lookup-in-lexenv x *environment* 'function)))
588 (ls-compile `(symbol-function ',x)))))))
591 (defun make-function-binding (fname)
592 (make-binding :name fname :type 'function :value (gvarname fname)))
594 (defun compile-function-definition (list)
595 (compile-lambda (car list) (cdr list)))
597 (defun translate-function (name)
598 (let ((b (lookup-in-lexenv name *environment* 'function)))
599 (and b (binding-value b))))
601 (define-compilation flet (definitions &rest body)
602 (let* ((fnames (mapcar #'car definitions))
603 (cfuncs (mapcar (lambda (def)
604 (compile-lambda (cadr def)
609 (extend-lexenv (mapcar #'make-function-binding fnames)
613 ,@(interleave (mapcar #'translate-function fnames) ",")
615 ,(ls-compile-block body t)
616 "})(" ,@(interleave cfuncs ",") ")")))
618 (define-compilation labels (definitions &rest body)
619 (let* ((fnames (mapcar #'car definitions))
621 (extend-lexenv (mapcar #'make-function-binding fnames)
625 `(code ,@(mapcar (lambda (func)
626 `(code "var " ,(translate-function (car func))
627 " = " ,(compile-lambda (cadr func)
628 `((block ,(car func) ,@(cddr func))))
631 (ls-compile-block body t))))
634 (defvar *compiling-file* nil)
635 (define-compilation eval-when-compile (&rest body)
638 (eval (cons 'progn body))
640 (ls-compile `(progn ,@body))))
642 (defmacro define-transformation (name args form)
643 `(define-compilation ,name ,args
646 (define-compilation progn (&rest body)
647 (if (null (cdr body))
648 (ls-compile (car body) *multiple-value-p*)
651 (append (mapcar #'ls-compile (butlast body))
652 (list (ls-compile (car (last body)) t)))
656 (define-compilation macrolet (definitions &rest body)
657 (let ((*environment* (copy-lexenv *environment*)))
658 (dolist (def definitions)
659 (destructuring-bind (name lambda-list &body body) def
660 (let ((binding (make-binding :name name :type 'macro :value
661 (let ((g!form (gensym)))
663 (destructuring-bind ,lambda-list ,g!form
665 (push-to-lexenv binding *environment* 'function))))
666 (ls-compile `(progn ,@body) *multiple-value-p*)))
669 (defun special-variable-p (x)
670 (and (claimp x 'variable 'special) t))
672 ;;; Wrap CODE to restore the symbol values of the dynamic
673 ;;; bindings. BINDINGS is a list of pairs of the form
674 ;;; (SYMBOL . PLACE), where PLACE is a Javascript variable
675 ;;; name to initialize the symbol value and where to stored
677 (defun let-binding-wrapper (bindings body)
678 (when (null bindings)
679 (return-from let-binding-wrapper body))
685 (let ((s (ls-compile `(quote ,(car b)))))
686 `(code "tmp = " ,s ".value;"
687 ,s ".value = " ,(cdr b) ";"
688 ,(cdr b) " = tmp;" )))
695 ,@(mapcar (lambda (b)
696 (let ((s (ls-compile `(quote ,(car b)))))
697 `(code ,s ".value" " = " ,(cdr b) ";" )))
701 (define-compilation let (bindings &rest body)
702 (let* ((bindings (mapcar #'ensure-list bindings))
703 (variables (mapcar #'first bindings))
704 (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
705 (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
710 (if (special-variable-p x)
711 (let ((v (gvarname x)))
712 (push (cons x v) dynamic-bindings)
714 (translate-variable x)))
718 ,(let ((body (ls-compile-block body t t)))
719 `(code ,(let-binding-wrapper dynamic-bindings body)))
720 "})(" ,@(interleave cvalues ",") ")")))
723 ;;; Return the code to initialize BINDING, and push it extending the
724 ;;; current lexical environment if the variable is not special.
725 (defun let*-initialize-value (binding)
726 (let ((var (first binding))
727 (value (second binding)))
728 (if (special-variable-p var)
729 `(code ,(ls-compile `(setq ,var ,value)) ";" )
730 (let* ((v (gvarname var))
731 (b (make-binding :name var :type 'variable :value v)))
732 (prog1 `(code "var " ,v " = " ,(ls-compile value) ";" )
733 (push-to-lexenv b *environment* 'variable))))))
735 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
736 ;;; DOES NOT generate code to initialize the value of the symbols,
737 ;;; unlike let-binding-wrapper.
738 (defun let*-binding-wrapper (symbols body)
740 (return-from let*-binding-wrapper body))
741 (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
742 (remove-if-not #'special-variable-p symbols))))
746 ,@(mapcar (lambda (b)
747 (let ((s (ls-compile `(quote ,(car b)))))
748 `(code "var " ,(cdr b) " = " ,s ".value;" )))
754 ,@(mapcar (lambda (b)
755 (let ((s (ls-compile `(quote ,(car b)))))
756 `(code ,s ".value" " = " ,(cdr b) ";" )))
760 (define-compilation let* (bindings &rest body)
761 (let ((bindings (mapcar #'ensure-list bindings))
762 (*environment* (copy-lexenv *environment*)))
764 (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
765 (body `(code ,@(mapcar #'let*-initialize-value bindings)
766 ,(ls-compile-block body t t))))
767 (let*-binding-wrapper specials body)))))
770 (define-compilation block (name &rest body)
771 ;; We use Javascript exceptions to implement non local control
772 ;; transfer. Exceptions has dynamic scoping, so we use a uniquely
773 ;; generated object to identify the block. The instance of a empty
774 ;; array is used to distinguish between nested dynamic Javascript
775 ;; exceptions. See https://github.com/davazp/jscl/issues/64 for
777 (let* ((idvar (gvarname name))
778 (b (make-binding :name name :type 'block :value idvar)))
779 (when *multiple-value-p*
780 (push 'multiple-value (binding-declarations b)))
781 (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
782 (cbody (ls-compile-block body t)))
783 (if (member 'used (binding-declarations b))
786 "var " idvar " = [];"
790 " if (cf.type == 'block' && cf.id == " idvar ")"
791 (if *multiple-value-p*
792 " return values.apply(this, forcemv(cf.values));"
793 " return cf.values;")
798 (js!selfcall cbody)))))
800 (define-compilation return-from (name &optional value)
801 (let* ((b (lookup-in-lexenv name *environment* 'block))
802 (multiple-value-p (member 'multiple-value (binding-declarations b))))
804 (error "Return from unknown block `~S'." (symbol-name name)))
805 (push 'used (binding-declarations b))
806 ;; The binding value is the name of a variable, whose value is the
807 ;; unique identifier of the block as exception. We can't use the
808 ;; variable name itself, because it could not to be unique, so we
809 ;; capture it in a closure.
811 (when multiple-value-p `(code "var values = mv;" ))
814 "id: " (binding-value b) ", "
815 "values: " (ls-compile value multiple-value-p) ", "
816 "message: 'Return from unknown block " (symbol-name name) ".'"
819 (define-compilation catch (id &rest body)
821 "var id = " (ls-compile id) ";"
823 `(code ,(ls-compile-block body t))
826 " if (cf.type == 'catch' && cf.id == id)"
827 (if *multiple-value-p*
828 " return values.apply(this, forcemv(cf.values));"
829 " return pv.apply(this, forcemv(cf.values));")
835 (define-compilation throw (id value)
840 "id: " (ls-compile id) ", "
841 "values: " (ls-compile value t) ", "
842 "message: 'Throw uncatched.'"
846 (or (integerp x) (symbolp x)))
848 (defun declare-tagbody-tags (tbidx body)
849 (let* ((go-tag-counter 0)
851 (mapcar (lambda (label)
852 (let ((tagidx (integer-to-string (incf go-tag-counter))))
853 (make-binding :name label :type 'gotag :value (list tbidx tagidx))))
854 (remove-if-not #'go-tag-p body))))
855 (extend-lexenv bindings *environment* 'gotag)))
857 (define-compilation tagbody (&rest body)
858 ;; Ignore the tagbody if it does not contain any go-tag. We do this
859 ;; because 1) it is easy and 2) many built-in forms expand to a
860 ;; implicit tagbody, so we save some space.
861 (unless (some #'go-tag-p body)
862 (return-from tagbody (ls-compile `(progn ,@body nil))))
863 ;; The translation assumes the first form in BODY is a label
864 (unless (go-tag-p (car body))
865 (push (gensym "START") body))
866 ;; Tagbody compilation
867 (let ((branch (gvarname 'branch))
868 (tbidx (gvarname 'tbidx)))
869 (let ((*environment* (declare-tagbody-tags tbidx body))
871 (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
872 (setq initag (second (binding-value b))))
874 ;; TAGBODY branch to take
875 "var " branch " = " initag ";"
876 "var " tbidx " = [];"
880 ,(let ((content nil))
881 `(code "switch(" ,branch "){"
883 ,@(dolist (form (cdr body) (reverse content))
884 (push (if (not (go-tag-p form))
885 `(code ,(ls-compile form) ";" )
886 (let ((b (lookup-in-lexenv form *environment* 'gotag)))
887 `(code "case " ,(second (binding-value b)) ":" )))
894 " if (jump.type == 'tagbody' && jump.id == " ,tbidx ")"
895 " " ,branch " = jump.label;"
900 "return " (ls-compile nil) ";" ))))
902 (define-compilation go (label)
903 (let ((b (lookup-in-lexenv label *environment* 'gotag))
905 ((symbolp label) (symbol-name label))
906 ((integerp label) (integer-to-string label)))))
908 (error "Unknown tag `~S'" label))
912 "id: " (first (binding-value b)) ", "
913 "label: " (second (binding-value b)) ", "
914 "message: 'Attempt to GO to non-existing tag " n "'"
917 (define-compilation unwind-protect (form &rest clean-up)
919 "var ret = " (ls-compile nil) ";"
921 `(code "ret = " ,(ls-compile form) ";" )
923 `(code ,(ls-compile-block clean-up))
927 (define-compilation multiple-value-call (func-form &rest forms)
929 "var func = " (ls-compile func-form) ";"
930 "var args = [" (if *multiple-value-p* "values" "pv") ", 0];"
936 ,@(mapcar (lambda (form)
937 `(code "vs = " ,(ls-compile form t) ";"
938 "if (typeof vs === 'object' && 'multiple-value' in vs)"
939 (code " args = args.concat(vs);" )
941 (code "args.push(vs);" )))
943 "args[1] = args.length-2;"
944 "return func.apply(window, args);" ) ";" ))
946 (define-compilation multiple-value-prog1 (first-form &rest forms)
948 "var args = " (ls-compile first-form *multiple-value-p*) ";"
949 (ls-compile-block forms)
952 (define-transformation backquote (form)
953 (bq-completely-process form))
958 (defvar *builtins* nil)
960 (defmacro define-raw-builtin (name args &body body)
961 ;; Creates a new primitive function `name' with parameters args and
962 ;; @body. The body can access to the local environment through the
963 ;; variable *ENVIRONMENT*.
964 `(push (list ',name (lambda ,args (block ,name ,@body)))
967 (defmacro define-builtin (name args &body body)
968 `(define-raw-builtin ,name ,args
969 (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
972 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
973 (defmacro type-check (decls &body body)
975 ,@(mapcar (lambda (decl)
976 `(let ((name ,(first decl))
977 (value ,(third decl)))
978 `(code "var " ,name " = " ,value ";" )))
980 ,@(mapcar (lambda (decl)
981 `(let ((name ,(first decl))
982 (type ,(second decl)))
983 `(code "if (typeof " ,name " != '" ,type "')"
984 (code "throw 'The value ' + "
986 " + ' is not a type "
991 `(code "return " ,,@body ";" )))
993 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
994 ;;; a variable which holds a list of forms. It will compile them and
995 ;;; store the result in some Javascript variables. BODY is evaluated
996 ;;; with ARGS bound to the list of these variables to generate the
997 ;;; code which performs the transformation on these variables.
999 (defun variable-arity-call (args function)
1000 (unless (consp args)
1001 (error "ARGS must be a non-empty list"))
1007 ((floatp x) (push (float-to-string x) fargs))
1008 ((numberp x) (push (integer-to-string x) fargs))
1009 (t (let ((v (code "x" (incf counter))))
1011 (push `(code "var " ,v " = " ,(ls-compile x) ";"
1012 "if (typeof " ,v " !== 'number') throw 'Not a number!';")
1015 `(code ,@(reverse prelude))
1016 (funcall function (reverse fargs)))))
1019 (defmacro variable-arity (args &body body)
1020 (unless (symbolp args)
1021 (error "`~S' is not a symbol." args))
1022 `(variable-arity-call ,args
1024 `(code "return " ,,@body ";" ))))
1026 (defun num-op-num (x op y)
1027 (type-check (("x" "number" x) ("y" "number" y))
1028 `(code "x" ,op "y")))
1030 (define-raw-builtin + (&rest numbers)
1033 (variable-arity numbers
1034 `(code ,@(interleave numbers "+")))))
1036 (define-raw-builtin - (x &rest others)
1037 (let ((args (cons x others)))
1038 (variable-arity args
1040 `(code "-" ,(car args))
1041 `(code ,@(interleave args "-"))))))
1043 (define-raw-builtin * (&rest numbers)
1046 (variable-arity numbers
1047 `(code ,@(interleave numbers "*")))))
1049 (define-raw-builtin / (x &rest others)
1050 (let ((args (cons x others)))
1051 (variable-arity args
1053 `(code "1 /" ,(car args))
1054 `(code ,@(interleave args "/"))))))
1056 (define-builtin mod (x y) (num-op-num x "%" y))
1059 (defun comparison-conjuntion (vars op)
1064 `(code ,(car vars) ,op ,(cadr vars)))
1066 `(code ,(car vars) ,op ,(cadr vars)
1068 ,(comparison-conjuntion (cdr vars) op)))))
1070 (defmacro define-builtin-comparison (op sym)
1071 `(define-raw-builtin ,op (x &rest args)
1072 (let ((args (cons x args)))
1073 (variable-arity args
1074 (js!bool (comparison-conjuntion args ,sym))))))
1076 (define-builtin-comparison > ">")
1077 (define-builtin-comparison < "<")
1078 (define-builtin-comparison >= ">=")
1079 (define-builtin-comparison <= "<=")
1080 (define-builtin-comparison = "==")
1081 (define-builtin-comparison /= "!=")
1083 (define-builtin numberp (x)
1084 (js!bool `(code "(typeof (" ,x ") == \"number\")")))
1086 (define-builtin floor (x)
1087 (type-check (("x" "number" x))
1090 (define-builtin expt (x y)
1091 (type-check (("x" "number" x)
1095 (define-builtin float-to-string (x)
1096 (type-check (("x" "number" x))
1097 "make_lisp_string(x.toString())"))
1099 (define-builtin cons (x y)
1100 `(code "({car: " ,x ", cdr: " ,y "})"))
1102 (define-builtin consp (x)
1106 "return (typeof tmp == 'object' && 'car' in tmp);" )))
1108 (define-builtin car (x)
1111 "return tmp === " (ls-compile nil)
1112 "? " (ls-compile nil)
1115 (define-builtin cdr (x)
1118 "return tmp === " (ls-compile nil) "? "
1122 (define-builtin rplaca (x new)
1123 (type-check (("x" "object" x))
1124 `(code "(x.car = " ,new ", x)")))
1126 (define-builtin rplacd (x new)
1127 (type-check (("x" "object" x))
1128 `(code "(x.cdr = " ,new ", x)")))
1130 (define-builtin symbolp (x)
1131 (js!bool `(code "(" ,x " instanceof Symbol)")))
1133 (define-builtin make-symbol (name)
1134 `(code "(new Symbol(" ,name "))"))
1136 (define-builtin symbol-name (x)
1137 `(code "(" ,x ").name"))
1139 (define-builtin set (symbol value)
1140 `(code "(" ,symbol ").value = " ,value))
1142 (define-builtin fset (symbol value)
1143 `(code "(" ,symbol ").fvalue = " ,value))
1145 (define-builtin boundp (x)
1146 (js!bool `(code "(" ,x ".value !== undefined)")))
1148 (define-builtin fboundp (x)
1149 (js!bool `(code "(" ,x ".fvalue !== undefined)")))
1151 (define-builtin symbol-value (x)
1153 "var symbol = " x ";"
1154 "var value = symbol.value;"
1155 "if (value === undefined) throw \"Variable `\" + xstring(symbol.name) + \"' is unbound.\";"
1158 (define-builtin symbol-function (x)
1160 "var symbol = " x ";"
1161 "var func = symbol.fvalue;"
1162 "if (func === undefined) throw \"Function `\" + xstring(symbol.name) + \"' is undefined.\";"
1165 (define-builtin symbol-plist (x)
1166 `(code "((" ,x ").plist || " ,(ls-compile nil) ")"))
1168 (define-builtin lambda-code (x)
1169 `(code "make_lisp_string((" ,x ").toString())"))
1171 (define-builtin eq (x y)
1172 (js!bool `(code "(" ,x " === " ,y ")")))
1174 (define-builtin char-code (x)
1175 (type-check (("x" "string" x))
1176 "char_to_codepoint(x)"))
1178 (define-builtin code-char (x)
1179 (type-check (("x" "number" x))
1180 "char_from_codepoint(x)"))
1182 (define-builtin characterp (x)
1186 "return (typeof(" x ") == \"string\") && (x.length == 1 || x.length == 2);")))
1188 (define-builtin char-upcase (x)
1189 `(code "safe_char_upcase(" ,x ")"))
1191 (define-builtin char-downcase (x)
1192 `(code "safe_char_downcase(" ,x ")"))
1194 (define-builtin stringp (x)
1198 "return typeof(x) == 'object' && 'length' in x && x.stringp == 1;")))
1200 (define-raw-builtin funcall (func &rest args)
1202 "var f = " (ls-compile func) ";"
1203 "return (typeof f === 'function'? f: f.fvalue)("
1205 ,@(interleave (list* (if *multiple-value-p* "values" "pv")
1206 (integer-to-string (length args))
1207 (mapcar #'ls-compile args))
1211 (define-raw-builtin apply (func &rest args)
1213 `(code "(" ,(ls-compile func) ")()")
1214 (let ((args (butlast args))
1215 (last (car (last args))))
1217 "var f = " (ls-compile func) ";"
1218 "var args = [" `(code
1219 ,@(interleave (list* (if *multiple-value-p* "values" "pv")
1220 (integer-to-string (length args))
1221 (mapcar #'ls-compile args))
1224 "var tail = (" (ls-compile last) ");"
1225 "while (tail != " (ls-compile nil) "){"
1226 " args.push(tail.car);"
1230 "return (typeof f === 'function'? f : f.fvalue).apply(this, args);" ))))
1232 (define-builtin js-eval (string)
1233 (if *multiple-value-p*
1235 "var v = globalEval(xstring(" string "));"
1236 "return values.apply(this, forcemv(v));" )
1237 `(code "globalEval(xstring(" ,string "))")))
1239 (define-builtin %throw (string)
1240 (js!selfcall "throw " string ";" ))
1242 (define-builtin functionp (x)
1243 (js!bool `(code "(typeof " ,x " == 'function')")))
1245 (define-builtin %write-string (x)
1246 `(code "lisp.write(" ,x ")"))
1248 (define-builtin /debug (x)
1249 `(code "console.log(xstring(" ,x "))"))
1252 ;;; Storage vectors. They are used to implement arrays and (in the
1253 ;;; future) structures.
1255 (define-builtin storage-vector-p (x)
1259 "return typeof x === 'object' && 'length' in x;")))
1261 (define-builtin make-storage-vector (n)
1267 (define-builtin storage-vector-size (x)
1268 `(code ,x ".length"))
1270 (define-builtin resize-storage-vector (vector new-size)
1271 `(code "(" ,vector ".length = " ,new-size ")"))
1273 (define-builtin storage-vector-ref (vector n)
1275 "var x = " "(" vector ")[" n "];"
1276 "if (x === undefined) throw 'Out of range';"
1279 (define-builtin storage-vector-set (vector n value)
1281 "var x = " vector ";"
1283 "if (i < 0 || i >= x.length) throw 'Out of range';"
1284 "return x[i] = " value ";" ))
1286 (define-builtin concatenate-storage-vector (sv1 sv2)
1288 "var sv1 = " sv1 ";"
1289 "var r = sv1.concat(" sv2 ");"
1290 "r.type = sv1.type;"
1291 "r.stringp = sv1.stringp;"
1294 (define-builtin get-internal-real-time ()
1295 "(new Date()).getTime()")
1297 (define-builtin values-array (array)
1298 (if *multiple-value-p*
1299 `(code "values.apply(this, " ,array ")")
1300 `(code "pv.apply(this, " ,array ")")))
1302 (define-raw-builtin values (&rest args)
1303 (if *multiple-value-p*
1304 `(code "values(" ,@(interleave (mapcar #'ls-compile args) ",") ")")
1305 `(code "pv(" ,@(interleave (mapcar #'ls-compile args) ", ") ")")))
1310 (define-builtin new () "{}")
1312 (define-raw-builtin oget* (object key &rest keys)
1314 "var tmp = (" (ls-compile object) ")[xstring(" (ls-compile key) ")];"
1316 ,@(mapcar (lambda (key)
1317 `(code "if (tmp === undefined) return " ,(ls-compile nil) ";"
1318 "tmp = tmp[xstring(" ,(ls-compile key) ")];" ))
1320 "return tmp === undefined? " (ls-compile nil) " : tmp;" ))
1322 (define-raw-builtin oset* (value object key &rest keys)
1323 (let ((keys (cons key keys)))
1325 "var obj = " (ls-compile object) ";"
1326 `(code ,@(mapcar (lambda (key)
1327 `(code "obj = obj[xstring(" ,(ls-compile key) ")];"
1328 "if (obj === undefined) throw 'Impossible to set Javascript property.';" ))
1330 "var tmp = obj[xstring(" (ls-compile (car (last keys))) ")] = " (ls-compile value) ";"
1331 "return tmp === undefined? " (ls-compile nil) " : tmp;" )))
1333 (define-raw-builtin oget (object key &rest keys)
1334 `(call |js_to_lisp| ,(ls-compile `(oget* ,object ,key ,@keys))))
1336 (define-raw-builtin oset (value object key &rest keys)
1337 (ls-compile `(oset* (lisp-to-js ,value) ,object ,key ,@keys)))
1339 (define-builtin objectp (x)
1340 (js!bool `(=== (typeof ,x) "object")))
1342 (define-builtin lisp-to-js (x) `(call |lisp_to_js| ,x))
1343 (define-builtin js-to-lisp (x) `(call |js_to_lisp| ,x))
1346 (define-builtin in (key object)
1347 (js!bool `(in (call |xstring| ,key) ,object)))
1349 (define-builtin map-for-in (function object)
1351 "var f = " function ";"
1352 "var g = (typeof f === 'function' ? f : f.fvalue);"
1353 "var o = " object ";"
1354 "for (var key in o){"
1355 `(code "g(" ,(if *multiple-value-p* "values" "pv") ", 1, o[key]);" )
1357 " return " (ls-compile nil) ";" ))
1359 (define-compilation %js-vref (var)
1360 `(code "js_to_lisp(" ,var ")"))
1362 (define-compilation %js-vset (var val)
1363 `(code "(" ,var " = lisp_to_js(" ,(ls-compile val) "))"))
1365 (define-setf-expander %js-vref (var)
1366 (let ((new-value (gensym)))
1367 (unless (stringp var)
1368 (error "`~S' is not a string." var))
1372 `(%js-vset ,var ,new-value)
1377 (defvar *macroexpander-cache*
1378 (make-hash-table :test #'eq))
1380 (defun !macro-function (symbol)
1381 (unless (symbolp symbol)
1382 (error "`~S' is not a symbol." symbol))
1383 (let ((b (lookup-in-lexenv symbol *environment* 'function)))
1384 (if (and b (eq (binding-type b) 'macro))
1385 (let ((expander (binding-value b)))
1388 ((gethash b *macroexpander-cache*)
1389 (setq expander (gethash b *macroexpander-cache*)))
1391 (let ((compiled (eval expander)))
1392 ;; The list representation are useful while
1393 ;; bootstrapping, as we can dump the definition of the
1394 ;; macros easily, but they are slow because we have to
1395 ;; evaluate them and compile them now and again. So, let
1396 ;; us replace the list representation version of the
1397 ;; function with the compiled one.
1399 #+jscl (setf (binding-value b) compiled)
1400 #-jscl (setf (gethash b *macroexpander-cache*) compiled)
1401 (setq expander compiled))))
1405 (defun !macroexpand-1 (form)
1408 (let ((b (lookup-in-lexenv form *environment* 'variable)))
1409 (if (and b (eq (binding-type b) 'macro))
1410 (values (binding-value b) t)
1411 (values form nil))))
1412 ((and (consp form) (symbolp (car form)))
1413 (let ((macrofun (!macro-function (car form))))
1415 (values (funcall macrofun (cdr form)) t)
1416 (values form nil))))
1418 (values form nil))))
1420 (defun compile-funcall (function args)
1421 (let* ((values-funcs (if *multiple-value-p* "values" "pv"))
1422 (arglist `(code "(" ,@(interleave (list* values-funcs
1423 (integer-to-string (length args))
1424 (mapcar #'ls-compile args))
1427 (unless (or (symbolp function)
1428 (and (consp function)
1429 (member (car function) '(lambda oget))))
1430 (error "Bad function designator `~S'" function))
1432 ((translate-function function)
1433 `(code ,(translate-function function) ,arglist))
1434 ((and (symbolp function)
1435 #+jscl (eq (symbol-package function) (find-package "COMMON-LISP"))
1437 `(code ,(ls-compile `',function) ".fvalue" ,arglist))
1438 #+jscl((symbolp function)
1439 `(code ,(ls-compile `#',function) ,arglist))
1440 ((and (consp function) (eq (car function) 'lambda))
1441 `(code ,(ls-compile `#',function) ,arglist))
1442 ((and (consp function) (eq (car function) 'oget))
1443 `(code ,(ls-compile function) ,arglist))
1445 (error "Bad function descriptor")))))
1447 (defun ls-compile-block (sexps &optional return-last-p decls-allowed-p)
1448 (multiple-value-bind (sexps decls)
1449 (parse-body sexps :declarations decls-allowed-p)
1450 (declare (ignore decls))
1452 `(code ,(ls-compile-block (butlast sexps) nil decls-allowed-p)
1453 "return " ,(ls-compile (car (last sexps)) *multiple-value-p*) ";")
1455 ,@(interleave (mapcar #'ls-compile sexps) ";
1459 (defun ls-compile* (sexp &optional multiple-value-p)
1460 (multiple-value-bind (sexp expandedp) (!macroexpand-1 sexp)
1462 (return-from ls-compile* (ls-compile sexp multiple-value-p)))
1463 ;; The expression has been macroexpanded. Now compile it!
1464 (let ((*multiple-value-p* multiple-value-p))
1467 (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1469 ((and b (not (member 'special (binding-declarations b))))
1471 ((or (keywordp sexp)
1472 (and b (member 'constant (binding-declarations b))))
1473 `(code ,(ls-compile `',sexp) ".value"))
1475 (ls-compile `(symbol-value ',sexp))))))
1476 ((or (integerp sexp) (floatp sexp) (characterp sexp) (stringp sexp) (arrayp sexp))
1479 (let ((name (car sexp))
1483 ((assoc name *compilations*)
1484 (let ((comp (second (assoc name *compilations*))))
1486 ;; Built-in functions
1487 ((and (assoc name *builtins*)
1488 (not (claimp name 'function 'notinline)))
1489 (let ((comp (second (assoc name *builtins*))))
1492 (compile-funcall name args)))))
1494 (error "How should I compile `~S'?" sexp))))))
1496 (defun ls-compile (sexp &optional multiple-value-p)
1497 `(code "(" ,(ls-compile* sexp multiple-value-p) ")"))
1500 (defvar *compile-print-toplevels* nil)
1502 (defun truncate-string (string &optional (width 60))
1503 (let ((n (or (position #\newline string)
1504 (min width (length string)))))
1505 (subseq string 0 n)))
1507 (defun convert-toplevel (sexp &optional multiple-value-p)
1508 (let ((*toplevel-compilations* nil))
1510 ;; Non-empty toplevel progn
1512 (eq (car sexp) 'progn)
1515 ,@(mapcar (lambda (s) (convert-toplevel s t))
1518 (when *compile-print-toplevels*
1519 (let ((form-string (prin1-to-string sexp)))
1520 (format t "Compiling ~a..." (truncate-string form-string))))
1521 (let ((code (ls-compile sexp multiple-value-p)))
1523 ,@(interleave (get-toplevel-compilations) ";
1526 `(code ,code ";"))))))))
1528 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
1529 (with-output-to-string (*standard-output*)
1530 (js (convert-toplevel sexp multiple-value-p))))