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 ;;; Translate the Lisp code to Javascript. It will compile the special
22 ;;; forms. Some primitive functions are compiled as special forms
23 ;;; too. The respective real functions are defined in the target (see
24 ;;; the beginning of this file) as well as some primitive functions.
26 (defun code (&rest args)
27 (mapconcat (lambda (arg)
30 ((integerp arg) (integer-to-string arg))
31 ((floatp arg) (float-to-string arg))
33 (t (error "Unknown argument `~S'." arg))))
36 ;;; Wrap X with a Javascript code to convert the result from
37 ;;; Javascript generalized booleans to T or NIL.
39 (code "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
41 ;;; Concatenate the arguments and wrap them with a self-calling
42 ;;; Javascript anonymous function. It is used to make some Javascript
43 ;;; statements valid expressions and provide a private scope as well.
44 ;;; It could be defined as function, but we could do some
45 ;;; preprocessing in the future.
46 (defmacro js!selfcall (&body body)
47 `(code "(function(){" *newline* (code ,@body) "})()"))
49 ;;; Like CODE, but prefix each line with four spaces. Two versions
50 ;;; of this function are available, because the Ecmalisp version is
51 ;;; very slow and bootstraping was annoying.
53 ;;; A Form can return a multiple values object calling VALUES, like
54 ;;; values(arg1, arg2, ...). It will work in any context, as well as
55 ;;; returning an individual object. However, if the special variable
56 ;;; `*multiple-value-p*' is NIL, is granted that only the primary
57 ;;; value will be used, so we can optimize to avoid the VALUES
59 (defvar *multiple-value-p* nil)
75 (defun lookup-in-lexenv (name lexenv namespace)
76 (find name (ecase namespace
77 (variable (lexenv-variable lexenv))
78 (function (lexenv-function lexenv))
79 (block (lexenv-block lexenv))
80 (gotag (lexenv-gotag lexenv)))
83 (defun push-to-lexenv (binding lexenv namespace)
85 (variable (push binding (lexenv-variable lexenv)))
86 (function (push binding (lexenv-function lexenv)))
87 (block (push binding (lexenv-block lexenv)))
88 (gotag (push binding (lexenv-gotag lexenv)))))
90 (defun extend-lexenv (bindings lexenv namespace)
91 (let ((env (copy-lexenv lexenv)))
92 (dolist (binding (reverse bindings) env)
93 (push-to-lexenv binding env namespace))))
96 (defvar *environment* (make-lexenv))
98 (defvar *variable-counter* 0)
100 (defun gvarname (symbol)
101 (declare (ignore symbol))
102 (code "v" (incf *variable-counter*)))
104 (defun translate-variable (symbol)
105 (awhen (lookup-in-lexenv symbol *environment* 'variable)
108 (defun extend-local-env (args)
109 (let ((new (copy-lexenv *environment*)))
110 (dolist (symbol args new)
111 (let ((b (make-binding :name symbol :type 'variable :value (gvarname symbol))))
112 (push-to-lexenv b new 'variable)))))
114 ;;; Toplevel compilations
115 (defvar *toplevel-compilations* nil)
117 (defun toplevel-compilation (string)
118 (push string *toplevel-compilations*))
120 (defun get-toplevel-compilations ()
121 (reverse *toplevel-compilations*))
123 (defun %compile-defmacro (name lambda)
124 (toplevel-compilation (ls-compile `',name))
125 (let ((binding (make-binding :name name :type 'macro :value lambda)))
126 (push-to-lexenv binding *environment* 'function))
129 (defun global-binding (name type namespace)
130 (or (lookup-in-lexenv name *environment* namespace)
131 (let ((b (make-binding :name name :type type :value nil)))
132 (push-to-lexenv b *environment* namespace)
135 (defun claimp (symbol namespace claim)
136 (let ((b (lookup-in-lexenv symbol *environment* namespace)))
137 (and b (member claim (binding-declarations b)))))
139 (defun !proclaim (decl)
142 (dolist (name (cdr decl))
143 (let ((b (global-binding name 'variable 'variable)))
144 (push 'special (binding-declarations b)))))
146 (dolist (name (cdr decl))
147 (let ((b (global-binding name 'function 'function)))
148 (push 'notinline (binding-declarations b)))))
150 (dolist (name (cdr decl))
151 (let ((b (global-binding name 'variable 'variable)))
152 (push 'constant (binding-declarations b)))))))
155 (fset 'proclaim #'!proclaim)
157 (defun %define-symbol-macro (name expansion)
158 (let ((b (make-binding :name name :type 'macro :value expansion)))
159 (push-to-lexenv b *environment* 'variable)
163 (defmacro define-symbol-macro (name expansion)
164 `(%define-symbol-macro ',name ',expansion))
169 (defvar *compilations* nil)
171 (defmacro define-compilation (name args &body body)
172 ;; Creates a new primitive `name' with parameters args and
173 ;; @body. The body can access to the local environment through the
174 ;; variable *ENVIRONMENT*.
175 `(push (list ',name (lambda ,args (block ,name ,@body)))
178 (define-compilation if (condition true &optional false)
179 (code "(" (ls-compile condition) " !== " (ls-compile nil)
180 " ? " (ls-compile true *multiple-value-p*)
181 " : " (ls-compile false *multiple-value-p*)
184 (defvar *ll-keywords* '(&optional &rest &key))
186 (defun list-until-keyword (list)
187 (if (or (null list) (member (car list) *ll-keywords*))
189 (cons (car list) (list-until-keyword (cdr list)))))
191 (defun ll-section (keyword ll)
192 (list-until-keyword (cdr (member keyword ll))))
194 (defun ll-required-arguments (ll)
195 (list-until-keyword ll))
197 (defun ll-optional-arguments-canonical (ll)
198 (mapcar #'ensure-list (ll-section '&optional ll)))
200 (defun ll-optional-arguments (ll)
201 (mapcar #'car (ll-optional-arguments-canonical ll)))
203 (defun ll-rest-argument (ll)
204 (let ((rest (ll-section '&rest ll)))
206 (error "Bad lambda-list `~S'." ll))
209 (defun ll-keyword-arguments-canonical (ll)
210 (flet ((canonicalize (keyarg)
211 ;; Build a canonical keyword argument descriptor, filling
212 ;; the optional fields. The result is a list of the form
213 ;; ((keyword-name var) init-form).
214 (let ((arg (ensure-list keyarg)))
215 (cons (if (listp (car arg))
217 (list (intern (symbol-name (car arg)) "KEYWORD") (car arg)))
219 (mapcar #'canonicalize (ll-section '&key ll))))
221 (defun ll-keyword-arguments (ll)
222 (mapcar (lambda (keyarg) (second (first keyarg)))
223 (ll-keyword-arguments-canonical ll)))
225 (defun ll-svars (lambda-list)
228 (ll-keyword-arguments-canonical lambda-list)
229 (ll-optional-arguments-canonical lambda-list))))
230 (remove nil (mapcar #'third args))))
232 (defun lambda-name/docstring-wrapper (name docstring &rest strs)
233 (if (or name docstring)
235 "var func = " (join strs) ";" *newline*
237 (code "func.fname = " (js-escape-string name) ";" *newline*))
239 (code "func.docstring = " (js-escape-string docstring) ";" *newline*))
240 "return func;" *newline*)
241 (apply #'code strs)))
243 (defun lambda-check-argument-count
244 (n-required-arguments n-optional-arguments rest-p)
245 ;; Note: Remember that we assume that the number of arguments of a
246 ;; call is at least 1 (the values argument).
247 (let ((min n-required-arguments)
248 (max (if rest-p 'n/a (+ n-required-arguments n-optional-arguments))))
250 ;; Special case: a positive exact number of arguments.
251 (when (and (< 0 min) (eql min max))
252 (return (code "checkArgs(nargs, " min ");" *newline*)))
256 (code "checkArgsAtLeast(nargs, " min ");" *newline*))
258 (code "checkArgsAtMost(nargs, " max ");" *newline*))))))
260 (defun compile-lambda-optional (ll)
261 (let* ((optional-arguments (ll-optional-arguments-canonical ll))
262 (n-required-arguments (length (ll-required-arguments ll)))
263 (n-optional-arguments (length optional-arguments)))
264 (when optional-arguments
265 (code "switch(nargs){" *newline*
269 (while (< idx n-optional-arguments)
270 (let ((arg (nth idx optional-arguments)))
271 (push (code "case " (+ idx n-required-arguments) ":" *newline*
272 (code (translate-variable (car arg))
274 (ls-compile (cadr arg)) ";" *newline*)
276 (code (translate-variable (third arg))
282 (push (code "default: break;" *newline*) cases)
283 (join (reverse cases))))
286 (defun compile-lambda-rest (ll)
287 (let ((n-required-arguments (length (ll-required-arguments ll)))
288 (n-optional-arguments (length (ll-optional-arguments ll)))
289 (rest-argument (ll-rest-argument ll)))
291 (let ((js!rest (translate-variable rest-argument)))
292 (code "var " js!rest "= " (ls-compile nil) ";" *newline*
293 "for (var i = nargs-1; i>=" (+ n-required-arguments n-optional-arguments)
295 (code js!rest " = {car: arguments[i+2], cdr: " js!rest "};" *newline*))))))
297 (defun compile-lambda-parse-keywords (ll)
298 (let ((n-required-arguments
299 (length (ll-required-arguments ll)))
300 (n-optional-arguments
301 (length (ll-optional-arguments ll)))
303 (ll-keyword-arguments-canonical ll)))
306 (mapconcat (lambda (arg)
307 (let ((var (second (car arg))))
308 (code "var " (translate-variable var) "; " *newline*
310 (code "var " (translate-variable (third arg))
311 " = " (ls-compile nil)
315 (flet ((parse-keyword (keyarg)
316 ;; ((keyword-name var) init-form)
317 (code "for (i=" (+ n-required-arguments n-optional-arguments)
318 "; i<nargs; i+=2){" *newline*
320 "if (arguments[i+2] === " (ls-compile (caar keyarg)) "){" *newline*
321 (code (translate-variable (cadr (car keyarg)))
324 (let ((svar (third keyarg)))
326 (code (translate-variable svar) " = " (ls-compile t) ";" *newline*)))
331 "if (i == nargs){" *newline*
332 (code (translate-variable (cadr (car keyarg))) " = " (ls-compile (cadr keyarg)) ";" *newline*)
334 (when keyword-arguments
335 (code "var i;" *newline*
336 (mapconcat #'parse-keyword keyword-arguments))))
337 ;; Check for unknown keywords
338 (when keyword-arguments
339 (code "var start = " (+ n-required-arguments n-optional-arguments) ";" *newline*
340 "if ((nargs - start) % 2 == 1){" *newline*
341 (code "throw 'Odd number of keyword arguments';" *newline*)
343 "for (i = start; i<nargs; i+=2){" *newline*
345 (join (mapcar (lambda (x)
346 (concat "arguments[i+2] !== " (ls-compile (caar x))))
351 "throw 'Unknown keyword argument ' + xstring(arguments[i+2].name);" *newline*))
354 (defun parse-lambda-list (ll)
355 (values (ll-required-arguments ll)
356 (ll-optional-arguments ll)
357 (ll-keyword-arguments ll)
358 (ll-rest-argument ll)))
360 ;;; Process BODY for declarations and/or docstrings. Return as
361 ;;; multiple values the BODY without docstrings or declarations, the
362 ;;; list of declaration forms and the docstring.
363 (defun parse-body (body &key declarations docstring)
364 (let ((value-declarations)
366 ;; Parse declarations
368 (do* ((rest body (cdr rest))
369 (form (car rest) (car rest)))
370 ((or (atom form) (not (eq (car form) 'declare)))
372 (push form value-declarations)))
376 (not (null (cdr body))))
377 (setq value-docstring (car body))
378 (setq body (cdr body)))
379 (values body value-declarations value-docstring)))
381 ;;; Compile a lambda function with lambda list LL and body BODY. If
382 ;;; NAME is given, it should be a constant string and it will become
383 ;;; the name of the function. If BLOCK is non-NIL, a named block is
384 ;;; created around the body. NOTE: No block (even anonymous) is
385 ;;; created if BLOCk is NIL.
386 (defun compile-lambda (ll body &key name block)
387 (multiple-value-bind (required-arguments
391 (parse-lambda-list ll)
392 (multiple-value-bind (body decls documentation)
393 (parse-body body :declarations t :docstring t)
394 (declare (ignore decls))
395 (let ((n-required-arguments (length required-arguments))
396 (n-optional-arguments (length optional-arguments))
397 (*environment* (extend-local-env
398 (append (ensure-list rest-argument)
403 (lambda-name/docstring-wrapper name documentation
405 (join (list* "values"
407 (mapcar #'translate-variable
408 (append required-arguments optional-arguments)))
412 ;; Check number of arguments
413 (lambda-check-argument-count n-required-arguments
415 (or rest-argument keyword-arguments))
416 (compile-lambda-optional ll)
417 (compile-lambda-rest ll)
418 (compile-lambda-parse-keywords ll)
419 (let ((*multiple-value-p* t))
421 (ls-compile-block `((block ,block ,@body)) t)
422 (ls-compile-block body t))))
426 (defun setq-pair (var val)
427 (let ((b (lookup-in-lexenv var *environment* 'variable)))
430 (eq (binding-type b) 'variable)
431 (not (member 'special (binding-declarations b)))
432 (not (member 'constant (binding-declarations b))))
433 (code (binding-value b) " = " (ls-compile val)))
434 ((and b (eq (binding-type b) 'macro))
435 (ls-compile `(setf ,var ,val)))
437 (ls-compile `(set ',var ,val))))))
440 (define-compilation setq (&rest pairs)
443 (return-from setq (ls-compile nil)))
449 (error "Odd pairs in SETQ"))
452 (concat (setq-pair (car pairs) (cadr pairs))
453 (if (null (cddr pairs)) "" ", ")))
454 (setq pairs (cddr pairs)))))
455 (code "(" result ")")))
458 ;;; Compilation of literals an object dumping
460 ;;; BOOTSTRAP MAGIC: We record the macro definitions as lists during
461 ;;; the bootstrap. Once everything is compiled, we want to dump the
462 ;;; whole global environment to the output file to reproduce it in the
463 ;;; run-time. However, the environment must contain expander functions
464 ;;; rather than lists. We do not know how to dump function objects
465 ;;; itself, so we mark the list definitions with this object and the
466 ;;; compiler will be called when this object has to be dumped.
467 ;;; Backquote/unquote does a similar magic, but this use is exclusive.
469 ;;; Indeed, perhaps to compile the object other macros need to be
470 ;;; evaluated. For this reason we define a valid macro-function for
472 (defvar *magic-unquote-marker* (gensym "MAGIC-UNQUOTE"))
474 (setf (macro-function *magic-unquote-marker*)
475 (lambda (form &optional environment)
476 (declare (ignore environment))
479 (defvar *literal-table* nil)
480 (defvar *literal-counter* 0)
483 (code "l" (incf *literal-counter*)))
485 (defun dump-symbol (symbol)
487 (let ((package (symbol-package symbol)))
488 (if (eq package (find-package "KEYWORD"))
489 (code "(new Symbol(" (dump-string (symbol-name symbol)) ", " (dump-string (package-name package)) "))")
490 (code "(new Symbol(" (dump-string (symbol-name symbol)) "))")))
492 (let ((package (symbol-package symbol)))
494 (code "(new Symbol(" (dump-string (symbol-name symbol)) "))")
495 (ls-compile `(intern ,(symbol-name symbol) ,(package-name package))))))
497 (defun dump-cons (cons)
498 (let ((head (butlast cons))
501 (join-trailing (mapcar (lambda (x) (literal x t)) head) ",")
502 (literal (car tail) t)
504 (literal (cdr tail) t)
507 (defun dump-array (array)
508 (let ((elements (vector-to-list array)))
509 (concat "[" (join (mapcar #'literal elements) ", ") "]")))
511 (defun dump-string (string)
512 (code "make_lisp_string(" (js-escape-string string) ")"))
514 (defun literal (sexp &optional recursive)
516 ((integerp sexp) (integer-to-string sexp))
517 ((floatp sexp) (float-to-string sexp))
518 ((characterp sexp) (js-escape-string (string sexp)))
520 (or (cdr (assoc sexp *literal-table* :test #'eql))
521 (let ((dumped (typecase sexp
522 (symbol (dump-symbol sexp))
523 (string (dump-string sexp))
525 ;; BOOTSTRAP MAGIC: See the root file
526 ;; jscl.lisp and the function
527 ;; `dump-global-environment' for futher
529 (if (eq (car sexp) *magic-unquote-marker*)
530 (ls-compile (second sexp))
532 (array (dump-array sexp)))))
533 (if (and recursive (not (symbolp sexp)))
535 (let ((jsvar (genlit)))
536 (push (cons sexp jsvar) *literal-table*)
537 (toplevel-compilation (code "var " jsvar " = " dumped))
538 (when (keywordp sexp)
539 (toplevel-compilation (code jsvar ".value = " jsvar)))
543 (define-compilation quote (sexp)
546 (define-compilation %while (pred &rest body)
548 "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
549 (code (ls-compile-block body))
551 "return " (ls-compile nil) ";" *newline*))
553 (define-compilation function (x)
555 ((and (listp x) (eq (car x) 'lambda))
556 (compile-lambda (cadr x) (cddr x)))
557 ((and (listp x) (eq (car x) 'named-lambda))
558 ;; TODO: destructuring-bind now! Do error checking manually is
560 (let ((name (cadr x))
563 (compile-lambda ll body
564 :name (symbol-name name)
567 (let ((b (lookup-in-lexenv x *environment* 'function)))
570 (ls-compile `(symbol-function ',x)))))))
573 (defun make-function-binding (fname)
574 (make-binding :name fname :type 'function :value (gvarname fname)))
576 (defun compile-function-definition (list)
577 (compile-lambda (car list) (cdr list)))
579 (defun translate-function (name)
580 (let ((b (lookup-in-lexenv name *environment* 'function)))
581 (and b (binding-value b))))
583 (define-compilation flet (definitions &rest body)
584 (let* ((fnames (mapcar #'car definitions))
585 (cfuncs (mapcar (lambda (def)
586 (compile-lambda (cadr def)
591 (extend-lexenv (mapcar #'make-function-binding fnames)
595 (join (mapcar #'translate-function fnames) ",")
597 (let ((body (ls-compile-block body t)))
599 "})(" (join cfuncs ",") ")")))
601 (define-compilation labels (definitions &rest body)
602 (let* ((fnames (mapcar #'car definitions))
604 (extend-lexenv (mapcar #'make-function-binding fnames)
608 (mapconcat (lambda (func)
609 (code "var " (translate-function (car func))
610 " = " (compile-lambda (cadr func)
611 `((block ,(car func) ,@(cddr func))))
614 (ls-compile-block body t))))
617 (defvar *compiling-file* nil)
618 (define-compilation eval-when-compile (&rest body)
621 (eval (cons 'progn body))
623 (ls-compile `(progn ,@body))))
625 (defmacro define-transformation (name args form)
626 `(define-compilation ,name ,args
629 (define-compilation progn (&rest body)
630 (if (null (cdr body))
631 (ls-compile (car body) *multiple-value-p*)
635 (mapcar #'ls-compile (butlast body))
636 (list (ls-compile (car (last body)) t)))
640 (define-compilation macrolet (definitions &rest body)
641 (let ((*environment* (copy-lexenv *environment*)))
642 (dolist (def definitions)
643 (destructuring-bind (name lambda-list &body body) def
644 (let ((binding (make-binding :name name :type 'macro :value
645 (let ((g!form (gensym)))
647 (destructuring-bind ,lambda-list ,g!form
649 (push-to-lexenv binding *environment* 'function))))
650 (ls-compile `(progn ,@body) *multiple-value-p*)))
653 (defun special-variable-p (x)
654 (and (claimp x 'variable 'special) t))
656 ;;; Wrap CODE to restore the symbol values of the dynamic
657 ;;; bindings. BINDINGS is a list of pairs of the form
658 ;;; (SYMBOL . PLACE), where PLACE is a Javascript variable
659 ;;; name to initialize the symbol value and where to stored
661 (defun let-binding-wrapper (bindings body)
662 (when (null bindings)
663 (return-from let-binding-wrapper body))
666 (code "var tmp;" *newline*
669 (let ((s (ls-compile `(quote ,(car b)))))
670 (code "tmp = " s ".value;" *newline*
671 s ".value = " (cdr b) ";" *newline*
672 (cdr b) " = tmp;" *newline*)))
676 "finally {" *newline*
678 (mapconcat (lambda (b)
679 (let ((s (ls-compile `(quote ,(car b)))))
680 (code s ".value" " = " (cdr b) ";" *newline*)))
684 (define-compilation let (bindings &rest body)
685 (let* ((bindings (mapcar #'ensure-list bindings))
686 (variables (mapcar #'first bindings))
687 (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
688 (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
691 (join (mapcar (lambda (x)
692 (if (special-variable-p x)
693 (let ((v (gvarname x)))
694 (push (cons x v) dynamic-bindings)
696 (translate-variable x)))
700 (let ((body (ls-compile-block body t t)))
701 (code (let-binding-wrapper dynamic-bindings body)))
702 "})(" (join cvalues ",") ")")))
705 ;;; Return the code to initialize BINDING, and push it extending the
706 ;;; current lexical environment if the variable is not special.
707 (defun let*-initialize-value (binding)
708 (let ((var (first binding))
709 (value (second binding)))
710 (if (special-variable-p var)
711 (code (ls-compile `(setq ,var ,value)) ";" *newline*)
712 (let* ((v (gvarname var))
713 (b (make-binding :name var :type 'variable :value v)))
714 (prog1 (code "var " v " = " (ls-compile value) ";" *newline*)
715 (push-to-lexenv b *environment* 'variable))))))
717 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
718 ;;; DOES NOT generate code to initialize the value of the symbols,
719 ;;; unlike let-binding-wrapper.
720 (defun let*-binding-wrapper (symbols body)
722 (return-from let*-binding-wrapper body))
723 (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
724 (remove-if-not #'special-variable-p symbols))))
728 (mapconcat (lambda (b)
729 (let ((s (ls-compile `(quote ,(car b)))))
730 (code "var " (cdr b) " = " s ".value;" *newline*)))
734 "finally {" *newline*
736 (mapconcat (lambda (b)
737 (let ((s (ls-compile `(quote ,(car b)))))
738 (code s ".value" " = " (cdr b) ";" *newline*)))
742 (define-compilation let* (bindings &rest body)
743 (let ((bindings (mapcar #'ensure-list bindings))
744 (*environment* (copy-lexenv *environment*)))
746 (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
747 (body (concat (mapconcat #'let*-initialize-value bindings)
748 (ls-compile-block body t t))))
749 (let*-binding-wrapper specials body)))))
752 (define-compilation block (name &rest body)
753 ;; We use Javascript exceptions to implement non local control
754 ;; transfer. Exceptions has dynamic scoping, so we use a uniquely
755 ;; generated object to identify the block. The instance of a empty
756 ;; array is used to distinguish between nested dynamic Javascript
757 ;; exceptions. See https://github.com/davazp/jscl/issues/64 for
759 (let* ((idvar (gvarname name))
760 (b (make-binding :name name :type 'block :value idvar)))
761 (when *multiple-value-p*
762 (push 'multiple-value (binding-declarations b)))
763 (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
764 (cbody (ls-compile-block body t)))
765 (if (member 'used (binding-declarations b))
768 "var " idvar " = [];" *newline*
771 "catch (cf){" *newline*
772 " if (cf.type == 'block' && cf.id == " idvar ")" *newline*
773 (if *multiple-value-p*
774 " return values.apply(this, forcemv(cf.values));"
775 " return cf.values;")
778 " throw cf;" *newline*
780 (js!selfcall cbody)))))
782 (define-compilation return-from (name &optional value)
783 (let* ((b (lookup-in-lexenv name *environment* 'block))
784 (multiple-value-p (member 'multiple-value (binding-declarations b))))
786 (error "Return from unknown block `~S'." (symbol-name name)))
787 (push 'used (binding-declarations b))
788 ;; The binding value is the name of a variable, whose value is the
789 ;; unique identifier of the block as exception. We can't use the
790 ;; variable name itself, because it could not to be unique, so we
791 ;; capture it in a closure.
793 (when multiple-value-p (code "var values = mv;" *newline*))
796 "id: " (binding-value b) ", "
797 "values: " (ls-compile value multiple-value-p) ", "
798 "message: 'Return from unknown block " (symbol-name name) ".'"
801 (define-compilation catch (id &rest body)
803 "var id = " (ls-compile id) ";" *newline*
805 (code (ls-compile-block body t)) *newline*
807 "catch (cf){" *newline*
808 " if (cf.type == 'catch' && cf.id == id)" *newline*
809 (if *multiple-value-p*
810 " return values.apply(this, forcemv(cf.values));"
811 " return pv.apply(this, forcemv(cf.values));")
814 " throw cf;" *newline*
817 (define-compilation throw (id value)
819 "var values = mv;" *newline*
822 "id: " (ls-compile id) ", "
823 "values: " (ls-compile value t) ", "
824 "message: 'Throw uncatched.'"
828 (or (integerp x) (symbolp x)))
830 (defun declare-tagbody-tags (tbidx body)
831 (let* ((go-tag-counter 0)
833 (mapcar (lambda (label)
834 (let ((tagidx (integer-to-string (incf go-tag-counter))))
835 (make-binding :name label :type 'gotag :value (list tbidx tagidx))))
836 (remove-if-not #'go-tag-p body))))
837 (extend-lexenv bindings *environment* 'gotag)))
839 (define-compilation tagbody (&rest body)
840 ;; Ignore the tagbody if it does not contain any go-tag. We do this
841 ;; because 1) it is easy and 2) many built-in forms expand to a
842 ;; implicit tagbody, so we save some space.
843 (unless (some #'go-tag-p body)
844 (return-from tagbody (ls-compile `(progn ,@body nil))))
845 ;; The translation assumes the first form in BODY is a label
846 (unless (go-tag-p (car body))
847 (push (gensym "START") body))
848 ;; Tagbody compilation
849 (let ((branch (gvarname 'branch))
850 (tbidx (gvarname 'tbidx)))
851 (let ((*environment* (declare-tagbody-tags tbidx body))
853 (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
854 (setq initag (second (binding-value b))))
856 ;; TAGBODY branch to take
857 "var " branch " = " initag ";" *newline*
858 "var " tbidx " = [];" *newline*
860 "while (true) {" *newline*
861 (code "try {" *newline*
862 (code (let ((content ""))
863 (code "switch(" branch "){" *newline*
864 "case " initag ":" *newline*
865 (dolist (form (cdr body) content)
867 (if (not (go-tag-p form))
868 (code (ls-compile form) ";" *newline*)
869 (let ((b (lookup-in-lexenv form *environment* 'gotag)))
870 (code "case " (second (binding-value b)) ":" *newline*)))))
872 " break tbloop;" *newline*
875 "catch (jump) {" *newline*
876 " if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
877 " " branch " = jump.label;" *newline*
879 " throw(jump);" *newline*
882 "return " (ls-compile nil) ";" *newline*))))
884 (define-compilation go (label)
885 (let ((b (lookup-in-lexenv label *environment* 'gotag))
887 ((symbolp label) (symbol-name label))
888 ((integerp label) (integer-to-string label)))))
890 (error "Unknown tag `~S'" label))
894 "id: " (first (binding-value b)) ", "
895 "label: " (second (binding-value b)) ", "
896 "message: 'Attempt to GO to non-existing tag " n "'"
899 (define-compilation unwind-protect (form &rest clean-up)
901 "var ret = " (ls-compile nil) ";" *newline*
903 (code "ret = " (ls-compile form) ";" *newline*)
904 "} finally {" *newline*
905 (code (ls-compile-block clean-up))
907 "return ret;" *newline*))
909 (define-compilation multiple-value-call (func-form &rest forms)
911 "var func = " (ls-compile func-form) ";" *newline*
912 "var args = [" (if *multiple-value-p* "values" "pv") ", 0];" *newline*
915 "var values = mv;" *newline*
917 (mapconcat (lambda (form)
918 (code "vs = " (ls-compile form t) ";" *newline*
919 "if (typeof vs === 'object' && 'multiple-value' in vs)" *newline*
920 (code "args = args.concat(vs);" *newline*)
922 (code "args.push(vs);" *newline*)))
924 "args[1] = args.length-2;" *newline*
925 "return func.apply(window, args);" *newline*) ";" *newline*))
927 (define-compilation multiple-value-prog1 (first-form &rest forms)
929 "var args = " (ls-compile first-form *multiple-value-p*) ";" *newline*
930 (ls-compile-block forms)
931 "return args;" *newline*))
933 (define-transformation backquote (form)
934 (bq-completely-process form))
939 (defvar *builtins* nil)
941 (defmacro define-raw-builtin (name args &body body)
942 ;; Creates a new primitive function `name' with parameters args and
943 ;; @body. The body can access to the local environment through the
944 ;; variable *ENVIRONMENT*.
945 `(push (list ',name (lambda ,args (block ,name ,@body)))
948 (defmacro define-builtin (name args &body body)
949 `(define-raw-builtin ,name ,args
950 (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
953 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
954 (defmacro type-check (decls &body body)
956 ,@(mapcar (lambda (decl)
957 `(code "var " ,(first decl) " = " ,(third decl) ";" *newline*))
959 ,@(mapcar (lambda (decl)
960 `(code "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
961 (code "throw 'The value ' + "
963 " + ' is not a type "
968 (code "return " (progn ,@body) ";" *newline*)))
970 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
971 ;;; a variable which holds a list of forms. It will compile them and
972 ;;; store the result in some Javascript variables. BODY is evaluated
973 ;;; with ARGS bound to the list of these variables to generate the
974 ;;; code which performs the transformation on these variables.
976 (defun variable-arity-call (args function)
978 (error "ARGS must be a non-empty list"))
984 ((floatp x) (push (float-to-string x) fargs))
985 ((numberp x) (push (integer-to-string x) fargs))
986 (t (let ((v (code "x" (incf counter))))
989 (code "var " v " = " (ls-compile x) ";" *newline*
990 "if (typeof " v " !== 'number') throw 'Not a number!';"
992 (js!selfcall prelude (funcall function (reverse fargs)))))
995 (defmacro variable-arity (args &body body)
996 (unless (symbolp args)
997 (error "`~S' is not a symbol." args))
998 `(variable-arity-call ,args
1000 (code "return " ,@body ";" *newline*))))
1002 (defun num-op-num (x op y)
1003 (type-check (("x" "number" x) ("y" "number" y))
1006 (define-raw-builtin + (&rest numbers)
1009 (variable-arity numbers
1010 (join numbers "+"))))
1012 (define-raw-builtin - (x &rest others)
1013 (let ((args (cons x others)))
1014 (variable-arity args
1016 (concat "-" (car args))
1019 (define-raw-builtin * (&rest numbers)
1022 (variable-arity numbers
1023 (join numbers "*"))))
1025 (define-raw-builtin / (x &rest others)
1026 (let ((args (cons x others)))
1027 (variable-arity args
1029 (concat "1 /" (car args))
1032 (define-builtin mod (x y) (num-op-num x "%" y))
1035 (defun comparison-conjuntion (vars op)
1040 (concat (car vars) op (cadr vars)))
1042 (concat (car vars) op (cadr vars)
1044 (comparison-conjuntion (cdr vars) op)))))
1046 (defmacro define-builtin-comparison (op sym)
1047 `(define-raw-builtin ,op (x &rest args)
1048 (let ((args (cons x args)))
1049 (variable-arity args
1050 (js!bool (comparison-conjuntion args ,sym))))))
1052 (define-builtin-comparison > ">")
1053 (define-builtin-comparison < "<")
1054 (define-builtin-comparison >= ">=")
1055 (define-builtin-comparison <= "<=")
1056 (define-builtin-comparison = "==")
1057 (define-builtin-comparison /= "!=")
1059 (define-builtin numberp (x)
1060 (js!bool (code "(typeof (" x ") == \"number\")")))
1062 (define-builtin floor (x)
1063 (type-check (("x" "number" x))
1066 (define-builtin expt (x y)
1067 (type-check (("x" "number" x)
1071 (define-builtin float-to-string (x)
1072 (type-check (("x" "number" x))
1073 "make_lisp_string(x.toString())"))
1075 (define-builtin cons (x y)
1076 (code "({car: " x ", cdr: " y "})"))
1078 (define-builtin consp (x)
1081 "var tmp = " x ";" *newline*
1082 "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1084 (define-builtin car (x)
1086 "var tmp = " x ";" *newline*
1087 "return tmp === " (ls-compile nil)
1088 "? " (ls-compile nil)
1089 ": tmp.car;" *newline*))
1091 (define-builtin cdr (x)
1093 "var tmp = " x ";" *newline*
1094 "return tmp === " (ls-compile nil) "? "
1096 ": tmp.cdr;" *newline*))
1098 (define-builtin rplaca (x new)
1099 (type-check (("x" "object" x))
1100 (code "(x.car = " new ", x)")))
1102 (define-builtin rplacd (x new)
1103 (type-check (("x" "object" x))
1104 (code "(x.cdr = " new ", x)")))
1106 (define-builtin symbolp (x)
1107 (js!bool (code "(" x " instanceof Symbol)")))
1109 (define-builtin make-symbol (name)
1110 (code "(new Symbol(" name "))"))
1112 (define-builtin symbol-name (x)
1113 (code "(" x ").name"))
1115 (define-builtin set (symbol value)
1116 (code "(" symbol ").value = " value))
1118 (define-builtin fset (symbol value)
1119 (code "(" symbol ").fvalue = " value))
1121 (define-builtin boundp (x)
1122 (js!bool (code "(" x ".value !== undefined)")))
1124 (define-builtin fboundp (x)
1125 (js!bool (code "(" x ".fvalue !== undefined)")))
1127 (define-builtin symbol-value (x)
1129 "var symbol = " x ";" *newline*
1130 "var value = symbol.value;" *newline*
1131 "if (value === undefined) throw \"Variable `\" + xstring(symbol.name) + \"' is unbound.\";" *newline*
1132 "return value;" *newline*))
1134 (define-builtin symbol-function (x)
1136 "var symbol = " x ";" *newline*
1137 "var func = symbol.fvalue;" *newline*
1138 "if (func === undefined) throw \"Function `\" + xstring(symbol.name) + \"' is undefined.\";" *newline*
1139 "return func;" *newline*))
1141 (define-builtin symbol-plist (x)
1142 (code "((" x ").plist || " (ls-compile nil) ")"))
1144 (define-builtin lambda-code (x)
1145 (code "make_lisp_string((" x ").toString())"))
1147 (define-builtin eq (x y)
1148 (js!bool (code "(" x " === " y ")")))
1150 (define-builtin char-code (x)
1151 (type-check (("x" "string" x))
1152 "char_to_codepoint(x)"))
1154 (define-builtin code-char (x)
1155 (type-check (("x" "number" x))
1156 "char_from_codepoint(x)"))
1158 (define-builtin characterp (x)
1161 "var x = " x ";" *newline*
1162 "return (typeof(" x ") == \"string\") && (x.length == 1 || x.length == 2);")))
1164 (define-builtin char-upcase (x)
1165 (code "safe_char_upcase(" x ")"))
1167 (define-builtin char-downcase (x)
1168 (code "safe_char_downcase(" x ")"))
1170 (define-builtin stringp (x)
1173 "var x = " x ";" *newline*
1174 "return typeof(x) == 'object' && 'length' in x && x.stringp == 1;")))
1176 (define-raw-builtin funcall (func &rest args)
1178 "var f = " (ls-compile func) ";" *newline*
1179 "return (typeof f === 'function'? f: f.fvalue)("
1180 (join (list* (if *multiple-value-p* "values" "pv")
1181 (integer-to-string (length args))
1182 (mapcar #'ls-compile args))
1186 (define-raw-builtin apply (func &rest args)
1188 (code "(" (ls-compile func) ")()")
1189 (let ((args (butlast args))
1190 (last (car (last args))))
1192 "var f = " (ls-compile func) ";" *newline*
1193 "var args = [" (join (list* (if *multiple-value-p* "values" "pv")
1194 (integer-to-string (length args))
1195 (mapcar #'ls-compile args))
1198 "var tail = (" (ls-compile last) ");" *newline*
1199 "while (tail != " (ls-compile nil) "){" *newline*
1200 " args.push(tail.car);" *newline*
1201 " args[1] += 1;" *newline*
1202 " tail = tail.cdr;" *newline*
1204 "return (typeof f === 'function'? f : f.fvalue).apply(this, args);" *newline*))))
1206 (define-builtin js-eval (string)
1207 (if *multiple-value-p*
1209 "var v = globalEval(xstring(" string "));" *newline*
1210 "return values.apply(this, forcemv(v));" *newline*)
1211 (code "globalEval(xstring(" string "))")))
1213 (define-builtin %throw (string)
1214 (js!selfcall "throw " string ";" *newline*))
1216 (define-builtin functionp (x)
1217 (js!bool (code "(typeof " x " == 'function')")))
1219 (define-builtin %write-string (x)
1220 (code "lisp.write(" x ")"))
1223 ;;; Storage vectors. They are used to implement arrays and (in the
1224 ;;; future) structures.
1226 (define-builtin storage-vector-p (x)
1229 "var x = " x ";" *newline*
1230 "return typeof x === 'object' && 'length' in x;")))
1232 (define-builtin make-storage-vector (n)
1234 "var r = [];" *newline*
1235 "r.length = " n ";" *newline*
1236 "return r;" *newline*))
1238 (define-builtin storage-vector-size (x)
1241 (define-builtin resize-storage-vector (vector new-size)
1242 (code "(" vector ".length = " new-size ")"))
1244 (define-builtin storage-vector-ref (vector n)
1246 "var x = " "(" vector ")[" n "];" *newline*
1247 "if (x === undefined) throw 'Out of range';" *newline*
1248 "return x;" *newline*))
1250 (define-builtin storage-vector-set (vector n value)
1252 "var x = " vector ";" *newline*
1253 "var i = " n ";" *newline*
1254 "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
1255 "return x[i] = " value ";" *newline*))
1257 (define-builtin concatenate-storage-vector (sv1 sv2)
1259 "var sv1 = " sv1 ";" *newline*
1260 "var r = sv1.concat(" sv2 ");" *newline*
1261 "r.type = sv1.type;" *newline*
1262 "r.stringp = sv1.stringp;" *newline*
1263 "return r;" *newline*))
1265 (define-builtin get-internal-real-time ()
1266 "(new Date()).getTime()")
1268 (define-builtin values-array (array)
1269 (if *multiple-value-p*
1270 (code "values.apply(this, " array ")")
1271 (code "pv.apply(this, " array ")")))
1273 (define-raw-builtin values (&rest args)
1274 (if *multiple-value-p*
1275 (code "values(" (join (mapcar #'ls-compile args) ", ") ")")
1276 (code "pv(" (join (mapcar #'ls-compile args) ", ") ")")))
1281 (define-builtin new () "{}")
1283 (define-raw-builtin oget* (object key &rest keys)
1285 "var tmp = (" (ls-compile object) ")[xstring(" (ls-compile key) ")];" *newline*
1286 (mapconcat (lambda (key)
1287 (code "if (tmp === undefined) return " (ls-compile nil) ";" *newline*
1288 "tmp = tmp[xstring(" (ls-compile key) ")];" *newline*))
1290 "return tmp === undefined? " (ls-compile nil) " : tmp;" *newline*))
1292 (define-raw-builtin oset* (value object key &rest keys)
1293 (let ((keys (cons key keys)))
1295 "var obj = " (ls-compile object) ";" *newline*
1296 (mapconcat (lambda (key)
1297 (code "obj = obj[xstring(" (ls-compile key) ")];"
1298 "if (obj === undefined) throw 'Impossible to set Javascript property.';" *newline*))
1300 "var tmp = obj[xstring(" (ls-compile (car (last keys))) ")] = " (ls-compile value) ";" *newline*
1301 "return tmp === undefined? " (ls-compile nil) " : tmp;" *newline*)))
1303 (define-raw-builtin oget (object key &rest keys)
1304 (code "js_to_lisp(" (ls-compile `(oget* ,object ,key ,@keys)) ")"))
1306 (define-raw-builtin oset (value object key &rest keys)
1307 (ls-compile `(oset* (lisp-to-js ,value) ,object ,key ,@keys)))
1309 (define-builtin objectp (x)
1310 (js!bool (code "(typeof (" x ") === 'object')")))
1312 (define-builtin lisp-to-js (x) (code "lisp_to_js(" x ")"))
1313 (define-builtin js-to-lisp (x) (code "js_to_lisp(" x ")"))
1316 (define-builtin in (key object)
1317 (js!bool (code "(xstring(" key ") in (" object "))")))
1319 (define-builtin map-for-in (function object)
1321 "var f = " function ";" *newline*
1322 "var g = (typeof f === 'function' ? f : f.fvalue);" *newline*
1323 "var o = " object ";" *newline*
1324 "for (var key in o){" *newline*
1325 (code "g(" (if *multiple-value-p* "values" "pv") ", 1, o[key]);" *newline*)
1327 " return " (ls-compile nil) ";" *newline*))
1329 (define-compilation %js-vref (var)
1330 (code "js_to_lisp(" var ")"))
1332 (define-compilation %js-vset (var val)
1333 (code "(" var " = lisp_to_js(" (ls-compile val) "))"))
1335 (define-setf-expander %js-vref (var)
1336 (let ((new-value (gensym)))
1337 (unless (stringp var)
1338 (error "`~S' is not a string." var))
1342 `(%js-vset ,var ,new-value)
1347 (defvar *macroexpander-cache*
1348 (make-hash-table :test #'eq))
1350 (defun !macro-function (symbol)
1351 (unless (symbolp symbol)
1352 (error "`~S' is not a symbol." symbol))
1353 (let ((b (lookup-in-lexenv symbol *environment* 'function)))
1354 (if (and b (eq (binding-type b) 'macro))
1355 (let ((expander (binding-value b)))
1358 ((gethash b *macroexpander-cache*)
1359 (setq expander (gethash b *macroexpander-cache*)))
1361 (let ((compiled (eval expander)))
1362 ;; The list representation are useful while
1363 ;; bootstrapping, as we can dump the definition of the
1364 ;; macros easily, but they are slow because we have to
1365 ;; evaluate them and compile them now and again. So, let
1366 ;; us replace the list representation version of the
1367 ;; function with the compiled one.
1369 #+jscl (setf (binding-value b) compiled)
1370 #-jscl (setf (gethash b *macroexpander-cache*) compiled)
1371 (setq expander compiled))))
1375 (defun !macroexpand-1 (form)
1378 (let ((b (lookup-in-lexenv form *environment* 'variable)))
1379 (if (and b (eq (binding-type b) 'macro))
1380 (values (binding-value b) t)
1381 (values form nil))))
1382 ((and (consp form) (symbolp (car form)))
1383 (let ((macrofun (!macro-function (car form))))
1385 (values (funcall macrofun (cdr form)) t)
1386 (values form nil))))
1388 (values form nil))))
1390 (defun compile-funcall (function args)
1391 (let* ((values-funcs (if *multiple-value-p* "values" "pv"))
1392 (arglist (concat "(" (join (list* values-funcs
1393 (integer-to-string (length args))
1394 (mapcar #'ls-compile args)) ", ") ")")))
1395 (unless (or (symbolp function)
1396 (and (consp function)
1397 (member (car function) '(lambda oget))))
1398 (error "Bad function designator `~S'" function))
1400 ((translate-function function)
1401 (concat (translate-function function) arglist))
1402 ((and (symbolp function)
1403 #+jscl (eq (symbol-package function) (find-package "COMMON-LISP"))
1405 (code (ls-compile `',function) ".fvalue" arglist))
1406 #+jscl((symbolp function)
1407 (code (ls-compile `#',function) arglist))
1408 ((and (consp function) (eq (car function) 'lambda))
1409 (code (ls-compile `#',function) arglist))
1410 ((and (consp function) (eq (car function) 'oget))
1411 (code (ls-compile function) arglist))
1413 (error "Bad function descriptor")))))
1415 (defun ls-compile-block (sexps &optional return-last-p decls-allowed-p)
1416 (multiple-value-bind (sexps decls)
1417 (parse-body sexps :declarations decls-allowed-p)
1418 (declare (ignore decls))
1420 (code (ls-compile-block (butlast sexps) nil decls-allowed-p)
1421 "return " (ls-compile (car (last sexps)) *multiple-value-p*) ";")
1423 (mapcar #'ls-compile sexps)
1424 (concat ";" *newline*)))))
1426 (defun ls-compile (sexp &optional multiple-value-p)
1427 (multiple-value-bind (sexp expandedp) (!macroexpand-1 sexp)
1429 (return-from ls-compile (ls-compile sexp multiple-value-p)))
1430 ;; The expression has been macroexpanded. Now compile it!
1431 (let ((*multiple-value-p* multiple-value-p))
1434 (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1436 ((and b (not (member 'special (binding-declarations b))))
1438 ((or (keywordp sexp)
1439 (and b (member 'constant (binding-declarations b))))
1440 (code (ls-compile `',sexp) ".value"))
1442 (ls-compile `(symbol-value ',sexp))))))
1443 ((or (integerp sexp) (floatp sexp) (characterp sexp) (stringp sexp) (arrayp sexp))
1446 (let ((name (car sexp))
1450 ((assoc name *compilations*)
1451 (let ((comp (second (assoc name *compilations*))))
1453 ;; Built-in functions
1454 ((and (assoc name *builtins*)
1455 (not (claimp name 'function 'notinline)))
1456 (let ((comp (second (assoc name *builtins*))))
1459 (compile-funcall name args)))))
1461 (error "How should I compile `~S'?" sexp))))))
1464 (defvar *compile-print-toplevels* nil)
1466 (defun truncate-string (string &optional (width 60))
1467 (let ((n (or (position #\newline string)
1468 (min width (length string)))))
1469 (subseq string 0 n)))
1471 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
1472 (let ((*toplevel-compilations* nil))
1474 ((and (consp sexp) (eq (car sexp) 'progn))
1475 (let ((subs (mapcar (lambda (s)
1476 (ls-compile-toplevel s t))
1480 (when *compile-print-toplevels*
1481 (let ((form-string (prin1-to-string sexp)))
1482 (format t "Compiling ~a..." (truncate-string form-string))))
1483 (let ((code (ls-compile sexp multiple-value-p)))
1484 (code (join-trailing (get-toplevel-compilations)
1485 (code ";" *newline*))
1487 (code code ";" *newline*))))))))