02aa16ed5a6dc341973bf770d0310eba20e20e5d
[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 pv (x) { return typeof x === 'object' && 'car' in x ? x.car : 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   (defun values-list (list)
607     (values-list list))
608
609   (defun values (&rest args)
610     (values-list args)))
611
612
613 ;;; The compiler offers some primitives and special forms which are
614 ;;; not found in Common Lisp, for instance, while. So, we grow Common
615 ;;; Lisp a bit to it can execute the rest of the file.
616 #+common-lisp
617 (progn
618   (defmacro while (condition &body body)
619     `(do ()
620          ((not ,condition))
621        ,@body))
622
623   (defmacro eval-when-compile (&body body)
624     `(eval-when (:compile-toplevel :load-toplevel :execute)
625        ,@body))
626
627   (defun concat-two (s1 s2)
628     (concatenate 'string s1 s2))
629
630   (defun setcar (cons new)
631     (setf (car cons) new))
632   (defun setcdr (cons new)
633     (setf (cdr cons) new))
634
635   (defun aset (array idx value)
636     (setf (aref array idx) value)))
637
638 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
639 ;;; from here, this code will compile on both. We define some helper
640 ;;; functions now for string manipulation and so on. They will be
641 ;;; useful in the compiler, mostly.
642
643 (defvar *newline* (string (code-char 10)))
644
645 (defun concat (&rest strs)
646   (!reduce #'concat-two strs ""))
647
648 (defmacro concatf (variable &body form)
649   `(setq ,variable (concat ,variable (progn ,@form))))
650
651 ;;; Concatenate a list of strings, with a separator
652 (defun join (list &optional (separator ""))
653   (cond
654     ((null list)
655      "")
656     ((null (cdr list))
657      (car list))
658     (t
659      (concat (car list)
660              separator
661              (join (cdr list) separator)))))
662
663 (defun join-trailing (list &optional (separator ""))
664   (if (null list)
665       ""
666       (concat (car list) separator (join-trailing (cdr list) separator))))
667
668 (defun mapconcat (func list)
669   (join (mapcar func list)))
670
671 (defun vector-to-list (vector)
672   (let ((list nil)
673         (size (length vector)))
674     (dotimes (i size (reverse list))
675       (push (aref vector i) list))))
676
677 (defun list-to-vector (list)
678   (let ((v (make-array (length list)))
679         (i 0))
680     (dolist (x list v)
681       (aset v i x)
682       (incf i))))
683
684 ;;; Like CONCAT, but prefix each line with four spaces. Two versions
685 ;;; of this function are available, because the Ecmalisp version is
686 ;;; very slow and bootstraping was annoying.
687
688 #+ecmalisp
689 (defun indent (&rest string)
690   (let ((input (join string)))
691     (let ((output "")
692           (index 0)
693           (size (length input)))
694       (when (plusp (length input)) (concatf output "    "))
695       (while (< index size)
696         (let ((str
697                (if (and (char= (char input index) #\newline)
698                         (< index (1- size))
699                         (not (char= (char input (1+ index)) #\newline)))
700                    (concat (string #\newline) "    ")
701                    (string (char input index)))))
702           (concatf output str))
703         (incf index))
704       output)))
705
706 #+common-lisp
707 (defun indent (&rest string)
708   (with-output-to-string (*standard-output*)
709     (with-input-from-string (input (join string))
710       (loop
711          for line = (read-line input nil)
712          while line
713          do (write-string "    ")
714          do (write-line line)))))
715
716
717 (defun integer-to-string (x)
718   (cond
719     ((zerop x)
720      "0")
721     ((minusp x)
722      (concat "-" (integer-to-string (- 0 x))))
723     (t
724      (let ((digits nil))
725        (while (not (zerop x))
726          (push (mod x 10) digits)
727          (setq x (truncate x 10)))
728        (join (mapcar (lambda (d) (string (char "0123456789" d)))
729                      digits))))))
730
731
732 ;;; Wrap X with a Javascript code to convert the result from
733 ;;; Javascript generalized booleans to T or NIL.
734 (defun js!bool (x)
735   (concat "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
736
737 ;;; Concatenate the arguments and wrap them with a self-calling
738 ;;; Javascript anonymous function. It is used to make some Javascript
739 ;;; statements valid expressions and provide a private scope as well.
740 ;;; It could be defined as function, but we could do some
741 ;;; preprocessing in the future.
742 (defmacro js!selfcall (&body body)
743   `(concat "(function(){" *newline* (indent ,@body) "})()"))
744
745
746 ;;; Printer
747
748 #+ecmalisp
749 (progn
750   (defun prin1-to-string (form)
751     (cond
752       ((symbolp form)
753        (if (cdr (%find-symbol (symbol-name form) *package*))
754            (symbol-name form)
755            (let ((package (symbol-package form))
756                  (name (symbol-name form)))
757              (concat (cond
758                        ((null package) "#")
759                        ((eq package (find-package "KEYWORD")) "")
760                        (t (package-name package)))
761                      ":" name))))
762       ((integerp form) (integer-to-string form))
763       ((stringp form) (concat "\"" (escape-string form) "\""))
764       ((functionp form)
765        (let ((name (oget form "fname")))
766          (if name
767              (concat "#<FUNCTION " name ">")
768              (concat "#<FUNCTION>"))))
769       ((listp form)
770        (concat "("
771                (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
772                (let ((last (last form)))
773                  (if (null (cdr last))
774                      (prin1-to-string (car last))
775                      (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
776                ")"))
777       ((arrayp form)
778        (concat "#" (prin1-to-string (vector-to-list form))))
779       ((packagep form)
780        (concat "#<PACKAGE " (package-name form) ">"))))
781
782   (defun write-line (x)
783     (write-string x)
784     (write-string *newline*)
785     x)
786
787   (defun warn (string)
788     (write-string "WARNING: ")
789     (write-line string))
790
791   (defun print (x)
792     (write-line (prin1-to-string x))
793     x))
794
795
796 ;;;; Reader
797
798 ;;; The Lisp reader, parse strings and return Lisp objects. The main
799 ;;; entry points are `ls-read' and `ls-read-from-string'.
800
801 (defun make-string-stream (string)
802   (cons string 0))
803
804 (defun %peek-char (stream)
805   (and (< (cdr stream) (length (car stream)))
806        (char (car stream) (cdr stream))))
807
808 (defun %read-char (stream)
809   (and (< (cdr stream) (length (car stream)))
810        (prog1 (char (car stream) (cdr stream))
811          (setcdr stream (1+ (cdr stream))))))
812
813 (defun whitespacep (ch)
814   (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
815
816 (defun skip-whitespaces (stream)
817   (let (ch)
818     (setq ch (%peek-char stream))
819     (while (and ch (whitespacep ch))
820       (%read-char stream)
821       (setq ch (%peek-char stream)))))
822
823 (defun terminalp (ch)
824   (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
825
826 (defun read-until (stream func)
827   (let ((string "")
828         (ch))
829     (setq ch (%peek-char stream))
830     (while (and ch (not (funcall func ch)))
831       (setq string (concat string (string ch)))
832       (%read-char stream)
833       (setq ch (%peek-char stream)))
834     string))
835
836 (defun skip-whitespaces-and-comments (stream)
837   (let (ch)
838     (skip-whitespaces stream)
839     (setq ch (%peek-char stream))
840     (while (and ch (char= ch #\;))
841       (read-until stream (lambda (x) (char= x #\newline)))
842       (skip-whitespaces stream)
843       (setq ch (%peek-char stream)))))
844
845 (defun %read-list (stream)
846   (skip-whitespaces-and-comments stream)
847   (let ((ch (%peek-char stream)))
848     (cond
849       ((null ch)
850        (error "Unspected EOF"))
851       ((char= ch #\))
852        (%read-char stream)
853        nil)
854       ((char= ch #\.)
855        (%read-char stream)
856        (prog1 (ls-read stream)
857          (skip-whitespaces-and-comments stream)
858          (unless (char= (%read-char stream) #\))
859            (error "')' was expected."))))
860       (t
861        (cons (ls-read stream) (%read-list stream))))))
862
863 (defun read-string (stream)
864   (let ((string "")
865         (ch nil))
866     (setq ch (%read-char stream))
867     (while (not (eql ch #\"))
868       (when (null ch)
869         (error "Unexpected EOF"))
870       (when (eql ch #\\)
871         (setq ch (%read-char stream)))
872       (setq string (concat string (string ch)))
873       (setq ch (%read-char stream)))
874     string))
875
876 (defun read-sharp (stream)
877   (%read-char stream)
878   (ecase (%read-char stream)
879     (#\'
880      (list 'function (ls-read stream)))
881     (#\( (list-to-vector (%read-list stream)))
882     (#\: (make-symbol (string-upcase (read-until stream #'terminalp))))
883     (#\\
884      (let ((cname
885             (concat (string (%read-char stream))
886                     (read-until stream #'terminalp))))
887        (cond
888          ((string= cname "space") (char-code #\space))
889          ((string= cname "tab") (char-code #\tab))
890          ((string= cname "newline") (char-code #\newline))
891          (t (char-code (char cname 0))))))
892     (#\+
893      (let ((feature (read-until stream #'terminalp)))
894        (cond
895          ((string= feature "common-lisp")
896           (ls-read stream)              ;ignore
897           (ls-read stream))
898          ((string= feature "ecmalisp")
899           (ls-read stream))
900          (t
901           (error "Unknown reader form.")))))))
902
903 ;;; Parse a string of the form NAME, PACKAGE:NAME or
904 ;;; PACKAGE::NAME and return the name. If the string is of the
905 ;;; form 1) or 3), but the symbol does not exist, it will be created
906 ;;; and interned in that package.
907 (defun read-symbol (string)
908   (let ((size (length string))
909         package name internalp index)
910     (setq index 0)
911     (while (and (< index size)
912                 (not (char= (char string index) #\:)))
913       (incf index))
914     (cond
915       ;; No package prefix
916       ((= index size)
917        (setq name string)
918        (setq package *package*)
919        (setq internalp t))
920       (t
921        ;; Package prefix
922        (if (zerop index)
923            (setq package "KEYWORD")
924            (setq package (string-upcase (subseq string 0 index))))
925        (incf index)
926        (when (char= (char string index) #\:)
927          (setq internalp t)
928          (incf index))
929        (setq name (subseq string index))))
930     ;; Canonalize symbol name and package
931     (setq name (string-upcase name))
932     (setq package (find-package package))
933     ;; TODO: PACKAGE:SYMBOL should signal error if SYMBOL is not an
934     ;; external symbol from PACKAGE.
935     (if (or internalp (eq package (find-package "KEYWORD")))
936         (intern name package)
937         (find-symbol name package))))
938
939 (defvar *eof* (gensym))
940 (defun ls-read (stream)
941   (skip-whitespaces-and-comments stream)
942   (let ((ch (%peek-char stream)))
943     (cond
944       ((or (null ch) (char= ch #\)))
945        *eof*)
946       ((char= ch #\()
947        (%read-char stream)
948        (%read-list stream))
949       ((char= ch #\')
950        (%read-char stream)
951        (list 'quote (ls-read stream)))
952       ((char= ch #\`)
953        (%read-char stream)
954        (list 'backquote (ls-read stream)))
955       ((char= ch #\")
956        (%read-char stream)
957        (read-string stream))
958       ((char= ch #\,)
959        (%read-char stream)
960        (if (eql (%peek-char stream) #\@)
961            (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
962            (list 'unquote (ls-read stream))))
963       ((char= ch #\#)
964        (read-sharp stream))
965       (t
966        (let ((string (read-until stream #'terminalp)))
967          (if (every #'digit-char-p string)
968              (parse-integer string)
969              (read-symbol string)))))))
970
971 (defun ls-read-from-string (string)
972   (ls-read (make-string-stream string)))
973
974
975 ;;;; Compiler
976
977 ;;; Translate the Lisp code to Javascript. It will compile the special
978 ;;; forms. Some primitive functions are compiled as special forms
979 ;;; too. The respective real functions are defined in the target (see
980 ;;; the beginning of this file) as well as some primitive functions.
981
982 (defvar *compilation-unit-checks* '())
983
984 (defun make-binding (name type value &optional declarations)
985   (list name type value declarations))
986
987 (defun binding-name (b) (first b))
988 (defun binding-type (b) (second b))
989 (defun binding-value (b) (third b))
990 (defun binding-declarations (b) (fourth b))
991
992 (defun set-binding-value (b value)
993   (setcar (cddr b) value))
994
995 (defun set-binding-declarations (b value)
996   (setcar (cdddr b) value))
997
998 (defun push-binding-declaration (decl b)
999   (set-binding-declarations b (cons decl (binding-declarations b))))
1000
1001
1002 (defun make-lexenv ()
1003   (list nil nil nil nil))
1004
1005 (defun copy-lexenv (lexenv)
1006   (copy-list lexenv))
1007
1008 (defun push-to-lexenv (binding lexenv namespace)
1009   (ecase namespace
1010     (variable   (setcar        lexenv  (cons binding (car lexenv))))
1011     (function   (setcar   (cdr lexenv) (cons binding (cadr lexenv))))
1012     (block      (setcar  (cddr lexenv) (cons binding (caddr lexenv))))
1013     (gotag      (setcar (cdddr lexenv) (cons binding (cadddr lexenv))))))
1014
1015 (defun extend-lexenv (bindings lexenv namespace)
1016   (let ((env (copy-lexenv lexenv)))
1017     (dolist (binding (reverse bindings) env)
1018       (push-to-lexenv binding env namespace))))
1019
1020 (defun lookup-in-lexenv (name lexenv namespace)
1021   (assoc name (ecase namespace
1022                 (variable (first lexenv))
1023                 (function (second lexenv))
1024                 (block (third lexenv))
1025                 (gotag (fourth lexenv)))))
1026
1027 (defvar *environment* (make-lexenv))
1028
1029 (defvar *variable-counter* 0)
1030 (defun gvarname (symbol)
1031   (concat "v" (integer-to-string (incf *variable-counter*))))
1032
1033 (defun translate-variable (symbol)
1034   (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
1035
1036 (defun extend-local-env (args)
1037   (let ((new (copy-lexenv *environment*)))
1038     (dolist (symbol args new)
1039       (let ((b (make-binding symbol 'lexical-variable (gvarname symbol))))
1040         (push-to-lexenv b new 'variable)))))
1041
1042 ;;; Toplevel compilations
1043 (defvar *toplevel-compilations* nil)
1044
1045 (defun toplevel-compilation (string)
1046   (push string *toplevel-compilations*))
1047
1048 (defun null-or-empty-p (x)
1049   (zerop (length x)))
1050
1051 (defun get-toplevel-compilations ()
1052   (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
1053
1054 (defun %compile-defmacro (name lambda)
1055   (toplevel-compilation (ls-compile `',name))
1056   (push-to-lexenv (make-binding name 'macro lambda) *environment* 'function))
1057
1058 (defun global-binding (name type namespace)
1059   (or (lookup-in-lexenv name *environment* namespace)
1060       (let ((b (make-binding name type nil)))
1061         (push-to-lexenv b *environment* namespace)
1062         b)))
1063
1064 (defun claimp (symbol namespace claim)
1065   (let ((b (lookup-in-lexenv symbol *environment* namespace)))
1066     (and b (member claim (binding-declarations b)))))
1067
1068 (defun !proclaim (decl)
1069   (case (car decl)
1070     (special
1071      (dolist (name (cdr decl))
1072        (let ((b (global-binding name 'variable 'variable)))
1073          (push-binding-declaration 'special b))))
1074     (notinline
1075      (dolist (name (cdr decl))
1076        (let ((b (global-binding name 'function 'function)))
1077          (push-binding-declaration 'notinline b))))
1078     (constant
1079      (dolist (name (cdr decl))
1080        (let ((b (global-binding name 'variable 'variable)))
1081          (push-binding-declaration 'constant b))))
1082     (non-overridable
1083      (dolist (name (cdr decl))
1084        (let ((b (global-binding name 'function 'function)))
1085          (push-binding-declaration 'non-overridable b))))))
1086
1087 #+ecmalisp
1088 (fset 'proclaim #'!proclaim)
1089
1090 ;;; Special forms
1091
1092 (defvar *compilations* nil)
1093
1094 (defmacro define-compilation (name args &body body)
1095   ;; Creates a new primitive `name' with parameters args and
1096   ;; @body. The body can access to the local environment through the
1097   ;; variable *ENVIRONMENT*.
1098   `(push (list ',name (lambda ,args (block ,name ,@body)))
1099          *compilations*))
1100
1101 (define-compilation if (condition true false)
1102   (concat "(" (ls-compile condition) " !== " (ls-compile nil)
1103           " ? " (ls-compile true)
1104           " : " (ls-compile false)
1105           ")"))
1106
1107 (defvar *lambda-list-keywords* '(&optional &rest))
1108
1109 (defun list-until-keyword (list)
1110   (if (or (null list) (member (car list) *lambda-list-keywords*))
1111       nil
1112       (cons (car list) (list-until-keyword (cdr list)))))
1113
1114 (defun lambda-list-required-arguments (lambda-list)
1115   (list-until-keyword lambda-list))
1116
1117 (defun lambda-list-optional-arguments-with-default (lambda-list)
1118   (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
1119
1120 (defun lambda-list-optional-arguments (lambda-list)
1121   (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
1122
1123 (defun lambda-list-rest-argument (lambda-list)
1124   (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
1125     (when (cdr rest)
1126       (error "Bad lambda-list"))
1127     (car rest)))
1128
1129
1130 (defun lambda-docstring-wrapper (docstring &rest strs)
1131   (if docstring
1132       (js!selfcall
1133         "var func = " (join strs) ";" *newline*
1134         "func.docstring = '" docstring "';" *newline*
1135         "return func;" *newline*)
1136       (join strs)))
1137
1138
1139 (defvar *compiling-lambda-p* nil)
1140
1141 (define-compilation lambda (lambda-list &rest body)
1142   (let ((required-arguments (lambda-list-required-arguments lambda-list))
1143         (optional-arguments (lambda-list-optional-arguments lambda-list))
1144         (rest-argument (lambda-list-rest-argument lambda-list))
1145         (*compiling-lambda-p* t)
1146         documentation)
1147     ;; Get the documentation string for the lambda function
1148     (when (and (stringp (car body))
1149                (not (null (cdr body))))
1150       (setq documentation (car body))
1151       (setq body (cdr body)))
1152     (let ((n-required-arguments (length required-arguments))
1153           (n-optional-arguments (length optional-arguments))
1154           (*environment* (extend-local-env
1155                           (append (ensure-list rest-argument)
1156                                   required-arguments
1157                                   optional-arguments))))
1158       (lambda-docstring-wrapper
1159        documentation
1160        "(function ("
1161        (join (cons "values"
1162                    (mapcar #'translate-variable
1163                            (append required-arguments optional-arguments)))
1164              ",")
1165        "){" *newline*
1166        ;; Check number of arguments
1167        (indent
1168         (if required-arguments
1169             (concat "if (arguments.length < " (integer-to-string (1+ n-required-arguments))
1170                     ") throw 'too few arguments';" *newline*)
1171             "")
1172         (if (not rest-argument)
1173             (concat "if (arguments.length > "
1174                     (integer-to-string (+ 1 n-required-arguments n-optional-arguments))
1175                     ") throw 'too many arguments';" *newline*)
1176             "")
1177         ;; Optional arguments
1178         (if optional-arguments
1179             (concat "switch(arguments.length-1){" *newline*
1180                     (let ((optional-and-defaults
1181                            (lambda-list-optional-arguments-with-default lambda-list))
1182                           (cases nil)
1183                           (idx 0))
1184                       (progn
1185                         (while (< idx n-optional-arguments)
1186                           (let ((arg (nth idx optional-and-defaults)))
1187                             (push (concat "case "
1188                                           (integer-to-string (+ idx n-required-arguments)) ":" *newline*
1189                                           (translate-variable (car arg))
1190                                           "="
1191                                           (ls-compile (cadr arg))
1192                                           ";" *newline*)
1193                                   cases)
1194                             (incf idx)))
1195                         (push (concat "default: break;" *newline*) cases)
1196                         (join (reverse cases))))
1197                     "}" *newline*)
1198             "")
1199         ;; &rest/&body argument
1200         (if rest-argument
1201             (let ((js!rest (translate-variable rest-argument)))
1202               (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
1203                       "for (var i = arguments.length-1; i>="
1204                       (integer-to-string (+ 1 n-required-arguments n-optional-arguments))
1205                       "; i--)" *newline*
1206                       (indent js!rest " = "
1207                               "{car: arguments[i], cdr: ") js!rest "};"
1208                       *newline*))
1209             "")
1210         ;; Body
1211         (ls-compile-block body t)) *newline*
1212        "})"))))
1213
1214
1215 (defun setq-pair (var val)
1216   (let ((b (lookup-in-lexenv var *environment* 'variable)))
1217     (if (eq (binding-type b) 'lexical-variable)
1218         (concat (binding-value b) " = " (ls-compile val))
1219         (ls-compile `(set ',var ,val)))))
1220
1221 (define-compilation setq (&rest pairs)
1222   (let ((result ""))
1223     (while t
1224       (cond
1225         ((null pairs) (return))
1226         ((null (cdr pairs))
1227          (error "Odd paris in SETQ"))
1228         (t
1229          (concatf result
1230            (concat (setq-pair (car pairs) (cadr pairs))
1231                    (if (null (cddr pairs)) "" ", ")))
1232          (setq pairs (cddr pairs)))))
1233     (concat "(" result ")")))
1234
1235 ;;; FFI Variable accessors
1236 (define-compilation js-vref (var)
1237   var)
1238
1239 (define-compilation js-vset (var val)
1240   (concat "(" var " = " (ls-compile val) ")"))
1241
1242
1243
1244 ;;; Literals
1245 (defun escape-string (string)
1246   (let ((output "")
1247         (index 0)
1248         (size (length string)))
1249     (while (< index size)
1250       (let ((ch (char string index)))
1251         (when (or (char= ch #\") (char= ch #\\))
1252           (setq output (concat output "\\")))
1253         (when (or (char= ch #\newline))
1254           (setq output (concat output "\\"))
1255           (setq ch #\n))
1256         (setq output (concat output (string ch))))
1257       (incf index))
1258     output))
1259
1260
1261 (defvar *literal-symbols* nil)
1262 (defvar *literal-counter* 0)
1263
1264 (defun genlit ()
1265   (concat "l" (integer-to-string (incf *literal-counter*))))
1266
1267 (defun literal (sexp &optional recursive)
1268   (cond
1269     ((integerp sexp) (integer-to-string sexp))
1270     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1271     ((symbolp sexp)
1272      (or (cdr (assoc sexp *literal-symbols*))
1273          (let ((v (genlit))
1274                (s #+common-lisp (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1275                   #+ecmalisp
1276                   (let ((package (symbol-package sexp)))
1277                     (if (null package)
1278                         (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1279                         (ls-compile `(intern ,(symbol-name sexp) ,(package-name package)))))))
1280            (push (cons sexp v) *literal-symbols*)
1281            (toplevel-compilation (concat "var " v " = " s))
1282            v)))
1283     ((consp sexp)
1284      (let ((c (concat "{car: " (literal (car sexp) t) ", "
1285                       "cdr: " (literal (cdr sexp) t) "}")))
1286        (if recursive
1287            c
1288            (let ((v (genlit)))
1289              (toplevel-compilation (concat "var " v " = " c))
1290              v))))
1291     ((arrayp sexp)
1292      (let ((elements (vector-to-list sexp)))
1293        (let ((c (concat "[" (join (mapcar #'literal elements) ", ") "]")))
1294          (if recursive
1295              c
1296              (let ((v (genlit)))
1297                (toplevel-compilation (concat "var " v " = " c))
1298                v)))))))
1299
1300 (define-compilation quote (sexp)
1301   (literal sexp))
1302
1303 (define-compilation %while (pred &rest body)
1304   (js!selfcall
1305     "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1306     (indent (ls-compile-block body))
1307     "}"
1308     "return " (ls-compile nil) ";" *newline*))
1309
1310 (define-compilation function (x)
1311   (cond
1312     ((and (listp x) (eq (car x) 'lambda))
1313      (ls-compile x))
1314     ((symbolp x)
1315      (ls-compile `(symbol-function ',x)))))
1316
1317 (define-compilation eval-when-compile (&rest body)
1318   (eval (cons 'progn body))
1319   nil)
1320
1321 (defmacro define-transformation (name args form)
1322   `(define-compilation ,name ,args
1323      (ls-compile ,form)))
1324
1325 (define-compilation progn (&rest body)
1326   (js!selfcall (ls-compile-block body t)))
1327
1328 (defun special-variable-p (x)
1329   (and (claimp x 'variable 'special) t))
1330
1331 ;;; Wrap CODE to restore the symbol values of the dynamic
1332 ;;; bindings. BINDINGS is a list of pairs of the form
1333 ;;; (SYMBOL . PLACE),  where PLACE is a Javascript variable
1334 ;;; name to initialize the symbol value and where to stored
1335 ;;; the old value.
1336 (defun let-binding-wrapper (bindings body)
1337   (when (null bindings)
1338     (return-from let-binding-wrapper body))
1339   (concat
1340    "try {" *newline*
1341    (indent "var tmp;" *newline*
1342            (mapconcat
1343             (lambda (b)
1344               (let ((s (ls-compile `(quote ,(car b)))))
1345                 (concat "tmp = " s ".value;" *newline*
1346                         s ".value = " (cdr b) ";" *newline*
1347                         (cdr b) " = tmp;" *newline*)))
1348             bindings)
1349            body *newline*)
1350    "}" *newline*
1351    "finally {"  *newline*
1352    (indent
1353     (mapconcat (lambda (b)
1354                  (let ((s (ls-compile `(quote ,(car b)))))
1355                    (concat s ".value" " = " (cdr b) ";" *newline*)))
1356                bindings))
1357    "}" *newline*))
1358
1359 (define-compilation let (bindings &rest body)
1360   (let* ((bindings (mapcar #'ensure-list bindings))
1361          (variables (mapcar #'first bindings))
1362          (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
1363          (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
1364          (dynamic-bindings))
1365     (concat "(function("
1366             (join (mapcar (lambda (x)
1367                             (if (special-variable-p x)
1368                                 (let ((v (gvarname x)))
1369                                   (push (cons x v) dynamic-bindings)
1370                                   v)
1371                                 (translate-variable x)))
1372                           variables)
1373                   ",")
1374             "){" *newline*
1375             (let ((body (ls-compile-block body t)))
1376               (indent (let-binding-wrapper dynamic-bindings body)))
1377             "})(" (join cvalues ",") ")")))
1378
1379
1380 ;;; Return the code to initialize BINDING, and push it extending the
1381 ;;; current lexical environment if the variable is special.
1382 (defun let*-initialize-value (binding)
1383   (let ((var (first binding))
1384         (value (second binding)))
1385     (if (special-variable-p var)
1386         (concat (ls-compile `(setq ,var ,value)) ";" *newline*)
1387         (let* ((v (gvarname var))
1388                (b (make-binding var 'variable v)))
1389           (prog1 (concat "var " v " = " (ls-compile value) ";" *newline*)
1390             (push-to-lexenv b *environment* 'variable))))))
1391
1392 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
1393 ;;; DOES NOT generate code to initialize the value of the symbols,
1394 ;;; unlike let-binding-wrapper.
1395 (defun let*-binding-wrapper (symbols body)
1396   (when (null symbols)
1397     (return-from let*-binding-wrapper body))
1398   (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
1399                        (remove-if-not #'special-variable-p symbols))))
1400     (concat
1401      "try {" *newline*
1402      (indent
1403       (mapconcat (lambda (b)
1404                    (let ((s (ls-compile `(quote ,(car b)))))
1405                      (concat "var " (cdr b) " = " s ".value;" *newline*)))
1406                  store)
1407       body)
1408      "}" *newline*
1409      "finally {" *newline*
1410      (indent
1411       (mapconcat (lambda (b)
1412                    (let ((s (ls-compile `(quote ,(car b)))))
1413                      (concat s ".value" " = " (cdr b) ";" *newline*)))
1414                  store))
1415      "}" *newline*)))
1416
1417
1418 (define-compilation let* (bindings &rest body)
1419   (let ((bindings (mapcar #'ensure-list bindings))
1420         (*environment* (copy-lexenv *environment*)))
1421     (js!selfcall
1422       (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
1423             (body (concat (mapconcat #'let*-initialize-value bindings)
1424                           (ls-compile-block body t))))
1425         (let*-binding-wrapper specials body)))))
1426
1427
1428 (defvar *block-counter* 0)
1429
1430 (define-compilation block (name &rest body)
1431   (let ((tr (integer-to-string (incf *block-counter*))))
1432     (let ((b (make-binding name 'block tr)))
1433       (js!selfcall
1434         "try {" *newline*
1435         (let ((*environment* (extend-lexenv (list b) *environment* 'block)))
1436           (indent "return " (ls-compile `(progn ,@body)) ";" *newline*))
1437         "}" *newline*
1438         "catch (cf){" *newline*
1439         "    if (cf.type == 'block' && cf.id == " tr ")" *newline*
1440         "        return cf.value;" *newline*
1441         "    else" *newline*
1442         "        throw cf;" *newline*
1443         "}" *newline*))))
1444
1445 (define-compilation return-from (name &optional value)
1446   (let ((b (lookup-in-lexenv name *environment* 'block)))
1447     (if b
1448         (js!selfcall
1449           "throw ({"
1450           "type: 'block', "
1451           "id: " (binding-value b) ", "
1452           "value: " (ls-compile value) ", "
1453           "message: 'Return from unknown block " (symbol-name name) ".'"
1454           "})")
1455         (error (concat "Unknown block `" (symbol-name name) "'.")))))
1456
1457
1458 (define-compilation catch (id &rest body)
1459   (js!selfcall
1460     "var id = " (ls-compile id) ";" *newline*
1461     "try {" *newline*
1462     (indent "return " (ls-compile `(progn ,@body))
1463             ";" *newline*)
1464     "}" *newline*
1465     "catch (cf){" *newline*
1466     "    if (cf.type == 'catch' && cf.id == id)" *newline*
1467     "        return cf.value;" *newline*
1468     "    else" *newline*
1469     "        throw cf;" *newline*
1470     "}" *newline*))
1471
1472 (define-compilation throw (id value)
1473   (js!selfcall
1474     "throw ({"
1475     "type: 'catch', "
1476     "id: " (ls-compile id) ", "
1477     "value: " (ls-compile value) ", "
1478     "message: 'Throw uncatched.'"
1479     "})"))
1480
1481
1482 (defvar *tagbody-counter* 0)
1483 (defvar *go-tag-counter* 0)
1484
1485 (defun go-tag-p (x)
1486   (or (integerp x) (symbolp x)))
1487
1488 (defun declare-tagbody-tags (tbidx body)
1489   (let ((bindings
1490          (mapcar (lambda (label)
1491                    (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1492                      (make-binding label 'gotag (list tbidx tagidx))))
1493                  (remove-if-not #'go-tag-p body))))
1494     (extend-lexenv bindings *environment* 'gotag)))
1495
1496 (define-compilation tagbody (&rest body)
1497   ;; Ignore the tagbody if it does not contain any go-tag. We do this
1498   ;; because 1) it is easy and 2) many built-in forms expand to a
1499   ;; implicit tagbody, so we save some space.
1500   (unless (some #'go-tag-p body)
1501     (return-from tagbody (ls-compile `(progn ,@body nil))))
1502   ;; The translation assumes the first form in BODY is a label
1503   (unless (go-tag-p (car body))
1504     (push (gensym "START") body))
1505   ;; Tagbody compilation
1506   (let ((tbidx (integer-to-string *tagbody-counter*)))
1507     (let ((*environment* (declare-tagbody-tags tbidx body))
1508           initag)
1509       (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1510         (setq initag (second (binding-value b))))
1511       (js!selfcall
1512         "var tagbody_" tbidx " = " initag ";" *newline*
1513         "tbloop:" *newline*
1514         "while (true) {" *newline*
1515         (indent "try {" *newline*
1516                 (indent (let ((content ""))
1517                           (concat "switch(tagbody_" tbidx "){" *newline*
1518                                   "case " initag ":" *newline*
1519                                   (dolist (form (cdr body) content)
1520                                     (concatf content
1521                                       (if (not (go-tag-p form))
1522                                           (indent (ls-compile form) ";" *newline*)
1523                                           (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1524                                             (concat "case " (second (binding-value b)) ":" *newline*)))))
1525                                   "default:" *newline*
1526                                   "    break tbloop;" *newline*
1527                                   "}" *newline*)))
1528                 "}" *newline*
1529                 "catch (jump) {" *newline*
1530                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1531                 "        tagbody_" tbidx " = jump.label;" *newline*
1532                 "    else" *newline*
1533                 "        throw(jump);" *newline*
1534                 "}" *newline*)
1535         "}" *newline*
1536         "return " (ls-compile nil) ";" *newline*))))
1537
1538 (define-compilation go (label)
1539   (let ((b (lookup-in-lexenv label *environment* 'gotag))
1540         (n (cond
1541              ((symbolp label) (symbol-name label))
1542              ((integerp label) (integer-to-string label)))))
1543     (if b
1544         (js!selfcall
1545           "throw ({"
1546           "type: 'tagbody', "
1547           "id: " (first (binding-value b)) ", "
1548           "label: " (second (binding-value b)) ", "
1549           "message: 'Attempt to GO to non-existing tag " n "'"
1550           "})" *newline*)
1551         (error (concat "Unknown tag `" n "'.")))))
1552
1553 (define-compilation unwind-protect (form &rest clean-up)
1554   (js!selfcall
1555     "var ret = " (ls-compile nil) ";" *newline*
1556     "try {" *newline*
1557     (indent "ret = " (ls-compile form) ";" *newline*)
1558     "} finally {" *newline*
1559     (indent (ls-compile-block clean-up))
1560     "}" *newline*
1561     "return ret;" *newline*))
1562
1563 (define-compilation multiple-value-call (func-form &rest forms)
1564   (let ((func (ls-compile func-form)))
1565     (js!selfcall
1566       "var args = [values];" *newline*
1567       "function values(){" *newline*
1568       (indent "var result = [];" *newline*
1569               "for (var i=0; i<arguments.length; i++)" *newline*
1570               (indent "result.push(arguments[i]);"))
1571       "}" *newline*
1572       (mapconcat (lambda (form)
1573                    (ls-compile form))
1574                  forms)
1575       "return (" func ").apply(window, [args]);")))
1576
1577
1578
1579 ;;; A little backquote implementation without optimizations of any
1580 ;;; kind for ecmalisp.
1581 (defun backquote-expand-1 (form)
1582   (cond
1583     ((symbolp form)
1584      (list 'quote form))
1585     ((atom form)
1586      form)
1587     ((eq (car form) 'unquote)
1588      (car form))
1589     ((eq (car form) 'backquote)
1590      (backquote-expand-1 (backquote-expand-1 (cadr form))))
1591     (t
1592      (cons 'append
1593            (mapcar (lambda (s)
1594                      (cond
1595                        ((and (listp s) (eq (car s) 'unquote))
1596                         (list 'list (cadr s)))
1597                        ((and (listp s) (eq (car s) 'unquote-splicing))
1598                         (cadr s))
1599                        (t
1600                         (list 'list (backquote-expand-1 s)))))
1601                    form)))))
1602
1603 (defun backquote-expand (form)
1604   (if (and (listp form) (eq (car form) 'backquote))
1605       (backquote-expand-1 (cadr form))
1606       form))
1607
1608 (defmacro backquote (form)
1609   (backquote-expand-1 form))
1610
1611 (define-transformation backquote (form)
1612   (backquote-expand-1 form))
1613
1614 ;;; Primitives
1615
1616 (defvar *builtins* nil)
1617
1618 (defmacro define-raw-builtin (name args &body body)
1619   ;; Creates a new primitive function `name' with parameters args and
1620   ;; @body. The body can access to the local environment through the
1621   ;; variable *ENVIRONMENT*.
1622   `(push (list ',name (lambda ,args (block ,name ,@body)))
1623          *builtins*))
1624
1625 (defmacro define-builtin (name args &body body)
1626   `(progn
1627      (define-raw-builtin ,name ,args
1628        (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1629          ,@body))))
1630
1631 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1632 (defmacro type-check (decls &body body)
1633   `(js!selfcall
1634      ,@(mapcar (lambda (decl)
1635                    `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1636                  decls)
1637      ,@(mapcar (lambda (decl)
1638                  `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1639                           (indent "throw 'The value ' + "
1640                                   ,(first decl)
1641                                   " + ' is not a type "
1642                                   ,(second decl)
1643                                   ".';"
1644                                   *newline*)))
1645                decls)
1646      (concat "return " (progn ,@body) ";" *newline*)))
1647
1648 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
1649 ;;; a variable which holds a list of forms. It will compile them and
1650 ;;; store the result in some Javascript variables. BODY is evaluated
1651 ;;; with ARGS bound to the list of these variables to generate the
1652 ;;; code which performs the transformation on these variables.
1653
1654 (defun variable-arity-call (args function)
1655   (unless (consp args)
1656     (error "ARGS must be a non-empty list"))
1657   (let ((counter 0)
1658         (variables '())
1659         (prelude ""))
1660     (dolist (x args)
1661       (let ((v (concat "x" (integer-to-string (incf counter)))))
1662         (push v variables)
1663         (concatf prelude
1664                  (concat "var " v " = " (ls-compile x) ";" *newline*
1665                          "if (typeof " v " !== 'number') throw 'Not a number!';"
1666                          *newline*))))
1667     (js!selfcall prelude (funcall function (reverse variables)))))
1668
1669
1670 (defmacro variable-arity (args &body body)
1671   (unless (symbolp args)
1672     (error "Bad usage of VARIABLE-ARITY, you must pass a symbol"))
1673   `(variable-arity-call ,args
1674                         (lambda (,args)
1675                           (concat "return " ,@body ";" *newline*))))
1676
1677 (defun num-op-num (x op y)
1678   (type-check (("x" "number" x) ("y" "number" y))
1679     (concat "x" op "y")))
1680
1681 (define-raw-builtin + (&rest numbers)
1682   (if (null numbers)
1683       "0"
1684       (variable-arity numbers
1685         (join numbers "+"))))
1686
1687 (define-raw-builtin - (x &rest others)
1688   (let ((args (cons x others)))
1689     (variable-arity args
1690       (if (null others)
1691           (concat "-" (car args))
1692           (join args "-")))))
1693
1694 (define-raw-builtin * (&rest numbers)
1695   (if (null numbers)
1696       "1"
1697       (variable-arity numbers
1698         (join numbers "*"))))
1699
1700 (define-raw-builtin / (x &rest others)
1701   (let ((args (cons x others)))
1702     (variable-arity args
1703       (if (null others)
1704           (concat "1 /" (car args))
1705           (join args "/")))))
1706
1707 (define-builtin mod (x y) (num-op-num x "%" y))
1708
1709
1710 (defun comparison-conjuntion (vars op)
1711   (cond
1712     ((null (cdr vars))
1713      "true")
1714     ((null (cddr vars))
1715      (concat (car vars) op (cadr vars)))
1716     (t
1717      (concat (car vars) op (cadr vars)
1718              " && "
1719              (comparison-conjuntion (cdr vars) op)))))
1720
1721 (defmacro define-builtin-comparison (op sym)
1722   `(define-raw-builtin ,op (x &rest args)
1723      (let ((args (cons x args)))
1724        (variable-arity args
1725          (js!bool (comparison-conjuntion args ,sym))))))
1726
1727 (define-builtin-comparison > ">")
1728 (define-builtin-comparison < "<")
1729 (define-builtin-comparison >= ">=")
1730 (define-builtin-comparison <= "<=")
1731 (define-builtin-comparison = "==")
1732
1733 (define-builtin numberp (x)
1734   (js!bool (concat "(typeof (" x ") == \"number\")")))
1735
1736 (define-builtin floor (x)
1737   (type-check (("x" "number" x))
1738     "Math.floor(x)"))
1739
1740 (define-builtin cons (x y)
1741   (concat "({car: " x ", cdr: " y "})"))
1742
1743 (define-builtin consp (x)
1744   (js!bool
1745    (js!selfcall
1746      "var tmp = " x ";" *newline*
1747      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1748
1749 (define-builtin car (x)
1750   (js!selfcall
1751     "var tmp = " x ";" *newline*
1752     "return tmp === " (ls-compile nil)
1753     "? " (ls-compile nil)
1754     ": tmp.car;" *newline*))
1755
1756 (define-builtin cdr (x)
1757   (js!selfcall
1758     "var tmp = " x ";" *newline*
1759     "return tmp === " (ls-compile nil) "? "
1760     (ls-compile nil)
1761     ": tmp.cdr;" *newline*))
1762
1763 (define-builtin setcar (x new)
1764   (type-check (("x" "object" x))
1765     (concat "(x.car = " new ")")))
1766
1767 (define-builtin setcdr (x new)
1768   (type-check (("x" "object" x))
1769     (concat "(x.cdr = " new ")")))
1770
1771 (define-builtin symbolp (x)
1772   (js!bool
1773    (js!selfcall
1774      "var tmp = " x ";" *newline*
1775      "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1776
1777 (define-builtin make-symbol (name)
1778   (type-check (("name" "string" name))
1779     "({name: name})"))
1780
1781 (define-builtin symbol-name (x)
1782   (concat "(" x ").name"))
1783
1784 (define-builtin set (symbol value)
1785   (concat "(" symbol ").value = " value))
1786
1787 (define-builtin fset (symbol value)
1788   (concat "(" symbol ").fvalue = " value))
1789
1790 (define-builtin boundp (x)
1791   (js!bool (concat "(" x ".value !== undefined)")))
1792
1793 (define-builtin symbol-value (x)
1794   (js!selfcall
1795     "var symbol = " x ";" *newline*
1796     "var value = symbol.value;" *newline*
1797     "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1798     "return value;" *newline*))
1799
1800 (define-builtin symbol-function (x)
1801   (js!selfcall
1802     "var symbol = " x ";" *newline*
1803     "var func = symbol.fvalue;" *newline*
1804     "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1805     "return func;" *newline*))
1806
1807 (define-builtin symbol-plist (x)
1808   (concat "((" x ").plist || " (ls-compile nil) ")"))
1809
1810 (define-builtin lambda-code (x)
1811   (concat "(" x ").toString()"))
1812
1813 (define-builtin eq    (x y) (js!bool (concat "(" x " === " y ")")))
1814 (define-builtin equal (x y) (js!bool (concat "(" x  " == " y ")")))
1815
1816 (define-builtin char-to-string (x)
1817   (type-check (("x" "number" x))
1818     "String.fromCharCode(x)"))
1819
1820 (define-builtin stringp (x)
1821   (js!bool (concat "(typeof(" x ") == \"string\")")))
1822
1823 (define-builtin string-upcase (x)
1824   (type-check (("x" "string" x))
1825     "x.toUpperCase()"))
1826
1827 (define-builtin string-length (x)
1828   (type-check (("x" "string" x))
1829     "x.length"))
1830
1831 (define-raw-builtin slice (string a &optional b)
1832   (js!selfcall
1833     "var str = " (ls-compile string) ";" *newline*
1834     "var a = " (ls-compile a) ";" *newline*
1835     "var b;" *newline*
1836     (if b
1837         (concat "b = " (ls-compile b) ";" *newline*)
1838         "")
1839     "return str.slice(a,b);" *newline*))
1840
1841 (define-builtin char (string index)
1842   (type-check (("string" "string" string)
1843                ("index" "number" index))
1844     "string.charCodeAt(index)"))
1845
1846 (define-builtin concat-two (string1 string2)
1847   (type-check (("string1" "string" string1)
1848                ("string2" "string" string2))
1849     "string1.concat(string2)"))
1850
1851 (define-raw-builtin funcall (func &rest args)
1852   (concat "(" (ls-compile func) ")("
1853           (join (cons "pv" (mapcar #'ls-compile args))
1854                 ", ")
1855           ")"))
1856
1857 (define-raw-builtin apply (func &rest args)
1858   (if (null args)
1859       (concat "(" (ls-compile func) ")()")
1860       (let ((args (butlast args))
1861             (last (car (last args))))
1862         (js!selfcall
1863           "var f = " (ls-compile func) ";" *newline*
1864           "var args = [" (join (cons "pv" (mapcar #'ls-compile args))
1865                                ", ")
1866           "];" *newline*
1867           "var tail = (" (ls-compile last) ");" *newline*
1868           "while (tail != " (ls-compile nil) "){" *newline*
1869           "    args.push(tail.car);" *newline*
1870           "    tail = tail.cdr;" *newline*
1871           "}" *newline*
1872           "return f.apply(this, args);" *newline*))))
1873
1874 (define-builtin js-eval (string)
1875   (type-check (("string" "string" string))
1876     "eval.apply(window, [string])"))
1877
1878 (define-builtin error (string)
1879   (js!selfcall "throw " string ";" *newline*))
1880
1881 (define-builtin new () "{}")
1882
1883 (define-builtin objectp (x)
1884   (js!bool (concat "(typeof (" x ") === 'object')")))
1885
1886 (define-builtin oget (object key)
1887   (js!selfcall
1888     "var tmp = " "(" object ")[" key "];" *newline*
1889     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1890
1891 (define-builtin oset (object key value)
1892   (concat "((" object ")[" key "] = " value ")"))
1893
1894 (define-builtin in (key object)
1895   (js!bool (concat "((" key ") in (" object "))")))
1896
1897 (define-builtin functionp (x)
1898   (js!bool (concat "(typeof " x " == 'function')")))
1899
1900 (define-builtin write-string (x)
1901   (type-check (("x" "string" x))
1902     "lisp.write(x)"))
1903
1904 (define-builtin make-array (n)
1905   (js!selfcall
1906     "var r = [];" *newline*
1907     "for (var i = 0; i < " n "; i++)" *newline*
1908     (indent "r.push(" (ls-compile nil) ");" *newline*)
1909     "return r;" *newline*))
1910
1911 (define-builtin arrayp (x)
1912   (js!bool
1913    (js!selfcall
1914      "var x = " x ";" *newline*
1915      "return typeof x === 'object' && 'length' in x;")))
1916
1917 (define-builtin aref (array n)
1918   (js!selfcall
1919     "var x = " "(" array ")[" n "];" *newline*
1920     "if (x === undefined) throw 'Out of range';" *newline*
1921     "return x;" *newline*))
1922
1923 (define-builtin aset (array n value)
1924   (js!selfcall
1925     "var x = " array ";" *newline*
1926     "var i = " n ";" *newline*
1927     "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
1928     "return x[i] = " value ";" *newline*))
1929
1930 (define-builtin get-unix-time ()
1931   (concat "(Math.round(new Date() / 1000))"))
1932
1933 (define-builtin values-list (list)
1934   (concat "values(" list ")"))
1935
1936 (defun macro (x)
1937   (and (symbolp x)
1938        (let ((b (lookup-in-lexenv x *environment* 'function)))
1939          (and (eq (binding-type b) 'macro)
1940               b))))
1941
1942 (defun ls-macroexpand-1 (form)
1943   (let ((macro-binding (macro (car form))))
1944     (if macro-binding
1945         (let ((expander (binding-value macro-binding)))
1946           (when (listp expander)
1947             (let ((compiled (eval expander)))
1948               ;; The list representation are useful while
1949               ;; bootstrapping, as we can dump the definition of the
1950               ;; macros easily, but they are slow because we have to
1951               ;; evaluate them and compile them now and again. So, let
1952               ;; us replace the list representation version of the
1953               ;; function with the compiled one.
1954               ;;
1955               #+ecmalisp (set-binding-value macro-binding compiled)
1956               (setq expander compiled)))
1957           (apply expander (cdr form)))
1958         form)))
1959
1960 (defun compile-funcall (function args)
1961   (if (and (symbolp function)
1962            (claimp function 'function 'non-overridable))
1963       (concat (ls-compile `',function) ".fvalue("
1964               (join (cons "pv" (mapcar #'ls-compile args))
1965                     ", ")
1966               ")")
1967       (concat (ls-compile `#',function) "("
1968               (join (cons "pv" (mapcar #'ls-compile args))
1969                     ", ")
1970               ")")))
1971
1972 (defun ls-compile-block (sexps &optional return-last-p)
1973   (if return-last-p
1974       (concat (ls-compile-block (butlast sexps))
1975               "return " (ls-compile (car (last sexps))) ";")
1976       (join-trailing
1977        (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
1978        (concat ";" *newline*))))
1979
1980 (defun ls-compile (sexp)
1981   (cond
1982     ((symbolp sexp)
1983      (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1984        (cond
1985          ((and b (not (member 'special (binding-declarations b))))
1986           (binding-value b))
1987          ((or (keywordp sexp)
1988               (member 'constant (binding-declarations b)))
1989           (concat (ls-compile `',sexp) ".value"))
1990          (t
1991           (ls-compile `(symbol-value ',sexp))))))
1992     ((integerp sexp) (integer-to-string sexp))
1993     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1994     ((arrayp sexp) (literal sexp))
1995     ((listp sexp)
1996      (let ((name (car sexp))
1997            (args (cdr sexp)))
1998        (cond
1999          ;; Special forms
2000          ((assoc name *compilations*)
2001           (let ((comp (second (assoc name *compilations*))))
2002             (apply comp args)))
2003          ;; Built-in functions
2004          ((and (assoc name *builtins*)
2005                (not (claimp name 'function 'notinline))
2006                *compiling-lambda-p*)
2007           (let ((comp (second (assoc name *builtins*))))
2008             (apply comp args)))
2009          (t
2010           (if (macro name)
2011               (ls-compile (ls-macroexpand-1 sexp))
2012               (compile-funcall name args))))))
2013     (t
2014      (error "How should I compile this?"))))
2015
2016 (defun ls-compile-toplevel (sexp)
2017   (let ((*toplevel-compilations* nil))
2018     (cond
2019       ((and (consp sexp) (eq (car sexp) 'progn))
2020        (let ((subs (mapcar #'ls-compile-toplevel (cdr sexp))))
2021          (join (remove-if #'null-or-empty-p subs))))
2022       (t
2023        (let ((code (ls-compile sexp)))
2024          (concat (join-trailing (get-toplevel-compilations)
2025                                 (concat ";" *newline*))
2026                  (if code
2027                      (concat code ";" *newline*)
2028                      "")))))))
2029
2030
2031 ;;; Once we have the compiler, we define the runtime environment and
2032 ;;; interactive development (eval), which works calling the compiler
2033 ;;; and evaluating the Javascript result globally.
2034
2035 #+ecmalisp
2036 (progn
2037   (defmacro with-compilation-unit (&body body)
2038     `(prog1
2039          (progn
2040            (setq *compilation-unit-checks* nil)
2041            ,@body)
2042        (dolist (check *compilation-unit-checks*)
2043          (funcall check))))
2044
2045   (defun eval (x)
2046     (let ((code
2047            (with-compilation-unit
2048                (ls-compile-toplevel x))))
2049       (js-eval code)))
2050
2051   (export '(&rest &optional &body * *gensym-counter* *package* + - / 1+ 1- < <= =
2052             = > >= and append apply aref arrayp aset assoc atom block boundp
2053             boundp butlast caar cadddr caddr cadr car car case catch cdar cdddr
2054             cddr cdr cdr char char-code char= code-char cond cons consp copy-list
2055             decf declaim defparameter defun defmacro defvar digit-char-p disassemble
2056             documentation dolist dotimes ecase eq eql equal error eval every
2057             export fdefinition find-package find-symbol first fourth fset funcall
2058             function functionp gensym get-universal-time go identity if in-package
2059             incf integerp integerp intern keywordp lambda last length let let*
2060             list-all-packages list listp make-array make-package make-symbol
2061             mapcar member minusp mod nil not nth nthcdr null numberp or
2062             package-name package-use-list packagep plusp prin1-to-string print
2063             proclaim prog1 prog2 progn psetq push quote remove remove-if
2064             remove-if-not return return-from revappend reverse second set setq
2065             some string-upcase string string= stringp subseq symbol-function
2066             symbol-name symbol-package symbol-plist symbol-value symbolp t tagbody
2067             third throw truncate unless unwind-protect variable warn when
2068             write-line write-string zerop))
2069
2070   (setq *package* *user-package*)
2071
2072   (js-eval "var lisp")
2073   (js-vset "lisp" (new))
2074   (js-vset "lisp.read" #'ls-read-from-string)
2075   (js-vset "lisp.print" #'prin1-to-string)
2076   (js-vset "lisp.eval" #'eval)
2077   (js-vset "lisp.compile" #'ls-compile-toplevel)
2078   (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
2079   (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str))))
2080
2081   ;; Set the initial global environment to be equal to the host global
2082   ;; environment at this point of the compilation.
2083   (eval-when-compile
2084     (toplevel-compilation
2085      (ls-compile
2086       `(progn
2087          ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
2088                    *literal-symbols*)
2089          (setq *literal-symbols* ',*literal-symbols*)
2090          (setq *environment* ',*environment*)
2091          (setq *variable-counter* ,*variable-counter*)
2092          (setq *gensym-counter* ,*gensym-counter*)
2093          (setq *block-counter* ,*block-counter*)))))
2094
2095   (eval-when-compile
2096     (toplevel-compilation
2097      (ls-compile
2098       `(setq *literal-counter* ,*literal-counter*)))))
2099
2100
2101 ;;; Finally, we provide a couple of functions to easily bootstrap
2102 ;;; this. It just calls the compiler with this file as input.
2103
2104 #+common-lisp
2105 (progn
2106   (defun read-whole-file (filename)
2107     (with-open-file (in filename)
2108       (let ((seq (make-array (file-length in) :element-type 'character)))
2109         (read-sequence seq in)
2110         seq)))
2111
2112   (defun ls-compile-file (filename output)
2113     (setq *compilation-unit-checks* nil)
2114     (with-open-file (out output :direction :output :if-exists :supersede)
2115       (let* ((source (read-whole-file filename))
2116              (in (make-string-stream source)))
2117         (loop
2118            for x = (ls-read in)
2119            until (eq x *eof*)
2120            for compilation = (ls-compile-toplevel x)
2121            when (plusp (length compilation))
2122            do (write-string compilation out))
2123         (dolist (check *compilation-unit-checks*)
2124           (funcall check))
2125         (setq *compilation-unit-checks* nil))))
2126
2127   (defun bootstrap ()
2128     (setq *environment* (make-lexenv))
2129     (setq *literal-symbols* nil)
2130     (setq *variable-counter* 0
2131           *gensym-counter* 0
2132           *literal-counter* 0
2133           *block-counter* 0)
2134     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))