Create a first parameter VALUES (unused by now) in each function and each funcall
[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 (cons "values"
1152                    (mapcar #'translate-variable
1153                            (append required-arguments optional-arguments)))
1154              ",")
1155        "){" *newline*
1156        ;; Check number of arguments
1157        (indent
1158         (if required-arguments
1159             (concat "if (arguments.length < " (integer-to-string (1+ n-required-arguments))
1160                     ") throw 'too few arguments';" *newline*)
1161             "")
1162         (if (not rest-argument)
1163             (concat "if (arguments.length > "
1164                     (integer-to-string (+ 1 n-required-arguments n-optional-arguments))
1165                     ") throw 'too many arguments';" *newline*)
1166             "")
1167         ;; Optional arguments
1168         (if optional-arguments
1169             (concat "switch(arguments.length-1){" *newline*
1170                     (let ((optional-and-defaults
1171                            (lambda-list-optional-arguments-with-default lambda-list))
1172                           (cases nil)
1173                           (idx 0))
1174                       (progn
1175                         (while (< idx n-optional-arguments)
1176                           (let ((arg (nth idx optional-and-defaults)))
1177                             (push (concat "case "
1178                                           (integer-to-string (+ idx n-required-arguments)) ":" *newline*
1179                                           (translate-variable (car arg))
1180                                           "="
1181                                           (ls-compile (cadr arg))
1182                                           ";" *newline*)
1183                                   cases)
1184                             (incf idx)))
1185                         (push (concat "default: break;" *newline*) cases)
1186                         (join (reverse cases))))
1187                     "}" *newline*)
1188             "")
1189         ;; &rest/&body argument
1190         (if rest-argument
1191             (let ((js!rest (translate-variable rest-argument)))
1192               (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
1193                       "for (var i = arguments.length-1; i>="
1194                       (integer-to-string (+ 1 n-required-arguments n-optional-arguments))
1195                       "; i--)" *newline*
1196                       (indent js!rest " = "
1197                               "{car: arguments[i], cdr: ") js!rest "};"
1198                       *newline*))
1199             "")
1200         ;; Body
1201         (ls-compile-block body t)) *newline*
1202        "})"))))
1203
1204
1205 (defun setq-pair (var val)
1206   (let ((b (lookup-in-lexenv var *environment* 'variable)))
1207     (if (eq (binding-type b) 'lexical-variable)
1208         (concat (binding-value b) " = " (ls-compile val))
1209         (ls-compile `(set ',var ,val)))))
1210
1211 (define-compilation setq (&rest pairs)
1212   (let ((result ""))
1213     (while t
1214       (cond
1215         ((null pairs) (return))
1216         ((null (cdr pairs))
1217          (error "Odd paris in SETQ"))
1218         (t
1219          (concatf result
1220            (concat (setq-pair (car pairs) (cadr pairs))
1221                    (if (null (cddr pairs)) "" ", ")))
1222          (setq pairs (cddr pairs)))))
1223     (concat "(" result ")")))
1224
1225 ;;; FFI Variable accessors
1226 (define-compilation js-vref (var)
1227   var)
1228
1229 (define-compilation js-vset (var val)
1230   (concat "(" var " = " (ls-compile val) ")"))
1231
1232
1233 ;;; Literals
1234 (defun escape-string (string)
1235   (let ((output "")
1236         (index 0)
1237         (size (length string)))
1238     (while (< index size)
1239       (let ((ch (char string index)))
1240         (when (or (char= ch #\") (char= ch #\\))
1241           (setq output (concat output "\\")))
1242         (when (or (char= ch #\newline))
1243           (setq output (concat output "\\"))
1244           (setq ch #\n))
1245         (setq output (concat output (string ch))))
1246       (incf index))
1247     output))
1248
1249
1250 (defvar *literal-symbols* nil)
1251 (defvar *literal-counter* 0)
1252
1253 (defun genlit ()
1254   (concat "l" (integer-to-string (incf *literal-counter*))))
1255
1256 (defun literal (sexp &optional recursive)
1257   (cond
1258     ((integerp sexp) (integer-to-string sexp))
1259     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1260     ((symbolp sexp)
1261      (or (cdr (assoc sexp *literal-symbols*))
1262          (let ((v (genlit))
1263                (s #+common-lisp (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1264                   #+ecmalisp
1265                   (let ((package (symbol-package sexp)))
1266                     (if (null package)
1267                         (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1268                         (ls-compile `(intern ,(symbol-name sexp) ,(package-name package)))))))
1269            (push (cons sexp v) *literal-symbols*)
1270            (toplevel-compilation (concat "var " v " = " s))
1271            v)))
1272     ((consp sexp)
1273      (let ((c (concat "{car: " (literal (car sexp) t) ", "
1274                       "cdr: " (literal (cdr sexp) t) "}")))
1275        (if recursive
1276            c
1277            (let ((v (genlit)))
1278              (toplevel-compilation (concat "var " v " = " c))
1279              v))))
1280     ((arrayp sexp)
1281      (let ((elements (vector-to-list sexp)))
1282        (let ((c (concat "[" (join (mapcar #'literal elements) ", ") "]")))
1283          (if recursive
1284              c
1285              (let ((v (genlit)))
1286                (toplevel-compilation (concat "var " v " = " c))
1287                v)))))))
1288
1289 (define-compilation quote (sexp)
1290   (literal sexp))
1291
1292 (define-compilation %while (pred &rest body)
1293   (js!selfcall
1294     "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1295     (indent (ls-compile-block body))
1296     "}"
1297     "return " (ls-compile nil) ";" *newline*))
1298
1299 (define-compilation function (x)
1300   (cond
1301     ((and (listp x) (eq (car x) 'lambda))
1302      (ls-compile x))
1303     ((symbolp x)
1304      (ls-compile `(symbol-function ',x)))))
1305
1306 (define-compilation eval-when-compile (&rest body)
1307   (eval (cons 'progn body))
1308   nil)
1309
1310 (defmacro define-transformation (name args form)
1311   `(define-compilation ,name ,args
1312      (ls-compile ,form)))
1313
1314 (define-compilation progn (&rest body)
1315   (js!selfcall (ls-compile-block body t)))
1316
1317 (defun special-variable-p (x)
1318   (and (claimp x 'variable 'special) t))
1319
1320 ;;; Wrap CODE to restore the symbol values of the dynamic
1321 ;;; bindings. BINDINGS is a list of pairs of the form
1322 ;;; (SYMBOL . PLACE),  where PLACE is a Javascript variable
1323 ;;; name to initialize the symbol value and where to stored
1324 ;;; the old value.
1325 (defun let-binding-wrapper (bindings body)
1326   (when (null bindings)
1327     (return-from let-binding-wrapper body))
1328   (concat
1329    "try {" *newline*
1330    (indent "var tmp;" *newline*
1331            (mapconcat
1332             (lambda (b)
1333               (let ((s (ls-compile `(quote ,(car b)))))
1334                 (concat "tmp = " s ".value;" *newline*
1335                         s ".value = " (cdr b) ";" *newline*
1336                         (cdr b) " = tmp;" *newline*)))
1337             bindings)
1338            body *newline*)
1339    "}" *newline*
1340    "finally {"  *newline*
1341    (indent
1342     (mapconcat (lambda (b)
1343                  (let ((s (ls-compile `(quote ,(car b)))))
1344                    (concat s ".value" " = " (cdr b) ";" *newline*)))
1345                bindings))
1346    "}" *newline*))
1347
1348 (define-compilation let (bindings &rest body)
1349   (let* ((bindings (mapcar #'ensure-list bindings))
1350          (variables (mapcar #'first bindings))
1351          (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
1352          (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
1353          (dynamic-bindings))
1354     (concat "(function("
1355             (join (mapcar (lambda (x)
1356                             (if (special-variable-p x)
1357                                 (let ((v (gvarname x)))
1358                                   (push (cons x v) dynamic-bindings)
1359                                   v)
1360                                 (translate-variable x)))
1361                           variables)
1362                   ",")
1363             "){" *newline*
1364             (let ((body (ls-compile-block body t)))
1365               (indent (let-binding-wrapper dynamic-bindings body)))
1366             "})(" (join cvalues ",") ")")))
1367
1368
1369 ;;; Return the code to initialize BINDING, and push it extending the
1370 ;;; current lexical environment if the variable is special.
1371 (defun let*-initialize-value (binding)
1372   (let ((var (first binding))
1373         (value (second binding)))
1374     (if (special-variable-p var)
1375         (concat (ls-compile `(setq ,var ,value)) ";" *newline*)
1376         (let* ((v (gvarname var))
1377                (b (make-binding var 'variable v)))
1378           (prog1 (concat "var " v " = " (ls-compile value) ";" *newline*)
1379             (push-to-lexenv b *environment* 'variable))))))
1380
1381 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
1382 ;;; DOES NOT generate code to initialize the value of the symbols,
1383 ;;; unlike let-binding-wrapper.
1384 (defun let*-binding-wrapper (symbols body)
1385   (when (null symbols)
1386     (return-from let*-binding-wrapper body))
1387   (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
1388                        (remove-if-not #'special-variable-p symbols))))
1389     (concat
1390      "try {" *newline*
1391      (indent
1392       (mapconcat (lambda (b)
1393                    (let ((s (ls-compile `(quote ,(car b)))))
1394                      (concat "var " (cdr b) " = " s ".value;" *newline*)))
1395                  store)
1396       body)
1397      "}" *newline*
1398      "finally {" *newline*
1399      (indent
1400       (mapconcat (lambda (b)
1401                    (let ((s (ls-compile `(quote ,(car b)))))
1402                      (concat s ".value" " = " (cdr b) ";" *newline*)))
1403                  store))
1404      "}" *newline*)))
1405
1406
1407 (define-compilation let* (bindings &rest body)
1408   (let ((bindings (mapcar #'ensure-list bindings))
1409         (*environment* (copy-lexenv *environment*)))
1410     (js!selfcall
1411       (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
1412             (body (concat (mapconcat #'let*-initialize-value bindings)
1413                           (ls-compile-block body t))))
1414         (let*-binding-wrapper specials body)))))
1415
1416
1417 (defvar *block-counter* 0)
1418
1419 (define-compilation block (name &rest body)
1420   (let ((tr (integer-to-string (incf *block-counter*))))
1421     (let ((b (make-binding name 'block tr)))
1422       (js!selfcall
1423         "try {" *newline*
1424         (let ((*environment* (extend-lexenv (list b) *environment* 'block)))
1425           (indent "return " (ls-compile `(progn ,@body)) ";" *newline*))
1426         "}" *newline*
1427         "catch (cf){" *newline*
1428         "    if (cf.type == 'block' && cf.id == " tr ")" *newline*
1429         "        return cf.value;" *newline*
1430         "    else" *newline*
1431         "        throw cf;" *newline*
1432         "}" *newline*))))
1433
1434 (define-compilation return-from (name &optional value)
1435   (let ((b (lookup-in-lexenv name *environment* 'block)))
1436     (if b
1437         (js!selfcall
1438           "throw ({"
1439           "type: 'block', "
1440           "id: " (binding-value b) ", "
1441           "value: " (ls-compile value) ", "
1442           "message: 'Return from unknown block " (symbol-name name) ".'"
1443           "})")
1444         (error (concat "Unknown block `" (symbol-name name) "'.")))))
1445
1446
1447 (define-compilation catch (id &rest body)
1448   (js!selfcall
1449     "var id = " (ls-compile id) ";" *newline*
1450     "try {" *newline*
1451     (indent "return " (ls-compile `(progn ,@body))
1452             ";" *newline*)
1453     "}" *newline*
1454     "catch (cf){" *newline*
1455     "    if (cf.type == 'catch' && cf.id == id)" *newline*
1456     "        return cf.value;" *newline*
1457     "    else" *newline*
1458     "        throw cf;" *newline*
1459     "}" *newline*))
1460
1461 (define-compilation throw (id value)
1462   (js!selfcall
1463     "throw ({"
1464     "type: 'catch', "
1465     "id: " (ls-compile id) ", "
1466     "value: " (ls-compile value) ", "
1467     "message: 'Throw uncatched.'"
1468     "})"))
1469
1470
1471 (defvar *tagbody-counter* 0)
1472 (defvar *go-tag-counter* 0)
1473
1474 (defun go-tag-p (x)
1475   (or (integerp x) (symbolp x)))
1476
1477 (defun declare-tagbody-tags (tbidx body)
1478   (let ((bindings
1479          (mapcar (lambda (label)
1480                    (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1481                      (make-binding label 'gotag (list tbidx tagidx))))
1482                  (remove-if-not #'go-tag-p body))))
1483     (extend-lexenv bindings *environment* 'gotag)))
1484
1485 (define-compilation tagbody (&rest body)
1486   ;; Ignore the tagbody if it does not contain any go-tag. We do this
1487   ;; because 1) it is easy and 2) many built-in forms expand to a
1488   ;; implicit tagbody, so we save some space.
1489   (unless (some #'go-tag-p body)
1490     (return-from tagbody (ls-compile `(progn ,@body nil))))
1491   ;; The translation assumes the first form in BODY is a label
1492   (unless (go-tag-p (car body))
1493     (push (gensym "START") body))
1494   ;; Tagbody compilation
1495   (let ((tbidx (integer-to-string *tagbody-counter*)))
1496     (let ((*environment* (declare-tagbody-tags tbidx body))
1497           initag)
1498       (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1499         (setq initag (second (binding-value b))))
1500       (js!selfcall
1501         "var tagbody_" tbidx " = " initag ";" *newline*
1502         "tbloop:" *newline*
1503         "while (true) {" *newline*
1504         (indent "try {" *newline*
1505                 (indent (let ((content ""))
1506                           (concat "switch(tagbody_" tbidx "){" *newline*
1507                                   "case " initag ":" *newline*
1508                                   (dolist (form (cdr body) content)
1509                                     (concatf content
1510                                       (if (not (go-tag-p form))
1511                                           (indent (ls-compile form) ";" *newline*)
1512                                           (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1513                                             (concat "case " (second (binding-value b)) ":" *newline*)))))
1514                                   "default:" *newline*
1515                                   "    break tbloop;" *newline*
1516                                   "}" *newline*)))
1517                 "}" *newline*
1518                 "catch (jump) {" *newline*
1519                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1520                 "        tagbody_" tbidx " = jump.label;" *newline*
1521                 "    else" *newline*
1522                 "        throw(jump);" *newline*
1523                 "}" *newline*)
1524         "}" *newline*
1525         "return " (ls-compile nil) ";" *newline*))))
1526
1527 (define-compilation go (label)
1528   (let ((b (lookup-in-lexenv label *environment* 'gotag))
1529         (n (cond
1530              ((symbolp label) (symbol-name label))
1531              ((integerp label) (integer-to-string label)))))
1532     (if b
1533         (js!selfcall
1534           "throw ({"
1535           "type: 'tagbody', "
1536           "id: " (first (binding-value b)) ", "
1537           "label: " (second (binding-value b)) ", "
1538           "message: 'Attempt to GO to non-existing tag " n "'"
1539           "})" *newline*)
1540         (error (concat "Unknown tag `" n "'.")))))
1541
1542
1543 (define-compilation unwind-protect (form &rest clean-up)
1544   (js!selfcall
1545     "var ret = " (ls-compile nil) ";" *newline*
1546     "try {" *newline*
1547     (indent "ret = " (ls-compile form) ";" *newline*)
1548     "} finally {" *newline*
1549     (indent (ls-compile-block clean-up))
1550     "}" *newline*
1551     "return ret;" *newline*))
1552
1553
1554 ;;; A little backquote implementation without optimizations of any
1555 ;;; kind for ecmalisp.
1556 (defun backquote-expand-1 (form)
1557   (cond
1558     ((symbolp form)
1559      (list 'quote form))
1560     ((atom form)
1561      form)
1562     ((eq (car form) 'unquote)
1563      (car form))
1564     ((eq (car form) 'backquote)
1565      (backquote-expand-1 (backquote-expand-1 (cadr form))))
1566     (t
1567      (cons 'append
1568            (mapcar (lambda (s)
1569                      (cond
1570                        ((and (listp s) (eq (car s) 'unquote))
1571                         (list 'list (cadr s)))
1572                        ((and (listp s) (eq (car s) 'unquote-splicing))
1573                         (cadr s))
1574                        (t
1575                         (list 'list (backquote-expand-1 s)))))
1576                    form)))))
1577
1578 (defun backquote-expand (form)
1579   (if (and (listp form) (eq (car form) 'backquote))
1580       (backquote-expand-1 (cadr form))
1581       form))
1582
1583 (defmacro backquote (form)
1584   (backquote-expand-1 form))
1585
1586 (define-transformation backquote (form)
1587   (backquote-expand-1 form))
1588
1589 ;;; Primitives
1590
1591 (defvar *builtins* nil)
1592
1593 (defmacro define-raw-builtin (name args &body body)
1594   ;; Creates a new primitive function `name' with parameters args and
1595   ;; @body. The body can access to the local environment through the
1596   ;; variable *ENVIRONMENT*.
1597   `(push (list ',name (lambda ,args (block ,name ,@body)))
1598          *builtins*))
1599
1600 (defmacro define-builtin (name args &body body)
1601   `(progn
1602      (define-raw-builtin ,name ,args
1603        (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1604          ,@body))))
1605
1606 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1607 (defmacro type-check (decls &body body)
1608   `(js!selfcall
1609      ,@(mapcar (lambda (decl)
1610                    `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1611                  decls)
1612      ,@(mapcar (lambda (decl)
1613                  `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1614                           (indent "throw 'The value ' + "
1615                                   ,(first decl)
1616                                   " + ' is not a type "
1617                                   ,(second decl)
1618                                   ".';"
1619                                   *newline*)))
1620                decls)
1621      (concat "return " (progn ,@body) ";" *newline*)))
1622
1623 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
1624 ;;; a variable which holds a list of forms. It will compile them and
1625 ;;; store the result in some Javascript variables. BODY is evaluated
1626 ;;; with ARGS bound to the list of these variables to generate the
1627 ;;; code which performs the transformation on these variables.
1628
1629 (defun variable-arity-call (args function)
1630   (unless (consp args)
1631     (error "ARGS must be a non-empty list"))
1632   (let ((counter 0)
1633         (variables '())
1634         (prelude ""))
1635     (dolist (x args)
1636       (let ((v (concat "x" (integer-to-string (incf counter)))))
1637         (push v variables)
1638         (concatf prelude
1639                  (concat "var " v " = " (ls-compile x) ";" *newline*
1640                          "if (typeof " v " !== 'number') throw 'Not a number!';"
1641                          *newline*))))
1642     (js!selfcall prelude (funcall function (reverse variables)))))
1643
1644
1645 (defmacro variable-arity (args &body body)
1646   (unless (symbolp args)
1647     (error "Bad usage of VARIABLE-ARITY, you must pass a symbol"))
1648   `(variable-arity-call ,args
1649                         (lambda (,args)
1650                           (concat "return " ,@body ";" *newline*))))
1651
1652 (defun num-op-num (x op y)
1653   (type-check (("x" "number" x) ("y" "number" y))
1654     (concat "x" op "y")))
1655
1656 (define-raw-builtin + (&rest numbers)
1657   (if (null numbers)
1658       "0"
1659       (variable-arity numbers
1660         (join numbers "+"))))
1661
1662 (define-raw-builtin - (x &rest others)
1663   (let ((args (cons x others)))
1664     (variable-arity args
1665       (if (null others)
1666           (concat "-" (car args))
1667           (join args "-")))))
1668
1669 (define-raw-builtin * (&rest numbers)
1670   (if (null numbers)
1671       "1"
1672       (variable-arity numbers
1673         (join numbers "*"))))
1674
1675 (define-raw-builtin / (x &rest others)
1676   (let ((args (cons x others)))
1677     (variable-arity args
1678       (if (null others)
1679           (concat "1 /" (car args))
1680           (join args "/")))))
1681
1682 (define-builtin mod (x y) (num-op-num x "%" y))
1683
1684
1685 (defun comparison-conjuntion (vars op)
1686   (cond
1687     ((null (cdr vars))
1688      "true")
1689     ((null (cddr vars))
1690      (concat (car vars) op (cadr vars)))
1691     (t
1692      (concat (car vars) op (cadr vars)
1693              " && "
1694              (comparison-conjuntion (cdr vars) op)))))
1695
1696 (defmacro define-builtin-comparison (op sym)
1697   `(define-raw-builtin ,op (x &rest args)
1698      (let ((args (cons x args)))
1699        (variable-arity args
1700          (js!bool (comparison-conjuntion args ,sym))))))
1701
1702 (define-builtin-comparison > ">")
1703 (define-builtin-comparison < "<")
1704 (define-builtin-comparison >= ">=")
1705 (define-builtin-comparison <= "<=")
1706 (define-builtin-comparison = "==")
1707
1708 (define-builtin numberp (x)
1709   (js!bool (concat "(typeof (" x ") == \"number\")")))
1710
1711 (define-builtin floor (x)
1712   (type-check (("x" "number" x))
1713     "Math.floor(x)"))
1714
1715 (define-builtin cons (x y)
1716   (concat "({car: " x ", cdr: " y "})"))
1717
1718 (define-builtin consp (x)
1719   (js!bool
1720    (js!selfcall
1721      "var tmp = " x ";" *newline*
1722      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1723
1724 (define-builtin car (x)
1725   (js!selfcall
1726     "var tmp = " x ";" *newline*
1727     "return tmp === " (ls-compile nil)
1728     "? " (ls-compile nil)
1729     ": tmp.car;" *newline*))
1730
1731 (define-builtin cdr (x)
1732   (js!selfcall
1733     "var tmp = " x ";" *newline*
1734     "return tmp === " (ls-compile nil) "? "
1735     (ls-compile nil)
1736     ": tmp.cdr;" *newline*))
1737
1738 (define-builtin setcar (x new)
1739   (type-check (("x" "object" x))
1740     (concat "(x.car = " new ")")))
1741
1742 (define-builtin setcdr (x new)
1743   (type-check (("x" "object" x))
1744     (concat "(x.cdr = " new ")")))
1745
1746 (define-builtin symbolp (x)
1747   (js!bool
1748    (js!selfcall
1749      "var tmp = " x ";" *newline*
1750      "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1751
1752 (define-builtin make-symbol (name)
1753   (type-check (("name" "string" name))
1754     "({name: name})"))
1755
1756 (define-builtin symbol-name (x)
1757   (concat "(" x ").name"))
1758
1759 (define-builtin set (symbol value)
1760   (concat "(" symbol ").value = " value))
1761
1762 (define-builtin fset (symbol value)
1763   (concat "(" symbol ").fvalue = " value))
1764
1765 (define-builtin boundp (x)
1766   (js!bool (concat "(" x ".value !== undefined)")))
1767
1768 (define-builtin symbol-value (x)
1769   (js!selfcall
1770     "var symbol = " x ";" *newline*
1771     "var value = symbol.value;" *newline*
1772     "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1773     "return value;" *newline*))
1774
1775 (define-builtin symbol-function (x)
1776   (js!selfcall
1777     "var symbol = " x ";" *newline*
1778     "var func = symbol.fvalue;" *newline*
1779     "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1780     "return func;" *newline*))
1781
1782 (define-builtin symbol-plist (x)
1783   (concat "((" x ").plist || " (ls-compile nil) ")"))
1784
1785 (define-builtin lambda-code (x)
1786   (concat "(" x ").toString()"))
1787
1788 (define-builtin eq    (x y) (js!bool (concat "(" x " === " y ")")))
1789 (define-builtin equal (x y) (js!bool (concat "(" x  " == " y ")")))
1790
1791 (define-builtin char-to-string (x)
1792   (type-check (("x" "number" x))
1793     "String.fromCharCode(x)"))
1794
1795 (define-builtin stringp (x)
1796   (js!bool (concat "(typeof(" x ") == \"string\")")))
1797
1798 (define-builtin string-upcase (x)
1799   (type-check (("x" "string" x))
1800     "x.toUpperCase()"))
1801
1802 (define-builtin string-length (x)
1803   (type-check (("x" "string" x))
1804     "x.length"))
1805
1806 (define-raw-builtin slice (string a &optional b)
1807   (js!selfcall
1808     "var str = " (ls-compile string) ";" *newline*
1809     "var a = " (ls-compile a) ";" *newline*
1810     "var b;" *newline*
1811     (if b
1812         (concat "b = " (ls-compile b) ";" *newline*)
1813         "")
1814     "return str.slice(a,b);" *newline*))
1815
1816 (define-builtin char (string index)
1817   (type-check (("string" "string" string)
1818                ("index" "number" index))
1819     "string.charCodeAt(index)"))
1820
1821 (define-builtin concat-two (string1 string2)
1822   (type-check (("string1" "string" string1)
1823                ("string2" "string" string2))
1824     "string1.concat(string2)"))
1825
1826 (define-raw-builtin funcall (func &rest args)
1827   (concat "(" (ls-compile func) ")("
1828           (join (cons "id" (mapcar #'ls-compile args))
1829                 ", ")
1830           ")"))
1831
1832 (define-raw-builtin apply (func &rest args)
1833   (if (null args)
1834       (concat "(" (ls-compile func) ")()")
1835       (let ((args (butlast args))
1836             (last (car (last args))))
1837         (js!selfcall
1838           "var f = " (ls-compile func) ";" *newline*
1839           "var args = [" (join (cons "id" (mapcar #'ls-compile args))
1840                                ", ")
1841           "];" *newline*
1842           "var tail = (" (ls-compile last) ");" *newline*
1843           "while (tail != " (ls-compile nil) "){" *newline*
1844           "    args.push(tail.car);" *newline*
1845           "    tail = tail.cdr;" *newline*
1846           "}" *newline*
1847           "return f.apply(this, args);" *newline*))))
1848
1849 (define-builtin js-eval (string)
1850   (type-check (("string" "string" string))
1851     "eval.apply(window, [string])"))
1852
1853 (define-builtin error (string)
1854   (js!selfcall "throw " string ";" *newline*))
1855
1856 (define-builtin new () "{}")
1857
1858 (define-builtin objectp (x)
1859   (js!bool (concat "(typeof (" x ") === 'object')")))
1860
1861 (define-builtin oget (object key)
1862   (js!selfcall
1863     "var tmp = " "(" object ")[" key "];" *newline*
1864     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1865
1866 (define-builtin oset (object key value)
1867   (concat "((" object ")[" key "] = " value ")"))
1868
1869 (define-builtin in (key object)
1870   (js!bool (concat "((" key ") in (" object "))")))
1871
1872 (define-builtin functionp (x)
1873   (js!bool (concat "(typeof " x " == 'function')")))
1874
1875 (define-builtin write-string (x)
1876   (type-check (("x" "string" x))
1877     "lisp.write(x)"))
1878
1879 (define-builtin make-array (n)
1880   (js!selfcall
1881     "var r = [];" *newline*
1882     "for (var i = 0; i < " n "; i++)" *newline*
1883     (indent "r.push(" (ls-compile nil) ");" *newline*)
1884     "return r;" *newline*))
1885
1886 (define-builtin arrayp (x)
1887   (js!bool
1888    (js!selfcall
1889      "var x = " x ";" *newline*
1890      "return typeof x === 'object' && 'length' in x;")))
1891
1892 (define-builtin aref (array n)
1893   (js!selfcall
1894     "var x = " "(" array ")[" n "];" *newline*
1895     "if (x === undefined) throw 'Out of range';" *newline*
1896     "return x;" *newline*))
1897
1898 (define-builtin aset (array n value)
1899   (js!selfcall
1900     "var x = " array ";" *newline*
1901     "var i = " n ";" *newline*
1902     "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
1903     "return x[i] = " value ";" *newline*))
1904
1905 (define-builtin get-unix-time ()
1906   (concat "(Math.round(new Date() / 1000))"))
1907
1908
1909 (defun macro (x)
1910   (and (symbolp x)
1911        (let ((b (lookup-in-lexenv x *environment* 'function)))
1912          (and (eq (binding-type b) 'macro)
1913               b))))
1914
1915 (defun ls-macroexpand-1 (form)
1916   (let ((macro-binding (macro (car form))))
1917     (if macro-binding
1918         (let ((expander (binding-value macro-binding)))
1919           (when (listp expander)
1920             (let ((compiled (eval expander)))
1921               ;; The list representation are useful while
1922               ;; bootstrapping, as we can dump the definition of the
1923               ;; macros easily, but they are slow because we have to
1924               ;; evaluate them and compile them now and again. So, let
1925               ;; us replace the list representation version of the
1926               ;; function with the compiled one.
1927               ;;
1928               #+ecmalisp (set-binding-value macro-binding compiled)
1929               (setq expander compiled)))
1930           (apply expander (cdr form)))
1931         form)))
1932
1933 (defun compile-funcall (function args)
1934   (if (and (symbolp function)
1935            (claimp function 'function 'non-overridable))
1936       (concat (ls-compile `',function) ".fvalue("
1937               (join (cons "id" (mapcar #'ls-compile args))
1938                     ", ")
1939               ")")
1940       (concat (ls-compile `#',function) "("
1941               (join (cons "id" (mapcar #'ls-compile args))
1942                     ", ")
1943               ")")))
1944
1945 (defun ls-compile-block (sexps &optional return-last-p)
1946   (if return-last-p
1947       (concat (ls-compile-block (butlast sexps))
1948               "return " (ls-compile (car (last sexps))) ";")
1949       (join-trailing
1950        (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
1951        (concat ";" *newline*))))
1952
1953 (defun ls-compile (sexp)
1954   (cond
1955     ((symbolp sexp)
1956      (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1957        (cond
1958          ((and b (not (member 'special (binding-declarations b))))
1959           (binding-value b))
1960          ((or (keywordp sexp)
1961               (member 'constant (binding-declarations b)))
1962           (concat (ls-compile `',sexp) ".value"))
1963          (t
1964           (ls-compile `(symbol-value ',sexp))))))
1965     ((integerp sexp) (integer-to-string sexp))
1966     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1967     ((arrayp sexp) (literal sexp))
1968     ((listp sexp)
1969      (let ((name (car sexp))
1970            (args (cdr sexp)))
1971        (cond
1972          ;; Special forms
1973          ((assoc name *compilations*)
1974           (let ((comp (second (assoc name *compilations*))))
1975             (apply comp args)))
1976          ;; Built-in functions
1977          ((and (assoc name *builtins*)
1978                (not (claimp name 'function 'notinline)))
1979           (let ((comp (second (assoc name *builtins*))))
1980             (apply comp args)))
1981          (t
1982           (if (macro name)
1983               (ls-compile (ls-macroexpand-1 sexp))
1984               (compile-funcall name args))))))
1985     (t
1986      (error "How should I compile this?"))))
1987
1988 (defun ls-compile-toplevel (sexp)
1989   (let ((*toplevel-compilations* nil))
1990     (cond
1991       ((and (consp sexp) (eq (car sexp) 'progn))
1992        (let ((subs (mapcar #'ls-compile-toplevel (cdr sexp))))
1993          (join (remove-if #'null-or-empty-p subs))))
1994       (t
1995        (let ((code (ls-compile sexp)))
1996          (concat (join-trailing (get-toplevel-compilations)
1997                                 (concat ";" *newline*))
1998                  (if code
1999                      (concat code ";" *newline*)
2000                      "")))))))
2001
2002
2003 ;;; Once we have the compiler, we define the runtime environment and
2004 ;;; interactive development (eval), which works calling the compiler
2005 ;;; and evaluating the Javascript result globally.
2006
2007 #+ecmalisp
2008 (progn
2009   (defmacro with-compilation-unit (&body body)
2010     `(prog1
2011          (progn
2012            (setq *compilation-unit-checks* nil)
2013            ,@body)
2014        (dolist (check *compilation-unit-checks*)
2015          (funcall check))))
2016
2017   (defun eval (x)
2018     (let ((code
2019            (with-compilation-unit
2020                (ls-compile-toplevel x))))
2021       (js-eval code)))
2022
2023   (export '(&rest &optional &body * *gensym-counter* *package* + - / 1+ 1- < <= =
2024             = > >= and append apply aref arrayp aset assoc atom block boundp
2025             boundp butlast caar cadddr caddr cadr car car case catch cdar cdddr
2026             cddr cdr cdr char char-code char= code-char cond cons consp copy-list
2027             decf declaim defparameter defun defmacro defvar digit-char-p disassemble
2028             documentation dolist dotimes ecase eq eql equal error eval every
2029             export fdefinition find-package find-symbol first fourth fset funcall
2030             function functionp gensym get-universal-time go identity if in-package
2031             incf integerp integerp intern keywordp lambda last length let let*
2032             list-all-packages list listp make-array make-package make-symbol
2033             mapcar member minusp mod nil not nth nthcdr null numberp or
2034             package-name package-use-list packagep plusp prin1-to-string print
2035             proclaim prog1 prog2 progn psetq push quote remove remove-if
2036             remove-if-not return return-from revappend reverse second set setq
2037             some string-upcase string string= stringp subseq symbol-function
2038             symbol-name symbol-package symbol-plist symbol-value symbolp t tagbody
2039             third throw truncate unless unwind-protect variable warn when
2040             write-line write-string zerop))
2041
2042   (setq *package* *user-package*)
2043
2044   (js-eval "var lisp")
2045   (js-vset "lisp" (new))
2046   (js-vset "lisp.read" #'ls-read-from-string)
2047   (js-vset "lisp.print" #'prin1-to-string)
2048   (js-vset "lisp.eval" #'eval)
2049   (js-vset "lisp.compile" #'ls-compile-toplevel)
2050   (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
2051   (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str))))
2052
2053   ;; Set the initial global environment to be equal to the host global
2054   ;; environment at this point of the compilation.
2055   (eval-when-compile
2056     (toplevel-compilation
2057      (ls-compile
2058       `(progn
2059          ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
2060                    *literal-symbols*)
2061          (setq *literal-symbols* ',*literal-symbols*)
2062          (setq *environment* ',*environment*)
2063          (setq *variable-counter* ,*variable-counter*)
2064          (setq *gensym-counter* ,*gensym-counter*)
2065          (setq *block-counter* ,*block-counter*)))))
2066
2067   (eval-when-compile
2068     (toplevel-compilation
2069      (ls-compile
2070       `(setq *literal-counter* ,*literal-counter*)))))
2071
2072
2073 ;;; Finally, we provide a couple of functions to easily bootstrap
2074 ;;; this. It just calls the compiler with this file as input.
2075
2076 #+common-lisp
2077 (progn
2078   (defun read-whole-file (filename)
2079     (with-open-file (in filename)
2080       (let ((seq (make-array (file-length in) :element-type 'character)))
2081         (read-sequence seq in)
2082         seq)))
2083
2084   (defun ls-compile-file (filename output)
2085     (setq *compilation-unit-checks* nil)
2086     (with-open-file (out output :direction :output :if-exists :supersede)
2087       (let* ((source (read-whole-file filename))
2088              (in (make-string-stream source)))
2089         (loop
2090            for x = (ls-read in)
2091            until (eq x *eof*)
2092            for compilation = (ls-compile-toplevel x)
2093            when (plusp (length compilation))
2094            do (write-string compilation out))
2095         (dolist (check *compilation-unit-checks*)
2096           (funcall check))
2097         (setq *compilation-unit-checks* nil))))
2098
2099   (defun bootstrap ()
2100     (setq *environment* (make-lexenv))
2101     (setq *literal-symbols* nil)
2102     (setq *variable-counter* 0
2103           *gensym-counter* 0
2104           *literal-counter* 0
2105           *block-counter* 0)
2106     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))