08137151119bf19c23b9a508987db87974b8fd00
[jscl.git] / ecmalisp.lisp
1 ;;; ecmalisp.lisp ---
2
3 ;; Copyright (C) 2012, 2013 David Vazquez
4 ;; Copyright (C) 2012 Raimon Grau
5
6 ;; This program 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 ;; This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
18
19 ;;; This code is executed when ecmalisp compiles this file
20 ;;; itself. The compiler provides compilation of some special forms,
21 ;;; as well as funcalls and macroexpansion, but no functions. So, we
22 ;;; define the Lisp world from scratch. This code has to define enough
23 ;;; language to the compiler to be able to run.
24
25 #+ecmalisp
26 (progn
27   (eval-when-compile
28     (%compile-defmacro 'defmacro
29                        '(function
30                          (lambda (name args &rest body)
31                           `(eval-when-compile
32                              (%compile-defmacro ',name
33                                                 '(function
34                                                   (lambda ,(mapcar #'(lambda (x)
35                                                                        (if (eq x '&body)
36                                                                            '&rest
37                                                                            x))
38                                                                    args)
39                                                    ,@body))))))))
40
41   (defmacro declaim (&rest decls)
42     `(eval-when-compile
43        ,@(mapcar (lambda (decl) `(!proclaim ',decl)) decls)))
44
45   (defmacro defconstant (name value &optional docstring)
46     `(progn
47        (declaim (special ,name))
48        (declaim (constant ,name))
49        (setq ,name ,value)
50        ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
51        ',name))
52
53   (defconstant t 't)
54   (defconstant nil 'nil)
55   (js-vset "nil" nil)
56
57   (defmacro lambda (args &body body)
58     `(function (lambda ,args ,@body)))
59
60   (defmacro when (condition &body body)
61     `(if ,condition (progn ,@body) nil))
62
63   (defmacro unless (condition &body body)
64     `(if ,condition nil (progn ,@body)))
65
66   (defmacro defvar (name value &optional docstring)
67     `(progn
68        (declaim (special ,name))
69        (unless (boundp ',name) (setq ,name ,value))
70        ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
71        ',name))
72
73   (defmacro defparameter (name value &optional docstring)
74     `(progn
75        (setq ,name ,value)
76        ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
77        ',name))
78
79   (defmacro named-lambda (name args &rest body)
80     (let ((x (gensym "FN")))
81       `(let ((,x (lambda ,args ,@body)))
82          (oset ,x "fname" ,name)
83          ,x)))
84
85   (defmacro defun (name args &rest body)
86     `(progn
87        (fset ',name
88              (named-lambda ,(symbol-name name) ,args
89                ,@(if (and (stringp (car body)) (not (null (cdr body))))
90                      `(,(car body) (block ,name ,@(cdr body)))
91                      `((block ,name ,@body)))))
92        ',name))
93
94   (defun null (x)
95     (eq x nil))
96
97   (defun endp (x)
98     (if (null x)
99         t
100         (if (consp x)
101             nil
102             (error "type-error"))))
103
104   (defmacro return (&optional value)
105     `(return-from nil ,value))
106
107   (defmacro while (condition &body body)
108     `(block nil (%while ,condition ,@body)))
109
110   (defvar *gensym-counter* 0)
111   (defun gensym (&optional (prefix "G"))
112     (setq *gensym-counter* (+ *gensym-counter* 1))
113     (make-symbol (concat-two prefix (integer-to-string *gensym-counter*))))
114
115   (defun boundp (x)
116     (boundp x))
117
118   ;; Basic functions
119   (defun = (x y) (= x y))
120   (defun * (x y) (* x y))
121   (defun / (x y) (/ x y))
122   (defun 1+ (x) (+ x 1))
123   (defun 1- (x) (- x 1))
124   (defun zerop (x) (= x 0))
125   (defun truncate (x y) (floor (/ x y)))
126
127   (defun eql (x y) (eq x y))
128
129   (defun not (x) (if x nil t))
130
131   (defun cons (x y ) (cons x y))
132   (defun consp (x) (consp x))
133
134   (defun car (x)
135     "Return the CAR part of a cons, or NIL if X is null."
136     (car x))
137
138   (defun cdr (x) (cdr x))
139   (defun caar (x) (car (car x)))
140   (defun cadr (x) (car (cdr x)))
141   (defun cdar (x) (cdr (car x)))
142   (defun cddr (x) (cdr (cdr x)))
143   (defun cadar (x) (car (cdr (car x))))
144   (defun caddr (x) (car (cdr (cdr x))))
145   (defun cdddr (x) (cdr (cdr (cdr x))))
146   (defun cadddr (x) (car (cdr (cdr (cdr x)))))
147   (defun first (x) (car x))
148   (defun second (x) (cadr x))
149   (defun third (x) (caddr x))
150   (defun fourth (x) (cadddr x))
151   (defun rest (x) (cdr x))
152
153   (defun list (&rest args) args)
154   (defun atom (x)
155     (not (consp x)))
156
157   ;; Basic macros
158
159   (defmacro incf (x &optional (delta 1))
160     `(setq ,x (+ ,x ,delta)))
161
162   (defmacro decf (x &optional (delta 1))
163     `(setq ,x (- ,x ,delta)))
164
165   (defmacro push (x place)
166     (multiple-value-bind (dummies vals newval setter getter)
167         (get-setf-expansion place)
168       (let ((g (gensym)))
169         `(let* ((,g ,x)
170                 ,@(mapcar #'list dummies vals)
171                 (,(car newval) (cons ,g ,getter))
172                 ,@(cdr newval))
173            ,setter))))
174
175   (defmacro dolist (iter &body body)
176     (let ((var (first iter))
177           (g!list (gensym)))
178       `(block nil
179          (let ((,g!list ,(second iter))
180                (,var nil))
181            (%while ,g!list
182                    (setq ,var (car ,g!list))
183                    (tagbody ,@body)
184                    (setq ,g!list (cdr ,g!list)))
185            ,(third iter)))))
186
187   (defmacro dotimes (iter &body body)
188     (let ((g!to (gensym))
189           (var (first iter))
190           (to (second iter))
191           (result (third iter)))
192       `(block nil
193          (let ((,var 0)
194                (,g!to ,to))
195            (%while (< ,var ,g!to)
196                    (tagbody ,@body)
197                    (incf ,var))
198            ,result))))
199
200   (defmacro cond (&rest clausules)
201     (if (null clausules)
202         nil
203         (if (eq (caar clausules) t)
204             `(progn ,@(cdar clausules))
205             `(if ,(caar clausules)
206                  (progn ,@(cdar clausules))
207                  (cond ,@(cdr clausules))))))
208
209   (defmacro case (form &rest clausules)
210     (let ((!form (gensym)))
211       `(let ((,!form ,form))
212          (cond
213            ,@(mapcar (lambda (clausule)
214                        (if (eq (car clausule) t)
215                            clausule
216                            `((eql ,!form ',(car clausule))
217                              ,@(cdr clausule))))
218                      clausules)))))
219
220   (defmacro ecase (form &rest clausules)
221     `(case ,form
222        ,@(append
223           clausules
224           `((t
225              (error "ECASE expression failed."))))))
226
227   (defmacro and (&rest forms)
228     (cond
229       ((null forms)
230        t)
231       ((null (cdr forms))
232        (car forms))
233       (t
234        `(if ,(car forms)
235             (and ,@(cdr forms))
236             nil))))
237
238   (defmacro or (&rest forms)
239     (cond
240       ((null forms)
241        nil)
242       ((null (cdr forms))
243        (car forms))
244       (t
245        (let ((g (gensym)))
246          `(let ((,g ,(car forms)))
247             (if ,g ,g (or ,@(cdr forms))))))))
248
249   (defmacro prog1 (form &body body)
250     (let ((value (gensym)))
251       `(let ((,value ,form))
252          ,@body
253          ,value)))
254
255   (defmacro prog2 (form1 result &body body)
256     `(prog1 (progn ,form1 ,result) ,@body)))
257
258
259 ;;; This couple of helper functions will be defined in both Common
260 ;;; Lisp and in Ecmalisp.
261 (defun ensure-list (x)
262   (if (listp x)
263       x
264       (list x)))
265
266 (defun !reduce (func list &key initial-value)
267   (if (null list)
268       initial-value
269       (!reduce func
270                (cdr list)
271                :initial-value (funcall func initial-value (car list)))))
272
273 ;;; Go on growing the Lisp language in Ecmalisp, with more high
274 ;;; level utilities as well as correct versions of other
275 ;;; constructions.
276 #+ecmalisp
277 (progn
278   (defun + (&rest args)
279     (let ((r 0))
280       (dolist (x args r)
281         (incf r x))))
282
283   (defun - (x &rest others)
284     (if (null others)
285         (- x)
286         (let ((r x))
287           (dolist (y others r)
288             (decf r y)))))
289
290   (defun append-two (list1 list2)
291     (if (null list1)
292         list2
293         (cons (car list1)
294               (append (cdr list1) list2))))
295
296   (defun append (&rest lists)
297     (!reduce #'append-two lists))
298
299   (defun revappend (list1 list2)
300     (while list1
301       (push (car list1) list2)
302       (setq list1 (cdr list1)))
303     list2)
304
305   (defun reverse (list)
306     (revappend list '()))
307
308   (defmacro psetq (&rest pairs)
309     (let ( ;; For each pair, we store here a list of the form
310           ;; (VARIABLE GENSYM VALUE).
311           (assignments '()))
312       (while t
313         (cond
314           ((null pairs) (return))
315           ((null (cdr pairs))
316            (error "Odd paris in PSETQ"))
317           (t
318            (let ((variable (car pairs))
319                  (value (cadr pairs)))
320              (push `(,variable ,(gensym) ,value)  assignments)
321              (setq pairs (cddr pairs))))))
322       (setq assignments (reverse assignments))
323       ;;
324       `(let ,(mapcar #'cdr assignments)
325          (setq ,@(!reduce #'append (mapcar #'butlast assignments))))))
326
327   (defmacro do (varlist endlist &body body)
328     `(block nil
329        (let ,(mapcar (lambda (x) (list (first x) (second x))) varlist)
330          (while t
331            (when ,(car endlist)
332              (return (progn ,@(cdr endlist))))
333            (tagbody ,@body)
334            (psetq
335             ,@(apply #'append
336                      (mapcar (lambda (v)
337                                (and (consp (cddr v))
338                                     (list (first v) (third v))))
339                              varlist)))))))
340
341   (defmacro do* (varlist endlist &body body)
342     `(block nil
343        (let* ,(mapcar (lambda (x) (list (first x) (second x))) varlist)
344          (while t
345            (when ,(car endlist)
346              (return (progn ,@(cdr endlist))))
347            (tagbody ,@body)
348            (setq
349             ,@(apply #'append
350                      (mapcar (lambda (v)
351                                (and (consp (cddr v))
352                                     (list (first v) (third v))))
353                              varlist)))))))
354
355   (defun list-length (list)
356     (let ((l 0))
357       (while (not (null list))
358         (incf l)
359         (setq list (cdr list)))
360       l))
361
362   (defun length (seq)
363     (cond
364       ((stringp seq)
365        (string-length seq))
366       ((arrayp seq)
367        (oget seq "length"))
368       ((listp seq)
369        (list-length seq))))
370
371   (defun concat-two (s1 s2)
372     (concat-two s1 s2))
373
374   (defmacro with-collect (&body body)
375     (let ((head (gensym))
376           (tail (gensym)))
377       `(let* ((,head (cons 'sentinel nil))
378               (,tail ,head))
379          (flet ((collect (x)
380                   (rplacd ,tail (cons x nil))
381                   (setq ,tail (cdr ,tail))
382                   x))
383            ,@body)
384          (cdr ,head))))
385
386   (defun map1 (func list)
387     (with-collect
388         (while list
389           (collect (funcall func (car list)))
390           (setq list (cdr list)))))
391
392   (defmacro loop (&body body)
393     `(while t ,@body))
394
395   (defun mapcar (func list &rest lists)
396     (let ((lists (cons list lists)))
397       (with-collect
398           (block loop
399             (loop
400                (let ((elems (map1 #'car lists)))
401                  (do ((tail lists (cdr tail)))
402                      ((null tail))
403                    (when (null (car tail)) (return-from loop))
404                    (rplaca tail (cdar tail)))
405                  (collect (apply func elems))))))))
406
407   (defun identity (x) x)
408
409   (defun constantly (x)
410     (lambda (&rest args)
411       x))
412
413   (defun copy-list (x)
414     (mapcar #'identity x))
415
416   (defun list* (arg &rest others)
417     (cond ((null others) arg)
418           ((null (cdr others)) (cons arg (car others)))
419           (t (do ((x others (cdr x)))
420                  ((null (cddr x)) (rplacd x (cadr x))))
421              (cons arg others))))
422
423   (defun code-char (x) x)
424   (defun char-code (x) x)
425   (defun char= (x y) (= x y))
426
427   (defun integerp (x)
428     (and (numberp x) (= (floor x) x)))
429
430   (defun plusp (x) (< 0 x))
431   (defun minusp (x) (< x 0))
432
433   (defun listp (x)
434     (or (consp x) (null x)))
435
436   (defun nthcdr (n list)
437     (while (and (plusp n) list)
438       (setq n (1- n))
439       (setq list (cdr list)))
440     list)
441
442   (defun nth (n list)
443     (car (nthcdr n list)))
444
445   (defun last (x)
446     (while (consp (cdr x))
447       (setq x (cdr x)))
448     x)
449
450   (defun butlast (x)
451     (and (consp (cdr x))
452          (cons (car x) (butlast (cdr x)))))
453
454   (defun member (x list)
455     (while list
456       (when (eql x (car list))
457         (return list))
458       (setq list (cdr list))))
459
460   (defun remove (x list)
461     (cond
462       ((null list)
463        nil)
464       ((eql x (car list))
465        (remove x (cdr list)))
466       (t
467        (cons (car list) (remove x (cdr list))))))
468
469   (defun remove-if (func list)
470     (cond
471       ((null list)
472        nil)
473       ((funcall func (car list))
474        (remove-if func (cdr list)))
475       (t
476        ;;
477        (cons (car list) (remove-if func (cdr list))))))
478
479   (defun remove-if-not (func list)
480     (cond
481       ((null list)
482        nil)
483       ((funcall func (car list))
484        (cons (car list) (remove-if-not func (cdr list))))
485       (t
486        (remove-if-not func (cdr list)))))
487
488   (defun digit-char-p (x)
489     (if (and (<= #\0 x) (<= x #\9))
490         (- x #\0)
491         nil))
492
493   (defun digit-char (weight)
494     (and (<= 0 weight 9)
495          (char "0123456789" weight)))
496
497   (defun subseq (seq a &optional b)
498     (cond
499       ((stringp seq)
500        (if b
501            (slice seq a b)
502            (slice seq a)))
503       (t
504        (error "Unsupported argument."))))
505
506   (defmacro do-sequence (iteration &body body)
507     (let ((seq (gensym))
508           (index (gensym)))
509       `(let ((,seq ,(second iteration)))
510          (cond
511            ;; Strings
512            ((stringp ,seq)
513             (let ((,index 0))
514               (dotimes (,index (length ,seq))
515                 (let ((,(first iteration)
516                        (char ,seq ,index)))
517                   ,@body))))
518            ;; Lists
519            ((listp ,seq)
520             (dolist (,(first iteration) ,seq)
521               ,@body))
522            (t
523             (error "type-error!"))))))
524
525   (defun some (function seq)
526     (do-sequence (elt seq)
527       (when (funcall function elt)
528         (return-from some t))))
529
530   (defun every (function seq)
531     (do-sequence (elt seq)
532       (unless (funcall function elt)
533         (return-from every nil)))
534     t)
535
536   (defun assoc (x alist)
537     (while alist
538       (if (eql x (caar alist))
539           (return)
540           (setq alist (cdr alist))))
541     (car alist))
542
543   (defun string (x)
544     (cond ((stringp x) x)
545           ((symbolp x) (symbol-name x))
546           (t (char-to-string x))))
547
548   (defun string= (s1 s2)
549     (equal s1 s2))
550
551   (defun fdefinition (x)
552     (cond
553       ((functionp x)
554        x)
555       ((symbolp x)
556        (symbol-function x))
557       (t
558        (error "Invalid function"))))
559
560   (defun disassemble (function)
561     (write-line (lambda-code (fdefinition function)))
562     nil)
563
564   (defun documentation (x type)
565     "Return the documentation of X. TYPE must be the symbol VARIABLE or FUNCTION."
566     (ecase type
567       (function
568        (let ((func (fdefinition x)))
569          (oget func "docstring")))
570       (variable
571        (unless (symbolp x)
572          (error "Wrong argument type! it should be a symbol"))
573        (oget x "vardoc"))))
574
575   (defmacro multiple-value-bind (variables value-from &body body)
576     `(multiple-value-call (lambda (&optional ,@variables &rest ,(gensym))
577                             ,@body)
578        ,value-from))
579
580   (defmacro multiple-value-list (value-from)
581     `(multiple-value-call #'list ,value-from))
582
583
584 ;;; Generalized references (SETF)
585
586   (defvar *setf-expanders* nil)
587
588   (defun get-setf-expansion (place)
589     (if (symbolp place)
590         (let ((value (gensym)))
591           (values nil
592                   nil
593                   `(,value)
594                   `(setq ,place ,value)
595                   place))
596         (let ((place (ls-macroexpand-1 place)))
597           (let* ((access-fn (car place))
598                  (expander (cdr (assoc access-fn *setf-expanders*))))
599             (when (null expander)
600               (error "Unknown generalized reference."))
601             (apply expander (cdr place))))))
602
603   (defmacro define-setf-expander (access-fn lambda-list &body body)
604     (unless (symbolp access-fn)
605       (error "ACCESS-FN must be a symbol."))
606     `(progn (push (cons ',access-fn (lambda ,lambda-list ,@body))
607                   *setf-expanders*)
608             ',access-fn))
609
610   (defmacro setf (&rest pairs)
611     (cond
612       ((null pairs)
613        nil)
614       ((null (cdr pairs))
615        (error "Odd number of arguments to setf."))
616       ((null (cddr pairs))
617        (let ((place (first pairs))
618              (value (second pairs)))
619          (multiple-value-bind (vars vals store-vars writer-form reader-form)
620              (get-setf-expansion place)
621            ;; TODO: Optimize the expansion a little bit to avoid let*
622            ;; or multiple-value-bind when unnecesary.
623            `(let* ,(mapcar #'list vars vals)
624               (multiple-value-bind ,store-vars
625                   ,value
626                 ,writer-form)))))
627       (t
628        `(progn
629           ,@(do ((pairs pairs (cddr pairs))
630                  (result '() (cons `(setf ,(car pairs) ,(cadr pairs)) result)))
631                 ((null pairs)
632                  (reverse result)))))))
633
634   (define-setf-expander car (x)
635     (let ((cons (gensym))
636           (new-value (gensym)))
637       (values (list cons)
638               (list x)
639               (list new-value)
640               `(progn (rplaca ,cons ,new-value) ,new-value)
641               `(car ,cons))))
642
643   (define-setf-expander cdr (x)
644     (let ((cons (gensym))
645           (new-value (gensym)))
646       (values (list cons)
647               (list x)
648               (list new-value)
649               `(progn (rplacd ,cons ,new-value) ,new-value)
650               `(car ,cons))))
651
652   ;; Incorrect typecase, but used in NCONC.
653   (defmacro typecase (x &rest clausules)
654     (let ((value (gensym)))
655       `(let ((,value ,x))
656          (cond
657            ,@(mapcar (lambda (c)
658                        (if (eq (car c) t)
659                            `((t ,@(rest c)))
660                            `((,(ecase (car c)
661                                       (integer 'integerp)
662                                       (cons 'consp)
663                                       (string 'stringp)
664                                       (atom 'atom)
665                                       (null 'null))
666                                ,value)
667                              ,@(or (rest c)
668                                    (list nil)))))
669                      clausules)))))
670
671   ;; The NCONC function is based on the SBCL's one.
672   (defun nconc (&rest lists)
673     (flet ((fail (object)
674              (error "type-error in nconc")))
675       (do ((top lists (cdr top)))
676           ((null top) nil)
677         (let ((top-of-top (car top)))
678           (typecase top-of-top
679             (cons
680              (let* ((result top-of-top)
681                     (splice result))
682                (do ((elements (cdr top) (cdr elements)))
683                    ((endp elements))
684                  (let ((ele (car elements)))
685                    (typecase ele
686                      (cons (rplacd (last splice) ele)
687                            (setf splice ele))
688                      (null (rplacd (last splice) nil))
689                      (atom (if (cdr elements)
690                                (fail ele)
691                                (rplacd (last splice) ele))))))
692                (return result)))
693             (null)
694             (atom
695              (if (cdr top)
696                  (fail top-of-top)
697                  (return top-of-top))))))))
698
699   (defun nreconc (x y)
700     (do ((1st (cdr x) (if (endp 1st) 1st (cdr 1st)))
701          (2nd x 1st)                ; 2nd follows first down the list.
702          (3rd y 2nd))               ;3rd follows 2nd down the list.
703         ((atom 2nd) 3rd)
704       (rplacd 2nd 3rd)))
705
706   (defun notany (fn seq)
707     (not (some fn seq)))
708
709
710   ;; Packages
711
712   (defvar *package-list* nil)
713
714   (defun list-all-packages ()
715     *package-list*)
716
717   (defun make-package (name &key use)
718     (let ((package (new))
719           (use (mapcar #'find-package-or-fail use)))
720       (oset package "packageName" name)
721       (oset package "symbols" (new))
722       (oset package "exports" (new))
723       (oset package "use" use)
724       (push package *package-list*)
725       package))
726
727   (defun packagep (x)
728     (and (objectp x) (in "symbols" x)))
729
730   (defun find-package (package-designator)
731     (when (packagep package-designator)
732       (return-from find-package package-designator))
733     (let ((name (string package-designator)))
734       (dolist (package *package-list*)
735         (when (string= (package-name package) name)
736           (return package)))))
737
738   (defun find-package-or-fail (package-designator)
739     (or (find-package package-designator)
740         (error "Package unknown.")))
741
742   (defun package-name (package-designator)
743     (let ((package (find-package-or-fail package-designator)))
744       (oget package "packageName")))
745
746   (defun %package-symbols (package-designator)
747     (let ((package (find-package-or-fail package-designator)))
748       (oget package "symbols")))
749
750   (defun package-use-list (package-designator)
751     (let ((package (find-package-or-fail package-designator)))
752       (oget package "use")))
753
754   (defun %package-external-symbols (package-designator)
755     (let ((package (find-package-or-fail package-designator)))
756       (oget package "exports")))
757
758   (defvar *common-lisp-package*
759     (make-package "CL"))
760
761   (defvar *js-package*
762     (make-package "JS"))
763
764   (defvar *user-package*
765     (make-package "CL-USER" :use (list *common-lisp-package*)))
766
767   (defvar *keyword-package*
768     (make-package "KEYWORD"))
769
770   (defun keywordp (x)
771     (and (symbolp x) (eq (symbol-package x) *keyword-package*)))
772
773   (defvar *package* *common-lisp-package*)
774
775   (defmacro in-package (package-designator)
776     `(eval-when-compile
777        (setq *package* (find-package-or-fail ,package-designator))))
778
779   ;; This function is used internally to initialize the CL package
780   ;; with the symbols built during bootstrap.
781   (defun %intern-symbol (symbol)
782     (let* ((package
783             (if (in "package" symbol)
784                 (find-package-or-fail (oget symbol "package"))
785                 *common-lisp-package*))
786            (symbols (%package-symbols package)))
787       (oset symbol "package" package)
788       (when (eq package *keyword-package*)
789         (oset symbol "value" symbol))
790       (oset symbols (symbol-name symbol) symbol)))
791
792   (defun find-symbol (name &optional (package *package*))
793     (let* ((package (find-package-or-fail package))
794            (externals (%package-external-symbols package))
795            (symbols (%package-symbols package)))
796       (cond
797         ((in name externals)
798          (values (oget externals name) :external))
799         ((in name symbols)
800          (values (oget symbols name) :internal))
801         (t
802          (dolist (used (package-use-list package) (values nil nil))
803            (let ((exports (%package-external-symbols used)))
804              (when (in name exports)
805                (return (values (oget exports name) :inherit)))))))))
806
807   (defun intern (name &optional (package *package*))
808     (let ((package (find-package-or-fail package)))
809       (multiple-value-bind (symbol foundp)
810           (find-symbol name package)
811         (if foundp
812             (values symbol foundp)
813             (let ((symbols (%package-symbols package)))
814               (oget symbols name)
815               (let ((symbol (make-symbol name)))
816                 (oset symbol "package" package)
817                 (when (eq package *keyword-package*)
818                   (oset symbol "value" symbol)
819                   (export (list symbol) package))
820                 (when (eq package *js-package*)
821                   (oset symbol "value" symbol)
822                   (export (list symbol) package))
823                 (oset symbols name symbol)
824                 (values symbol nil)))))))
825
826   (defun symbol-package (symbol)
827     (unless (symbolp symbol)
828       (error "it is not a symbol"))
829     (oget symbol "package"))
830
831   (defun export (symbols &optional (package *package*))
832     (let ((exports (%package-external-symbols package)))
833       (dolist (symb symbols t)
834         (oset exports (symbol-name symb) symb))))
835
836   (defun get-universal-time ()
837     (+ (get-unix-time) 2208988800)))
838
839
840 ;;; The compiler offers some primitives and special forms which are
841 ;;; not found in Common Lisp, for instance, while. So, we grow Common
842 ;;; Lisp a bit to it can execute the rest of the file.
843 #+common-lisp
844 (progn
845   (defmacro while (condition &body body)
846     `(do ()
847          ((not ,condition))
848        ,@body))
849
850   (defmacro eval-when-compile (&body body)
851     `(eval-when (:compile-toplevel :load-toplevel :execute)
852        ,@body))
853
854   (defun concat-two (s1 s2)
855     (concatenate 'string s1 s2))
856
857   (defun aset (array idx value)
858     (setf (aref array idx) value)))
859
860 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
861 ;;; from here, this code will compile on both. We define some helper
862 ;;; functions now for string manipulation and so on. They will be
863 ;;; useful in the compiler, mostly.
864
865 (defvar *newline* (string (code-char 10)))
866
867 (defun concat (&rest strs)
868   (!reduce #'concat-two strs :initial-value ""))
869
870 (defmacro concatf (variable &body form)
871   `(setq ,variable (concat ,variable (progn ,@form))))
872
873 ;;; Concatenate a list of strings, with a separator
874 (defun join (list &optional (separator ""))
875   (cond
876     ((null list)
877      "")
878     ((null (cdr list))
879      (car list))
880     (t
881      (concat (car list)
882              separator
883              (join (cdr list) separator)))))
884
885 (defun join-trailing (list &optional (separator ""))
886   (if (null list)
887       ""
888       (concat (car list) separator (join-trailing (cdr list) separator))))
889
890 (defun mapconcat (func list)
891   (join (mapcar func list)))
892
893 (defun vector-to-list (vector)
894   (let ((list nil)
895         (size (length vector)))
896     (dotimes (i size (reverse list))
897       (push (aref vector i) list))))
898
899 (defun list-to-vector (list)
900   (let ((v (make-array (length list)))
901         (i 0))
902     (dolist (x list v)
903       (aset v i x)
904       (incf i))))
905
906 #+ecmalisp
907 (progn
908   (defun values-list (list)
909     (values-array (list-to-vector list)))
910
911   (defun values (&rest args)
912     (values-list args)))
913
914 (defun integer-to-string (x)
915   (cond
916     ((zerop x)
917      "0")
918     ((minusp x)
919      (concat "-" (integer-to-string (- 0 x))))
920     (t
921      (let ((digits nil))
922        (while (not (zerop x))
923          (push (mod x 10) digits)
924          (setq x (truncate x 10)))
925        (mapconcat (lambda (x) (string (digit-char x)))
926                   digits)))))
927
928
929 ;;; Printer
930
931 #+ecmalisp
932 (progn
933   (defun prin1-to-string (form)
934     (cond
935       ((symbolp form)
936        (multiple-value-bind (symbol foundp)
937            (find-symbol (symbol-name form) *package*)
938          (if (and foundp (eq symbol form))
939              (symbol-name form)
940              (let ((package (symbol-package form))
941                    (name (symbol-name form)))
942                (concat (cond
943                          ((null package) "#")
944                          ((eq package (find-package "KEYWORD")) "")
945                          (t (package-name package)))
946                        ":" name)))))
947       ((integerp form) (integer-to-string form))
948       ((stringp form) (concat "\"" (escape-string form) "\""))
949       ((functionp form)
950        (let ((name (oget form "fname")))
951          (if name
952              (concat "#<FUNCTION " name ">")
953              (concat "#<FUNCTION>"))))
954       ((listp form)
955        (concat "("
956                (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
957                (let ((last (last form)))
958                  (if (null (cdr last))
959                      (prin1-to-string (car last))
960                      (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
961                ")"))
962       ((arrayp form)
963        (concat "#" (if (zerop (length form))
964                        "()"
965                        (prin1-to-string (vector-to-list form)))))
966       ((packagep form)
967        (concat "#<PACKAGE " (package-name form) ">"))))
968
969   (defun write-line (x)
970     (write-string x)
971     (write-string *newline*)
972     x)
973
974   (defun warn (string)
975     (write-string "WARNING: ")
976     (write-line string))
977
978   (defun print (x)
979     (write-line (prin1-to-string x))
980     x))
981
982
983
984 ;;;; Reader
985
986 ;;; The Lisp reader, parse strings and return Lisp objects. The main
987 ;;; entry points are `ls-read' and `ls-read-from-string'.
988
989 (defun make-string-stream (string)
990   (cons string 0))
991
992 (defun %peek-char (stream)
993   (and (< (cdr stream) (length (car stream)))
994        (char (car stream) (cdr stream))))
995
996 (defun %read-char (stream)
997   (and (< (cdr stream) (length (car stream)))
998        (prog1 (char (car stream) (cdr stream))
999          (rplacd stream (1+ (cdr stream))))))
1000
1001 (defun whitespacep (ch)
1002   (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
1003
1004 (defun skip-whitespaces (stream)
1005   (let (ch)
1006     (setq ch (%peek-char stream))
1007     (while (and ch (whitespacep ch))
1008       (%read-char stream)
1009       (setq ch (%peek-char stream)))))
1010
1011 (defun terminalp (ch)
1012   (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
1013
1014 (defun read-until (stream func)
1015   (let ((string "")
1016         (ch))
1017     (setq ch (%peek-char stream))
1018     (while (and ch (not (funcall func ch)))
1019       (setq string (concat string (string ch)))
1020       (%read-char stream)
1021       (setq ch (%peek-char stream)))
1022     string))
1023
1024 (defun skip-whitespaces-and-comments (stream)
1025   (let (ch)
1026     (skip-whitespaces stream)
1027     (setq ch (%peek-char stream))
1028     (while (and ch (char= ch #\;))
1029       (read-until stream (lambda (x) (char= x #\newline)))
1030       (skip-whitespaces stream)
1031       (setq ch (%peek-char stream)))))
1032
1033 (defun %read-list (stream)
1034   (skip-whitespaces-and-comments stream)
1035   (let ((ch (%peek-char stream)))
1036     (cond
1037       ((null ch)
1038        (error "Unspected EOF"))
1039       ((char= ch #\))
1040        (%read-char stream)
1041        nil)
1042       ((char= ch #\.)
1043        (%read-char stream)
1044        (prog1 (ls-read stream)
1045          (skip-whitespaces-and-comments stream)
1046          (unless (char= (%read-char stream) #\))
1047            (error "')' was expected."))))
1048       (t
1049        (cons (ls-read stream) (%read-list stream))))))
1050
1051 (defun read-string (stream)
1052   (let ((string "")
1053         (ch nil))
1054     (setq ch (%read-char stream))
1055     (while (not (eql ch #\"))
1056       (when (null ch)
1057         (error "Unexpected EOF"))
1058       (when (eql ch #\\)
1059         (setq ch (%read-char stream)))
1060       (setq string (concat string (string ch)))
1061       (setq ch (%read-char stream)))
1062     string))
1063
1064 (defun read-sharp (stream)
1065   (%read-char stream)
1066   (ecase (%read-char stream)
1067     (#\'
1068      (list 'function (ls-read stream)))
1069     (#\( (list-to-vector (%read-list stream)))
1070     (#\: (make-symbol (string-upcase (read-until stream #'terminalp))))
1071     (#\\
1072      (let ((cname
1073             (concat (string (%read-char stream))
1074                     (read-until stream #'terminalp))))
1075        (cond
1076          ((string= cname "space") (char-code #\space))
1077          ((string= cname "tab") (char-code #\tab))
1078          ((string= cname "newline") (char-code #\newline))
1079          (t (char-code (char cname 0))))))
1080     (#\+
1081      (let ((feature (read-until stream #'terminalp)))
1082        (cond
1083          ((string= feature "common-lisp")
1084           (ls-read stream)              ;ignore
1085           (ls-read stream))
1086          ((string= feature "ecmalisp")
1087           (ls-read stream))
1088          (t
1089           (error "Unknown reader form.")))))))
1090
1091 ;;; Parse a string of the form NAME, PACKAGE:NAME or
1092 ;;; PACKAGE::NAME and return the name. If the string is of the
1093 ;;; form 1) or 3), but the symbol does not exist, it will be created
1094 ;;; and interned in that package.
1095 (defun read-symbol (string)
1096   (let ((size (length string))
1097         package name internalp index)
1098     (setq index 0)
1099     (while (and (< index size)
1100                 (not (char= (char string index) #\:)))
1101       (incf index))
1102     (cond
1103       ;; No package prefix
1104       ((= index size)
1105        (setq name string)
1106        (setq package *package*)
1107        (setq internalp t))
1108       (t
1109        ;; Package prefix
1110        (if (zerop index)
1111            (setq package "KEYWORD")
1112            (setq package (string-upcase (subseq string 0 index))))
1113        (incf index)
1114        (when (char= (char string index) #\:)
1115          (setq internalp t)
1116          (incf index))
1117        (setq name (subseq string index))))
1118     ;; Canonalize symbol name and package
1119     (when (not (eq package "JS"))
1120       (setq name (string-upcase name)))
1121     (setq package (find-package package))
1122     ;; TODO: PACKAGE:SYMBOL should signal error if SYMBOL is not an
1123     ;; external symbol from PACKAGE.
1124     (if (or internalp (eq package (or (find-package "KEYWORD")
1125                                       (find-package "JS"))))
1126         (intern name package)
1127         (find-symbol name package))))
1128
1129
1130 (defun !parse-integer (string junk-allow)
1131   (block nil
1132     (let ((value 0)
1133           (index 0)
1134           (size (length string))
1135           (sign 1))
1136       (when (zerop size) (return (values nil 0)))
1137       ;; Optional sign
1138       (case (char string 0)
1139         (#\+ (incf index))
1140         (#\- (setq sign -1)
1141              (incf index)))
1142       ;; First digit
1143       (unless (and (< index size)
1144                    (setq value (digit-char-p (char string index))))
1145         (return (values nil index)))
1146       (incf index)
1147       ;; Other digits
1148       (while (< index size)
1149         (let ((digit (digit-char-p (char string index))))
1150           (unless digit (return))
1151           (setq value (+ (* value 10) digit))
1152           (incf index)))
1153       (if (or junk-allow
1154               (= index size)
1155               (char= (char string index) #\space))
1156           (values (* sign value) index)
1157           (values nil index)))))
1158
1159 #+ecmalisp
1160 (defun parse-integer (string)
1161   (!parse-integer string nil))
1162
1163 (defvar *eof* (gensym))
1164 (defun ls-read (stream)
1165   (skip-whitespaces-and-comments stream)
1166   (let ((ch (%peek-char stream)))
1167     (cond
1168       ((or (null ch) (char= ch #\)))
1169        *eof*)
1170       ((char= ch #\()
1171        (%read-char stream)
1172        (%read-list stream))
1173       ((char= ch #\')
1174        (%read-char stream)
1175        (list 'quote (ls-read stream)))
1176       ((char= ch #\`)
1177        (%read-char stream)
1178        (list 'backquote (ls-read stream)))
1179       ((char= ch #\")
1180        (%read-char stream)
1181        (read-string stream))
1182       ((char= ch #\,)
1183        (%read-char stream)
1184        (if (eql (%peek-char stream) #\@)
1185            (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
1186            (list 'unquote (ls-read stream))))
1187       ((char= ch #\#)
1188        (read-sharp stream))
1189       (t
1190        (let ((string (read-until stream #'terminalp)))
1191          (or (values (!parse-integer string nil))
1192              (read-symbol string)))))))
1193
1194 (defun ls-read-from-string (string)
1195   (ls-read (make-string-stream string)))
1196
1197
1198 ;;;; Compiler
1199
1200 ;;; Translate the Lisp code to Javascript. It will compile the special
1201 ;;; forms. Some primitive functions are compiled as special forms
1202 ;;; too. The respective real functions are defined in the target (see
1203 ;;; the beginning of this file) as well as some primitive functions.
1204
1205 (defun code (&rest args)
1206   (mapconcat (lambda (arg)
1207                (cond
1208                  ((null arg) "")
1209                  ((integerp arg) (integer-to-string arg))
1210                  ((stringp arg) arg)
1211                  (t (error "Unknown argument."))))
1212              args))
1213
1214 ;;; Wrap X with a Javascript code to convert the result from
1215 ;;; Javascript generalized booleans to T or NIL.
1216 (defun js!bool (x)
1217   (code "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
1218
1219 ;;; Concatenate the arguments and wrap them with a self-calling
1220 ;;; Javascript anonymous function. It is used to make some Javascript
1221 ;;; statements valid expressions and provide a private scope as well.
1222 ;;; It could be defined as function, but we could do some
1223 ;;; preprocessing in the future.
1224 (defmacro js!selfcall (&body body)
1225   `(code "(function(){" *newline* (indent ,@body) "})()"))
1226
1227 ;;; Like CODE, but prefix each line with four spaces. Two versions
1228 ;;; of this function are available, because the Ecmalisp version is
1229 ;;; very slow and bootstraping was annoying.
1230
1231 #+ecmalisp
1232 (defun indent (&rest string)
1233   (let ((input (apply #'code string)))
1234     (let ((output "")
1235           (index 0)
1236           (size (length input)))
1237       (when (plusp (length input)) (concatf output "    "))
1238       (while (< index size)
1239         (let ((str
1240                (if (and (char= (char input index) #\newline)
1241                         (< index (1- size))
1242                         (not (char= (char input (1+ index)) #\newline)))
1243                    (concat (string #\newline) "    ")
1244                    (string (char input index)))))
1245           (concatf output str))
1246         (incf index))
1247       output)))
1248
1249 #+common-lisp
1250 (defun indent (&rest string)
1251   (with-output-to-string (*standard-output*)
1252     (with-input-from-string (input (apply #'code string))
1253       (loop
1254          for line = (read-line input nil)
1255          while line
1256          do (write-string "    ")
1257          do (write-line line)))))
1258
1259
1260 ;;; A Form can return a multiple values object calling VALUES, like
1261 ;;; values(arg1, arg2, ...). It will work in any context, as well as
1262 ;;; returning an individual object. However, if the special variable
1263 ;;; `*multiple-value-p*' is NIL, is granted that only the primary
1264 ;;; value will be used, so we can optimize to avoid the VALUES
1265 ;;; function call.
1266 (defvar *multiple-value-p* nil)
1267
1268 (defun make-binding (name type value &optional declarations)
1269   (list name type value declarations))
1270
1271 (defun binding-name (b) (first b))
1272 (defun binding-type (b) (second b))
1273 (defun binding-value (b) (third b))
1274 (defun binding-declarations (b) (fourth b))
1275
1276 (defun set-binding-value (b value)
1277   (rplaca (cddr b) value))
1278
1279 (defun set-binding-declarations (b value)
1280   (rplaca (cdddr b) value))
1281
1282 (defun push-binding-declaration (decl b)
1283   (set-binding-declarations b (cons decl (binding-declarations b))))
1284
1285
1286 (defun make-lexenv ()
1287   (list nil nil nil nil))
1288
1289 (defun copy-lexenv (lexenv)
1290   (copy-list lexenv))
1291
1292 (defun push-to-lexenv (binding lexenv namespace)
1293   (ecase namespace
1294     (variable   (rplaca        lexenv  (cons binding (car lexenv))))
1295     (function   (rplaca   (cdr lexenv) (cons binding (cadr lexenv))))
1296     (block      (rplaca  (cddr lexenv) (cons binding (caddr lexenv))))
1297     (gotag      (rplaca (cdddr lexenv) (cons binding (cadddr lexenv))))))
1298
1299 (defun extend-lexenv (bindings lexenv namespace)
1300   (let ((env (copy-lexenv lexenv)))
1301     (dolist (binding (reverse bindings) env)
1302       (push-to-lexenv binding env namespace))))
1303
1304 (defun lookup-in-lexenv (name lexenv namespace)
1305   (assoc name (ecase namespace
1306                 (variable (first lexenv))
1307                 (function (second lexenv))
1308                 (block (third lexenv))
1309                 (gotag (fourth lexenv)))))
1310
1311 (defvar *environment* (make-lexenv))
1312
1313 (defvar *variable-counter* 0)
1314
1315 (defun gvarname (symbol)
1316   (code "v" (incf *variable-counter*)))
1317
1318 (defun translate-variable (symbol)
1319   (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
1320
1321 (defun extend-local-env (args)
1322   (let ((new (copy-lexenv *environment*)))
1323     (dolist (symbol args new)
1324       (let ((b (make-binding symbol 'variable (gvarname symbol))))
1325         (push-to-lexenv b new 'variable)))))
1326
1327 ;;; Toplevel compilations
1328 (defvar *toplevel-compilations* nil)
1329
1330 (defun toplevel-compilation (string)
1331   (push string *toplevel-compilations*))
1332
1333 (defun null-or-empty-p (x)
1334   (zerop (length x)))
1335
1336 (defun get-toplevel-compilations ()
1337   (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
1338
1339 (defun %compile-defmacro (name lambda)
1340   (toplevel-compilation (ls-compile `',name))
1341   (push-to-lexenv (make-binding name 'macro lambda) *environment* 'function)
1342   name)
1343
1344 (defun global-binding (name type namespace)
1345   (or (lookup-in-lexenv name *environment* namespace)
1346       (let ((b (make-binding name type nil)))
1347         (push-to-lexenv b *environment* namespace)
1348         b)))
1349
1350 (defun claimp (symbol namespace claim)
1351   (let ((b (lookup-in-lexenv symbol *environment* namespace)))
1352     (and b (member claim (binding-declarations b)))))
1353
1354 (defun !proclaim (decl)
1355   (case (car decl)
1356     (special
1357      (dolist (name (cdr decl))
1358        (let ((b (global-binding name 'variable 'variable)))
1359          (push-binding-declaration 'special b))))
1360     (notinline
1361      (dolist (name (cdr decl))
1362        (let ((b (global-binding name 'function 'function)))
1363          (push-binding-declaration 'notinline b))))
1364     (constant
1365      (dolist (name (cdr decl))
1366        (let ((b (global-binding name 'variable 'variable)))
1367          (push-binding-declaration 'constant b))))))
1368
1369 #+ecmalisp
1370 (fset 'proclaim #'!proclaim)
1371
1372 ;;; Special forms
1373
1374 (defvar *compilations* nil)
1375
1376 (defmacro define-compilation (name args &body body)
1377   ;; Creates a new primitive `name' with parameters args and
1378   ;; @body. The body can access to the local environment through the
1379   ;; variable *ENVIRONMENT*.
1380   `(push (list ',name (lambda ,args (block ,name ,@body)))
1381          *compilations*))
1382
1383 (define-compilation if (condition true false)
1384   (code "(" (ls-compile condition) " !== " (ls-compile nil)
1385         " ? " (ls-compile true *multiple-value-p*)
1386         " : " (ls-compile false *multiple-value-p*)
1387         ")"))
1388
1389 (defvar *ll-keywords* '(&optional &rest &key))
1390
1391 (defun list-until-keyword (list)
1392   (if (or (null list) (member (car list) *ll-keywords*))
1393       nil
1394       (cons (car list) (list-until-keyword (cdr list)))))
1395
1396 (defun ll-section (keyword ll)
1397   (list-until-keyword (cdr (member keyword ll))))
1398
1399 (defun ll-required-arguments (ll)
1400   (list-until-keyword ll))
1401
1402 (defun ll-optional-arguments-canonical (ll)
1403   (mapcar #'ensure-list (ll-section '&optional ll)))
1404
1405 (defun ll-optional-arguments (ll)
1406   (mapcar #'car (ll-optional-arguments-canonical ll)))
1407
1408 (defun ll-rest-argument (ll)
1409   (let ((rest (ll-section '&rest ll)))
1410     (when (cdr rest)
1411       (error "Bad lambda-list"))
1412     (car rest)))
1413
1414 (defun ll-keyword-arguments-canonical (ll)
1415   (flet ((canonicalize (keyarg)
1416            ;; Build a canonical keyword argument descriptor, filling
1417            ;; the optional fields. The result is a list of the form
1418            ;; ((keyword-name var) init-form).
1419            (let ((arg (ensure-list keyarg)))
1420              (cons (if (listp (car arg))
1421                        (car arg)
1422                        (list (intern (symbol-name (car arg)) "KEYWORD") (car arg)))
1423                    (cdr arg)))))
1424     (mapcar #'canonicalize (ll-section '&key ll))))
1425
1426 (defun ll-keyword-arguments (ll)
1427   (mapcar (lambda (keyarg) (second (first keyarg)))
1428           (ll-keyword-arguments-canonical ll)))
1429
1430 (defun ll-svars (lambda-list)
1431   (let ((args
1432          (append
1433           (ll-keyword-arguments-canonical lambda-list)
1434           (ll-optional-arguments-canonical lambda-list))))
1435     (remove nil (mapcar #'third args))))
1436
1437 (defun lambda-docstring-wrapper (docstring &rest strs)
1438   (if docstring
1439       (js!selfcall
1440         "var func = " (join strs) ";" *newline*
1441         "func.docstring = '" docstring "';" *newline*
1442         "return func;" *newline*)
1443       (apply #'code strs)))
1444
1445 (defun lambda-check-argument-count
1446     (n-required-arguments n-optional-arguments rest-p)
1447   ;; Note: Remember that we assume that the number of arguments of a
1448   ;; call is at least 1 (the values argument).
1449   (let ((min (1+ n-required-arguments))
1450         (max (if rest-p 'n/a (+ 1 n-required-arguments n-optional-arguments))))
1451     (block nil
1452       ;; Special case: a positive exact number of arguments.
1453       (when (and (< 1 min) (eql min max))
1454         (return (code "checkArgs(arguments, " min ");" *newline*)))
1455       ;; General case:
1456       (code
1457        (when (< 1 min)
1458          (code "checkArgsAtLeast(arguments, " min ");" *newline*))
1459        (when (numberp max)
1460          (code "checkArgsAtMost(arguments, " max ");" *newline*))))))
1461
1462 (defun compile-lambda-optional (ll)
1463   (let* ((optional-arguments (ll-optional-arguments-canonical ll))
1464          (n-required-arguments (length (ll-required-arguments ll)))
1465          (n-optional-arguments (length optional-arguments)))
1466     (when optional-arguments
1467       (code (mapconcat (lambda (arg)
1468                          (code "var " (translate-variable (first arg)) "; " *newline*
1469                                (when (third arg)
1470                                  (code "var " (translate-variable (third arg))
1471                                        " = " (ls-compile t)
1472                                        "; " *newline*))))
1473                        optional-arguments)
1474             "switch(arguments.length-1){" *newline*
1475             (let ((cases nil)
1476                   (idx 0))
1477               (progn
1478                 (while (< idx n-optional-arguments)
1479                   (let ((arg (nth idx optional-arguments)))
1480                     (push (code "case " (+ idx n-required-arguments) ":" *newline*
1481                                 (indent (translate-variable (car arg))
1482                                         "="
1483                                         (ls-compile (cadr arg)) ";" *newline*)
1484                                 (when (third arg)
1485                                   (indent (translate-variable (third arg))
1486                                           "="
1487                                           (ls-compile nil)
1488                                           ";" *newline*)))
1489                           cases)
1490                     (incf idx)))
1491                 (push (code "default: break;" *newline*) cases)
1492                 (join (reverse cases))))
1493             "}" *newline*))))
1494
1495 (defun compile-lambda-rest (ll)
1496   (let ((n-required-arguments (length (ll-required-arguments ll)))
1497         (n-optional-arguments (length (ll-optional-arguments ll)))
1498         (rest-argument (ll-rest-argument ll)))
1499     (when rest-argument
1500       (let ((js!rest (translate-variable rest-argument)))
1501         (code "var " js!rest "= " (ls-compile nil) ";" *newline*
1502               "for (var i = arguments.length-1; i>="
1503               (+ 1 n-required-arguments n-optional-arguments)
1504               "; i--)" *newline*
1505               (indent js!rest " = {car: arguments[i], cdr: ") js!rest "};"
1506               *newline*)))))
1507
1508 (defun compile-lambda-parse-keywords (ll)
1509   (let ((n-required-arguments
1510          (length (ll-required-arguments ll)))
1511         (n-optional-arguments
1512          (length (ll-optional-arguments ll)))
1513         (keyword-arguments
1514          (ll-keyword-arguments-canonical ll)))
1515     (code
1516      ;; Declare variables
1517      (mapconcat (lambda (arg)
1518                   (let ((var (second (car arg))))
1519                     (code "var " (translate-variable var) "; " *newline*
1520                           (when (third arg)
1521                             (code "var " (translate-variable (third arg))
1522                                   " = " (ls-compile nil)
1523                                   ";" *newline*)))))
1524                 keyword-arguments)
1525      ;; Parse keywords
1526      (flet ((parse-keyword (keyarg)
1527               ;; ((keyword-name var) init-form)
1528               (code "for (i=" (+ 1 n-required-arguments n-optional-arguments)
1529                     "; i<arguments.length; i+=2){" *newline*
1530                     (indent
1531                      "if (arguments[i] === " (ls-compile (caar keyarg)) "){" *newline*
1532                      (indent (translate-variable (cadr (car keyarg)))
1533                              " = arguments[i+1];"
1534                              *newline*
1535                              (let ((svar (third keyarg)))
1536                                (when svar
1537                                  (code (translate-variable svar) " = " (ls-compile t) ";" *newline*)))
1538                              "break;" *newline*)
1539                      "}" *newline*)
1540                     "}" *newline*
1541                     ;; Default value
1542                     "if (i == arguments.length){" *newline*
1543                     (indent (translate-variable (cadr (car keyarg))) " = " (ls-compile (cadr keyarg)) ";" *newline*)
1544                     "}" *newline*)))
1545        (when keyword-arguments
1546          (code "var i;" *newline*
1547                (mapconcat #'parse-keyword keyword-arguments))))
1548      ;; Check for unknown keywords
1549      (when keyword-arguments
1550        (code "for (i=" (+ 1 n-required-arguments n-optional-arguments)
1551              "; i<arguments.length; i+=2){" *newline*
1552              (indent "if ("
1553                      (join (mapcar (lambda (x)
1554                                      (concat "arguments[i] !== " (ls-compile (caar x))))
1555                                    keyword-arguments)
1556                            " && ")
1557                      ")" *newline*
1558                      (indent
1559                       "throw 'Unknown keyword argument ' + arguments[i].name;" *newline*))
1560              "}" *newline*)))))
1561
1562 (defun compile-lambda (ll body)
1563   (let ((required-arguments (ll-required-arguments ll))
1564         (optional-arguments (ll-optional-arguments ll))
1565         (keyword-arguments  (ll-keyword-arguments  ll))
1566         (rest-argument      (ll-rest-argument      ll))
1567         documentation)
1568     ;; Get the documentation string for the lambda function
1569     (when (and (stringp (car body))
1570                (not (null (cdr body))))
1571       (setq documentation (car body))
1572       (setq body (cdr body)))
1573     (let ((n-required-arguments (length required-arguments))
1574           (n-optional-arguments (length optional-arguments))
1575           (*environment* (extend-local-env
1576                           (append (ensure-list rest-argument)
1577                                   required-arguments
1578                                   optional-arguments
1579                                   keyword-arguments
1580                                   (ll-svars ll)))))
1581       (lambda-docstring-wrapper
1582        documentation
1583        "(function ("
1584        (join (cons "values"
1585                    (mapcar #'translate-variable
1586                            (append required-arguments optional-arguments)))
1587              ",")
1588        "){" *newline*
1589        (indent
1590         ;; Check number of arguments
1591         (lambda-check-argument-count n-required-arguments
1592                                      n-optional-arguments
1593                                      (or rest-argument keyword-arguments))
1594         (compile-lambda-optional ll)
1595         (compile-lambda-rest ll)
1596         (compile-lambda-parse-keywords ll)
1597         (let ((*multiple-value-p* t))
1598           (ls-compile-block body t)))
1599        "})"))))
1600
1601
1602
1603 (defun setq-pair (var val)
1604   (let ((b (lookup-in-lexenv var *environment* 'variable)))
1605     (if (and (eq (binding-type b) 'variable)
1606              (not (member 'special (binding-declarations b)))
1607              (not (member 'constant (binding-declarations b))))
1608         (code (binding-value b) " = " (ls-compile val))
1609         (ls-compile `(set ',var ,val)))))
1610
1611 (define-compilation setq (&rest pairs)
1612   (let ((result ""))
1613     (while t
1614       (cond
1615         ((null pairs) (return))
1616         ((null (cdr pairs))
1617          (error "Odd paris in SETQ"))
1618         (t
1619          (concatf result
1620            (concat (setq-pair (car pairs) (cadr pairs))
1621                    (if (null (cddr pairs)) "" ", ")))
1622          (setq pairs (cddr pairs)))))
1623     (code "(" result ")")))
1624
1625 ;;; FFI Variable accessors
1626 (define-compilation js-vref (var)
1627   var)
1628
1629 (define-compilation js-vset (var val)
1630   (code "(" var " = " (ls-compile val) ")"))
1631
1632
1633 ;;; Literals
1634 (defun escape-string (string)
1635   (let ((output "")
1636         (index 0)
1637         (size (length string)))
1638     (while (< index size)
1639       (let ((ch (char string index)))
1640         (when (or (char= ch #\") (char= ch #\\))
1641           (setq output (concat output "\\")))
1642         (when (or (char= ch #\newline))
1643           (setq output (concat output "\\"))
1644           (setq ch #\n))
1645         (setq output (concat output (string ch))))
1646       (incf index))
1647     output))
1648
1649
1650 (defvar *literal-symbols* nil)
1651 (defvar *literal-counter* 0)
1652
1653 (defun genlit ()
1654   (code "l" (incf *literal-counter*)))
1655
1656 (defun literal (sexp &optional recursive)
1657   (cond
1658     ((integerp sexp) (integer-to-string sexp))
1659     ((stringp sexp) (code "\"" (escape-string sexp) "\""))
1660     ((symbolp sexp)
1661      (or (cdr (assoc sexp *literal-symbols*))
1662          (let ((v (genlit))
1663                (s #+common-lisp
1664                  (let ((package (symbol-package sexp)))
1665                    (if (eq package (find-package "KEYWORD"))
1666                        (code "{name: \"" (escape-string (symbol-name sexp))
1667                              "\", 'package': '" (package-name package) "'}")
1668                        (code "{name: \"" (escape-string (symbol-name sexp)) "\"}")))
1669                  #+ecmalisp
1670                  (let ((package (symbol-package sexp)))
1671                    (if (null package)
1672                        (code "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1673                        (ls-compile `(intern ,(symbol-name sexp) ,(package-name package)))))))
1674            (push (cons sexp v) *literal-symbols*)
1675            (toplevel-compilation (code "var " v " = " s))
1676            v)))
1677     ((consp sexp)
1678      (let* ((head (butlast sexp))
1679             (tail (last sexp))
1680             (c (code "QIList("
1681                      (join-trailing (mapcar (lambda (x) (literal x t)) head) ",")
1682                      (literal (car tail) t)
1683                      ","
1684                      (literal (cdr tail) t)
1685                      ")")))
1686        (if recursive
1687            c
1688            (let ((v (genlit)))
1689              (toplevel-compilation (code "var " v " = " c))
1690              v))))
1691     ((arrayp sexp)
1692      (let ((elements (vector-to-list sexp)))
1693        (let ((c (concat "[" (join (mapcar #'literal elements) ", ") "]")))
1694          (if recursive
1695              c
1696              (let ((v (genlit)))
1697                (toplevel-compilation (code "var " v " = " c))
1698                v)))))))
1699
1700 (define-compilation quote (sexp)
1701   (literal sexp))
1702
1703 (define-compilation %while (pred &rest body)
1704   (js!selfcall
1705     "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1706     (indent (ls-compile-block body))
1707     "}"
1708     "return " (ls-compile nil) ";" *newline*))
1709
1710 (define-compilation function (x)
1711   (cond
1712     ((and (listp x) (eq (car x) 'lambda))
1713      (compile-lambda (cadr x) (cddr x)))
1714     ((symbolp x)
1715      (let ((b (lookup-in-lexenv x *environment* 'function)))
1716        (if b
1717            (binding-value b)
1718            (ls-compile `(symbol-function ',x)))))))
1719
1720
1721 (defun make-function-binding (fname)
1722   (make-binding fname 'function (gvarname fname)))
1723
1724 (defun compile-function-definition (list)
1725   (compile-lambda (car list) (cdr list)))
1726
1727 (defun translate-function (name)
1728   (let ((b (lookup-in-lexenv name *environment* 'function)))
1729     (binding-value b)))
1730
1731 (define-compilation flet (definitions &rest body)
1732   (let* ((fnames (mapcar #'car definitions))
1733          (fbody  (mapcar #'cdr definitions))
1734          (cfuncs (mapcar #'compile-function-definition fbody))
1735          (*environment*
1736           (extend-lexenv (mapcar #'make-function-binding fnames)
1737                          *environment*
1738                          'function)))
1739     (code "(function("
1740           (join (mapcar #'translate-function fnames) ",")
1741           "){" *newline*
1742           (let ((body (ls-compile-block body t)))
1743             (indent body))
1744           "})(" (join cfuncs ",") ")")))
1745
1746 (define-compilation labels (definitions &rest body)
1747   (let* ((fnames (mapcar #'car definitions))
1748          (*environment*
1749           (extend-lexenv (mapcar #'make-function-binding fnames)
1750                          *environment*
1751                          'function)))
1752     (js!selfcall
1753       (mapconcat (lambda (func)
1754                    (code "var " (translate-function (car func))
1755                          " = " (compile-lambda (cadr func) (cddr func))
1756                          ";" *newline*))
1757                  definitions)
1758       (ls-compile-block body t))))
1759
1760
1761 (defvar *compiling-file* nil)
1762 (define-compilation eval-when-compile (&rest body)
1763   (if *compiling-file*
1764       (progn
1765         (eval (cons 'progn body))
1766         nil)
1767       (ls-compile `(progn ,@body))))
1768
1769 (defmacro define-transformation (name args form)
1770   `(define-compilation ,name ,args
1771      (ls-compile ,form)))
1772
1773 (define-compilation progn (&rest body)
1774   (if (null (cdr body))
1775       (ls-compile (car body) *multiple-value-p*)
1776       (js!selfcall (ls-compile-block body t))))
1777
1778 (defun special-variable-p (x)
1779   (and (claimp x 'variable 'special) t))
1780
1781 ;;; Wrap CODE to restore the symbol values of the dynamic
1782 ;;; bindings. BINDINGS is a list of pairs of the form
1783 ;;; (SYMBOL . PLACE),  where PLACE is a Javascript variable
1784 ;;; name to initialize the symbol value and where to stored
1785 ;;; the old value.
1786 (defun let-binding-wrapper (bindings body)
1787   (when (null bindings)
1788     (return-from let-binding-wrapper body))
1789   (code
1790    "try {" *newline*
1791    (indent "var tmp;" *newline*
1792            (mapconcat
1793             (lambda (b)
1794               (let ((s (ls-compile `(quote ,(car b)))))
1795                 (code "tmp = " s ".value;" *newline*
1796                       s ".value = " (cdr b) ";" *newline*
1797                       (cdr b) " = tmp;" *newline*)))
1798             bindings)
1799            body *newline*)
1800    "}" *newline*
1801    "finally {"  *newline*
1802    (indent
1803     (mapconcat (lambda (b)
1804                  (let ((s (ls-compile `(quote ,(car b)))))
1805                    (code s ".value" " = " (cdr b) ";" *newline*)))
1806                bindings))
1807    "}" *newline*))
1808
1809 (define-compilation let (bindings &rest body)
1810   (let* ((bindings (mapcar #'ensure-list bindings))
1811          (variables (mapcar #'first bindings))
1812          (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
1813          (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
1814          (dynamic-bindings))
1815     (code "(function("
1816           (join (mapcar (lambda (x)
1817                           (if (special-variable-p x)
1818                               (let ((v (gvarname x)))
1819                                 (push (cons x v) dynamic-bindings)
1820                                 v)
1821                               (translate-variable x)))
1822                         variables)
1823                 ",")
1824           "){" *newline*
1825           (let ((body (ls-compile-block body t)))
1826             (indent (let-binding-wrapper dynamic-bindings body)))
1827           "})(" (join cvalues ",") ")")))
1828
1829
1830 ;;; Return the code to initialize BINDING, and push it extending the
1831 ;;; current lexical environment if the variable is not special.
1832 (defun let*-initialize-value (binding)
1833   (let ((var (first binding))
1834         (value (second binding)))
1835     (if (special-variable-p var)
1836         (code (ls-compile `(setq ,var ,value)) ";" *newline*)
1837         (let* ((v (gvarname var))
1838                (b (make-binding var 'variable v)))
1839           (prog1 (code "var " v " = " (ls-compile value) ";" *newline*)
1840             (push-to-lexenv b *environment* 'variable))))))
1841
1842 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
1843 ;;; DOES NOT generate code to initialize the value of the symbols,
1844 ;;; unlike let-binding-wrapper.
1845 (defun let*-binding-wrapper (symbols body)
1846   (when (null symbols)
1847     (return-from let*-binding-wrapper body))
1848   (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
1849                        (remove-if-not #'special-variable-p symbols))))
1850     (code
1851      "try {" *newline*
1852      (indent
1853       (mapconcat (lambda (b)
1854                    (let ((s (ls-compile `(quote ,(car b)))))
1855                      (code "var " (cdr b) " = " s ".value;" *newline*)))
1856                  store)
1857       body)
1858      "}" *newline*
1859      "finally {" *newline*
1860      (indent
1861       (mapconcat (lambda (b)
1862                    (let ((s (ls-compile `(quote ,(car b)))))
1863                      (code s ".value" " = " (cdr b) ";" *newline*)))
1864                  store))
1865      "}" *newline*)))
1866
1867 (define-compilation let* (bindings &rest body)
1868   (let ((bindings (mapcar #'ensure-list bindings))
1869         (*environment* (copy-lexenv *environment*)))
1870     (js!selfcall
1871       (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
1872             (body (concat (mapconcat #'let*-initialize-value bindings)
1873                           (ls-compile-block body t))))
1874         (let*-binding-wrapper specials body)))))
1875
1876
1877 (defvar *block-counter* 0)
1878
1879 (define-compilation block (name &rest body)
1880   (let* ((tr (incf *block-counter*))
1881          (b (make-binding name 'block tr)))
1882     (when *multiple-value-p*
1883       (push-binding-declaration 'multiple-value b))
1884     (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
1885            (cbody (ls-compile-block body t)))
1886       (if (member 'used (binding-declarations b))
1887           (js!selfcall
1888             "try {" *newline*
1889             (indent cbody)
1890             "}" *newline*
1891             "catch (cf){" *newline*
1892             "    if (cf.type == 'block' && cf.id == " tr ")" *newline*
1893             (if *multiple-value-p*
1894                 "        return values.apply(this, forcemv(cf.values));"
1895                 "        return cf.values;")
1896             *newline*
1897             "    else" *newline*
1898             "        throw cf;" *newline*
1899             "}" *newline*)
1900           (js!selfcall cbody)))))
1901
1902 (define-compilation return-from (name &optional value)
1903   (let* ((b (lookup-in-lexenv name *environment* 'block))
1904          (multiple-value-p (member 'multiple-value (binding-declarations b))))
1905     (when (null b)
1906       (error (concat "Unknown block `" (symbol-name name) "'.")))
1907     (push-binding-declaration 'used b)
1908     (js!selfcall
1909       (when multiple-value-p (code "var values = mv;" *newline*))
1910       "throw ({"
1911       "type: 'block', "
1912       "id: " (binding-value b) ", "
1913       "values: " (ls-compile value multiple-value-p) ", "
1914       "message: 'Return from unknown block " (symbol-name name) ".'"
1915       "})")))
1916
1917 (define-compilation catch (id &rest body)
1918   (js!selfcall
1919     "var id = " (ls-compile id) ";" *newline*
1920     "try {" *newline*
1921     (indent (ls-compile-block body t)) *newline*
1922     "}" *newline*
1923     "catch (cf){" *newline*
1924     "    if (cf.type == 'catch' && cf.id == id)" *newline*
1925     (if *multiple-value-p*
1926         "        return values.apply(this, forcemv(cf.values));"
1927         "        return pv.apply(this, forcemv(cf.values));")
1928     *newline*
1929     "    else" *newline*
1930     "        throw cf;" *newline*
1931     "}" *newline*))
1932
1933 (define-compilation throw (id value)
1934   (js!selfcall
1935     "var values = mv;" *newline*
1936     "throw ({"
1937     "type: 'catch', "
1938     "id: " (ls-compile id) ", "
1939     "values: " (ls-compile value t) ", "
1940     "message: 'Throw uncatched.'"
1941     "})"))
1942
1943
1944 (defvar *tagbody-counter* 0)
1945 (defvar *go-tag-counter* 0)
1946
1947 (defun go-tag-p (x)
1948   (or (integerp x) (symbolp x)))
1949
1950 (defun declare-tagbody-tags (tbidx body)
1951   (let ((bindings
1952          (mapcar (lambda (label)
1953                    (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1954                      (make-binding label 'gotag (list tbidx tagidx))))
1955                  (remove-if-not #'go-tag-p body))))
1956     (extend-lexenv bindings *environment* 'gotag)))
1957
1958 (define-compilation tagbody (&rest body)
1959   ;; Ignore the tagbody if it does not contain any go-tag. We do this
1960   ;; because 1) it is easy and 2) many built-in forms expand to a
1961   ;; implicit tagbody, so we save some space.
1962   (unless (some #'go-tag-p body)
1963     (return-from tagbody (ls-compile `(progn ,@body nil))))
1964   ;; The translation assumes the first form in BODY is a label
1965   (unless (go-tag-p (car body))
1966     (push (gensym "START") body))
1967   ;; Tagbody compilation
1968   (let ((tbidx *tagbody-counter*))
1969     (let ((*environment* (declare-tagbody-tags tbidx body))
1970           initag)
1971       (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1972         (setq initag (second (binding-value b))))
1973       (js!selfcall
1974         "var tagbody_" tbidx " = " initag ";" *newline*
1975         "tbloop:" *newline*
1976         "while (true) {" *newline*
1977         (indent "try {" *newline*
1978                 (indent (let ((content ""))
1979                           (code "switch(tagbody_" tbidx "){" *newline*
1980                                 "case " initag ":" *newline*
1981                                 (dolist (form (cdr body) content)
1982                                   (concatf content
1983                                     (if (not (go-tag-p form))
1984                                         (indent (ls-compile form) ";" *newline*)
1985                                         (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1986                                           (code "case " (second (binding-value b)) ":" *newline*)))))
1987                                 "default:" *newline*
1988                                 "    break tbloop;" *newline*
1989                                 "}" *newline*)))
1990                 "}" *newline*
1991                 "catch (jump) {" *newline*
1992                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1993                 "        tagbody_" tbidx " = jump.label;" *newline*
1994                 "    else" *newline*
1995                 "        throw(jump);" *newline*
1996                 "}" *newline*)
1997         "}" *newline*
1998         "return " (ls-compile nil) ";" *newline*))))
1999
2000 (define-compilation go (label)
2001   (let ((b (lookup-in-lexenv label *environment* 'gotag))
2002         (n (cond
2003              ((symbolp label) (symbol-name label))
2004              ((integerp label) (integer-to-string label)))))
2005     (when (null b)
2006       (error (concat "Unknown tag `" n "'.")))
2007     (js!selfcall
2008       "throw ({"
2009       "type: 'tagbody', "
2010       "id: " (first (binding-value b)) ", "
2011       "label: " (second (binding-value b)) ", "
2012       "message: 'Attempt to GO to non-existing tag " n "'"
2013       "})" *newline*)))
2014
2015 (define-compilation unwind-protect (form &rest clean-up)
2016   (js!selfcall
2017     "var ret = " (ls-compile nil) ";" *newline*
2018     "try {" *newline*
2019     (indent "ret = " (ls-compile form) ";" *newline*)
2020     "} finally {" *newline*
2021     (indent (ls-compile-block clean-up))
2022     "}" *newline*
2023     "return ret;" *newline*))
2024
2025 (define-compilation multiple-value-call (func-form &rest forms)
2026   (js!selfcall
2027     "var func = " (ls-compile func-form) ";" *newline*
2028     "var args = [" (if *multiple-value-p* "values" "pv") "];" *newline*
2029     "return "
2030     (js!selfcall
2031       "var values = mv;" *newline*
2032       "var vs;" *newline*
2033       (mapconcat (lambda (form)
2034                    (code "vs = " (ls-compile form t) ";" *newline*
2035                          "if (typeof vs === 'object' && 'multiple-value' in vs)" *newline*
2036                          (indent "args = args.concat(vs);" *newline*)
2037                          "else" *newline*
2038                          (indent "args.push(vs);" *newline*)))
2039                  forms)
2040       "return func.apply(window, args);" *newline*) ";" *newline*))
2041
2042 (define-compilation multiple-value-prog1 (first-form &rest forms)
2043   (js!selfcall
2044     "var args = " (ls-compile first-form *multiple-value-p*) ";" *newline*
2045     (ls-compile-block forms)
2046     "return args;" *newline*))
2047
2048
2049 ;;; Backquote implementation.
2050 ;;;
2051 ;;;    Author: Guy L. Steele Jr.     Date: 27 December 1985
2052 ;;;    Tested under Symbolics Common Lisp and Lucid Common Lisp.
2053 ;;;    This software is in the public domain.
2054
2055 ;;;    The following are unique tokens used during processing.
2056 ;;;    They need not be symbols; they need not even be atoms.
2057 (defvar *comma* 'unquote)
2058 (defvar *comma-atsign* 'unquote-splicing)
2059
2060 (defvar *bq-list* (make-symbol "BQ-LIST"))
2061 (defvar *bq-append* (make-symbol "BQ-APPEND"))
2062 (defvar *bq-list** (make-symbol "BQ-LIST*"))
2063 (defvar *bq-nconc* (make-symbol "BQ-NCONC"))
2064 (defvar *bq-clobberable* (make-symbol "BQ-CLOBBERABLE"))
2065 (defvar *bq-quote* (make-symbol "BQ-QUOTE"))
2066 (defvar *bq-quote-nil* (list *bq-quote* nil))
2067
2068 ;;; BACKQUOTE is an ordinary macro (not a read-macro) that processes
2069 ;;; the expression foo, looking for occurrences of #:COMMA,
2070 ;;; #:COMMA-ATSIGN, and #:COMMA-DOT.  It constructs code in strict
2071 ;;; accordance with the rules on pages 349-350 of the first edition
2072 ;;; (pages 528-529 of this second edition).  It then optionally
2073 ;;; applies a code simplifier.
2074
2075 ;;; If the value of *BQ-SIMPLIFY* is non-NIL, then BACKQUOTE
2076 ;;; processing applies the code simplifier.  If the value is NIL,
2077 ;;; then the code resulting from BACKQUOTE is exactly that
2078 ;;; specified by the official rules.
2079 (defparameter *bq-simplify* t)
2080
2081 (defmacro backquote (x)
2082   (bq-completely-process x))
2083
2084 ;;; Backquote processing proceeds in three stages:
2085 ;;;
2086 ;;; (1) BQ-PROCESS applies the rules to remove occurrences of
2087 ;;; #:COMMA, #:COMMA-ATSIGN, and #:COMMA-DOT corresponding to
2088 ;;; this level of BACKQUOTE.  (It also causes embedded calls to
2089 ;;; BACKQUOTE to be expanded so that nesting is properly handled.)
2090 ;;; Code is produced that is expressed in terms of functions
2091 ;;; #:BQ-LIST, #:BQ-APPEND, and #:BQ-CLOBBERABLE.  This is done
2092 ;;; so that the simplifier will simplify only list construction
2093 ;;; functions actually generated by BACKQUOTE and will not involve
2094 ;;; any user code in the simplification.  #:BQ-LIST means LIST,
2095 ;;; #:BQ-APPEND means APPEND, and #:BQ-CLOBBERABLE means IDENTITY
2096 ;;; but indicates places where "%." was used and where NCONC may
2097 ;;; therefore be introduced by the simplifier for efficiency.
2098 ;;;
2099 ;;; (2) BQ-SIMPLIFY, if used, rewrites the code produced by
2100 ;;; BQ-PROCESS to produce equivalent but faster code.  The
2101 ;;; additional functions #:BQ-LIST* and #:BQ-NCONC may be
2102 ;;; introduced into the code.
2103 ;;;
2104 ;;; (3) BQ-REMOVE-TOKENS goes through the code and replaces
2105 ;;; #:BQ-LIST with LIST, #:BQ-APPEND with APPEND, and so on.
2106 ;;; #:BQ-CLOBBERABLE is simply eliminated (a call to it being
2107 ;;; replaced by its argument).  #:BQ-LIST* is replaced by either
2108 ;;; LIST* or CONS (the latter is used in the two-argument case,
2109 ;;; purely to make the resulting code a tad more readable).
2110
2111 (defun bq-completely-process (x)
2112   (let ((raw-result (bq-process x)))
2113     (bq-remove-tokens (if *bq-simplify*
2114                           (bq-simplify raw-result)
2115                           raw-result))))
2116
2117 (defun bq-process (x)
2118   (cond ((atom x)
2119          (list *bq-quote* x))
2120         ((eq (car x) 'backquote)
2121          (bq-process (bq-completely-process (cadr x))))
2122         ((eq (car x) *comma*) (cadr x))
2123         ((eq (car x) *comma-atsign*)
2124          ;; (error ",@~S after `" (cadr x))
2125          (error "ill-formed"))
2126         ;; ((eq (car x) *comma-dot*)
2127         ;;  ;; (error ",.~S after `" (cadr x))
2128         ;;  (error "ill-formed"))
2129         (t (do ((p x (cdr p))
2130                 (q '() (cons (bracket (car p)) q)))
2131                ((atom p)
2132                 (cons *bq-append*
2133                       (nreconc q (list (list *bq-quote* p)))))
2134              (when (eq (car p) *comma*)
2135                (unless (null (cddr p))
2136                  ;; (error "Malformed ,~S" p)
2137                  (error "Malformed"))
2138                (return (cons *bq-append*
2139                              (nreconc q (list (cadr p))))))
2140              (when (eq (car p) *comma-atsign*)
2141                ;; (error "Dotted ,@~S" p)
2142                (error "Dotted"))
2143              ;; (when (eq (car p) *comma-dot*)
2144              ;;   ;; (error "Dotted ,.~S" p)
2145              ;;   (error "Dotted"))
2146              ))))
2147
2148 ;;; This implements the bracket operator of the formal rules.
2149 (defun bracket (x)
2150   (cond ((atom x)
2151          (list *bq-list* (bq-process x)))
2152         ((eq (car x) *comma*)
2153          (list *bq-list* (cadr x)))
2154         ((eq (car x) *comma-atsign*)
2155          (cadr x))
2156         ;; ((eq (car x) *comma-dot*)
2157         ;;  (list *bq-clobberable* (cadr x)))
2158         (t (list *bq-list* (bq-process x)))))
2159
2160 ;;; This auxiliary function is like MAPCAR but has two extra
2161 ;;; purposes: (1) it handles dotted lists; (2) it tries to make
2162 ;;; the result share with the argument x as much as possible.
2163 (defun maptree (fn x)
2164   (if (atom x)
2165       (funcall fn x)
2166       (let ((a (funcall fn (car x)))
2167             (d (maptree fn (cdr x))))
2168         (if (and (eql a (car x)) (eql d (cdr x)))
2169             x
2170             (cons a d)))))
2171
2172 ;;; This predicate is true of a form that when read looked
2173 ;;; like %@foo or %.foo.
2174 (defun bq-splicing-frob (x)
2175   (and (consp x)
2176        (or (eq (car x) *comma-atsign*)
2177            ;; (eq (car x) *comma-dot*)
2178            )))
2179
2180 ;;; This predicate is true of a form that when read
2181 ;;; looked like %@foo or %.foo or just plain %foo.
2182 (defun bq-frob (x)
2183   (and (consp x)
2184        (or (eq (car x) *comma*)
2185            (eq (car x) *comma-atsign*)
2186            ;; (eq (car x) *comma-dot*)
2187            )))
2188
2189 ;;; The simplifier essentially looks for calls to #:BQ-APPEND and
2190 ;;; tries to simplify them.  The arguments to #:BQ-APPEND are
2191 ;;; processed from right to left, building up a replacement form.
2192 ;;; At each step a number of special cases are handled that,
2193 ;;; loosely speaking, look like this:
2194 ;;;
2195 ;;;  (APPEND (LIST a b c) foo) => (LIST* a b c foo)
2196 ;;;       provided a, b, c are not splicing frobs
2197 ;;;  (APPEND (LIST* a b c) foo) => (LIST* a b (APPEND c foo))
2198 ;;;       provided a, b, c are not splicing frobs
2199 ;;;  (APPEND (QUOTE (x)) foo) => (LIST* (QUOTE x) foo)
2200 ;;;  (APPEND (CLOBBERABLE x) foo) => (NCONC x foo)
2201 (defun bq-simplify (x)
2202   (if (atom x)
2203       x
2204       (let ((x (if (eq (car x) *bq-quote*)
2205                    x
2206                    (maptree #'bq-simplify x))))
2207         (if (not (eq (car x) *bq-append*))
2208             x
2209             (bq-simplify-args x)))))
2210
2211 (defun bq-simplify-args (x)
2212   (do ((args (reverse (cdr x)) (cdr args))
2213        (result
2214          nil
2215          (cond ((atom (car args))
2216                 (bq-attach-append *bq-append* (car args) result))
2217                ((and (eq (caar args) *bq-list*)
2218                      (notany #'bq-splicing-frob (cdar args)))
2219                 (bq-attach-conses (cdar args) result))
2220                ((and (eq (caar args) *bq-list**)
2221                      (notany #'bq-splicing-frob (cdar args)))
2222                 (bq-attach-conses
2223                   (reverse (cdr (reverse (cdar args))))
2224                   (bq-attach-append *bq-append*
2225                                     (car (last (car args)))
2226                                     result)))
2227                ((and (eq (caar args) *bq-quote*)
2228                      (consp (cadar args))
2229                      (not (bq-frob (cadar args)))
2230                      (null (cddar args)))
2231                 (bq-attach-conses (list (list *bq-quote*
2232                                               (caadar args)))
2233                                   result))
2234                ((eq (caar args) *bq-clobberable*)
2235                 (bq-attach-append *bq-nconc* (cadar args) result))
2236                (t (bq-attach-append *bq-append*
2237                                     (car args)
2238                                     result)))))
2239       ((null args) result)))
2240
2241 (defun null-or-quoted (x)
2242   (or (null x) (and (consp x) (eq (car x) *bq-quote*))))
2243
2244 ;;; When BQ-ATTACH-APPEND is called, the OP should be #:BQ-APPEND
2245 ;;; or #:BQ-NCONC.  This produces a form (op item result) but
2246 ;;; some simplifications are done on the fly:
2247 ;;;
2248 ;;;  (op '(a b c) '(d e f g)) => '(a b c d e f g)
2249 ;;;  (op item 'nil) => item, provided item is not a splicable frob
2250 ;;;  (op item 'nil) => (op item), if item is a splicable frob
2251 ;;;  (op item (op a b c)) => (op item a b c)
2252 (defun bq-attach-append (op item result)
2253   (cond ((and (null-or-quoted item) (null-or-quoted result))
2254          (list *bq-quote* (append (cadr item) (cadr result))))
2255         ((or (null result) (equal result *bq-quote-nil*))
2256          (if (bq-splicing-frob item) (list op item) item))
2257         ((and (consp result) (eq (car result) op))
2258          (list* (car result) item (cdr result)))
2259         (t (list op item result))))
2260
2261 ;;; The effect of BQ-ATTACH-CONSES is to produce a form as if by
2262 ;;; `(LIST* ,@items ,result) but some simplifications are done
2263 ;;; on the fly.
2264 ;;;
2265 ;;;  (LIST* 'a 'b 'c 'd) => '(a b c . d)
2266 ;;;  (LIST* a b c 'nil) => (LIST a b c)
2267 ;;;  (LIST* a b c (LIST* d e f g)) => (LIST* a b c d e f g)
2268 ;;;  (LIST* a b c (LIST d e f g)) => (LIST a b c d e f g)
2269 (defun bq-attach-conses (items result)
2270   (cond ((and (every #'null-or-quoted items)
2271               (null-or-quoted result))
2272          (list *bq-quote*
2273                (append (mapcar #'cadr items) (cadr result))))
2274         ((or (null result) (equal result *bq-quote-nil*))
2275          (cons *bq-list* items))
2276         ((and (consp result)
2277               (or (eq (car result) *bq-list*)
2278                   (eq (car result) *bq-list**)))
2279          (cons (car result) (append items (cdr result))))
2280         (t (cons *bq-list** (append items (list result))))))
2281
2282 ;;; Removes funny tokens and changes (#:BQ-LIST* a b) into
2283 ;;; (CONS a b) instead of (LIST* a b), purely for readability.
2284 (defun bq-remove-tokens (x)
2285   (cond ((eq x *bq-list*) 'list)
2286         ((eq x *bq-append*) 'append)
2287         ((eq x *bq-nconc*) 'nconc)
2288         ((eq x *bq-list**) 'list*)
2289         ((eq x *bq-quote*) 'quote)
2290         ((atom x) x)
2291         ((eq (car x) *bq-clobberable*)
2292          (bq-remove-tokens (cadr x)))
2293         ((and (eq (car x) *bq-list**)
2294               (consp (cddr x))
2295               (null (cdddr x)))
2296          (cons 'cons (maptree #'bq-remove-tokens (cdr x))))
2297         (t (maptree #'bq-remove-tokens x))))
2298
2299 (define-transformation backquote (form)
2300   (bq-completely-process form))
2301
2302
2303 ;;; Primitives
2304
2305 (defvar *builtins* nil)
2306
2307 (defmacro define-raw-builtin (name args &body body)
2308   ;; Creates a new primitive function `name' with parameters args and
2309   ;; @body. The body can access to the local environment through the
2310   ;; variable *ENVIRONMENT*.
2311   `(push (list ',name (lambda ,args (block ,name ,@body)))
2312          *builtins*))
2313
2314 (defmacro define-builtin (name args &body body)
2315   `(define-raw-builtin ,name ,args
2316      (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
2317        ,@body)))
2318
2319 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
2320 (defmacro type-check (decls &body body)
2321   `(js!selfcall
2322      ,@(mapcar (lambda (decl)
2323                  `(code "var " ,(first decl) " = " ,(third decl) ";" *newline*))
2324                decls)
2325      ,@(mapcar (lambda (decl)
2326                  `(code "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
2327                         (indent "throw 'The value ' + "
2328                                 ,(first decl)
2329                                 " + ' is not a type "
2330                                 ,(second decl)
2331                                 ".';"
2332                                 *newline*)))
2333                decls)
2334      (code "return " (progn ,@body) ";" *newline*)))
2335
2336 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
2337 ;;; a variable which holds a list of forms. It will compile them and
2338 ;;; store the result in some Javascript variables. BODY is evaluated
2339 ;;; with ARGS bound to the list of these variables to generate the
2340 ;;; code which performs the transformation on these variables.
2341
2342 (defun variable-arity-call (args function)
2343   (unless (consp args)
2344     (error "ARGS must be a non-empty list"))
2345   (let ((counter 0)
2346         (fargs '())
2347         (prelude ""))
2348     (dolist (x args)
2349       (if (numberp x)
2350           (push (integer-to-string x) fargs)
2351           (let ((v (code "x" (incf counter))))
2352             (push v fargs)
2353             (concatf prelude
2354               (code "var " v " = " (ls-compile x) ";" *newline*
2355                     "if (typeof " v " !== 'number') throw 'Not a number!';"
2356                     *newline*)))))
2357     (js!selfcall prelude (funcall function (reverse fargs)))))
2358
2359
2360 (defmacro variable-arity (args &body body)
2361   (unless (symbolp args)
2362     (error "Bad usage of VARIABLE-ARITY, you must pass a symbol"))
2363   `(variable-arity-call ,args
2364                         (lambda (,args)
2365                           (code "return " ,@body ";" *newline*))))
2366
2367 (defun num-op-num (x op y)
2368   (type-check (("x" "number" x) ("y" "number" y))
2369     (code "x" op "y")))
2370
2371 (define-raw-builtin + (&rest numbers)
2372   (if (null numbers)
2373       "0"
2374       (variable-arity numbers
2375         (join numbers "+"))))
2376
2377 (define-raw-builtin - (x &rest others)
2378   (let ((args (cons x others)))
2379     (variable-arity args
2380       (if (null others)
2381           (concat "-" (car args))
2382           (join args "-")))))
2383
2384 (define-raw-builtin * (&rest numbers)
2385   (if (null numbers)
2386       "1"
2387       (variable-arity numbers
2388         (join numbers "*"))))
2389
2390 (define-raw-builtin / (x &rest others)
2391   (let ((args (cons x others)))
2392     (variable-arity args
2393       (if (null others)
2394           (concat "1 /" (car args))
2395           (join args "/")))))
2396
2397 (define-builtin mod (x y) (num-op-num x "%" y))
2398
2399
2400 (defun comparison-conjuntion (vars op)
2401   (cond
2402     ((null (cdr vars))
2403      "true")
2404     ((null (cddr vars))
2405      (concat (car vars) op (cadr vars)))
2406     (t
2407      (concat (car vars) op (cadr vars)
2408              " && "
2409              (comparison-conjuntion (cdr vars) op)))))
2410
2411 (defmacro define-builtin-comparison (op sym)
2412   `(define-raw-builtin ,op (x &rest args)
2413      (let ((args (cons x args)))
2414        (variable-arity args
2415          (js!bool (comparison-conjuntion args ,sym))))))
2416
2417 (define-builtin-comparison > ">")
2418 (define-builtin-comparison < "<")
2419 (define-builtin-comparison >= ">=")
2420 (define-builtin-comparison <= "<=")
2421 (define-builtin-comparison = "==")
2422
2423 (define-builtin numberp (x)
2424   (js!bool (code "(typeof (" x ") == \"number\")")))
2425
2426 (define-builtin floor (x)
2427   (type-check (("x" "number" x))
2428     "Math.floor(x)"))
2429
2430 (define-builtin cons (x y)
2431   (code "({car: " x ", cdr: " y "})"))
2432
2433 (define-builtin consp (x)
2434   (js!bool
2435    (js!selfcall
2436      "var tmp = " x ";" *newline*
2437      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
2438
2439 (define-builtin car (x)
2440   (js!selfcall
2441     "var tmp = " x ";" *newline*
2442     "return tmp === " (ls-compile nil)
2443     "? " (ls-compile nil)
2444     ": tmp.car;" *newline*))
2445
2446 (define-builtin cdr (x)
2447   (js!selfcall
2448     "var tmp = " x ";" *newline*
2449     "return tmp === " (ls-compile nil) "? "
2450     (ls-compile nil)
2451     ": tmp.cdr;" *newline*))
2452
2453 (define-builtin rplaca (x new)
2454   (type-check (("x" "object" x))
2455     (code "(x.car = " new ", x)")))
2456
2457 (define-builtin rplacd (x new)
2458   (type-check (("x" "object" x))
2459     (code "(x.cdr = " new ", x)")))
2460
2461 (define-builtin symbolp (x)
2462   (js!bool
2463    (js!selfcall
2464      "var tmp = " x ";" *newline*
2465      "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
2466
2467 (define-builtin make-symbol (name)
2468   (type-check (("name" "string" name))
2469     "({name: name})"))
2470
2471 (define-builtin symbol-name (x)
2472   (code "(" x ").name"))
2473
2474 (define-builtin set (symbol value)
2475   (code "(" symbol ").value = " value))
2476
2477 (define-builtin fset (symbol value)
2478   (code "(" symbol ").fvalue = " value))
2479
2480 (define-builtin boundp (x)
2481   (js!bool (code "(" x ".value !== undefined)")))
2482
2483 (define-builtin symbol-value (x)
2484   (js!selfcall
2485     "var symbol = " x ";" *newline*
2486     "var value = symbol.value;" *newline*
2487     "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
2488     "return value;" *newline*))
2489
2490 (define-builtin symbol-function (x)
2491   (js!selfcall
2492     "var symbol = " x ";" *newline*
2493     "var func = symbol.fvalue;" *newline*
2494     "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
2495     "return func;" *newline*))
2496
2497 (define-builtin symbol-plist (x)
2498   (code "((" x ").plist || " (ls-compile nil) ")"))
2499
2500 (define-builtin lambda-code (x)
2501   (code "(" x ").toString()"))
2502
2503 (define-builtin eq    (x y) (js!bool (code "(" x " === " y ")")))
2504 (define-builtin equal (x y) (js!bool (code "(" x  " == " y ")")))
2505
2506 (define-builtin char-to-string (x)
2507   (type-check (("x" "number" x))
2508     "String.fromCharCode(x)"))
2509
2510 (define-builtin stringp (x)
2511   (js!bool (code "(typeof(" x ") == \"string\")")))
2512
2513 (define-builtin string-upcase (x)
2514   (type-check (("x" "string" x))
2515     "x.toUpperCase()"))
2516
2517 (define-builtin string-length (x)
2518   (type-check (("x" "string" x))
2519     "x.length"))
2520
2521 (define-raw-builtin slice (string a &optional b)
2522   (js!selfcall
2523     "var str = " (ls-compile string) ";" *newline*
2524     "var a = " (ls-compile a) ";" *newline*
2525     "var b;" *newline*
2526     (when b (code "b = " (ls-compile b) ";" *newline*))
2527     "return str.slice(a,b);" *newline*))
2528
2529 (define-builtin char (string index)
2530   (type-check (("string" "string" string)
2531                ("index" "number" index))
2532     "string.charCodeAt(index)"))
2533
2534 (define-builtin concat-two (string1 string2)
2535   (type-check (("string1" "string" string1)
2536                ("string2" "string" string2))
2537     "string1.concat(string2)"))
2538
2539 (define-raw-builtin funcall (func &rest args)
2540   (js!selfcall
2541     "var f = " (ls-compile func) ";" *newline*
2542     "return (typeof f === 'function'? f: f.fvalue)("
2543     (join (cons (if *multiple-value-p* "values" "pv")
2544                 (mapcar #'ls-compile args))
2545           ", ")
2546     ")"))
2547
2548 (define-raw-builtin apply (func &rest args)
2549   (if (null args)
2550       (code "(" (ls-compile func) ")()")
2551       (let ((args (butlast args))
2552             (last (car (last args))))
2553         (js!selfcall
2554           "var f = " (ls-compile func) ";" *newline*
2555           "var args = [" (join (cons (if *multiple-value-p* "values" "pv")
2556                                      (mapcar #'ls-compile args))
2557                                ", ")
2558           "];" *newline*
2559           "var tail = (" (ls-compile last) ");" *newline*
2560           "while (tail != " (ls-compile nil) "){" *newline*
2561           "    args.push(tail.car);" *newline*
2562           "    tail = tail.cdr;" *newline*
2563           "}" *newline*
2564           "return (typeof f === 'function'? f : f.fvalue).apply(this, args);" *newline*))))
2565
2566 (define-builtin js-eval (string)
2567   (type-check (("string" "string" string))
2568     (if *multiple-value-p*
2569         (js!selfcall
2570           "var v = eval.apply(window, [string]);" *newline*
2571           "if (typeof v !== 'object' || !('multiple-value' in v)){" *newline*
2572           (indent "v = [v];" *newline*
2573                   "v['multiple-value'] = true;" *newline*)
2574           "}" *newline*
2575           "return values.apply(this, v);" *newline*)
2576         "eval.apply(window, [string])")))
2577
2578 (define-builtin error (string)
2579   (js!selfcall "throw " string ";" *newline*))
2580
2581 (define-builtin new () "{}")
2582
2583 (define-builtin objectp (x)
2584   (js!bool (code "(typeof (" x ") === 'object')")))
2585
2586 (define-builtin oget (object key)
2587   (js!selfcall
2588     "var tmp = " "(" object ")[" key "];" *newline*
2589     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
2590
2591 (define-builtin oset (object key value)
2592   (code "((" object ")[" key "] = " value ")"))
2593
2594 (define-builtin in (key object)
2595   (js!bool (code "((" key ") in (" object "))")))
2596
2597 (define-builtin functionp (x)
2598   (js!bool (code "(typeof " x " == 'function')")))
2599
2600 (define-builtin write-string (x)
2601   (type-check (("x" "string" x))
2602     "lisp.write(x)"))
2603
2604 (define-builtin make-array (n)
2605   (js!selfcall
2606     "var r = [];" *newline*
2607     "for (var i = 0; i < " n "; i++)" *newline*
2608     (indent "r.push(" (ls-compile nil) ");" *newline*)
2609     "return r;" *newline*))
2610
2611 (define-builtin arrayp (x)
2612   (js!bool
2613    (js!selfcall
2614      "var x = " x ";" *newline*
2615      "return typeof x === 'object' && 'length' in x;")))
2616
2617 (define-builtin aref (array n)
2618   (js!selfcall
2619     "var x = " "(" array ")[" n "];" *newline*
2620     "if (x === undefined) throw 'Out of range';" *newline*
2621     "return x;" *newline*))
2622
2623 (define-builtin aset (array n value)
2624   (js!selfcall
2625     "var x = " array ";" *newline*
2626     "var i = " n ";" *newline*
2627     "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
2628     "return x[i] = " value ";" *newline*))
2629
2630 (define-builtin get-unix-time ()
2631   (code "(Math.round(new Date() / 1000))"))
2632
2633 (define-builtin values-array (array)
2634   (if *multiple-value-p*
2635       (code "values.apply(this, " array ")")
2636       (code "pv.apply(this, " array ")")))
2637
2638 (define-raw-builtin values (&rest args)
2639   (if *multiple-value-p*
2640       (code "values(" (join (mapcar #'ls-compile args) ", ") ")")
2641       (code "pv(" (join (mapcar #'ls-compile args) ", ") ")")))
2642
2643 (defun macro (x)
2644   (and (symbolp x)
2645        (let ((b (lookup-in-lexenv x *environment* 'function)))
2646          (and (eq (binding-type b) 'macro)
2647               b))))
2648
2649 (defun ls-macroexpand-1 (form)
2650   (let ((macro-binding (macro (car form))))
2651     (if macro-binding
2652         (let ((expander (binding-value macro-binding)))
2653           (when (listp expander)
2654             (let ((compiled (eval expander)))
2655               ;; The list representation are useful while
2656               ;; bootstrapping, as we can dump the definition of the
2657               ;; macros easily, but they are slow because we have to
2658               ;; evaluate them and compile them now and again. So, let
2659               ;; us replace the list representation version of the
2660               ;; function with the compiled one.
2661               ;;
2662               #+ecmalisp (set-binding-value macro-binding compiled)
2663               (setq expander compiled)))
2664           (apply expander (cdr form)))
2665         form)))
2666
2667 (defun compile-funcall (function args)
2668   (let* ((values-funcs (if *multiple-value-p* "values" "pv"))
2669          (arglist (concat "(" (join (cons values-funcs (mapcar #'ls-compile args)) ", ") ")")))
2670     (cond
2671       ((translate-function function)
2672        (concat (translate-function function) arglist))
2673       ((and (symbolp function)
2674             #+ecmalisp (eq (symbol-package function) (find-package "COMMON-LISP"))
2675             #+common-lisp t)
2676        (code (ls-compile `',function) ".fvalue" arglist))
2677       (t
2678        (code (ls-compile `#',function) arglist)))))
2679
2680 (defun ls-compile-block (sexps &optional return-last-p)
2681   (if return-last-p
2682       (code (ls-compile-block (butlast sexps))
2683             "return " (ls-compile (car (last sexps)) *multiple-value-p*) ";")
2684       (join-trailing
2685        (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
2686        (concat ";" *newline*))))
2687
2688 (defun ls-compile (sexp &optional multiple-value-p)
2689   (let ((*multiple-value-p* multiple-value-p))
2690     (cond
2691       ((symbolp sexp)
2692        (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
2693          (cond
2694            ((and b (not (member 'special (binding-declarations b))))
2695             (binding-value b))
2696            ((or (keywordp sexp)
2697                 (member 'constant (binding-declarations b)))
2698             (code (ls-compile `',sexp) ".value"))
2699            (t
2700             (ls-compile `(symbol-value ',sexp))))))
2701       ((integerp sexp) (integer-to-string sexp))
2702       ((stringp sexp) (code "\"" (escape-string sexp) "\""))
2703       ((arrayp sexp) (literal sexp))
2704       ((listp sexp)
2705        (let ((name (car sexp))
2706              (args (cdr sexp)))
2707          (cond
2708            ;; Special forms
2709            ((assoc name *compilations*)
2710             (let ((comp (second (assoc name *compilations*))))
2711               (apply comp args)))
2712            ;; Built-in functions
2713            ((and (assoc name *builtins*)
2714                  (not (claimp name 'function 'notinline)))
2715             (let ((comp (second (assoc name *builtins*))))
2716               (apply comp args)))
2717            (t
2718             (if (macro name)
2719                 (ls-compile (ls-macroexpand-1 sexp) multiple-value-p)
2720                 (compile-funcall name args))))))
2721       (t
2722        (error (concat "How should I compile " (prin1-to-string sexp) "?"))))))
2723
2724 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
2725   (let ((*toplevel-compilations* nil))
2726     (cond
2727       ((and (consp sexp) (eq (car sexp) 'progn))
2728        (let ((subs (mapcar (lambda (s)
2729                              (ls-compile-toplevel s t))
2730                            (cdr sexp))))
2731          (join (remove-if #'null-or-empty-p subs))))
2732       (t
2733        (let ((code (ls-compile sexp multiple-value-p)))
2734          (code (join-trailing (get-toplevel-compilations)
2735                               (code ";" *newline*))
2736                (when code
2737                  (code code ";" *newline*))))))))
2738
2739
2740 ;;; Once we have the compiler, we define the runtime environment and
2741 ;;; interactive development (eval), which works calling the compiler
2742 ;;; and evaluating the Javascript result globally.
2743
2744 #+ecmalisp
2745 (progn
2746   (defun eval (x)
2747     (js-eval (ls-compile-toplevel x t)))
2748
2749   (export '(&rest &key &optional &body * *gensym-counter* *package* + - / 1+ 1- <
2750             <= = = > >= and append apply aref arrayp assoc atom block boundp
2751             boundp butlast caar cadddr caddr cadr car car case catch cdar cdddr
2752             cddr cdr cdr char char-code fdefinition find-package find-symbol first
2753             flet fourth fset funcall function functionp gensym get-setf-expansion
2754             get-universal-time go identity if in-package incf integerp integerp
2755             intern keywordp labels lambda last length let let* char= code-char
2756             cond cons consp constantly copy-list decf declaim define-setf-expander
2757             defconstant defparameter defun defmacro defvar digit-char digit-char-p
2758             disassemble do do* documentation dolist dotimes ecase eq eql equal
2759             error eval every export list-all-packages list list* listp loop make-array
2760             make-package make-symbol mapcar member minusp mod multiple-value-bind
2761             multiple-value-call multiple-value-list multiple-value-prog1 nconc nil not
2762             nth nthcdr null numberp or package-name package-use-list packagep
2763             parse-integer plusp prin1-to-string print proclaim prog1 prog2 progn
2764             psetq push quote nreconc remove remove-if remove-if-not return return-from
2765             revappend reverse rplaca rplacd second set setf setq some
2766             string-upcase string string= stringp subseq symbol-function
2767             symbol-name symbol-package symbol-plist symbol-value symbolp t tagbody
2768             third throw truncate unless unwind-protect values values-list variable
2769             warn when write-line write-string zerop))
2770
2771   (setq *package* *user-package*)
2772
2773   (js-eval "var lisp")
2774   (js-vset "lisp" (new))
2775   (js-vset "lisp.read" #'ls-read-from-string)
2776   (js-vset "lisp.print" #'prin1-to-string)
2777   (js-vset "lisp.eval" #'eval)
2778   (js-vset "lisp.compile" (lambda (s) (ls-compile-toplevel s t)))
2779   (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
2780   (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str) t)))
2781
2782   ;; Set the initial global environment to be equal to the host global
2783   ;; environment at this point of the compilation.
2784   (eval-when-compile
2785     (toplevel-compilation
2786      (ls-compile `(setq *environment* ',*environment*))))
2787
2788   (eval-when-compile
2789     (toplevel-compilation
2790      (ls-compile
2791       `(progn
2792          ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
2793                    *literal-symbols*)
2794          (setq *literal-symbols* ',*literal-symbols*)
2795          (setq *variable-counter* ,*variable-counter*)
2796          (setq *gensym-counter* ,*gensym-counter*)
2797          (setq *block-counter* ,*block-counter*)))))
2798
2799   (eval-when-compile
2800     (toplevel-compilation
2801      (ls-compile
2802       `(setq *literal-counter* ,*literal-counter*)))))
2803
2804
2805 ;;; Finally, we provide a couple of functions to easily bootstrap
2806 ;;; this. It just calls the compiler with this file as input.
2807
2808 #+common-lisp
2809 (progn
2810   (defun read-whole-file (filename)
2811     (with-open-file (in filename)
2812       (let ((seq (make-array (file-length in) :element-type 'character)))
2813         (read-sequence seq in)
2814         seq)))
2815
2816   (defun ls-compile-file (filename output)
2817     (let ((*compiling-file* t))
2818       (with-open-file (out output :direction :output :if-exists :supersede)
2819         (write-string (read-whole-file "prelude.js") out)
2820         (let* ((source (read-whole-file filename))
2821                (in (make-string-stream source)))
2822           (loop
2823              for x = (ls-read in)
2824              until (eq x *eof*)
2825              for compilation = (ls-compile-toplevel x)
2826              when (plusp (length compilation))
2827              do (write-string compilation out))))))
2828
2829   (defun bootstrap ()
2830     (setq *environment* (make-lexenv))
2831     (setq *literal-symbols* nil)
2832     (setq *variable-counter* 0
2833           *gensym-counter* 0
2834           *literal-counter* 0
2835           *block-counter* 0)
2836     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))