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