e1212584e1ee66e0ad6e62316a80acaba56d6ccf
[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   ;; The `values-list' primitive cannot be inlined out of functions as
607   ;; the VALUES argument is not available there. We declare it
608   ;; NOTINLINE to avoid it.
609   (defun values-list (list)
610     (values-list list))
611   (declaim (notinline values-list))
612
613   (defun values (&rest args)
614     (values-list args)))
615
616
617 ;;; The compiler offers some primitives and special forms which are
618 ;;; not found in Common Lisp, for instance, while. So, we grow Common
619 ;;; Lisp a bit to it can execute the rest of the file.
620 #+common-lisp
621 (progn
622   (defmacro while (condition &body body)
623     `(do ()
624          ((not ,condition))
625        ,@body))
626
627   (defmacro eval-when-compile (&body body)
628     `(eval-when (:compile-toplevel :load-toplevel :execute)
629        ,@body))
630
631   (defun concat-two (s1 s2)
632     (concatenate 'string s1 s2))
633
634   (defun setcar (cons new)
635     (setf (car cons) new))
636   (defun setcdr (cons new)
637     (setf (cdr cons) new))
638
639   (defun aset (array idx value)
640     (setf (aref array idx) value)))
641
642 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
643 ;;; from here, this code will compile on both. We define some helper
644 ;;; functions now for string manipulation and so on. They will be
645 ;;; useful in the compiler, mostly.
646
647 (defvar *newline* (string (code-char 10)))
648
649 (defun concat (&rest strs)
650   (!reduce #'concat-two strs ""))
651
652 (defmacro concatf (variable &body form)
653   `(setq ,variable (concat ,variable (progn ,@form))))
654
655 ;;; Concatenate a list of strings, with a separator
656 (defun join (list &optional (separator ""))
657   (cond
658     ((null list)
659      "")
660     ((null (cdr list))
661      (car list))
662     (t
663      (concat (car list)
664              separator
665              (join (cdr list) separator)))))
666
667 (defun join-trailing (list &optional (separator ""))
668   (if (null list)
669       ""
670       (concat (car list) separator (join-trailing (cdr list) separator))))
671
672 (defun mapconcat (func list)
673   (join (mapcar func list)))
674
675 (defun vector-to-list (vector)
676   (let ((list nil)
677         (size (length vector)))
678     (dotimes (i size (reverse list))
679       (push (aref vector i) list))))
680
681 (defun list-to-vector (list)
682   (let ((v (make-array (length list)))
683         (i 0))
684     (dolist (x list v)
685       (aset v i x)
686       (incf i))))
687
688 ;;; Like CONCAT, but prefix each line with four spaces. Two versions
689 ;;; of this function are available, because the Ecmalisp version is
690 ;;; very slow and bootstraping was annoying.
691
692 #+ecmalisp
693 (defun indent (&rest string)
694   (let ((input (join string)))
695     (let ((output "")
696           (index 0)
697           (size (length input)))
698       (when (plusp (length input)) (concatf output "    "))
699       (while (< index size)
700         (let ((str
701                (if (and (char= (char input index) #\newline)
702                         (< index (1- size))
703                         (not (char= (char input (1+ index)) #\newline)))
704                    (concat (string #\newline) "    ")
705                    (string (char input index)))))
706           (concatf output str))
707         (incf index))
708       output)))
709
710 #+common-lisp
711 (defun indent (&rest string)
712   (with-output-to-string (*standard-output*)
713     (with-input-from-string (input (join string))
714       (loop
715          for line = (read-line input nil)
716          while line
717          do (write-string "    ")
718          do (write-line line)))))
719
720
721 (defun integer-to-string (x)
722   (cond
723     ((zerop x)
724      "0")
725     ((minusp x)
726      (concat "-" (integer-to-string (- 0 x))))
727     (t
728      (let ((digits nil))
729        (while (not (zerop x))
730          (push (mod x 10) digits)
731          (setq x (truncate x 10)))
732        (join (mapcar (lambda (d) (string (char "0123456789" d)))
733                      digits))))))
734
735
736 ;;; Wrap X with a Javascript code to convert the result from
737 ;;; Javascript generalized booleans to T or NIL.
738 (defun js!bool (x)
739   (concat "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
740
741 ;;; Concatenate the arguments and wrap them with a self-calling
742 ;;; Javascript anonymous function. It is used to make some Javascript
743 ;;; statements valid expressions and provide a private scope as well.
744 ;;; It could be defined as function, but we could do some
745 ;;; preprocessing in the future.
746 (defmacro js!selfcall (&body body)
747   `(concat "(function(){" *newline* (indent ,@body) "})()"))
748
749
750 ;;; Printer
751
752 #+ecmalisp
753 (progn
754   (defun prin1-to-string (form)
755     (cond
756       ((symbolp form)
757        (if (cdr (%find-symbol (symbol-name form) *package*))
758            (symbol-name form)
759            (let ((package (symbol-package form))
760                  (name (symbol-name form)))
761              (concat (cond
762                        ((null package) "#")
763                        ((eq package (find-package "KEYWORD")) "")
764                        (t (package-name package)))
765                      ":" name))))
766       ((integerp form) (integer-to-string form))
767       ((stringp form) (concat "\"" (escape-string form) "\""))
768       ((functionp form)
769        (let ((name (oget form "fname")))
770          (if name
771              (concat "#<FUNCTION " name ">")
772              (concat "#<FUNCTION>"))))
773       ((listp form)
774        (concat "("
775                (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
776                (let ((last (last form)))
777                  (if (null (cdr last))
778                      (prin1-to-string (car last))
779                      (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
780                ")"))
781       ((arrayp form)
782        (concat "#" (prin1-to-string (vector-to-list form))))
783       ((packagep form)
784        (concat "#<PACKAGE " (package-name form) ">"))))
785
786   (defun write-line (x)
787     (write-string x)
788     (write-string *newline*)
789     x)
790
791   (defun warn (string)
792     (write-string "WARNING: ")
793     (write-line string))
794
795   (defun print (x)
796     (write-line (prin1-to-string x))
797     x))
798
799
800 ;;;; Reader
801
802 ;;; The Lisp reader, parse strings and return Lisp objects. The main
803 ;;; entry points are `ls-read' and `ls-read-from-string'.
804
805 (defun make-string-stream (string)
806   (cons string 0))
807
808 (defun %peek-char (stream)
809   (and (< (cdr stream) (length (car stream)))
810        (char (car stream) (cdr stream))))
811
812 (defun %read-char (stream)
813   (and (< (cdr stream) (length (car stream)))
814        (prog1 (char (car stream) (cdr stream))
815          (setcdr stream (1+ (cdr stream))))))
816
817 (defun whitespacep (ch)
818   (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
819
820 (defun skip-whitespaces (stream)
821   (let (ch)
822     (setq ch (%peek-char stream))
823     (while (and ch (whitespacep ch))
824       (%read-char stream)
825       (setq ch (%peek-char stream)))))
826
827 (defun terminalp (ch)
828   (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
829
830 (defun read-until (stream func)
831   (let ((string "")
832         (ch))
833     (setq ch (%peek-char stream))
834     (while (and ch (not (funcall func ch)))
835       (setq string (concat string (string ch)))
836       (%read-char stream)
837       (setq ch (%peek-char stream)))
838     string))
839
840 (defun skip-whitespaces-and-comments (stream)
841   (let (ch)
842     (skip-whitespaces stream)
843     (setq ch (%peek-char stream))
844     (while (and ch (char= ch #\;))
845       (read-until stream (lambda (x) (char= x #\newline)))
846       (skip-whitespaces stream)
847       (setq ch (%peek-char stream)))))
848
849 (defun %read-list (stream)
850   (skip-whitespaces-and-comments stream)
851   (let ((ch (%peek-char stream)))
852     (cond
853       ((null ch)
854        (error "Unspected EOF"))
855       ((char= ch #\))
856        (%read-char stream)
857        nil)
858       ((char= ch #\.)
859        (%read-char stream)
860        (prog1 (ls-read stream)
861          (skip-whitespaces-and-comments stream)
862          (unless (char= (%read-char stream) #\))
863            (error "')' was expected."))))
864       (t
865        (cons (ls-read stream) (%read-list stream))))))
866
867 (defun read-string (stream)
868   (let ((string "")
869         (ch nil))
870     (setq ch (%read-char stream))
871     (while (not (eql ch #\"))
872       (when (null ch)
873         (error "Unexpected EOF"))
874       (when (eql ch #\\)
875         (setq ch (%read-char stream)))
876       (setq string (concat string (string ch)))
877       (setq ch (%read-char stream)))
878     string))
879
880 (defun read-sharp (stream)
881   (%read-char stream)
882   (ecase (%read-char stream)
883     (#\'
884      (list 'function (ls-read stream)))
885     (#\( (list-to-vector (%read-list stream)))
886     (#\: (make-symbol (string-upcase (read-until stream #'terminalp))))
887     (#\\
888      (let ((cname
889             (concat (string (%read-char stream))
890                     (read-until stream #'terminalp))))
891        (cond
892          ((string= cname "space") (char-code #\space))
893          ((string= cname "tab") (char-code #\tab))
894          ((string= cname "newline") (char-code #\newline))
895          (t (char-code (char cname 0))))))
896     (#\+
897      (let ((feature (read-until stream #'terminalp)))
898        (cond
899          ((string= feature "common-lisp")
900           (ls-read stream)              ;ignore
901           (ls-read stream))
902          ((string= feature "ecmalisp")
903           (ls-read stream))
904          (t
905           (error "Unknown reader form.")))))))
906
907 ;;; Parse a string of the form NAME, PACKAGE:NAME or
908 ;;; PACKAGE::NAME and return the name. If the string is of the
909 ;;; form 1) or 3), but the symbol does not exist, it will be created
910 ;;; and interned in that package.
911 (defun read-symbol (string)
912   (let ((size (length string))
913         package name internalp index)
914     (setq index 0)
915     (while (and (< index size)
916                 (not (char= (char string index) #\:)))
917       (incf index))
918     (cond
919       ;; No package prefix
920       ((= index size)
921        (setq name string)
922        (setq package *package*)
923        (setq internalp t))
924       (t
925        ;; Package prefix
926        (if (zerop index)
927            (setq package "KEYWORD")
928            (setq package (string-upcase (subseq string 0 index))))
929        (incf index)
930        (when (char= (char string index) #\:)
931          (setq internalp t)
932          (incf index))
933        (setq name (subseq string index))))
934     ;; Canonalize symbol name and package
935     (setq name (string-upcase name))
936     (setq package (find-package package))
937     ;; TODO: PACKAGE:SYMBOL should signal error if SYMBOL is not an
938     ;; external symbol from PACKAGE.
939     (if (or internalp (eq package (find-package "KEYWORD")))
940         (intern name package)
941         (find-symbol name package))))
942
943 (defvar *eof* (gensym))
944 (defun ls-read (stream)
945   (skip-whitespaces-and-comments stream)
946   (let ((ch (%peek-char stream)))
947     (cond
948       ((or (null ch) (char= ch #\)))
949        *eof*)
950       ((char= ch #\()
951        (%read-char stream)
952        (%read-list stream))
953       ((char= ch #\')
954        (%read-char stream)
955        (list 'quote (ls-read stream)))
956       ((char= ch #\`)
957        (%read-char stream)
958        (list 'backquote (ls-read stream)))
959       ((char= ch #\")
960        (%read-char stream)
961        (read-string stream))
962       ((char= ch #\,)
963        (%read-char stream)
964        (if (eql (%peek-char stream) #\@)
965            (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
966            (list 'unquote (ls-read stream))))
967       ((char= ch #\#)
968        (read-sharp stream))
969       (t
970        (let ((string (read-until stream #'terminalp)))
971          (if (every #'digit-char-p string)
972              (parse-integer string)
973              (read-symbol string)))))))
974
975 (defun ls-read-from-string (string)
976   (ls-read (make-string-stream string)))
977
978
979 ;;;; Compiler
980
981 ;;; Translate the Lisp code to Javascript. It will compile the special
982 ;;; forms. Some primitive functions are compiled as special forms
983 ;;; too. The respective real functions are defined in the target (see
984 ;;; the beginning of this file) as well as some primitive functions.
985
986 (defvar *compilation-unit-checks* '())
987
988 (defun make-binding (name type value &optional declarations)
989   (list name type value declarations))
990
991 (defun binding-name (b) (first b))
992 (defun binding-type (b) (second b))
993 (defun binding-value (b) (third b))
994 (defun binding-declarations (b) (fourth b))
995
996 (defun set-binding-value (b value)
997   (setcar (cddr b) value))
998
999 (defun set-binding-declarations (b value)
1000   (setcar (cdddr b) value))
1001
1002 (defun push-binding-declaration (decl b)
1003   (set-binding-declarations b (cons decl (binding-declarations b))))
1004
1005
1006 (defun make-lexenv ()
1007   (list nil nil nil nil))
1008
1009 (defun copy-lexenv (lexenv)
1010   (copy-list lexenv))
1011
1012 (defun push-to-lexenv (binding lexenv namespace)
1013   (ecase namespace
1014     (variable   (setcar        lexenv  (cons binding (car lexenv))))
1015     (function   (setcar   (cdr lexenv) (cons binding (cadr lexenv))))
1016     (block      (setcar  (cddr lexenv) (cons binding (caddr lexenv))))
1017     (gotag      (setcar (cdddr lexenv) (cons binding (cadddr lexenv))))))
1018
1019 (defun extend-lexenv (bindings lexenv namespace)
1020   (let ((env (copy-lexenv lexenv)))
1021     (dolist (binding (reverse bindings) env)
1022       (push-to-lexenv binding env namespace))))
1023
1024 (defun lookup-in-lexenv (name lexenv namespace)
1025   (assoc name (ecase namespace
1026                 (variable (first lexenv))
1027                 (function (second lexenv))
1028                 (block (third lexenv))
1029                 (gotag (fourth lexenv)))))
1030
1031 (defvar *environment* (make-lexenv))
1032
1033 (defvar *variable-counter* 0)
1034 (defun gvarname (symbol)
1035   (concat "v" (integer-to-string (incf *variable-counter*))))
1036
1037 (defun translate-variable (symbol)
1038   (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
1039
1040 (defun extend-local-env (args)
1041   (let ((new (copy-lexenv *environment*)))
1042     (dolist (symbol args new)
1043       (let ((b (make-binding symbol 'lexical-variable (gvarname symbol))))
1044         (push-to-lexenv b new 'variable)))))
1045
1046 ;;; Toplevel compilations
1047 (defvar *toplevel-compilations* nil)
1048
1049 (defun toplevel-compilation (string)
1050   (push string *toplevel-compilations*))
1051
1052 (defun null-or-empty-p (x)
1053   (zerop (length x)))
1054
1055 (defun get-toplevel-compilations ()
1056   (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
1057
1058 (defun %compile-defmacro (name lambda)
1059   (toplevel-compilation (ls-compile `',name))
1060   (push-to-lexenv (make-binding name 'macro lambda) *environment* 'function))
1061
1062 (defun global-binding (name type namespace)
1063   (or (lookup-in-lexenv name *environment* namespace)
1064       (let ((b (make-binding name type nil)))
1065         (push-to-lexenv b *environment* namespace)
1066         b)))
1067
1068 (defun claimp (symbol namespace claim)
1069   (let ((b (lookup-in-lexenv symbol *environment* namespace)))
1070     (and b (member claim (binding-declarations b)))))
1071
1072 (defun !proclaim (decl)
1073   (case (car decl)
1074     (special
1075      (dolist (name (cdr decl))
1076        (let ((b (global-binding name 'variable 'variable)))
1077          (push-binding-declaration 'special b))))
1078     (notinline
1079      (dolist (name (cdr decl))
1080        (let ((b (global-binding name 'function 'function)))
1081          (push-binding-declaration 'notinline b))))
1082     (constant
1083      (dolist (name (cdr decl))
1084        (let ((b (global-binding name 'variable 'variable)))
1085          (push-binding-declaration 'constant b))))
1086     (non-overridable
1087      (dolist (name (cdr decl))
1088        (let ((b (global-binding name 'function 'function)))
1089          (push-binding-declaration 'non-overridable b))))))
1090
1091 #+ecmalisp
1092 (fset 'proclaim #'!proclaim)
1093
1094 ;;; Special forms
1095
1096 (defvar *compilations* nil)
1097
1098 (defmacro define-compilation (name args &body body)
1099   ;; Creates a new primitive `name' with parameters args and
1100   ;; @body. The body can access to the local environment through the
1101   ;; variable *ENVIRONMENT*.
1102   `(push (list ',name (lambda ,args (block ,name ,@body)))
1103          *compilations*))
1104
1105 (define-compilation if (condition true false)
1106   (concat "(" (ls-compile condition) " !== " (ls-compile nil)
1107           " ? " (ls-compile true)
1108           " : " (ls-compile false)
1109           ")"))
1110
1111 (defvar *lambda-list-keywords* '(&optional &rest))
1112
1113 (defun list-until-keyword (list)
1114   (if (or (null list) (member (car list) *lambda-list-keywords*))
1115       nil
1116       (cons (car list) (list-until-keyword (cdr list)))))
1117
1118 (defun lambda-list-required-arguments (lambda-list)
1119   (list-until-keyword lambda-list))
1120
1121 (defun lambda-list-optional-arguments-with-default (lambda-list)
1122   (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
1123
1124 (defun lambda-list-optional-arguments (lambda-list)
1125   (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
1126
1127 (defun lambda-list-rest-argument (lambda-list)
1128   (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
1129     (when (cdr rest)
1130       (error "Bad lambda-list"))
1131     (car rest)))
1132
1133
1134 (defun lambda-docstring-wrapper (docstring &rest strs)
1135   (if docstring
1136       (js!selfcall
1137         "var func = " (join strs) ";" *newline*
1138         "func.docstring = '" docstring "';" *newline*
1139         "return func;" *newline*)
1140       (join strs)))
1141
1142 (define-compilation lambda (lambda-list &rest body)
1143   (let ((required-arguments (lambda-list-required-arguments lambda-list))
1144         (optional-arguments (lambda-list-optional-arguments lambda-list))
1145         (rest-argument (lambda-list-rest-argument lambda-list))
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           (let ((comp (second (assoc name *builtins*))))
2007             (apply comp args)))
2008          (t
2009           (if (macro name)
2010               (ls-compile (ls-macroexpand-1 sexp))
2011               (compile-funcall name args))))))
2012     (t
2013      (error "How should I compile this?"))))
2014
2015 (defun ls-compile-toplevel (sexp)
2016   (let ((*toplevel-compilations* nil))
2017     (cond
2018       ((and (consp sexp) (eq (car sexp) 'progn))
2019        (let ((subs (mapcar #'ls-compile-toplevel (cdr sexp))))
2020          (join (remove-if #'null-or-empty-p subs))))
2021       (t
2022        (let ((code (ls-compile sexp)))
2023          (concat (join-trailing (get-toplevel-compilations)
2024                                 (concat ";" *newline*))
2025                  (if code
2026                      (concat code ";" *newline*)
2027                      "")))))))
2028
2029
2030 ;;; Once we have the compiler, we define the runtime environment and
2031 ;;; interactive development (eval), which works calling the compiler
2032 ;;; and evaluating the Javascript result globally.
2033
2034 #+ecmalisp
2035 (progn
2036   (defmacro with-compilation-unit (&body body)
2037     `(prog1
2038          (progn
2039            (setq *compilation-unit-checks* nil)
2040            ,@body)
2041        (dolist (check *compilation-unit-checks*)
2042          (funcall check))))
2043
2044   (defun eval (x)
2045     (let ((code
2046            (with-compilation-unit
2047                (ls-compile-toplevel x))))
2048       (js-eval code)))
2049
2050   (export '(&rest &optional &body * *gensym-counter* *package* + - / 1+ 1- < <= =
2051             = > >= and append apply aref arrayp aset assoc atom block boundp
2052             boundp butlast caar cadddr caddr cadr car car case catch cdar cdddr
2053             cddr cdr cdr char char-code char= code-char cond cons consp copy-list
2054             decf declaim defparameter defun defmacro defvar digit-char-p disassemble
2055             documentation dolist dotimes ecase eq eql equal error eval every
2056             export fdefinition find-package find-symbol first fourth fset funcall
2057             function functionp gensym get-universal-time go identity if in-package
2058             incf integerp integerp intern keywordp lambda last length let let*
2059             list-all-packages list listp make-array make-package make-symbol
2060             mapcar member minusp mod nil not nth nthcdr null numberp or
2061             package-name package-use-list packagep plusp prin1-to-string print
2062             proclaim prog1 prog2 progn psetq push quote remove remove-if
2063             remove-if-not return return-from revappend reverse second set setq
2064             some string-upcase string string= stringp subseq symbol-function
2065             symbol-name symbol-package symbol-plist symbol-value symbolp t tagbody
2066             third throw truncate unless unwind-protect variable warn when
2067             write-line write-string zerop))
2068
2069   (setq *package* *user-package*)
2070
2071   (js-eval "var lisp")
2072   (js-vset "lisp" (new))
2073   (js-vset "lisp.read" #'ls-read-from-string)
2074   (js-vset "lisp.print" #'prin1-to-string)
2075   (js-vset "lisp.eval" #'eval)
2076   (js-vset "lisp.compile" #'ls-compile-toplevel)
2077   (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
2078   (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str))))
2079
2080   ;; Set the initial global environment to be equal to the host global
2081   ;; environment at this point of the compilation.
2082   (eval-when-compile
2083     (toplevel-compilation
2084      (ls-compile
2085       `(progn
2086          ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
2087                    *literal-symbols*)
2088          (setq *literal-symbols* ',*literal-symbols*)
2089          (setq *environment* ',*environment*)
2090          (setq *variable-counter* ,*variable-counter*)
2091          (setq *gensym-counter* ,*gensym-counter*)
2092          (setq *block-counter* ,*block-counter*)))))
2093
2094   (eval-when-compile
2095     (toplevel-compilation
2096      (ls-compile
2097       `(setq *literal-counter* ,*literal-counter*)))))
2098
2099
2100 ;;; Finally, we provide a couple of functions to easily bootstrap
2101 ;;; this. It just calls the compiler with this file as input.
2102
2103 #+common-lisp
2104 (progn
2105   (defun read-whole-file (filename)
2106     (with-open-file (in filename)
2107       (let ((seq (make-array (file-length in) :element-type 'character)))
2108         (read-sequence seq in)
2109         seq)))
2110
2111   (defun ls-compile-file (filename output)
2112     (setq *compilation-unit-checks* nil)
2113     (with-open-file (out output :direction :output :if-exists :supersede)
2114       (let* ((source (read-whole-file filename))
2115              (in (make-string-stream source)))
2116         (loop
2117            for x = (ls-read in)
2118            until (eq x *eof*)
2119            for compilation = (ls-compile-toplevel x)
2120            when (plusp (length compilation))
2121            do (write-string compilation out))
2122         (dolist (check *compilation-unit-checks*)
2123           (funcall check))
2124         (setq *compilation-unit-checks* nil))))
2125
2126   (defun bootstrap ()
2127     (setq *environment* (make-lexenv))
2128     (setq *literal-symbols* nil)
2129     (setq *variable-counter* 0
2130           *gensym-counter* 0
2131           *literal-counter* 0
2132           *block-counter* 0)
2133     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))