85742223f4c4584ca32b76de615866b14be2b611
[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   (declaim (constant nil t) (special t nil))
46   (setq nil 'nil)
47   (js-vset "nil" nil)
48   (setq t 't)
49
50   (defmacro lambda (args &body body)
51     `(function (lambda ,args ,@body)))
52
53   (defmacro when (condition &body body)
54     `(if ,condition (progn ,@body) nil))
55
56   (defmacro unless (condition &body body)
57     `(if ,condition nil (progn ,@body)))
58
59   (defmacro defvar (name value &optional docstring)
60     `(progn
61        (declaim (special ,name))
62        (unless (boundp ',name) (setq ,name ,value))
63        ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
64        ',name))
65
66   (defmacro defparameter (name value &optional docstring)
67     `(progn
68        (setq ,name ,value)
69        ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
70        ',name))
71
72   (defmacro named-lambda (name args &rest body)
73     (let ((x (gensym "FN")))
74       `(let ((,x (lambda ,args ,@body)))
75          (oset ,x "fname" ,name)
76          ,x)))
77
78   (defmacro defun (name args &rest body)
79     `(progn
80        (fset ',name
81              (named-lambda ,(symbol-name name) ,args
82                ,@(if (and (stringp (car body)) (not (null (cdr body))))
83                      `(,(car body) (block ,name ,@(cdr body)))
84                      `((block ,name ,@body)))))
85        ',name))
86
87   (defun null (x)
88     (eq x nil))
89
90   (defmacro return (&optional value)
91     `(return-from nil ,value))
92
93   (defmacro while (condition &body body)
94     `(block nil (%while ,condition ,@body)))
95
96   (defvar *gensym-counter* 0)
97   (defun gensym (&optional (prefix "G"))
98     (setq *gensym-counter* (+ *gensym-counter* 1))
99     (make-symbol (concat-two prefix (integer-to-string *gensym-counter*))))
100
101   (defun boundp (x)
102     (boundp x))
103
104   ;; Basic functions
105   (defun = (x y) (= x y))
106   (defun * (x y) (* x y))
107   (defun / (x y) (/ x y))
108   (defun 1+ (x) (+ x 1))
109   (defun 1- (x) (- x 1))
110   (defun zerop (x) (= x 0))
111   (defun truncate (x y) (floor (/ x y)))
112
113   (defun eql (x y) (eq x y))
114
115   (defun not (x) (if x nil t))
116
117   (defun cons (x y ) (cons x y))
118   (defun consp (x) (consp x))
119
120   (defun car (x)
121     "Return the CAR part of a cons, or NIL if X is null."
122     (car x))
123
124   (defun cdr (x) (cdr x))
125   (defun caar (x) (car (car x)))
126   (defun cadr (x) (car (cdr x)))
127   (defun cdar (x) (cdr (car x)))
128   (defun cddr (x) (cdr (cdr x)))
129   (defun caddr (x) (car (cdr (cdr x))))
130   (defun cdddr (x) (cdr (cdr (cdr x))))
131   (defun cadddr (x) (car (cdr (cdr (cdr x)))))
132   (defun first (x) (car x))
133   (defun second (x) (cadr x))
134   (defun third (x) (caddr x))
135   (defun fourth (x) (cadddr x))
136
137   (defun list (&rest args) args)
138   (defun atom (x)
139     (not (consp x)))
140
141   ;; Basic macros
142
143   (defmacro incf (x &optional (delta 1))
144     `(setq ,x (+ ,x ,delta)))
145
146   (defmacro decf (x &optional (delta 1))
147     `(setq ,x (- ,x ,delta)))
148
149   (defmacro push (x place)
150     `(setq ,place (cons ,x ,place)))
151
152   (defmacro dolist (iter &body body)
153     (let ((var (first iter))
154           (g!list (gensym)))
155       `(block nil
156          (let ((,g!list ,(second iter))
157                (,var nil))
158            (%while ,g!list
159                    (setq ,var (car ,g!list))
160                    (tagbody ,@body)
161                    (setq ,g!list (cdr ,g!list)))
162            ,(third iter)))))
163
164   (defmacro dotimes (iter &body body)
165     (let ((g!to (gensym))
166           (var (first iter))
167           (to (second iter))
168           (result (third iter)))
169       `(block nil
170          (let ((,var 0)
171                (,g!to ,to))
172            (%while (< ,var ,g!to)
173                    (tagbody ,@body)
174                    (incf ,var))
175            ,result))))
176
177   (defmacro cond (&rest clausules)
178     (if (null clausules)
179         nil
180         (if (eq (caar clausules) t)
181             `(progn ,@(cdar clausules))
182             `(if ,(caar clausules)
183                  (progn ,@(cdar clausules))
184                  (cond ,@(cdr clausules))))))
185
186   (defmacro case (form &rest clausules)
187     (let ((!form (gensym)))
188       `(let ((,!form ,form))
189          (cond
190            ,@(mapcar (lambda (clausule)
191                        (if (eq (car clausule) t)
192                            clausule
193                            `((eql ,!form ',(car clausule))
194                              ,@(cdr clausule))))
195                      clausules)))))
196
197   (defmacro ecase (form &rest clausules)
198     `(case ,form
199        ,@(append
200           clausules
201           `((t
202              (error "ECASE expression failed."))))))
203
204   (defmacro and (&rest forms)
205     (cond
206       ((null forms)
207        t)
208       ((null (cdr forms))
209        (car forms))
210       (t
211        `(if ,(car forms)
212             (and ,@(cdr forms))
213             nil))))
214
215   (defmacro or (&rest forms)
216     (cond
217       ((null forms)
218        nil)
219       ((null (cdr forms))
220        (car forms))
221       (t
222        (let ((g (gensym)))
223          `(let ((,g ,(car forms)))
224             (if ,g ,g (or ,@(cdr forms))))))))
225
226   (defmacro prog1 (form &body body)
227     (let ((value (gensym)))
228       `(let ((,value ,form))
229          ,@body
230          ,value)))
231
232   (defmacro prog2 (form1 result &body body)
233     `(prog1 (progn ,form1 ,result) ,@body)))
234
235
236 ;;; This couple of helper functions will be defined in both Common
237 ;;; Lisp and in Ecmalisp.
238 (defun ensure-list (x)
239   (if (listp x)
240       x
241       (list x)))
242
243 (defun !reduce (func list initial)
244   (if (null list)
245       initial
246       (!reduce func
247                (cdr list)
248                (funcall func initial (car list)))))
249
250 ;;; Go on growing the Lisp language in Ecmalisp, with more high
251 ;;; level utilities as well as correct versions of other
252 ;;; constructions.
253 #+ecmalisp
254 (progn
255   (defun + (&rest args)
256     (let ((r 0))
257       (dolist (x args r)
258         (incf r x))))
259
260   (defun - (x &rest others)
261     (if (null others)
262         (- x)
263         (let ((r x))
264           (dolist (y others r)
265             (decf r y)))))
266
267   (defun append-two (list1 list2)
268     (if (null list1)
269         list2
270         (cons (car list1)
271               (append (cdr list1) list2))))
272
273   (defun append (&rest lists)
274     (!reduce #'append-two lists '()))
275
276   (defun revappend (list1 list2)
277     (while list1
278       (push (car list1) list2)
279       (setq list1 (cdr list1)))
280     list2)
281
282   (defun reverse (list)
283     (revappend list '()))
284
285   (defmacro psetq (&rest pairs)
286     (let ( ;; For each pair, we store here a list of the form
287           ;; (VARIABLE GENSYM VALUE).
288           (assignments '()))
289       (while t
290         (cond
291           ((null pairs) (return))
292           ((null (cdr pairs))
293            (error "Odd paris in PSETQ"))
294           (t
295            (let ((variable (car pairs))
296                  (value (cadr pairs)))
297              (push `(,variable ,(gensym) ,value)  assignments)
298              (setq pairs (cddr pairs))))))
299       (setq assignments (reverse assignments))
300       ;;
301       `(let ,(mapcar #'cdr assignments)
302          (setq ,@(!reduce #'append (mapcar #'butlast assignments) '())))))
303
304   (defun list-length (list)
305     (let ((l 0))
306       (while (not (null list))
307         (incf l)
308         (setq list (cdr list)))
309       l))
310
311   (defun length (seq)
312     (cond
313       ((stringp seq)
314        (string-length seq))
315       ((arrayp seq)
316        (oget seq "length"))
317       ((listp seq)
318        (list-length seq))))
319
320   (defun concat-two (s1 s2)
321     (concat-two s1 s2))
322
323   (defun mapcar (func list)
324     (if (null list)
325         '()
326         (cons (funcall func (car list))
327               (mapcar func (cdr list)))))
328
329   (defun identity (x) x)
330
331   (defun copy-list (x)
332     (mapcar #'identity x))
333
334   (defun code-char (x) x)
335   (defun char-code (x) x)
336   (defun char= (x y) (= x y))
337
338   (defun integerp (x)
339     (and (numberp x) (= (floor x) x)))
340
341   (defun plusp (x) (< 0 x))
342   (defun minusp (x) (< x 0))
343
344   (defun listp (x)
345     (or (consp x) (null x)))
346
347   (defun nthcdr (n list)
348     (while (and (plusp n) list)
349       (setq n (1- n))
350       (setq list (cdr list)))
351     list)
352
353   (defun nth (n list)
354     (car (nthcdr n list)))
355
356   (defun last (x)
357     (while (consp (cdr x))
358       (setq x (cdr x)))
359     x)
360
361   (defun butlast (x)
362     (and (consp (cdr x))
363          (cons (car x) (butlast (cdr x)))))
364
365   (defun member (x list)
366     (while list
367       (when (eql x (car list))
368         (return list))
369       (setq list (cdr list))))
370
371   (defun remove (x list)
372     (cond
373       ((null list)
374        nil)
375       ((eql x (car list))
376        (remove x (cdr list)))
377       (t
378        (cons (car list) (remove x (cdr list))))))
379
380   (defun remove-if (func list)
381     (cond
382       ((null list)
383        nil)
384       ((funcall func (car list))
385        (remove-if func (cdr list)))
386       (t
387        (cons (car list) (remove-if func (cdr list))))))
388
389   (defun remove-if-not (func list)
390     (cond
391       ((null list)
392        nil)
393       ((funcall func (car list))
394        (cons (car list) (remove-if-not func (cdr list))))
395       (t
396        (remove-if-not func (cdr list)))))
397
398   (defun digit-char-p (x)
399     (if (and (<= #\0 x) (<= x #\9))
400         (- x #\0)
401         nil))
402
403   (defun subseq (seq a &optional b)
404     (cond
405       ((stringp seq)
406        (if b
407            (slice seq a b)
408            (slice seq a)))
409       (t
410        (error "Unsupported argument."))))
411
412   (defun parse-integer (string)
413     (let ((value 0)
414           (index 0)
415           (size (length string)))
416       (while (< index size)
417         (setq value (+ (* value 10) (digit-char-p (char string index))))
418         (incf index))
419       value))
420
421   (defun some (function seq)
422     (cond
423       ((stringp seq)
424        (let ((index 0)
425              (size (length seq)))
426          (while (< index size)
427            (when (funcall function (char seq index))
428              (return-from some t))
429            (incf index))
430          nil))
431       ((listp seq)
432        (dolist (x seq nil)
433          (when (funcall function x)
434            (return t))))
435       (t
436        (error "Unknown sequence."))))
437
438   (defun every (function seq)
439     (cond
440       ((stringp seq)
441        (let ((index 0)
442              (size (length seq)))
443          (while (< index size)
444            (unless (funcall function (char seq index))
445              (return-from every nil))
446            (incf index))
447          t))
448       ((listp seq)
449        (dolist (x seq t)
450          (unless (funcall function x)
451            (return))))
452       (t
453        (error "Unknown sequence."))))
454
455   (defun assoc (x alist)
456     (while alist
457       (if (eql x (caar alist))
458           (return)
459           (setq alist (cdr alist))))
460     (car alist))
461
462   (defun string (x)
463     (cond ((stringp x) x)
464           ((symbolp x) (symbol-name x))
465           (t (char-to-string x))))
466
467   (defun string= (s1 s2)
468     (equal s1 s2))
469
470   (defun fdefinition (x)
471     (cond
472       ((functionp x)
473        x)
474       ((symbolp x)
475        (symbol-function x))
476       (t
477        (error "Invalid function"))))
478
479   (defun disassemble (function)
480     (write-line (lambda-code (fdefinition function)))
481     nil)
482
483   (defun documentation (x type)
484     "Return the documentation of X. TYPE must be the symbol VARIABLE or FUNCTION."
485     (ecase type
486       (function
487        (let ((func (fdefinition x)))
488          (oget func "docstring")))
489       (variable
490        (unless (symbolp x)
491          (error "Wrong argument type! it should be a symbol"))
492        (oget x "vardoc"))))
493
494   ;; Packages
495
496   (defvar *package-list* nil)
497
498   (defun list-all-packages ()
499     *package-list*)
500
501   (defun make-package (name &optional use)
502     (let ((package (new))
503           (use (mapcar #'find-package-or-fail use)))
504       (oset package "packageName" name)
505       (oset package "symbols" (new))
506       (oset package "exports" (new))
507       (oset package "use" use)
508       (push package *package-list*)
509       package))
510
511   (defun packagep (x)
512     (and (objectp x) (in "symbols" x)))
513
514   (defun find-package (package-designator)
515     (when (packagep package-designator)
516       (return-from find-package package-designator))
517     (let ((name (string package-designator)))
518       (dolist (package *package-list*)
519         (when (string= (package-name package) name)
520           (return package)))))
521
522   (defun find-package-or-fail (package-designator)
523     (or (find-package package-designator)
524         (error "Package unknown.")))
525
526   (defun package-name (package-designator)
527     (let ((package (find-package-or-fail package-designator)))
528       (oget package "packageName")))
529
530   (defun %package-symbols (package-designator)
531     (let ((package (find-package-or-fail package-designator)))
532       (oget package "symbols")))
533
534   (defun package-use-list (package-designator)
535     (let ((package (find-package-or-fail package-designator)))
536       (oget package "use")))
537
538   (defun %package-external-symbols (package-designator)
539     (let ((package (find-package-or-fail package-designator)))
540       (oget package "exports")))
541
542   (defvar *common-lisp-package*
543     (make-package "CL"))
544
545   (defvar *user-package*
546     (make-package "CL-USER" (list *common-lisp-package*)))
547
548   (defvar *keyword-package*
549     (make-package "KEYWORD"))
550
551   (defun keywordp (x)
552     (and (symbolp x) (eq (symbol-package x) *keyword-package*)))
553
554   (defvar *package* *common-lisp-package*)
555
556   (defmacro in-package (package-designator)
557     `(eval-when-compile
558        (setq *package* (find-package-or-fail ,package-designator))))
559
560   ;; This function is used internally to initialize the CL package
561   ;; with the symbols built during bootstrap.
562   (defun %intern-symbol (symbol)
563     (let ((symbols (%package-symbols *common-lisp-package*)))
564       (oset symbol "package" *common-lisp-package*)
565       (oset symbols (symbol-name symbol) symbol)))
566
567   (defun %find-symbol (name package)
568     (let ((package (find-package-or-fail package)))
569       (let ((symbols (%package-symbols package)))
570         (if (in name symbols)
571             (cons (oget symbols name) t)
572             (dolist (used (package-use-list package) (cons nil nil))
573               (let ((exports (%package-external-symbols used)))
574                 (when (in name exports)
575                   (return-from %find-symbol
576                     (cons (oget exports name) t)))))))))
577
578   (defun find-symbol (name &optional (package *package*))
579     (car (%find-symbol name package)))
580
581   (defun intern (name &optional (package *package*))
582     (let ((package (find-package-or-fail package)))
583       (let ((result (%find-symbol name package)))
584         (if (cdr result)
585             (car result)
586             (let ((symbols (%package-symbols package)))
587               (oget symbols name)
588               (let ((symbol (make-symbol name)))
589                 (oset symbol "package" package)
590                 (when (eq package *keyword-package*)
591                   (oset symbol "value" symbol)
592                   (export (list symbol) package))
593                 (oset symbols name symbol)))))))
594
595   (defun symbol-package (symbol)
596     (unless (symbolp symbol)
597       (error "it is not a symbol"))
598     (oget symbol "package"))
599
600   (defun export (symbols &optional (package *package*))
601     (let ((exports (%package-external-symbols package)))
602       (dolist (symb symbols t)
603         (oset exports (symbol-name symb) symb))))
604
605   (defun get-universal-time ()
606     (+ (get-unix-time) 2208988800)))
607
608
609 ;;; The compiler offers some primitives and special forms which are
610 ;;; not found in Common Lisp, for instance, while. So, we grow Common
611 ;;; Lisp a bit to it can execute the rest of the file.
612 #+common-lisp
613 (progn
614   (defmacro while (condition &body body)
615     `(do ()
616          ((not ,condition))
617        ,@body))
618
619   (defmacro eval-when-compile (&body body)
620     `(eval-when (:compile-toplevel :load-toplevel :execute)
621        ,@body))
622
623   (defun concat-two (s1 s2)
624     (concatenate 'string s1 s2))
625
626   (defun aset (array idx value)
627     (setf (aref array idx) value)))
628
629 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
630 ;;; from here, this code will compile on both. We define some helper
631 ;;; functions now for string manipulation and so on. They will be
632 ;;; useful in the compiler, mostly.
633
634 (defvar *newline* (string (code-char 10)))
635
636 (defun concat (&rest strs)
637   (!reduce #'concat-two strs ""))
638
639 (defmacro concatf (variable &body form)
640   `(setq ,variable (concat ,variable (progn ,@form))))
641
642 ;;; Concatenate a list of strings, with a separator
643 (defun join (list &optional (separator ""))
644   (cond
645     ((null list)
646      "")
647     ((null (cdr list))
648      (car list))
649     (t
650      (concat (car list)
651              separator
652              (join (cdr list) separator)))))
653
654 (defun join-trailing (list &optional (separator ""))
655   (if (null list)
656       ""
657       (concat (car list) separator (join-trailing (cdr list) separator))))
658
659 (defun mapconcat (func list)
660   (join (mapcar func list)))
661
662 (defun vector-to-list (vector)
663   (let ((list nil)
664         (size (length vector)))
665     (dotimes (i size (reverse list))
666       (push (aref vector i) list))))
667
668 (defun list-to-vector (list)
669   (let ((v (make-array (length list)))
670         (i 0))
671     (dolist (x list v)
672       (aset v i x)
673       (incf i))))
674
675 #+ecmalisp
676 (progn
677   (defun values-list (list)
678     (values-array (list-to-vector list)))
679
680   (defun values (&rest args)
681     (values-list args))
682
683   (defmacro multiple-value-bind (variables value-from &body body)
684     `(multiple-value-call (lambda (&optional ,@variables &rest ,(gensym))
685                             ,@body)
686        ,value-from))
687
688   (defmacro multiple-value-list (value-from)
689     `(multiple-value-call #'list ,value-from)))
690
691
692 ;;; Like CONCAT, but prefix each line with four spaces. Two versions
693 ;;; of this function are available, because the Ecmalisp version is
694 ;;; very slow and bootstraping was annoying.
695
696 #+ecmalisp
697 (defun indent (&rest string)
698   (let ((input (join string)))
699     (let ((output "")
700           (index 0)
701           (size (length input)))
702       (when (plusp (length input)) (concatf output "    "))
703       (while (< index size)
704         (let ((str
705                (if (and (char= (char input index) #\newline)
706                         (< index (1- size))
707                         (not (char= (char input (1+ index)) #\newline)))
708                    (concat (string #\newline) "    ")
709                    (string (char input index)))))
710           (concatf output str))
711         (incf index))
712       output)))
713
714 #+common-lisp
715 (defun indent (&rest string)
716   (with-output-to-string (*standard-output*)
717     (with-input-from-string (input (join string))
718       (loop
719          for line = (read-line input nil)
720          while line
721          do (write-string "    ")
722          do (write-line line)))))
723
724
725 (defun integer-to-string (x)
726   (cond
727     ((zerop x)
728      "0")
729     ((minusp x)
730      (concat "-" (integer-to-string (- 0 x))))
731     (t
732      (let ((digits nil))
733        (while (not (zerop x))
734          (push (mod x 10) digits)
735          (setq x (truncate x 10)))
736        (join (mapcar (lambda (d) (string (char "0123456789" d)))
737                      digits))))))
738
739
740 ;;; Wrap X with a Javascript code to convert the result from
741 ;;; Javascript generalized booleans to T or NIL.
742 (defun js!bool (x)
743   (concat "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
744
745 ;;; Concatenate the arguments and wrap them with a self-calling
746 ;;; Javascript anonymous function. It is used to make some Javascript
747 ;;; statements valid expressions and provide a private scope as well.
748 ;;; It could be defined as function, but we could do some
749 ;;; preprocessing in the future.
750 (defmacro js!selfcall (&body body)
751   `(concat "(function(){" *newline* (indent ,@body) "})()"))
752
753
754 ;;; Printer
755
756 #+ecmalisp
757 (progn
758   (defun prin1-to-string (form)
759     (cond
760       ((symbolp form)
761        (if (cdr (%find-symbol (symbol-name form) *package*))
762            (symbol-name form)
763            (let ((package (symbol-package form))
764                  (name (symbol-name form)))
765              (concat (cond
766                        ((null package) "#")
767                        ((eq package (find-package "KEYWORD")) "")
768                        (t (package-name package)))
769                      ":" name))))
770       ((integerp form) (integer-to-string form))
771       ((stringp form) (concat "\"" (escape-string form) "\""))
772       ((functionp form)
773        (let ((name (oget form "fname")))
774          (if name
775              (concat "#<FUNCTION " name ">")
776              (concat "#<FUNCTION>"))))
777       ((listp form)
778        (concat "("
779                (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
780                (let ((last (last form)))
781                  (if (null (cdr last))
782                      (prin1-to-string (car last))
783                      (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
784                ")"))
785       ((arrayp form)
786        (concat "#" (prin1-to-string (vector-to-list form))))
787       ((packagep form)
788        (concat "#<PACKAGE " (package-name form) ">"))))
789
790   (defun write-line (x)
791     (write-string x)
792     (write-string *newline*)
793     x)
794
795   (defun warn (string)
796     (write-string "WARNING: ")
797     (write-line string))
798
799   (defun print (x)
800     (write-line (prin1-to-string x))
801     x))
802
803
804 ;;;; Reader
805
806 ;;; The Lisp reader, parse strings and return Lisp objects. The main
807 ;;; entry points are `ls-read' and `ls-read-from-string'.
808
809 (defun make-string-stream (string)
810   (cons string 0))
811
812 (defun %peek-char (stream)
813   (and (< (cdr stream) (length (car stream)))
814        (char (car stream) (cdr stream))))
815
816 (defun %read-char (stream)
817   (and (< (cdr stream) (length (car stream)))
818        (prog1 (char (car stream) (cdr stream))
819          (rplacd stream (1+ (cdr stream))))))
820
821 (defun whitespacep (ch)
822   (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
823
824 (defun skip-whitespaces (stream)
825   (let (ch)
826     (setq ch (%peek-char stream))
827     (while (and ch (whitespacep ch))
828       (%read-char stream)
829       (setq ch (%peek-char stream)))))
830
831 (defun terminalp (ch)
832   (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
833
834 (defun read-until (stream func)
835   (let ((string "")
836         (ch))
837     (setq ch (%peek-char stream))
838     (while (and ch (not (funcall func ch)))
839       (setq string (concat string (string ch)))
840       (%read-char stream)
841       (setq ch (%peek-char stream)))
842     string))
843
844 (defun skip-whitespaces-and-comments (stream)
845   (let (ch)
846     (skip-whitespaces stream)
847     (setq ch (%peek-char stream))
848     (while (and ch (char= ch #\;))
849       (read-until stream (lambda (x) (char= x #\newline)))
850       (skip-whitespaces stream)
851       (setq ch (%peek-char stream)))))
852
853 (defun %read-list (stream)
854   (skip-whitespaces-and-comments stream)
855   (let ((ch (%peek-char stream)))
856     (cond
857       ((null ch)
858        (error "Unspected EOF"))
859       ((char= ch #\))
860        (%read-char stream)
861        nil)
862       ((char= ch #\.)
863        (%read-char stream)
864        (prog1 (ls-read stream)
865          (skip-whitespaces-and-comments stream)
866          (unless (char= (%read-char stream) #\))
867            (error "')' was expected."))))
868       (t
869        (cons (ls-read stream) (%read-list stream))))))
870
871 (defun read-string (stream)
872   (let ((string "")
873         (ch nil))
874     (setq ch (%read-char stream))
875     (while (not (eql ch #\"))
876       (when (null ch)
877         (error "Unexpected EOF"))
878       (when (eql ch #\\)
879         (setq ch (%read-char stream)))
880       (setq string (concat string (string ch)))
881       (setq ch (%read-char stream)))
882     string))
883
884 (defun read-sharp (stream)
885   (%read-char stream)
886   (ecase (%read-char stream)
887     (#\'
888      (list 'function (ls-read stream)))
889     (#\( (list-to-vector (%read-list stream)))
890     (#\: (make-symbol (string-upcase (read-until stream #'terminalp))))
891     (#\\
892      (let ((cname
893             (concat (string (%read-char stream))
894                     (read-until stream #'terminalp))))
895        (cond
896          ((string= cname "space") (char-code #\space))
897          ((string= cname "tab") (char-code #\tab))
898          ((string= cname "newline") (char-code #\newline))
899          (t (char-code (char cname 0))))))
900     (#\+
901      (let ((feature (read-until stream #'terminalp)))
902        (cond
903          ((string= feature "common-lisp")
904           (ls-read stream)              ;ignore
905           (ls-read stream))
906          ((string= feature "ecmalisp")
907           (ls-read stream))
908          (t
909           (error "Unknown reader form.")))))))
910
911 ;;; Parse a string of the form NAME, PACKAGE:NAME or
912 ;;; PACKAGE::NAME and return the name. If the string is of the
913 ;;; form 1) or 3), but the symbol does not exist, it will be created
914 ;;; and interned in that package.
915 (defun read-symbol (string)
916   (let ((size (length string))
917         package name internalp index)
918     (setq index 0)
919     (while (and (< index size)
920                 (not (char= (char string index) #\:)))
921       (incf index))
922     (cond
923       ;; No package prefix
924       ((= index size)
925        (setq name string)
926        (setq package *package*)
927        (setq internalp t))
928       (t
929        ;; Package prefix
930        (if (zerop index)
931            (setq package "KEYWORD")
932            (setq package (string-upcase (subseq string 0 index))))
933        (incf index)
934        (when (char= (char string index) #\:)
935          (setq internalp t)
936          (incf index))
937        (setq name (subseq string index))))
938     ;; Canonalize symbol name and package
939     (setq name (string-upcase name))
940     (setq package (find-package package))
941     ;; TODO: PACKAGE:SYMBOL should signal error if SYMBOL is not an
942     ;; external symbol from PACKAGE.
943     (if (or internalp (eq package (find-package "KEYWORD")))
944         (intern name package)
945         (find-symbol name package))))
946
947 (defvar *eof* (gensym))
948 (defun ls-read (stream)
949   (skip-whitespaces-and-comments stream)
950   (let ((ch (%peek-char stream)))
951     (cond
952       ((or (null ch) (char= ch #\)))
953        *eof*)
954       ((char= ch #\()
955        (%read-char stream)
956        (%read-list stream))
957       ((char= ch #\')
958        (%read-char stream)
959        (list 'quote (ls-read stream)))
960       ((char= ch #\`)
961        (%read-char stream)
962        (list 'backquote (ls-read stream)))
963       ((char= ch #\")
964        (%read-char stream)
965        (read-string stream))
966       ((char= ch #\,)
967        (%read-char stream)
968        (if (eql (%peek-char stream) #\@)
969            (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
970            (list 'unquote (ls-read stream))))
971       ((char= ch #\#)
972        (read-sharp stream))
973       (t
974        (let ((string (read-until stream #'terminalp)))
975          (if (every #'digit-char-p string)
976              (parse-integer string)
977              (read-symbol string)))))))
978
979 (defun ls-read-from-string (string)
980   (ls-read (make-string-stream string)))
981
982
983 ;;;; Compiler
984
985 ;;; Translate the Lisp code to Javascript. It will compile the special
986 ;;; forms. Some primitive functions are compiled as special forms
987 ;;; too. The respective real functions are defined in the target (see
988 ;;; the beginning of this file) as well as some primitive functions.
989
990 ;;; A Form can return a multiple values object calling VALUES, like
991 ;;; values(arg1, arg2, ...). It will work in any context, as well as
992 ;;; returning an individual object. However, if the special variable
993 ;;; `*multiple-value-p*' is NIL, is granted that only the primary
994 ;;; value will be used, so we can optimize to avoid the VALUES
995 ;;; function call.
996 (defvar *multiple-value-p* nil)
997
998
999 (defun make-binding (name type value &optional declarations)
1000   (list name type value declarations))
1001
1002 (defun binding-name (b) (first b))
1003 (defun binding-type (b) (second b))
1004 (defun binding-value (b) (third b))
1005 (defun binding-declarations (b) (fourth b))
1006
1007 (defun set-binding-value (b value)
1008   (rplaca (cddr b) value))
1009
1010 (defun set-binding-declarations (b value)
1011   (rplaca (cdddr b) value))
1012
1013 (defun push-binding-declaration (decl b)
1014   (set-binding-declarations b (cons decl (binding-declarations b))))
1015
1016
1017 (defun make-lexenv ()
1018   (list nil nil nil nil))
1019
1020 (defun copy-lexenv (lexenv)
1021   (copy-list lexenv))
1022
1023 (defun push-to-lexenv (binding lexenv namespace)
1024   (ecase namespace
1025     (variable   (rplaca        lexenv  (cons binding (car lexenv))))
1026     (function   (rplaca   (cdr lexenv) (cons binding (cadr lexenv))))
1027     (block      (rplaca  (cddr lexenv) (cons binding (caddr lexenv))))
1028     (gotag      (rplaca (cdddr lexenv) (cons binding (cadddr lexenv))))))
1029
1030 (defun extend-lexenv (bindings lexenv namespace)
1031   (let ((env (copy-lexenv lexenv)))
1032     (dolist (binding (reverse bindings) env)
1033       (push-to-lexenv binding env namespace))))
1034
1035 (defun lookup-in-lexenv (name lexenv namespace)
1036   (assoc name (ecase namespace
1037                 (variable (first lexenv))
1038                 (function (second lexenv))
1039                 (block (third lexenv))
1040                 (gotag (fourth lexenv)))))
1041
1042 (defvar *environment* (make-lexenv))
1043
1044 (defvar *variable-counter* 0)
1045 (defun gvarname (symbol)
1046   (concat "v" (integer-to-string (incf *variable-counter*))))
1047
1048 (defun translate-variable (symbol)
1049   (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
1050
1051 (defun extend-local-env (args)
1052   (let ((new (copy-lexenv *environment*)))
1053     (dolist (symbol args new)
1054       (let ((b (make-binding symbol 'lexical-variable (gvarname symbol))))
1055         (push-to-lexenv b new 'variable)))))
1056
1057 ;;; Toplevel compilations
1058 (defvar *toplevel-compilations* nil)
1059
1060 (defun toplevel-compilation (string)
1061   (push string *toplevel-compilations*))
1062
1063 (defun null-or-empty-p (x)
1064   (zerop (length x)))
1065
1066 (defun get-toplevel-compilations ()
1067   (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
1068
1069 (defun %compile-defmacro (name lambda)
1070   (toplevel-compilation (ls-compile `',name))
1071   (push-to-lexenv (make-binding name 'macro lambda) *environment* 'function)
1072   name)
1073
1074 (defun global-binding (name type namespace)
1075   (or (lookup-in-lexenv name *environment* namespace)
1076       (let ((b (make-binding name type nil)))
1077         (push-to-lexenv b *environment* namespace)
1078         b)))
1079
1080 (defun claimp (symbol namespace claim)
1081   (let ((b (lookup-in-lexenv symbol *environment* namespace)))
1082     (and b (member claim (binding-declarations b)))))
1083
1084 (defun !proclaim (decl)
1085   (case (car decl)
1086     (special
1087      (dolist (name (cdr decl))
1088        (let ((b (global-binding name 'variable 'variable)))
1089          (push-binding-declaration 'special b))))
1090     (notinline
1091      (dolist (name (cdr decl))
1092        (let ((b (global-binding name 'function 'function)))
1093          (push-binding-declaration 'notinline b))))
1094     (constant
1095      (dolist (name (cdr decl))
1096        (let ((b (global-binding name 'variable 'variable)))
1097          (push-binding-declaration 'constant b))))))
1098
1099 #+ecmalisp
1100 (fset 'proclaim #'!proclaim)
1101
1102 ;;; Special forms
1103
1104 (defvar *compilations* nil)
1105
1106 (defmacro define-compilation (name args &body body)
1107   ;; Creates a new primitive `name' with parameters args and
1108   ;; @body. The body can access to the local environment through the
1109   ;; variable *ENVIRONMENT*.
1110   `(push (list ',name (lambda ,args (block ,name ,@body)))
1111          *compilations*))
1112
1113 (define-compilation if (condition true false)
1114   (concat "(" (ls-compile condition) " !== " (ls-compile nil)
1115           " ? " (ls-compile true *multiple-value-p*)
1116           " : " (ls-compile false *multiple-value-p*)
1117           ")"))
1118
1119 (defvar *lambda-list-keywords* '(&optional &rest))
1120
1121 (defun list-until-keyword (list)
1122   (if (or (null list) (member (car list) *lambda-list-keywords*))
1123       nil
1124       (cons (car list) (list-until-keyword (cdr list)))))
1125
1126 (defun lambda-list-required-arguments (lambda-list)
1127   (list-until-keyword lambda-list))
1128
1129 (defun lambda-list-optional-arguments-with-default (lambda-list)
1130   (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
1131
1132 (defun lambda-list-optional-arguments (lambda-list)
1133   (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
1134
1135 (defun lambda-list-rest-argument (lambda-list)
1136   (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
1137     (when (cdr rest)
1138       (error "Bad lambda-list"))
1139     (car rest)))
1140
1141 (defun lambda-docstring-wrapper (docstring &rest strs)
1142   (if docstring
1143       (js!selfcall
1144         "var func = " (join strs) ";" *newline*
1145         "func.docstring = '" docstring "';" *newline*
1146         "return func;" *newline*)
1147       (join strs)))
1148
1149 (defun lambda-check-argument-count
1150     (n-required-arguments n-optional-arguments rest-p)
1151   ;; Note: Remember that we assume that the number of arguments of a
1152   ;; call is at least 1 (the values argument).
1153   (let ((min (1+ n-required-arguments))
1154         (max (if rest-p 'n/a (+ 1 n-required-arguments n-optional-arguments))))
1155     (block nil
1156       ;; Special case: a positive exact number of arguments.
1157       (when (and (< 1 min) (eql min max))
1158         (return (concat "checkArgs(arguments, " (integer-to-string min) ");" *newline*)))
1159       ;; General case:
1160       (concat
1161        (if (< 1 min)
1162            (concat "checkArgsAtLeast(arguments, " (integer-to-string min) ");" *newline*)
1163            "")
1164        (if (numberp max)
1165            (concat "checkArgsAtMost(arguments, " (integer-to-string max) ");" *newline*)
1166            "")))))
1167
1168 (defun compile-lambda (lambda-list body)
1169   (let ((required-arguments (lambda-list-required-arguments lambda-list))
1170         (optional-arguments (lambda-list-optional-arguments lambda-list))
1171         (rest-argument (lambda-list-rest-argument lambda-list))
1172         documentation)
1173     ;; Get the documentation string for the lambda function
1174     (when (and (stringp (car body))
1175                (not (null (cdr body))))
1176       (setq documentation (car body))
1177       (setq body (cdr body)))
1178     (let ((n-required-arguments (length required-arguments))
1179           (n-optional-arguments (length optional-arguments))
1180           (*environment* (extend-local-env
1181                           (append (ensure-list rest-argument)
1182                                   required-arguments
1183                                   optional-arguments))))
1184       (lambda-docstring-wrapper
1185        documentation
1186        "(function ("
1187        (join (cons "values"
1188                    (mapcar #'translate-variable
1189                            (append required-arguments optional-arguments)))
1190              ",")
1191        "){" *newline*
1192        (indent
1193         ;; Check number of arguments
1194         (lambda-check-argument-count n-required-arguments
1195                                      n-optional-arguments
1196                                      rest-argument)
1197         ;; Optional arguments
1198         (if optional-arguments
1199             (concat "switch(arguments.length-1){" *newline*
1200                     (let ((optional-and-defaults
1201                            (lambda-list-optional-arguments-with-default lambda-list))
1202                           (cases nil)
1203                           (idx 0))
1204                       (progn
1205                         (while (< idx n-optional-arguments)
1206                           (let ((arg (nth idx optional-and-defaults)))
1207                             (push (concat "case "
1208                                           (integer-to-string (+ idx n-required-arguments)) ":" *newline*
1209                                           (translate-variable (car arg))
1210                                           "="
1211                                           (ls-compile (cadr arg))
1212                                           ";" *newline*)
1213                                   cases)
1214                             (incf idx)))
1215                         (push (concat "default: break;" *newline*) cases)
1216                         (join (reverse cases))))
1217                     "}" *newline*)
1218             "")
1219         ;; &rest/&body argument
1220         (if rest-argument
1221             (let ((js!rest (translate-variable rest-argument)))
1222               (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
1223                       "for (var i = arguments.length-1; i>="
1224                       (integer-to-string (+ 1 n-required-arguments n-optional-arguments))
1225                       "; i--)" *newline*
1226                       (indent js!rest " = "
1227                               "{car: arguments[i], cdr: ") js!rest "};"
1228                       *newline*))
1229             "")
1230         ;; Body
1231         (let ((*multiple-value-p* t)) (ls-compile-block body t)))
1232        "})"))))
1233
1234
1235 (defun setq-pair (var val)
1236   (let ((b (lookup-in-lexenv var *environment* 'variable)))
1237     (if (eq (binding-type b) 'lexical-variable)
1238         (concat (binding-value b) " = " (ls-compile val))
1239         (ls-compile `(set ',var ,val)))))
1240
1241 (define-compilation setq (&rest pairs)
1242   (let ((result ""))
1243     (while t
1244       (cond
1245         ((null pairs) (return))
1246         ((null (cdr pairs))
1247          (error "Odd paris in SETQ"))
1248         (t
1249          (concatf result
1250            (concat (setq-pair (car pairs) (cadr pairs))
1251                    (if (null (cddr pairs)) "" ", ")))
1252          (setq pairs (cddr pairs)))))
1253     (concat "(" result ")")))
1254
1255 ;;; FFI Variable accessors
1256 (define-compilation js-vref (var)
1257   var)
1258
1259 (define-compilation js-vset (var val)
1260   (concat "(" var " = " (ls-compile val) ")"))
1261
1262
1263
1264 ;;; Literals
1265 (defun escape-string (string)
1266   (let ((output "")
1267         (index 0)
1268         (size (length string)))
1269     (while (< index size)
1270       (let ((ch (char string index)))
1271         (when (or (char= ch #\") (char= ch #\\))
1272           (setq output (concat output "\\")))
1273         (when (or (char= ch #\newline))
1274           (setq output (concat output "\\"))
1275           (setq ch #\n))
1276         (setq output (concat output (string ch))))
1277       (incf index))
1278     output))
1279
1280
1281 (defvar *literal-symbols* nil)
1282 (defvar *literal-counter* 0)
1283
1284 (defun genlit ()
1285   (concat "l" (integer-to-string (incf *literal-counter*))))
1286
1287 (defun literal (sexp &optional recursive)
1288   (cond
1289     ((integerp sexp) (integer-to-string sexp))
1290     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1291     ((symbolp sexp)
1292      (or (cdr (assoc sexp *literal-symbols*))
1293          (let ((v (genlit))
1294                (s #+common-lisp (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1295                   #+ecmalisp
1296                   (let ((package (symbol-package sexp)))
1297                     (if (null package)
1298                         (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1299                         (ls-compile `(intern ,(symbol-name sexp) ,(package-name package)))))))
1300            (push (cons sexp v) *literal-symbols*)
1301            (toplevel-compilation (concat "var " v " = " s))
1302            v)))
1303     ((consp sexp)
1304      (let* ((head (butlast sexp))
1305             (tail (last sexp))
1306             (c (concat "QIList("
1307                        (join-trailing (mapcar (lambda (x) (literal x t)) head) ",")
1308                        (literal (car tail) t)
1309                        ","
1310                        (literal (cdr tail) t)
1311                        ")")))
1312        (if recursive
1313            c
1314            (let ((v (genlit)))
1315              (toplevel-compilation (concat "var " v " = " c))
1316              v))))
1317     ((arrayp sexp)
1318      (let ((elements (vector-to-list sexp)))
1319        (let ((c (concat "[" (join (mapcar #'literal elements) ", ") "]")))
1320          (if recursive
1321              c
1322              (let ((v (genlit)))
1323                (toplevel-compilation (concat "var " v " = " c))
1324                v)))))))
1325
1326 (define-compilation quote (sexp)
1327   (literal sexp))
1328
1329 (define-compilation %while (pred &rest body)
1330   (js!selfcall
1331     "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1332     (indent (ls-compile-block body))
1333     "}"
1334     "return " (ls-compile nil) ";" *newline*))
1335
1336 (define-compilation function (x)
1337   (cond
1338     ((and (listp x) (eq (car x) 'lambda))
1339      (compile-lambda (cadr x) (cddr x)))
1340     ((symbolp x)
1341      (ls-compile `(symbol-function ',x)))))
1342
1343 (defvar *compiling-file* nil)
1344 (define-compilation eval-when-compile (&rest body)
1345   (if *compiling-file*
1346       (progn
1347         (eval (cons 'progn body))
1348         nil)
1349       (ls-compile `(progn ,@body))))
1350
1351 (defmacro define-transformation (name args form)
1352   `(define-compilation ,name ,args
1353      (ls-compile ,form)))
1354
1355 (define-compilation progn (&rest body)
1356   (if (null (cdr body))
1357       (ls-compile (car body) *multiple-value-p*)
1358       (js!selfcall (ls-compile-block body t))))
1359
1360 (defun special-variable-p (x)
1361   (and (claimp x 'variable 'special) t))
1362
1363 ;;; Wrap CODE to restore the symbol values of the dynamic
1364 ;;; bindings. BINDINGS is a list of pairs of the form
1365 ;;; (SYMBOL . PLACE),  where PLACE is a Javascript variable
1366 ;;; name to initialize the symbol value and where to stored
1367 ;;; the old value.
1368 (defun let-binding-wrapper (bindings body)
1369   (when (null bindings)
1370     (return-from let-binding-wrapper body))
1371   (concat
1372    "try {" *newline*
1373    (indent "var tmp;" *newline*
1374            (mapconcat
1375             (lambda (b)
1376               (let ((s (ls-compile `(quote ,(car b)))))
1377                 (concat "tmp = " s ".value;" *newline*
1378                         s ".value = " (cdr b) ";" *newline*
1379                         (cdr b) " = tmp;" *newline*)))
1380             bindings)
1381            body *newline*)
1382    "}" *newline*
1383    "finally {"  *newline*
1384    (indent
1385     (mapconcat (lambda (b)
1386                  (let ((s (ls-compile `(quote ,(car b)))))
1387                    (concat s ".value" " = " (cdr b) ";" *newline*)))
1388                bindings))
1389    "}" *newline*))
1390
1391 (define-compilation let (bindings &rest body)
1392   (let* ((bindings (mapcar #'ensure-list bindings))
1393          (variables (mapcar #'first bindings))
1394          (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
1395          (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
1396          (dynamic-bindings))
1397     (concat "(function("
1398             (join (mapcar (lambda (x)
1399                             (if (special-variable-p x)
1400                                 (let ((v (gvarname x)))
1401                                   (push (cons x v) dynamic-bindings)
1402                                   v)
1403                                 (translate-variable x)))
1404                           variables)
1405                   ",")
1406             "){" *newline*
1407             (let ((body (ls-compile-block body t)))
1408               (indent (let-binding-wrapper dynamic-bindings body)))
1409             "})(" (join cvalues ",") ")")))
1410
1411
1412 ;;; Return the code to initialize BINDING, and push it extending the
1413 ;;; current lexical environment if the variable is special.
1414 (defun let*-initialize-value (binding)
1415   (let ((var (first binding))
1416         (value (second binding)))
1417     (if (special-variable-p var)
1418         (concat (ls-compile `(setq ,var ,value)) ";" *newline*)
1419         (let* ((v (gvarname var))
1420                (b (make-binding var 'variable v)))
1421           (prog1 (concat "var " v " = " (ls-compile value) ";" *newline*)
1422             (push-to-lexenv b *environment* 'variable))))))
1423
1424 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
1425 ;;; DOES NOT generate code to initialize the value of the symbols,
1426 ;;; unlike let-binding-wrapper.
1427 (defun let*-binding-wrapper (symbols body)
1428   (when (null symbols)
1429     (return-from let*-binding-wrapper body))
1430   (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
1431                        (remove-if-not #'special-variable-p symbols))))
1432     (concat
1433      "try {" *newline*
1434      (indent
1435       (mapconcat (lambda (b)
1436                    (let ((s (ls-compile `(quote ,(car b)))))
1437                      (concat "var " (cdr b) " = " s ".value;" *newline*)))
1438                  store)
1439       body)
1440      "}" *newline*
1441      "finally {" *newline*
1442      (indent
1443       (mapconcat (lambda (b)
1444                    (let ((s (ls-compile `(quote ,(car b)))))
1445                      (concat s ".value" " = " (cdr b) ";" *newline*)))
1446                  store))
1447      "}" *newline*)))
1448
1449 (define-compilation let* (bindings &rest body)
1450   (let ((bindings (mapcar #'ensure-list bindings))
1451         (*environment* (copy-lexenv *environment*)))
1452     (js!selfcall
1453       (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
1454             (body (concat (mapconcat #'let*-initialize-value bindings)
1455                           (ls-compile-block body t))))
1456         (let*-binding-wrapper specials body)))))
1457
1458
1459 (defvar *block-counter* 0)
1460
1461 (define-compilation block (name &rest body)
1462   (let* ((tr (integer-to-string (incf *block-counter*)))
1463          (b (make-binding name 'block tr)))
1464     (when *multiple-value-p*
1465       (push-binding-declaration 'multiple-value b))
1466     (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
1467            (cbody (ls-compile-block body t)))
1468       (if (member 'used (binding-declarations b))
1469           (js!selfcall
1470             "try {" *newline*
1471             (indent cbody)
1472             "}" *newline*
1473             "catch (cf){" *newline*
1474             "    if (cf.type == 'block' && cf.id == " tr ")" *newline*
1475             (if *multiple-value-p*
1476                 "        return values.apply(this, forcemv(cf.values));"
1477                 "        return cf.values;")
1478             *newline*
1479             "    else" *newline*
1480             "        throw cf;" *newline*
1481             "}" *newline*)
1482           (js!selfcall cbody)))))
1483
1484 (define-compilation return-from (name &optional value)
1485   (let* ((b (lookup-in-lexenv name *environment* 'block))
1486          (multiple-value-p (member 'multiple-value (binding-declarations b))))
1487     (when (null b)
1488       (error (concat "Unknown block `" (symbol-name name) "'.")))
1489     (push-binding-declaration 'used b)
1490     (js!selfcall
1491       (if multiple-value-p
1492           (concat "var values = mv;" *newline*)
1493           "")
1494       "throw ({"
1495       "type: 'block', "
1496       "id: " (binding-value b) ", "
1497       "values: " (ls-compile value multiple-value-p) ", "
1498       "message: 'Return from unknown block " (symbol-name name) ".'"
1499       "})")))
1500
1501 (define-compilation catch (id &rest body)
1502   (js!selfcall
1503     "var id = " (ls-compile id) ";" *newline*
1504     "try {" *newline*
1505     (indent (ls-compile-block body t)) *newline*
1506     "}" *newline*
1507     "catch (cf){" *newline*
1508     "    if (cf.type == 'catch' && cf.id == id)" *newline*
1509     (if *multiple-value-p*
1510         "        return values.apply(this, forcemv(cf.values));"
1511         "        return pv.apply(this, forcemv(cf.values));")
1512     *newline*
1513     "    else" *newline*
1514     "        throw cf;" *newline*
1515     "}" *newline*))
1516
1517 (define-compilation throw (id value)
1518   (js!selfcall
1519     "var values = mv;" *newline*
1520     "throw ({"
1521     "type: 'catch', "
1522     "id: " (ls-compile id) ", "
1523     "values: " (ls-compile value t) ", "
1524     "message: 'Throw uncatched.'"
1525     "})"))
1526
1527
1528 (defvar *tagbody-counter* 0)
1529 (defvar *go-tag-counter* 0)
1530
1531 (defun go-tag-p (x)
1532   (or (integerp x) (symbolp x)))
1533
1534 (defun declare-tagbody-tags (tbidx body)
1535   (let ((bindings
1536          (mapcar (lambda (label)
1537                    (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1538                      (make-binding label 'gotag (list tbidx tagidx))))
1539                  (remove-if-not #'go-tag-p body))))
1540     (extend-lexenv bindings *environment* 'gotag)))
1541
1542 (define-compilation tagbody (&rest body)
1543   ;; Ignore the tagbody if it does not contain any go-tag. We do this
1544   ;; because 1) it is easy and 2) many built-in forms expand to a
1545   ;; implicit tagbody, so we save some space.
1546   (unless (some #'go-tag-p body)
1547     (return-from tagbody (ls-compile `(progn ,@body nil))))
1548   ;; The translation assumes the first form in BODY is a label
1549   (unless (go-tag-p (car body))
1550     (push (gensym "START") body))
1551   ;; Tagbody compilation
1552   (let ((tbidx (integer-to-string *tagbody-counter*)))
1553     (let ((*environment* (declare-tagbody-tags tbidx body))
1554           initag)
1555       (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1556         (setq initag (second (binding-value b))))
1557       (js!selfcall
1558         "var tagbody_" tbidx " = " initag ";" *newline*
1559         "tbloop:" *newline*
1560         "while (true) {" *newline*
1561         (indent "try {" *newline*
1562                 (indent (let ((content ""))
1563                           (concat "switch(tagbody_" tbidx "){" *newline*
1564                                   "case " initag ":" *newline*
1565                                   (dolist (form (cdr body) content)
1566                                     (concatf content
1567                                       (if (not (go-tag-p form))
1568                                           (indent (ls-compile form) ";" *newline*)
1569                                           (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1570                                             (concat "case " (second (binding-value b)) ":" *newline*)))))
1571                                   "default:" *newline*
1572                                   "    break tbloop;" *newline*
1573                                   "}" *newline*)))
1574                 "}" *newline*
1575                 "catch (jump) {" *newline*
1576                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1577                 "        tagbody_" tbidx " = jump.label;" *newline*
1578                 "    else" *newline*
1579                 "        throw(jump);" *newline*
1580                 "}" *newline*)
1581         "}" *newline*
1582         "return " (ls-compile nil) ";" *newline*))))
1583
1584 (define-compilation go (label)
1585   (let ((b (lookup-in-lexenv label *environment* 'gotag))
1586         (n (cond
1587              ((symbolp label) (symbol-name label))
1588              ((integerp label) (integer-to-string label)))))
1589     (if b
1590         (js!selfcall
1591           "throw ({"
1592           "type: 'tagbody', "
1593           "id: " (first (binding-value b)) ", "
1594           "label: " (second (binding-value b)) ", "
1595           "message: 'Attempt to GO to non-existing tag " n "'"
1596           "})" *newline*)
1597         (error (concat "Unknown tag `" n "'.")))))
1598
1599 (define-compilation unwind-protect (form &rest clean-up)
1600   (js!selfcall
1601     "var ret = " (ls-compile nil) ";" *newline*
1602     "try {" *newline*
1603     (indent "ret = " (ls-compile form) ";" *newline*)
1604     "} finally {" *newline*
1605     (indent (ls-compile-block clean-up))
1606     "}" *newline*
1607     "return ret;" *newline*))
1608
1609 (define-compilation multiple-value-call (func-form &rest forms)
1610   (js!selfcall
1611     "var func = " (ls-compile func-form) ";" *newline*
1612     "var args = [" (if *multiple-value-p* "values" "pv") "];" *newline*
1613     "return "
1614     (js!selfcall
1615       "var values = mv;" *newline*
1616       "var vs;" *newline*
1617       (mapconcat (lambda (form)
1618                    (concat "vs = " (ls-compile form t) ";" *newline*
1619                            "if (typeof vs === 'object' && 'multiple-value' in vs)" *newline*
1620                            (indent "args = args.concat(vs);" *newline*)
1621                            "else" *newline*
1622                            (indent "args.push(vs);" *newline*)))
1623                  forms)
1624       "return func.apply(window, args);" *newline*) ";" *newline*))
1625
1626 (define-compilation multiple-value-prog1 (first-form &rest forms)
1627   (js!selfcall
1628     "var args = " (ls-compile first-form *multiple-value-p*) ";" *newline*
1629     (ls-compile-block forms)
1630     "return args;" *newline*))
1631
1632
1633
1634 ;;; A little backquote implementation without optimizations of any
1635 ;;; kind for ecmalisp.
1636 (defun backquote-expand-1 (form)
1637   (cond
1638     ((symbolp form)
1639      (list 'quote form))
1640     ((atom form)
1641      form)
1642     ((eq (car form) 'unquote)
1643      (car form))
1644     ((eq (car form) 'backquote)
1645      (backquote-expand-1 (backquote-expand-1 (cadr form))))
1646     (t
1647      (cons 'append
1648            (mapcar (lambda (s)
1649                      (cond
1650                        ((and (listp s) (eq (car s) 'unquote))
1651                         (list 'list (cadr s)))
1652                        ((and (listp s) (eq (car s) 'unquote-splicing))
1653                         (cadr s))
1654                        (t
1655                         (list 'list (backquote-expand-1 s)))))
1656                    form)))))
1657
1658 (defun backquote-expand (form)
1659   (if (and (listp form) (eq (car form) 'backquote))
1660       (backquote-expand-1 (cadr form))
1661       form))
1662
1663 (defmacro backquote (form)
1664   (backquote-expand-1 form))
1665
1666 (define-transformation backquote (form)
1667   (backquote-expand-1 form))
1668
1669 ;;; Primitives
1670
1671 (defvar *builtins* nil)
1672
1673 (defmacro define-raw-builtin (name args &body body)
1674   ;; Creates a new primitive function `name' with parameters args and
1675   ;; @body. The body can access to the local environment through the
1676   ;; variable *ENVIRONMENT*.
1677   `(push (list ',name (lambda ,args (block ,name ,@body)))
1678          *builtins*))
1679
1680 (defmacro define-builtin (name args &body body)
1681   `(progn
1682      (define-raw-builtin ,name ,args
1683        (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1684          ,@body))))
1685
1686 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1687 (defmacro type-check (decls &body body)
1688   `(js!selfcall
1689      ,@(mapcar (lambda (decl)
1690                    `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1691                  decls)
1692      ,@(mapcar (lambda (decl)
1693                  `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1694                           (indent "throw 'The value ' + "
1695                                   ,(first decl)
1696                                   " + ' is not a type "
1697                                   ,(second decl)
1698                                   ".';"
1699                                   *newline*)))
1700                decls)
1701      (concat "return " (progn ,@body) ";" *newline*)))
1702
1703 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
1704 ;;; a variable which holds a list of forms. It will compile them and
1705 ;;; store the result in some Javascript variables. BODY is evaluated
1706 ;;; with ARGS bound to the list of these variables to generate the
1707 ;;; code which performs the transformation on these variables.
1708
1709 (defun variable-arity-call (args function)
1710   (unless (consp args)
1711     (error "ARGS must be a non-empty list"))
1712   (let ((counter 0)
1713         (variables '())
1714         (prelude ""))
1715     (dolist (x args)
1716       (let ((v (concat "x" (integer-to-string (incf counter)))))
1717         (push v variables)
1718         (concatf prelude
1719                  (concat "var " v " = " (ls-compile x) ";" *newline*
1720                          "if (typeof " v " !== 'number') throw 'Not a number!';"
1721                          *newline*))))
1722     (js!selfcall prelude (funcall function (reverse variables)))))
1723
1724
1725 (defmacro variable-arity (args &body body)
1726   (unless (symbolp args)
1727     (error "Bad usage of VARIABLE-ARITY, you must pass a symbol"))
1728   `(variable-arity-call ,args
1729                         (lambda (,args)
1730                           (concat "return " ,@body ";" *newline*))))
1731
1732 (defun num-op-num (x op y)
1733   (type-check (("x" "number" x) ("y" "number" y))
1734     (concat "x" op "y")))
1735
1736 (define-raw-builtin + (&rest numbers)
1737   (if (null numbers)
1738       "0"
1739       (variable-arity numbers
1740         (join numbers "+"))))
1741
1742 (define-raw-builtin - (x &rest others)
1743   (let ((args (cons x others)))
1744     (variable-arity args
1745       (if (null others)
1746           (concat "-" (car args))
1747           (join args "-")))))
1748
1749 (define-raw-builtin * (&rest numbers)
1750   (if (null numbers)
1751       "1"
1752       (variable-arity numbers
1753         (join numbers "*"))))
1754
1755 (define-raw-builtin / (x &rest others)
1756   (let ((args (cons x others)))
1757     (variable-arity args
1758       (if (null others)
1759           (concat "1 /" (car args))
1760           (join args "/")))))
1761
1762 (define-builtin mod (x y) (num-op-num x "%" y))
1763
1764
1765 (defun comparison-conjuntion (vars op)
1766   (cond
1767     ((null (cdr vars))
1768      "true")
1769     ((null (cddr vars))
1770      (concat (car vars) op (cadr vars)))
1771     (t
1772      (concat (car vars) op (cadr vars)
1773              " && "
1774              (comparison-conjuntion (cdr vars) op)))))
1775
1776 (defmacro define-builtin-comparison (op sym)
1777   `(define-raw-builtin ,op (x &rest args)
1778      (let ((args (cons x args)))
1779        (variable-arity args
1780          (js!bool (comparison-conjuntion args ,sym))))))
1781
1782 (define-builtin-comparison > ">")
1783 (define-builtin-comparison < "<")
1784 (define-builtin-comparison >= ">=")
1785 (define-builtin-comparison <= "<=")
1786 (define-builtin-comparison = "==")
1787
1788 (define-builtin numberp (x)
1789   (js!bool (concat "(typeof (" x ") == \"number\")")))
1790
1791 (define-builtin floor (x)
1792   (type-check (("x" "number" x))
1793     "Math.floor(x)"))
1794
1795 (define-builtin cons (x y)
1796   (concat "({car: " x ", cdr: " y "})"))
1797
1798 (define-builtin consp (x)
1799   (js!bool
1800    (js!selfcall
1801      "var tmp = " x ";" *newline*
1802      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1803
1804 (define-builtin car (x)
1805   (js!selfcall
1806     "var tmp = " x ";" *newline*
1807     "return tmp === " (ls-compile nil)
1808     "? " (ls-compile nil)
1809     ": tmp.car;" *newline*))
1810
1811 (define-builtin cdr (x)
1812   (js!selfcall
1813     "var tmp = " x ";" *newline*
1814     "return tmp === " (ls-compile nil) "? "
1815     (ls-compile nil)
1816     ": tmp.cdr;" *newline*))
1817
1818 (define-builtin rplaca (x new)
1819   (type-check (("x" "object" x))
1820     (concat "(x.car = " new ", x)")))
1821
1822 (define-builtin rplacd (x new)
1823   (type-check (("x" "object" x))
1824     (concat "(x.cdr = " new ", x)")))
1825
1826 (define-builtin symbolp (x)
1827   (js!bool
1828    (js!selfcall
1829      "var tmp = " x ";" *newline*
1830      "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1831
1832 (define-builtin make-symbol (name)
1833   (type-check (("name" "string" name))
1834     "({name: name})"))
1835
1836 (define-builtin symbol-name (x)
1837   (concat "(" x ").name"))
1838
1839 (define-builtin set (symbol value)
1840   (concat "(" symbol ").value = " value))
1841
1842 (define-builtin fset (symbol value)
1843   (concat "(" symbol ").fvalue = " value))
1844
1845 (define-builtin boundp (x)
1846   (js!bool (concat "(" x ".value !== undefined)")))
1847
1848 (define-builtin symbol-value (x)
1849   (js!selfcall
1850     "var symbol = " x ";" *newline*
1851     "var value = symbol.value;" *newline*
1852     "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1853     "return value;" *newline*))
1854
1855 (define-builtin symbol-function (x)
1856   (js!selfcall
1857     "var symbol = " x ";" *newline*
1858     "var func = symbol.fvalue;" *newline*
1859     "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1860     "return func;" *newline*))
1861
1862 (define-builtin symbol-plist (x)
1863   (concat "((" x ").plist || " (ls-compile nil) ")"))
1864
1865 (define-builtin lambda-code (x)
1866   (concat "(" x ").toString()"))
1867
1868 (define-builtin eq    (x y) (js!bool (concat "(" x " === " y ")")))
1869 (define-builtin equal (x y) (js!bool (concat "(" x  " == " y ")")))
1870
1871 (define-builtin char-to-string (x)
1872   (type-check (("x" "number" x))
1873     "String.fromCharCode(x)"))
1874
1875 (define-builtin stringp (x)
1876   (js!bool (concat "(typeof(" x ") == \"string\")")))
1877
1878 (define-builtin string-upcase (x)
1879   (type-check (("x" "string" x))
1880     "x.toUpperCase()"))
1881
1882 (define-builtin string-length (x)
1883   (type-check (("x" "string" x))
1884     "x.length"))
1885
1886 (define-raw-builtin slice (string a &optional b)
1887   (js!selfcall
1888     "var str = " (ls-compile string) ";" *newline*
1889     "var a = " (ls-compile a) ";" *newline*
1890     "var b;" *newline*
1891     (if b
1892         (concat "b = " (ls-compile b) ";" *newline*)
1893         "")
1894     "return str.slice(a,b);" *newline*))
1895
1896 (define-builtin char (string index)
1897   (type-check (("string" "string" string)
1898                ("index" "number" index))
1899     "string.charCodeAt(index)"))
1900
1901 (define-builtin concat-two (string1 string2)
1902   (type-check (("string1" "string" string1)
1903                ("string2" "string" string2))
1904     "string1.concat(string2)"))
1905
1906 (define-raw-builtin funcall (func &rest args)
1907   (concat "(" (ls-compile func) ")("
1908           (join (cons (if *multiple-value-p* "values" "pv")
1909                       (mapcar #'ls-compile args))
1910                 ", ")
1911           ")"))
1912
1913 (define-raw-builtin apply (func &rest args)
1914   (if (null args)
1915       (concat "(" (ls-compile func) ")()")
1916       (let ((args (butlast args))
1917             (last (car (last args))))
1918         (js!selfcall
1919           "var f = " (ls-compile func) ";" *newline*
1920           "var args = [" (join (cons (if *multiple-value-p* "values" "pv")
1921                                      (mapcar #'ls-compile args))
1922                                ", ")
1923           "];" *newline*
1924           "var tail = (" (ls-compile last) ");" *newline*
1925           "while (tail != " (ls-compile nil) "){" *newline*
1926           "    args.push(tail.car);" *newline*
1927           "    tail = tail.cdr;" *newline*
1928           "}" *newline*
1929           "return f.apply(this, args);" *newline*))))
1930
1931 (define-builtin js-eval (string)
1932   (type-check (("string" "string" string))
1933     (if *multiple-value-p*
1934         (js!selfcall
1935           "var v = eval.apply(window, [string]);" *newline*
1936           "if (typeof v !== 'object' || !('multiple-value' in v)){" *newline*
1937           (indent "v = [v];" *newline*
1938                   "v['multiple-value'] = true;" *newline*)
1939           "}" *newline*
1940           "return values.apply(this, v);" *newline*)
1941         "eval.apply(window, [string])")))
1942
1943 (define-builtin error (string)
1944   (js!selfcall "throw " string ";" *newline*))
1945
1946 (define-builtin new () "{}")
1947
1948 (define-builtin objectp (x)
1949   (js!bool (concat "(typeof (" x ") === 'object')")))
1950
1951 (define-builtin oget (object key)
1952   (js!selfcall
1953     "var tmp = " "(" object ")[" key "];" *newline*
1954     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1955
1956 (define-builtin oset (object key value)
1957   (concat "((" object ")[" key "] = " value ")"))
1958
1959 (define-builtin in (key object)
1960   (js!bool (concat "((" key ") in (" object "))")))
1961
1962 (define-builtin functionp (x)
1963   (js!bool (concat "(typeof " x " == 'function')")))
1964
1965 (define-builtin write-string (x)
1966   (type-check (("x" "string" x))
1967     "lisp.write(x)"))
1968
1969 (define-builtin make-array (n)
1970   (js!selfcall
1971     "var r = [];" *newline*
1972     "for (var i = 0; i < " n "; i++)" *newline*
1973     (indent "r.push(" (ls-compile nil) ");" *newline*)
1974     "return r;" *newline*))
1975
1976 (define-builtin arrayp (x)
1977   (js!bool
1978    (js!selfcall
1979      "var x = " x ";" *newline*
1980      "return typeof x === 'object' && 'length' in x;")))
1981
1982 (define-builtin aref (array n)
1983   (js!selfcall
1984     "var x = " "(" array ")[" n "];" *newline*
1985     "if (x === undefined) throw 'Out of range';" *newline*
1986     "return x;" *newline*))
1987
1988 (define-builtin aset (array n value)
1989   (js!selfcall
1990     "var x = " array ";" *newline*
1991     "var i = " n ";" *newline*
1992     "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
1993     "return x[i] = " value ";" *newline*))
1994
1995 (define-builtin get-unix-time ()
1996   (concat "(Math.round(new Date() / 1000))"))
1997
1998 (define-builtin values-array (array)
1999   (if *multiple-value-p*
2000       (concat "values.apply(this, " array ")")
2001       (concat "pv.apply(this, " array ")")))
2002
2003 (define-raw-builtin values (&rest args)
2004   (if *multiple-value-p*
2005       (concat "values(" (join (mapcar #'ls-compile args) ", ") ")")
2006       (concat "pv(" (join (mapcar #'ls-compile args) ", ") ")")))
2007
2008 (defun macro (x)
2009   (and (symbolp x)
2010        (let ((b (lookup-in-lexenv x *environment* 'function)))
2011          (and (eq (binding-type b) 'macro)
2012               b))))
2013
2014 (defun ls-macroexpand-1 (form)
2015   (let ((macro-binding (macro (car form))))
2016     (if macro-binding
2017         (let ((expander (binding-value macro-binding)))
2018           (when (listp expander)
2019             (let ((compiled (eval expander)))
2020               ;; The list representation are useful while
2021               ;; bootstrapping, as we can dump the definition of the
2022               ;; macros easily, but they are slow because we have to
2023               ;; evaluate them and compile them now and again. So, let
2024               ;; us replace the list representation version of the
2025               ;; function with the compiled one.
2026               ;;
2027               #+ecmalisp (set-binding-value macro-binding compiled)
2028               (setq expander compiled)))
2029           (apply expander (cdr form)))
2030         form)))
2031
2032 (defun compile-funcall (function args)
2033   (let ((values-funcs (if *multiple-value-p* "values" "pv")))
2034     (if (and (symbolp function)
2035              #+ecmalisp (eq (symbol-package function) (find-package "COMMON-LISP"))
2036              #+common-lisp t)
2037         (concat (ls-compile `',function) ".fvalue("
2038                 (join (cons values-funcs (mapcar #'ls-compile args))
2039                       ", ")
2040                 ")")
2041         (concat (ls-compile `#',function) "("
2042                 (join (cons values-funcs (mapcar #'ls-compile args))
2043                       ", ")
2044                 ")"))))
2045
2046 (defun ls-compile-block (sexps &optional return-last-p)
2047   (if return-last-p
2048       (concat (ls-compile-block (butlast sexps))
2049               "return " (ls-compile (car (last sexps)) *multiple-value-p*) ";")
2050       (join-trailing
2051        (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
2052        (concat ";" *newline*))))
2053
2054 (defun ls-compile (sexp &optional multiple-value-p)
2055   (let ((*multiple-value-p* multiple-value-p))
2056     (cond
2057       ((symbolp sexp)
2058        (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
2059          (cond
2060            ((and b (not (member 'special (binding-declarations b))))
2061             (binding-value b))
2062            ((or (keywordp sexp)
2063                 (member 'constant (binding-declarations b)))
2064             (concat (ls-compile `',sexp) ".value"))
2065            (t
2066             (ls-compile `(symbol-value ',sexp))))))
2067       ((integerp sexp) (integer-to-string sexp))
2068       ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
2069       ((arrayp sexp) (literal sexp))
2070       ((listp sexp)
2071        (let ((name (car sexp))
2072              (args (cdr sexp)))
2073          (cond
2074            ;; Special forms
2075            ((assoc name *compilations*)
2076             (let ((comp (second (assoc name *compilations*))))
2077               (apply comp args)))
2078            ;; Built-in functions
2079            ((and (assoc name *builtins*)
2080                  (not (claimp name 'function 'notinline)))
2081             (let ((comp (second (assoc name *builtins*))))
2082               (apply comp args)))
2083            (t
2084             (if (macro name)
2085                 (ls-compile (ls-macroexpand-1 sexp) multiple-value-p)
2086                 (compile-funcall name args))))))
2087       (t
2088        (error "How should I compile this?")))))
2089
2090 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
2091   (let ((*toplevel-compilations* nil))
2092     (cond
2093       ((and (consp sexp) (eq (car sexp) 'progn))
2094        (let ((subs (mapcar (lambda (s)
2095                              (ls-compile-toplevel s t))
2096                            (cdr sexp))))
2097          (join (remove-if #'null-or-empty-p subs))))
2098       (t
2099        (let ((code (ls-compile sexp multiple-value-p)))
2100          (concat (join-trailing (get-toplevel-compilations)
2101                                 (concat ";" *newline*))
2102                  (if code
2103                      (concat code ";" *newline*)
2104                      "")))))))
2105
2106
2107 ;;; Once we have the compiler, we define the runtime environment and
2108 ;;; interactive development (eval), which works calling the compiler
2109 ;;; and evaluating the Javascript result globally.
2110
2111 #+ecmalisp
2112 (progn
2113   (defun eval (x)
2114     (js-eval (ls-compile-toplevel x t)))
2115
2116   (export '(&rest &optional &body * *gensym-counter* *package* + - / 1+ 1- < <= =
2117             = > >= and append apply aref arrayp aset assoc atom block boundp
2118             boundp butlast caar cadddr caddr cadr car car case catch cdar cdddr
2119             cddr cdr cdr char char-code char= code-char cond cons consp copy-list
2120             decf declaim defparameter defun defmacro defvar digit-char-p
2121             disassemble documentation dolist dotimes ecase eq eql equal error eval
2122             every export fdefinition find-package find-symbol first fourth fset
2123             funcall function functionp gensym get-universal-time go identity if
2124             in-package incf integerp integerp intern keywordp lambda last length
2125             let let* list-all-packages list listp make-array make-package
2126             make-symbol mapcar member minusp mod multiple-value-bind
2127             multiple-value-call multiple-value-list multiple-value-prog1 nil not
2128             nth nthcdr null numberp or package-name package-use-list packagep
2129             plusp prin1-to-string print proclaim prog1 prog2 progn psetq push
2130             quote remove remove-if remove-if-not return return-from revappend
2131             reverse rplaca rplacd second set setq some string-upcase string
2132             string= stringp subseq symbol-function symbol-name symbol-package
2133             symbol-plist symbol-value symbolp t tagbody third throw truncate
2134             unless unwind-protect values values-list variable warn when write-line
2135             write-string zerop))
2136
2137   (setq *package* *user-package*)
2138
2139   (js-eval "var lisp")
2140   (js-vset "lisp" (new))
2141   (js-vset "lisp.read" #'ls-read-from-string)
2142   (js-vset "lisp.print" #'prin1-to-string)
2143   (js-vset "lisp.eval" #'eval)
2144   (js-vset "lisp.compile" (lambda (s) (ls-compile-toplevel s t)))
2145   (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
2146   (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str) t)))
2147
2148   ;; Set the initial global environment to be equal to the host global
2149   ;; environment at this point of the compilation.
2150   (eval-when-compile
2151     (toplevel-compilation
2152      (ls-compile
2153       `(progn
2154          ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
2155                    *literal-symbols*)
2156          (setq *literal-symbols* ',*literal-symbols*)
2157          (setq *environment* ',*environment*)
2158          (setq *variable-counter* ,*variable-counter*)
2159          (setq *gensym-counter* ,*gensym-counter*)
2160          (setq *block-counter* ,*block-counter*)))))
2161
2162   (eval-when-compile
2163     (toplevel-compilation
2164      (ls-compile
2165       `(setq *literal-counter* ,*literal-counter*)))))
2166
2167
2168 ;;; Finally, we provide a couple of functions to easily bootstrap
2169 ;;; this. It just calls the compiler with this file as input.
2170
2171 #+common-lisp
2172 (progn
2173   (defun read-whole-file (filename)
2174     (with-open-file (in filename)
2175       (let ((seq (make-array (file-length in) :element-type 'character)))
2176         (read-sequence seq in)
2177         seq)))
2178
2179   (defun ls-compile-file (filename output)
2180     (let ((*compiling-file* t))
2181       (with-open-file (out output :direction :output :if-exists :supersede)
2182         (write-string (read-whole-file "prelude.js") out)
2183         (let* ((source (read-whole-file filename))
2184                (in (make-string-stream source)))
2185           (loop
2186              for x = (ls-read in)
2187              until (eq x *eof*)
2188              for compilation = (ls-compile-toplevel x)
2189              when (plusp (length compilation))
2190              do (write-string compilation out))))))
2191
2192   (defun bootstrap ()
2193     (setq *environment* (make-lexenv))
2194     (setq *literal-symbols* nil)
2195     (setq *variable-counter* 0
2196           *gensym-counter* 0
2197           *literal-counter* 0
2198           *block-counter* 0)
2199     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))