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