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 null-or-empty-p (x)
123 (defun get-toplevel-compilations ()
124 (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
126 (defun %compile-defmacro (name lambda)
127 (toplevel-compilation (ls-compile `',name))
128 (let ((binding (make-binding :name name :type 'macro :value lambda)))
129 (push-to-lexenv binding *environment* 'function))
132 (defun global-binding (name type namespace)
133 (or (lookup-in-lexenv name *environment* namespace)
134 (let ((b (make-binding :name name :type type :value nil)))
135 (push-to-lexenv b *environment* namespace)
138 (defun claimp (symbol namespace claim)
139 (let ((b (lookup-in-lexenv symbol *environment* namespace)))
140 (and b (member claim (binding-declarations b)))))
142 (defun !proclaim (decl)
145 (dolist (name (cdr decl))
146 (let ((b (global-binding name 'variable 'variable)))
147 (push 'special (binding-declarations b)))))
149 (dolist (name (cdr decl))
150 (let ((b (global-binding name 'function 'function)))
151 (push 'notinline (binding-declarations b)))))
153 (dolist (name (cdr decl))
154 (let ((b (global-binding name 'variable 'variable)))
155 (push 'constant (binding-declarations b)))))))
158 (fset 'proclaim #'!proclaim)
160 (defun %define-symbol-macro (name expansion)
161 (let ((b (make-binding :name name :type 'macro :value expansion)))
162 (push-to-lexenv b *environment* 'variable)
166 (defmacro define-symbol-macro (name expansion)
167 `(%define-symbol-macro ',name ',expansion))
172 (defvar *compilations* nil)
174 (defmacro define-compilation (name args &body body)
175 ;; Creates a new primitive `name' with parameters args and
176 ;; @body. The body can access to the local environment through the
177 ;; variable *ENVIRONMENT*.
178 `(push (list ',name (lambda ,args (block ,name ,@body)))
181 (define-compilation if (condition true &optional false)
182 (code "(" (ls-compile condition) " !== " (ls-compile nil)
183 " ? " (ls-compile true *multiple-value-p*)
184 " : " (ls-compile false *multiple-value-p*)
187 (defvar *ll-keywords* '(&optional &rest &key))
189 (defun list-until-keyword (list)
190 (if (or (null list) (member (car list) *ll-keywords*))
192 (cons (car list) (list-until-keyword (cdr list)))))
194 (defun ll-section (keyword ll)
195 (list-until-keyword (cdr (member keyword ll))))
197 (defun ll-required-arguments (ll)
198 (list-until-keyword ll))
200 (defun ll-optional-arguments-canonical (ll)
201 (mapcar #'ensure-list (ll-section '&optional ll)))
203 (defun ll-optional-arguments (ll)
204 (mapcar #'car (ll-optional-arguments-canonical ll)))
206 (defun ll-rest-argument (ll)
207 (let ((rest (ll-section '&rest ll)))
209 (error "Bad lambda-list `~S'." ll))
212 (defun ll-keyword-arguments-canonical (ll)
213 (flet ((canonicalize (keyarg)
214 ;; Build a canonical keyword argument descriptor, filling
215 ;; the optional fields. The result is a list of the form
216 ;; ((keyword-name var) init-form).
217 (let ((arg (ensure-list keyarg)))
218 (cons (if (listp (car arg))
220 (list (intern (symbol-name (car arg)) "KEYWORD") (car arg)))
222 (mapcar #'canonicalize (ll-section '&key ll))))
224 (defun ll-keyword-arguments (ll)
225 (mapcar (lambda (keyarg) (second (first keyarg)))
226 (ll-keyword-arguments-canonical ll)))
228 (defun ll-svars (lambda-list)
231 (ll-keyword-arguments-canonical lambda-list)
232 (ll-optional-arguments-canonical lambda-list))))
233 (remove nil (mapcar #'third args))))
235 (defun lambda-name/docstring-wrapper (name docstring &rest strs)
236 (if (or name docstring)
238 "var func = " (join strs) ";" *newline*
240 (code "func.fname = " (js-escape-string name) ";" *newline*))
242 (code "func.docstring = " (js-escape-string docstring) ";" *newline*))
243 "return func;" *newline*)
244 (apply #'code strs)))
246 (defun lambda-check-argument-count
247 (n-required-arguments n-optional-arguments rest-p)
248 ;; Note: Remember that we assume that the number of arguments of a
249 ;; call is at least 1 (the values argument).
250 (let ((min n-required-arguments)
251 (max (if rest-p 'n/a (+ n-required-arguments n-optional-arguments))))
253 ;; Special case: a positive exact number of arguments.
254 (when (and (< 0 min) (eql min max))
255 (return (code "checkArgs(nargs, " min ");" *newline*)))
259 (code "checkArgsAtLeast(nargs, " min ");" *newline*))
261 (code "checkArgsAtMost(nargs, " max ");" *newline*))))))
263 (defun compile-lambda-optional (ll)
264 (let* ((optional-arguments (ll-optional-arguments-canonical ll))
265 (n-required-arguments (length (ll-required-arguments ll)))
266 (n-optional-arguments (length optional-arguments)))
267 (when optional-arguments
268 (code "switch(nargs){" *newline*
272 (while (< idx n-optional-arguments)
273 (let ((arg (nth idx optional-arguments)))
274 (push (code "case " (+ idx n-required-arguments) ":" *newline*
275 (code (translate-variable (car arg))
277 (ls-compile (cadr arg)) ";" *newline*)
279 (code (translate-variable (third arg))
285 (push (code "default: break;" *newline*) cases)
286 (join (reverse cases))))
289 (defun compile-lambda-rest (ll)
290 (let ((n-required-arguments (length (ll-required-arguments ll)))
291 (n-optional-arguments (length (ll-optional-arguments ll)))
292 (rest-argument (ll-rest-argument ll)))
294 (let ((js!rest (translate-variable rest-argument)))
295 (code "var " js!rest "= " (ls-compile nil) ";" *newline*
296 "for (var i = nargs-1; i>=" (+ n-required-arguments n-optional-arguments)
298 (code js!rest " = {car: arguments[i+2], cdr: " js!rest "};" *newline*))))))
300 (defun compile-lambda-parse-keywords (ll)
301 (let ((n-required-arguments
302 (length (ll-required-arguments ll)))
303 (n-optional-arguments
304 (length (ll-optional-arguments ll)))
306 (ll-keyword-arguments-canonical ll)))
309 (mapconcat (lambda (arg)
310 (let ((var (second (car arg))))
311 (code "var " (translate-variable var) "; " *newline*
313 (code "var " (translate-variable (third arg))
314 " = " (ls-compile nil)
318 (flet ((parse-keyword (keyarg)
319 ;; ((keyword-name var) init-form)
320 (code "for (i=" (+ n-required-arguments n-optional-arguments)
321 "; i<nargs; i+=2){" *newline*
323 "if (arguments[i+2] === " (ls-compile (caar keyarg)) "){" *newline*
324 (code (translate-variable (cadr (car keyarg)))
327 (let ((svar (third keyarg)))
329 (code (translate-variable svar) " = " (ls-compile t) ";" *newline*)))
334 "if (i == nargs){" *newline*
335 (code (translate-variable (cadr (car keyarg))) " = " (ls-compile (cadr keyarg)) ";" *newline*)
337 (when keyword-arguments
338 (code "var i;" *newline*
339 (mapconcat #'parse-keyword keyword-arguments))))
340 ;; Check for unknown keywords
341 (when keyword-arguments
342 (code "var start = " (+ n-required-arguments n-optional-arguments) ";" *newline*
343 "if ((nargs - start) % 2 == 1){" *newline*
344 (code "throw 'Odd number of keyword arguments';" *newline*)
346 "for (i = start; i<nargs; i+=2){" *newline*
348 (join (mapcar (lambda (x)
349 (concat "arguments[i+2] !== " (ls-compile (caar x))))
354 "throw 'Unknown keyword argument ' + xstring(arguments[i+2].name);" *newline*))
357 (defun parse-lambda-list (ll)
358 (values (ll-required-arguments ll)
359 (ll-optional-arguments ll)
360 (ll-keyword-arguments ll)
361 (ll-rest-argument ll)))
363 ;;; Process BODY for declarations and/or docstrings. Return as
364 ;;; multiple values the BODY without docstrings or declarations, the
365 ;;; list of declaration forms and the docstring.
366 (defun parse-body (body &key declarations docstring)
367 (let ((value-declarations)
369 ;; Parse declarations
371 (do* ((rest body (cdr rest))
372 (form (car rest) (car rest)))
373 ((or (atom form) (not (eq (car form) 'declare)))
375 (push form value-declarations)))
379 (not (null (cdr body))))
380 (setq value-docstring (car body))
381 (setq body (cdr body)))
382 (values body value-declarations value-docstring)))
384 ;;; Compile a lambda function with lambda list LL and body BODY. If
385 ;;; NAME is given, it should be a constant string and it will become
386 ;;; the name of the function. If BLOCK is non-NIL, a named block is
387 ;;; created around the body. NOTE: No block (even anonymous) is
388 ;;; created if BLOCk is NIL.
389 (defun compile-lambda (ll body &key name block)
390 (multiple-value-bind (required-arguments
394 (parse-lambda-list ll)
395 (multiple-value-bind (body decls documentation)
396 (parse-body body :declarations t :docstring t)
397 (declare (ignore decls))
398 (let ((n-required-arguments (length required-arguments))
399 (n-optional-arguments (length optional-arguments))
400 (*environment* (extend-local-env
401 (append (ensure-list rest-argument)
406 (lambda-name/docstring-wrapper name documentation
408 (join (list* "values"
410 (mapcar #'translate-variable
411 (append required-arguments optional-arguments)))
415 ;; Check number of arguments
416 (lambda-check-argument-count n-required-arguments
418 (or rest-argument keyword-arguments))
419 (compile-lambda-optional ll)
420 (compile-lambda-rest ll)
421 (compile-lambda-parse-keywords ll)
422 (let ((*multiple-value-p* t))
424 (ls-compile-block `((block ,block ,@body)) t)
425 (ls-compile-block body t))))
429 (defun setq-pair (var val)
430 (let ((b (lookup-in-lexenv var *environment* 'variable)))
433 (eq (binding-type b) 'variable)
434 (not (member 'special (binding-declarations b)))
435 (not (member 'constant (binding-declarations b))))
436 (code (binding-value b) " = " (ls-compile val)))
437 ((and b (eq (binding-type b) 'macro))
438 (ls-compile `(setf ,var ,val)))
440 (ls-compile `(set ',var ,val))))))
443 (define-compilation setq (&rest pairs)
446 (return-from setq (ls-compile nil)))
452 (error "Odd pairs in SETQ"))
455 (concat (setq-pair (car pairs) (cadr pairs))
456 (if (null (cddr pairs)) "" ", ")))
457 (setq pairs (cddr pairs)))))
458 (code "(" result ")")))
461 ;;; Compilation of literals an object dumping
463 ;;; BOOTSTRAP MAGIC: We record the macro definitions as lists during
464 ;;; the bootstrap. Once everything is compiled, we want to dump the
465 ;;; whole global environment to the output file to reproduce it in the
466 ;;; run-time. However, the environment must contain expander functions
467 ;;; rather than lists. We do not know how to dump function objects
468 ;;; itself, so we mark the list definitions with this object and the
469 ;;; compiler will be called when this object has to be dumped.
470 ;;; Backquote/unquote does a similar magic, but this use is exclusive.
472 ;;; Indeed, perhaps to compile the object other macros need to be
473 ;;; evaluated. For this reason we define a valid macro-function for
475 (defvar *magic-unquote-marker* (gensym "MAGIC-UNQUOTE"))
477 (setf (macro-function *magic-unquote-marker*)
478 (lambda (form &optional environment)
479 (declare (ignore environment))
482 (defvar *literal-table* nil)
483 (defvar *literal-counter* 0)
486 (code "l" (incf *literal-counter*)))
488 (defun dump-symbol (symbol)
490 (let ((package (symbol-package symbol)))
491 (if (eq package (find-package "KEYWORD"))
492 (code "(new Symbol(" (dump-string (symbol-name symbol)) ", " (dump-string (package-name package)) "))")
493 (code "(new Symbol(" (dump-string (symbol-name symbol)) "))")))
495 (let ((package (symbol-package symbol)))
497 (code "(new Symbol(" (dump-string (symbol-name symbol)) "))")
498 (ls-compile `(intern ,(symbol-name symbol) ,(package-name package))))))
500 (defun dump-cons (cons)
501 (let ((head (butlast cons))
504 (join-trailing (mapcar (lambda (x) (literal x t)) head) ",")
505 (literal (car tail) t)
507 (literal (cdr tail) t)
510 (defun dump-array (array)
511 (let ((elements (vector-to-list array)))
512 (concat "[" (join (mapcar #'literal elements) ", ") "]")))
514 (defun dump-string (string)
515 (code "make_lisp_string(" (js-escape-string string) ")"))
517 (defun literal (sexp &optional recursive)
519 ((integerp sexp) (integer-to-string sexp))
520 ((floatp sexp) (float-to-string sexp))
521 ((characterp sexp) (js-escape-string (string sexp)))
523 (or (cdr (assoc sexp *literal-table* :test #'eql))
524 (let ((dumped (typecase sexp
525 (symbol (dump-symbol sexp))
526 (string (dump-string sexp))
528 ;; BOOTSTRAP MAGIC: See the root file
529 ;; jscl.lisp and the function
530 ;; `dump-global-environment' for futher
532 (if (eq (car sexp) *magic-unquote-marker*)
533 (ls-compile (second sexp))
535 (array (dump-array sexp)))))
536 (if (and recursive (not (symbolp sexp)))
538 (let ((jsvar (genlit)))
539 (push (cons sexp jsvar) *literal-table*)
540 (toplevel-compilation (code "var " jsvar " = " dumped))
541 (when (keywordp sexp)
542 (toplevel-compilation (code jsvar ".value = " jsvar)))
546 (define-compilation quote (sexp)
549 (define-compilation %while (pred &rest body)
551 "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
552 (code (ls-compile-block body))
554 "return " (ls-compile nil) ";" *newline*))
556 (define-compilation function (x)
558 ((and (listp x) (eq (car x) 'lambda))
559 (compile-lambda (cadr x) (cddr x)))
560 ((and (listp x) (eq (car x) 'named-lambda))
561 ;; TODO: destructuring-bind now! Do error checking manually is
563 (let ((name (cadr x))
566 (compile-lambda ll body
567 :name (symbol-name name)
570 (let ((b (lookup-in-lexenv x *environment* 'function)))
573 (ls-compile `(symbol-function ',x)))))))
576 (defun make-function-binding (fname)
577 (make-binding :name fname :type 'function :value (gvarname fname)))
579 (defun compile-function-definition (list)
580 (compile-lambda (car list) (cdr list)))
582 (defun translate-function (name)
583 (let ((b (lookup-in-lexenv name *environment* 'function)))
584 (and b (binding-value b))))
586 (define-compilation flet (definitions &rest body)
587 (let* ((fnames (mapcar #'car definitions))
588 (cfuncs (mapcar (lambda (def)
589 (compile-lambda (cadr def)
594 (extend-lexenv (mapcar #'make-function-binding fnames)
598 (join (mapcar #'translate-function fnames) ",")
600 (let ((body (ls-compile-block body t)))
602 "})(" (join cfuncs ",") ")")))
604 (define-compilation labels (definitions &rest body)
605 (let* ((fnames (mapcar #'car definitions))
607 (extend-lexenv (mapcar #'make-function-binding fnames)
611 (mapconcat (lambda (func)
612 (code "var " (translate-function (car func))
613 " = " (compile-lambda (cadr func)
614 `((block ,(car func) ,@(cddr func))))
617 (ls-compile-block body t))))
620 (defvar *compiling-file* nil)
621 (define-compilation eval-when-compile (&rest body)
624 (eval (cons 'progn body))
626 (ls-compile `(progn ,@body))))
628 (defmacro define-transformation (name args form)
629 `(define-compilation ,name ,args
632 (define-compilation progn (&rest body)
633 (if (null (cdr body))
634 (ls-compile (car body) *multiple-value-p*)
637 (remove-if #'null-or-empty-p
639 (mapcar #'ls-compile (butlast body))
640 (list (ls-compile (car (last body)) t))))
644 (define-compilation macrolet (definitions &rest body)
645 (let ((*environment* (copy-lexenv *environment*)))
646 (dolist (def definitions)
647 (destructuring-bind (name lambda-list &body body) def
648 (let ((binding (make-binding :name name :type 'macro :value
649 (let ((g!form (gensym)))
651 (destructuring-bind ,lambda-list ,g!form
653 (push-to-lexenv binding *environment* 'function))))
654 (ls-compile `(progn ,@body) *multiple-value-p*)))
657 (defun special-variable-p (x)
658 (and (claimp x 'variable 'special) t))
660 ;;; Wrap CODE to restore the symbol values of the dynamic
661 ;;; bindings. BINDINGS is a list of pairs of the form
662 ;;; (SYMBOL . PLACE), where PLACE is a Javascript variable
663 ;;; name to initialize the symbol value and where to stored
665 (defun let-binding-wrapper (bindings body)
666 (when (null bindings)
667 (return-from let-binding-wrapper body))
670 (code "var tmp;" *newline*
673 (let ((s (ls-compile `(quote ,(car b)))))
674 (code "tmp = " s ".value;" *newline*
675 s ".value = " (cdr b) ";" *newline*
676 (cdr b) " = tmp;" *newline*)))
680 "finally {" *newline*
682 (mapconcat (lambda (b)
683 (let ((s (ls-compile `(quote ,(car b)))))
684 (code s ".value" " = " (cdr b) ";" *newline*)))
688 (define-compilation let (bindings &rest body)
689 (let* ((bindings (mapcar #'ensure-list bindings))
690 (variables (mapcar #'first bindings))
691 (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
692 (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
695 (join (mapcar (lambda (x)
696 (if (special-variable-p x)
697 (let ((v (gvarname x)))
698 (push (cons x v) dynamic-bindings)
700 (translate-variable x)))
704 (let ((body (ls-compile-block body t t)))
705 (code (let-binding-wrapper dynamic-bindings body)))
706 "})(" (join cvalues ",") ")")))
709 ;;; Return the code to initialize BINDING, and push it extending the
710 ;;; current lexical environment if the variable is not special.
711 (defun let*-initialize-value (binding)
712 (let ((var (first binding))
713 (value (second binding)))
714 (if (special-variable-p var)
715 (code (ls-compile `(setq ,var ,value)) ";" *newline*)
716 (let* ((v (gvarname var))
717 (b (make-binding :name var :type 'variable :value v)))
718 (prog1 (code "var " v " = " (ls-compile value) ";" *newline*)
719 (push-to-lexenv b *environment* 'variable))))))
721 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
722 ;;; DOES NOT generate code to initialize the value of the symbols,
723 ;;; unlike let-binding-wrapper.
724 (defun let*-binding-wrapper (symbols body)
726 (return-from let*-binding-wrapper body))
727 (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
728 (remove-if-not #'special-variable-p symbols))))
732 (mapconcat (lambda (b)
733 (let ((s (ls-compile `(quote ,(car b)))))
734 (code "var " (cdr b) " = " s ".value;" *newline*)))
738 "finally {" *newline*
740 (mapconcat (lambda (b)
741 (let ((s (ls-compile `(quote ,(car b)))))
742 (code s ".value" " = " (cdr b) ";" *newline*)))
746 (define-compilation let* (bindings &rest body)
747 (let ((bindings (mapcar #'ensure-list bindings))
748 (*environment* (copy-lexenv *environment*)))
750 (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
751 (body (concat (mapconcat #'let*-initialize-value bindings)
752 (ls-compile-block body t t))))
753 (let*-binding-wrapper specials body)))))
756 (define-compilation block (name &rest body)
757 ;; We use Javascript exceptions to implement non local control
758 ;; transfer. Exceptions has dynamic scoping, so we use a uniquely
759 ;; generated object to identify the block. The instance of a empty
760 ;; array is used to distinguish between nested dynamic Javascript
761 ;; exceptions. See https://github.com/davazp/jscl/issues/64 for
763 (let* ((idvar (gvarname name))
764 (b (make-binding :name name :type 'block :value idvar)))
765 (when *multiple-value-p*
766 (push 'multiple-value (binding-declarations b)))
767 (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
768 (cbody (ls-compile-block body t)))
769 (if (member 'used (binding-declarations b))
772 "var " idvar " = [];" *newline*
775 "catch (cf){" *newline*
776 " if (cf.type == 'block' && cf.id == " idvar ")" *newline*
777 (if *multiple-value-p*
778 " return values.apply(this, forcemv(cf.values));"
779 " return cf.values;")
782 " throw cf;" *newline*
784 (js!selfcall cbody)))))
786 (define-compilation return-from (name &optional value)
787 (let* ((b (lookup-in-lexenv name *environment* 'block))
788 (multiple-value-p (member 'multiple-value (binding-declarations b))))
790 (error "Return from unknown block `~S'." (symbol-name name)))
791 (push 'used (binding-declarations b))
792 ;; The binding value is the name of a variable, whose value is the
793 ;; unique identifier of the block as exception. We can't use the
794 ;; variable name itself, because it could not to be unique, so we
795 ;; capture it in a closure.
797 (when multiple-value-p (code "var values = mv;" *newline*))
800 "id: " (binding-value b) ", "
801 "values: " (ls-compile value multiple-value-p) ", "
802 "message: 'Return from unknown block " (symbol-name name) ".'"
805 (define-compilation catch (id &rest body)
807 "var id = " (ls-compile id) ";" *newline*
809 (code (ls-compile-block body t)) *newline*
811 "catch (cf){" *newline*
812 " if (cf.type == 'catch' && cf.id == id)" *newline*
813 (if *multiple-value-p*
814 " return values.apply(this, forcemv(cf.values));"
815 " return pv.apply(this, forcemv(cf.values));")
818 " throw cf;" *newline*
821 (define-compilation throw (id value)
823 "var values = mv;" *newline*
826 "id: " (ls-compile id) ", "
827 "values: " (ls-compile value t) ", "
828 "message: 'Throw uncatched.'"
832 (or (integerp x) (symbolp x)))
834 (defun declare-tagbody-tags (tbidx body)
835 (let* ((go-tag-counter 0)
837 (mapcar (lambda (label)
838 (let ((tagidx (integer-to-string (incf go-tag-counter))))
839 (make-binding :name label :type 'gotag :value (list tbidx tagidx))))
840 (remove-if-not #'go-tag-p body))))
841 (extend-lexenv bindings *environment* 'gotag)))
843 (define-compilation tagbody (&rest body)
844 ;; Ignore the tagbody if it does not contain any go-tag. We do this
845 ;; because 1) it is easy and 2) many built-in forms expand to a
846 ;; implicit tagbody, so we save some space.
847 (unless (some #'go-tag-p body)
848 (return-from tagbody (ls-compile `(progn ,@body nil))))
849 ;; The translation assumes the first form in BODY is a label
850 (unless (go-tag-p (car body))
851 (push (gensym "START") body))
852 ;; Tagbody compilation
853 (let ((branch (gvarname 'branch))
854 (tbidx (gvarname 'tbidx)))
855 (let ((*environment* (declare-tagbody-tags tbidx body))
857 (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
858 (setq initag (second (binding-value b))))
860 ;; TAGBODY branch to take
861 "var " branch " = " initag ";" *newline*
862 "var " tbidx " = [];" *newline*
864 "while (true) {" *newline*
865 (code "try {" *newline*
866 (code (let ((content ""))
867 (code "switch(" branch "){" *newline*
868 "case " initag ":" *newline*
869 (dolist (form (cdr body) content)
871 (if (not (go-tag-p form))
872 (code (ls-compile form) ";" *newline*)
873 (let ((b (lookup-in-lexenv form *environment* 'gotag)))
874 (code "case " (second (binding-value b)) ":" *newline*)))))
876 " break tbloop;" *newline*
879 "catch (jump) {" *newline*
880 " if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
881 " " branch " = jump.label;" *newline*
883 " throw(jump);" *newline*
886 "return " (ls-compile nil) ";" *newline*))))
888 (define-compilation go (label)
889 (let ((b (lookup-in-lexenv label *environment* 'gotag))
891 ((symbolp label) (symbol-name label))
892 ((integerp label) (integer-to-string label)))))
894 (error "Unknown tag `~S'" label))
898 "id: " (first (binding-value b)) ", "
899 "label: " (second (binding-value b)) ", "
900 "message: 'Attempt to GO to non-existing tag " n "'"
903 (define-compilation unwind-protect (form &rest clean-up)
905 "var ret = " (ls-compile nil) ";" *newline*
907 (code "ret = " (ls-compile form) ";" *newline*)
908 "} finally {" *newline*
909 (code (ls-compile-block clean-up))
911 "return ret;" *newline*))
913 (define-compilation multiple-value-call (func-form &rest forms)
915 "var func = " (ls-compile func-form) ";" *newline*
916 "var args = [" (if *multiple-value-p* "values" "pv") ", 0];" *newline*
919 "var values = mv;" *newline*
921 (mapconcat (lambda (form)
922 (code "vs = " (ls-compile form t) ";" *newline*
923 "if (typeof vs === 'object' && 'multiple-value' in vs)" *newline*
924 (code "args = args.concat(vs);" *newline*)
926 (code "args.push(vs);" *newline*)))
928 "args[1] = args.length-2;" *newline*
929 "return func.apply(window, args);" *newline*) ";" *newline*))
931 (define-compilation multiple-value-prog1 (first-form &rest forms)
933 "var args = " (ls-compile first-form *multiple-value-p*) ";" *newline*
934 (ls-compile-block forms)
935 "return args;" *newline*))
937 (define-transformation backquote (form)
938 (bq-completely-process form))
943 (defvar *builtins* nil)
945 (defmacro define-raw-builtin (name args &body body)
946 ;; Creates a new primitive function `name' with parameters args and
947 ;; @body. The body can access to the local environment through the
948 ;; variable *ENVIRONMENT*.
949 `(push (list ',name (lambda ,args (block ,name ,@body)))
952 (defmacro define-builtin (name args &body body)
953 `(define-raw-builtin ,name ,args
954 (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
957 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
958 (defmacro type-check (decls &body body)
960 ,@(mapcar (lambda (decl)
961 `(code "var " ,(first decl) " = " ,(third decl) ";" *newline*))
963 ,@(mapcar (lambda (decl)
964 `(code "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
965 (code "throw 'The value ' + "
967 " + ' is not a type "
972 (code "return " (progn ,@body) ";" *newline*)))
974 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
975 ;;; a variable which holds a list of forms. It will compile them and
976 ;;; store the result in some Javascript variables. BODY is evaluated
977 ;;; with ARGS bound to the list of these variables to generate the
978 ;;; code which performs the transformation on these variables.
980 (defun variable-arity-call (args function)
982 (error "ARGS must be a non-empty list"))
988 ((floatp x) (push (float-to-string x) fargs))
989 ((numberp x) (push (integer-to-string x) fargs))
990 (t (let ((v (code "x" (incf counter))))
993 (code "var " v " = " (ls-compile x) ";" *newline*
994 "if (typeof " v " !== 'number') throw 'Not a number!';"
996 (js!selfcall prelude (funcall function (reverse fargs)))))
999 (defmacro variable-arity (args &body body)
1000 (unless (symbolp args)
1001 (error "`~S' is not a symbol." args))
1002 `(variable-arity-call ,args
1004 (code "return " ,@body ";" *newline*))))
1006 (defun num-op-num (x op y)
1007 (type-check (("x" "number" x) ("y" "number" y))
1010 (define-raw-builtin + (&rest numbers)
1013 (variable-arity numbers
1014 (join numbers "+"))))
1016 (define-raw-builtin - (x &rest others)
1017 (let ((args (cons x others)))
1018 (variable-arity args
1020 (concat "-" (car args))
1023 (define-raw-builtin * (&rest numbers)
1026 (variable-arity numbers
1027 (join numbers "*"))))
1029 (define-raw-builtin / (x &rest others)
1030 (let ((args (cons x others)))
1031 (variable-arity args
1033 (concat "1 /" (car args))
1036 (define-builtin mod (x y) (num-op-num x "%" y))
1039 (defun comparison-conjuntion (vars op)
1044 (concat (car vars) op (cadr vars)))
1046 (concat (car vars) op (cadr vars)
1048 (comparison-conjuntion (cdr vars) op)))))
1050 (defmacro define-builtin-comparison (op sym)
1051 `(define-raw-builtin ,op (x &rest args)
1052 (let ((args (cons x args)))
1053 (variable-arity args
1054 (js!bool (comparison-conjuntion args ,sym))))))
1056 (define-builtin-comparison > ">")
1057 (define-builtin-comparison < "<")
1058 (define-builtin-comparison >= ">=")
1059 (define-builtin-comparison <= "<=")
1060 (define-builtin-comparison = "==")
1061 (define-builtin-comparison /= "!=")
1063 (define-builtin numberp (x)
1064 (js!bool (code "(typeof (" x ") == \"number\")")))
1066 (define-builtin floor (x)
1067 (type-check (("x" "number" x))
1070 (define-builtin expt (x y)
1071 (type-check (("x" "number" x)
1075 (define-builtin float-to-string (x)
1076 (type-check (("x" "number" x))
1077 "make_lisp_string(x.toString())"))
1079 (define-builtin cons (x y)
1080 (code "({car: " x ", cdr: " y "})"))
1082 (define-builtin consp (x)
1085 "var tmp = " x ";" *newline*
1086 "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1088 (define-builtin car (x)
1090 "var tmp = " x ";" *newline*
1091 "return tmp === " (ls-compile nil)
1092 "? " (ls-compile nil)
1093 ": tmp.car;" *newline*))
1095 (define-builtin cdr (x)
1097 "var tmp = " x ";" *newline*
1098 "return tmp === " (ls-compile nil) "? "
1100 ": tmp.cdr;" *newline*))
1102 (define-builtin rplaca (x new)
1103 (type-check (("x" "object" x))
1104 (code "(x.car = " new ", x)")))
1106 (define-builtin rplacd (x new)
1107 (type-check (("x" "object" x))
1108 (code "(x.cdr = " new ", x)")))
1110 (define-builtin symbolp (x)
1111 (js!bool (code "(" x " instanceof Symbol)")))
1113 (define-builtin make-symbol (name)
1114 (code "(new Symbol(" name "))"))
1116 (define-builtin symbol-name (x)
1117 (code "(" x ").name"))
1119 (define-builtin set (symbol value)
1120 (code "(" symbol ").value = " value))
1122 (define-builtin fset (symbol value)
1123 (code "(" symbol ").fvalue = " value))
1125 (define-builtin boundp (x)
1126 (js!bool (code "(" x ".value !== undefined)")))
1128 (define-builtin fboundp (x)
1129 (js!bool (code "(" x ".fvalue !== undefined)")))
1131 (define-builtin symbol-value (x)
1133 "var symbol = " x ";" *newline*
1134 "var value = symbol.value;" *newline*
1135 "if (value === undefined) throw \"Variable `\" + xstring(symbol.name) + \"' is unbound.\";" *newline*
1136 "return value;" *newline*))
1138 (define-builtin symbol-function (x)
1140 "var symbol = " x ";" *newline*
1141 "var func = symbol.fvalue;" *newline*
1142 "if (func === undefined) throw \"Function `\" + xstring(symbol.name) + \"' is undefined.\";" *newline*
1143 "return func;" *newline*))
1145 (define-builtin symbol-plist (x)
1146 (code "((" x ").plist || " (ls-compile nil) ")"))
1148 (define-builtin lambda-code (x)
1149 (code "make_lisp_string((" x ").toString())"))
1151 (define-builtin eq (x y)
1152 (js!bool (code "(" x " === " y ")")))
1154 (define-builtin char-code (x)
1155 (type-check (("x" "string" x))
1156 "char_to_codepoint(x)"))
1158 (define-builtin code-char (x)
1159 (type-check (("x" "number" x))
1160 "char_from_codepoint(x)"))
1162 (define-builtin characterp (x)
1165 "var x = " x ";" *newline*
1166 "return (typeof(" x ") == \"string\") && (x.length == 1 || x.length == 2);")))
1168 (define-builtin char-upcase (x)
1169 (code "safe_char_upcase(" x ")"))
1171 (define-builtin char-downcase (x)
1172 (code "safe_char_downcase(" x ")"))
1174 (define-builtin stringp (x)
1177 "var x = " x ";" *newline*
1178 "return typeof(x) == 'object' && 'length' in x && x.stringp == 1;")))
1180 (define-raw-builtin funcall (func &rest args)
1182 "var f = " (ls-compile func) ";" *newline*
1183 "return (typeof f === 'function'? f: f.fvalue)("
1184 (join (list* (if *multiple-value-p* "values" "pv")
1185 (integer-to-string (length args))
1186 (mapcar #'ls-compile args))
1190 (define-raw-builtin apply (func &rest args)
1192 (code "(" (ls-compile func) ")()")
1193 (let ((args (butlast args))
1194 (last (car (last args))))
1196 "var f = " (ls-compile func) ";" *newline*
1197 "var args = [" (join (list* (if *multiple-value-p* "values" "pv")
1198 (integer-to-string (length args))
1199 (mapcar #'ls-compile args))
1202 "var tail = (" (ls-compile last) ");" *newline*
1203 "while (tail != " (ls-compile nil) "){" *newline*
1204 " args.push(tail.car);" *newline*
1205 " args[1] += 1;" *newline*
1206 " tail = tail.cdr;" *newline*
1208 "return (typeof f === 'function'? f : f.fvalue).apply(this, args);" *newline*))))
1210 (define-builtin js-eval (string)
1211 (if *multiple-value-p*
1213 "var v = globalEval(xstring(" string "));" *newline*
1214 "return values.apply(this, forcemv(v));" *newline*)
1215 (code "globalEval(xstring(" string "))")))
1217 (define-builtin %throw (string)
1218 (js!selfcall "throw " string ";" *newline*))
1220 (define-builtin functionp (x)
1221 (js!bool (code "(typeof " x " == 'function')")))
1223 (define-builtin %write-string (x)
1224 (code "lisp.write(" x ")"))
1227 ;;; Storage vectors. They are used to implement arrays and (in the
1228 ;;; future) structures.
1230 (define-builtin storage-vector-p (x)
1233 "var x = " x ";" *newline*
1234 "return typeof x === 'object' && 'length' in x;")))
1236 (define-builtin make-storage-vector (n)
1238 "var r = [];" *newline*
1239 "r.length = " n ";" *newline*
1240 "return r;" *newline*))
1242 (define-builtin storage-vector-size (x)
1245 (define-builtin resize-storage-vector (vector new-size)
1246 (code "(" vector ".length = " new-size ")"))
1248 (define-builtin storage-vector-ref (vector n)
1250 "var x = " "(" vector ")[" n "];" *newline*
1251 "if (x === undefined) throw 'Out of range';" *newline*
1252 "return x;" *newline*))
1254 (define-builtin storage-vector-set (vector n value)
1256 "var x = " vector ";" *newline*
1257 "var i = " n ";" *newline*
1258 "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
1259 "return x[i] = " value ";" *newline*))
1261 (define-builtin concatenate-storage-vector (sv1 sv2)
1263 "var sv1 = " sv1 ";" *newline*
1264 "var r = sv1.concat(" sv2 ");" *newline*
1265 "r.type = sv1.type;" *newline*
1266 "r.stringp = sv1.stringp;" *newline*
1267 "return r;" *newline*))
1269 (define-builtin get-internal-real-time ()
1270 "(new Date()).getTime()")
1272 (define-builtin values-array (array)
1273 (if *multiple-value-p*
1274 (code "values.apply(this, " array ")")
1275 (code "pv.apply(this, " array ")")))
1277 (define-raw-builtin values (&rest args)
1278 (if *multiple-value-p*
1279 (code "values(" (join (mapcar #'ls-compile args) ", ") ")")
1280 (code "pv(" (join (mapcar #'ls-compile args) ", ") ")")))
1285 (define-builtin new () "{}")
1287 (define-raw-builtin oget* (object key &rest keys)
1289 "var tmp = (" (ls-compile object) ")[xstring(" (ls-compile key) ")];" *newline*
1290 (mapconcat (lambda (key)
1291 (code "if (tmp === undefined) return " (ls-compile nil) ";" *newline*
1292 "tmp = tmp[xstring(" (ls-compile key) ")];" *newline*))
1294 "return tmp === undefined? " (ls-compile nil) " : tmp;" *newline*))
1296 (define-raw-builtin oset* (value object key &rest keys)
1297 (let ((keys (cons key keys)))
1299 "var obj = " (ls-compile object) ";" *newline*
1300 (mapconcat (lambda (key)
1301 (code "obj = obj[xstring(" (ls-compile key) ")];"
1302 "if (obj === undefined) throw 'Impossible to set Javascript property.';" *newline*))
1304 "var tmp = obj[xstring(" (ls-compile (car (last keys))) ")] = " (ls-compile value) ";" *newline*
1305 "return tmp === undefined? " (ls-compile nil) " : tmp;" *newline*)))
1307 (define-raw-builtin oget (object key &rest keys)
1308 (code "js_to_lisp(" (ls-compile `(oget* ,object ,key ,@keys)) ")"))
1310 (define-raw-builtin oset (value object key &rest keys)
1311 (ls-compile `(oset* (lisp-to-js ,value) ,object ,key ,@keys)))
1313 (define-builtin objectp (x)
1314 (js!bool (code "(typeof (" x ") === 'object')")))
1316 (define-builtin lisp-to-js (x) (code "lisp_to_js(" x ")"))
1317 (define-builtin js-to-lisp (x) (code "js_to_lisp(" x ")"))
1320 (define-builtin in (key object)
1321 (js!bool (code "(xstring(" key ") in (" object "))")))
1323 (define-builtin map-for-in (function object)
1325 "var f = " function ";" *newline*
1326 "var g = (typeof f === 'function' ? f : f.fvalue);" *newline*
1327 "var o = " object ";" *newline*
1328 "for (var key in o){" *newline*
1329 (code "g(" (if *multiple-value-p* "values" "pv") ", 1, o[key]);" *newline*)
1331 " return " (ls-compile nil) ";" *newline*))
1333 (define-compilation %js-vref (var)
1334 (code "js_to_lisp(" var ")"))
1336 (define-compilation %js-vset (var val)
1337 (code "(" var " = lisp_to_js(" (ls-compile val) "))"))
1339 (define-setf-expander %js-vref (var)
1340 (let ((new-value (gensym)))
1341 (unless (stringp var)
1342 (error "`~S' is not a string." var))
1346 `(%js-vset ,var ,new-value)
1351 (defvar *macroexpander-cache*
1352 (make-hash-table :test #'eq))
1354 (defun !macro-function (symbol)
1355 (unless (symbolp symbol)
1356 (error "`~S' is not a symbol." symbol))
1357 (let ((b (lookup-in-lexenv symbol *environment* 'function)))
1358 (if (and b (eq (binding-type b) 'macro))
1359 (let ((expander (binding-value b)))
1362 ((gethash b *macroexpander-cache*)
1363 (setq expander (gethash b *macroexpander-cache*)))
1365 (let ((compiled (eval expander)))
1366 ;; The list representation are useful while
1367 ;; bootstrapping, as we can dump the definition of the
1368 ;; macros easily, but they are slow because we have to
1369 ;; evaluate them and compile them now and again. So, let
1370 ;; us replace the list representation version of the
1371 ;; function with the compiled one.
1373 #+jscl (setf (binding-value b) compiled)
1374 #-jscl (setf (gethash b *macroexpander-cache*) compiled)
1375 (setq expander compiled))))
1379 (defun !macroexpand-1 (form)
1382 (let ((b (lookup-in-lexenv form *environment* 'variable)))
1383 (if (and b (eq (binding-type b) 'macro))
1384 (values (binding-value b) t)
1385 (values form nil))))
1386 ((and (consp form) (symbolp (car form)))
1387 (let ((macrofun (!macro-function (car form))))
1389 (values (funcall macrofun (cdr form)) t)
1390 (values form nil))))
1392 (values form nil))))
1394 (defun compile-funcall (function args)
1395 (let* ((values-funcs (if *multiple-value-p* "values" "pv"))
1396 (arglist (concat "(" (join (list* values-funcs
1397 (integer-to-string (length args))
1398 (mapcar #'ls-compile args)) ", ") ")")))
1399 (unless (or (symbolp function)
1400 (and (consp function)
1401 (member (car function) '(lambda oget))))
1402 (error "Bad function designator `~S'" function))
1404 ((translate-function function)
1405 (concat (translate-function function) arglist))
1406 ((and (symbolp function)
1407 #+jscl (eq (symbol-package function) (find-package "COMMON-LISP"))
1409 (code (ls-compile `',function) ".fvalue" arglist))
1410 #+jscl((symbolp function)
1411 (code (ls-compile `#',function) arglist))
1412 ((and (consp function) (eq (car function) 'lambda))
1413 (code (ls-compile `#',function) arglist))
1414 ((and (consp function) (eq (car function) 'oget))
1415 (code (ls-compile function) arglist))
1417 (error "Bad function descriptor")))))
1419 (defun ls-compile-block (sexps &optional return-last-p decls-allowed-p)
1420 (multiple-value-bind (sexps decls)
1421 (parse-body sexps :declarations decls-allowed-p)
1422 (declare (ignore decls))
1424 (code (ls-compile-block (butlast sexps) nil decls-allowed-p)
1425 "return " (ls-compile (car (last sexps)) *multiple-value-p*) ";")
1427 (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
1428 (concat ";" *newline*)))))
1430 (defun ls-compile (sexp &optional multiple-value-p)
1431 (multiple-value-bind (sexp expandedp) (!macroexpand-1 sexp)
1433 (return-from ls-compile (ls-compile sexp multiple-value-p)))
1434 ;; The expression has been macroexpanded. Now compile it!
1435 (let ((*multiple-value-p* multiple-value-p))
1438 (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1440 ((and b (not (member 'special (binding-declarations b))))
1442 ((or (keywordp sexp)
1443 (and b (member 'constant (binding-declarations b))))
1444 (code (ls-compile `',sexp) ".value"))
1446 (ls-compile `(symbol-value ',sexp))))))
1447 ((or (integerp sexp) (floatp sexp) (characterp sexp) (stringp sexp) (arrayp sexp))
1450 (let ((name (car sexp))
1454 ((assoc name *compilations*)
1455 (let ((comp (second (assoc name *compilations*))))
1457 ;; Built-in functions
1458 ((and (assoc name *builtins*)
1459 (not (claimp name 'function 'notinline)))
1460 (let ((comp (second (assoc name *builtins*))))
1463 (compile-funcall name args)))))
1465 (error "How should I compile `~S'?" sexp))))))
1468 (defvar *compile-print-toplevels* nil)
1470 (defun truncate-string (string &optional (width 60))
1471 (let ((n (or (position #\newline string)
1472 (min width (length string)))))
1473 (subseq string 0 n)))
1475 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
1476 (let ((*toplevel-compilations* nil))
1478 ((and (consp sexp) (eq (car sexp) 'progn))
1479 (let ((subs (mapcar (lambda (s)
1480 (ls-compile-toplevel s t))
1482 (join (remove-if #'null-or-empty-p subs))))
1484 (when *compile-print-toplevels*
1485 (let ((form-string (prin1-to-string sexp)))
1486 (format t "Compiling ~a..." (truncate-string form-string))))
1487 (let ((code (ls-compile sexp multiple-value-p)))
1488 (code (join-trailing (get-toplevel-compilations)
1489 (code ";" *newline*))
1491 (code code ";" *newline*))))))))