Merge pull request #68 from 6502/case-otherwise
[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."))))
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 accessor."))))
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 ,(concat "The object is not a type " 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"))
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 ' + 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 paris 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: \"" (escape-string (symbol-name symbol))
568               "\", 'package': '" (package-name package) "'}")
569         (code "{name: \"" (escape-string (symbol-name symbol)) "\"}")))
570   #+jscl
571   (let ((package (symbol-package symbol)))
572     (if (null package)
573         (code "{name: \"" (escape-string (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 literal (sexp &optional recursive)
591   (cond
592     ((integerp sexp) (integer-to-string sexp))
593     ((floatp sexp) (float-to-string sexp))
594     ((stringp sexp) (code "\"" (escape-string sexp) "\""))
595     (t
596      (or (cdr (assoc sexp *literal-table*))
597          (let ((dumped (typecase sexp
598                          (symbol (dump-symbol sexp))
599                          (cons (dump-cons sexp))
600                          (array (dump-array sexp)))))
601            (if (and recursive (not (symbolp sexp)))
602                dumped
603                (let ((jsvar (genlit)))
604                  (push (cons sexp jsvar) *literal-table*)
605                  (toplevel-compilation (code "var " jsvar " = " dumped))
606                  jsvar)))))))
607
608 (define-compilation quote (sexp)
609   (literal sexp))
610
611 (define-compilation %while (pred &rest body)
612   (js!selfcall
613     "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
614     (indent (ls-compile-block body))
615     "}"
616     "return " (ls-compile nil) ";" *newline*))
617
618 (define-compilation function (x)
619   (cond
620     ((and (listp x) (eq (car x) 'lambda))
621      (compile-lambda (cadr x) (cddr x)))
622     ((and (listp x) (eq (car x) 'named-lambda))
623      ;; TODO: destructuring-bind now! Do error checking manually is
624      ;; very annoying.
625      (let ((name (cadr x))
626            (ll (caddr x))
627            (body (cdddr x)))
628        (compile-lambda ll body
629                        :name (symbol-name name)
630                        :block name)))
631     ((symbolp x)
632      (let ((b (lookup-in-lexenv x *environment* 'function)))
633        (if b
634            (binding-value b)
635            (ls-compile `(symbol-function ',x)))))))
636
637
638 (defun make-function-binding (fname)
639   (make-binding :name fname :type 'function :value (gvarname fname)))
640
641 (defun compile-function-definition (list)
642   (compile-lambda (car list) (cdr list)))
643
644 (defun translate-function (name)
645   (let ((b (lookup-in-lexenv name *environment* 'function)))
646     (and b (binding-value b))))
647
648 (define-compilation flet (definitions &rest body)
649   (let* ((fnames (mapcar #'car definitions))
650          (fbody  (mapcar #'cdr definitions))
651          (cfuncs (mapcar #'compile-function-definition fbody))
652          (*environment*
653           (extend-lexenv (mapcar #'make-function-binding fnames)
654                          *environment*
655                          'function)))
656     (code "(function("
657           (join (mapcar #'translate-function fnames) ",")
658           "){" *newline*
659           (let ((body (ls-compile-block body t)))
660             (indent body))
661           "})(" (join cfuncs ",") ")")))
662
663 (define-compilation labels (definitions &rest body)
664   (let* ((fnames (mapcar #'car definitions))
665          (*environment*
666           (extend-lexenv (mapcar #'make-function-binding fnames)
667                          *environment*
668                          'function)))
669     (js!selfcall
670       (mapconcat (lambda (func)
671                    (code "var " (translate-function (car func))
672                          " = " (compile-lambda (cadr func) (cddr func))
673                          ";" *newline*))
674                  definitions)
675       (ls-compile-block body t))))
676
677
678 (defvar *compiling-file* nil)
679 (define-compilation eval-when-compile (&rest body)
680   (if *compiling-file*
681       (progn
682         (eval (cons 'progn body))
683         nil)
684       (ls-compile `(progn ,@body))))
685
686 (defmacro define-transformation (name args form)
687   `(define-compilation ,name ,args
688      (ls-compile ,form)))
689
690 (define-compilation progn (&rest body)
691   (if (null (cdr body))
692       (ls-compile (car body) *multiple-value-p*)
693       (js!selfcall (ls-compile-block body t))))
694
695 (defun special-variable-p (x)
696   (and (claimp x 'variable 'special) t))
697
698 ;;; Wrap CODE to restore the symbol values of the dynamic
699 ;;; bindings. BINDINGS is a list of pairs of the form
700 ;;; (SYMBOL . PLACE),  where PLACE is a Javascript variable
701 ;;; name to initialize the symbol value and where to stored
702 ;;; the old value.
703 (defun let-binding-wrapper (bindings body)
704   (when (null bindings)
705     (return-from let-binding-wrapper body))
706   (code
707    "try {" *newline*
708    (indent "var tmp;" *newline*
709            (mapconcat
710             (lambda (b)
711               (let ((s (ls-compile `(quote ,(car b)))))
712                 (code "tmp = " s ".value;" *newline*
713                       s ".value = " (cdr b) ";" *newline*
714                       (cdr b) " = tmp;" *newline*)))
715             bindings)
716            body *newline*)
717    "}" *newline*
718    "finally {"  *newline*
719    (indent
720     (mapconcat (lambda (b)
721                  (let ((s (ls-compile `(quote ,(car b)))))
722                    (code s ".value" " = " (cdr b) ";" *newline*)))
723                bindings))
724    "}" *newline*))
725
726 (define-compilation let (bindings &rest body)
727   (let* ((bindings (mapcar #'ensure-list bindings))
728          (variables (mapcar #'first bindings))
729          (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
730          (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
731          (dynamic-bindings))
732     (code "(function("
733           (join (mapcar (lambda (x)
734                           (if (special-variable-p x)
735                               (let ((v (gvarname x)))
736                                 (push (cons x v) dynamic-bindings)
737                                 v)
738                               (translate-variable x)))
739                         variables)
740                 ",")
741           "){" *newline*
742           (let ((body (ls-compile-block body t)))
743             (indent (let-binding-wrapper dynamic-bindings body)))
744           "})(" (join cvalues ",") ")")))
745
746
747 ;;; Return the code to initialize BINDING, and push it extending the
748 ;;; current lexical environment if the variable is not special.
749 (defun let*-initialize-value (binding)
750   (let ((var (first binding))
751         (value (second binding)))
752     (if (special-variable-p var)
753         (code (ls-compile `(setq ,var ,value)) ";" *newline*)
754         (let* ((v (gvarname var))
755                (b (make-binding :name var :type 'variable :value v)))
756           (prog1 (code "var " v " = " (ls-compile value) ";" *newline*)
757             (push-to-lexenv b *environment* 'variable))))))
758
759 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
760 ;;; DOES NOT generate code to initialize the value of the symbols,
761 ;;; unlike let-binding-wrapper.
762 (defun let*-binding-wrapper (symbols body)
763   (when (null symbols)
764     (return-from let*-binding-wrapper body))
765   (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
766                        (remove-if-not #'special-variable-p symbols))))
767     (code
768      "try {" *newline*
769      (indent
770       (mapconcat (lambda (b)
771                    (let ((s (ls-compile `(quote ,(car b)))))
772                      (code "var " (cdr b) " = " s ".value;" *newline*)))
773                  store)
774       body)
775      "}" *newline*
776      "finally {" *newline*
777      (indent
778       (mapconcat (lambda (b)
779                    (let ((s (ls-compile `(quote ,(car b)))))
780                      (code s ".value" " = " (cdr b) ";" *newline*)))
781                  store))
782      "}" *newline*)))
783
784 (define-compilation let* (bindings &rest body)
785   (let ((bindings (mapcar #'ensure-list bindings))
786         (*environment* (copy-lexenv *environment*)))
787     (js!selfcall
788       (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
789             (body (concat (mapconcat #'let*-initialize-value bindings)
790                           (ls-compile-block body t))))
791         (let*-binding-wrapper specials body)))))
792
793
794 (define-compilation block (name &rest body)
795   ;; We use Javascript exceptions to implement non local control
796   ;; transfer. Exceptions has dynamic scoping, so we use a uniquely
797   ;; generated object to identify the block. The instance of a empty
798   ;; array is used to distinguish between nested dynamic Javascript
799   ;; exceptions. See https://github.com/davazp/jscl/issues/64 for
800   ;; futher details.
801   (let* ((idvar (gvarname name))
802          (b (make-binding :name name :type 'block :value idvar)))
803     (when *multiple-value-p*
804       (push 'multiple-value (binding-declarations b)))
805     (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
806            (cbody (ls-compile-block body t)))
807       (if (member 'used (binding-declarations b))
808           (js!selfcall
809             "try {" *newline*
810             "var " idvar " = [];" *newline*
811             (indent cbody)
812             "}" *newline*
813             "catch (cf){" *newline*
814             "    if (cf.type == 'block' && cf.id == " idvar ")" *newline*
815             (if *multiple-value-p*
816                 "        return values.apply(this, forcemv(cf.values));"
817                 "        return cf.values;")
818             *newline*
819             "    else" *newline*
820             "        throw cf;" *newline*
821             "}" *newline*)
822           (js!selfcall cbody)))))
823
824 (define-compilation return-from (name &optional value)
825   (let* ((b (lookup-in-lexenv name *environment* 'block))
826          (multiple-value-p (member 'multiple-value (binding-declarations b))))
827     (when (null b)
828       (error (concat "Unknown block `" (symbol-name name) "'.")))
829     (push 'used (binding-declarations b))
830     ;; The binding value is the name of a variable, whose value is the
831     ;; unique identifier of the block as exception. We can't use the
832     ;; variable name itself, because it could not to be unique, so we
833     ;; capture it in a closure.
834     (js!selfcall
835       (when multiple-value-p (code "var values = mv;" *newline*))
836       "throw ({"
837       "type: 'block', "
838       "id: " (binding-value b) ", "
839       "values: " (ls-compile value multiple-value-p) ", "
840       "message: 'Return from unknown block " (symbol-name name) ".'"
841       "})")))
842
843 (define-compilation catch (id &rest body)
844   (js!selfcall
845     "var id = " (ls-compile id) ";" *newline*
846     "try {" *newline*
847     (indent (ls-compile-block body t)) *newline*
848     "}" *newline*
849     "catch (cf){" *newline*
850     "    if (cf.type == 'catch' && cf.id == id)" *newline*
851     (if *multiple-value-p*
852         "        return values.apply(this, forcemv(cf.values));"
853         "        return pv.apply(this, forcemv(cf.values));")
854     *newline*
855     "    else" *newline*
856     "        throw cf;" *newline*
857     "}" *newline*))
858
859 (define-compilation throw (id value)
860   (js!selfcall
861     "var values = mv;" *newline*
862     "throw ({"
863     "type: 'catch', "
864     "id: " (ls-compile id) ", "
865     "values: " (ls-compile value t) ", "
866     "message: 'Throw uncatched.'"
867     "})"))
868
869 (defun go-tag-p (x)
870   (or (integerp x) (symbolp x)))
871
872 (defun declare-tagbody-tags (tbidx body)
873   (let* ((go-tag-counter 0)
874          (bindings
875           (mapcar (lambda (label)
876                     (let ((tagidx (integer-to-string (incf go-tag-counter))))
877                       (make-binding :name label :type 'gotag :value (list tbidx tagidx))))
878                   (remove-if-not #'go-tag-p body))))
879     (extend-lexenv bindings *environment* 'gotag)))
880
881 (define-compilation tagbody (&rest body)
882   ;; Ignore the tagbody if it does not contain any go-tag. We do this
883   ;; because 1) it is easy and 2) many built-in forms expand to a
884   ;; implicit tagbody, so we save some space.
885   (unless (some #'go-tag-p body)
886     (return-from tagbody (ls-compile `(progn ,@body nil))))
887   ;; The translation assumes the first form in BODY is a label
888   (unless (go-tag-p (car body))
889     (push (gensym "START") body))
890   ;; Tagbody compilation
891   (let ((branch (gvarname 'branch))
892         (tbidx (gvarname 'tbidx)))
893     (let ((*environment* (declare-tagbody-tags tbidx body))
894           initag)
895       (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
896         (setq initag (second (binding-value b))))
897       (js!selfcall
898         ;; TAGBODY branch to take
899         "var " branch " = " initag ";" *newline*
900         "var " tbidx " = [];" *newline*
901         "tbloop:" *newline*
902         "while (true) {" *newline*
903         (indent "try {" *newline*
904                 (indent (let ((content ""))
905                           (code "switch(" branch "){" *newline*
906                                 "case " initag ":" *newline*
907                                 (dolist (form (cdr body) content)
908                                   (concatf content
909                                     (if (not (go-tag-p form))
910                                         (indent (ls-compile form) ";" *newline*)
911                                         (let ((b (lookup-in-lexenv form *environment* 'gotag)))
912                                           (code "case " (second (binding-value b)) ":" *newline*)))))
913                                 "default:" *newline*
914                                 "    break tbloop;" *newline*
915                                 "}" *newline*)))
916                 "}" *newline*
917                 "catch (jump) {" *newline*
918                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
919                 "        " branch " = jump.label;" *newline*
920                 "    else" *newline*
921                 "        throw(jump);" *newline*
922                 "}" *newline*)
923         "}" *newline*
924         "return " (ls-compile nil) ";" *newline*))))
925
926 (define-compilation go (label)
927   (let ((b (lookup-in-lexenv label *environment* 'gotag))
928         (n (cond
929              ((symbolp label) (symbol-name label))
930              ((integerp label) (integer-to-string label)))))
931     (when (null b)
932       (error (concat "Unknown tag `" n "'.")))
933     (js!selfcall
934       "throw ({"
935       "type: 'tagbody', "
936       "id: " (first (binding-value b)) ", "
937       "label: " (second (binding-value b)) ", "
938       "message: 'Attempt to GO to non-existing tag " n "'"
939       "})" *newline*)))
940
941 (define-compilation unwind-protect (form &rest clean-up)
942   (js!selfcall
943     "var ret = " (ls-compile nil) ";" *newline*
944     "try {" *newline*
945     (indent "ret = " (ls-compile form) ";" *newline*)
946     "} finally {" *newline*
947     (indent (ls-compile-block clean-up))
948     "}" *newline*
949     "return ret;" *newline*))
950
951 (define-compilation multiple-value-call (func-form &rest forms)
952   (js!selfcall
953     "var func = " (ls-compile func-form) ";" *newline*
954     "var args = [" (if *multiple-value-p* "values" "pv") ", 0];" *newline*
955     "return "
956     (js!selfcall
957       "var values = mv;" *newline*
958       "var vs;" *newline*
959       (mapconcat (lambda (form)
960                    (code "vs = " (ls-compile form t) ";" *newline*
961                          "if (typeof vs === 'object' && 'multiple-value' in vs)" *newline*
962                          (indent "args = args.concat(vs);" *newline*)
963                          "else" *newline*
964                          (indent "args.push(vs);" *newline*)))
965                  forms)
966       "args[1] = args.length-2;" *newline*
967       "return func.apply(window, args);" *newline*) ";" *newline*))
968
969 (define-compilation multiple-value-prog1 (first-form &rest forms)
970   (js!selfcall
971     "var args = " (ls-compile first-form *multiple-value-p*) ";" *newline*
972     (ls-compile-block forms)
973     "return args;" *newline*))
974
975
976 ;;; Javascript FFI
977
978 (define-compilation %js-vref (var) var)
979
980 (define-compilation %js-vset (var val)
981   (code "(" var " = " (ls-compile val) ")"))
982
983 (define-setf-expander %js-vref (var)
984   (let ((new-value (gensym)))
985     (unless (stringp var)
986       (error "a string was expected"))
987     (values nil
988             (list var)
989             (list new-value)
990             `(%js-vset ,var ,new-value)
991             `(%js-vref ,var))))
992
993
994 ;;; Backquote implementation.
995 ;;;
996 ;;;    Author: Guy L. Steele Jr.     Date: 27 December 1985
997 ;;;    Tested under Symbolics Common Lisp and Lucid Common Lisp.
998 ;;;    This software is in the public domain.
999
1000 ;;;    The following are unique tokens used during processing.
1001 ;;;    They need not be symbols; they need not even be atoms.
1002 (defvar *comma* 'unquote)
1003 (defvar *comma-atsign* 'unquote-splicing)
1004
1005 (defvar *bq-list* (make-symbol "BQ-LIST"))
1006 (defvar *bq-append* (make-symbol "BQ-APPEND"))
1007 (defvar *bq-list** (make-symbol "BQ-LIST*"))
1008 (defvar *bq-nconc* (make-symbol "BQ-NCONC"))
1009 (defvar *bq-clobberable* (make-symbol "BQ-CLOBBERABLE"))
1010 (defvar *bq-quote* (make-symbol "BQ-QUOTE"))
1011 (defvar *bq-quote-nil* (list *bq-quote* nil))
1012
1013 ;;; BACKQUOTE is an ordinary macro (not a read-macro) that processes
1014 ;;; the expression foo, looking for occurrences of #:COMMA,
1015 ;;; #:COMMA-ATSIGN, and #:COMMA-DOT.  It constructs code in strict
1016 ;;; accordance with the rules on pages 349-350 of the first edition
1017 ;;; (pages 528-529 of this second edition).  It then optionally
1018 ;;; applies a code simplifier.
1019
1020 ;;; If the value of *BQ-SIMPLIFY* is non-NIL, then BACKQUOTE
1021 ;;; processing applies the code simplifier.  If the value is NIL,
1022 ;;; then the code resulting from BACKQUOTE is exactly that
1023 ;;; specified by the official rules.
1024 (defparameter *bq-simplify* t)
1025
1026 (defmacro backquote (x)
1027   (bq-completely-process x))
1028
1029 ;;; Backquote processing proceeds in three stages:
1030 ;;;
1031 ;;; (1) BQ-PROCESS applies the rules to remove occurrences of
1032 ;;; #:COMMA, #:COMMA-ATSIGN, and #:COMMA-DOT corresponding to
1033 ;;; this level of BACKQUOTE.  (It also causes embedded calls to
1034 ;;; BACKQUOTE to be expanded so that nesting is properly handled.)
1035 ;;; Code is produced that is expressed in terms of functions
1036 ;;; #:BQ-LIST, #:BQ-APPEND, and #:BQ-CLOBBERABLE.  This is done
1037 ;;; so that the simplifier will simplify only list construction
1038 ;;; functions actually generated by BACKQUOTE and will not involve
1039 ;;; any user code in the simplification.  #:BQ-LIST means LIST,
1040 ;;; #:BQ-APPEND means APPEND, and #:BQ-CLOBBERABLE means IDENTITY
1041 ;;; but indicates places where "%." was used and where NCONC may
1042 ;;; therefore be introduced by the simplifier for efficiency.
1043 ;;;
1044 ;;; (2) BQ-SIMPLIFY, if used, rewrites the code produced by
1045 ;;; BQ-PROCESS to produce equivalent but faster code.  The
1046 ;;; additional functions #:BQ-LIST* and #:BQ-NCONC may be
1047 ;;; introduced into the code.
1048 ;;;
1049 ;;; (3) BQ-REMOVE-TOKENS goes through the code and replaces
1050 ;;; #:BQ-LIST with LIST, #:BQ-APPEND with APPEND, and so on.
1051 ;;; #:BQ-CLOBBERABLE is simply eliminated (a call to it being
1052 ;;; replaced by its argument).  #:BQ-LIST* is replaced by either
1053 ;;; LIST* or CONS (the latter is used in the two-argument case,
1054 ;;; purely to make the resulting code a tad more readable).
1055
1056 (defun bq-completely-process (x)
1057   (let ((raw-result (bq-process x)))
1058     (bq-remove-tokens (if *bq-simplify*
1059                           (bq-simplify raw-result)
1060                           raw-result))))
1061
1062 (defun bq-process (x)
1063   (cond ((atom x)
1064          (list *bq-quote* x))
1065         ((eq (car x) 'backquote)
1066          (bq-process (bq-completely-process (cadr x))))
1067         ((eq (car x) *comma*) (cadr x))
1068         ((eq (car x) *comma-atsign*)
1069          ;; (error ",@~S after `" (cadr x))
1070          (error "ill-formed"))
1071         ;; ((eq (car x) *comma-dot*)
1072         ;;  ;; (error ",.~S after `" (cadr x))
1073         ;;  (error "ill-formed"))
1074         (t (do ((p x (cdr p))
1075                 (q '() (cons (bracket (car p)) q)))
1076                ((atom p)
1077                 (cons *bq-append*
1078                       (nreconc q (list (list *bq-quote* p)))))
1079              (when (eq (car p) *comma*)
1080                (unless (null (cddr p))
1081                  ;; (error "Malformed ,~S" p)
1082                  (error "Malformed"))
1083                (return (cons *bq-append*
1084                              (nreconc q (list (cadr p))))))
1085              (when (eq (car p) *comma-atsign*)
1086                ;; (error "Dotted ,@~S" p)
1087                (error "Dotted"))
1088              ;; (when (eq (car p) *comma-dot*)
1089              ;;   ;; (error "Dotted ,.~S" p)
1090              ;;   (error "Dotted"))
1091              ))))
1092
1093 ;;; This implements the bracket operator of the formal rules.
1094 (defun bracket (x)
1095   (cond ((atom x)
1096          (list *bq-list* (bq-process x)))
1097         ((eq (car x) *comma*)
1098          (list *bq-list* (cadr x)))
1099         ((eq (car x) *comma-atsign*)
1100          (cadr x))
1101         ;; ((eq (car x) *comma-dot*)
1102         ;;  (list *bq-clobberable* (cadr x)))
1103         (t (list *bq-list* (bq-process x)))))
1104
1105 ;;; This auxiliary function is like MAPCAR but has two extra
1106 ;;; purposes: (1) it handles dotted lists; (2) it tries to make
1107 ;;; the result share with the argument x as much as possible.
1108 (defun maptree (fn x)
1109   (if (atom x)
1110       (funcall fn x)
1111       (let ((a (funcall fn (car x)))
1112             (d (maptree fn (cdr x))))
1113         (if (and (eql a (car x)) (eql d (cdr x)))
1114             x
1115             (cons a d)))))
1116
1117 ;;; This predicate is true of a form that when read looked
1118 ;;; like %@foo or %.foo.
1119 (defun bq-splicing-frob (x)
1120   (and (consp x)
1121        (or (eq (car x) *comma-atsign*)
1122            ;; (eq (car x) *comma-dot*)
1123            )))
1124
1125 ;;; This predicate is true of a form that when read
1126 ;;; looked like %@foo or %.foo or just plain %foo.
1127 (defun bq-frob (x)
1128   (and (consp x)
1129        (or (eq (car x) *comma*)
1130            (eq (car x) *comma-atsign*)
1131            ;; (eq (car x) *comma-dot*)
1132            )))
1133
1134 ;;; The simplifier essentially looks for calls to #:BQ-APPEND and
1135 ;;; tries to simplify them.  The arguments to #:BQ-APPEND are
1136 ;;; processed from right to left, building up a replacement form.
1137 ;;; At each step a number of special cases are handled that,
1138 ;;; loosely speaking, look like this:
1139 ;;;
1140 ;;;  (APPEND (LIST a b c) foo) => (LIST* a b c foo)
1141 ;;;       provided a, b, c are not splicing frobs
1142 ;;;  (APPEND (LIST* a b c) foo) => (LIST* a b (APPEND c foo))
1143 ;;;       provided a, b, c are not splicing frobs
1144 ;;;  (APPEND (QUOTE (x)) foo) => (LIST* (QUOTE x) foo)
1145 ;;;  (APPEND (CLOBBERABLE x) foo) => (NCONC x foo)
1146 (defun bq-simplify (x)
1147   (if (atom x)
1148       x
1149       (let ((x (if (eq (car x) *bq-quote*)
1150                    x
1151                    (maptree #'bq-simplify x))))
1152         (if (not (eq (car x) *bq-append*))
1153             x
1154             (bq-simplify-args x)))))
1155
1156 (defun bq-simplify-args (x)
1157   (do ((args (reverse (cdr x)) (cdr args))
1158        (result
1159          nil
1160          (cond ((atom (car args))
1161                 (bq-attach-append *bq-append* (car args) result))
1162                ((and (eq (caar args) *bq-list*)
1163                      (notany #'bq-splicing-frob (cdar args)))
1164                 (bq-attach-conses (cdar args) result))
1165                ((and (eq (caar args) *bq-list**)
1166                      (notany #'bq-splicing-frob (cdar args)))
1167                 (bq-attach-conses
1168                   (reverse (cdr (reverse (cdar args))))
1169                   (bq-attach-append *bq-append*
1170                                     (car (last (car args)))
1171                                     result)))
1172                ((and (eq (caar args) *bq-quote*)
1173                      (consp (cadar args))
1174                      (not (bq-frob (cadar args)))
1175                      (null (cddar args)))
1176                 (bq-attach-conses (list (list *bq-quote*
1177                                               (caadar args)))
1178                                   result))
1179                ((eq (caar args) *bq-clobberable*)
1180                 (bq-attach-append *bq-nconc* (cadar args) result))
1181                (t (bq-attach-append *bq-append*
1182                                     (car args)
1183                                     result)))))
1184       ((null args) result)))
1185
1186 (defun null-or-quoted (x)
1187   (or (null x) (and (consp x) (eq (car x) *bq-quote*))))
1188
1189 ;;; When BQ-ATTACH-APPEND is called, the OP should be #:BQ-APPEND
1190 ;;; or #:BQ-NCONC.  This produces a form (op item result) but
1191 ;;; some simplifications are done on the fly:
1192 ;;;
1193 ;;;  (op '(a b c) '(d e f g)) => '(a b c d e f g)
1194 ;;;  (op item 'nil) => item, provided item is not a splicable frob
1195 ;;;  (op item 'nil) => (op item), if item is a splicable frob
1196 ;;;  (op item (op a b c)) => (op item a b c)
1197 (defun bq-attach-append (op item result)
1198   (cond ((and (null-or-quoted item) (null-or-quoted result))
1199          (list *bq-quote* (append (cadr item) (cadr result))))
1200         ((or (null result) (equal result *bq-quote-nil*))
1201          (if (bq-splicing-frob item) (list op item) item))
1202         ((and (consp result) (eq (car result) op))
1203          (list* (car result) item (cdr result)))
1204         (t (list op item result))))
1205
1206 ;;; The effect of BQ-ATTACH-CONSES is to produce a form as if by
1207 ;;; `(LIST* ,@items ,result) but some simplifications are done
1208 ;;; on the fly.
1209 ;;;
1210 ;;;  (LIST* 'a 'b 'c 'd) => '(a b c . d)
1211 ;;;  (LIST* a b c 'nil) => (LIST a b c)
1212 ;;;  (LIST* a b c (LIST* d e f g)) => (LIST* a b c d e f g)
1213 ;;;  (LIST* a b c (LIST d e f g)) => (LIST a b c d e f g)
1214 (defun bq-attach-conses (items result)
1215   (cond ((and (every #'null-or-quoted items)
1216               (null-or-quoted result))
1217          (list *bq-quote*
1218                (append (mapcar #'cadr items) (cadr result))))
1219         ((or (null result) (equal result *bq-quote-nil*))
1220          (cons *bq-list* items))
1221         ((and (consp result)
1222               (or (eq (car result) *bq-list*)
1223                   (eq (car result) *bq-list**)))
1224          (cons (car result) (append items (cdr result))))
1225         (t (cons *bq-list** (append items (list result))))))
1226
1227 ;;; Removes funny tokens and changes (#:BQ-LIST* a b) into
1228 ;;; (CONS a b) instead of (LIST* a b), purely for readability.
1229 (defun bq-remove-tokens (x)
1230   (cond ((eq x *bq-list*) 'list)
1231         ((eq x *bq-append*) 'append)
1232         ((eq x *bq-nconc*) 'nconc)
1233         ((eq x *bq-list**) 'list*)
1234         ((eq x *bq-quote*) 'quote)
1235         ((atom x) x)
1236         ((eq (car x) *bq-clobberable*)
1237          (bq-remove-tokens (cadr x)))
1238         ((and (eq (car x) *bq-list**)
1239               (consp (cddr x))
1240               (null (cdddr x)))
1241          (cons 'cons (maptree #'bq-remove-tokens (cdr x))))
1242         (t (maptree #'bq-remove-tokens x))))
1243
1244 (define-transformation backquote (form)
1245   (bq-completely-process form))
1246
1247
1248 ;;; Primitives
1249
1250 (defvar *builtins* nil)
1251
1252 (defmacro define-raw-builtin (name args &body body)
1253   ;; Creates a new primitive function `name' with parameters args and
1254   ;; @body. The body can access to the local environment through the
1255   ;; variable *ENVIRONMENT*.
1256   `(push (list ',name (lambda ,args (block ,name ,@body)))
1257          *builtins*))
1258
1259 (defmacro define-builtin (name args &body body)
1260   `(define-raw-builtin ,name ,args
1261      (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1262        ,@body)))
1263
1264 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1265 (defmacro type-check (decls &body body)
1266   `(js!selfcall
1267      ,@(mapcar (lambda (decl)
1268                  `(code "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1269                decls)
1270      ,@(mapcar (lambda (decl)
1271                  `(code "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1272                         (indent "throw 'The value ' + "
1273                                 ,(first decl)
1274                                 " + ' is not a type "
1275                                 ,(second decl)
1276                                 ".';"
1277                                 *newline*)))
1278                decls)
1279      (code "return " (progn ,@body) ";" *newline*)))
1280
1281 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
1282 ;;; a variable which holds a list of forms. It will compile them and
1283 ;;; store the result in some Javascript variables. BODY is evaluated
1284 ;;; with ARGS bound to the list of these variables to generate the
1285 ;;; code which performs the transformation on these variables.
1286
1287 (defun variable-arity-call (args function)
1288   (unless (consp args)
1289     (error "ARGS must be a non-empty list"))
1290   (let ((counter 0)
1291         (fargs '())
1292         (prelude ""))
1293     (dolist (x args)
1294       (cond
1295         ((floatp x) (push (float-to-string x) fargs))
1296         ((numberp x) (push (integer-to-string x) fargs))
1297         (t (let ((v (code "x" (incf counter))))
1298              (push v fargs)
1299              (concatf prelude
1300                (code "var " v " = " (ls-compile x) ";" *newline*
1301                      "if (typeof " v " !== 'number') throw 'Not a number!';"
1302                      *newline*))))))
1303     (js!selfcall prelude (funcall function (reverse fargs)))))
1304
1305
1306 (defmacro variable-arity (args &body body)
1307   (unless (symbolp args)
1308     (error "Bad usage of VARIABLE-ARITY, you must pass a symbol"))
1309   `(variable-arity-call ,args
1310                         (lambda (,args)
1311                           (code "return " ,@body ";" *newline*))))
1312
1313 (defun num-op-num (x op y)
1314   (type-check (("x" "number" x) ("y" "number" y))
1315     (code "x" op "y")))
1316
1317 (define-raw-builtin + (&rest numbers)
1318   (if (null numbers)
1319       "0"
1320       (variable-arity numbers
1321         (join numbers "+"))))
1322
1323 (define-raw-builtin - (x &rest others)
1324   (let ((args (cons x others)))
1325     (variable-arity args
1326       (if (null others)
1327           (concat "-" (car args))
1328           (join args "-")))))
1329
1330 (define-raw-builtin * (&rest numbers)
1331   (if (null numbers)
1332       "1"
1333       (variable-arity numbers
1334         (join numbers "*"))))
1335
1336 (define-raw-builtin / (x &rest others)
1337   (let ((args (cons x others)))
1338     (variable-arity args
1339       (if (null others)
1340           (concat "1 /" (car args))
1341           (join args "/")))))
1342
1343 (define-builtin mod (x y) (num-op-num x "%" y))
1344
1345
1346 (defun comparison-conjuntion (vars op)
1347   (cond
1348     ((null (cdr vars))
1349      "true")
1350     ((null (cddr vars))
1351      (concat (car vars) op (cadr vars)))
1352     (t
1353      (concat (car vars) op (cadr vars)
1354              " && "
1355              (comparison-conjuntion (cdr vars) op)))))
1356
1357 (defmacro define-builtin-comparison (op sym)
1358   `(define-raw-builtin ,op (x &rest args)
1359      (let ((args (cons x args)))
1360        (variable-arity args
1361          (js!bool (comparison-conjuntion args ,sym))))))
1362
1363 (define-builtin-comparison > ">")
1364 (define-builtin-comparison < "<")
1365 (define-builtin-comparison >= ">=")
1366 (define-builtin-comparison <= "<=")
1367 (define-builtin-comparison = "==")
1368
1369 (define-builtin numberp (x)
1370   (js!bool (code "(typeof (" x ") == \"number\")")))
1371
1372 (define-builtin floor (x)
1373   (type-check (("x" "number" x))
1374     "Math.floor(x)"))
1375
1376 (define-builtin expt (x y)
1377   (type-check (("x" "number" x)
1378                ("y" "number" y))
1379     "Math.pow(x, y)"))
1380
1381 (define-builtin float-to-string (x)
1382   (type-check (("x" "number" x))
1383     "x.toString()"))
1384
1385 (define-builtin cons (x y)
1386   (code "({car: " x ", cdr: " y "})"))
1387
1388 (define-builtin consp (x)
1389   (js!bool
1390    (js!selfcall
1391      "var tmp = " x ";" *newline*
1392      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1393
1394 (define-builtin car (x)
1395   (js!selfcall
1396     "var tmp = " x ";" *newline*
1397     "return tmp === " (ls-compile nil)
1398     "? " (ls-compile nil)
1399     ": tmp.car;" *newline*))
1400
1401 (define-builtin cdr (x)
1402   (js!selfcall
1403     "var tmp = " x ";" *newline*
1404     "return tmp === " (ls-compile nil) "? "
1405     (ls-compile nil)
1406     ": tmp.cdr;" *newline*))
1407
1408 (define-builtin rplaca (x new)
1409   (type-check (("x" "object" x))
1410     (code "(x.car = " new ", x)")))
1411
1412 (define-builtin rplacd (x new)
1413   (type-check (("x" "object" x))
1414     (code "(x.cdr = " new ", x)")))
1415
1416 (define-builtin symbolp (x)
1417   (js!bool
1418    (js!selfcall
1419      "var tmp = " x ";" *newline*
1420      "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1421
1422 (define-builtin make-symbol (name)
1423   (type-check (("name" "string" name))
1424     "({name: name})"))
1425
1426 (define-builtin symbol-name (x)
1427   (code "(" x ").name"))
1428
1429 (define-builtin set (symbol value)
1430   (code "(" symbol ").value = " value))
1431
1432 (define-builtin fset (symbol value)
1433   (code "(" symbol ").fvalue = " value))
1434
1435 (define-builtin boundp (x)
1436   (js!bool (code "(" x ".value !== undefined)")))
1437
1438 (define-builtin symbol-value (x)
1439   (js!selfcall
1440     "var symbol = " x ";" *newline*
1441     "var value = symbol.value;" *newline*
1442     "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1443     "return value;" *newline*))
1444
1445 (define-builtin symbol-function (x)
1446   (js!selfcall
1447     "var symbol = " x ";" *newline*
1448     "var func = symbol.fvalue;" *newline*
1449     "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1450     "return func;" *newline*))
1451
1452 (define-builtin symbol-plist (x)
1453   (code "((" x ").plist || " (ls-compile nil) ")"))
1454
1455 (define-builtin lambda-code (x)
1456   (code "(" x ").toString()"))
1457
1458 (define-builtin eq    (x y) (js!bool (code "(" x " === " y ")")))
1459
1460 (define-builtin char-to-string (x)
1461   (type-check (("x" "number" x))
1462     "String.fromCharCode(x)"))
1463
1464 (define-builtin stringp (x)
1465   (js!bool (code "(typeof(" x ") == \"string\")")))
1466
1467 (define-builtin string-upcase (x)
1468   (type-check (("x" "string" x))
1469     "x.toUpperCase()"))
1470
1471 (define-builtin string-length (x)
1472   (type-check (("x" "string" x))
1473     "x.length"))
1474
1475 (define-raw-builtin slice (string a &optional b)
1476   (js!selfcall
1477     "var str = " (ls-compile string) ";" *newline*
1478     "var a = " (ls-compile a) ";" *newline*
1479     "var b;" *newline*
1480     (when b (code "b = " (ls-compile b) ";" *newline*))
1481     "return str.slice(a,b);" *newline*))
1482
1483 (define-builtin char (string index)
1484   (type-check (("string" "string" string)
1485                ("index" "number" index))
1486     "string.charCodeAt(index)"))
1487
1488 (define-builtin concat-two (string1 string2)
1489   (type-check (("string1" "string" string1)
1490                ("string2" "string" string2))
1491     "string1.concat(string2)"))
1492
1493 (define-raw-builtin funcall (func &rest args)
1494   (js!selfcall
1495     "var f = " (ls-compile func) ";" *newline*
1496     "return (typeof f === 'function'? f: f.fvalue)("
1497     (join (list* (if *multiple-value-p* "values" "pv")
1498                  (integer-to-string (length args))
1499                  (mapcar #'ls-compile args))
1500           ", ")
1501     ")"))
1502
1503 (define-raw-builtin apply (func &rest args)
1504   (if (null args)
1505       (code "(" (ls-compile func) ")()")
1506       (let ((args (butlast args))
1507             (last (car (last args))))
1508         (js!selfcall
1509           "var f = " (ls-compile func) ";" *newline*
1510           "var args = [" (join (list* (if *multiple-value-p* "values" "pv")
1511                                       (integer-to-string (length args))
1512                                       (mapcar #'ls-compile args))
1513                                ", ")
1514           "];" *newline*
1515           "var tail = (" (ls-compile last) ");" *newline*
1516           "while (tail != " (ls-compile nil) "){" *newline*
1517           "    args.push(tail.car);" *newline*
1518           "    args[1] += 1;" *newline*
1519           "    tail = tail.cdr;" *newline*
1520           "}" *newline*
1521           "return (typeof f === 'function'? f : f.fvalue).apply(this, args);" *newline*))))
1522
1523 (define-builtin js-eval (string)
1524   (type-check (("string" "string" string))
1525     (if *multiple-value-p*
1526         (js!selfcall
1527           "var v = globalEval(string);" *newline*
1528           "return values.apply(this, forcemv(v));" *newline*)
1529         "globalEval(string)")))
1530
1531 (define-builtin error (string)
1532   (js!selfcall "throw " string ";" *newline*))
1533
1534 (define-builtin new () "{}")
1535
1536 (define-builtin objectp (x)
1537   (js!bool (code "(typeof (" x ") === 'object')")))
1538
1539 (define-builtin oget (object key)
1540   (js!selfcall
1541     "var tmp = " "(" object ")[" key "];" *newline*
1542     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1543
1544 (define-builtin oset (object key value)
1545   (code "((" object ")[" key "] = " value ")"))
1546
1547 (define-builtin in (key object)
1548   (js!bool (code "((" key ") in (" object "))")))
1549
1550 (define-builtin functionp (x)
1551   (js!bool (code "(typeof " x " == 'function')")))
1552
1553 (define-builtin write-string (x)
1554   (type-check (("x" "string" x))
1555     "lisp.write(x)"))
1556
1557 (define-builtin make-array (n)
1558   (js!selfcall
1559     "var r = [];" *newline*
1560     "for (var i = 0; i < " n "; i++)" *newline*
1561     (indent "r.push(" (ls-compile nil) ");" *newline*)
1562     "return r;" *newline*))
1563
1564 (define-builtin arrayp (x)
1565   (js!bool
1566    (js!selfcall
1567      "var x = " x ";" *newline*
1568      "return typeof x === 'object' && 'length' in x;")))
1569
1570 (define-builtin aref (array n)
1571   (js!selfcall
1572     "var x = " "(" array ")[" n "];" *newline*
1573     "if (x === undefined) throw 'Out of range';" *newline*
1574     "return x;" *newline*))
1575
1576 (define-builtin aset (array n value)
1577   (js!selfcall
1578     "var x = " array ";" *newline*
1579     "var i = " n ";" *newline*
1580     "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
1581     "return x[i] = " value ";" *newline*))
1582
1583 (define-builtin get-internal-real-time ()
1584   "(new Date()).getTime()")
1585
1586 (define-builtin values-array (array)
1587   (if *multiple-value-p*
1588       (code "values.apply(this, " array ")")
1589       (code "pv.apply(this, " array ")")))
1590
1591 (define-raw-builtin values (&rest args)
1592   (if *multiple-value-p*
1593       (code "values(" (join (mapcar #'ls-compile args) ", ") ")")
1594       (code "pv(" (join (mapcar #'ls-compile args) ", ") ")")))
1595
1596 ;; Receives the JS function as first argument as a literal string. The
1597 ;; second argument is compiled and should evaluate to a vector of
1598 ;; values to apply to the the function. The result returned.
1599 (define-builtin %js-call (fun args)
1600   (code fun ".apply(this, " args ")"))
1601
1602 (defun macro (x)
1603   (and (symbolp x)
1604        (let ((b (lookup-in-lexenv x *environment* 'function)))
1605          (if (and b (eq (binding-type b) 'macro))
1606              b
1607              nil))))
1608
1609 #+common-lisp
1610 (defvar *macroexpander-cache*
1611   (make-hash-table :test #'eq))
1612
1613 (defun ls-macroexpand-1 (form)
1614   (cond
1615     ((symbolp form)
1616      (let ((b (lookup-in-lexenv form *environment* 'variable)))
1617        (if (and b (eq (binding-type b) 'macro))
1618            (values (binding-value b) t)
1619            (values form nil))))
1620     ((consp form)
1621      (let ((macro-binding (macro (car form))))
1622        (if macro-binding
1623            (let ((expander (binding-value macro-binding)))
1624              (cond
1625                #+common-lisp
1626                ((gethash macro-binding *macroexpander-cache*)
1627                 (setq expander (gethash macro-binding *macroexpander-cache*)))
1628                ((listp expander)
1629                 (let ((compiled (eval expander)))
1630                   ;; The list representation are useful while
1631                   ;; bootstrapping, as we can dump the definition of the
1632                   ;; macros easily, but they are slow because we have to
1633                   ;; evaluate them and compile them now and again. So, let
1634                   ;; us replace the list representation version of the
1635                   ;; function with the compiled one.
1636                   ;;
1637                   #+jscl (setf (binding-value macro-binding) compiled)
1638                   #+common-lisp (setf (gethash macro-binding *macroexpander-cache*) compiled)
1639                   (setq expander compiled))))
1640              (values (apply expander (cdr form)) t))
1641            (values form nil))))
1642     (t
1643      (values form nil))))
1644
1645 (defun compile-funcall (function args)
1646   (let* ((values-funcs (if *multiple-value-p* "values" "pv"))
1647          (arglist (concat "(" (join (list* values-funcs
1648                                            (integer-to-string (length args))
1649                                            (mapcar #'ls-compile args)) ", ") ")")))
1650     (unless (or (symbolp function)
1651                 (and (consp function)
1652                      (eq (car function) 'lambda)))
1653       (error "Bad function"))
1654     (cond
1655       ((translate-function function)
1656        (concat (translate-function function) arglist))
1657       ((and (symbolp function)
1658             #+jscl (eq (symbol-package function) (find-package "COMMON-LISP"))
1659             #+common-lisp t)
1660        (code (ls-compile `',function) ".fvalue" arglist))
1661       (t
1662        (code (ls-compile `#',function) arglist)))))
1663
1664 (defun ls-compile-block (sexps &optional return-last-p)
1665   (if return-last-p
1666       (code (ls-compile-block (butlast sexps))
1667             "return " (ls-compile (car (last sexps)) *multiple-value-p*) ";")
1668       (join-trailing
1669        (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
1670        (concat ";" *newline*))))
1671
1672 (defun ls-compile (sexp &optional multiple-value-p)
1673   (multiple-value-bind (sexp expandedp) (ls-macroexpand-1 sexp)
1674     (when expandedp
1675       (return-from ls-compile (ls-compile sexp multiple-value-p)))
1676     ;; The expression has been macroexpanded. Now compile it!
1677     (let ((*multiple-value-p* multiple-value-p))
1678       (cond
1679         ((symbolp sexp)
1680          (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1681            (cond
1682              ((and b (not (member 'special (binding-declarations b))))
1683               (binding-value b))
1684              ((or (keywordp sexp)
1685                   (and b (member 'constant (binding-declarations b))))
1686               (code (ls-compile `',sexp) ".value"))
1687              (t
1688               (ls-compile `(symbol-value ',sexp))))))
1689         ((integerp sexp) (integer-to-string sexp))
1690         ((floatp sexp) (float-to-string sexp))
1691         ((stringp sexp) (code "\"" (escape-string sexp) "\""))
1692         ((arrayp sexp) (literal sexp))
1693         ((listp sexp)
1694          (let ((name (car sexp))
1695                (args (cdr sexp)))
1696            (cond
1697              ;; Special forms
1698              ((assoc name *compilations*)
1699               (let ((comp (second (assoc name *compilations*))))
1700                 (apply comp args)))
1701              ;; Built-in functions
1702              ((and (assoc name *builtins*)
1703                    (not (claimp name 'function 'notinline)))
1704               (let ((comp (second (assoc name *builtins*))))
1705                 (apply comp args)))
1706              (t
1707               (compile-funcall name args)))))
1708         (t
1709          (error (concat "How should I compile " (prin1-to-string sexp) "?")))))))
1710
1711
1712 (defvar *compile-print-toplevels* nil)
1713
1714 (defun truncate-string (string &optional (width 60))
1715   (let ((n (or (position #\newline string)
1716                (min width (length string)))))
1717     (subseq string 0 n)))
1718
1719 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
1720   (let ((*toplevel-compilations* nil))
1721     (cond
1722       ((and (consp sexp) (eq (car sexp) 'progn))
1723        (let ((subs (mapcar (lambda (s)
1724                              (ls-compile-toplevel s t))
1725                            (cdr sexp))))
1726          (join (remove-if #'null-or-empty-p subs))))
1727       (t
1728        (when *compile-print-toplevels*
1729          (let ((form-string (prin1-to-string sexp)))
1730            (write-string "Compiling ")
1731            (write-string (truncate-string form-string))
1732            (write-line "...")))
1733
1734        (let ((code (ls-compile sexp multiple-value-p)))
1735          (code (join-trailing (get-toplevel-compilations)
1736                               (code ";" *newline*))
1737                (when code
1738                  (code code ";" *newline*))))))))