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