IF can return multiple values
[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 *multiple-value-p*)
1111           " : " (ls-compile false *multiple-value-p*)
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       "values = function(){" *newline*
1572       (indent "var result = [];" *newline*
1573               "result['multiple-value'] = true;" *newline*
1574               "for (var i=0; i<arguments.length; i++)" *newline*
1575               (indent "result.push(arguments[i]);" *newline*)
1576               "return result;" *newline*)
1577       "}" *newline*
1578       "var vs;" *newline*
1579       (mapconcat (lambda (form)
1580                    (concat "vs = " (ls-compile form t) ";" *newline*
1581                            "if (typeof vs === 'object' && 'multiple-value' in vs)" *newline*
1582                            (indent "args = args.concat(vs);" *newline*)
1583                            "else" *newline*
1584                            (indent "args.push(vs);" *newline*)))
1585                  forms)
1586       "return (" func ").apply(window, args);" *newline*)))
1587
1588
1589
1590 ;;; A little backquote implementation without optimizations of any
1591 ;;; kind for ecmalisp.
1592 (defun backquote-expand-1 (form)
1593   (cond
1594     ((symbolp form)
1595      (list 'quote form))
1596     ((atom form)
1597      form)
1598     ((eq (car form) 'unquote)
1599      (car form))
1600     ((eq (car form) 'backquote)
1601      (backquote-expand-1 (backquote-expand-1 (cadr form))))
1602     (t
1603      (cons 'append
1604            (mapcar (lambda (s)
1605                      (cond
1606                        ((and (listp s) (eq (car s) 'unquote))
1607                         (list 'list (cadr s)))
1608                        ((and (listp s) (eq (car s) 'unquote-splicing))
1609                         (cadr s))
1610                        (t
1611                         (list 'list (backquote-expand-1 s)))))
1612                    form)))))
1613
1614 (defun backquote-expand (form)
1615   (if (and (listp form) (eq (car form) 'backquote))
1616       (backquote-expand-1 (cadr form))
1617       form))
1618
1619 (defmacro backquote (form)
1620   (backquote-expand-1 form))
1621
1622 (define-transformation backquote (form)
1623   (backquote-expand-1 form))
1624
1625 ;;; Primitives
1626
1627 (defvar *builtins* nil)
1628
1629 (defmacro define-raw-builtin (name args &body body)
1630   ;; Creates a new primitive function `name' with parameters args and
1631   ;; @body. The body can access to the local environment through the
1632   ;; variable *ENVIRONMENT*.
1633   `(push (list ',name (lambda ,args (block ,name ,@body)))
1634          *builtins*))
1635
1636 (defmacro define-builtin (name args &body body)
1637   `(progn
1638      (define-raw-builtin ,name ,args
1639        (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1640          ,@body))))
1641
1642 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1643 (defmacro type-check (decls &body body)
1644   `(js!selfcall
1645      ,@(mapcar (lambda (decl)
1646                    `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1647                  decls)
1648      ,@(mapcar (lambda (decl)
1649                  `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1650                           (indent "throw 'The value ' + "
1651                                   ,(first decl)
1652                                   " + ' is not a type "
1653                                   ,(second decl)
1654                                   ".';"
1655                                   *newline*)))
1656                decls)
1657      (concat "return " (progn ,@body) ";" *newline*)))
1658
1659 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
1660 ;;; a variable which holds a list of forms. It will compile them and
1661 ;;; store the result in some Javascript variables. BODY is evaluated
1662 ;;; with ARGS bound to the list of these variables to generate the
1663 ;;; code which performs the transformation on these variables.
1664
1665 (defun variable-arity-call (args function)
1666   (unless (consp args)
1667     (error "ARGS must be a non-empty list"))
1668   (let ((counter 0)
1669         (variables '())
1670         (prelude ""))
1671     (dolist (x args)
1672       (let ((v (concat "x" (integer-to-string (incf counter)))))
1673         (push v variables)
1674         (concatf prelude
1675                  (concat "var " v " = " (ls-compile x) ";" *newline*
1676                          "if (typeof " v " !== 'number') throw 'Not a number!';"
1677                          *newline*))))
1678     (js!selfcall prelude (funcall function (reverse variables)))))
1679
1680
1681 (defmacro variable-arity (args &body body)
1682   (unless (symbolp args)
1683     (error "Bad usage of VARIABLE-ARITY, you must pass a symbol"))
1684   `(variable-arity-call ,args
1685                         (lambda (,args)
1686                           (concat "return " ,@body ";" *newline*))))
1687
1688 (defun num-op-num (x op y)
1689   (type-check (("x" "number" x) ("y" "number" y))
1690     (concat "x" op "y")))
1691
1692 (define-raw-builtin + (&rest numbers)
1693   (if (null numbers)
1694       "0"
1695       (variable-arity numbers
1696         (join numbers "+"))))
1697
1698 (define-raw-builtin - (x &rest others)
1699   (let ((args (cons x others)))
1700     (variable-arity args
1701       (if (null others)
1702           (concat "-" (car args))
1703           (join args "-")))))
1704
1705 (define-raw-builtin * (&rest numbers)
1706   (if (null numbers)
1707       "1"
1708       (variable-arity numbers
1709         (join numbers "*"))))
1710
1711 (define-raw-builtin / (x &rest others)
1712   (let ((args (cons x others)))
1713     (variable-arity args
1714       (if (null others)
1715           (concat "1 /" (car args))
1716           (join args "/")))))
1717
1718 (define-builtin mod (x y) (num-op-num x "%" y))
1719
1720
1721 (defun comparison-conjuntion (vars op)
1722   (cond
1723     ((null (cdr vars))
1724      "true")
1725     ((null (cddr vars))
1726      (concat (car vars) op (cadr vars)))
1727     (t
1728      (concat (car vars) op (cadr vars)
1729              " && "
1730              (comparison-conjuntion (cdr vars) op)))))
1731
1732 (defmacro define-builtin-comparison (op sym)
1733   `(define-raw-builtin ,op (x &rest args)
1734      (let ((args (cons x args)))
1735        (variable-arity args
1736          (js!bool (comparison-conjuntion args ,sym))))))
1737
1738 (define-builtin-comparison > ">")
1739 (define-builtin-comparison < "<")
1740 (define-builtin-comparison >= ">=")
1741 (define-builtin-comparison <= "<=")
1742 (define-builtin-comparison = "==")
1743
1744 (define-builtin numberp (x)
1745   (js!bool (concat "(typeof (" x ") == \"number\")")))
1746
1747 (define-builtin floor (x)
1748   (type-check (("x" "number" x))
1749     "Math.floor(x)"))
1750
1751 (define-builtin cons (x y)
1752   (concat "({car: " x ", cdr: " y "})"))
1753
1754 (define-builtin consp (x)
1755   (js!bool
1756    (js!selfcall
1757      "var tmp = " x ";" *newline*
1758      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1759
1760 (define-builtin car (x)
1761   (js!selfcall
1762     "var tmp = " x ";" *newline*
1763     "return tmp === " (ls-compile nil)
1764     "? " (ls-compile nil)
1765     ": tmp.car;" *newline*))
1766
1767 (define-builtin cdr (x)
1768   (js!selfcall
1769     "var tmp = " x ";" *newline*
1770     "return tmp === " (ls-compile nil) "? "
1771     (ls-compile nil)
1772     ": tmp.cdr;" *newline*))
1773
1774 (define-builtin setcar (x new)
1775   (type-check (("x" "object" x))
1776     (concat "(x.car = " new ")")))
1777
1778 (define-builtin setcdr (x new)
1779   (type-check (("x" "object" x))
1780     (concat "(x.cdr = " new ")")))
1781
1782 (define-builtin symbolp (x)
1783   (js!bool
1784    (js!selfcall
1785      "var tmp = " x ";" *newline*
1786      "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1787
1788 (define-builtin make-symbol (name)
1789   (type-check (("name" "string" name))
1790     "({name: name})"))
1791
1792 (define-builtin symbol-name (x)
1793   (concat "(" x ").name"))
1794
1795 (define-builtin set (symbol value)
1796   (concat "(" symbol ").value = " value))
1797
1798 (define-builtin fset (symbol value)
1799   (concat "(" symbol ").fvalue = " value))
1800
1801 (define-builtin boundp (x)
1802   (js!bool (concat "(" x ".value !== undefined)")))
1803
1804 (define-builtin symbol-value (x)
1805   (js!selfcall
1806     "var symbol = " x ";" *newline*
1807     "var value = symbol.value;" *newline*
1808     "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1809     "return value;" *newline*))
1810
1811 (define-builtin symbol-function (x)
1812   (js!selfcall
1813     "var symbol = " x ";" *newline*
1814     "var func = symbol.fvalue;" *newline*
1815     "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1816     "return func;" *newline*))
1817
1818 (define-builtin symbol-plist (x)
1819   (concat "((" x ").plist || " (ls-compile nil) ")"))
1820
1821 (define-builtin lambda-code (x)
1822   (concat "(" x ").toString()"))
1823
1824 (define-builtin eq    (x y) (js!bool (concat "(" x " === " y ")")))
1825 (define-builtin equal (x y) (js!bool (concat "(" x  " == " y ")")))
1826
1827 (define-builtin char-to-string (x)
1828   (type-check (("x" "number" x))
1829     "String.fromCharCode(x)"))
1830
1831 (define-builtin stringp (x)
1832   (js!bool (concat "(typeof(" x ") == \"string\")")))
1833
1834 (define-builtin string-upcase (x)
1835   (type-check (("x" "string" x))
1836     "x.toUpperCase()"))
1837
1838 (define-builtin string-length (x)
1839   (type-check (("x" "string" x))
1840     "x.length"))
1841
1842 (define-raw-builtin slice (string a &optional b)
1843   (js!selfcall
1844     "var str = " (ls-compile string) ";" *newline*
1845     "var a = " (ls-compile a) ";" *newline*
1846     "var b;" *newline*
1847     (if b
1848         (concat "b = " (ls-compile b) ";" *newline*)
1849         "")
1850     "return str.slice(a,b);" *newline*))
1851
1852 (define-builtin char (string index)
1853   (type-check (("string" "string" string)
1854                ("index" "number" index))
1855     "string.charCodeAt(index)"))
1856
1857 (define-builtin concat-two (string1 string2)
1858   (type-check (("string1" "string" string1)
1859                ("string2" "string" string2))
1860     "string1.concat(string2)"))
1861
1862 (define-raw-builtin funcall (func &rest args)
1863   (concat "(" (ls-compile func) ")("
1864           (join (cons "pv" (mapcar #'ls-compile args))
1865                 ", ")
1866           ")"))
1867
1868 (define-raw-builtin apply (func &rest args)
1869   (if (null args)
1870       (concat "(" (ls-compile func) ")()")
1871       (let ((args (butlast args))
1872             (last (car (last args))))
1873         (js!selfcall
1874           "var f = " (ls-compile func) ";" *newline*
1875           "var args = [" (join (cons "pv" (mapcar #'ls-compile args))
1876                                ", ")
1877           "];" *newline*
1878           "var tail = (" (ls-compile last) ");" *newline*
1879           "while (tail != " (ls-compile nil) "){" *newline*
1880           "    args.push(tail.car);" *newline*
1881           "    tail = tail.cdr;" *newline*
1882           "}" *newline*
1883           "return f.apply(this, args);" *newline*))))
1884
1885 (define-builtin js-eval (string)
1886   (type-check (("string" "string" string))
1887     "eval.apply(window, [string])"))
1888
1889 (define-builtin error (string)
1890   (js!selfcall "throw " string ";" *newline*))
1891
1892 (define-builtin new () "{}")
1893
1894 (define-builtin objectp (x)
1895   (js!bool (concat "(typeof (" x ") === 'object')")))
1896
1897 (define-builtin oget (object key)
1898   (js!selfcall
1899     "var tmp = " "(" object ")[" key "];" *newline*
1900     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1901
1902 (define-builtin oset (object key value)
1903   (concat "((" object ")[" key "] = " value ")"))
1904
1905 (define-builtin in (key object)
1906   (js!bool (concat "((" key ") in (" object "))")))
1907
1908 (define-builtin functionp (x)
1909   (js!bool (concat "(typeof " x " == 'function')")))
1910
1911 (define-builtin write-string (x)
1912   (type-check (("x" "string" x))
1913     "lisp.write(x)"))
1914
1915 (define-builtin make-array (n)
1916   (js!selfcall
1917     "var r = [];" *newline*
1918     "for (var i = 0; i < " n "; i++)" *newline*
1919     (indent "r.push(" (ls-compile nil) ");" *newline*)
1920     "return r;" *newline*))
1921
1922 (define-builtin arrayp (x)
1923   (js!bool
1924    (js!selfcall
1925      "var x = " x ";" *newline*
1926      "return typeof x === 'object' && 'length' in x;")))
1927
1928 (define-builtin aref (array n)
1929   (js!selfcall
1930     "var x = " "(" array ")[" n "];" *newline*
1931     "if (x === undefined) throw 'Out of range';" *newline*
1932     "return x;" *newline*))
1933
1934 (define-builtin aset (array n value)
1935   (js!selfcall
1936     "var x = " array ";" *newline*
1937     "var i = " n ";" *newline*
1938     "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
1939     "return x[i] = " value ";" *newline*))
1940
1941 (define-builtin get-unix-time ()
1942   (concat "(Math.round(new Date() / 1000))"))
1943
1944 (define-builtin values-array (array)
1945   (concat "values.apply(this, " array ")"))
1946
1947 (define-raw-builtin values (&rest args)
1948   (concat "values(" (join (mapcar #'ls-compile args) ", ") ")"))
1949
1950
1951 (defun macro (x)
1952   (and (symbolp x)
1953        (let ((b (lookup-in-lexenv x *environment* 'function)))
1954          (and (eq (binding-type b) 'macro)
1955               b))))
1956
1957 (defun ls-macroexpand-1 (form)
1958   (let ((macro-binding (macro (car form))))
1959     (if macro-binding
1960         (let ((expander (binding-value macro-binding)))
1961           (when (listp expander)
1962             (let ((compiled (eval expander)))
1963               ;; The list representation are useful while
1964               ;; bootstrapping, as we can dump the definition of the
1965               ;; macros easily, but they are slow because we have to
1966               ;; evaluate them and compile them now and again. So, let
1967               ;; us replace the list representation version of the
1968               ;; function with the compiled one.
1969               ;;
1970               #+ecmalisp (set-binding-value macro-binding compiled)
1971               (setq expander compiled)))
1972           (apply expander (cdr form)))
1973         form)))
1974
1975 (defun compile-funcall (function args)
1976   (let ((values-funcs (if *multiple-value-p* "values" "pv")))
1977     (if (and (symbolp function)
1978              (claimp function 'function 'non-overridable))
1979         (concat (ls-compile `',function) ".fvalue("
1980                 (join (cons values-funcs (mapcar #'ls-compile args))
1981                       ", ")
1982                 ")")
1983         (concat (ls-compile `#',function) "("
1984                 (join (cons values-funcs (mapcar #'ls-compile args))
1985                       ", ")
1986                 ")"))))
1987
1988 (defun ls-compile-block (sexps &optional return-last-p)
1989   (if return-last-p
1990       (concat (ls-compile-block (butlast sexps))
1991               "return " (ls-compile (car (last sexps))) ";")
1992       (join-trailing
1993        (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
1994        (concat ";" *newline*))))
1995
1996 (defun ls-compile (sexp &optional multiple-value-p)
1997   (let ((*multiple-value-p* multiple-value-p))
1998     (cond
1999       ((symbolp sexp)
2000        (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
2001          (cond
2002            ((and b (not (member 'special (binding-declarations b))))
2003             (binding-value b))
2004            ((or (keywordp sexp)
2005                 (member 'constant (binding-declarations b)))
2006             (concat (ls-compile `',sexp) ".value"))
2007            (t
2008             (ls-compile `(symbol-value ',sexp))))))
2009       ((integerp sexp) (integer-to-string sexp))
2010       ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
2011       ((arrayp sexp) (literal sexp))
2012       ((listp sexp)
2013        (let ((name (car sexp))
2014              (args (cdr sexp)))
2015          (cond
2016            ;; Special forms
2017            ((assoc name *compilations*)
2018             (let ((comp (second (assoc name *compilations*))))
2019               (apply comp args)))
2020            ;; Built-in functions
2021            ((and (assoc name *builtins*)
2022                  (not (claimp name 'function 'notinline)))
2023             (let ((comp (second (assoc name *builtins*))))
2024               (apply comp args)))
2025            (t
2026             (if (macro name)
2027                 (ls-compile (ls-macroexpand-1 sexp))
2028                 (compile-funcall name args))))))
2029       (t
2030        (error "How should I compile this?")))))
2031
2032 (defun ls-compile-toplevel (sexp)
2033   (let ((*toplevel-compilations* nil))
2034     (cond
2035       ((and (consp sexp) (eq (car sexp) 'progn))
2036        (let ((subs (mapcar #'ls-compile-toplevel (cdr sexp))))
2037          (join (remove-if #'null-or-empty-p subs))))
2038       (t
2039        (let ((code (ls-compile sexp)))
2040          (concat (join-trailing (get-toplevel-compilations)
2041                                 (concat ";" *newline*))
2042                  (if code
2043                      (concat code ";" *newline*)
2044                      "")))))))
2045
2046
2047 ;;; Once we have the compiler, we define the runtime environment and
2048 ;;; interactive development (eval), which works calling the compiler
2049 ;;; and evaluating the Javascript result globally.
2050
2051 #+ecmalisp
2052 (progn
2053   (defmacro with-compilation-unit (&body body)
2054     `(prog1
2055          (progn
2056            (setq *compilation-unit-checks* nil)
2057            ,@body)
2058        (dolist (check *compilation-unit-checks*)
2059          (funcall check))))
2060
2061   (defun eval (x)
2062     (let ((code
2063            (with-compilation-unit
2064                (ls-compile-toplevel x))))
2065       (js-eval code)))
2066
2067   (export '(&rest &optional &body * *gensym-counter* *package* + - / 1+ 1- < <= =
2068             = > >= and append apply aref arrayp aset assoc atom block boundp
2069             boundp butlast caar cadddr caddr cadr car car case catch cdar cdddr
2070             cddr cdr cdr char char-code char= code-char cond cons consp copy-list
2071             decf declaim defparameter defun defmacro defvar digit-char-p disassemble
2072             documentation dolist dotimes ecase eq eql equal error eval every
2073             export fdefinition find-package find-symbol first fourth fset funcall
2074             function functionp gensym get-universal-time go identity if in-package
2075             incf integerp integerp intern keywordp lambda last length let let*
2076             list-all-packages list listp make-array make-package make-symbol
2077             mapcar member minusp mod multiple-value-call  nil not nth nthcdr null
2078             numberp or package-name package-use-list packagep plusp prin1-to-string
2079             print proclaim prog1 prog2 progn psetq push quote remove remove-if
2080             remove-if-not return return-from revappend reverse second set setq
2081             some string-upcase string string= stringp subseq symbol-function
2082             symbol-name symbol-package symbol-plist symbol-value symbolp t tagbody
2083             third throw truncate unless unwind-protect values values-list variable
2084             warn when write-line write-string zerop))
2085
2086   (setq *package* *user-package*)
2087
2088   (js-eval "var lisp")
2089   (js-vset "lisp" (new))
2090   (js-vset "lisp.read" #'ls-read-from-string)
2091   (js-vset "lisp.print" #'prin1-to-string)
2092   (js-vset "lisp.eval" #'eval)
2093   (js-vset "lisp.compile" #'ls-compile-toplevel)
2094   (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
2095   (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str))))
2096
2097   ;; Set the initial global environment to be equal to the host global
2098   ;; environment at this point of the compilation.
2099   (eval-when-compile
2100     (toplevel-compilation
2101      (ls-compile
2102       `(progn
2103          ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
2104                    *literal-symbols*)
2105          (setq *literal-symbols* ',*literal-symbols*)
2106          (setq *environment* ',*environment*)
2107          (setq *variable-counter* ,*variable-counter*)
2108          (setq *gensym-counter* ,*gensym-counter*)
2109          (setq *block-counter* ,*block-counter*)))))
2110
2111   (eval-when-compile
2112     (toplevel-compilation
2113      (ls-compile
2114       `(setq *literal-counter* ,*literal-counter*)))))
2115
2116
2117 ;;; Finally, we provide a couple of functions to easily bootstrap
2118 ;;; this. It just calls the compiler with this file as input.
2119
2120 #+common-lisp
2121 (progn
2122   (defun read-whole-file (filename)
2123     (with-open-file (in filename)
2124       (let ((seq (make-array (file-length in) :element-type 'character)))
2125         (read-sequence seq in)
2126         seq)))
2127
2128   (defun ls-compile-file (filename output)
2129     (setq *compilation-unit-checks* nil)
2130     (with-open-file (out output :direction :output :if-exists :supersede)
2131       (let* ((source (read-whole-file filename))
2132              (in (make-string-stream source)))
2133         (loop
2134            for x = (ls-read in)
2135            until (eq x *eof*)
2136            for compilation = (ls-compile-toplevel x)
2137            when (plusp (length compilation))
2138            do (write-string compilation out))
2139         (dolist (check *compilation-unit-checks*)
2140           (funcall check))
2141         (setq *compilation-unit-checks* nil))))
2142
2143   (defun bootstrap ()
2144     (setq *environment* (make-lexenv))
2145     (setq *literal-symbols* nil)
2146     (setq *variable-counter* 0
2147           *gensym-counter* 0
2148           *literal-counter* 0
2149           *block-counter* 0)
2150     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))