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