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