94e77ce5c837098361d8b818398d5467716382f2
[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 ;;; 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.
25
26 (defun code (&rest args)
27   (mapconcat (lambda (arg)
28                (cond
29                  ((null arg) "")
30                  ((integerp arg) (integer-to-string arg))
31                  ((floatp arg) (float-to-string arg))
32                  ((stringp arg) arg)
33                  (t (error "Unknown argument `~S'." arg))))
34              args))
35
36 ;;; Wrap X with a Javascript code to convert the result from
37 ;;; Javascript generalized booleans to T or NIL.
38 (defun js!bool (x)
39   (code "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
40
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) "})()"))
48
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.
52
53 #+jscl
54 (defun indent (&rest string)
55   (let ((input (apply #'code string)))
56     (let ((output "")
57           (index 0)
58           (size (length input)))
59       (when (plusp (length input)) (concatf output "    "))
60       (while (< index size)
61         (let ((str
62                (if (and (char= (char input index) #\newline)
63                         (< index (1- size))
64                         (not (char= (char input (1+ index)) #\newline)))
65                    (concat (string #\newline) "    ")
66                    (string (char input index)))))
67           (concatf output str))
68         (incf index))
69       output)))
70
71 #+common-lisp
72 (defun indent (&rest string)
73   (with-output-to-string (*standard-output*)
74     (with-input-from-string (input (apply #'code string))
75       (loop
76          for line = (read-line input nil)
77          while line
78          do (write-string "    ")
79          do (write-line line)))))
80
81
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
87 ;;; function call.
88 (defvar *multiple-value-p* nil)
89
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))
97          (slot-descriptions
98           (mapcar (lambda (sd)
99                     (cond
100                       ((symbolp sd)
101                        (list sd))
102                       ((and (listp sd) (car sd) (cddr sd))
103                        sd)
104                       (t
105                        (error "Bad slot description `~S'." sd))))
106                   slots))
107          (predicate (intern (concat name-string "-P"))))
108     `(progn
109        ;; Constructor
110        (defun ,(intern (concat "MAKE-" name-string)) (&key ,@slot-descriptions)
111          (list ',name ,@(mapcar #'car slot-descriptions)))
112        ;; Predicate
113        (defun ,predicate (x)
114          (and (consp x) (eq (car x) ',name)))
115        ;; Copier
116        (defun ,(intern (concat "COPY-" name-string)) (x)
117          (copy-list x))
118        ;; Slot accessors
119        ,@(with-collect
120           (let ((index 1))
121             (dolist (slot slot-descriptions)
122               (let* ((name (car slot))
123                      (accessor-name (intern (concat name-string "-" (string name)))))
124                 (collect
125                     `(defun ,accessor-name (x)
126                        (unless (,predicate x)
127                          (error "The object `~S' is not of type `~S'" x ,name-string))
128                        (nth ,index x)))
129                 ;; TODO: Implement this with a higher level
130                 ;; abstraction like defsetf or (defun (setf ..))
131                 (collect
132                     `(define-setf-expander ,accessor-name (x)
133                        (let ((object (gensym))
134                              (new-value (gensym)))
135                          (values (list object)
136                                  (list x)
137                                  (list new-value)
138                                  `(progn
139                                     (rplaca (nthcdr ,',index ,object) ,new-value) 
140                                     ,new-value)
141                                  `(,',accessor-name ,object)))))
142                 (incf index)))))
143        ',name)))
144
145
146 ;;; Environment
147
148 (def!struct binding
149   name
150   type
151   value
152   declarations)
153
154 (def!struct lexenv
155   variable
156   function
157   block
158   gotag)
159
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))
167
168 (defun push-to-lexenv (binding lexenv namespace)
169   (ecase 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)))))
174
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))))
179
180
181 (defvar *environment* (make-lexenv))
182
183 (defvar *variable-counter* 0)
184
185 (defun gvarname (symbol)
186   (declare (ignore symbol))
187   (code "v" (incf *variable-counter*)))
188
189 (defun translate-variable (symbol)
190   (awhen (lookup-in-lexenv symbol *environment* 'variable)
191     (binding-value it)))
192
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)))))
198
199 ;;; Toplevel compilations
200 (defvar *toplevel-compilations* nil)
201
202 (defun toplevel-compilation (string)
203   (push string *toplevel-compilations*))
204
205 (defun null-or-empty-p (x)
206   (zerop (length x)))
207
208 (defun get-toplevel-compilations ()
209   (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
210
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))
215   name)
216
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)
221         b)))
222
223 (defun claimp (symbol namespace claim)
224   (let ((b (lookup-in-lexenv symbol *environment* namespace)))
225     (and b (member claim (binding-declarations b)))))
226
227 (defun !proclaim (decl)
228   (case (car decl)
229     (special
230      (dolist (name (cdr decl))
231        (let ((b (global-binding name 'variable 'variable)))
232          (push 'special (binding-declarations b)))))
233     (notinline
234      (dolist (name (cdr decl))
235        (let ((b (global-binding name 'function 'function)))
236          (push 'notinline (binding-declarations b)))))
237     (constant
238      (dolist (name (cdr decl))
239        (let ((b (global-binding name 'variable 'variable)))
240          (push 'constant (binding-declarations b)))))))
241
242 #+jscl
243 (fset 'proclaim #'!proclaim)
244
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)
248     name))
249
250 #+jscl
251 (defmacro define-symbol-macro (name expansion)
252   `(%define-symbol-macro ',name ',expansion))
253
254
255 ;;; Special forms
256
257 (defvar *compilations* nil)
258
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)))
264          *compilations*))
265
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*)
270         ")"))
271
272 (defvar *ll-keywords* '(&optional &rest &key))
273
274 (defun list-until-keyword (list)
275   (if (or (null list) (member (car list) *ll-keywords*))
276       nil
277       (cons (car list) (list-until-keyword (cdr list)))))
278
279 (defun ll-section (keyword ll)
280   (list-until-keyword (cdr (member keyword ll))))
281
282 (defun ll-required-arguments (ll)
283   (list-until-keyword ll))
284
285 (defun ll-optional-arguments-canonical (ll)
286   (mapcar #'ensure-list (ll-section '&optional ll)))
287
288 (defun ll-optional-arguments (ll)
289   (mapcar #'car (ll-optional-arguments-canonical ll)))
290
291 (defun ll-rest-argument (ll)
292   (let ((rest (ll-section '&rest ll)))
293     (when (cdr rest)
294       (error "Bad lambda-list `~S'." ll))
295     (car rest)))
296
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))
304                        (car arg)
305                        (list (intern (symbol-name (car arg)) "KEYWORD") (car arg)))
306                    (cdr arg)))))
307     (mapcar #'canonicalize (ll-section '&key ll))))
308
309 (defun ll-keyword-arguments (ll)
310   (mapcar (lambda (keyarg) (second (first keyarg)))
311           (ll-keyword-arguments-canonical ll)))
312
313 (defun ll-svars (lambda-list)
314   (let ((args
315          (append
316           (ll-keyword-arguments-canonical lambda-list)
317           (ll-optional-arguments-canonical lambda-list))))
318     (remove nil (mapcar #'third args))))
319
320 (defun lambda-name/docstring-wrapper (name docstring &rest strs)
321   (if (or name docstring)
322       (js!selfcall
323         "var func = " (join strs) ";" *newline*
324         (when name
325           (code "func.fname = '" (escape-string name) "';" *newline*))
326         (when docstring
327           (code "func.docstring = '" (escape-string docstring) "';" *newline*))
328         "return func;" *newline*)
329       (apply #'code strs)))
330
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 n-required-arguments)
336         (max (if rest-p 'n/a (+ n-required-arguments n-optional-arguments))))
337     (block nil
338       ;; Special case: a positive exact number of arguments.
339       (when (and (< 0 min) (eql min max))
340         (return (code "checkArgs(nargs, " min ");" *newline*)))
341       ;; General case:
342       (code
343        (when (< 0 min)
344          (code "checkArgsAtLeast(nargs, " min ");" *newline*))
345        (when (numberp max)
346          (code "checkArgsAtMost(nargs, " max ");" *newline*))))))
347
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 "switch(nargs){" *newline*
354             (let ((cases nil)
355                   (idx 0))
356               (progn
357                 (while (< idx n-optional-arguments)
358                   (let ((arg (nth idx optional-arguments)))
359                     (push (code "case " (+ idx n-required-arguments) ":" *newline*
360                                 (indent (translate-variable (car arg))
361                                         "="
362                                         (ls-compile (cadr arg)) ";" *newline*)
363                                 (when (third arg)
364                                   (indent (translate-variable (third arg))
365                                           "="
366                                           (ls-compile nil)
367                                           ";" *newline*)))
368                           cases)
369                     (incf idx)))
370                 (push (code "default: break;" *newline*) cases)
371                 (join (reverse cases))))
372             "}" *newline*))))
373
374 (defun compile-lambda-rest (ll)
375   (let ((n-required-arguments (length (ll-required-arguments ll)))
376         (n-optional-arguments (length (ll-optional-arguments ll)))
377         (rest-argument (ll-rest-argument ll)))
378     (when rest-argument
379       (let ((js!rest (translate-variable rest-argument)))
380         (code "var " js!rest "= " (ls-compile nil) ";" *newline*
381               "for (var i = nargs-1; i>=" (+ n-required-arguments n-optional-arguments)
382               "; i--)" *newline*
383               (indent js!rest " = {car: arguments[i+2], cdr: " js!rest "};" *newline*))))))
384
385 (defun compile-lambda-parse-keywords (ll)
386   (let ((n-required-arguments
387          (length (ll-required-arguments ll)))
388         (n-optional-arguments
389          (length (ll-optional-arguments ll)))
390         (keyword-arguments
391          (ll-keyword-arguments-canonical ll)))
392     (code
393      ;; Declare variables
394      (mapconcat (lambda (arg)
395                   (let ((var (second (car arg))))
396                     (code "var " (translate-variable var) "; " *newline*
397                           (when (third arg)
398                             (code "var " (translate-variable (third arg))
399                                   " = " (ls-compile nil)
400                                   ";" *newline*)))))
401                 keyword-arguments)
402      ;; Parse keywords
403      (flet ((parse-keyword (keyarg)
404               ;; ((keyword-name var) init-form)
405               (code "for (i=" (+ n-required-arguments n-optional-arguments)
406                     "; i<nargs; i+=2){" *newline*
407                     (indent
408                      "if (arguments[i+2] === " (ls-compile (caar keyarg)) "){" *newline*
409                      (indent (translate-variable (cadr (car keyarg)))
410                              " = arguments[i+3];"
411                              *newline*
412                              (let ((svar (third keyarg)))
413                                (when svar
414                                  (code (translate-variable svar) " = " (ls-compile t) ";" *newline*)))
415                              "break;" *newline*)
416                      "}" *newline*)
417                     "}" *newline*
418                     ;; Default value
419                     "if (i == nargs){" *newline*
420                     (indent (translate-variable (cadr (car keyarg))) " = " (ls-compile (cadr keyarg)) ";" *newline*)
421                     "}" *newline*)))
422        (when keyword-arguments
423          (code "var i;" *newline*
424                (mapconcat #'parse-keyword keyword-arguments))))
425      ;; Check for unknown keywords
426      (when keyword-arguments
427        (code "for (i=" (+ n-required-arguments n-optional-arguments)
428              "; i<nargs; i+=2){" *newline*
429              (indent "if ("
430                      (join (mapcar (lambda (x)
431                                      (concat "arguments[i+2] !== " (ls-compile (caar x))))
432                                    keyword-arguments)
433                            " && ")
434                      ")" *newline*
435                      (indent
436                       "throw 'Unknown keyword argument ' + xstring(arguments[i].name);" *newline*))
437              "}" *newline*)))))
438
439 (defun parse-lambda-list (ll)
440   (values (ll-required-arguments ll)
441           (ll-optional-arguments ll)
442           (ll-keyword-arguments  ll)
443           (ll-rest-argument      ll)))
444
445 ;;; Process BODY for declarations and/or docstrings. Return as
446 ;;; multiple values the BODY without docstrings or declarations, the
447 ;;; list of declaration forms and the docstring.
448 (defun parse-body (body &key declarations docstring)
449   (let ((value-declarations)
450         (value-docstring))
451     ;; Parse declarations
452     (when declarations
453       (do* ((rest body (cdr rest))
454             (form (car rest) (car rest)))
455            ((or (atom form) (not (eq (car form) 'declare)))
456             (setf body rest))
457         (push form value-declarations)))
458     ;; Parse docstring
459     (when (and docstring
460                (stringp (car body))
461                (not (null (cdr body))))
462       (setq value-docstring (car body))
463       (setq body (cdr body)))
464     (values body value-declarations value-docstring)))
465
466 ;;; Compile a lambda function with lambda list LL and body BODY. If
467 ;;; NAME is given, it should be a constant string and it will become
468 ;;; the name of the function. If BLOCK is non-NIL, a named block is
469 ;;; created around the body. NOTE: No block (even anonymous) is
470 ;;; created if BLOCk is NIL.
471 (defun compile-lambda (ll body &key name block)
472   (multiple-value-bind (required-arguments
473                         optional-arguments
474                         keyword-arguments
475                         rest-argument)
476       (parse-lambda-list ll)
477     (multiple-value-bind (body decls documentation)
478         (parse-body body :declarations t :docstring t)
479       (declare (ignore decls))
480       (let ((n-required-arguments (length required-arguments))
481             (n-optional-arguments (length optional-arguments))
482             (*environment* (extend-local-env
483                             (append (ensure-list rest-argument)
484                                     required-arguments
485                                     optional-arguments
486                                     keyword-arguments
487                                     (ll-svars ll)))))
488         (lambda-name/docstring-wrapper name documentation
489          "(function ("
490          (join (list* "values"
491                       "nargs"
492                       (mapcar #'translate-variable
493                               (append required-arguments optional-arguments)))
494                ",")
495          "){" *newline*
496          (indent
497           ;; Check number of arguments
498           (lambda-check-argument-count n-required-arguments
499                                        n-optional-arguments
500                                        (or rest-argument keyword-arguments))
501                                         (compile-lambda-optional ll)
502                                         (compile-lambda-rest ll)
503                                         (compile-lambda-parse-keywords ll)
504                                         (let ((*multiple-value-p* t))
505                                           (if block
506                                               (ls-compile-block `((block ,block ,@body)) t)
507                                               (ls-compile-block body t))))
508          "})")))))
509
510
511 (defun setq-pair (var val)
512   (let ((b (lookup-in-lexenv var *environment* 'variable)))
513     (cond
514       ((and b
515             (eq (binding-type b) 'variable)
516             (not (member 'special (binding-declarations b)))
517             (not (member 'constant (binding-declarations b))))
518        (code (binding-value b) " = " (ls-compile val)))
519       ((and b (eq (binding-type b) 'macro))
520        (ls-compile `(setf ,var ,val)))
521       (t
522        (ls-compile `(set ',var ,val))))))
523
524
525 (define-compilation setq (&rest pairs)
526   (let ((result ""))
527     (while t
528       (cond
529         ((null pairs) (return))
530         ((null (cdr pairs))
531          (error "Odd pairs in SETQ"))
532         (t
533          (concatf result
534            (concat (setq-pair (car pairs) (cadr pairs))
535                    (if (null (cddr pairs)) "" ", ")))
536          (setq pairs (cddr pairs)))))
537     (code "(" result ")")))
538
539
540 ;;; Literals
541 (defun escape-string (string)
542   (let ((output "")
543         (index 0)
544         (size (length string)))
545     (while (< index size)
546       (let ((ch (char string index)))
547         (when (or (char= ch #\") (char= ch #\\))
548           (setq output (concat output "\\")))
549         (when (or (char= ch #\newline))
550           (setq output (concat output "\\"))
551           (setq ch #\n))
552         (setq output (concat output (string ch))))
553       (incf index))
554     output))
555
556
557 (defvar *literal-table* nil)
558 (defvar *literal-counter* 0)
559
560 (defun genlit ()
561   (code "l" (incf *literal-counter*)))
562
563 (defun dump-symbol (symbol)
564   #+common-lisp
565   (let ((package (symbol-package symbol)))
566     (if (eq package (find-package "KEYWORD"))
567         (code "{name: " (dump-string (symbol-name symbol))
568               ", 'package': " (dump-string (package-name package)) "}")
569         (code "{name: " (dump-string (symbol-name symbol)) "}")))
570   #+jscl
571   (let ((package (symbol-package symbol)))
572     (if (null package)
573         (code "{name: " (dump-symbol (symbol-name symbol)) "}")
574         (ls-compile `(intern ,(symbol-name symbol) ,(package-name package))))))
575
576 (defun dump-cons (cons)
577   (let ((head (butlast cons))
578         (tail (last cons)))
579     (code "QIList("
580           (join-trailing (mapcar (lambda (x) (literal x t)) head) ",")
581           (literal (car tail) t)
582           ","
583           (literal (cdr tail) t)
584           ")")))
585
586 (defun dump-array (array)
587   (let ((elements (vector-to-list array)))
588     (concat "[" (join (mapcar #'literal elements) ", ") "]")))
589
590 (defun dump-string (string)
591   (code "make_lisp_string(\"" (escape-string string) "\")"))
592
593 (defun literal (sexp &optional recursive)
594   (cond
595     ((integerp sexp) (integer-to-string sexp))
596     ((floatp sexp) (float-to-string sexp))
597     ((characterp sexp) (code "\"" (escape-string (string sexp)) "\""))
598     (t
599      (or (cdr (assoc sexp *literal-table* :test #'equal))
600          (let ((dumped (typecase sexp
601                          (symbol (dump-symbol sexp))
602                          (cons (dump-cons sexp))
603                          (string (dump-string sexp))
604                          (array (dump-array sexp)))))
605            (if (and recursive (not (symbolp sexp)))
606                dumped
607                (let ((jsvar (genlit)))
608                  (push (cons sexp jsvar) *literal-table*)
609                  (toplevel-compilation (code "var " jsvar " = " dumped))
610                  jsvar)))))))
611
612 (define-compilation quote (sexp)
613   (literal sexp))
614
615 (define-compilation %while (pred &rest body)
616   (js!selfcall
617     "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
618     (indent (ls-compile-block body))
619     "}"
620     "return " (ls-compile nil) ";" *newline*))
621
622 (define-compilation function (x)
623   (cond
624     ((and (listp x) (eq (car x) 'lambda))
625      (compile-lambda (cadr x) (cddr x)))
626     ((and (listp x) (eq (car x) 'named-lambda))
627      ;; TODO: destructuring-bind now! Do error checking manually is
628      ;; very annoying.
629      (let ((name (cadr x))
630            (ll (caddr x))
631            (body (cdddr x)))
632        (compile-lambda ll body
633                        :name (symbol-name name)
634                        :block name)))
635     ((symbolp x)
636      (let ((b (lookup-in-lexenv x *environment* 'function)))
637        (if b
638            (binding-value b)
639            (ls-compile `(symbol-function ',x)))))))
640
641
642 (defun make-function-binding (fname)
643   (make-binding :name fname :type 'function :value (gvarname fname)))
644
645 (defun compile-function-definition (list)
646   (compile-lambda (car list) (cdr list)))
647
648 (defun translate-function (name)
649   (let ((b (lookup-in-lexenv name *environment* 'function)))
650     (and b (binding-value b))))
651
652 (define-compilation flet (definitions &rest body)
653   (let* ((fnames (mapcar #'car definitions))
654          (cfuncs (mapcar (lambda (def)
655                            (compile-lambda (cadr def)
656                                            `((block ,(car def)
657                                                ,@(cddr def)))))
658                          definitions))
659          (*environment*
660           (extend-lexenv (mapcar #'make-function-binding fnames)
661                          *environment*
662                          'function)))
663     (code "(function("
664           (join (mapcar #'translate-function fnames) ",")
665           "){" *newline*
666           (let ((body (ls-compile-block body t)))
667             (indent body))
668           "})(" (join cfuncs ",") ")")))
669
670 (define-compilation labels (definitions &rest body)
671   (let* ((fnames (mapcar #'car definitions))
672          (*environment*
673           (extend-lexenv (mapcar #'make-function-binding fnames)
674                          *environment*
675                          'function)))
676     (js!selfcall
677       (mapconcat (lambda (func)
678                    (code "var " (translate-function (car func))
679                          " = " (compile-lambda (cadr func)
680                                                `((block ,(car func) ,@(cddr func))))
681                          ";" *newline*))
682                  definitions)
683       (ls-compile-block body t))))
684
685
686 (defvar *compiling-file* nil)
687 (define-compilation eval-when-compile (&rest body)
688   (if *compiling-file*
689       (progn
690         (eval (cons 'progn body))
691         nil)
692       (ls-compile `(progn ,@body))))
693
694 (defmacro define-transformation (name args form)
695   `(define-compilation ,name ,args
696      (ls-compile ,form)))
697
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))))
702
703 (defun special-variable-p (x)
704   (and (claimp x 'variable 'special) t))
705
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
710 ;;; the old value.
711 (defun let-binding-wrapper (bindings body)
712   (when (null bindings)
713     (return-from let-binding-wrapper body))
714   (code
715    "try {" *newline*
716    (indent "var tmp;" *newline*
717            (mapconcat
718             (lambda (b)
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*)))
723             bindings)
724            body *newline*)
725    "}" *newline*
726    "finally {"  *newline*
727    (indent
728     (mapconcat (lambda (b)
729                  (let ((s (ls-compile `(quote ,(car b)))))
730                    (code s ".value" " = " (cdr b) ";" *newline*)))
731                bindings))
732    "}" *newline*))
733
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)))
739          (dynamic-bindings))
740     (code "(function("
741           (join (mapcar (lambda (x)
742                           (if (special-variable-p x)
743                               (let ((v (gvarname x)))
744                                 (push (cons x v) dynamic-bindings)
745                                 v)
746                               (translate-variable x)))
747                         variables)
748                 ",")
749           "){" *newline*
750           (let ((body (ls-compile-block body t)))
751             (indent (let-binding-wrapper dynamic-bindings body)))
752           "})(" (join cvalues ",") ")")))
753
754
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))))))
766
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)
771   (when (null symbols)
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))))
775     (code
776      "try {" *newline*
777      (indent
778       (mapconcat (lambda (b)
779                    (let ((s (ls-compile `(quote ,(car b)))))
780                      (code "var " (cdr b) " = " s ".value;" *newline*)))
781                  store)
782       body)
783      "}" *newline*
784      "finally {" *newline*
785      (indent
786       (mapconcat (lambda (b)
787                    (let ((s (ls-compile `(quote ,(car b)))))
788                      (code s ".value" " = " (cdr b) ";" *newline*)))
789                  store))
790      "}" *newline*)))
791
792 (define-compilation let* (bindings &rest body)
793   (let ((bindings (mapcar #'ensure-list bindings))
794         (*environment* (copy-lexenv *environment*)))
795     (js!selfcall
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)))))
800
801
802 (define-compilation block (name &rest body)
803   ;; We use Javascript exceptions to implement non local control
804   ;; transfer. Exceptions has dynamic scoping, so we use a uniquely
805   ;; generated object to identify the block. The instance of a empty
806   ;; array is used to distinguish between nested dynamic Javascript
807   ;; exceptions. See https://github.com/davazp/jscl/issues/64 for
808   ;; futher details.
809   (let* ((idvar (gvarname name))
810          (b (make-binding :name name :type 'block :value idvar)))
811     (when *multiple-value-p*
812       (push 'multiple-value (binding-declarations b)))
813     (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
814            (cbody (ls-compile-block body t)))
815       (if (member 'used (binding-declarations b))
816           (js!selfcall
817             "try {" *newline*
818             "var " idvar " = [];" *newline*
819             (indent cbody)
820             "}" *newline*
821             "catch (cf){" *newline*
822             "    if (cf.type == 'block' && cf.id == " idvar ")" *newline*
823             (if *multiple-value-p*
824                 "        return values.apply(this, forcemv(cf.values));"
825                 "        return cf.values;")
826             *newline*
827             "    else" *newline*
828             "        throw cf;" *newline*
829             "}" *newline*)
830           (js!selfcall cbody)))))
831
832 (define-compilation return-from (name &optional value)
833   (let* ((b (lookup-in-lexenv name *environment* 'block))
834          (multiple-value-p (member 'multiple-value (binding-declarations b))))
835     (when (null b)
836       (error "Return from unknown block `~S'." (symbol-name name)))
837     (push 'used (binding-declarations b))
838     ;; The binding value is the name of a variable, whose value is the
839     ;; unique identifier of the block as exception. We can't use the
840     ;; variable name itself, because it could not to be unique, so we
841     ;; capture it in a closure.
842     (js!selfcall
843       (when multiple-value-p (code "var values = mv;" *newline*))
844       "throw ({"
845       "type: 'block', "
846       "id: " (binding-value b) ", "
847       "values: " (ls-compile value multiple-value-p) ", "
848       "message: 'Return from unknown block " (symbol-name name) ".'"
849       "})")))
850
851 (define-compilation catch (id &rest body)
852   (js!selfcall
853     "var id = " (ls-compile id) ";" *newline*
854     "try {" *newline*
855     (indent (ls-compile-block body t)) *newline*
856     "}" *newline*
857     "catch (cf){" *newline*
858     "    if (cf.type == 'catch' && cf.id == id)" *newline*
859     (if *multiple-value-p*
860         "        return values.apply(this, forcemv(cf.values));"
861         "        return pv.apply(this, forcemv(cf.values));")
862     *newline*
863     "    else" *newline*
864     "        throw cf;" *newline*
865     "}" *newline*))
866
867 (define-compilation throw (id value)
868   (js!selfcall
869     "var values = mv;" *newline*
870     "throw ({"
871     "type: 'catch', "
872     "id: " (ls-compile id) ", "
873     "values: " (ls-compile value t) ", "
874     "message: 'Throw uncatched.'"
875     "})"))
876
877 (defun go-tag-p (x)
878   (or (integerp x) (symbolp x)))
879
880 (defun declare-tagbody-tags (tbidx body)
881   (let* ((go-tag-counter 0)
882          (bindings
883           (mapcar (lambda (label)
884                     (let ((tagidx (integer-to-string (incf go-tag-counter))))
885                       (make-binding :name label :type 'gotag :value (list tbidx tagidx))))
886                   (remove-if-not #'go-tag-p body))))
887     (extend-lexenv bindings *environment* 'gotag)))
888
889 (define-compilation tagbody (&rest body)
890   ;; Ignore the tagbody if it does not contain any go-tag. We do this
891   ;; because 1) it is easy and 2) many built-in forms expand to a
892   ;; implicit tagbody, so we save some space.
893   (unless (some #'go-tag-p body)
894     (return-from tagbody (ls-compile `(progn ,@body nil))))
895   ;; The translation assumes the first form in BODY is a label
896   (unless (go-tag-p (car body))
897     (push (gensym "START") body))
898   ;; Tagbody compilation
899   (let ((branch (gvarname 'branch))
900         (tbidx (gvarname 'tbidx)))
901     (let ((*environment* (declare-tagbody-tags tbidx body))
902           initag)
903       (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
904         (setq initag (second (binding-value b))))
905       (js!selfcall
906         ;; TAGBODY branch to take
907         "var " branch " = " initag ";" *newline*
908         "var " tbidx " = [];" *newline*
909         "tbloop:" *newline*
910         "while (true) {" *newline*
911         (indent "try {" *newline*
912                 (indent (let ((content ""))
913                           (code "switch(" branch "){" *newline*
914                                 "case " initag ":" *newline*
915                                 (dolist (form (cdr body) content)
916                                   (concatf content
917                                     (if (not (go-tag-p form))
918                                         (indent (ls-compile form) ";" *newline*)
919                                         (let ((b (lookup-in-lexenv form *environment* 'gotag)))
920                                           (code "case " (second (binding-value b)) ":" *newline*)))))
921                                 "default:" *newline*
922                                 "    break tbloop;" *newline*
923                                 "}" *newline*)))
924                 "}" *newline*
925                 "catch (jump) {" *newline*
926                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
927                 "        " branch " = jump.label;" *newline*
928                 "    else" *newline*
929                 "        throw(jump);" *newline*
930                 "}" *newline*)
931         "}" *newline*
932         "return " (ls-compile nil) ";" *newline*))))
933
934 (define-compilation go (label)
935   (let ((b (lookup-in-lexenv label *environment* 'gotag))
936         (n (cond
937              ((symbolp label) (symbol-name label))
938              ((integerp label) (integer-to-string label)))))
939     (when (null b)
940       (error "Unknown tag `~S'" label))
941     (js!selfcall
942       "throw ({"
943       "type: 'tagbody', "
944       "id: " (first (binding-value b)) ", "
945       "label: " (second (binding-value b)) ", "
946       "message: 'Attempt to GO to non-existing tag " n "'"
947       "})" *newline*)))
948
949 (define-compilation unwind-protect (form &rest clean-up)
950   (js!selfcall
951     "var ret = " (ls-compile nil) ";" *newline*
952     "try {" *newline*
953     (indent "ret = " (ls-compile form) ";" *newline*)
954     "} finally {" *newline*
955     (indent (ls-compile-block clean-up))
956     "}" *newline*
957     "return ret;" *newline*))
958
959 (define-compilation multiple-value-call (func-form &rest forms)
960   (js!selfcall
961     "var func = " (ls-compile func-form) ";" *newline*
962     "var args = [" (if *multiple-value-p* "values" "pv") ", 0];" *newline*
963     "return "
964     (js!selfcall
965       "var values = mv;" *newline*
966       "var vs;" *newline*
967       (mapconcat (lambda (form)
968                    (code "vs = " (ls-compile form t) ";" *newline*
969                          "if (typeof vs === 'object' && 'multiple-value' in vs)" *newline*
970                          (indent "args = args.concat(vs);" *newline*)
971                          "else" *newline*
972                          (indent "args.push(vs);" *newline*)))
973                  forms)
974       "args[1] = args.length-2;" *newline*
975       "return func.apply(window, args);" *newline*) ";" *newline*))
976
977 (define-compilation multiple-value-prog1 (first-form &rest forms)
978   (js!selfcall
979     "var args = " (ls-compile first-form *multiple-value-p*) ";" *newline*
980     (ls-compile-block forms)
981     "return args;" *newline*))
982
983
984 ;;; Javascript FFI
985
986 (define-compilation %js-vref (var) var)
987
988 (define-compilation %js-vset (var val)
989   (code "(" var " = " (ls-compile val) ")"))
990
991 (define-setf-expander %js-vref (var)
992   (let ((new-value (gensym)))
993     (unless (stringp var)
994       (error "`~S' is not a string." var))
995     (values nil
996             (list var)
997             (list new-value)
998             `(%js-vset ,var ,new-value)
999             `(%js-vref ,var))))
1000
1001
1002 ;;; Backquote implementation.
1003 ;;;
1004 ;;;    Author: Guy L. Steele Jr.     Date: 27 December 1985
1005 ;;;    Tested under Symbolics Common Lisp and Lucid Common Lisp.
1006 ;;;    This software is in the public domain.
1007
1008 ;;;    The following are unique tokens used during processing.
1009 ;;;    They need not be symbols; they need not even be atoms.
1010 (defvar *comma* 'unquote)
1011 (defvar *comma-atsign* 'unquote-splicing)
1012
1013 (defvar *bq-list* (make-symbol "BQ-LIST"))
1014 (defvar *bq-append* (make-symbol "BQ-APPEND"))
1015 (defvar *bq-list** (make-symbol "BQ-LIST*"))
1016 (defvar *bq-nconc* (make-symbol "BQ-NCONC"))
1017 (defvar *bq-clobberable* (make-symbol "BQ-CLOBBERABLE"))
1018 (defvar *bq-quote* (make-symbol "BQ-QUOTE"))
1019 (defvar *bq-quote-nil* (list *bq-quote* nil))
1020
1021 ;;; BACKQUOTE is an ordinary macro (not a read-macro) that processes
1022 ;;; the expression foo, looking for occurrences of #:COMMA,
1023 ;;; #:COMMA-ATSIGN, and #:COMMA-DOT.  It constructs code in strict
1024 ;;; accordance with the rules on pages 349-350 of the first edition
1025 ;;; (pages 528-529 of this second edition).  It then optionally
1026 ;;; applies a code simplifier.
1027
1028 ;;; If the value of *BQ-SIMPLIFY* is non-NIL, then BACKQUOTE
1029 ;;; processing applies the code simplifier.  If the value is NIL,
1030 ;;; then the code resulting from BACKQUOTE is exactly that
1031 ;;; specified by the official rules.
1032 (defparameter *bq-simplify* t)
1033
1034 (defmacro backquote (x)
1035   (bq-completely-process x))
1036
1037 ;;; Backquote processing proceeds in three stages:
1038 ;;;
1039 ;;; (1) BQ-PROCESS applies the rules to remove occurrences of
1040 ;;; #:COMMA, #:COMMA-ATSIGN, and #:COMMA-DOT corresponding to
1041 ;;; this level of BACKQUOTE.  (It also causes embedded calls to
1042 ;;; BACKQUOTE to be expanded so that nesting is properly handled.)
1043 ;;; Code is produced that is expressed in terms of functions
1044 ;;; #:BQ-LIST, #:BQ-APPEND, and #:BQ-CLOBBERABLE.  This is done
1045 ;;; so that the simplifier will simplify only list construction
1046 ;;; functions actually generated by BACKQUOTE and will not involve
1047 ;;; any user code in the simplification.  #:BQ-LIST means LIST,
1048 ;;; #:BQ-APPEND means APPEND, and #:BQ-CLOBBERABLE means IDENTITY
1049 ;;; but indicates places where "%." was used and where NCONC may
1050 ;;; therefore be introduced by the simplifier for efficiency.
1051 ;;;
1052 ;;; (2) BQ-SIMPLIFY, if used, rewrites the code produced by
1053 ;;; BQ-PROCESS to produce equivalent but faster code.  The
1054 ;;; additional functions #:BQ-LIST* and #:BQ-NCONC may be
1055 ;;; introduced into the code.
1056 ;;;
1057 ;;; (3) BQ-REMOVE-TOKENS goes through the code and replaces
1058 ;;; #:BQ-LIST with LIST, #:BQ-APPEND with APPEND, and so on.
1059 ;;; #:BQ-CLOBBERABLE is simply eliminated (a call to it being
1060 ;;; replaced by its argument).  #:BQ-LIST* is replaced by either
1061 ;;; LIST* or CONS (the latter is used in the two-argument case,
1062 ;;; purely to make the resulting code a tad more readable).
1063
1064 (defun bq-completely-process (x)
1065   (let ((raw-result (bq-process x)))
1066     (bq-remove-tokens (if *bq-simplify*
1067                           (bq-simplify raw-result)
1068                           raw-result))))
1069
1070 (defun bq-process (x)
1071   (cond ((atom x)
1072          (list *bq-quote* x))
1073         ((eq (car x) 'backquote)
1074          (bq-process (bq-completely-process (cadr x))))
1075         ((eq (car x) *comma*) (cadr x))
1076         ((eq (car x) *comma-atsign*)
1077          (error ",@~S after `" (cadr x)))
1078         ;; ((eq (car x) *comma-dot*)
1079         ;;  ;; (error ",.~S after `" (cadr x))
1080         ;;  (error "ill-formed"))
1081         (t (do ((p x (cdr p))
1082                 (q '() (cons (bracket (car p)) q)))
1083                ((atom p)
1084                 (cons *bq-append*
1085                       (nreconc q (list (list *bq-quote* p)))))
1086              (when (eq (car p) *comma*)
1087                (unless (null (cddr p))
1088                  (error "Malformed ,~S" p))
1089                (return (cons *bq-append*
1090                              (nreconc q (list (cadr p))))))
1091              (when (eq (car p) *comma-atsign*)
1092                (error "Dotted ,@~S" p))
1093              ;; (when (eq (car p) *comma-dot*)
1094              ;;   ;; (error "Dotted ,.~S" p)
1095              ;;   (error "Dotted"))
1096              ))))
1097
1098 ;;; This implements the bracket operator of the formal rules.
1099 (defun bracket (x)
1100   (cond ((atom x)
1101          (list *bq-list* (bq-process x)))
1102         ((eq (car x) *comma*)
1103          (list *bq-list* (cadr x)))
1104         ((eq (car x) *comma-atsign*)
1105          (cadr x))
1106         ;; ((eq (car x) *comma-dot*)
1107         ;;  (list *bq-clobberable* (cadr x)))
1108         (t (list *bq-list* (bq-process x)))))
1109
1110 ;;; This auxiliary function is like MAPCAR but has two extra
1111 ;;; purposes: (1) it handles dotted lists; (2) it tries to make
1112 ;;; the result share with the argument x as much as possible.
1113 (defun maptree (fn x)
1114   (if (atom x)
1115       (funcall fn x)
1116       (let ((a (funcall fn (car x)))
1117             (d (maptree fn (cdr x))))
1118         (if (and (eql a (car x)) (eql d (cdr x)))
1119             x
1120             (cons a d)))))
1121
1122 ;;; This predicate is true of a form that when read looked
1123 ;;; like %@foo or %.foo.
1124 (defun bq-splicing-frob (x)
1125   (and (consp x)
1126        (or (eq (car x) *comma-atsign*)
1127            ;; (eq (car x) *comma-dot*)
1128            )))
1129
1130 ;;; This predicate is true of a form that when read
1131 ;;; looked like %@foo or %.foo or just plain %foo.
1132 (defun bq-frob (x)
1133   (and (consp x)
1134        (or (eq (car x) *comma*)
1135            (eq (car x) *comma-atsign*)
1136            ;; (eq (car x) *comma-dot*)
1137            )))
1138
1139 ;;; The simplifier essentially looks for calls to #:BQ-APPEND and
1140 ;;; tries to simplify them.  The arguments to #:BQ-APPEND are
1141 ;;; processed from right to left, building up a replacement form.
1142 ;;; At each step a number of special cases are handled that,
1143 ;;; loosely speaking, look like this:
1144 ;;;
1145 ;;;  (APPEND (LIST a b c) foo) => (LIST* a b c foo)
1146 ;;;       provided a, b, c are not splicing frobs
1147 ;;;  (APPEND (LIST* a b c) foo) => (LIST* a b (APPEND c foo))
1148 ;;;       provided a, b, c are not splicing frobs
1149 ;;;  (APPEND (QUOTE (x)) foo) => (LIST* (QUOTE x) foo)
1150 ;;;  (APPEND (CLOBBERABLE x) foo) => (NCONC x foo)
1151 (defun bq-simplify (x)
1152   (if (atom x)
1153       x
1154       (let ((x (if (eq (car x) *bq-quote*)
1155                    x
1156                    (maptree #'bq-simplify x))))
1157         (if (not (eq (car x) *bq-append*))
1158             x
1159             (bq-simplify-args x)))))
1160
1161 (defun bq-simplify-args (x)
1162   (do ((args (reverse (cdr x)) (cdr args))
1163        (result
1164          nil
1165          (cond ((atom (car args))
1166                 (bq-attach-append *bq-append* (car args) result))
1167                ((and (eq (caar args) *bq-list*)
1168                      (notany #'bq-splicing-frob (cdar args)))
1169                 (bq-attach-conses (cdar args) result))
1170                ((and (eq (caar args) *bq-list**)
1171                      (notany #'bq-splicing-frob (cdar args)))
1172                 (bq-attach-conses
1173                   (reverse (cdr (reverse (cdar args))))
1174                   (bq-attach-append *bq-append*
1175                                     (car (last (car args)))
1176                                     result)))
1177                ((and (eq (caar args) *bq-quote*)
1178                      (consp (cadar args))
1179                      (not (bq-frob (cadar args)))
1180                      (null (cddar args)))
1181                 (bq-attach-conses (list (list *bq-quote*
1182                                               (caadar args)))
1183                                   result))
1184                ((eq (caar args) *bq-clobberable*)
1185                 (bq-attach-append *bq-nconc* (cadar args) result))
1186                (t (bq-attach-append *bq-append*
1187                                     (car args)
1188                                     result)))))
1189       ((null args) result)))
1190
1191 (defun null-or-quoted (x)
1192   (or (null x) (and (consp x) (eq (car x) *bq-quote*))))
1193
1194 ;;; When BQ-ATTACH-APPEND is called, the OP should be #:BQ-APPEND
1195 ;;; or #:BQ-NCONC.  This produces a form (op item result) but
1196 ;;; some simplifications are done on the fly:
1197 ;;;
1198 ;;;  (op '(a b c) '(d e f g)) => '(a b c d e f g)
1199 ;;;  (op item 'nil) => item, provided item is not a splicable frob
1200 ;;;  (op item 'nil) => (op item), if item is a splicable frob
1201 ;;;  (op item (op a b c)) => (op item a b c)
1202 (defun bq-attach-append (op item result)
1203   (cond ((and (null-or-quoted item) (null-or-quoted result))
1204          (list *bq-quote* (append (cadr item) (cadr result))))
1205         ((or (null result) (equal result *bq-quote-nil*))
1206          (if (bq-splicing-frob item) (list op item) item))
1207         ((and (consp result) (eq (car result) op))
1208          (list* (car result) item (cdr result)))
1209         (t (list op item result))))
1210
1211 ;;; The effect of BQ-ATTACH-CONSES is to produce a form as if by
1212 ;;; `(LIST* ,@items ,result) but some simplifications are done
1213 ;;; on the fly.
1214 ;;;
1215 ;;;  (LIST* 'a 'b 'c 'd) => '(a b c . d)
1216 ;;;  (LIST* a b c 'nil) => (LIST a b c)
1217 ;;;  (LIST* a b c (LIST* d e f g)) => (LIST* a b c d e f g)
1218 ;;;  (LIST* a b c (LIST d e f g)) => (LIST a b c d e f g)
1219 (defun bq-attach-conses (items result)
1220   (cond ((and (every #'null-or-quoted items)
1221               (null-or-quoted result))
1222          (list *bq-quote*
1223                (append (mapcar #'cadr items) (cadr result))))
1224         ((or (null result) (equal result *bq-quote-nil*))
1225          (cons *bq-list* items))
1226         ((and (consp result)
1227               (or (eq (car result) *bq-list*)
1228                   (eq (car result) *bq-list**)))
1229          (cons (car result) (append items (cdr result))))
1230         (t (cons *bq-list** (append items (list result))))))
1231
1232 ;;; Removes funny tokens and changes (#:BQ-LIST* a b) into
1233 ;;; (CONS a b) instead of (LIST* a b), purely for readability.
1234 (defun bq-remove-tokens (x)
1235   (cond ((eq x *bq-list*) 'list)
1236         ((eq x *bq-append*) 'append)
1237         ((eq x *bq-nconc*) 'nconc)
1238         ((eq x *bq-list**) 'list*)
1239         ((eq x *bq-quote*) 'quote)
1240         ((atom x) x)
1241         ((eq (car x) *bq-clobberable*)
1242          (bq-remove-tokens (cadr x)))
1243         ((and (eq (car x) *bq-list**)
1244               (consp (cddr x))
1245               (null (cdddr x)))
1246          (cons 'cons (maptree #'bq-remove-tokens (cdr x))))
1247         (t (maptree #'bq-remove-tokens x))))
1248
1249 (define-transformation backquote (form)
1250   (bq-completely-process form))
1251
1252
1253 ;;; Primitives
1254
1255 (defvar *builtins* nil)
1256
1257 (defmacro define-raw-builtin (name args &body body)
1258   ;; Creates a new primitive function `name' with parameters args and
1259   ;; @body. The body can access to the local environment through the
1260   ;; variable *ENVIRONMENT*.
1261   `(push (list ',name (lambda ,args (block ,name ,@body)))
1262          *builtins*))
1263
1264 (defmacro define-builtin (name args &body body)
1265   `(define-raw-builtin ,name ,args
1266      (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1267        ,@body)))
1268
1269 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1270 (defmacro type-check (decls &body body)
1271   `(js!selfcall
1272      ,@(mapcar (lambda (decl)
1273                  `(code "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1274                decls)
1275      ,@(mapcar (lambda (decl)
1276                  `(code "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1277                         (indent "throw 'The value ' + "
1278                                 ,(first decl)
1279                                 " + ' is not a type "
1280                                 ,(second decl)
1281                                 ".';"
1282                                 *newline*)))
1283                decls)
1284      (code "return " (progn ,@body) ";" *newline*)))
1285
1286 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
1287 ;;; a variable which holds a list of forms. It will compile them and
1288 ;;; store the result in some Javascript variables. BODY is evaluated
1289 ;;; with ARGS bound to the list of these variables to generate the
1290 ;;; code which performs the transformation on these variables.
1291
1292 (defun variable-arity-call (args function)
1293   (unless (consp args)
1294     (error "ARGS must be a non-empty list"))
1295   (let ((counter 0)
1296         (fargs '())
1297         (prelude ""))
1298     (dolist (x args)
1299       (cond
1300         ((floatp x) (push (float-to-string x) fargs))
1301         ((numberp x) (push (integer-to-string x) fargs))
1302         (t (let ((v (code "x" (incf counter))))
1303              (push v fargs)
1304              (concatf prelude
1305                (code "var " v " = " (ls-compile x) ";" *newline*
1306                      "if (typeof " v " !== 'number') throw 'Not a number!';"
1307                      *newline*))))))
1308     (js!selfcall prelude (funcall function (reverse fargs)))))
1309
1310
1311 (defmacro variable-arity (args &body body)
1312   (unless (symbolp args)
1313     (error "`~S' is not a symbol." args))
1314   `(variable-arity-call ,args
1315                         (lambda (,args)
1316                           (code "return " ,@body ";" *newline*))))
1317
1318 (defun num-op-num (x op y)
1319   (type-check (("x" "number" x) ("y" "number" y))
1320     (code "x" op "y")))
1321
1322 (define-raw-builtin + (&rest numbers)
1323   (if (null numbers)
1324       "0"
1325       (variable-arity numbers
1326         (join numbers "+"))))
1327
1328 (define-raw-builtin - (x &rest others)
1329   (let ((args (cons x others)))
1330     (variable-arity args
1331       (if (null others)
1332           (concat "-" (car args))
1333           (join args "-")))))
1334
1335 (define-raw-builtin * (&rest numbers)
1336   (if (null numbers)
1337       "1"
1338       (variable-arity numbers
1339         (join numbers "*"))))
1340
1341 (define-raw-builtin / (x &rest others)
1342   (let ((args (cons x others)))
1343     (variable-arity args
1344       (if (null others)
1345           (concat "1 /" (car args))
1346           (join args "/")))))
1347
1348 (define-builtin mod (x y) (num-op-num x "%" y))
1349
1350
1351 (defun comparison-conjuntion (vars op)
1352   (cond
1353     ((null (cdr vars))
1354      "true")
1355     ((null (cddr vars))
1356      (concat (car vars) op (cadr vars)))
1357     (t
1358      (concat (car vars) op (cadr vars)
1359              " && "
1360              (comparison-conjuntion (cdr vars) op)))))
1361
1362 (defmacro define-builtin-comparison (op sym)
1363   `(define-raw-builtin ,op (x &rest args)
1364      (let ((args (cons x args)))
1365        (variable-arity args
1366          (js!bool (comparison-conjuntion args ,sym))))))
1367
1368 (define-builtin-comparison > ">")
1369 (define-builtin-comparison < "<")
1370 (define-builtin-comparison >= ">=")
1371 (define-builtin-comparison <= "<=")
1372 (define-builtin-comparison = "==")
1373
1374 (define-builtin numberp (x)
1375   (js!bool (code "(typeof (" x ") == \"number\")")))
1376
1377 (define-builtin floor (x)
1378   (type-check (("x" "number" x))
1379     "Math.floor(x)"))
1380
1381 (define-builtin expt (x y)
1382   (type-check (("x" "number" x)
1383                ("y" "number" y))
1384     "Math.pow(x, y)"))
1385
1386 (define-builtin float-to-string (x)
1387   (type-check (("x" "number" x))
1388     "make_lisp_string(x.toString())"))
1389
1390 (define-builtin cons (x y)
1391   (code "({car: " x ", cdr: " y "})"))
1392
1393 (define-builtin consp (x)
1394   (js!bool
1395    (js!selfcall
1396      "var tmp = " x ";" *newline*
1397      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1398
1399 (define-builtin car (x)
1400   (js!selfcall
1401     "var tmp = " x ";" *newline*
1402     "return tmp === " (ls-compile nil)
1403     "? " (ls-compile nil)
1404     ": tmp.car;" *newline*))
1405
1406 (define-builtin cdr (x)
1407   (js!selfcall
1408     "var tmp = " x ";" *newline*
1409     "return tmp === " (ls-compile nil) "? "
1410     (ls-compile nil)
1411     ": tmp.cdr;" *newline*))
1412
1413 (define-builtin rplaca (x new)
1414   (type-check (("x" "object" x))
1415     (code "(x.car = " new ", x)")))
1416
1417 (define-builtin rplacd (x new)
1418   (type-check (("x" "object" x))
1419     (code "(x.cdr = " new ", x)")))
1420
1421 (define-builtin symbolp (x)
1422   (js!bool
1423    (js!selfcall
1424      "var tmp = " x ";" *newline*
1425      "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1426
1427 (define-builtin make-symbol (name)
1428   (code "({name: " name "})"))
1429
1430 (define-builtin symbol-name (x)
1431   (code "(" x ").name"))
1432
1433 (define-builtin set (symbol value)
1434   (code "(" symbol ").value = " value))
1435
1436 (define-builtin fset (symbol value)
1437   (code "(" symbol ").fvalue = " value))
1438
1439 (define-builtin boundp (x)
1440   (js!bool (code "(" x ".value !== undefined)")))
1441
1442 (define-builtin symbol-value (x)
1443   (js!selfcall
1444     "var symbol = " x ";" *newline*
1445     "var value = symbol.value;" *newline*
1446     "if (value === undefined) throw \"Variable `\" + xstring(symbol.name) + \"' is unbound.\";" *newline*
1447     "return value;" *newline*))
1448
1449 (define-builtin symbol-function (x)
1450   (js!selfcall
1451     "var symbol = " x ";" *newline*
1452     "var func = symbol.fvalue;" *newline*
1453     "if (func === undefined) throw \"Function `\" + xstring(symbol.name) + \"' is undefined.\";" *newline*
1454     "return func;" *newline*))
1455
1456 (define-builtin symbol-plist (x)
1457   (code "((" x ").plist || " (ls-compile nil) ")"))
1458
1459 (define-builtin lambda-code (x)
1460   (code "make_lisp_string((" x ").toString())"))
1461
1462 (define-builtin eq (x y)
1463   (js!bool (code "(" x " === " y ")")))
1464
1465 (define-builtin char-code (x)
1466   (type-check (("x" "string" x))
1467     "x.charCodeAt(0)"))
1468
1469 (define-builtin code-char (x)
1470   (type-check (("x" "number" x))
1471     "String.fromCharCode(x)"))
1472
1473 (define-builtin characterp (x)
1474   (js!bool
1475    (js!selfcall
1476      "var x = " x ";" *newline*
1477      "return (typeof(" x ") == \"string\") && x.length == 1;")))
1478
1479 (define-builtin char-to-string (x)
1480   (js!selfcall
1481     "var r = [" x "];" *newline*
1482     "r.type = 'character';"
1483     "return r"))
1484
1485 (define-builtin stringp (x)
1486   (js!bool
1487    (js!selfcall
1488      "var x = " x ";" *newline*
1489      "return typeof(x) == 'object' && 'length' in x && x.type == 'character';")))
1490
1491 (define-builtin string-upcase (x)
1492   (code "make_lisp_string(xstring(" x ").toUpperCase())"))
1493
1494 (define-builtin string-length (x)
1495   (code x ".length"))
1496
1497 (define-raw-builtin slice (vector a &optional b)
1498   (js!selfcall
1499     "var vector = " (ls-compile vector) ";" *newline*
1500     "var a = " (ls-compile a) ";" *newline*
1501     "var b;" *newline*
1502     (when b (code "b = " (ls-compile b) ";" *newline*))
1503     "return vector.slice(a,b);" *newline*))
1504
1505 (define-builtin char (string index)
1506   (code string "[" index "]"))
1507
1508 (define-builtin concat-two (string1 string2)
1509   (js!selfcall
1510     "var r = " string1 ".concat(" string2 ");" *newline*
1511     "r.type = 'character';"
1512     "return r;" *newline*))
1513
1514 (define-raw-builtin funcall (func &rest args)
1515   (js!selfcall
1516     "var f = " (ls-compile func) ";" *newline*
1517     "return (typeof f === 'function'? f: f.fvalue)("
1518     (join (list* (if *multiple-value-p* "values" "pv")
1519                  (integer-to-string (length args))
1520                  (mapcar #'ls-compile args))
1521           ", ")
1522     ")"))
1523
1524 (define-raw-builtin apply (func &rest args)
1525   (if (null args)
1526       (code "(" (ls-compile func) ")()")
1527       (let ((args (butlast args))
1528             (last (car (last args))))
1529         (js!selfcall
1530           "var f = " (ls-compile func) ";" *newline*
1531           "var args = [" (join (list* (if *multiple-value-p* "values" "pv")
1532                                       (integer-to-string (length args))
1533                                       (mapcar #'ls-compile args))
1534                                ", ")
1535           "];" *newline*
1536           "var tail = (" (ls-compile last) ");" *newline*
1537           "while (tail != " (ls-compile nil) "){" *newline*
1538           "    args.push(tail.car);" *newline*
1539           "    args[1] += 1;" *newline*
1540           "    tail = tail.cdr;" *newline*
1541           "}" *newline*
1542           "return (typeof f === 'function'? f : f.fvalue).apply(this, args);" *newline*))))
1543
1544 (define-builtin js-eval (string)
1545   (if *multiple-value-p*
1546       (js!selfcall
1547         "var v = globalEval(xstring(" string "));" *newline*
1548         "return values.apply(this, forcemv(v));" *newline*)
1549       (code "globalEval(xstring(" string ")")))
1550
1551 (define-builtin %throw (string)
1552   (js!selfcall "throw " string ";" *newline*))
1553
1554 (define-builtin new () "{}")
1555
1556 (define-builtin objectp (x)
1557   (js!bool (code "(typeof (" x ") === 'object')")))
1558
1559 (define-builtin oget (object key)
1560   (js!selfcall
1561     "var tmp = " "(" object ")[xstring(" key ")];" *newline*
1562     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1563
1564 (define-builtin oset (object key value)
1565   (code "((" object ")[xstring(" key ")] = " value ")"))
1566
1567 (define-builtin in (key object)
1568   (js!bool (code "(xstring(" key ") in (" object ")")))
1569
1570 (define-builtin functionp (x)
1571   (js!bool (code "(typeof " x " == 'function')")))
1572
1573 (define-builtin write-string (x)
1574   (code "lisp.write(xstring(" x "))"))
1575
1576 (define-builtin make-array (n)
1577   (js!selfcall
1578     "var r = [];" *newline*
1579     "for (var i = 0; i < " n "; i++)" *newline*
1580     (indent "r.push(" (ls-compile nil) ");" *newline*)
1581     "return r;" *newline*))
1582
1583 (define-builtin arrayp (x)
1584   (js!bool
1585    (js!selfcall
1586      "var x = " x ";" *newline*
1587      "return typeof x === 'object' && 'length' in x;")))
1588
1589 (define-builtin aref (array n)
1590   (js!selfcall
1591     "var x = " "(" array ")[" n "];" *newline*
1592     "if (x === undefined) throw 'Out of range';" *newline*
1593     "return x;" *newline*))
1594
1595 (define-builtin aset (array n value)
1596   (js!selfcall
1597     "var x = " array ";" *newline*
1598     "var i = " n ";" *newline*
1599     "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
1600     "return x[i] = " value ";" *newline*))
1601
1602 (define-builtin get-internal-real-time ()
1603   "(new Date()).getTime()")
1604
1605 (define-builtin values-array (array)
1606   (if *multiple-value-p*
1607       (code "values.apply(this, " array ")")
1608       (code "pv.apply(this, " array ")")))
1609
1610 (define-raw-builtin values (&rest args)
1611   (if *multiple-value-p*
1612       (code "values(" (join (mapcar #'ls-compile args) ", ") ")")
1613       (code "pv(" (join (mapcar #'ls-compile args) ", ") ")")))
1614
1615 ;; Receives the JS function as first argument as a literal string. The
1616 ;; second argument is compiled and should evaluate to a vector of
1617 ;; values to apply to the the function. The result returned.
1618 (define-builtin %js-call (fun args)
1619   (code fun ".apply(this, " args ")"))
1620
1621 (defun macro (x)
1622   (and (symbolp x)
1623        (let ((b (lookup-in-lexenv x *environment* 'function)))
1624          (if (and b (eq (binding-type b) 'macro))
1625              b
1626              nil))))
1627
1628 #+common-lisp
1629 (defvar *macroexpander-cache*
1630   (make-hash-table :test #'eq))
1631
1632 (defun ls-macroexpand-1 (form)
1633   (cond
1634     ((symbolp form)
1635      (let ((b (lookup-in-lexenv form *environment* 'variable)))
1636        (if (and b (eq (binding-type b) 'macro))
1637            (values (binding-value b) t)
1638            (values form nil))))
1639     ((consp form)
1640      (let ((macro-binding (macro (car form))))
1641        (if macro-binding
1642            (let ((expander (binding-value macro-binding)))
1643              (cond
1644                #+common-lisp
1645                ((gethash macro-binding *macroexpander-cache*)
1646                 (setq expander (gethash macro-binding *macroexpander-cache*)))
1647                ((listp expander)
1648                 (let ((compiled (eval expander)))
1649                   ;; The list representation are useful while
1650                   ;; bootstrapping, as we can dump the definition of the
1651                   ;; macros easily, but they are slow because we have to
1652                   ;; evaluate them and compile them now and again. So, let
1653                   ;; us replace the list representation version of the
1654                   ;; function with the compiled one.
1655                   ;;
1656                   #+jscl (setf (binding-value macro-binding) compiled)
1657                   #+common-lisp (setf (gethash macro-binding *macroexpander-cache*) compiled)
1658                   (setq expander compiled))))
1659              (values (apply expander (cdr form)) t))
1660            (values form nil))))
1661     (t
1662      (values form nil))))
1663
1664 (defun compile-funcall (function args)
1665   (let* ((values-funcs (if *multiple-value-p* "values" "pv"))
1666          (arglist (concat "(" (join (list* values-funcs
1667                                            (integer-to-string (length args))
1668                                            (mapcar #'ls-compile args)) ", ") ")")))
1669     (unless (or (symbolp function)
1670                 (and (consp function)
1671                      (eq (car function) 'lambda)))
1672       (error "Bad function designator `~S'" function))
1673     (cond
1674       ((translate-function function)
1675        (concat (translate-function function) arglist))
1676       ((and (symbolp function)
1677             #+jscl (eq (symbol-package function) (find-package "COMMON-LISP"))
1678             #+common-lisp t)
1679        (code (ls-compile `',function) ".fvalue" arglist))
1680       (t
1681        (code (ls-compile `#',function) arglist)))))
1682
1683 (defun ls-compile-block (sexps &optional return-last-p)
1684   (if return-last-p
1685       (code (ls-compile-block (butlast sexps))
1686             "return " (ls-compile (car (last sexps)) *multiple-value-p*) ";")
1687       (join-trailing
1688        (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
1689        (concat ";" *newline*))))
1690
1691 (defun ls-compile (sexp &optional multiple-value-p)
1692   (multiple-value-bind (sexp expandedp) (ls-macroexpand-1 sexp)
1693     (when expandedp
1694       (return-from ls-compile (ls-compile sexp multiple-value-p)))
1695     ;; The expression has been macroexpanded. Now compile it!
1696     (let ((*multiple-value-p* multiple-value-p))
1697       (cond
1698         ((symbolp sexp)
1699          (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1700            (cond
1701              ((and b (not (member 'special (binding-declarations b))))
1702               (binding-value b))
1703              ((or (keywordp sexp)
1704                   (and b (member 'constant (binding-declarations b))))
1705               (code (ls-compile `',sexp) ".value"))
1706              (t
1707               (ls-compile `(symbol-value ',sexp))))))
1708         ((or (integerp sexp) (floatp sexp) (characterp sexp) (stringp sexp) (arrayp sexp))
1709          (literal sexp))
1710         ((listp sexp)
1711          (let ((name (car sexp))
1712                (args (cdr sexp)))
1713            (cond
1714              ;; Special forms
1715              ((assoc name *compilations*)
1716               (let ((comp (second (assoc name *compilations*))))
1717                 (apply comp args)))
1718              ;; Built-in functions
1719              ((and (assoc name *builtins*)
1720                    (not (claimp name 'function 'notinline)))
1721               (let ((comp (second (assoc name *builtins*))))
1722                 (apply comp args)))
1723              (t
1724               (compile-funcall name args)))))
1725         (t
1726          (error "How should I compile `~S'?" sexp))))))
1727
1728
1729 (defvar *compile-print-toplevels* nil)
1730
1731 (defun truncate-string (string &optional (width 60))
1732   (let ((n (or (position #\newline string)
1733                (min width (length string)))))
1734     (subseq string 0 n)))
1735
1736 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
1737   (let ((*toplevel-compilations* nil))
1738     (cond
1739       ((and (consp sexp) (eq (car sexp) 'progn))
1740        (let ((subs (mapcar (lambda (s)
1741                              (ls-compile-toplevel s t))
1742                            (cdr sexp))))
1743          (join (remove-if #'null-or-empty-p subs))))
1744       (t
1745        (when *compile-print-toplevels*
1746          (let ((form-string (prin1-to-string sexp)))
1747            (format t "Compiling ~a..." (truncate-string form-string))))
1748        (let ((code (ls-compile sexp multiple-value-p)))
1749          (code (join-trailing (get-toplevel-compilations)
1750                               (code ";" *newline*))
1751                (when code
1752                  (code code ";" *newline*))))))))