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."))))
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)
90 ;; A very simple defstruct built on lists. It supports just slot with
91 ;; an optional default initform, and it will create a constructor,
92 ;; predicate and accessors for you.
93 (defmacro def!struct (name &rest slots)
94 (unless (symbolp name)
95 (error "It is not a full defstruct implementation."))
96 (let* ((name-string (symbol-name name))
102 ((and (listp sd) (car sd) (cddr sd))
105 (error "Bad slot accessor."))))
107 (predicate (intern (concat name-string "-P"))))
110 (defun ,(intern (concat "MAKE-" name-string)) (&key ,@slot-descriptions)
111 (list ',name ,@(mapcar #'car slot-descriptions)))
113 (defun ,predicate (x)
114 (and (consp x) (eq (car x) ',name)))
116 (defun ,(intern (concat "COPY-" name-string)) (x)
121 (dolist (slot slot-descriptions)
122 (let* ((name (car slot))
123 (accessor-name (intern (concat name-string "-" (string name)))))
125 `(defun ,accessor-name (x)
126 (unless (,predicate x)
127 (error ,(concat "The object is not a type " name-string)))
129 ;; TODO: Implement this with a higher level
130 ;; abstraction like defsetf or (defun (setf ..))
132 `(define-setf-expander ,accessor-name (x)
133 (let ((object (gensym))
134 (new-value (gensym)))
135 (values (list object)
139 (rplaca (nthcdr ,',index ,object) ,new-value)
141 `(,',accessor-name ,object)))))
160 (defun lookup-in-lexenv (name lexenv namespace)
161 (find name (ecase namespace
162 (variable (lexenv-variable lexenv))
163 (function (lexenv-function lexenv))
164 (block (lexenv-block lexenv))
165 (gotag (lexenv-gotag lexenv)))
166 :key #'binding-name))
168 (defun push-to-lexenv (binding lexenv namespace)
170 (variable (push binding (lexenv-variable lexenv)))
171 (function (push binding (lexenv-function lexenv)))
172 (block (push binding (lexenv-block lexenv)))
173 (gotag (push binding (lexenv-gotag lexenv)))))
175 (defun extend-lexenv (bindings lexenv namespace)
176 (let ((env (copy-lexenv lexenv)))
177 (dolist (binding (reverse bindings) env)
178 (push-to-lexenv binding env namespace))))
181 (defvar *environment* (make-lexenv))
183 (defvar *variable-counter* 0)
185 (defun gvarname (symbol)
186 (declare (ignore symbol))
187 (code "v" (incf *variable-counter*)))
189 (defun translate-variable (symbol)
190 (awhen (lookup-in-lexenv symbol *environment* 'variable)
193 (defun extend-local-env (args)
194 (let ((new (copy-lexenv *environment*)))
195 (dolist (symbol args new)
196 (let ((b (make-binding :name symbol :type 'variable :value (gvarname symbol))))
197 (push-to-lexenv b new 'variable)))))
199 ;;; Toplevel compilations
200 (defvar *toplevel-compilations* nil)
202 (defun toplevel-compilation (string)
203 (push string *toplevel-compilations*))
205 (defun null-or-empty-p (x)
208 (defun get-toplevel-compilations ()
209 (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
211 (defun %compile-defmacro (name lambda)
212 (toplevel-compilation (ls-compile `',name))
213 (let ((binding (make-binding :name name :type 'macro :value lambda)))
214 (push-to-lexenv binding *environment* 'function))
217 (defun global-binding (name type namespace)
218 (or (lookup-in-lexenv name *environment* namespace)
219 (let ((b (make-binding :name name :type type :value nil)))
220 (push-to-lexenv b *environment* namespace)
223 (defun claimp (symbol namespace claim)
224 (let ((b (lookup-in-lexenv symbol *environment* namespace)))
225 (and b (member claim (binding-declarations b)))))
227 (defun !proclaim (decl)
230 (dolist (name (cdr decl))
231 (let ((b (global-binding name 'variable 'variable)))
232 (push 'special (binding-declarations b)))))
234 (dolist (name (cdr decl))
235 (let ((b (global-binding name 'function 'function)))
236 (push 'notinline (binding-declarations b)))))
238 (dolist (name (cdr decl))
239 (let ((b (global-binding name 'variable 'variable)))
240 (push 'constant (binding-declarations b)))))))
243 (fset 'proclaim #'!proclaim)
245 (defun %define-symbol-macro (name expansion)
246 (let ((b (make-binding :name name :type 'macro :value expansion)))
247 (push-to-lexenv b *environment* 'variable)
251 (defmacro define-symbol-macro (name expansion)
252 `(%define-symbol-macro ',name ',expansion))
257 (defvar *compilations* nil)
259 (defmacro define-compilation (name args &body body)
260 ;; Creates a new primitive `name' with parameters args and
261 ;; @body. The body can access to the local environment through the
262 ;; variable *ENVIRONMENT*.
263 `(push (list ',name (lambda ,args (block ,name ,@body)))
266 (define-compilation if (condition true false)
267 (code "(" (ls-compile condition) " !== " (ls-compile nil)
268 " ? " (ls-compile true *multiple-value-p*)
269 " : " (ls-compile false *multiple-value-p*)
272 (defvar *ll-keywords* '(&optional &rest &key))
274 (defun list-until-keyword (list)
275 (if (or (null list) (member (car list) *ll-keywords*))
277 (cons (car list) (list-until-keyword (cdr list)))))
279 (defun ll-section (keyword ll)
280 (list-until-keyword (cdr (member keyword ll))))
282 (defun ll-required-arguments (ll)
283 (list-until-keyword ll))
285 (defun ll-optional-arguments-canonical (ll)
286 (mapcar #'ensure-list (ll-section '&optional ll)))
288 (defun ll-optional-arguments (ll)
289 (mapcar #'car (ll-optional-arguments-canonical ll)))
291 (defun ll-rest-argument (ll)
292 (let ((rest (ll-section '&rest ll)))
294 (error "Bad lambda-list"))
297 (defun ll-keyword-arguments-canonical (ll)
298 (flet ((canonicalize (keyarg)
299 ;; Build a canonical keyword argument descriptor, filling
300 ;; the optional fields. The result is a list of the form
301 ;; ((keyword-name var) init-form).
302 (let ((arg (ensure-list keyarg)))
303 (cons (if (listp (car arg))
305 (list (intern (symbol-name (car arg)) "KEYWORD") (car arg)))
307 (mapcar #'canonicalize (ll-section '&key ll))))
309 (defun ll-keyword-arguments (ll)
310 (mapcar (lambda (keyarg) (second (first keyarg)))
311 (ll-keyword-arguments-canonical ll)))
313 (defun ll-svars (lambda-list)
316 (ll-keyword-arguments-canonical lambda-list)
317 (ll-optional-arguments-canonical lambda-list))))
318 (remove nil (mapcar #'third args))))
320 (defun lambda-name/docstring-wrapper (name docstring &rest strs)
321 (if (or name docstring)
323 "var func = " (join strs) ";" *newline*
325 (code "func.fname = '" (escape-string name) "';" *newline*))
327 (code "func.docstring = '" (escape-string docstring) "';" *newline*))
328 "return func;" *newline*)
329 (apply #'code strs)))
331 (defun lambda-check-argument-count
332 (n-required-arguments n-optional-arguments rest-p)
333 ;; Note: Remember that we assume that the number of arguments of a
334 ;; call is at least 1 (the values argument).
335 (let ((min (1+ n-required-arguments))
336 (max (if rest-p 'n/a (+ 1 n-required-arguments n-optional-arguments))))
338 ;; Special case: a positive exact number of arguments.
339 (when (and (< 1 min) (eql min max))
340 (return (code "checkArgs(arguments, " min ");" *newline*)))
344 (code "checkArgsAtLeast(arguments, " min ");" *newline*))
346 (code "checkArgsAtMost(arguments, " max ");" *newline*))))))
348 (defun compile-lambda-optional (ll)
349 (let* ((optional-arguments (ll-optional-arguments-canonical ll))
350 (n-required-arguments (length (ll-required-arguments ll)))
351 (n-optional-arguments (length optional-arguments)))
352 (when optional-arguments
353 (code (mapconcat (lambda (arg)
354 (code "var " (translate-variable (first arg)) "; " *newline*
356 (code "var " (translate-variable (third arg))
360 "switch(arguments.length-1){" *newline*
364 (while (< idx n-optional-arguments)
365 (let ((arg (nth idx optional-arguments)))
366 (push (code "case " (+ idx n-required-arguments) ":" *newline*
367 (indent (translate-variable (car arg))
369 (ls-compile (cadr arg)) ";" *newline*)
371 (indent (translate-variable (third arg))
377 (push (code "default: break;" *newline*) cases)
378 (join (reverse cases))))
381 (defun compile-lambda-rest (ll)
382 (let ((n-required-arguments (length (ll-required-arguments ll)))
383 (n-optional-arguments (length (ll-optional-arguments ll)))
384 (rest-argument (ll-rest-argument ll)))
386 (let ((js!rest (translate-variable rest-argument)))
387 (code "var " js!rest "= " (ls-compile nil) ";" *newline*
388 "for (var i = arguments.length-1; i>="
389 (+ 1 n-required-arguments n-optional-arguments)
391 (indent js!rest " = {car: arguments[i], cdr: ") js!rest "};"
394 (defun compile-lambda-parse-keywords (ll)
395 (let ((n-required-arguments
396 (length (ll-required-arguments ll)))
397 (n-optional-arguments
398 (length (ll-optional-arguments ll)))
400 (ll-keyword-arguments-canonical ll)))
403 (mapconcat (lambda (arg)
404 (let ((var (second (car arg))))
405 (code "var " (translate-variable var) "; " *newline*
407 (code "var " (translate-variable (third arg))
408 " = " (ls-compile nil)
412 (flet ((parse-keyword (keyarg)
413 ;; ((keyword-name var) init-form)
414 (code "for (i=" (+ 1 n-required-arguments n-optional-arguments)
415 "; i<arguments.length; i+=2){" *newline*
417 "if (arguments[i] === " (ls-compile (caar keyarg)) "){" *newline*
418 (indent (translate-variable (cadr (car keyarg)))
421 (let ((svar (third keyarg)))
423 (code (translate-variable svar) " = " (ls-compile t) ";" *newline*)))
428 "if (i == arguments.length){" *newline*
429 (indent (translate-variable (cadr (car keyarg))) " = " (ls-compile (cadr keyarg)) ";" *newline*)
431 (when keyword-arguments
432 (code "var i;" *newline*
433 (mapconcat #'parse-keyword keyword-arguments))))
434 ;; Check for unknown keywords
435 (when keyword-arguments
436 (code "for (i=" (+ 1 n-required-arguments n-optional-arguments)
437 "; i<arguments.length; i+=2){" *newline*
439 (join (mapcar (lambda (x)
440 (concat "arguments[i] !== " (ls-compile (caar x))))
445 "throw 'Unknown keyword argument ' + arguments[i].name;" *newline*))
448 (defun parse-lambda-list (ll)
449 (values (ll-required-arguments ll)
450 (ll-optional-arguments ll)
451 (ll-keyword-arguments ll)
452 (ll-rest-argument ll)))
454 ;;; Process BODY for declarations and/or docstrings. Return as
455 ;;; multiple values the BODY without docstrings or declarations, the
456 ;;; list of declaration forms and the docstring.
457 (defun parse-body (body &key declarations docstring)
458 (let ((value-declarations)
460 ;; Parse declarations
462 (do* ((rest body (cdr rest))
463 (form (car rest) (car rest)))
464 ((or (atom form) (not (eq (car form) 'declare)))
466 (push form value-declarations)))
470 (not (null (cdr body))))
471 (setq value-docstring (car body))
472 (setq body (cdr body)))
473 (values body value-declarations value-docstring)))
475 ;;; Compile a lambda function with lambda list LL and body BODY. If
476 ;;; NAME is given, it should be a constant string and it will become
477 ;;; the name of the function. If BLOCK is non-NIL, a named block is
478 ;;; created around the body. NOTE: No block (even anonymous) is
479 ;;; created if BLOCk is NIL.
480 (defun compile-lambda (ll body &key name block)
481 (multiple-value-bind (required-arguments
485 (parse-lambda-list ll)
486 (multiple-value-bind (body decls documentation)
487 (parse-body body :declarations t :docstring t)
488 (declare (ignore decls))
489 (let ((n-required-arguments (length required-arguments))
490 (n-optional-arguments (length optional-arguments))
491 (*environment* (extend-local-env
492 (append (ensure-list rest-argument)
497 (lambda-name/docstring-wrapper name documentation
500 (mapcar #'translate-variable
501 (append required-arguments optional-arguments)))
505 ;; Check number of arguments
506 (lambda-check-argument-count n-required-arguments
508 (or rest-argument keyword-arguments))
509 (compile-lambda-optional ll)
510 (compile-lambda-rest ll)
511 (compile-lambda-parse-keywords ll)
512 (let ((*multiple-value-p* t))
514 (ls-compile-block `((block ,block ,@body)) t)
515 (ls-compile-block body t))))
519 (defun setq-pair (var val)
520 (let ((b (lookup-in-lexenv var *environment* 'variable)))
523 (eq (binding-type b) 'variable)
524 (not (member 'special (binding-declarations b)))
525 (not (member 'constant (binding-declarations b))))
526 (code (binding-value b) " = " (ls-compile val)))
527 ((and b (eq (binding-type b) 'macro))
528 (ls-compile `(setf ,var ,val)))
530 (ls-compile `(set ',var ,val))))))
533 (define-compilation setq (&rest pairs)
537 ((null pairs) (return))
539 (error "Odd paris in SETQ"))
542 (concat (setq-pair (car pairs) (cadr pairs))
543 (if (null (cddr pairs)) "" ", ")))
544 (setq pairs (cddr pairs)))))
545 (code "(" result ")")))
549 (defun escape-string (string)
552 (size (length string)))
553 (while (< index size)
554 (let ((ch (char string index)))
555 (when (or (char= ch #\") (char= ch #\\))
556 (setq output (concat output "\\")))
557 (when (or (char= ch #\newline))
558 (setq output (concat output "\\"))
560 (setq output (concat output (string ch))))
565 (defvar *literal-table* nil)
566 (defvar *literal-counter* 0)
569 (code "l" (incf *literal-counter*)))
571 (defun dump-symbol (symbol)
573 (let ((package (symbol-package symbol)))
574 (if (eq package (find-package "KEYWORD"))
575 (code "{name: \"" (escape-string (symbol-name symbol))
576 "\", 'package': '" (package-name package) "'}")
577 (code "{name: \"" (escape-string (symbol-name symbol)) "\"}")))
579 (let ((package (symbol-package symbol)))
581 (code "{name: \"" (escape-string (symbol-name symbol)) "\"}")
582 (ls-compile `(intern ,(symbol-name symbol) ,(package-name package))))))
584 (defun dump-cons (cons)
585 (let ((head (butlast cons))
588 (join-trailing (mapcar (lambda (x) (literal x t)) head) ",")
589 (literal (car tail) t)
591 (literal (cdr tail) t)
594 (defun dump-array (array)
595 (let ((elements (vector-to-list array)))
596 (concat "[" (join (mapcar #'literal elements) ", ") "]")))
598 (defun literal (sexp &optional recursive)
600 ((integerp sexp) (integer-to-string sexp))
601 ((floatp sexp) (float-to-string sexp))
602 ((stringp sexp) (code "\"" (escape-string sexp) "\""))
604 (or (cdr (assoc sexp *literal-table*))
605 (let ((dumped (typecase sexp
606 (symbol (dump-symbol sexp))
607 (cons (dump-cons sexp))
608 (array (dump-array sexp)))))
609 (if (and recursive (not (symbolp sexp)))
611 (let ((jsvar (genlit)))
612 (push (cons sexp jsvar) *literal-table*)
613 (toplevel-compilation (code "var " jsvar " = " dumped))
616 (define-compilation quote (sexp)
619 (define-compilation %while (pred &rest body)
621 "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
622 (indent (ls-compile-block body))
624 "return " (ls-compile nil) ";" *newline*))
626 (define-compilation function (x)
628 ((and (listp x) (eq (car x) 'lambda))
629 (compile-lambda (cadr x) (cddr x)))
630 ((and (listp x) (eq (car x) 'named-lambda))
631 ;; TODO: destructuring-bind now! Do error checking manually is
633 (let ((name (cadr x))
636 (compile-lambda ll body
637 :name (symbol-name name)
640 (let ((b (lookup-in-lexenv x *environment* 'function)))
643 (ls-compile `(symbol-function ',x)))))))
646 (defun make-function-binding (fname)
647 (make-binding :name fname :type 'function :value (gvarname fname)))
649 (defun compile-function-definition (list)
650 (compile-lambda (car list) (cdr list)))
652 (defun translate-function (name)
653 (let ((b (lookup-in-lexenv name *environment* 'function)))
654 (and b (binding-value b))))
656 (define-compilation flet (definitions &rest body)
657 (let* ((fnames (mapcar #'car definitions))
658 (fbody (mapcar #'cdr definitions))
659 (cfuncs (mapcar #'compile-function-definition fbody))
661 (extend-lexenv (mapcar #'make-function-binding fnames)
665 (join (mapcar #'translate-function fnames) ",")
667 (let ((body (ls-compile-block body t)))
669 "})(" (join cfuncs ",") ")")))
671 (define-compilation labels (definitions &rest body)
672 (let* ((fnames (mapcar #'car definitions))
674 (extend-lexenv (mapcar #'make-function-binding fnames)
678 (mapconcat (lambda (func)
679 (code "var " (translate-function (car func))
680 " = " (compile-lambda (cadr func) (cddr func))
683 (ls-compile-block body t))))
686 (defvar *compiling-file* nil)
687 (define-compilation eval-when-compile (&rest body)
690 (eval (cons 'progn body))
692 (ls-compile `(progn ,@body))))
694 (defmacro define-transformation (name args form)
695 `(define-compilation ,name ,args
698 (define-compilation progn (&rest body)
699 (if (null (cdr body))
700 (ls-compile (car body) *multiple-value-p*)
701 (js!selfcall (ls-compile-block body t))))
703 (defun special-variable-p (x)
704 (and (claimp x 'variable 'special) t))
706 ;;; Wrap CODE to restore the symbol values of the dynamic
707 ;;; bindings. BINDINGS is a list of pairs of the form
708 ;;; (SYMBOL . PLACE), where PLACE is a Javascript variable
709 ;;; name to initialize the symbol value and where to stored
711 (defun let-binding-wrapper (bindings body)
712 (when (null bindings)
713 (return-from let-binding-wrapper body))
716 (indent "var tmp;" *newline*
719 (let ((s (ls-compile `(quote ,(car b)))))
720 (code "tmp = " s ".value;" *newline*
721 s ".value = " (cdr b) ";" *newline*
722 (cdr b) " = tmp;" *newline*)))
726 "finally {" *newline*
728 (mapconcat (lambda (b)
729 (let ((s (ls-compile `(quote ,(car b)))))
730 (code s ".value" " = " (cdr b) ";" *newline*)))
734 (define-compilation let (bindings &rest body)
735 (let* ((bindings (mapcar #'ensure-list bindings))
736 (variables (mapcar #'first bindings))
737 (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
738 (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
741 (join (mapcar (lambda (x)
742 (if (special-variable-p x)
743 (let ((v (gvarname x)))
744 (push (cons x v) dynamic-bindings)
746 (translate-variable x)))
750 (let ((body (ls-compile-block body t)))
751 (indent (let-binding-wrapper dynamic-bindings body)))
752 "})(" (join cvalues ",") ")")))
755 ;;; Return the code to initialize BINDING, and push it extending the
756 ;;; current lexical environment if the variable is not special.
757 (defun let*-initialize-value (binding)
758 (let ((var (first binding))
759 (value (second binding)))
760 (if (special-variable-p var)
761 (code (ls-compile `(setq ,var ,value)) ";" *newline*)
762 (let* ((v (gvarname var))
763 (b (make-binding :name var :type 'variable :value v)))
764 (prog1 (code "var " v " = " (ls-compile value) ";" *newline*)
765 (push-to-lexenv b *environment* 'variable))))))
767 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
768 ;;; DOES NOT generate code to initialize the value of the symbols,
769 ;;; unlike let-binding-wrapper.
770 (defun let*-binding-wrapper (symbols body)
772 (return-from let*-binding-wrapper body))
773 (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
774 (remove-if-not #'special-variable-p symbols))))
778 (mapconcat (lambda (b)
779 (let ((s (ls-compile `(quote ,(car b)))))
780 (code "var " (cdr b) " = " s ".value;" *newline*)))
784 "finally {" *newline*
786 (mapconcat (lambda (b)
787 (let ((s (ls-compile `(quote ,(car b)))))
788 (code s ".value" " = " (cdr b) ";" *newline*)))
792 (define-compilation let* (bindings &rest body)
793 (let ((bindings (mapcar #'ensure-list bindings))
794 (*environment* (copy-lexenv *environment*)))
796 (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
797 (body (concat (mapconcat #'let*-initialize-value bindings)
798 (ls-compile-block body t))))
799 (let*-binding-wrapper specials body)))))
802 (defvar *block-counter* 0)
804 (define-compilation block (name &rest body)
805 (let* ((tr (incf *block-counter*))
806 (b (make-binding :name name :type 'block :value tr)))
807 (when *multiple-value-p*
808 (push 'multiple-value (binding-declarations b)))
809 (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
810 (cbody (ls-compile-block body t)))
811 (if (member 'used (binding-declarations b))
816 "catch (cf){" *newline*
817 " if (cf.type == 'block' && cf.id == " tr ")" *newline*
818 (if *multiple-value-p*
819 " return values.apply(this, forcemv(cf.values));"
820 " return cf.values;")
823 " throw cf;" *newline*
825 (js!selfcall cbody)))))
827 (define-compilation return-from (name &optional value)
828 (let* ((b (lookup-in-lexenv name *environment* 'block))
829 (multiple-value-p (member 'multiple-value (binding-declarations b))))
831 (error (concat "Unknown block `" (symbol-name name) "'.")))
832 (push 'used (binding-declarations b))
834 (when multiple-value-p (code "var values = mv;" *newline*))
837 "id: " (binding-value b) ", "
838 "values: " (ls-compile value multiple-value-p) ", "
839 "message: 'Return from unknown block " (symbol-name name) ".'"
842 (define-compilation catch (id &rest body)
844 "var id = " (ls-compile id) ";" *newline*
846 (indent (ls-compile-block body t)) *newline*
848 "catch (cf){" *newline*
849 " if (cf.type == 'catch' && cf.id == id)" *newline*
850 (if *multiple-value-p*
851 " return values.apply(this, forcemv(cf.values));"
852 " return pv.apply(this, forcemv(cf.values));")
855 " throw cf;" *newline*
858 (define-compilation throw (id value)
860 "var values = mv;" *newline*
863 "id: " (ls-compile id) ", "
864 "values: " (ls-compile value t) ", "
865 "message: 'Throw uncatched.'"
869 (defvar *tagbody-counter* 0)
870 (defvar *go-tag-counter* 0)
873 (or (integerp x) (symbolp x)))
875 (defun declare-tagbody-tags (tbidx body)
877 (mapcar (lambda (label)
878 (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
879 (make-binding :name label :type 'gotag :value (list tbidx tagidx))))
880 (remove-if-not #'go-tag-p body))))
881 (extend-lexenv bindings *environment* 'gotag)))
883 (define-compilation tagbody (&rest body)
884 ;; Ignore the tagbody if it does not contain any go-tag. We do this
885 ;; because 1) it is easy and 2) many built-in forms expand to a
886 ;; implicit tagbody, so we save some space.
887 (unless (some #'go-tag-p body)
888 (return-from tagbody (ls-compile `(progn ,@body nil))))
889 ;; The translation assumes the first form in BODY is a label
890 (unless (go-tag-p (car body))
891 (push (gensym "START") body))
892 ;; Tagbody compilation
893 (let ((tbidx *tagbody-counter*))
894 (let ((*environment* (declare-tagbody-tags tbidx body))
896 (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
897 (setq initag (second (binding-value b))))
899 "var tagbody_" tbidx " = " initag ";" *newline*
901 "while (true) {" *newline*
902 (indent "try {" *newline*
903 (indent (let ((content ""))
904 (code "switch(tagbody_" tbidx "){" *newline*
905 "case " initag ":" *newline*
906 (dolist (form (cdr body) content)
908 (if (not (go-tag-p form))
909 (indent (ls-compile form) ";" *newline*)
910 (let ((b (lookup-in-lexenv form *environment* 'gotag)))
911 (code "case " (second (binding-value b)) ":" *newline*)))))
913 " break tbloop;" *newline*
916 "catch (jump) {" *newline*
917 " if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
918 " tagbody_" tbidx " = jump.label;" *newline*
920 " throw(jump);" *newline*
923 "return " (ls-compile nil) ";" *newline*))))
925 (define-compilation go (label)
926 (let ((b (lookup-in-lexenv label *environment* 'gotag))
928 ((symbolp label) (symbol-name label))
929 ((integerp label) (integer-to-string label)))))
931 (error (concat "Unknown tag `" n "'.")))
935 "id: " (first (binding-value b)) ", "
936 "label: " (second (binding-value b)) ", "
937 "message: 'Attempt to GO to non-existing tag " n "'"
940 (define-compilation unwind-protect (form &rest clean-up)
942 "var ret = " (ls-compile nil) ";" *newline*
944 (indent "ret = " (ls-compile form) ";" *newline*)
945 "} finally {" *newline*
946 (indent (ls-compile-block clean-up))
948 "return ret;" *newline*))
950 (define-compilation multiple-value-call (func-form &rest forms)
952 "var func = " (ls-compile func-form) ";" *newline*
953 "var args = [" (if *multiple-value-p* "values" "pv") "];" *newline*
956 "var values = mv;" *newline*
958 (mapconcat (lambda (form)
959 (code "vs = " (ls-compile form t) ";" *newline*
960 "if (typeof vs === 'object' && 'multiple-value' in vs)" *newline*
961 (indent "args = args.concat(vs);" *newline*)
963 (indent "args.push(vs);" *newline*)))
965 "return func.apply(window, args);" *newline*) ";" *newline*))
967 (define-compilation multiple-value-prog1 (first-form &rest forms)
969 "var args = " (ls-compile first-form *multiple-value-p*) ";" *newline*
970 (ls-compile-block forms)
971 "return args;" *newline*))
976 (define-compilation %js-vref (var) var)
978 (define-compilation %js-vset (var val)
979 (code "(" var " = " (ls-compile val) ")"))
981 (define-setf-expander %js-vref (var)
982 (let ((new-value (gensym)))
983 (unless (stringp var)
984 (error "a string was expected"))
988 `(%js-vset ,var ,new-value)
992 ;;; Backquote implementation.
994 ;;; Author: Guy L. Steele Jr. Date: 27 December 1985
995 ;;; Tested under Symbolics Common Lisp and Lucid Common Lisp.
996 ;;; This software is in the public domain.
998 ;;; The following are unique tokens used during processing.
999 ;;; They need not be symbols; they need not even be atoms.
1000 (defvar *comma* 'unquote)
1001 (defvar *comma-atsign* 'unquote-splicing)
1003 (defvar *bq-list* (make-symbol "BQ-LIST"))
1004 (defvar *bq-append* (make-symbol "BQ-APPEND"))
1005 (defvar *bq-list** (make-symbol "BQ-LIST*"))
1006 (defvar *bq-nconc* (make-symbol "BQ-NCONC"))
1007 (defvar *bq-clobberable* (make-symbol "BQ-CLOBBERABLE"))
1008 (defvar *bq-quote* (make-symbol "BQ-QUOTE"))
1009 (defvar *bq-quote-nil* (list *bq-quote* nil))
1011 ;;; BACKQUOTE is an ordinary macro (not a read-macro) that processes
1012 ;;; the expression foo, looking for occurrences of #:COMMA,
1013 ;;; #:COMMA-ATSIGN, and #:COMMA-DOT. It constructs code in strict
1014 ;;; accordance with the rules on pages 349-350 of the first edition
1015 ;;; (pages 528-529 of this second edition). It then optionally
1016 ;;; applies a code simplifier.
1018 ;;; If the value of *BQ-SIMPLIFY* is non-NIL, then BACKQUOTE
1019 ;;; processing applies the code simplifier. If the value is NIL,
1020 ;;; then the code resulting from BACKQUOTE is exactly that
1021 ;;; specified by the official rules.
1022 (defparameter *bq-simplify* t)
1024 (defmacro backquote (x)
1025 (bq-completely-process x))
1027 ;;; Backquote processing proceeds in three stages:
1029 ;;; (1) BQ-PROCESS applies the rules to remove occurrences of
1030 ;;; #:COMMA, #:COMMA-ATSIGN, and #:COMMA-DOT corresponding to
1031 ;;; this level of BACKQUOTE. (It also causes embedded calls to
1032 ;;; BACKQUOTE to be expanded so that nesting is properly handled.)
1033 ;;; Code is produced that is expressed in terms of functions
1034 ;;; #:BQ-LIST, #:BQ-APPEND, and #:BQ-CLOBBERABLE. This is done
1035 ;;; so that the simplifier will simplify only list construction
1036 ;;; functions actually generated by BACKQUOTE and will not involve
1037 ;;; any user code in the simplification. #:BQ-LIST means LIST,
1038 ;;; #:BQ-APPEND means APPEND, and #:BQ-CLOBBERABLE means IDENTITY
1039 ;;; but indicates places where "%." was used and where NCONC may
1040 ;;; therefore be introduced by the simplifier for efficiency.
1042 ;;; (2) BQ-SIMPLIFY, if used, rewrites the code produced by
1043 ;;; BQ-PROCESS to produce equivalent but faster code. The
1044 ;;; additional functions #:BQ-LIST* and #:BQ-NCONC may be
1045 ;;; introduced into the code.
1047 ;;; (3) BQ-REMOVE-TOKENS goes through the code and replaces
1048 ;;; #:BQ-LIST with LIST, #:BQ-APPEND with APPEND, and so on.
1049 ;;; #:BQ-CLOBBERABLE is simply eliminated (a call to it being
1050 ;;; replaced by its argument). #:BQ-LIST* is replaced by either
1051 ;;; LIST* or CONS (the latter is used in the two-argument case,
1052 ;;; purely to make the resulting code a tad more readable).
1054 (defun bq-completely-process (x)
1055 (let ((raw-result (bq-process x)))
1056 (bq-remove-tokens (if *bq-simplify*
1057 (bq-simplify raw-result)
1060 (defun bq-process (x)
1062 (list *bq-quote* x))
1063 ((eq (car x) 'backquote)
1064 (bq-process (bq-completely-process (cadr x))))
1065 ((eq (car x) *comma*) (cadr x))
1066 ((eq (car x) *comma-atsign*)
1067 ;; (error ",@~S after `" (cadr x))
1068 (error "ill-formed"))
1069 ;; ((eq (car x) *comma-dot*)
1070 ;; ;; (error ",.~S after `" (cadr x))
1071 ;; (error "ill-formed"))
1072 (t (do ((p x (cdr p))
1073 (q '() (cons (bracket (car p)) q)))
1076 (nreconc q (list (list *bq-quote* p)))))
1077 (when (eq (car p) *comma*)
1078 (unless (null (cddr p))
1079 ;; (error "Malformed ,~S" p)
1080 (error "Malformed"))
1081 (return (cons *bq-append*
1082 (nreconc q (list (cadr p))))))
1083 (when (eq (car p) *comma-atsign*)
1084 ;; (error "Dotted ,@~S" p)
1086 ;; (when (eq (car p) *comma-dot*)
1087 ;; ;; (error "Dotted ,.~S" p)
1088 ;; (error "Dotted"))
1091 ;;; This implements the bracket operator of the formal rules.
1094 (list *bq-list* (bq-process x)))
1095 ((eq (car x) *comma*)
1096 (list *bq-list* (cadr x)))
1097 ((eq (car x) *comma-atsign*)
1099 ;; ((eq (car x) *comma-dot*)
1100 ;; (list *bq-clobberable* (cadr x)))
1101 (t (list *bq-list* (bq-process x)))))
1103 ;;; This auxiliary function is like MAPCAR but has two extra
1104 ;;; purposes: (1) it handles dotted lists; (2) it tries to make
1105 ;;; the result share with the argument x as much as possible.
1106 (defun maptree (fn x)
1109 (let ((a (funcall fn (car x)))
1110 (d (maptree fn (cdr x))))
1111 (if (and (eql a (car x)) (eql d (cdr x)))
1115 ;;; This predicate is true of a form that when read looked
1116 ;;; like %@foo or %.foo.
1117 (defun bq-splicing-frob (x)
1119 (or (eq (car x) *comma-atsign*)
1120 ;; (eq (car x) *comma-dot*)
1123 ;;; This predicate is true of a form that when read
1124 ;;; looked like %@foo or %.foo or just plain %foo.
1127 (or (eq (car x) *comma*)
1128 (eq (car x) *comma-atsign*)
1129 ;; (eq (car x) *comma-dot*)
1132 ;;; The simplifier essentially looks for calls to #:BQ-APPEND and
1133 ;;; tries to simplify them. The arguments to #:BQ-APPEND are
1134 ;;; processed from right to left, building up a replacement form.
1135 ;;; At each step a number of special cases are handled that,
1136 ;;; loosely speaking, look like this:
1138 ;;; (APPEND (LIST a b c) foo) => (LIST* a b c foo)
1139 ;;; provided a, b, c are not splicing frobs
1140 ;;; (APPEND (LIST* a b c) foo) => (LIST* a b (APPEND c foo))
1141 ;;; provided a, b, c are not splicing frobs
1142 ;;; (APPEND (QUOTE (x)) foo) => (LIST* (QUOTE x) foo)
1143 ;;; (APPEND (CLOBBERABLE x) foo) => (NCONC x foo)
1144 (defun bq-simplify (x)
1147 (let ((x (if (eq (car x) *bq-quote*)
1149 (maptree #'bq-simplify x))))
1150 (if (not (eq (car x) *bq-append*))
1152 (bq-simplify-args x)))))
1154 (defun bq-simplify-args (x)
1155 (do ((args (reverse (cdr x)) (cdr args))
1158 (cond ((atom (car args))
1159 (bq-attach-append *bq-append* (car args) result))
1160 ((and (eq (caar args) *bq-list*)
1161 (notany #'bq-splicing-frob (cdar args)))
1162 (bq-attach-conses (cdar args) result))
1163 ((and (eq (caar args) *bq-list**)
1164 (notany #'bq-splicing-frob (cdar args)))
1166 (reverse (cdr (reverse (cdar args))))
1167 (bq-attach-append *bq-append*
1168 (car (last (car args)))
1170 ((and (eq (caar args) *bq-quote*)
1171 (consp (cadar args))
1172 (not (bq-frob (cadar args)))
1173 (null (cddar args)))
1174 (bq-attach-conses (list (list *bq-quote*
1177 ((eq (caar args) *bq-clobberable*)
1178 (bq-attach-append *bq-nconc* (cadar args) result))
1179 (t (bq-attach-append *bq-append*
1182 ((null args) result)))
1184 (defun null-or-quoted (x)
1185 (or (null x) (and (consp x) (eq (car x) *bq-quote*))))
1187 ;;; When BQ-ATTACH-APPEND is called, the OP should be #:BQ-APPEND
1188 ;;; or #:BQ-NCONC. This produces a form (op item result) but
1189 ;;; some simplifications are done on the fly:
1191 ;;; (op '(a b c) '(d e f g)) => '(a b c d e f g)
1192 ;;; (op item 'nil) => item, provided item is not a splicable frob
1193 ;;; (op item 'nil) => (op item), if item is a splicable frob
1194 ;;; (op item (op a b c)) => (op item a b c)
1195 (defun bq-attach-append (op item result)
1196 (cond ((and (null-or-quoted item) (null-or-quoted result))
1197 (list *bq-quote* (append (cadr item) (cadr result))))
1198 ((or (null result) (equal result *bq-quote-nil*))
1199 (if (bq-splicing-frob item) (list op item) item))
1200 ((and (consp result) (eq (car result) op))
1201 (list* (car result) item (cdr result)))
1202 (t (list op item result))))
1204 ;;; The effect of BQ-ATTACH-CONSES is to produce a form as if by
1205 ;;; `(LIST* ,@items ,result) but some simplifications are done
1208 ;;; (LIST* 'a 'b 'c 'd) => '(a b c . d)
1209 ;;; (LIST* a b c 'nil) => (LIST a b c)
1210 ;;; (LIST* a b c (LIST* d e f g)) => (LIST* a b c d e f g)
1211 ;;; (LIST* a b c (LIST d e f g)) => (LIST a b c d e f g)
1212 (defun bq-attach-conses (items result)
1213 (cond ((and (every #'null-or-quoted items)
1214 (null-or-quoted result))
1216 (append (mapcar #'cadr items) (cadr result))))
1217 ((or (null result) (equal result *bq-quote-nil*))
1218 (cons *bq-list* items))
1219 ((and (consp result)
1220 (or (eq (car result) *bq-list*)
1221 (eq (car result) *bq-list**)))
1222 (cons (car result) (append items (cdr result))))
1223 (t (cons *bq-list** (append items (list result))))))
1225 ;;; Removes funny tokens and changes (#:BQ-LIST* a b) into
1226 ;;; (CONS a b) instead of (LIST* a b), purely for readability.
1227 (defun bq-remove-tokens (x)
1228 (cond ((eq x *bq-list*) 'list)
1229 ((eq x *bq-append*) 'append)
1230 ((eq x *bq-nconc*) 'nconc)
1231 ((eq x *bq-list**) 'list*)
1232 ((eq x *bq-quote*) 'quote)
1234 ((eq (car x) *bq-clobberable*)
1235 (bq-remove-tokens (cadr x)))
1236 ((and (eq (car x) *bq-list**)
1239 (cons 'cons (maptree #'bq-remove-tokens (cdr x))))
1240 (t (maptree #'bq-remove-tokens x))))
1242 (define-transformation backquote (form)
1243 (bq-completely-process form))
1248 (defvar *builtins* nil)
1250 (defmacro define-raw-builtin (name args &body body)
1251 ;; Creates a new primitive function `name' with parameters args and
1252 ;; @body. The body can access to the local environment through the
1253 ;; variable *ENVIRONMENT*.
1254 `(push (list ',name (lambda ,args (block ,name ,@body)))
1257 (defmacro define-builtin (name args &body body)
1258 `(define-raw-builtin ,name ,args
1259 (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1262 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1263 (defmacro type-check (decls &body body)
1265 ,@(mapcar (lambda (decl)
1266 `(code "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1268 ,@(mapcar (lambda (decl)
1269 `(code "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1270 (indent "throw 'The value ' + "
1272 " + ' is not a type "
1277 (code "return " (progn ,@body) ";" *newline*)))
1279 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
1280 ;;; a variable which holds a list of forms. It will compile them and
1281 ;;; store the result in some Javascript variables. BODY is evaluated
1282 ;;; with ARGS bound to the list of these variables to generate the
1283 ;;; code which performs the transformation on these variables.
1285 (defun variable-arity-call (args function)
1286 (unless (consp args)
1287 (error "ARGS must be a non-empty list"))
1293 ((floatp x) (push (float-to-string x) fargs))
1294 ((numberp x) (push (integer-to-string x) fargs))
1295 (t (let ((v (code "x" (incf counter))))
1298 (code "var " v " = " (ls-compile x) ";" *newline*
1299 "if (typeof " v " !== 'number') throw 'Not a number!';"
1301 (js!selfcall prelude (funcall function (reverse fargs)))))
1304 (defmacro variable-arity (args &body body)
1305 (unless (symbolp args)
1306 (error "Bad usage of VARIABLE-ARITY, you must pass a symbol"))
1307 `(variable-arity-call ,args
1309 (code "return " ,@body ";" *newline*))))
1311 (defun num-op-num (x op y)
1312 (type-check (("x" "number" x) ("y" "number" y))
1315 (define-raw-builtin + (&rest numbers)
1318 (variable-arity numbers
1319 (join numbers "+"))))
1321 (define-raw-builtin - (x &rest others)
1322 (let ((args (cons x others)))
1323 (variable-arity args
1325 (concat "-" (car args))
1328 (define-raw-builtin * (&rest numbers)
1331 (variable-arity numbers
1332 (join numbers "*"))))
1334 (define-raw-builtin / (x &rest others)
1335 (let ((args (cons x others)))
1336 (variable-arity args
1338 (concat "1 /" (car args))
1341 (define-builtin mod (x y) (num-op-num x "%" y))
1344 (defun comparison-conjuntion (vars op)
1349 (concat (car vars) op (cadr vars)))
1351 (concat (car vars) op (cadr vars)
1353 (comparison-conjuntion (cdr vars) op)))))
1355 (defmacro define-builtin-comparison (op sym)
1356 `(define-raw-builtin ,op (x &rest args)
1357 (let ((args (cons x args)))
1358 (variable-arity args
1359 (js!bool (comparison-conjuntion args ,sym))))))
1361 (define-builtin-comparison > ">")
1362 (define-builtin-comparison < "<")
1363 (define-builtin-comparison >= ">=")
1364 (define-builtin-comparison <= "<=")
1365 (define-builtin-comparison = "==")
1367 (define-builtin numberp (x)
1368 (js!bool (code "(typeof (" x ") == \"number\")")))
1370 (define-builtin floor (x)
1371 (type-check (("x" "number" x))
1374 (define-builtin expt (x y)
1375 (type-check (("x" "number" x)
1379 (define-builtin float-to-string (x)
1380 (type-check (("x" "number" x))
1383 (define-builtin cons (x y)
1384 (code "({car: " x ", cdr: " y "})"))
1386 (define-builtin consp (x)
1389 "var tmp = " x ";" *newline*
1390 "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1392 (define-builtin car (x)
1394 "var tmp = " x ";" *newline*
1395 "return tmp === " (ls-compile nil)
1396 "? " (ls-compile nil)
1397 ": tmp.car;" *newline*))
1399 (define-builtin cdr (x)
1401 "var tmp = " x ";" *newline*
1402 "return tmp === " (ls-compile nil) "? "
1404 ": tmp.cdr;" *newline*))
1406 (define-builtin rplaca (x new)
1407 (type-check (("x" "object" x))
1408 (code "(x.car = " new ", x)")))
1410 (define-builtin rplacd (x new)
1411 (type-check (("x" "object" x))
1412 (code "(x.cdr = " new ", x)")))
1414 (define-builtin symbolp (x)
1417 "var tmp = " x ";" *newline*
1418 "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1420 (define-builtin make-symbol (name)
1421 (type-check (("name" "string" name))
1424 (define-builtin symbol-name (x)
1425 (code "(" x ").name"))
1427 (define-builtin set (symbol value)
1428 (code "(" symbol ").value = " value))
1430 (define-builtin fset (symbol value)
1431 (code "(" symbol ").fvalue = " value))
1433 (define-builtin boundp (x)
1434 (js!bool (code "(" x ".value !== undefined)")))
1436 (define-builtin symbol-value (x)
1438 "var symbol = " x ";" *newline*
1439 "var value = symbol.value;" *newline*
1440 "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1441 "return value;" *newline*))
1443 (define-builtin symbol-function (x)
1445 "var symbol = " x ";" *newline*
1446 "var func = symbol.fvalue;" *newline*
1447 "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1448 "return func;" *newline*))
1450 (define-builtin symbol-plist (x)
1451 (code "((" x ").plist || " (ls-compile nil) ")"))
1453 (define-builtin lambda-code (x)
1454 (code "(" x ").toString()"))
1456 (define-builtin eq (x y) (js!bool (code "(" x " === " y ")")))
1458 (define-builtin char-to-string (x)
1459 (type-check (("x" "number" x))
1460 "String.fromCharCode(x)"))
1462 (define-builtin stringp (x)
1463 (js!bool (code "(typeof(" x ") == \"string\")")))
1465 (define-builtin string-upcase (x)
1466 (type-check (("x" "string" x))
1469 (define-builtin string-length (x)
1470 (type-check (("x" "string" x))
1473 (define-raw-builtin slice (string a &optional b)
1475 "var str = " (ls-compile string) ";" *newline*
1476 "var a = " (ls-compile a) ";" *newline*
1478 (when b (code "b = " (ls-compile b) ";" *newline*))
1479 "return str.slice(a,b);" *newline*))
1481 (define-builtin char (string index)
1482 (type-check (("string" "string" string)
1483 ("index" "number" index))
1484 "string.charCodeAt(index)"))
1486 (define-builtin concat-two (string1 string2)
1487 (type-check (("string1" "string" string1)
1488 ("string2" "string" string2))
1489 "string1.concat(string2)"))
1491 (define-raw-builtin funcall (func &rest args)
1493 "var f = " (ls-compile func) ";" *newline*
1494 "return (typeof f === 'function'? f: f.fvalue)("
1495 (join (cons (if *multiple-value-p* "values" "pv")
1496 (mapcar #'ls-compile args))
1500 (define-raw-builtin apply (func &rest args)
1502 (code "(" (ls-compile func) ")()")
1503 (let ((args (butlast args))
1504 (last (car (last args))))
1506 "var f = " (ls-compile func) ";" *newline*
1507 "var args = [" (join (cons (if *multiple-value-p* "values" "pv")
1508 (mapcar #'ls-compile args))
1511 "var tail = (" (ls-compile last) ");" *newline*
1512 "while (tail != " (ls-compile nil) "){" *newline*
1513 " args.push(tail.car);" *newline*
1514 " tail = tail.cdr;" *newline*
1516 "return (typeof f === 'function'? f : f.fvalue).apply(this, args);" *newline*))))
1518 (define-builtin js-eval (string)
1519 (type-check (("string" "string" string))
1520 (if *multiple-value-p*
1522 "var v = globalEval(string);" *newline*
1523 "if (typeof v !== 'object' || !('multiple-value' in v)){" *newline*
1524 (indent "v = [v];" *newline*
1525 "v['multiple-value'] = true;" *newline*)
1527 "return values.apply(this, v);" *newline*)
1528 "globalEval(string)")))
1530 (define-builtin error (string)
1531 (js!selfcall "throw " string ";" *newline*))
1533 (define-builtin new () "{}")
1535 (define-builtin objectp (x)
1536 (js!bool (code "(typeof (" x ") === 'object')")))
1538 (define-builtin oget (object key)
1540 "var tmp = " "(" object ")[" key "];" *newline*
1541 "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1543 (define-builtin oset (object key value)
1544 (code "((" object ")[" key "] = " value ")"))
1546 (define-builtin in (key object)
1547 (js!bool (code "((" key ") in (" object "))")))
1549 (define-builtin functionp (x)
1550 (js!bool (code "(typeof " x " == 'function')")))
1552 (define-builtin write-string (x)
1553 (type-check (("x" "string" x))
1556 (define-builtin make-array (n)
1558 "var r = [];" *newline*
1559 "for (var i = 0; i < " n "; i++)" *newline*
1560 (indent "r.push(" (ls-compile nil) ");" *newline*)
1561 "return r;" *newline*))
1563 (define-builtin arrayp (x)
1566 "var x = " x ";" *newline*
1567 "return typeof x === 'object' && 'length' in x;")))
1569 (define-builtin aref (array n)
1571 "var x = " "(" array ")[" n "];" *newline*
1572 "if (x === undefined) throw 'Out of range';" *newline*
1573 "return x;" *newline*))
1575 (define-builtin aset (array n value)
1577 "var x = " array ";" *newline*
1578 "var i = " n ";" *newline*
1579 "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
1580 "return x[i] = " value ";" *newline*))
1582 (define-builtin get-internal-real-time ()
1583 "(new Date()).getTime()")
1585 (define-builtin values-array (array)
1586 (if *multiple-value-p*
1587 (code "values.apply(this, " array ")")
1588 (code "pv.apply(this, " array ")")))
1590 (define-raw-builtin values (&rest args)
1591 (if *multiple-value-p*
1592 (code "values(" (join (mapcar #'ls-compile args) ", ") ")")
1593 (code "pv(" (join (mapcar #'ls-compile args) ", ") ")")))
1595 ;; Receives the JS function as first argument as a literal string. The
1596 ;; second argument is compiled and should evaluate to a vector of
1597 ;; values to apply to the the function. The result returned.
1598 (define-builtin %js-call (fun args)
1599 (code fun ".apply(this, " args ")"))
1603 (let ((b (lookup-in-lexenv x *environment* 'function)))
1604 (if (and b (eq (binding-type b) 'macro))
1609 (defvar *macroexpander-cache*
1610 (make-hash-table :test #'eq))
1612 (defun ls-macroexpand-1 (form)
1615 (let ((b (lookup-in-lexenv form *environment* 'variable)))
1616 (if (and b (eq (binding-type b) 'macro))
1617 (values (binding-value b) t)
1618 (values form nil))))
1620 (let ((macro-binding (macro (car form))))
1622 (let ((expander (binding-value macro-binding)))
1625 ((gethash macro-binding *macroexpander-cache*)
1626 (setq expander (gethash macro-binding *macroexpander-cache*)))
1628 (let ((compiled (eval expander)))
1629 ;; The list representation are useful while
1630 ;; bootstrapping, as we can dump the definition of the
1631 ;; macros easily, but they are slow because we have to
1632 ;; evaluate them and compile them now and again. So, let
1633 ;; us replace the list representation version of the
1634 ;; function with the compiled one.
1636 #+jscl (setf (binding-value macro-binding) compiled)
1637 #+common-lisp (setf (gethash macro-binding *macroexpander-cache*) compiled)
1638 (setq expander compiled))))
1639 (values (apply expander (cdr form)) t))
1640 (values form nil))))
1642 (values form nil))))
1644 (defun compile-funcall (function args)
1645 (let* ((values-funcs (if *multiple-value-p* "values" "pv"))
1646 (arglist (concat "(" (join (cons values-funcs (mapcar #'ls-compile args)) ", ") ")")))
1647 (unless (or (symbolp function)
1648 (and (consp function)
1649 (eq (car function) 'lambda)))
1650 (error "Bad function"))
1652 ((translate-function function)
1653 (concat (translate-function function) arglist))
1654 ((and (symbolp function)
1655 #+jscl (eq (symbol-package function) (find-package "COMMON-LISP"))
1657 (code (ls-compile `',function) ".fvalue" arglist))
1659 (code (ls-compile `#',function) arglist)))))
1661 (defun ls-compile-block (sexps &optional return-last-p)
1663 (code (ls-compile-block (butlast sexps))
1664 "return " (ls-compile (car (last sexps)) *multiple-value-p*) ";")
1666 (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
1667 (concat ";" *newline*))))
1669 (defun ls-compile (sexp &optional multiple-value-p)
1670 (multiple-value-bind (sexp expandedp) (ls-macroexpand-1 sexp)
1672 (return-from ls-compile (ls-compile sexp multiple-value-p)))
1673 ;; The expression has been macroexpanded. Now compile it!
1674 (let ((*multiple-value-p* multiple-value-p))
1677 (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1679 ((and b (not (member 'special (binding-declarations b))))
1681 ((or (keywordp sexp)
1682 (and b (member 'constant (binding-declarations b))))
1683 (code (ls-compile `',sexp) ".value"))
1685 (ls-compile `(symbol-value ',sexp))))))
1686 ((integerp sexp) (integer-to-string sexp))
1687 ((floatp sexp) (float-to-string sexp))
1688 ((stringp sexp) (code "\"" (escape-string sexp) "\""))
1689 ((arrayp sexp) (literal sexp))
1691 (let ((name (car sexp))
1695 ((assoc name *compilations*)
1696 (let ((comp (second (assoc name *compilations*))))
1698 ;; Built-in functions
1699 ((and (assoc name *builtins*)
1700 (not (claimp name 'function 'notinline)))
1701 (let ((comp (second (assoc name *builtins*))))
1704 (compile-funcall name args)))))
1706 (error (concat "How should I compile " (prin1-to-string sexp) "?")))))))
1709 (defvar *compile-print-toplevels* nil)
1711 (defun truncate-string (string &optional (width 60))
1712 (let ((n (or (position #\newline string)
1713 (min width (length string)))))
1714 (subseq string 0 n)))
1716 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
1717 (let ((*toplevel-compilations* nil))
1719 ((and (consp sexp) (eq (car sexp) 'progn))
1720 (let ((subs (mapcar (lambda (s)
1721 (ls-compile-toplevel s t))
1723 (join (remove-if #'null-or-empty-p subs))))
1725 (when *compile-print-toplevels*
1726 (let ((form-string (prin1-to-string sexp)))
1727 (write-string "Compiling ")
1728 (write-string (truncate-string form-string))
1729 (write-line "...")))
1731 (let ((code (ls-compile sexp multiple-value-p)))
1732 (code (join-trailing (get-toplevel-compilations)
1733 (code ";" *newline*))
1735 (code code ";" *newline*))))))))