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* (indent ,@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.
54 (defun indent (&rest string)
55 (let ((input (apply #'code string)))
58 (size (length input)))
59 (when (plusp (length input)) (concatf output " "))
62 (if (and (char= (char input index) #\newline)
64 (not (char= (char input (1+ index)) #\newline)))
65 (concat (string #\newline) " ")
66 (string (char input index)))))
72 (defun indent (&rest string)
73 (with-output-to-string (*standard-output*)
74 (with-input-from-string (input (apply #'code string))
76 for line = (read-line input nil)
79 do (write-line line)))))
82 ;;; A Form can return a multiple values object calling VALUES, like
83 ;;; values(arg1, arg2, ...). It will work in any context, as well as
84 ;;; returning an individual object. However, if the special variable
85 ;;; `*multiple-value-p*' is NIL, is granted that only the primary
86 ;;; value will be used, so we can optimize to avoid the VALUES
88 (defvar *multiple-value-p* nil)
104 (defun lookup-in-lexenv (name lexenv namespace)
105 (find name (ecase namespace
106 (variable (lexenv-variable lexenv))
107 (function (lexenv-function lexenv))
108 (block (lexenv-block lexenv))
109 (gotag (lexenv-gotag lexenv)))
110 :key #'binding-name))
112 (defun push-to-lexenv (binding lexenv namespace)
114 (variable (push binding (lexenv-variable lexenv)))
115 (function (push binding (lexenv-function lexenv)))
116 (block (push binding (lexenv-block lexenv)))
117 (gotag (push binding (lexenv-gotag lexenv)))))
119 (defun extend-lexenv (bindings lexenv namespace)
120 (let ((env (copy-lexenv lexenv)))
121 (dolist (binding (reverse bindings) env)
122 (push-to-lexenv binding env namespace))))
125 (defvar *environment* (make-lexenv))
127 (defvar *variable-counter* 0)
129 (defun gvarname (symbol)
130 (declare (ignore symbol))
131 (code "v" (incf *variable-counter*)))
133 (defun translate-variable (symbol)
134 (awhen (lookup-in-lexenv symbol *environment* 'variable)
137 (defun extend-local-env (args)
138 (let ((new (copy-lexenv *environment*)))
139 (dolist (symbol args new)
140 (let ((b (make-binding :name symbol :type 'variable :value (gvarname symbol))))
141 (push-to-lexenv b new 'variable)))))
143 ;;; Toplevel compilations
144 (defvar *toplevel-compilations* nil)
146 (defun toplevel-compilation (string)
147 (push string *toplevel-compilations*))
149 (defun null-or-empty-p (x)
152 (defun get-toplevel-compilations ()
153 (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
155 (defun %compile-defmacro (name lambda)
156 (toplevel-compilation (ls-compile `',name))
157 (let ((binding (make-binding :name name :type 'macro :value lambda)))
158 (push-to-lexenv binding *environment* 'function))
161 (defun global-binding (name type namespace)
162 (or (lookup-in-lexenv name *environment* namespace)
163 (let ((b (make-binding :name name :type type :value nil)))
164 (push-to-lexenv b *environment* namespace)
167 (defun claimp (symbol namespace claim)
168 (let ((b (lookup-in-lexenv symbol *environment* namespace)))
169 (and b (member claim (binding-declarations b)))))
171 (defun !proclaim (decl)
174 (dolist (name (cdr decl))
175 (let ((b (global-binding name 'variable 'variable)))
176 (push 'special (binding-declarations b)))))
178 (dolist (name (cdr decl))
179 (let ((b (global-binding name 'function 'function)))
180 (push 'notinline (binding-declarations b)))))
182 (dolist (name (cdr decl))
183 (let ((b (global-binding name 'variable 'variable)))
184 (push 'constant (binding-declarations b)))))))
187 (fset 'proclaim #'!proclaim)
189 (defun %define-symbol-macro (name expansion)
190 (let ((b (make-binding :name name :type 'macro :value expansion)))
191 (push-to-lexenv b *environment* 'variable)
195 (defmacro define-symbol-macro (name expansion)
196 `(%define-symbol-macro ',name ',expansion))
201 (defvar *compilations* nil)
203 (defmacro define-compilation (name args &body body)
204 ;; Creates a new primitive `name' with parameters args and
205 ;; @body. The body can access to the local environment through the
206 ;; variable *ENVIRONMENT*.
207 `(push (list ',name (lambda ,args (block ,name ,@body)))
210 (define-compilation if (condition true false)
211 (code "(" (ls-compile condition) " !== " (ls-compile nil)
212 " ? " (ls-compile true *multiple-value-p*)
213 " : " (ls-compile false *multiple-value-p*)
216 (defvar *ll-keywords* '(&optional &rest &key))
218 (defun list-until-keyword (list)
219 (if (or (null list) (member (car list) *ll-keywords*))
221 (cons (car list) (list-until-keyword (cdr list)))))
223 (defun ll-section (keyword ll)
224 (list-until-keyword (cdr (member keyword ll))))
226 (defun ll-required-arguments (ll)
227 (list-until-keyword ll))
229 (defun ll-optional-arguments-canonical (ll)
230 (mapcar #'ensure-list (ll-section '&optional ll)))
232 (defun ll-optional-arguments (ll)
233 (mapcar #'car (ll-optional-arguments-canonical ll)))
235 (defun ll-rest-argument (ll)
236 (let ((rest (ll-section '&rest ll)))
238 (error "Bad lambda-list `~S'." ll))
241 (defun ll-keyword-arguments-canonical (ll)
242 (flet ((canonicalize (keyarg)
243 ;; Build a canonical keyword argument descriptor, filling
244 ;; the optional fields. The result is a list of the form
245 ;; ((keyword-name var) init-form).
246 (let ((arg (ensure-list keyarg)))
247 (cons (if (listp (car arg))
249 (list (intern (symbol-name (car arg)) "KEYWORD") (car arg)))
251 (mapcar #'canonicalize (ll-section '&key ll))))
253 (defun ll-keyword-arguments (ll)
254 (mapcar (lambda (keyarg) (second (first keyarg)))
255 (ll-keyword-arguments-canonical ll)))
257 (defun ll-svars (lambda-list)
260 (ll-keyword-arguments-canonical lambda-list)
261 (ll-optional-arguments-canonical lambda-list))))
262 (remove nil (mapcar #'third args))))
264 (defun lambda-name/docstring-wrapper (name docstring &rest strs)
265 (if (or name docstring)
267 "var func = " (join strs) ";" *newline*
269 (code "func.fname = '" (escape-string name) "';" *newline*))
271 (code "func.docstring = '" (escape-string docstring) "';" *newline*))
272 "return func;" *newline*)
273 (apply #'code strs)))
275 (defun lambda-check-argument-count
276 (n-required-arguments n-optional-arguments rest-p)
277 ;; Note: Remember that we assume that the number of arguments of a
278 ;; call is at least 1 (the values argument).
279 (let ((min n-required-arguments)
280 (max (if rest-p 'n/a (+ n-required-arguments n-optional-arguments))))
282 ;; Special case: a positive exact number of arguments.
283 (when (and (< 0 min) (eql min max))
284 (return (code "checkArgs(nargs, " min ");" *newline*)))
288 (code "checkArgsAtLeast(nargs, " min ");" *newline*))
290 (code "checkArgsAtMost(nargs, " max ");" *newline*))))))
292 (defun compile-lambda-optional (ll)
293 (let* ((optional-arguments (ll-optional-arguments-canonical ll))
294 (n-required-arguments (length (ll-required-arguments ll)))
295 (n-optional-arguments (length optional-arguments)))
296 (when optional-arguments
297 (code "switch(nargs){" *newline*
301 (while (< idx n-optional-arguments)
302 (let ((arg (nth idx optional-arguments)))
303 (push (code "case " (+ idx n-required-arguments) ":" *newline*
304 (indent (translate-variable (car arg))
306 (ls-compile (cadr arg)) ";" *newline*)
308 (indent (translate-variable (third arg))
314 (push (code "default: break;" *newline*) cases)
315 (join (reverse cases))))
318 (defun compile-lambda-rest (ll)
319 (let ((n-required-arguments (length (ll-required-arguments ll)))
320 (n-optional-arguments (length (ll-optional-arguments ll)))
321 (rest-argument (ll-rest-argument ll)))
323 (let ((js!rest (translate-variable rest-argument)))
324 (code "var " js!rest "= " (ls-compile nil) ";" *newline*
325 "for (var i = nargs-1; i>=" (+ n-required-arguments n-optional-arguments)
327 (indent js!rest " = {car: arguments[i+2], cdr: " js!rest "};" *newline*))))))
329 (defun compile-lambda-parse-keywords (ll)
330 (let ((n-required-arguments
331 (length (ll-required-arguments ll)))
332 (n-optional-arguments
333 (length (ll-optional-arguments ll)))
335 (ll-keyword-arguments-canonical ll)))
338 (mapconcat (lambda (arg)
339 (let ((var (second (car arg))))
340 (code "var " (translate-variable var) "; " *newline*
342 (code "var " (translate-variable (third arg))
343 " = " (ls-compile nil)
347 (flet ((parse-keyword (keyarg)
348 ;; ((keyword-name var) init-form)
349 (code "for (i=" (+ n-required-arguments n-optional-arguments)
350 "; i<nargs; i+=2){" *newline*
352 "if (arguments[i+2] === " (ls-compile (caar keyarg)) "){" *newline*
353 (indent (translate-variable (cadr (car keyarg)))
356 (let ((svar (third keyarg)))
358 (code (translate-variable svar) " = " (ls-compile t) ";" *newline*)))
363 "if (i == nargs){" *newline*
364 (indent (translate-variable (cadr (car keyarg))) " = " (ls-compile (cadr keyarg)) ";" *newline*)
366 (when keyword-arguments
367 (code "var i;" *newline*
368 (mapconcat #'parse-keyword keyword-arguments))))
369 ;; Check for unknown keywords
370 (when keyword-arguments
371 (code "for (i=" (+ n-required-arguments n-optional-arguments)
372 "; i<nargs; i+=2){" *newline*
374 (join (mapcar (lambda (x)
375 (concat "arguments[i+2] !== " (ls-compile (caar x))))
380 "throw 'Unknown keyword argument ' + xstring(arguments[i].name);" *newline*))
383 (defun parse-lambda-list (ll)
384 (values (ll-required-arguments ll)
385 (ll-optional-arguments ll)
386 (ll-keyword-arguments ll)
387 (ll-rest-argument ll)))
389 ;;; Process BODY for declarations and/or docstrings. Return as
390 ;;; multiple values the BODY without docstrings or declarations, the
391 ;;; list of declaration forms and the docstring.
392 (defun parse-body (body &key declarations docstring)
393 (let ((value-declarations)
395 ;; Parse declarations
397 (do* ((rest body (cdr rest))
398 (form (car rest) (car rest)))
399 ((or (atom form) (not (eq (car form) 'declare)))
401 (push form value-declarations)))
405 (not (null (cdr body))))
406 (setq value-docstring (car body))
407 (setq body (cdr body)))
408 (values body value-declarations value-docstring)))
410 ;;; Compile a lambda function with lambda list LL and body BODY. If
411 ;;; NAME is given, it should be a constant string and it will become
412 ;;; the name of the function. If BLOCK is non-NIL, a named block is
413 ;;; created around the body. NOTE: No block (even anonymous) is
414 ;;; created if BLOCk is NIL.
415 (defun compile-lambda (ll body &key name block)
416 (multiple-value-bind (required-arguments
420 (parse-lambda-list ll)
421 (multiple-value-bind (body decls documentation)
422 (parse-body body :declarations t :docstring t)
423 (declare (ignore decls))
424 (let ((n-required-arguments (length required-arguments))
425 (n-optional-arguments (length optional-arguments))
426 (*environment* (extend-local-env
427 (append (ensure-list rest-argument)
432 (lambda-name/docstring-wrapper name documentation
434 (join (list* "values"
436 (mapcar #'translate-variable
437 (append required-arguments optional-arguments)))
441 ;; Check number of arguments
442 (lambda-check-argument-count n-required-arguments
444 (or rest-argument keyword-arguments))
445 (compile-lambda-optional ll)
446 (compile-lambda-rest ll)
447 (compile-lambda-parse-keywords ll)
448 (let ((*multiple-value-p* t))
450 (ls-compile-block `((block ,block ,@body)) t)
451 (ls-compile-block body t))))
455 (defun setq-pair (var val)
456 (let ((b (lookup-in-lexenv var *environment* 'variable)))
459 (eq (binding-type b) 'variable)
460 (not (member 'special (binding-declarations b)))
461 (not (member 'constant (binding-declarations b))))
462 (code (binding-value b) " = " (ls-compile val)))
463 ((and b (eq (binding-type b) 'macro))
464 (ls-compile `(setf ,var ,val)))
466 (ls-compile `(set ',var ,val))))))
469 (define-compilation setq (&rest pairs)
473 ((null pairs) (return))
475 (error "Odd pairs in SETQ"))
478 (concat (setq-pair (car pairs) (cadr pairs))
479 (if (null (cddr pairs)) "" ", ")))
480 (setq pairs (cddr pairs)))))
481 (code "(" result ")")))
484 ;;; Compilation of literals an object dumping
486 (defun escape-string (string)
489 (size (length string)))
490 (while (< index size)
491 (let ((ch (char string index)))
492 (when (or (char= ch #\") (char= ch #\\))
493 (setq output (concat output "\\")))
494 (when (or (char= ch #\newline))
495 (setq output (concat output "\\"))
497 (setq output (concat output (string ch))))
501 ;;; BOOTSTRAP MAGIC: We record the macro definitions as lists during
502 ;;; the bootstrap. Once everything is compiled, we want to dump the
503 ;;; whole global environment to the output file to reproduce it in the
504 ;;; run-time. However, the environment must contain expander functions
505 ;;; rather than lists. We do not know how to dump function objects
506 ;;; itself, so we mark the list definitions with this object and the
507 ;;; compiler will be called when this object has to be dumped.
508 ;;; Backquote/unquote does a similar magic, but this use is exclusive.
510 ;;; Indeed, perhaps to compile the object other macros need to be
511 ;;; evaluated. For this reason we define a valid macro-function for
513 (defvar *magic-unquote-marker* (gensym "MAGIC-UNQUOTE"))
515 (setf (macro-function *magic-unquote-marker*)
516 (lambda (form &optional environment)
517 (declare (ignore environment))
520 (defvar *literal-table* nil)
521 (defvar *literal-counter* 0)
524 (code "l" (incf *literal-counter*)))
526 (defun dump-symbol (symbol)
528 (let ((package (symbol-package symbol)))
529 (if (eq package (find-package "KEYWORD"))
530 (code "(new Symbol(" (dump-string (symbol-name symbol)) ", " (dump-string (package-name package)) "))")
531 (code "(new Symbol(" (dump-string (symbol-name symbol)) "))")))
533 (let ((package (symbol-package symbol)))
535 (code "(new Symbol(" (dump-string (symbol-name symbol)) "))")
536 (ls-compile `(intern ,(symbol-name symbol) ,(package-name package))))))
538 (defun dump-cons (cons)
539 (let ((head (butlast cons))
542 (join-trailing (mapcar (lambda (x) (literal x t)) head) ",")
543 (literal (car tail) t)
545 (literal (cdr tail) t)
548 (defun dump-array (array)
549 (let ((elements (vector-to-list array)))
550 (concat "[" (join (mapcar #'literal elements) ", ") "]")))
552 (defun dump-string (string)
553 (code "make_lisp_string(\"" (escape-string string) "\")"))
555 (defun literal (sexp &optional recursive)
557 ((integerp sexp) (integer-to-string sexp))
558 ((floatp sexp) (float-to-string sexp))
559 ((characterp sexp) (code "\"" (escape-string (string sexp)) "\""))
561 (or (cdr (assoc sexp *literal-table* :test #'eql))
562 (let ((dumped (typecase sexp
563 (symbol (dump-symbol sexp))
564 (string (dump-string sexp))
566 ;; BOOTSTRAP MAGIC: See the root file
567 ;; jscl.lisp and the function
568 ;; `dump-global-environment' for futher
570 (if (eq (car sexp) *magic-unquote-marker*)
571 (ls-compile (second sexp))
573 (array (dump-array sexp)))))
574 (if (and recursive (not (symbolp sexp)))
576 (let ((jsvar (genlit)))
577 (push (cons sexp jsvar) *literal-table*)
578 (toplevel-compilation (code "var " jsvar " = " dumped))
579 (when (keywordp sexp)
580 (toplevel-compilation (code jsvar ".value = " jsvar)))
584 (define-compilation quote (sexp)
587 (define-compilation %while (pred &rest body)
589 "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
590 (indent (ls-compile-block body))
592 "return " (ls-compile nil) ";" *newline*))
594 (define-compilation function (x)
596 ((and (listp x) (eq (car x) 'lambda))
597 (compile-lambda (cadr x) (cddr x)))
598 ((and (listp x) (eq (car x) 'named-lambda))
599 ;; TODO: destructuring-bind now! Do error checking manually is
601 (let ((name (cadr x))
604 (compile-lambda ll body
605 :name (symbol-name name)
608 (let ((b (lookup-in-lexenv x *environment* 'function)))
611 (ls-compile `(symbol-function ',x)))))))
614 (defun make-function-binding (fname)
615 (make-binding :name fname :type 'function :value (gvarname fname)))
617 (defun compile-function-definition (list)
618 (compile-lambda (car list) (cdr list)))
620 (defun translate-function (name)
621 (let ((b (lookup-in-lexenv name *environment* 'function)))
622 (and b (binding-value b))))
624 (define-compilation flet (definitions &rest body)
625 (let* ((fnames (mapcar #'car definitions))
626 (cfuncs (mapcar (lambda (def)
627 (compile-lambda (cadr def)
632 (extend-lexenv (mapcar #'make-function-binding fnames)
636 (join (mapcar #'translate-function fnames) ",")
638 (let ((body (ls-compile-block body t)))
640 "})(" (join cfuncs ",") ")")))
642 (define-compilation labels (definitions &rest body)
643 (let* ((fnames (mapcar #'car definitions))
645 (extend-lexenv (mapcar #'make-function-binding fnames)
649 (mapconcat (lambda (func)
650 (code "var " (translate-function (car func))
651 " = " (compile-lambda (cadr func)
652 `((block ,(car func) ,@(cddr func))))
655 (ls-compile-block body t))))
658 (defvar *compiling-file* nil)
659 (define-compilation eval-when-compile (&rest body)
662 (eval (cons 'progn body))
664 (ls-compile `(progn ,@body))))
666 (defmacro define-transformation (name args form)
667 `(define-compilation ,name ,args
670 (define-compilation progn (&rest body)
671 (if (null (cdr body))
672 (ls-compile (car body) *multiple-value-p*)
673 (js!selfcall (ls-compile-block body t))))
675 (defun special-variable-p (x)
676 (and (claimp x 'variable 'special) t))
678 ;;; Wrap CODE to restore the symbol values of the dynamic
679 ;;; bindings. BINDINGS is a list of pairs of the form
680 ;;; (SYMBOL . PLACE), where PLACE is a Javascript variable
681 ;;; name to initialize the symbol value and where to stored
683 (defun let-binding-wrapper (bindings body)
684 (when (null bindings)
685 (return-from let-binding-wrapper body))
688 (indent "var tmp;" *newline*
691 (let ((s (ls-compile `(quote ,(car b)))))
692 (code "tmp = " s ".value;" *newline*
693 s ".value = " (cdr b) ";" *newline*
694 (cdr b) " = tmp;" *newline*)))
698 "finally {" *newline*
700 (mapconcat (lambda (b)
701 (let ((s (ls-compile `(quote ,(car b)))))
702 (code s ".value" " = " (cdr b) ";" *newline*)))
706 (define-compilation let (bindings &rest body)
707 (let* ((bindings (mapcar #'ensure-list bindings))
708 (variables (mapcar #'first bindings))
709 (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
710 (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
713 (join (mapcar (lambda (x)
714 (if (special-variable-p x)
715 (let ((v (gvarname x)))
716 (push (cons x v) dynamic-bindings)
718 (translate-variable x)))
722 (let ((body (ls-compile-block body t t)))
723 (indent (let-binding-wrapper dynamic-bindings body)))
724 "})(" (join cvalues ",") ")")))
727 ;;; Return the code to initialize BINDING, and push it extending the
728 ;;; current lexical environment if the variable is not special.
729 (defun let*-initialize-value (binding)
730 (let ((var (first binding))
731 (value (second binding)))
732 (if (special-variable-p var)
733 (code (ls-compile `(setq ,var ,value)) ";" *newline*)
734 (let* ((v (gvarname var))
735 (b (make-binding :name var :type 'variable :value v)))
736 (prog1 (code "var " v " = " (ls-compile value) ";" *newline*)
737 (push-to-lexenv b *environment* 'variable))))))
739 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
740 ;;; DOES NOT generate code to initialize the value of the symbols,
741 ;;; unlike let-binding-wrapper.
742 (defun let*-binding-wrapper (symbols body)
744 (return-from let*-binding-wrapper body))
745 (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
746 (remove-if-not #'special-variable-p symbols))))
750 (mapconcat (lambda (b)
751 (let ((s (ls-compile `(quote ,(car b)))))
752 (code "var " (cdr b) " = " s ".value;" *newline*)))
756 "finally {" *newline*
758 (mapconcat (lambda (b)
759 (let ((s (ls-compile `(quote ,(car b)))))
760 (code s ".value" " = " (cdr b) ";" *newline*)))
764 (define-compilation let* (bindings &rest body)
765 (let ((bindings (mapcar #'ensure-list bindings))
766 (*environment* (copy-lexenv *environment*)))
768 (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
769 (body (concat (mapconcat #'let*-initialize-value bindings)
770 (ls-compile-block body t t))))
771 (let*-binding-wrapper specials body)))))
774 (define-compilation block (name &rest body)
775 ;; We use Javascript exceptions to implement non local control
776 ;; transfer. Exceptions has dynamic scoping, so we use a uniquely
777 ;; generated object to identify the block. The instance of a empty
778 ;; array is used to distinguish between nested dynamic Javascript
779 ;; exceptions. See https://github.com/davazp/jscl/issues/64 for
781 (let* ((idvar (gvarname name))
782 (b (make-binding :name name :type 'block :value idvar)))
783 (when *multiple-value-p*
784 (push 'multiple-value (binding-declarations b)))
785 (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
786 (cbody (ls-compile-block body t)))
787 (if (member 'used (binding-declarations b))
790 "var " idvar " = [];" *newline*
793 "catch (cf){" *newline*
794 " if (cf.type == 'block' && cf.id == " idvar ")" *newline*
795 (if *multiple-value-p*
796 " return values.apply(this, forcemv(cf.values));"
797 " return cf.values;")
800 " throw cf;" *newline*
802 (js!selfcall cbody)))))
804 (define-compilation return-from (name &optional value)
805 (let* ((b (lookup-in-lexenv name *environment* 'block))
806 (multiple-value-p (member 'multiple-value (binding-declarations b))))
808 (error "Return from unknown block `~S'." (symbol-name name)))
809 (push 'used (binding-declarations b))
810 ;; The binding value is the name of a variable, whose value is the
811 ;; unique identifier of the block as exception. We can't use the
812 ;; variable name itself, because it could not to be unique, so we
813 ;; capture it in a closure.
815 (when multiple-value-p (code "var values = mv;" *newline*))
818 "id: " (binding-value b) ", "
819 "values: " (ls-compile value multiple-value-p) ", "
820 "message: 'Return from unknown block " (symbol-name name) ".'"
823 (define-compilation catch (id &rest body)
825 "var id = " (ls-compile id) ";" *newline*
827 (indent (ls-compile-block body t)) *newline*
829 "catch (cf){" *newline*
830 " if (cf.type == 'catch' && cf.id == id)" *newline*
831 (if *multiple-value-p*
832 " return values.apply(this, forcemv(cf.values));"
833 " return pv.apply(this, forcemv(cf.values));")
836 " throw cf;" *newline*
839 (define-compilation throw (id value)
841 "var values = mv;" *newline*
844 "id: " (ls-compile id) ", "
845 "values: " (ls-compile value t) ", "
846 "message: 'Throw uncatched.'"
850 (or (integerp x) (symbolp x)))
852 (defun declare-tagbody-tags (tbidx body)
853 (let* ((go-tag-counter 0)
855 (mapcar (lambda (label)
856 (let ((tagidx (integer-to-string (incf go-tag-counter))))
857 (make-binding :name label :type 'gotag :value (list tbidx tagidx))))
858 (remove-if-not #'go-tag-p body))))
859 (extend-lexenv bindings *environment* 'gotag)))
861 (define-compilation tagbody (&rest body)
862 ;; Ignore the tagbody if it does not contain any go-tag. We do this
863 ;; because 1) it is easy and 2) many built-in forms expand to a
864 ;; implicit tagbody, so we save some space.
865 (unless (some #'go-tag-p body)
866 (return-from tagbody (ls-compile `(progn ,@body nil))))
867 ;; The translation assumes the first form in BODY is a label
868 (unless (go-tag-p (car body))
869 (push (gensym "START") body))
870 ;; Tagbody compilation
871 (let ((branch (gvarname 'branch))
872 (tbidx (gvarname 'tbidx)))
873 (let ((*environment* (declare-tagbody-tags tbidx body))
875 (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
876 (setq initag (second (binding-value b))))
878 ;; TAGBODY branch to take
879 "var " branch " = " initag ";" *newline*
880 "var " tbidx " = [];" *newline*
882 "while (true) {" *newline*
883 (indent "try {" *newline*
884 (indent (let ((content ""))
885 (code "switch(" branch "){" *newline*
886 "case " initag ":" *newline*
887 (dolist (form (cdr body) content)
889 (if (not (go-tag-p form))
890 (indent (ls-compile form) ";" *newline*)
891 (let ((b (lookup-in-lexenv form *environment* 'gotag)))
892 (code "case " (second (binding-value b)) ":" *newline*)))))
894 " break tbloop;" *newline*
897 "catch (jump) {" *newline*
898 " if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
899 " " branch " = jump.label;" *newline*
901 " throw(jump);" *newline*
904 "return " (ls-compile nil) ";" *newline*))))
906 (define-compilation go (label)
907 (let ((b (lookup-in-lexenv label *environment* 'gotag))
909 ((symbolp label) (symbol-name label))
910 ((integerp label) (integer-to-string label)))))
912 (error "Unknown tag `~S'" label))
916 "id: " (first (binding-value b)) ", "
917 "label: " (second (binding-value b)) ", "
918 "message: 'Attempt to GO to non-existing tag " n "'"
921 (define-compilation unwind-protect (form &rest clean-up)
923 "var ret = " (ls-compile nil) ";" *newline*
925 (indent "ret = " (ls-compile form) ";" *newline*)
926 "} finally {" *newline*
927 (indent (ls-compile-block clean-up))
929 "return ret;" *newline*))
931 (define-compilation multiple-value-call (func-form &rest forms)
933 "var func = " (ls-compile func-form) ";" *newline*
934 "var args = [" (if *multiple-value-p* "values" "pv") ", 0];" *newline*
937 "var values = mv;" *newline*
939 (mapconcat (lambda (form)
940 (code "vs = " (ls-compile form t) ";" *newline*
941 "if (typeof vs === 'object' && 'multiple-value' in vs)" *newline*
942 (indent "args = args.concat(vs);" *newline*)
944 (indent "args.push(vs);" *newline*)))
946 "args[1] = args.length-2;" *newline*
947 "return func.apply(window, args);" *newline*) ";" *newline*))
949 (define-compilation multiple-value-prog1 (first-form &rest forms)
951 "var args = " (ls-compile first-form *multiple-value-p*) ";" *newline*
952 (ls-compile-block forms)
953 "return args;" *newline*))
956 ;;; Backquote implementation.
958 ;;; Author: Guy L. Steele Jr. Date: 27 December 1985
959 ;;; Tested under Symbolics Common Lisp and Lucid Common Lisp.
960 ;;; This software is in the public domain.
962 ;;; The following are unique tokens used during processing.
963 ;;; They need not be symbols; they need not even be atoms.
964 (defvar *comma* 'unquote)
965 (defvar *comma-atsign* 'unquote-splicing)
967 (defvar *bq-list* (make-symbol "BQ-LIST"))
968 (defvar *bq-append* (make-symbol "BQ-APPEND"))
969 (defvar *bq-list** (make-symbol "BQ-LIST*"))
970 (defvar *bq-nconc* (make-symbol "BQ-NCONC"))
971 (defvar *bq-clobberable* (make-symbol "BQ-CLOBBERABLE"))
972 (defvar *bq-quote* (make-symbol "BQ-QUOTE"))
973 (defvar *bq-quote-nil* (list *bq-quote* nil))
975 ;;; BACKQUOTE is an ordinary macro (not a read-macro) that processes
976 ;;; the expression foo, looking for occurrences of #:COMMA,
977 ;;; #:COMMA-ATSIGN, and #:COMMA-DOT. It constructs code in strict
978 ;;; accordance with the rules on pages 349-350 of the first edition
979 ;;; (pages 528-529 of this second edition). It then optionally
980 ;;; applies a code simplifier.
982 ;;; If the value of *BQ-SIMPLIFY* is non-NIL, then BACKQUOTE
983 ;;; processing applies the code simplifier. If the value is NIL,
984 ;;; then the code resulting from BACKQUOTE is exactly that
985 ;;; specified by the official rules.
986 (defparameter *bq-simplify* t)
988 (defmacro backquote (x)
989 (bq-completely-process x))
991 ;;; Backquote processing proceeds in three stages:
993 ;;; (1) BQ-PROCESS applies the rules to remove occurrences of
994 ;;; #:COMMA, #:COMMA-ATSIGN, and #:COMMA-DOT corresponding to
995 ;;; this level of BACKQUOTE. (It also causes embedded calls to
996 ;;; BACKQUOTE to be expanded so that nesting is properly handled.)
997 ;;; Code is produced that is expressed in terms of functions
998 ;;; #:BQ-LIST, #:BQ-APPEND, and #:BQ-CLOBBERABLE. This is done
999 ;;; so that the simplifier will simplify only list construction
1000 ;;; functions actually generated by BACKQUOTE and will not involve
1001 ;;; any user code in the simplification. #:BQ-LIST means LIST,
1002 ;;; #:BQ-APPEND means APPEND, and #:BQ-CLOBBERABLE means IDENTITY
1003 ;;; but indicates places where "%." was used and where NCONC may
1004 ;;; therefore be introduced by the simplifier for efficiency.
1006 ;;; (2) BQ-SIMPLIFY, if used, rewrites the code produced by
1007 ;;; BQ-PROCESS to produce equivalent but faster code. The
1008 ;;; additional functions #:BQ-LIST* and #:BQ-NCONC may be
1009 ;;; introduced into the code.
1011 ;;; (3) BQ-REMOVE-TOKENS goes through the code and replaces
1012 ;;; #:BQ-LIST with LIST, #:BQ-APPEND with APPEND, and so on.
1013 ;;; #:BQ-CLOBBERABLE is simply eliminated (a call to it being
1014 ;;; replaced by its argument). #:BQ-LIST* is replaced by either
1015 ;;; LIST* or CONS (the latter is used in the two-argument case,
1016 ;;; purely to make the resulting code a tad more readable).
1018 (defun bq-completely-process (x)
1019 (let ((raw-result (bq-process x)))
1020 (bq-remove-tokens (if *bq-simplify*
1021 (bq-simplify raw-result)
1024 (defun bq-process (x)
1026 (list *bq-quote* x))
1027 ((eq (car x) 'backquote)
1028 (bq-process (bq-completely-process (cadr x))))
1029 ((eq (car x) *comma*) (cadr x))
1030 ((eq (car x) *comma-atsign*)
1031 (error ",@~S after `" (cadr x)))
1032 ;; ((eq (car x) *comma-dot*)
1033 ;; ;; (error ",.~S after `" (cadr x))
1034 ;; (error "ill-formed"))
1035 (t (do ((p x (cdr p))
1036 (q '() (cons (bracket (car p)) q)))
1039 (nreconc q (list (list *bq-quote* p)))))
1040 (when (eq (car p) *comma*)
1041 (unless (null (cddr p))
1042 (error "Malformed ,~S" p))
1043 (return (cons *bq-append*
1044 (nreconc q (list (cadr p))))))
1045 (when (eq (car p) *comma-atsign*)
1046 (error "Dotted ,@~S" p))
1047 ;; (when (eq (car p) *comma-dot*)
1048 ;; ;; (error "Dotted ,.~S" p)
1049 ;; (error "Dotted"))
1052 ;;; This implements the bracket operator of the formal rules.
1055 (list *bq-list* (bq-process x)))
1056 ((eq (car x) *comma*)
1057 (list *bq-list* (cadr x)))
1058 ((eq (car x) *comma-atsign*)
1060 ;; ((eq (car x) *comma-dot*)
1061 ;; (list *bq-clobberable* (cadr x)))
1062 (t (list *bq-list* (bq-process x)))))
1064 ;;; This auxiliary function is like MAPCAR but has two extra
1065 ;;; purposes: (1) it handles dotted lists; (2) it tries to make
1066 ;;; the result share with the argument x as much as possible.
1067 (defun maptree (fn x)
1070 (let ((a (funcall fn (car x)))
1071 (d (maptree fn (cdr x))))
1072 (if (and (eql a (car x)) (eql d (cdr x)))
1076 ;;; This predicate is true of a form that when read looked
1077 ;;; like %@foo or %.foo.
1078 (defun bq-splicing-frob (x)
1080 (or (eq (car x) *comma-atsign*)
1081 ;; (eq (car x) *comma-dot*)
1084 ;;; This predicate is true of a form that when read
1085 ;;; looked like %@foo or %.foo or just plain %foo.
1088 (or (eq (car x) *comma*)
1089 (eq (car x) *comma-atsign*)
1090 ;; (eq (car x) *comma-dot*)
1093 ;;; The simplifier essentially looks for calls to #:BQ-APPEND and
1094 ;;; tries to simplify them. The arguments to #:BQ-APPEND are
1095 ;;; processed from right to left, building up a replacement form.
1096 ;;; At each step a number of special cases are handled that,
1097 ;;; loosely speaking, look like this:
1099 ;;; (APPEND (LIST a b c) foo) => (LIST* a b c foo)
1100 ;;; provided a, b, c are not splicing frobs
1101 ;;; (APPEND (LIST* a b c) foo) => (LIST* a b (APPEND c foo))
1102 ;;; provided a, b, c are not splicing frobs
1103 ;;; (APPEND (QUOTE (x)) foo) => (LIST* (QUOTE x) foo)
1104 ;;; (APPEND (CLOBBERABLE x) foo) => (NCONC x foo)
1105 (defun bq-simplify (x)
1108 (let ((x (if (eq (car x) *bq-quote*)
1110 (maptree #'bq-simplify x))))
1111 (if (not (eq (car x) *bq-append*))
1113 (bq-simplify-args x)))))
1115 (defun bq-simplify-args (x)
1116 (do ((args (reverse (cdr x)) (cdr args))
1119 (cond ((atom (car args))
1120 (bq-attach-append *bq-append* (car args) result))
1121 ((and (eq (caar args) *bq-list*)
1122 (notany #'bq-splicing-frob (cdar args)))
1123 (bq-attach-conses (cdar args) result))
1124 ((and (eq (caar args) *bq-list**)
1125 (notany #'bq-splicing-frob (cdar args)))
1127 (reverse (cdr (reverse (cdar args))))
1128 (bq-attach-append *bq-append*
1129 (car (last (car args)))
1131 ((and (eq (caar args) *bq-quote*)
1132 (consp (cadar args))
1133 (not (bq-frob (cadar args)))
1134 (null (cddar args)))
1135 (bq-attach-conses (list (list *bq-quote*
1138 ((eq (caar args) *bq-clobberable*)
1139 (bq-attach-append *bq-nconc* (cadar args) result))
1140 (t (bq-attach-append *bq-append*
1143 ((null args) result)))
1145 (defun null-or-quoted (x)
1146 (or (null x) (and (consp x) (eq (car x) *bq-quote*))))
1148 ;;; When BQ-ATTACH-APPEND is called, the OP should be #:BQ-APPEND
1149 ;;; or #:BQ-NCONC. This produces a form (op item result) but
1150 ;;; some simplifications are done on the fly:
1152 ;;; (op '(a b c) '(d e f g)) => '(a b c d e f g)
1153 ;;; (op item 'nil) => item, provided item is not a splicable frob
1154 ;;; (op item 'nil) => (op item), if item is a splicable frob
1155 ;;; (op item (op a b c)) => (op item a b c)
1156 (defun bq-attach-append (op item result)
1157 (cond ((and (null-or-quoted item) (null-or-quoted result))
1158 (list *bq-quote* (append (cadr item) (cadr result))))
1159 ((or (null result) (equal result *bq-quote-nil*))
1160 (if (bq-splicing-frob item) (list op item) item))
1161 ((and (consp result) (eq (car result) op))
1162 (list* (car result) item (cdr result)))
1163 (t (list op item result))))
1165 ;;; The effect of BQ-ATTACH-CONSES is to produce a form as if by
1166 ;;; `(LIST* ,@items ,result) but some simplifications are done
1169 ;;; (LIST* 'a 'b 'c 'd) => '(a b c . d)
1170 ;;; (LIST* a b c 'nil) => (LIST a b c)
1171 ;;; (LIST* a b c (LIST* d e f g)) => (LIST* a b c d e f g)
1172 ;;; (LIST* a b c (LIST d e f g)) => (LIST a b c d e f g)
1173 (defun bq-attach-conses (items result)
1174 (cond ((and (every #'null-or-quoted items)
1175 (null-or-quoted result))
1177 (append (mapcar #'cadr items) (cadr result))))
1178 ((or (null result) (equal result *bq-quote-nil*))
1179 (cons *bq-list* items))
1180 ((and (consp result)
1181 (or (eq (car result) *bq-list*)
1182 (eq (car result) *bq-list**)))
1183 (cons (car result) (append items (cdr result))))
1184 (t (cons *bq-list** (append items (list result))))))
1186 ;;; Removes funny tokens and changes (#:BQ-LIST* a b) into
1187 ;;; (CONS a b) instead of (LIST* a b), purely for readability.
1188 (defun bq-remove-tokens (x)
1189 (cond ((eq x *bq-list*) 'list)
1190 ((eq x *bq-append*) 'append)
1191 ((eq x *bq-nconc*) 'nconc)
1192 ((eq x *bq-list**) 'list*)
1193 ((eq x *bq-quote*) 'quote)
1195 ((eq (car x) *bq-clobberable*)
1196 (bq-remove-tokens (cadr x)))
1197 ((and (eq (car x) *bq-list**)
1200 (cons 'cons (maptree #'bq-remove-tokens (cdr x))))
1201 (t (maptree #'bq-remove-tokens x))))
1203 (define-transformation backquote (form)
1204 (bq-completely-process form))
1209 (defvar *builtins* nil)
1211 (defmacro define-raw-builtin (name args &body body)
1212 ;; Creates a new primitive function `name' with parameters args and
1213 ;; @body. The body can access to the local environment through the
1214 ;; variable *ENVIRONMENT*.
1215 `(push (list ',name (lambda ,args (block ,name ,@body)))
1218 (defmacro define-builtin (name args &body body)
1219 `(define-raw-builtin ,name ,args
1220 (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1223 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1224 (defmacro type-check (decls &body body)
1226 ,@(mapcar (lambda (decl)
1227 `(code "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1229 ,@(mapcar (lambda (decl)
1230 `(code "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1231 (indent "throw 'The value ' + "
1233 " + ' is not a type "
1238 (code "return " (progn ,@body) ";" *newline*)))
1240 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
1241 ;;; a variable which holds a list of forms. It will compile them and
1242 ;;; store the result in some Javascript variables. BODY is evaluated
1243 ;;; with ARGS bound to the list of these variables to generate the
1244 ;;; code which performs the transformation on these variables.
1246 (defun variable-arity-call (args function)
1247 (unless (consp args)
1248 (error "ARGS must be a non-empty list"))
1254 ((floatp x) (push (float-to-string x) fargs))
1255 ((numberp x) (push (integer-to-string x) fargs))
1256 (t (let ((v (code "x" (incf counter))))
1259 (code "var " v " = " (ls-compile x) ";" *newline*
1260 "if (typeof " v " !== 'number') throw 'Not a number!';"
1262 (js!selfcall prelude (funcall function (reverse fargs)))))
1265 (defmacro variable-arity (args &body body)
1266 (unless (symbolp args)
1267 (error "`~S' is not a symbol." args))
1268 `(variable-arity-call ,args
1270 (code "return " ,@body ";" *newline*))))
1272 (defun num-op-num (x op y)
1273 (type-check (("x" "number" x) ("y" "number" y))
1276 (define-raw-builtin + (&rest numbers)
1279 (variable-arity numbers
1280 (join numbers "+"))))
1282 (define-raw-builtin - (x &rest others)
1283 (let ((args (cons x others)))
1284 (variable-arity args
1286 (concat "-" (car args))
1289 (define-raw-builtin * (&rest numbers)
1292 (variable-arity numbers
1293 (join numbers "*"))))
1295 (define-raw-builtin / (x &rest others)
1296 (let ((args (cons x others)))
1297 (variable-arity args
1299 (concat "1 /" (car args))
1302 (define-builtin mod (x y) (num-op-num x "%" y))
1305 (defun comparison-conjuntion (vars op)
1310 (concat (car vars) op (cadr vars)))
1312 (concat (car vars) op (cadr vars)
1314 (comparison-conjuntion (cdr vars) op)))))
1316 (defmacro define-builtin-comparison (op sym)
1317 `(define-raw-builtin ,op (x &rest args)
1318 (let ((args (cons x args)))
1319 (variable-arity args
1320 (js!bool (comparison-conjuntion args ,sym))))))
1322 (define-builtin-comparison > ">")
1323 (define-builtin-comparison < "<")
1324 (define-builtin-comparison >= ">=")
1325 (define-builtin-comparison <= "<=")
1326 (define-builtin-comparison = "==")
1328 (define-builtin numberp (x)
1329 (js!bool (code "(typeof (" x ") == \"number\")")))
1331 (define-builtin floor (x)
1332 (type-check (("x" "number" x))
1335 (define-builtin expt (x y)
1336 (type-check (("x" "number" x)
1340 (define-builtin float-to-string (x)
1341 (type-check (("x" "number" x))
1342 "make_lisp_string(x.toString())"))
1344 (define-builtin cons (x y)
1345 (code "({car: " x ", cdr: " y "})"))
1347 (define-builtin consp (x)
1350 "var tmp = " x ";" *newline*
1351 "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1353 (define-builtin car (x)
1355 "var tmp = " x ";" *newline*
1356 "return tmp === " (ls-compile nil)
1357 "? " (ls-compile nil)
1358 ": tmp.car;" *newline*))
1360 (define-builtin cdr (x)
1362 "var tmp = " x ";" *newline*
1363 "return tmp === " (ls-compile nil) "? "
1365 ": tmp.cdr;" *newline*))
1367 (define-builtin rplaca (x new)
1368 (type-check (("x" "object" x))
1369 (code "(x.car = " new ", x)")))
1371 (define-builtin rplacd (x new)
1372 (type-check (("x" "object" x))
1373 (code "(x.cdr = " new ", x)")))
1375 (define-builtin symbolp (x)
1376 (js!bool (code "(" x " instanceof Symbol)")))
1378 (define-builtin make-symbol (name)
1379 (code "(new Symbol(" name "))"))
1381 (define-builtin symbol-name (x)
1382 (code "(" x ").name"))
1384 (define-builtin set (symbol value)
1385 (code "(" symbol ").value = " value))
1387 (define-builtin fset (symbol value)
1388 (code "(" symbol ").fvalue = " value))
1390 (define-builtin boundp (x)
1391 (js!bool (code "(" x ".value !== undefined)")))
1393 (define-builtin fboundp (x)
1394 (js!bool (code "(" x ".fvalue !== undefined)")))
1396 (define-builtin symbol-value (x)
1398 "var symbol = " x ";" *newline*
1399 "var value = symbol.value;" *newline*
1400 "if (value === undefined) throw \"Variable `\" + xstring(symbol.name) + \"' is unbound.\";" *newline*
1401 "return value;" *newline*))
1403 (define-builtin symbol-function (x)
1405 "var symbol = " x ";" *newline*
1406 "var func = symbol.fvalue;" *newline*
1407 "if (func === undefined) throw \"Function `\" + xstring(symbol.name) + \"' is undefined.\";" *newline*
1408 "return func;" *newline*))
1410 (define-builtin symbol-plist (x)
1411 (code "((" x ").plist || " (ls-compile nil) ")"))
1413 (define-builtin lambda-code (x)
1414 (code "make_lisp_string((" x ").toString())"))
1416 (define-builtin eq (x y)
1417 (js!bool (code "(" x " === " y ")")))
1419 (define-builtin char-code (x)
1420 (type-check (("x" "string" x))
1423 (define-builtin code-char (x)
1424 (type-check (("x" "number" x))
1425 "String.fromCharCode(x)"))
1427 (define-builtin characterp (x)
1430 "var x = " x ";" *newline*
1431 "return (typeof(" x ") == \"string\") && x.length == 1;")))
1433 (define-builtin char-to-string (x)
1435 "var r = [" x "];" *newline*
1436 "r.type = 'character';"
1439 (define-builtin char-upcase (x)
1440 (code x ".toUpperCase()"))
1442 (define-builtin char-downcase (x)
1443 (code x ".toLowerCase()"))
1445 (define-builtin stringp (x)
1448 "var x = " x ";" *newline*
1449 "return typeof(x) == 'object' && 'length' in x && x.type == 'character';")))
1451 (define-builtin string-upcase (x)
1452 (code "make_lisp_string(xstring(" x ").toUpperCase())"))
1454 (define-builtin string-length (x)
1457 (define-raw-builtin slice (vector a &optional b)
1459 "var vector = " (ls-compile vector) ";" *newline*
1460 "var a = " (ls-compile a) ";" *newline*
1462 (when b (code "b = " (ls-compile b) ";" *newline*))
1463 "return vector.slice(a,b);" *newline*))
1465 (define-builtin char (string index)
1466 (code string "[" index "]"))
1468 (define-builtin concat-two (string1 string2)
1470 "var r = " string1 ".concat(" string2 ");" *newline*
1471 "r.type = 'character';"
1472 "return r;" *newline*))
1474 (define-raw-builtin funcall (func &rest args)
1476 "var f = " (ls-compile func) ";" *newline*
1477 "return (typeof f === 'function'? f: f.fvalue)("
1478 (join (list* (if *multiple-value-p* "values" "pv")
1479 (integer-to-string (length args))
1480 (mapcar #'ls-compile args))
1484 (define-raw-builtin apply (func &rest args)
1486 (code "(" (ls-compile func) ")()")
1487 (let ((args (butlast args))
1488 (last (car (last args))))
1490 "var f = " (ls-compile func) ";" *newline*
1491 "var args = [" (join (list* (if *multiple-value-p* "values" "pv")
1492 (integer-to-string (length args))
1493 (mapcar #'ls-compile args))
1496 "var tail = (" (ls-compile last) ");" *newline*
1497 "while (tail != " (ls-compile nil) "){" *newline*
1498 " args.push(tail.car);" *newline*
1499 " args[1] += 1;" *newline*
1500 " tail = tail.cdr;" *newline*
1502 "return (typeof f === 'function'? f : f.fvalue).apply(this, args);" *newline*))))
1504 (define-builtin js-eval (string)
1505 (if *multiple-value-p*
1507 "var v = globalEval(xstring(" string "));" *newline*
1508 "return values.apply(this, forcemv(v));" *newline*)
1509 (code "globalEval(xstring(" string "))")))
1511 (define-builtin %throw (string)
1512 (js!selfcall "throw " string ";" *newline*))
1514 (define-builtin new () "{}")
1516 (define-builtin objectp (x)
1517 (js!bool (code "(typeof (" x ") === 'object')")))
1519 (define-builtin oget (object key)
1521 "var tmp = " "(" object ")[xstring(" key ")];" *newline*
1522 "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1524 (define-builtin oset (object key value)
1525 (code "((" object ")[xstring(" key ")] = " value ")"))
1527 (define-builtin in (key object)
1528 (js!bool (code "(xstring(" key ") in (" object "))")))
1530 (define-builtin map-for-in (function object)
1532 "var f = " function ";" *newline*
1533 "var g = (typeof f === 'function' ? f : f.fvalue);" *newline*
1534 "var o = " object ";" *newline*
1535 "for (var key in o){" *newline*
1536 (indent "g(" (if *multiple-value-p* "values" "pv") ", 1, o[key]);" *newline*)
1538 " return " (ls-compile nil) ";" *newline*))
1540 (define-builtin functionp (x)
1541 (js!bool (code "(typeof " x " == 'function')")))
1543 (define-builtin write-string (x)
1544 (code "lisp.write(" x ")"))
1546 (define-builtin make-array (n)
1548 "var r = [];" *newline*
1549 "for (var i = 0; i < " n "; i++)" *newline*
1550 (indent "r.push(" (ls-compile nil) ");" *newline*)
1551 "return r;" *newline*))
1553 ;;; FIXME: should take optional min-extension.
1554 ;;; FIXME: should use fill-pointer instead of the absolute end of array
1555 (define-builtin vector-push-extend (new vector)
1557 "var v = " vector ";" *newline*
1558 "v.push(" new ");" *newline*
1561 (define-builtin arrayp (x)
1564 "var x = " x ";" *newline*
1565 "return typeof x === 'object' && 'length' in x;")))
1567 (define-builtin aref (array n)
1569 "var x = " "(" array ")[" n "];" *newline*
1570 "if (x === undefined) throw 'Out of range';" *newline*
1571 "return x;" *newline*))
1573 (define-builtin aset (array n value)
1575 "var x = " array ";" *newline*
1576 "var i = " n ";" *newline*
1577 "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
1578 "return x[i] = " value ";" *newline*))
1580 (define-builtin afind (value array)
1582 "var v = " value ";" *newline*
1583 "var x = " array ";" *newline*
1584 "return x.indexOf(v);" *newline*))
1586 (define-builtin aresize (array new-size)
1588 "var x = " array ";" *newline*
1589 "var n = " new-size ";" *newline*
1590 "return x.length = n;" *newline*))
1592 (define-builtin get-internal-real-time ()
1593 "(new Date()).getTime()")
1595 (define-builtin values-array (array)
1596 (if *multiple-value-p*
1597 (code "values.apply(this, " array ")")
1598 (code "pv.apply(this, " array ")")))
1600 (define-raw-builtin values (&rest args)
1601 (if *multiple-value-p*
1602 (code "values(" (join (mapcar #'ls-compile args) ", ") ")")
1603 (code "pv(" (join (mapcar #'ls-compile args) ", ") ")")))
1608 (define-compilation %js-vref (var)
1609 (code "js_to_lisp(" var ")"))
1611 (define-compilation %js-vset (var val)
1612 (code "(" var " = lisp_to_js(" (ls-compile val) "))"))
1614 (define-setf-expander %js-vref (var)
1615 (let ((new-value (gensym)))
1616 (unless (stringp var)
1617 (error "`~S' is not a string." var))
1621 `(%js-vset ,var ,new-value)
1626 (defvar *macroexpander-cache*
1627 (make-hash-table :test #'eq))
1629 (defun !macro-function (symbol)
1630 (unless (symbolp symbol)
1631 (error "`~S' is not a symbol." symbol))
1632 (let ((b (lookup-in-lexenv symbol *environment* 'function)))
1633 (if (and b (eq (binding-type b) 'macro))
1634 (let ((expander (binding-value b)))
1637 ((gethash b *macroexpander-cache*)
1638 (setq expander (gethash b *macroexpander-cache*)))
1640 (let ((compiled (eval expander)))
1641 ;; The list representation are useful while
1642 ;; bootstrapping, as we can dump the definition of the
1643 ;; macros easily, but they are slow because we have to
1644 ;; evaluate them and compile them now and again. So, let
1645 ;; us replace the list representation version of the
1646 ;; function with the compiled one.
1648 #+jscl (setf (binding-value b) compiled)
1649 #-jscl (setf (gethash b *macroexpander-cache*) compiled)
1650 (setq expander compiled))))
1654 (defun !macroexpand-1 (form)
1657 (let ((b (lookup-in-lexenv form *environment* 'variable)))
1658 (if (and b (eq (binding-type b) 'macro))
1659 (values (binding-value b) t)
1660 (values form nil))))
1661 ((and (consp form) (symbolp (car form)))
1662 (let ((macrofun (!macro-function (car form))))
1664 (values (funcall macrofun (cdr form)) t)
1665 (values form nil))))
1667 (values form nil))))
1669 (defun compile-funcall (function args)
1670 (let* ((values-funcs (if *multiple-value-p* "values" "pv"))
1671 (arglist (concat "(" (join (list* values-funcs
1672 (integer-to-string (length args))
1673 (mapcar #'ls-compile args)) ", ") ")")))
1674 (unless (or (symbolp function)
1675 (and (consp function)
1676 (eq (car function) 'lambda)))
1677 (error "Bad function designator `~S'" function))
1679 ((translate-function function)
1680 (concat (translate-function function) arglist))
1681 ((and (symbolp function)
1682 #+jscl (eq (symbol-package function) (find-package "COMMON-LISP"))
1684 (code (ls-compile `',function) ".fvalue" arglist))
1686 (code (ls-compile `#',function) arglist)))))
1688 (defun ls-compile-block (sexps &optional return-last-p decls-allowed-p)
1689 (multiple-value-bind (sexps decls)
1690 (parse-body sexps :declarations decls-allowed-p)
1691 (declare (ignore decls))
1693 (code (ls-compile-block (butlast sexps) nil decls-allowed-p)
1694 "return " (ls-compile (car (last sexps)) *multiple-value-p*) ";")
1696 (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
1697 (concat ";" *newline*)))))
1699 (defun ls-compile (sexp &optional multiple-value-p)
1700 (multiple-value-bind (sexp expandedp) (!macroexpand-1 sexp)
1702 (return-from ls-compile (ls-compile sexp multiple-value-p)))
1703 ;; The expression has been macroexpanded. Now compile it!
1704 (let ((*multiple-value-p* multiple-value-p))
1707 (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1709 ((and b (not (member 'special (binding-declarations b))))
1711 ((or (keywordp sexp)
1712 (and b (member 'constant (binding-declarations b))))
1713 (code (ls-compile `',sexp) ".value"))
1715 (ls-compile `(symbol-value ',sexp))))))
1716 ((or (integerp sexp) (floatp sexp) (characterp sexp) (stringp sexp) (arrayp sexp))
1719 (let ((name (car sexp))
1723 ((assoc name *compilations*)
1724 (let ((comp (second (assoc name *compilations*))))
1726 ;; Built-in functions
1727 ((and (assoc name *builtins*)
1728 (not (claimp name 'function 'notinline)))
1729 (let ((comp (second (assoc name *builtins*))))
1732 (compile-funcall name args)))))
1734 (error "How should I compile `~S'?" sexp))))))
1737 (defvar *compile-print-toplevels* nil)
1739 (defun truncate-string (string &optional (width 60))
1740 (let ((n (or (position #\newline string)
1741 (min width (length string)))))
1742 (subseq string 0 n)))
1744 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
1745 (let ((*toplevel-compilations* nil))
1747 ((and (consp sexp) (eq (car sexp) 'progn))
1748 (let ((subs (mapcar (lambda (s)
1749 (ls-compile-toplevel s t))
1751 (join (remove-if #'null-or-empty-p subs))))
1753 (when *compile-print-toplevels*
1754 (let ((form-string (prin1-to-string sexp)))
1755 (format t "Compiling ~a..." (truncate-string form-string))))
1756 (let ((code (ls-compile sexp multiple-value-p)))
1757 (code (join-trailing (get-toplevel-compilations)
1758 (code ";" *newline*))
1760 (code code ";" *newline*))))))))