Migrate EQ, CHAR-UPCASE and CHAR-DOWNCASE
[jscl.git] / src / compiler.lisp
1 ;;; compiler.lisp ---
2
3 ;; copyright (C) 2012, 2013 David Vazquez
4 ;; Copyright (C) 2012 Raimon Grau
5
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.
10 ;;
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.
15 ;;
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/>.
18
19 ;;;; Compiler
20
21 (/debug "loading compiler.lisp!")
22
23 ;;; Translate the Lisp code to Javascript. It will compile the special
24 ;;; forms. Some primitive functions are compiled as special forms
25 ;;; too. The respective real functions are defined in the target (see
26 ;;; the beginning of this file) as well as some primitive functions.
27
28 (defun interleave (list element &optional after-last-p)
29   (unless (null list)
30     (with-collect
31       (collect (car list))
32       (dolist (x (cdr list))
33         (collect element)
34         (collect x))
35       (when after-last-p
36         (collect element)))))
37
38 (defun code (&rest args)
39   (mapconcat (lambda (arg)
40                (cond
41                  ((null arg) "")
42                  ((integerp arg) (integer-to-string arg))
43                  ((floatp arg) (float-to-string arg))
44                  ((stringp arg) arg)
45                  (t
46                   (with-output-to-string (*standard-output*)
47                     (js-expr arg)))))
48              args))
49
50 ;;; Wrap X with a Javascript code to convert the result from
51 ;;; Javascript generalized booleans to T or NIL.
52 (defun js!bool (x)
53   `(if ,x ,(ls-compile t) ,(ls-compile nil)))
54
55 ;;; Concatenate the arguments and wrap them with a self-calling
56 ;;; Javascript anonymous function. It is used to make some Javascript
57 ;;; statements valid expressions and provide a private scope as well.
58 ;;; It could be defined as function, but we could do some
59 ;;; preprocessing in the future.
60 (defmacro js!selfcall (&body body)
61   ``(call (function nil (code ,,@body))))
62
63 (defmacro js!selfcall* (&body body)
64   ``(call (function nil ,,@body)))
65
66
67 ;;; Like CODE, but prefix each line with four spaces. Two versions
68 ;;; of this function are available, because the Ecmalisp version is
69 ;;; very slow and bootstraping was annoying.
70
71 ;;; A Form can return a multiple values object calling VALUES, like
72 ;;; values(arg1, arg2, ...). It will work in any context, as well as
73 ;;; returning an individual object. However, if the special variable
74 ;;; `*multiple-value-p*' is NIL, is granted that only the primary
75 ;;; value will be used, so we can optimize to avoid the VALUES
76 ;;; function call.
77 (defvar *multiple-value-p* nil)
78
79 ;;; Environment
80
81 (def!struct binding
82   name
83   type
84   value
85   declarations)
86
87 (def!struct lexenv
88   variable
89   function
90   block
91   gotag)
92
93 (defun lookup-in-lexenv (name lexenv namespace)
94   (find name (ecase namespace
95                 (variable (lexenv-variable lexenv))
96                 (function (lexenv-function lexenv))
97                 (block    (lexenv-block    lexenv))
98                 (gotag    (lexenv-gotag    lexenv)))
99         :key #'binding-name))
100
101 (defun push-to-lexenv (binding lexenv namespace)
102   (ecase namespace
103     (variable (push binding (lexenv-variable lexenv)))
104     (function (push binding (lexenv-function lexenv)))
105     (block    (push binding (lexenv-block    lexenv)))
106     (gotag    (push binding (lexenv-gotag    lexenv)))))
107
108 (defun extend-lexenv (bindings lexenv namespace)
109   (let ((env (copy-lexenv lexenv)))
110     (dolist (binding (reverse bindings) env)
111       (push-to-lexenv binding env namespace))))
112
113
114 (defvar *environment* (make-lexenv))
115
116 (defvar *variable-counter* 0)
117
118 (defun gvarname (symbol)
119   (declare (ignore symbol))
120   (code "v" (incf *variable-counter*)))
121
122 (defun translate-variable (symbol)
123   (awhen (lookup-in-lexenv symbol *environment* 'variable)
124     (binding-value it)))
125
126 (defun extend-local-env (args)
127   (let ((new (copy-lexenv *environment*)))
128     (dolist (symbol args new)
129       (let ((b (make-binding :name symbol :type 'variable :value (gvarname symbol))))
130         (push-to-lexenv b new 'variable)))))
131
132 ;;; Toplevel compilations
133 (defvar *toplevel-compilations* nil)
134
135 (defun toplevel-compilation (string)
136   (push string *toplevel-compilations*))
137
138 (defun get-toplevel-compilations ()
139   (reverse *toplevel-compilations*))
140
141 (defun %compile-defmacro (name lambda)
142   (toplevel-compilation (ls-compile `',name))
143   (let ((binding (make-binding :name name :type 'macro :value lambda)))
144     (push-to-lexenv binding  *environment* 'function))
145   name)
146
147 (defun global-binding (name type namespace)
148   (or (lookup-in-lexenv name *environment* namespace)
149       (let ((b (make-binding :name name :type type :value nil)))
150         (push-to-lexenv b *environment* namespace)
151         b)))
152
153 (defun claimp (symbol namespace claim)
154   (let ((b (lookup-in-lexenv symbol *environment* namespace)))
155     (and b (member claim (binding-declarations b)))))
156
157 (defun !proclaim (decl)
158   (case (car decl)
159     (special
160      (dolist (name (cdr decl))
161        (let ((b (global-binding name 'variable 'variable)))
162          (push 'special (binding-declarations b)))))
163     (notinline
164      (dolist (name (cdr decl))
165        (let ((b (global-binding name 'function 'function)))
166          (push 'notinline (binding-declarations b)))))
167     (constant
168      (dolist (name (cdr decl))
169        (let ((b (global-binding name 'variable 'variable)))
170          (push 'constant (binding-declarations b)))))))
171
172 #+jscl
173 (fset 'proclaim #'!proclaim)
174
175 (defun %define-symbol-macro (name expansion)
176   (let ((b (make-binding :name name :type 'macro :value expansion)))
177     (push-to-lexenv b *environment* 'variable)
178     name))
179
180 #+jscl
181 (defmacro define-symbol-macro (name expansion)
182   `(%define-symbol-macro ',name ',expansion))
183
184
185 ;;; Special forms
186
187 (defvar *compilations* nil)
188
189 (defmacro define-compilation (name args &body body)
190   ;; Creates a new primitive `name' with parameters args and
191   ;; @body. The body can access to the local environment through the
192   ;; variable *ENVIRONMENT*.
193   `(push (list ',name (lambda ,args (block ,name ,@body)))
194          *compilations*))
195
196 (define-compilation if (condition true &optional false)
197   `(if (!== ,(ls-compile condition) ,(ls-compile nil))
198        ,(ls-compile true *multiple-value-p*)
199        ,(ls-compile false *multiple-value-p*)))
200
201 (defvar *ll-keywords* '(&optional &rest &key))
202
203 (defun list-until-keyword (list)
204   (if (or (null list) (member (car list) *ll-keywords*))
205       nil
206       (cons (car list) (list-until-keyword (cdr list)))))
207
208 (defun ll-section (keyword ll)
209   (list-until-keyword (cdr (member keyword ll))))
210
211 (defun ll-required-arguments (ll)
212   (list-until-keyword ll))
213
214 (defun ll-optional-arguments-canonical (ll)
215   (mapcar #'ensure-list (ll-section '&optional ll)))
216
217 (defun ll-optional-arguments (ll)
218   (mapcar #'car (ll-optional-arguments-canonical ll)))
219
220 (defun ll-rest-argument (ll)
221   (let ((rest (ll-section '&rest ll)))
222     (when (cdr rest)
223       (error "Bad lambda-list `~S'." ll))
224     (car rest)))
225
226 (defun ll-keyword-arguments-canonical (ll)
227   (flet ((canonicalize (keyarg)
228            ;; Build a canonical keyword argument descriptor, filling
229            ;; the optional fields. The result is a list of the form
230            ;; ((keyword-name var) init-form).
231            (let ((arg (ensure-list keyarg)))
232              (cons (if (listp (car arg))
233                        (car arg)
234                        (list (intern (symbol-name (car arg)) "KEYWORD") (car arg)))
235                    (cdr arg)))))
236     (mapcar #'canonicalize (ll-section '&key ll))))
237
238 (defun ll-keyword-arguments (ll)
239   (mapcar (lambda (keyarg) (second (first keyarg)))
240           (ll-keyword-arguments-canonical ll)))
241
242 (defun ll-svars (lambda-list)
243   (let ((args
244          (append
245           (ll-keyword-arguments-canonical lambda-list)
246           (ll-optional-arguments-canonical lambda-list))))
247     (remove nil (mapcar #'third args))))
248
249 (defun lambda-name/docstring-wrapper (name docstring code)
250   (if (or name docstring)
251       (js!selfcall*
252         `(var (func ,code))
253         (when name      `(= (get func |fname|) ,name))
254         (when docstring `(= (get func |docstring|) ,docstring))
255         `(return func))
256       `(code ,code)))
257
258 (defun lambda-check-argument-count
259     (n-required-arguments n-optional-arguments rest-p)
260   ;; Note: Remember that we assume that the number of arguments of a
261   ;; call is at least 1 (the values argument).
262   (let ((min n-required-arguments)
263         (max (if rest-p 'n/a (+ n-required-arguments n-optional-arguments))))
264     (block nil
265       ;; Special case: a positive exact number of arguments.
266       (when (and (< 0 min) (eql min max))
267         (return `(code "checkArgs(nargs, " ,min ");")))
268       ;; General case:
269       `(code
270         ,(when (< 0 min)
271            `(code "checkArgsAtLeast(nargs, " ,min ");"))
272         ,(when (numberp max)
273            `(code "checkArgsAtMost(nargs, " ,max ");"))))))
274
275 (defun compile-lambda-optional (ll)
276   (let* ((optional-arguments (ll-optional-arguments-canonical ll))
277          (n-required-arguments (length (ll-required-arguments ll)))
278          (n-optional-arguments (length optional-arguments)))
279     (when optional-arguments
280       `(code "switch(nargs){"
281              ,(let ((cases nil)
282                     (idx 0))
283                    (progn
284                      (while (< idx n-optional-arguments)
285                        (let ((arg (nth idx optional-arguments)))
286                          (push `(code "case " ,(+ idx n-required-arguments) ":"
287                                       (code ,(translate-variable (car arg))
288                                             "="
289                                             ,(ls-compile (cadr arg)) ";")
290                                       ,(when (third arg)
291                                          `(code ,(translate-variable (third arg))
292                                                 "="
293                                                 ,(ls-compile nil)
294                                                 ";")))
295                                cases)
296                          (incf idx)))
297                      (push `(code "default: break;") cases)
298                      `(code ,@(reverse cases))))
299              "}"))))
300
301 (defun compile-lambda-rest (ll)
302   (let ((n-required-arguments (length (ll-required-arguments ll)))
303         (n-optional-arguments (length (ll-optional-arguments ll)))
304         (rest-argument (ll-rest-argument ll)))
305     (when rest-argument
306       (let ((js!rest (translate-variable rest-argument)))
307         `(code "var " ,js!rest "= " ,(ls-compile nil) ";"
308                "for (var i = nargs-1; i>=" ,(+ n-required-arguments n-optional-arguments)
309                "; i--)"
310                (code ,js!rest " = {car: arguments[i+2], cdr: " ,js!rest "};"))))))
311
312 (defun compile-lambda-parse-keywords (ll)
313   (let ((n-required-arguments
314          (length (ll-required-arguments ll)))
315         (n-optional-arguments
316          (length (ll-optional-arguments ll)))
317         (keyword-arguments
318          (ll-keyword-arguments-canonical ll)))
319     `(code
320       ;; Declare variables
321       ,@(mapcar (lambda (arg)
322                   (let ((var (second (car arg))))
323                     `(code "var " ,(translate-variable var) "; "
324                            ,(when (third arg)
325                               `(code "var " ,(translate-variable (third arg))
326                                      " = " ,(ls-compile nil)
327                                      ";" )))))
328                 keyword-arguments)
329       ;; Parse keywords
330       ,(flet ((parse-keyword (keyarg)
331                ;; ((keyword-name var) init-form)
332                `(code "for (i=" ,(+ n-required-arguments n-optional-arguments)
333                       "; i<nargs; i+=2){"
334                       "if (arguments[i+2] === " ,(ls-compile (caar keyarg)) "){"
335                       ,(translate-variable (cadr (car keyarg)))
336                       " = arguments[i+3];"
337                       ,(let ((svar (third keyarg)))
338                             (when svar
339                               `(code ,(translate-variable svar) " = " ,(ls-compile t) ";" )))
340                       "break;"
341                       "}"
342                       "}"
343                       ;; Default value
344                       "if (i == nargs){"
345                       ,(translate-variable (cadr (car keyarg)))
346                       " = "
347                       ,(ls-compile (cadr keyarg))
348                       ";"
349                       "}")))
350         (when keyword-arguments
351           `(code "var i;"
352                  ,@(mapcar #'parse-keyword keyword-arguments))))
353       ;; Check for unknown keywords
354       ,(when keyword-arguments
355         `(code "var start = " ,(+ n-required-arguments n-optional-arguments) ";"
356                "if ((nargs - start) % 2 == 1){"
357                "throw 'Odd number of keyword arguments';" 
358                "}"
359                "for (i = start; i<nargs; i+=2){"
360                "if ("
361                ,@(interleave (mapcar (lambda (x)
362                                        `(code "arguments[i+2] !== " ,(ls-compile (caar x))))
363                                      keyword-arguments)
364                             " && ")
365                ")"
366                "throw 'Unknown keyword argument ' + xstring(arguments[i+2].name);" 
367                "}" )))))
368
369 (defun parse-lambda-list (ll)
370   (values (ll-required-arguments ll)
371           (ll-optional-arguments ll)
372           (ll-keyword-arguments  ll)
373           (ll-rest-argument      ll)))
374
375 ;;; Process BODY for declarations and/or docstrings. Return as
376 ;;; multiple values the BODY without docstrings or declarations, the
377 ;;; list of declaration forms and the docstring.
378 (defun parse-body (body &key declarations docstring)
379   (let ((value-declarations)
380         (value-docstring))
381     ;; Parse declarations
382     (when declarations
383       (do* ((rest body (cdr rest))
384             (form (car rest) (car rest)))
385            ((or (atom form) (not (eq (car form) 'declare)))
386             (setf body rest))
387         (push form value-declarations)))
388     ;; Parse docstring
389     (when (and docstring
390                (stringp (car body))
391                (not (null (cdr body))))
392       (setq value-docstring (car body))
393       (setq body (cdr body)))
394     (values body value-declarations value-docstring)))
395
396 ;;; Compile a lambda function with lambda list LL and body BODY. If
397 ;;; NAME is given, it should be a constant string and it will become
398 ;;; the name of the function. If BLOCK is non-NIL, a named block is
399 ;;; created around the body. NOTE: No block (even anonymous) is
400 ;;; created if BLOCk is NIL.
401 (defun compile-lambda (ll body &key name block)
402   (multiple-value-bind (required-arguments
403                         optional-arguments
404                         keyword-arguments
405                         rest-argument)
406       (parse-lambda-list ll)
407     (multiple-value-bind (body decls documentation)
408         (parse-body body :declarations t :docstring t)
409       (declare (ignore decls))
410       (let ((n-required-arguments (length required-arguments))
411             (n-optional-arguments (length optional-arguments))
412             (*environment* (extend-local-env
413                             (append (ensure-list rest-argument)
414                                     required-arguments
415                                     optional-arguments
416                                     keyword-arguments
417                                     (ll-svars ll)))))
418         (lambda-name/docstring-wrapper name documentation
419          `(code
420            "(function ("
421            ,(join (list* "values"
422                          "nargs"
423                          (mapcar #'translate-variable
424                                  (append required-arguments optional-arguments)))
425                   ",")
426            "){"
427            ;; Check number of arguments
428            ,(lambda-check-argument-count n-required-arguments
429                                          n-optional-arguments
430                                          (or rest-argument keyword-arguments))
431            ,(compile-lambda-optional ll)
432            ,(compile-lambda-rest ll)
433            ,(compile-lambda-parse-keywords ll)
434            ,(let ((*multiple-value-p* t))
435                  (if block
436                      (ls-compile-block `((block ,block ,@body)) t)
437                      (ls-compile-block body t)))
438            "})"))))))
439
440
441 (defun setq-pair (var val)
442   (let ((b (lookup-in-lexenv var *environment* 'variable)))
443     (cond
444       ((and b
445             (eq (binding-type b) 'variable)
446             (not (member 'special (binding-declarations b)))
447             (not (member 'constant (binding-declarations b))))
448        ;; TODO: Unnecesary make-symbol when codegen migration is
449        ;; finished.
450        `(= ,(make-symbol (binding-value b)) ,(ls-compile val)))
451       ((and b (eq (binding-type b) 'macro))
452        (ls-compile `(setf ,var ,val)))
453       (t
454        (ls-compile `(set ',var ,val))))))
455
456
457 (define-compilation setq (&rest pairs)
458   (let ((result nil))
459     (when (null pairs)
460       (return-from setq (ls-compile nil)))
461     (while t
462       (cond
463         ((null pairs)
464          (return))
465         ((null (cdr pairs))
466          (error "Odd pairs in SETQ"))
467         (t
468          (push `,(setq-pair (car pairs) (cadr pairs)) result)
469          (setq pairs (cddr pairs)))))
470     `(progn ,@(reverse result))))
471
472
473 ;;; Compilation of literals an object dumping
474
475 ;;; BOOTSTRAP MAGIC: We record the macro definitions as lists during
476 ;;; the bootstrap. Once everything is compiled, we want to dump the
477 ;;; whole global environment to the output file to reproduce it in the
478 ;;; run-time. However, the environment must contain expander functions
479 ;;; rather than lists. We do not know how to dump function objects
480 ;;; itself, so we mark the list definitions with this object and the
481 ;;; compiler will be called when this object has to be dumped.
482 ;;; Backquote/unquote does a similar magic, but this use is exclusive.
483 ;;;
484 ;;; Indeed, perhaps to compile the object other macros need to be
485 ;;; evaluated. For this reason we define a valid macro-function for
486 ;;; this symbol.
487 (defvar *magic-unquote-marker* (gensym "MAGIC-UNQUOTE"))
488 #-jscl
489 (setf (macro-function *magic-unquote-marker*)
490       (lambda (form &optional environment)
491         (declare (ignore environment))
492         (second form)))
493
494 (defvar *literal-table* nil)
495 (defvar *literal-counter* 0)
496
497 (defun genlit ()
498   (code "l" (incf *literal-counter*)))
499
500 (defun dump-symbol (symbol)
501   #-jscl
502   (let ((package (symbol-package symbol)))
503     (if (eq package (find-package "KEYWORD"))
504         `(new (call |Symbol| ,(dump-string (symbol-name symbol)) ,(dump-string (package-name package))))
505         `(new (call |Symbol| ,(dump-string (symbol-name symbol))))))
506   #+jscl
507   (let ((package (symbol-package symbol)))
508     (if (null package)
509         `(new (call |Symbol| ,(dump-string (symbol-name symbol))))
510         (ls-compile `(intern ,(symbol-name symbol) ,(package-name package))))))
511
512 (defun dump-cons (cons)
513   (let ((head (butlast cons))
514         (tail (last cons)))
515     `(call |QIList|
516            ,@(mapcar (lambda (x) `(code ,(literal x t))) head)
517            (code ,(literal (car tail) t))
518            (code ,(literal (cdr tail) t)))))
519
520 (defun dump-array (array)
521   (let ((elements (vector-to-list array)))
522     (list-to-vector (mapcar (lambda (x) `(code ,(literal x)))
523                             elements))))
524
525 (defun dump-string (string)
526   `(call |make_lisp_string| ,string))
527
528 (defun literal (sexp &optional recursive)
529   (cond
530     ((integerp sexp) (integer-to-string sexp))
531     ((floatp sexp) (float-to-string sexp))
532     ((characterp sexp) (js-escape-string (string sexp)))
533     (t
534      (or (cdr (assoc sexp *literal-table* :test #'eql))
535          (let ((dumped (typecase sexp
536                          (symbol (dump-symbol sexp))
537                          (string (dump-string sexp))
538                          (cons
539                           ;; BOOTSTRAP MAGIC: See the root file
540                           ;; jscl.lisp and the function
541                           ;; `dump-global-environment' for futher
542                           ;; information.
543                           (if (eq (car sexp) *magic-unquote-marker*)
544                               (ls-compile (second sexp))
545                               (dump-cons sexp)))
546                          (array (dump-array sexp)))))
547            (if (and recursive (not (symbolp sexp)))
548                dumped
549                (let ((jsvar (genlit)))
550                  (push (cons sexp jsvar) *literal-table*)
551                  (toplevel-compilation `(code "var " ,jsvar " = " ,dumped))
552                  (when (keywordp sexp)
553                    (toplevel-compilation `(code ,jsvar ".value = " ,jsvar)))
554                  jsvar)))))))
555
556
557 (define-compilation quote (sexp)
558   (literal sexp))
559
560 (define-compilation %while (pred &rest body)
561   (js!selfcall*
562     `(while (!== ,(ls-compile pred) ,(ls-compile nil))
563        0                                ; TODO: Force
564                                         ; braces. Unnecesary when code
565                                         ; is gone
566        ,(ls-compile-block body))
567    `(return ,(ls-compile nil))))
568
569 (define-compilation function (x)
570   (cond
571     ((and (listp x) (eq (car x) 'lambda))
572      (compile-lambda (cadr x) (cddr x)))
573     ((and (listp x) (eq (car x) 'named-lambda))
574      ;; TODO: destructuring-bind now! Do error checking manually is
575      ;; very annoying.
576      (let ((name (cadr x))
577            (ll (caddr x))
578            (body (cdddr x)))
579        (compile-lambda ll body
580                        :name (symbol-name name)
581                        :block name)))
582     ((symbolp x)
583      (let ((b (lookup-in-lexenv x *environment* 'function)))
584        (if b
585            (binding-value b)
586            (ls-compile `(symbol-function ',x)))))))
587
588
589 (defun make-function-binding (fname)
590   (make-binding :name fname :type 'function :value (gvarname fname)))
591
592 (defun compile-function-definition (list)
593   (compile-lambda (car list) (cdr list)))
594
595 (defun translate-function (name)
596   (let ((b (lookup-in-lexenv name *environment* 'function)))
597     (and b (binding-value b))))
598
599 (define-compilation flet (definitions &rest body)
600   (let* ((fnames (mapcar #'car definitions))
601          (cfuncs (mapcar (lambda (def)
602                            (compile-lambda (cadr def)
603                                            `((block ,(car def)
604                                                ,@(cddr def)))))
605                          definitions))
606          (*environment*
607           (extend-lexenv (mapcar #'make-function-binding fnames)
608                          *environment*
609                          'function)))
610     `(code "(function("
611            ,@(interleave (mapcar #'translate-function fnames) ",")
612            "){"
613            ,(ls-compile-block body t)
614            "})(" ,@(interleave cfuncs ",") ")")))
615
616 (define-compilation labels (definitions &rest body)
617   (let* ((fnames (mapcar #'car definitions))
618          (*environment*
619           (extend-lexenv (mapcar #'make-function-binding fnames)
620                          *environment*
621                          'function)))
622     (js!selfcall
623       `(code ,@(mapcar (lambda (func)
624                          `(code "var " ,(translate-function (car func))
625                                 " = " ,(compile-lambda (cadr func)
626                                                        `((block ,(car func) ,@(cddr func))))
627                                 ";" ))
628                        definitions))
629       (ls-compile-block body t))))
630
631
632 (defvar *compiling-file* nil)
633 (define-compilation eval-when-compile (&rest body)
634   (if *compiling-file*
635       (progn
636         (eval (cons 'progn body))
637         (ls-compile 0))
638       (ls-compile `(progn ,@body))))
639
640 (defmacro define-transformation (name args form)
641   `(define-compilation ,name ,args
642      (ls-compile ,form)))
643
644 (define-compilation progn (&rest body)
645   (if (null (cdr body))
646       (ls-compile (car body) *multiple-value-p*)
647       `(progn
648          ,@(append (mapcar #'ls-compile (butlast body))
649                    (list (ls-compile (car (last body)) t))))))
650
651 (define-compilation macrolet (definitions &rest body)
652   (let ((*environment* (copy-lexenv *environment*)))
653     (dolist (def definitions)
654       (destructuring-bind (name lambda-list &body body) def
655         (let ((binding (make-binding :name name :type 'macro :value
656                                      (let ((g!form (gensym)))
657                                        `(lambda (,g!form)
658                                           (destructuring-bind ,lambda-list ,g!form
659                                             ,@body))))))
660           (push-to-lexenv binding  *environment* 'function))))
661     (ls-compile `(progn ,@body) *multiple-value-p*)))
662
663
664 (defun special-variable-p (x)
665   (and (claimp x 'variable 'special) t))
666
667 ;;; Wrap CODE to restore the symbol values of the dynamic
668 ;;; bindings. BINDINGS is a list of pairs of the form
669 ;;; (SYMBOL . PLACE),  where PLACE is a Javascript variable
670 ;;; name to initialize the symbol value and where to stored
671 ;;; the old value.
672 (defun let-binding-wrapper (bindings body)
673   (when (null bindings)
674     (return-from let-binding-wrapper body))
675   `(code
676     "try {"
677     (code "var tmp;"
678           ,@(mapcar
679              (lambda (b)
680                (let ((s (ls-compile `(quote ,(car b)))))
681                  `(code "tmp = " ,s ".value;"
682                         ,s ".value = " ,(cdr b) ";"
683                         ,(cdr b) " = tmp;" )))
684              bindings)
685           ,body
686           )
687     "}"
688     "finally {"
689     (code
690      ,@(mapcar (lambda (b)
691                  (let ((s (ls-compile `(quote ,(car b)))))
692                    `(code ,s ".value" " = " ,(cdr b) ";" )))
693                bindings))
694     "}" ))
695
696 (define-compilation let (bindings &rest body)
697   (let* ((bindings (mapcar #'ensure-list bindings))
698          (variables (mapcar #'first bindings))
699          (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
700          (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
701          (dynamic-bindings))
702     `(code "(function("
703            ,@(interleave
704               (mapcar (lambda (x)
705                         (if (special-variable-p x)
706                             (let ((v (gvarname x)))
707                               (push (cons x v) dynamic-bindings)
708                               v)
709                             (translate-variable x)))
710                       variables)
711               ",")
712            "){"
713            ,(let ((body (ls-compile-block body t t)))
714              `(code ,(let-binding-wrapper dynamic-bindings body)))
715            "})(" ,@(interleave cvalues ",") ")")))
716
717
718 ;;; Return the code to initialize BINDING, and push it extending the
719 ;;; current lexical environment if the variable is not special.
720 (defun let*-initialize-value (binding)
721   (let ((var (first binding))
722         (value (second binding)))
723     (if (special-variable-p var)
724         `(code ,(ls-compile `(setq ,var ,value)) ";" )
725         (let* ((v (gvarname var))
726                (b (make-binding :name var :type 'variable :value v)))
727           (prog1 `(code "var " ,v " = " ,(ls-compile value) ";" )
728             (push-to-lexenv b *environment* 'variable))))))
729
730 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
731 ;;; DOES NOT generate code to initialize the value of the symbols,
732 ;;; unlike let-binding-wrapper.
733 (defun let*-binding-wrapper (symbols body)
734   (when (null symbols)
735     (return-from let*-binding-wrapper body))
736   (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
737                        (remove-if-not #'special-variable-p symbols))))
738     `(code
739       "try {"
740       (code
741        ,@(mapcar (lambda (b)
742                    (let ((s (ls-compile `(quote ,(car b)))))
743                      `(code "var " ,(cdr b) " = " ,s ".value;" )))
744                  store)
745        ,body)
746       "}"
747       "finally {"
748       (code
749        ,@(mapcar (lambda (b)
750                    (let ((s (ls-compile `(quote ,(car b)))))
751                      `(code ,s ".value" " = " ,(cdr b) ";" )))
752                  store))
753       "}" )))
754
755 (define-compilation let* (bindings &rest body)
756   (let ((bindings (mapcar #'ensure-list bindings))
757         (*environment* (copy-lexenv *environment*)))
758     (js!selfcall
759       (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
760             (body `(code ,@(mapcar #'let*-initialize-value bindings)
761                          ,(ls-compile-block body t t))))
762         (let*-binding-wrapper specials body)))))
763
764
765 (define-compilation block (name &rest body)
766   ;; We use Javascript exceptions to implement non local control
767   ;; transfer. Exceptions has dynamic scoping, so we use a uniquely
768   ;; generated object to identify the block. The instance of a empty
769   ;; array is used to distinguish between nested dynamic Javascript
770   ;; exceptions. See https://github.com/davazp/jscl/issues/64 for
771   ;; futher details.
772   (let* ((idvar (gvarname name))
773          (b (make-binding :name name :type 'block :value idvar)))
774     (when *multiple-value-p*
775       (push 'multiple-value (binding-declarations b)))
776     (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
777            (cbody (ls-compile-block body t)))
778       (if (member 'used (binding-declarations b))
779           (js!selfcall
780             "try {"
781             "var " idvar " = [];"
782             `(code ,cbody)
783             "}"
784             "catch (cf){"
785             "    if (cf.type == 'block' && cf.id == " idvar ")"
786             (if *multiple-value-p*
787                 "        return values.apply(this, forcemv(cf.values));"
788                 "        return cf.values;")
789
790             "    else"
791             "        throw cf;"
792             "}" )
793           (js!selfcall cbody)))))
794
795 (define-compilation return-from (name &optional value)
796   (let* ((b (lookup-in-lexenv name *environment* 'block))
797          (multiple-value-p (member 'multiple-value (binding-declarations b))))
798     (when (null b)
799       (error "Return from unknown block `~S'." (symbol-name name)))
800     (push 'used (binding-declarations b))
801     ;; The binding value is the name of a variable, whose value is the
802     ;; unique identifier of the block as exception. We can't use the
803     ;; variable name itself, because it could not to be unique, so we
804     ;; capture it in a closure.
805     (js!selfcall
806       (when multiple-value-p `(code "var values = mv;" ))
807       "throw ({"
808       "type: 'block', "
809       "id: " (binding-value b) ", "
810       "values: " (ls-compile value multiple-value-p) ", "
811       "message: 'Return from unknown block " (symbol-name name) ".'"
812       "})")))
813
814 (define-compilation catch (id &rest body)
815   (js!selfcall*
816     `(var (|id| ,(ls-compile id)))
817     `(try
818       ,(ls-compile-block body t))
819     `(catch (|cf|)
820        (if (and (== (get |cf| |type|) "catch")
821                 (== (get |cf| |id|) |id|))
822            ,(if *multiple-value-p*
823                 `(return (call (get |values| |apply|)
824                                this
825                                (call |forcemv| (get |cf| |values|))))
826                 `(return (call (get |pv| |apply|)
827                                this
828                                (call |forcemv| (get |cf| |values|)))))
829            (throw |cf|)))))
830
831 (define-compilation throw (id value)
832   (js!selfcall*
833     `(var (|values| |mv|))
834     `(throw (object
835              |type| "catch"
836              |id| ,(ls-compile id)
837              |values| ,(ls-compile value t)
838              |message| "Throw uncatched."))))
839
840 (defun go-tag-p (x)
841   (or (integerp x) (symbolp x)))
842
843 (defun declare-tagbody-tags (tbidx body)
844   (let* ((go-tag-counter 0)
845          (bindings
846           (mapcar (lambda (label)
847                     (let ((tagidx (integer-to-string (incf go-tag-counter))))
848                       (make-binding :name label :type 'gotag :value (list tbidx tagidx))))
849                   (remove-if-not #'go-tag-p body))))
850     (extend-lexenv bindings *environment* 'gotag)))
851
852 (define-compilation tagbody (&rest body)
853   ;; Ignore the tagbody if it does not contain any go-tag. We do this
854   ;; because 1) it is easy and 2) many built-in forms expand to a
855   ;; implicit tagbody, so we save some space.
856   (unless (some #'go-tag-p body)
857     (return-from tagbody (ls-compile `(progn ,@body nil))))
858   ;; The translation assumes the first form in BODY is a label
859   (unless (go-tag-p (car body))
860     (push (gensym "START") body))
861   ;; Tagbody compilation
862   (let ((branch (gvarname 'branch))
863         (tbidx (gvarname 'tbidx)))
864     (let ((*environment* (declare-tagbody-tags tbidx body))
865           initag)
866       (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
867         (setq initag (second (binding-value b))))
868       (js!selfcall
869         ;; TAGBODY branch to take
870         "var " branch " = " initag ";"
871         "var " tbidx " = [];"
872         "tbloop:"
873         "while (true) {"
874         `(code "try {"
875                ,(let ((content nil))
876                   `(code "switch(" ,branch "){"
877                         "case " ,initag ":"
878                         ,@(dolist (form (cdr body) (reverse content))
879                           (push (if (not (go-tag-p form))
880                                     `(code ,(ls-compile form) ";" )
881                                     (let ((b (lookup-in-lexenv form *environment* 'gotag)))
882                                       `(code "case " ,(second (binding-value b)) ":" )))
883                                 content))
884                            "default:"
885                            "    break tbloop;"
886                            "}" ))
887                "}"
888                "catch (jump) {"
889                "    if (jump.type == 'tagbody' && jump.id == " ,tbidx ")"
890                "        " ,branch " = jump.label;"
891                "    else"
892                "        throw(jump);"
893                "}" )
894         "}"
895         "return " (ls-compile nil) ";" ))))
896
897 (define-compilation go (label)
898   (let ((b (lookup-in-lexenv label *environment* 'gotag))
899         (n (cond
900              ((symbolp label) (symbol-name label))
901              ((integerp label) (integer-to-string label)))))
902     (when (null b)
903       (error "Unknown tag `~S'" label))
904     (js!selfcall
905       "throw ({"
906       "type: 'tagbody', "
907       "id: " (first (binding-value b)) ", "
908       "label: " (second (binding-value b)) ", "
909       "message: 'Attempt to GO to non-existing tag " n "'"
910       "})" )))
911
912 (define-compilation unwind-protect (form &rest clean-up)
913   (js!selfcall*
914     `(var (|ret| ,(ls-compile nil)))
915     `(try
916        (= |ret| ,(ls-compile form)))
917     `(finally
918       ,(ls-compile-block clean-up))
919     `(return |ret|)))
920
921 (define-compilation multiple-value-call (func-form &rest forms)
922   (js!selfcall
923     "var func = " (ls-compile func-form) ";"
924     "var args = [" (if *multiple-value-p* "values" "pv") ", 0];"
925     "return "
926     (js!selfcall
927       "var values = mv;"
928       "var vs;"
929       `(code
930         ,@(mapcar (lambda (form)
931                     `(code "vs = " ,(ls-compile form t) ";"
932                            "if (typeof vs === 'object' && 'multiple-value' in vs)"
933                            (code " args = args.concat(vs);" )
934                            " else "
935                            (code "args.push(vs);" )))
936                   forms))
937       "args[1] = args.length-2;"
938       "return func.apply(window, args);" ) ";" ))
939
940 (define-compilation multiple-value-prog1 (first-form &rest forms)
941   (js!selfcall
942     "var args = " (ls-compile first-form *multiple-value-p*) ";"
943     (ls-compile-block forms)
944     "return args;" ))
945
946 (define-transformation backquote (form)
947   (bq-completely-process form))
948
949
950 ;;; Primitives
951
952 (defvar *builtins* nil)
953
954 (defmacro define-raw-builtin (name args &body body)
955   ;; Creates a new primitive function `name' with parameters args and
956   ;; @body. The body can access to the local environment through the
957   ;; variable *ENVIRONMENT*.
958   `(push (list ',name (lambda ,args (block ,name ,@body)))
959          *builtins*))
960
961 (defmacro define-builtin (name args &body body)
962   `(define-raw-builtin ,name ,args
963      (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
964        ,@body)))
965
966 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
967 (defmacro type-check (decls &body body)
968   `(js!selfcall
969      ,@(mapcar (lambda (decl)
970                  `(let ((name ,(first decl))
971                         (value ,(third decl)))
972                     `(code "var " ,name " = " ,value ";" )))
973                decls)
974      ,@(mapcar (lambda (decl)
975                  `(let ((name ,(first decl))
976                         (type ,(second decl)))
977                     `(code "if (typeof " ,name " != '" ,type "')"
978                            (code "throw 'The value ' + "
979                                  ,name
980                                  " + ' is not a type "
981                                  ,type
982                                  ".';"
983                                  ))))
984                decls)
985      `(code "return " ,,@body ";" )))
986
987 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
988 ;;; a variable which holds a list of forms. It will compile them and
989 ;;; store the result in some Javascript variables. BODY is evaluated
990 ;;; with ARGS bound to the list of these variables to generate the
991 ;;; code which performs the transformation on these variables.
992
993 (defun variable-arity-call (args function)
994   (unless (consp args)
995     (error "ARGS must be a non-empty list"))
996   (let ((counter 0)
997         (fargs '())
998         (prelude '()))
999     (dolist (x args)
1000       (cond
1001         ((or (floatp x) (numberp x)) (push x fargs))
1002         (t (let ((v (make-symbol (code "x" (incf counter)))))
1003              (push v fargs)
1004              (push `(code "var " ,v " = " ,(ls-compile x) ";"
1005                           "if (typeof " ,v " !== 'number') throw 'Not a number!';")
1006                    prelude)))))
1007     (js!selfcall
1008       `(code ,@(reverse prelude))
1009       (funcall function (reverse fargs)))))
1010
1011
1012 (defmacro variable-arity (args &body body)
1013   (unless (symbolp args)
1014     (error "`~S' is not a symbol." args))
1015   `(variable-arity-call ,args
1016                         (lambda (,args)
1017                           `(code "return " ,,@body ";" ))))
1018
1019 (defun num-op-num (x op y)
1020   (type-check (("x" "number" x) ("y" "number" y))
1021     `(code "x" ,op "y")))
1022
1023 (define-raw-builtin + (&rest numbers)
1024   (if (null numbers)
1025       0
1026       (variable-arity numbers
1027         `(+ ,@numbers))))
1028
1029 (define-raw-builtin - (x &rest others)
1030   (let ((args (cons x others)))
1031     (variable-arity args `(- ,@args))))
1032
1033 (define-raw-builtin * (&rest numbers)
1034   (if (null numbers)
1035       1
1036       (variable-arity numbers `(* ,@numbers))))
1037
1038 (define-raw-builtin / (x &rest others)
1039   (let ((args (cons x others)))
1040     (variable-arity args
1041       (if (null others)
1042           `(/ 1 ,(car args))
1043           (reduce (lambda (x y) `(/ ,x ,y))
1044                   args)))))
1045
1046 (define-builtin mod (x y) (num-op-num x "%" y))
1047
1048
1049 (defun comparison-conjuntion (vars op)
1050   (cond
1051     ((null (cdr vars))
1052      'true)
1053     ((null (cddr vars))
1054      `(,op ,(car vars) ,(cadr vars)))
1055     (t
1056      `(and (,op ,(car vars) ,(cadr vars))
1057            ,(comparison-conjuntion (cdr vars) op)))))
1058
1059 (defmacro define-builtin-comparison (op sym)
1060   `(define-raw-builtin ,op (x &rest args)
1061      (let ((args (cons x args)))
1062        (variable-arity args
1063          (js!bool (comparison-conjuntion args ',sym))))))
1064
1065 (define-builtin-comparison > >)
1066 (define-builtin-comparison < <)
1067 (define-builtin-comparison >= >=)
1068 (define-builtin-comparison <= <=)
1069 (define-builtin-comparison = ==)
1070 (define-builtin-comparison /= !=)
1071
1072 (define-builtin numberp (x)
1073   (js!bool `(== (typeof ,x) "number")))
1074
1075 (define-builtin floor (x)
1076   (type-check (("x" "number" x))
1077     "Math.floor(x)"))
1078
1079 (define-builtin expt (x y)
1080   (type-check (("x" "number" x)
1081                ("y" "number" y))
1082     "Math.pow(x, y)"))
1083
1084 (define-builtin float-to-string (x)
1085   (type-check (("x" "number" x))
1086     "make_lisp_string(x.toString())"))
1087
1088 (define-builtin cons (x y)
1089   `(object "car" ,x "cdr" ,y))
1090
1091 (define-builtin consp (x)
1092   (js!bool
1093    (js!selfcall
1094      "var tmp = " x ";"
1095      "return (typeof tmp == 'object' && 'car' in tmp);" )))
1096
1097 (define-builtin car (x)
1098   (js!selfcall*
1099     `(var (tmp ,x))
1100     `(return (if (=== tmp ,(ls-compile nil))
1101                  ,(ls-compile nil)
1102                  (get tmp "car")))))
1103
1104 (define-builtin cdr (x)
1105   (js!selfcall*
1106     `(var (tmp ,x))
1107     `(return (if (=== tmp ,(ls-compile nil))
1108                  ,(ls-compile nil)
1109                  (get tmp "cdr")))))
1110
1111 (define-builtin rplaca (x new)
1112   (type-check (("x" "object" x))
1113     `(code "(x.car = " ,new ", x)")))
1114
1115 (define-builtin rplacd (x new)
1116   (type-check (("x" "object" x))
1117     `(code "(x.cdr = " ,new ", x)")))
1118
1119 (define-builtin symbolp (x)
1120   (js!bool `(instanceof ,x |Symbol|)))
1121
1122 (define-builtin make-symbol (name)
1123   `(new (call |Symbol| ,name)))
1124
1125 (define-builtin symbol-name (x)
1126   `(get ,x "name"))
1127
1128 (define-builtin set (symbol value)
1129   `(= (get ,symbol "value") ,value))
1130
1131 (define-builtin fset (symbol value)
1132   `(= (get ,symbol "fvalue") ,value))
1133
1134 (define-builtin boundp (x)
1135   (js!bool `(!== (get ,x "value") undefined)))
1136
1137 (define-builtin fboundp (x)
1138   (js!bool `(!== (get ,x "fvalue") undefined)))
1139
1140 (define-builtin symbol-value (x)
1141   (js!selfcall*
1142     `(var (symbol ,x)
1143           (value (get symbol "value")))
1144     `(if (=== value undefined)
1145          (throw (+ "Variable `" (call |xstring| (get symbol "name")) "' is unbound.")))
1146     `(return value)))
1147
1148 (define-builtin symbol-function (x)
1149   (js!selfcall*
1150     `(var (symbol ,x)
1151           (func (get symbol "fvalue")))
1152     `(if (=== func undefined)
1153          (throw (+ "Function `" (call |xstring| (get symbol "name")) "' is undefined.")))
1154     `(return func)))
1155
1156 (define-builtin symbol-plist (x)
1157   `(or (get ,x "plist") ,(ls-compile nil)))
1158
1159 (define-builtin lambda-code (x)
1160   `(call |make_lisp_string| (call (get ,x "toString"))))
1161
1162 (define-builtin eq (x y)
1163   (js!bool `(=== ,x ,y)))
1164
1165 (define-builtin char-code (x)
1166   (type-check (("x" "string" x))
1167     "char_to_codepoint(x)"))
1168
1169 (define-builtin code-char (x)
1170   (type-check (("x" "number" x))
1171     "char_from_codepoint(x)"))
1172
1173 (define-builtin characterp (x)
1174   (js!bool
1175    (js!selfcall
1176      "var x = " x ";"
1177      "return (typeof(" x ") == \"string\") && (x.length == 1 || x.length == 2);")))
1178
1179 (define-builtin char-upcase (x)
1180   `(call |safe_char_upcase| ,x))
1181
1182 (define-builtin char-downcase (x)
1183   `(call |safe_char_downcase| ,x))
1184
1185 (define-builtin stringp (x)
1186   (js!bool
1187    (js!selfcall
1188      "var x = " x ";"
1189      "return typeof(x) == 'object' && 'length' in x && x.stringp == 1;")))
1190
1191 (define-raw-builtin funcall (func &rest args)
1192   (js!selfcall
1193     "var f = " (ls-compile func) ";"
1194     "return (typeof f === 'function'? f: f.fvalue)("
1195     `(code
1196      ,@(interleave (list* (if *multiple-value-p* "values" "pv")
1197                           (integer-to-string (length args))
1198                           (mapcar #'ls-compile args))
1199                    ", "))
1200     ")"))
1201
1202 (define-raw-builtin apply (func &rest args)
1203   (if (null args)
1204       `(code "(" ,(ls-compile func) ")()")
1205       (let ((args (butlast args))
1206             (last (car (last args))))
1207         (js!selfcall
1208           "var f = " (ls-compile func) ";"
1209           "var args = [" `(code
1210                            ,@(interleave (list* (if *multiple-value-p* "values" "pv")
1211                                                 (integer-to-string (length args))
1212                                                 (mapcar #'ls-compile args))
1213                                          ", "))
1214           "];"
1215           "var tail = (" (ls-compile last) ");"
1216           "while (tail != " (ls-compile nil) "){"
1217           "    args.push(tail.car);"
1218           "    args[1] += 1;"
1219           "    tail = tail.cdr;"
1220           "}"
1221           "return (typeof f === 'function'? f : f.fvalue).apply(this, args);" ))))
1222
1223 (define-builtin js-eval (string)
1224   (if *multiple-value-p*
1225       (js!selfcall
1226         "var v = globalEval(xstring(" string "));"
1227         "return values.apply(this, forcemv(v));" )
1228       `(code "globalEval(xstring(" ,string "))")))
1229
1230 (define-builtin %throw (string)
1231   (js!selfcall "throw " string ";" ))
1232
1233 (define-builtin functionp (x)
1234   (js!bool `(code "(typeof " ,x " == 'function')")))
1235
1236 (define-builtin %write-string (x)
1237   `(code "lisp.write(" ,x ")"))
1238
1239 (define-builtin /debug (x)
1240   `(code "console.log(xstring(" ,x "))"))
1241
1242
1243 ;;; Storage vectors. They are used to implement arrays and (in the
1244 ;;; future) structures.
1245
1246 (define-builtin storage-vector-p (x)
1247   (js!bool
1248    (js!selfcall
1249      "var x = " x ";"
1250      "return typeof x === 'object' && 'length' in x;")))
1251
1252 (define-builtin make-storage-vector (n)
1253   (js!selfcall
1254     "var r = [];"
1255     "r.length = " n ";"
1256     "return r;" ))
1257
1258 (define-builtin storage-vector-size (x)
1259   `(code ,x ".length"))
1260
1261 (define-builtin resize-storage-vector (vector new-size)
1262   `(code "(" ,vector ".length = " ,new-size ")"))
1263
1264 (define-builtin storage-vector-ref (vector n)
1265   (js!selfcall
1266     "var x = " "(" vector ")[" n "];"
1267     "if (x === undefined) throw 'Out of range';"
1268     "return x;" ))
1269
1270 (define-builtin storage-vector-set (vector n value)
1271   (js!selfcall
1272     "var x = " vector ";"
1273     "var i = " n ";"
1274     "if (i < 0 || i >= x.length) throw 'Out of range';"
1275     "return x[i] = " value ";" ))
1276
1277 (define-builtin concatenate-storage-vector (sv1 sv2)
1278   (js!selfcall
1279     "var sv1 = " sv1 ";"
1280     "var r = sv1.concat(" sv2 ");"
1281     "r.type = sv1.type;"
1282     "r.stringp = sv1.stringp;"
1283     "return r;" ))
1284
1285 (define-builtin get-internal-real-time ()
1286   "(new Date()).getTime()")
1287
1288 (define-builtin values-array (array)
1289   (if *multiple-value-p*
1290       `(code "values.apply(this, " ,array ")")
1291       `(code "pv.apply(this, " ,array ")")))
1292
1293 (define-raw-builtin values (&rest args)
1294   (if *multiple-value-p*
1295       `(code "values(" ,@(interleave (mapcar #'ls-compile args) ",") ")")
1296       `(code "pv(" ,@(interleave (mapcar #'ls-compile args) ", ") ")")))
1297
1298
1299 ;;; Javascript FFI
1300
1301 (define-builtin new () "{}")
1302
1303 (define-raw-builtin oget* (object key &rest keys)
1304   (js!selfcall
1305     "var tmp = (" (ls-compile object) ")[xstring(" (ls-compile key) ")];"
1306     `(code
1307       ,@(mapcar (lambda (key)
1308                   `(code "if (tmp === undefined) return " ,(ls-compile nil) ";"
1309                          "tmp = tmp[xstring(" ,(ls-compile key) ")];" ))
1310                 keys))
1311     "return tmp === undefined? " (ls-compile nil) " : tmp;" ))
1312
1313 (define-raw-builtin oset* (value object key &rest keys)
1314   (let ((keys (cons key keys)))
1315     (js!selfcall
1316       "var obj = " (ls-compile object) ";"
1317       `(code ,@(mapcar (lambda (key)
1318                          `(code "obj = obj[xstring(" ,(ls-compile key) ")];"
1319                                 "if (obj === undefined) throw 'Impossible to set Javascript property.';" ))
1320                        (butlast keys)))
1321       "var tmp = obj[xstring(" (ls-compile (car (last keys))) ")] = " (ls-compile value) ";"
1322       "return tmp === undefined? " (ls-compile nil) " : tmp;" )))
1323
1324 (define-raw-builtin oget (object key &rest keys)
1325   `(call |js_to_lisp| ,(ls-compile `(oget* ,object ,key ,@keys))))
1326
1327 (define-raw-builtin oset (value object key &rest keys)
1328   (ls-compile `(oset* (lisp-to-js ,value) ,object ,key ,@keys)))
1329
1330 (define-builtin objectp (x)
1331   (js!bool `(=== (typeof ,x) "object")))
1332
1333 (define-builtin lisp-to-js (x) `(call |lisp_to_js| ,x))
1334 (define-builtin js-to-lisp (x) `(call |js_to_lisp| ,x))
1335
1336
1337 (define-builtin in (key object)
1338   (js!bool `(in (call |xstring| ,key) ,object)))
1339
1340 (define-builtin map-for-in (function object)
1341   (js!selfcall
1342    "var f = " function ";"
1343    "var g = (typeof f === 'function' ? f : f.fvalue);"
1344    "var o = " object ";"
1345    "for (var key in o){"
1346    `(code "g(" ,(if *multiple-value-p* "values" "pv") ", 1, o[key]);" )
1347    "}"
1348    " return " (ls-compile nil) ";" ))
1349
1350 (define-compilation %js-vref (var)
1351   `(code "js_to_lisp(" ,var ")"))
1352
1353 (define-compilation %js-vset (var val)
1354   `(code "(" ,var " = lisp_to_js(" ,(ls-compile val) "))"))
1355
1356 (define-setf-expander %js-vref (var)
1357   (let ((new-value (gensym)))
1358     (unless (stringp var)
1359       (error "`~S' is not a string." var))
1360     (values nil
1361             (list var)
1362             (list new-value)
1363             `(%js-vset ,var ,new-value)
1364             `(%js-vref ,var))))
1365
1366
1367 #-jscl
1368 (defvar *macroexpander-cache*
1369   (make-hash-table :test #'eq))
1370
1371 (defun !macro-function (symbol)
1372   (unless (symbolp symbol)
1373     (error "`~S' is not a symbol." symbol))
1374   (let ((b (lookup-in-lexenv symbol *environment* 'function)))
1375     (if (and b (eq (binding-type b) 'macro))
1376         (let ((expander (binding-value b)))
1377           (cond
1378             #-jscl
1379             ((gethash b *macroexpander-cache*)
1380              (setq expander (gethash b *macroexpander-cache*)))
1381             ((listp expander)
1382              (let ((compiled (eval expander)))
1383                ;; The list representation are useful while
1384                ;; bootstrapping, as we can dump the definition of the
1385                ;; macros easily, but they are slow because we have to
1386                ;; evaluate them and compile them now and again. So, let
1387                ;; us replace the list representation version of the
1388                ;; function with the compiled one.
1389                ;;
1390                #+jscl (setf (binding-value b) compiled)
1391                #-jscl (setf (gethash b *macroexpander-cache*) compiled)
1392                (setq expander compiled))))
1393           expander)
1394         nil)))
1395
1396 (defun !macroexpand-1 (form)
1397   (cond
1398     ((symbolp form)
1399      (let ((b (lookup-in-lexenv form *environment* 'variable)))
1400        (if (and b (eq (binding-type b) 'macro))
1401            (values (binding-value b) t)
1402            (values form nil))))
1403     ((and (consp form) (symbolp (car form)))
1404      (let ((macrofun (!macro-function (car form))))
1405        (if macrofun
1406            (values (funcall macrofun (cdr form)) t)
1407            (values form nil))))
1408     (t
1409      (values form nil))))
1410
1411 (defun compile-funcall (function args)
1412   (let* ((values-funcs (if *multiple-value-p* "values" "pv"))
1413          (arglist `(code "(" ,@(interleave (list* values-funcs
1414                                                   (integer-to-string (length args))
1415                                                   (mapcar #'ls-compile args))
1416                                            ", ")
1417                          ")")))
1418     (unless (or (symbolp function)
1419                 (and (consp function)
1420                      (member (car function) '(lambda oget))))
1421       (error "Bad function designator `~S'" function))
1422     (cond
1423       ((translate-function function)
1424        `(code ,(translate-function function) ,arglist))
1425       ((and (symbolp function)
1426             #+jscl (eq (symbol-package function) (find-package "COMMON-LISP"))
1427             #-jscl t)
1428        `(code ,(ls-compile `',function) ".fvalue" ,arglist))
1429       #+jscl((symbolp function)
1430        `(code ,(ls-compile `#',function) ,arglist))
1431       ((and (consp function) (eq (car function) 'lambda))
1432        `(code ,(ls-compile `#',function) ,arglist))
1433       ((and (consp function) (eq (car function) 'oget))
1434        `(code ,(ls-compile function) ,arglist))
1435       (t
1436        (error "Bad function descriptor")))))
1437
1438 (defun ls-compile-block (sexps &optional return-last-p decls-allowed-p)
1439   (multiple-value-bind (sexps decls)
1440       (parse-body sexps :declarations decls-allowed-p)
1441     (declare (ignore decls))
1442     (if return-last-p
1443         `(code ,(ls-compile-block (butlast sexps) nil decls-allowed-p)
1444                "return " ,(ls-compile (car (last sexps)) *multiple-value-p*) ";")
1445         `(code
1446           ,@(interleave (mapcar #'ls-compile sexps) ";
1447 " *newline*)
1448           ";" ,*newline*))))
1449
1450 (defun ls-compile* (sexp &optional multiple-value-p)
1451   (multiple-value-bind (sexp expandedp) (!macroexpand-1 sexp)
1452     (when expandedp
1453       (return-from ls-compile* (ls-compile sexp multiple-value-p)))
1454     ;; The expression has been macroexpanded. Now compile it!
1455     (let ((*multiple-value-p* multiple-value-p))
1456       (cond
1457         ((symbolp sexp)
1458          (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1459            (cond
1460              ((and b (not (member 'special (binding-declarations b))))
1461               (binding-value b))
1462              ((or (keywordp sexp)
1463                   (and b (member 'constant (binding-declarations b))))
1464               `(code ,(ls-compile `',sexp) ".value"))
1465              (t
1466               (ls-compile `(symbol-value ',sexp))))))
1467         ((or (integerp sexp) (floatp sexp) (characterp sexp) (stringp sexp) (arrayp sexp))
1468          (literal sexp))
1469         ((listp sexp)
1470          (let ((name (car sexp))
1471                (args (cdr sexp)))
1472            (cond
1473              ;; Special forms
1474              ((assoc name *compilations*)
1475               (let ((comp (second (assoc name *compilations*))))
1476                 (apply comp args)))
1477              ;; Built-in functions
1478              ((and (assoc name *builtins*)
1479                    (not (claimp name 'function 'notinline)))
1480               (let ((comp (second (assoc name *builtins*))))
1481                 (apply comp args)))
1482              (t
1483               (compile-funcall name args)))))
1484         (t
1485          (error "How should I compile `~S'?" sexp))))))
1486
1487 (defun ls-compile (sexp &optional multiple-value-p)
1488   `(code "(" ,(ls-compile* sexp multiple-value-p) ")"))
1489
1490
1491 (defvar *compile-print-toplevels* nil)
1492
1493 (defun truncate-string (string &optional (width 60))
1494   (let ((n (or (position #\newline string)
1495                (min width (length string)))))
1496     (subseq string 0 n)))
1497
1498 (defun convert-toplevel (sexp &optional multiple-value-p)
1499   (let ((*toplevel-compilations* nil))
1500     (cond
1501       ;; Non-empty toplevel progn
1502       ((and (consp sexp)
1503             (eq (car sexp) 'progn)
1504             (cdr sexp))
1505        `(progn
1506           ,@(mapcar (lambda (s) (convert-toplevel s t))
1507                     (cdr sexp))))
1508       (t
1509        (when *compile-print-toplevels*
1510          (let ((form-string (prin1-to-string sexp)))
1511            (format t "Compiling ~a..." (truncate-string form-string))))
1512        (let ((code (ls-compile sexp multiple-value-p)))
1513          `(code
1514            ,@(interleave (get-toplevel-compilations) ";
1515 " t)
1516            ,(when code
1517                   `(code ,code ";"))))))))
1518
1519 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
1520   (with-output-to-string (*standard-output*)
1521     (js (convert-toplevel sexp multiple-value-p))))