Fix `unknown variable' and `unknown function' error signaling
[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 #+ecmalisp
25 (progn
26   (eval-when-compile
27     (%compile-defmacro 'defmacro
28                        '(lambda (name args &rest body)
29                          `(eval-when-compile
30                             (%compile-defmacro ',name
31                                                '(lambda ,(mapcar (lambda (x)
32                                                                    (if (eq x '&body)
33                                                                        '&rest
34                                                                        x))
35                                                                  args)
36                                                  ,@body))))))
37
38   (defmacro %defvar (name value)
39     `(progn
40        (eval-when-compile
41          (%compile-defvar ',name))
42        (setq ,name ,value)))
43
44   (defmacro defvar (name &optional value)
45     `(%defvar ,name ,value))
46
47   (defmacro named-lambda (name args &rest body)
48     (let ((x (gensym "FN")))
49       `(let ((,x (lambda ,args ,@body)))
50          (set ,x "fname" ,name)
51          ,x)))
52
53   (defmacro %defun (name args &rest body)
54     `(progn
55        (eval-when-compile
56          (%compile-defun ',name))
57        (fsetq ,name (named-lambda ,(symbol-name name) ,args
58                       (block ,name ,@body)))))
59
60   (defmacro defun (name args &rest body)
61     `(%defun ,name ,args ,@body))
62
63   (defvar *package* (new))
64
65   (defvar nil (make-symbol "NIL"))
66   (set *package* "NIL" nil)
67
68   (defvar t (make-symbol "T"))
69   (set *package* "T" t)
70
71   (defun null (x)
72     (eq x nil))
73
74   (defmacro return (&optional value)
75     `(return-from nil ,value))
76
77   (defmacro while (condition &body body)
78     `(block nil (%while ,condition ,@body)))
79
80   (defun internp (name)
81     (in name *package*))
82
83   (defun intern (name)
84     (if (internp name)
85         (get *package* name)
86         (set *package* name (make-symbol name))))
87
88   (defun find-symbol (name)
89     (get *package* name))
90
91   (defvar *gensym-counter* 0)
92   (defun gensym (&optional (prefix "G"))
93     (setq *gensym-counter* (+ *gensym-counter* 1))
94     (make-symbol (concat-two prefix (integer-to-string *gensym-counter*))))
95
96   ;; Basic functions
97   (defun = (x y) (= x y))
98   (defun + (x y) (+ x y))
99   (defun - (x y) (- x y))
100   (defun * (x y) (* x y))
101   (defun / (x y) (/ x y))
102   (defun 1+ (x) (+ x 1))
103   (defun 1- (x) (- x 1))
104   (defun zerop (x) (= x 0))
105   (defun truncate (x y) (floor (/ x y)))
106
107   (defun eql (x y) (eq x y))
108
109   (defun not (x) (if x nil t))
110
111   (defun cons (x y ) (cons x y))
112   (defun consp (x) (consp x))
113   (defun car (x) (car x))
114   (defun cdr (x) (cdr x))
115   (defun caar (x) (car (car x)))
116   (defun cadr (x) (car (cdr x)))
117   (defun cdar (x) (cdr (car x)))
118   (defun cddr (x) (cdr (cdr x)))
119   (defun caddr (x) (car (cdr (cdr x))))
120   (defun cdddr (x) (cdr (cdr (cdr x))))
121   (defun cadddr (x) (car (cdr (cdr (cdr x)))))
122   (defun first (x) (car x))
123   (defun second (x) (cadr x))
124   (defun third (x) (caddr x))
125   (defun fourth (x) (cadddr x))
126
127   (defun list (&rest args) args)
128   (defun atom (x)
129     (not (consp x)))
130
131   ;; Basic macros
132
133   (defmacro incf (x &optional (delta 1))
134     `(setq ,x (+ ,x ,delta)))
135
136   (defmacro decf (x &optional (delta 1))
137     `(setq ,x (- ,x ,delta)))
138
139   (defmacro push (x place)
140     `(setq ,place (cons ,x ,place)))
141
142   (defmacro when (condition &body body)
143     `(if ,condition (progn ,@body) nil))
144
145   (defmacro unless (condition &body body)
146     `(if ,condition nil (progn ,@body)))
147
148   (defmacro dolist (iter &body body)
149     (let ((var (first iter))
150           (g!list (gensym)))
151       `(block nil
152          (let ((,g!list ,(second iter))
153                (,var nil))
154            (%while ,g!list
155                    (setq ,var (car ,g!list))
156                    (tagbody ,@body)
157                    (setq ,g!list (cdr ,g!list)))
158            ,(third iter)))))
159
160   (defmacro dotimes (iter &body body)
161     (let ((g!to (gensym))
162           (var (first iter))
163           (to (second iter))
164           (result (third iter)))
165       `(block nil
166          (let ((,var 0)
167                (,g!to ,to))
168            (%while (< ,var ,g!to)
169                    (tagbody ,@body)
170                    (incf ,var))
171            ,result))))
172
173   (defmacro cond (&rest clausules)
174     (if (null clausules)
175         nil
176         (if (eq (caar clausules) t)
177             `(progn ,@(cdar clausules))
178             `(if ,(caar clausules)
179                  (progn ,@(cdar clausules))
180                  (cond ,@(cdr clausules))))))
181
182   (defmacro case (form &rest clausules)
183     (let ((!form (gensym)))
184       `(let ((,!form ,form))
185          (cond
186            ,@(mapcar (lambda (clausule)
187                        (if (eq (car clausule) t)
188                            clausule
189                            `((eql ,!form ',(car clausule))
190                              ,@(cdr clausule))))
191                      clausules)))))
192
193   (defmacro ecase (form &rest clausules)
194     `(case ,form
195        ,@(append
196           clausules
197           `((t
198              (error "ECASE expression failed."))))))
199
200   (defmacro and (&rest forms)
201     (cond
202       ((null forms)
203        t)
204       ((null (cdr forms))
205        (car forms))
206       (t
207        `(if ,(car forms)
208             (and ,@(cdr forms))
209             nil))))
210
211   (defmacro or (&rest forms)
212     (cond
213       ((null forms)
214        nil)
215       ((null (cdr forms))
216        (car forms))
217       (t
218        (let ((g (gensym)))
219          `(let ((,g ,(car forms)))
220             (if ,g ,g (or ,@(cdr forms))))))))
221
222   (defmacro prog1 (form &body body)
223     (let ((value (gensym)))
224       `(let ((,value ,form))
225          ,@body
226          ,value))))
227
228 ;;; This couple of helper functions will be defined in both Common
229 ;;; Lisp and in Ecmalisp.
230 (defun ensure-list (x)
231   (if (listp x)
232       x
233       (list x)))
234
235 (defun !reduce (func list initial)
236   (if (null list)
237       initial
238       (!reduce func
239                (cdr list)
240                (funcall func initial (car list)))))
241
242 ;;; Go on growing the Lisp language in Ecmalisp, with more high
243 ;;; level utilities as well as correct versions of other
244 ;;; constructions.
245 #+ecmalisp
246 (progn
247   (defmacro defun (name args &body body)
248     `(progn
249        (%defun ,name ,args ,@body)
250        ',name))
251
252   (defmacro defvar (name &optional value)
253     `(progn
254        (%defvar ,name ,value)
255        ',name))
256
257   (defun append-two (list1 list2)
258     (if (null list1)
259         list2
260         (cons (car list1)
261               (append (cdr list1) list2))))
262
263   (defun append (&rest lists)
264     (!reduce #'append-two lists '()))
265
266   (defun reverse-aux (list acc)
267     (if (null list)
268         acc
269         (reverse-aux (cdr list) (cons (car list) acc))))
270
271   (defun reverse (list)
272     (reverse-aux list '()))
273
274   (defun list-length (list)
275     (let ((l 0))
276       (while (not (null list))
277         (incf l)
278         (setq list (cdr list)))
279       l))
280
281   (defun length (seq)
282     (if (stringp seq)
283         (string-length seq)
284         (list-length seq)))
285
286   (defun concat-two (s1 s2)
287     (concat-two s1 s2))
288
289   (defun mapcar (func list)
290     (if (null list)
291         '()
292         (cons (funcall func (car list))
293               (mapcar func (cdr list)))))
294
295   (defun identity (x) x)
296
297   (defun copy-list (x)
298     (mapcar #'identity x))
299
300   (defun code-char (x) x)
301   (defun char-code (x) x)
302   (defun char= (x y) (= x y))
303
304   (defun integerp (x)
305     (and (numberp x) (= (floor x) x)))
306
307   (defun plusp (x) (< 0 x))
308   (defun minusp (x) (< x 0))
309
310   (defun listp (x)
311     (or (consp x) (null x)))
312
313   (defun nth (n list)
314     (cond
315       ((null list) list)
316       ((zerop n) (car list))
317       (t (nth (1- n) (cdr list)))))
318
319   (defun last (x)
320     (if (consp (cdr x))
321         (last (cdr x))
322         x))
323
324   (defun butlast (x)
325     (and (consp (cdr x))
326          (cons (car x) (butlast (cdr x)))))
327
328   (defun member (x list)
329     (cond
330       ((null list)
331        nil)
332       ((eql x (car list))
333        list)
334       (t
335        (member x (cdr list)))))
336
337   (defun remove (x list)
338     (cond
339       ((null list)
340        nil)
341       ((eql x (car list))
342        (remove x (cdr list)))
343       (t
344        (cons (car list) (remove x (cdr list))))))
345
346   (defun remove-if (func list)
347     (cond
348       ((null list)
349        nil)
350       ((funcall func (car list))
351        (remove-if func (cdr list)))
352       (t
353        (cons (car list) (remove-if func (cdr list))))))
354
355   (defun remove-if-not (func list)
356     (cond
357       ((null list)
358        nil)
359       ((funcall func (car list))
360        (cons (car list) (remove-if-not func (cdr list))))
361       (t
362        (remove-if-not func (cdr list)))))
363
364   (defun digit-char-p (x)
365     (if (and (<= #\0 x) (<= x #\9))
366         (- x #\0)
367         nil))
368
369   (defun subseq (seq a &optional b)
370     (cond
371       ((stringp seq)
372        (if b
373            (slice seq a b)
374            (slice seq a)))
375       (t
376        (error "Unsupported argument."))))
377
378   (defun parse-integer (string)
379     (let ((value 0)
380           (index 0)
381           (size (length string)))
382       (while (< index size)
383         (setq value (+ (* value 10) (digit-char-p (char string index))))
384         (incf index))
385       value))
386
387   (defun some (function seq)
388     (cond
389       ((stringp seq)
390        (let ((index 0)
391              (size (length seq)))
392          (while (< index size)
393            (when (funcall function (char seq index))
394              (return-from some t))
395            (incf index))
396          nil))
397       ((listp seq)
398        (dolist (x seq nil)
399          (when (funcall function x)
400            (return t))))
401       (t
402        (error "Unknown sequence."))))
403
404   (defun every (function seq)
405     (cond
406       ((stringp seq)
407        (let ((index 0)
408              (size (length seq)))
409          (while (< index size)
410            (unless (funcall function (char seq index))
411              (return-from every nil))
412            (incf index))
413          t))
414       ((listp seq)
415        (dolist (x seq t)
416          (unless (funcall function x)
417            (return))))
418       (t
419        (error "Unknown sequence."))))
420
421   (defun assoc (x alist)
422     (while alist
423       (if (eql x (caar alist))
424           (return)
425           (setq alist (cdr alist))))
426     (car alist))
427
428   (defun string= (s1 s2)
429     (equal s1 s2)))
430
431
432 ;;; The compiler offers some primitives and special forms which are
433 ;;; not found in Common Lisp, for instance, while. So, we grow Common
434 ;;; Lisp a bit to it can execute the rest of the file.
435 #+common-lisp
436 (progn
437   (defmacro while (condition &body body)
438     `(do ()
439          ((not ,condition))
440        ,@body))
441
442   (defmacro eval-when-compile (&body body)
443     `(eval-when (:compile-toplevel :load-toplevel :execute)
444        ,@body))
445
446   (defun concat-two (s1 s2)
447     (concatenate 'string s1 s2))
448
449   (defun setcar (cons new)
450     (setf (car cons) new))
451   (defun setcdr (cons new)
452     (setf (cdr cons) new)))
453
454 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
455 ;;; from here, this code will compile on both. We define some helper
456 ;;; functions now for string manipulation and so on. They will be
457 ;;; useful in the compiler, mostly.
458
459 (defvar *newline* (string (code-char 10)))
460
461 (defun concat (&rest strs)
462   (!reduce #'concat-two strs ""))
463
464 (defmacro concatf (variable &body form)
465   `(setq ,variable (concat ,variable (progn ,@form))))
466
467 ;;; Concatenate a list of strings, with a separator
468 (defun join (list &optional (separator ""))
469   (cond
470     ((null list)
471      "")
472     ((null (cdr list))
473      (car list))
474     (t
475      (concat (car list)
476              separator
477              (join (cdr list) separator)))))
478
479 (defun join-trailing (list &optional (separator ""))
480   (if (null list)
481       ""
482       (concat (car list) separator (join-trailing (cdr list) separator))))
483
484 ;;; Like CONCAT, but prefix each line with four spaces.
485 (defun indent (&rest string)
486   (let ((input (join string)))
487     (let ((output "")
488           (index 0)
489           (size (length input)))
490       (when (plusp size)
491         (setq output "    "))
492       (while (< index size)
493         (setq output
494               (concat output
495                       (if (and (char= (char input index) #\newline)
496                                (< index (1- size))
497                                (not (char= (char input (1+ index)) #\newline)))
498                           (concat (string #\newline) "    ")
499                           (subseq input index (1+ index)))))
500         (incf index))
501       output)))
502
503 (defun integer-to-string (x)
504   (cond
505     ((zerop x)
506      "0")
507     ((minusp x)
508      (concat "-" (integer-to-string (- 0 x))))
509     (t
510      (let ((digits nil))
511        (while (not (zerop x))
512          (push (mod x 10) digits)
513          (setq x (truncate x 10)))
514        (join (mapcar (lambda (d) (string (char "0123456789" d)))
515                      digits))))))
516
517
518 ;;; Wrap X with a Javascript code to convert the result from
519 ;;; Javascript generalized booleans to T or NIL.
520 (defun js!bool (x)
521   (concat "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
522
523 ;;; Concatenate the arguments and wrap them with a self-calling
524 ;;; Javascript anonymous function. It is used to make some Javascript
525 ;;; statements valid expressions and provide a private scope as well.
526 ;;; It could be defined as function, but we could do some
527 ;;; preprocessing in the future.
528 (defmacro js!selfcall (&body body)
529   `(concat "(function(){" *newline* (indent ,@body) "})()"))
530
531
532 ;;; Printer
533
534 #+ecmalisp
535 (progn
536   (defun prin1-to-string (form)
537     (cond
538       ((symbolp form) (symbol-name form))
539       ((integerp form) (integer-to-string form))
540       ((stringp form) (concat "\"" (escape-string form) "\""))
541       ((functionp form)
542        (let ((name (get form "fname")))
543          (if name
544              (concat "#<FUNCTION " name ">")
545              (concat "#<FUNCTION>"))))
546       ((listp form)
547        (concat "("
548                (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
549                (let ((last (last form)))
550                  (if (null (cdr last))
551                      (prin1-to-string (car last))
552                      (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
553                ")"))))
554
555   (defun write-line (x)
556     (write-string x)
557     (write-string *newline*)
558     x)
559
560   (defun print (x)
561     (write-line (prin1-to-string x))
562     x))
563
564
565 ;;;; Reader
566
567 ;;; The Lisp reader, parse strings and return Lisp objects. The main
568 ;;; entry points are `ls-read' and `ls-read-from-string'.
569
570 (defun make-string-stream (string)
571   (cons string 0))
572
573 (defun %peek-char (stream)
574   (and (< (cdr stream) (length (car stream)))
575        (char (car stream) (cdr stream))))
576
577 (defun %read-char (stream)
578   (and (< (cdr stream) (length (car stream)))
579        (prog1 (char (car stream) (cdr stream))
580          (setcdr stream (1+ (cdr stream))))))
581
582 (defun whitespacep (ch)
583   (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
584
585 (defun skip-whitespaces (stream)
586   (let (ch)
587     (setq ch (%peek-char stream))
588     (while (and ch (whitespacep ch))
589       (%read-char stream)
590       (setq ch (%peek-char stream)))))
591
592 (defun terminalp (ch)
593   (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
594
595 (defun read-until (stream func)
596   (let ((string "")
597         (ch))
598     (setq ch (%peek-char stream))
599     (while (and ch (not (funcall func ch)))
600       (setq string (concat string (string ch)))
601       (%read-char stream)
602       (setq ch (%peek-char stream)))
603     string))
604
605 (defun skip-whitespaces-and-comments (stream)
606   (let (ch)
607     (skip-whitespaces stream)
608     (setq ch (%peek-char stream))
609     (while (and ch (char= ch #\;))
610       (read-until stream (lambda (x) (char= x #\newline)))
611       (skip-whitespaces stream)
612       (setq ch (%peek-char stream)))))
613
614 (defun %read-list (stream)
615   (skip-whitespaces-and-comments stream)
616   (let ((ch (%peek-char stream)))
617     (cond
618       ((null ch)
619        (error "Unspected EOF"))
620       ((char= ch #\))
621        (%read-char stream)
622        nil)
623       ((char= ch #\.)
624        (%read-char stream)
625        (prog1 (ls-read stream)
626          (skip-whitespaces-and-comments stream)
627          (unless (char= (%read-char stream) #\))
628            (error "')' was expected."))))
629       (t
630        (cons (ls-read stream) (%read-list stream))))))
631
632 (defun read-string (stream)
633   (let ((string "")
634         (ch nil))
635     (setq ch (%read-char stream))
636     (while (not (eql ch #\"))
637       (when (null ch)
638         (error "Unexpected EOF"))
639       (when (eql ch #\\)
640         (setq ch (%read-char stream)))
641       (setq string (concat string (string ch)))
642       (setq ch (%read-char stream)))
643     string))
644
645 (defun read-sharp (stream)
646   (%read-char stream)
647   (ecase (%read-char stream)
648     (#\'
649      (list 'function (ls-read stream)))
650     (#\\
651      (let ((cname
652             (concat (string (%read-char stream))
653                     (read-until stream #'terminalp))))
654        (cond
655          ((string= cname "space") (char-code #\space))
656          ((string= cname "tab") (char-code #\tab))
657          ((string= cname "newline") (char-code #\newline))
658          (t (char-code (char cname 0))))))
659     (#\+
660      (let ((feature (read-until stream #'terminalp)))
661        (cond
662          ((string= feature "common-lisp")
663           (ls-read stream)              ;ignore
664           (ls-read stream))
665          ((string= feature "ecmalisp")
666           (ls-read stream))
667          (t
668           (error "Unknown reader form.")))))))
669
670 (defvar *eof* (make-symbol "EOF"))
671 (defun ls-read (stream)
672   (skip-whitespaces-and-comments stream)
673   (let ((ch (%peek-char stream)))
674     (cond
675       ((null ch)
676        *eof*)
677       ((char= ch #\()
678        (%read-char stream)
679        (%read-list stream))
680       ((char= ch #\')
681        (%read-char stream)
682        (list 'quote (ls-read stream)))
683       ((char= ch #\`)
684        (%read-char stream)
685        (list 'backquote (ls-read stream)))
686       ((char= ch #\")
687        (%read-char stream)
688        (read-string stream))
689       ((char= ch #\,)
690        (%read-char stream)
691        (if (eql (%peek-char stream) #\@)
692            (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
693            (list 'unquote (ls-read stream))))
694       ((char= ch #\#)
695        (read-sharp stream))
696       (t
697        (let ((string (read-until stream #'terminalp)))
698          (if (every #'digit-char-p string)
699              (parse-integer string)
700              (intern (string-upcase string))))))))
701
702 (defun ls-read-from-string (string)
703   (ls-read (make-string-stream string)))
704
705
706 ;;;; Compiler
707
708 ;;; Translate the Lisp code to Javascript. It will compile the special
709 ;;; forms. Some primitive functions are compiled as special forms
710 ;;; too. The respective real functions are defined in the target (see
711 ;;; the beginning of this file) as well as some primitive functions.
712
713 (defvar *compilation-unit-checks* '())
714
715 (defun make-binding (name type translation declared)
716   (list name type translation declared))
717
718 (defun binding-name (b) (first b))
719 (defun binding-type (b) (second b))
720 (defun binding-translation (b) (third b))
721 (defun binding-declared (b)
722   (and b (fourth b)))
723 (defun mark-binding-as-declared (b)
724   (setcar (cdddr b) t))
725
726 (defun make-lexenv ()
727   (list nil nil nil nil))
728
729 (defun copy-lexenv (lexenv)
730   (copy-list lexenv))
731
732 (defun push-to-lexenv (binding lexenv namespace)
733   (ecase namespace
734     (variable
735      (setcar lexenv (cons binding (car lexenv))))
736     (function
737      (setcar (cdr lexenv) (cons binding (cadr lexenv))))
738     (block
739      (setcar (cddr lexenv) (cons binding (caddr lexenv))))
740     (gotag
741      (setcar (cdddr lexenv) (cons binding (cadddr lexenv))))))
742
743 (defun extend-lexenv (bindings lexenv namespace)
744   (let ((env (copy-lexenv lexenv)))
745     (dolist (binding (reverse bindings) env)
746       (push-to-lexenv binding env namespace))))
747
748 (defun lookup-in-lexenv (name lexenv namespace)
749   (assoc name (ecase namespace
750                 (variable (first lexenv))
751                 (function (second lexenv))
752                 (block (third lexenv))
753                 (gotag (fourth lexenv)))))
754
755 (defvar *environment* (make-lexenv))
756
757 (defun clear-undeclared-global-bindings ()
758   (setq *environment*
759         (mapcar (lambda (namespace)
760                   (remove-if-not #'binding-declared namespace))
761                 *environment*)))
762
763
764 (defvar *variable-counter* 0)
765 (defun gvarname (symbol)
766   (concat "v" (integer-to-string (incf *variable-counter*))))
767
768 (defun lookup-variable (symbol env)
769   (or (lookup-in-lexenv symbol env 'variable)
770       (lookup-in-lexenv symbol *environment* 'variable)
771       (let ((name (symbol-name symbol))
772             (binding (make-binding symbol 'variable (gvarname symbol) nil)))
773         (push-to-lexenv binding *environment* 'variable)
774         (push (lambda ()
775                 (let ((b (lookup-in-lexenv symbol *environment* 'variable)))
776                   (unless (binding-declared b)
777                       (error (concat "Undefined variable `" name "'")))))
778               *compilation-unit-checks*)
779         binding)))
780
781 (defun lookup-variable-translation (symbol env)
782   (binding-translation (lookup-variable symbol env)))
783
784 (defun extend-local-env (args env)
785   (let ((new (copy-lexenv env)))
786     (dolist (symbol args new)
787       (let ((b (make-binding symbol 'variable (gvarname symbol) t)))
788         (push-to-lexenv b new 'variable)))))
789
790 (defvar *function-counter* 0)
791 (defun lookup-function (symbol env)
792   (or (lookup-in-lexenv symbol env 'function)
793       (lookup-in-lexenv symbol *environment* 'function)
794       (let ((name (symbol-name symbol))
795             (binding
796              (make-binding symbol
797                            'function
798                            (concat "f" (integer-to-string (incf *function-counter*)))
799                            nil)))
800         (push-to-lexenv binding *environment* 'function)
801         (push (lambda ()
802                 (let ((b (lookup-in-lexenv symbol *environment* 'function)))
803                   (unless (binding-declared b)
804                     (error (concat "Undefined function `" name "'")))))
805               *compilation-unit-checks*)
806         binding)))
807
808 (defun lookup-function-translation (symbol env)
809   (binding-translation (lookup-function symbol env)))
810
811 (defvar *toplevel-compilations* nil)
812
813 (defun %compile-defvar (name)
814   (let ((b (lookup-variable name *environment*)))
815     (mark-binding-as-declared b)
816     (push (concat "var " (binding-translation b)) *toplevel-compilations*)))
817
818 (defun %compile-defun (name)
819   (let ((b (lookup-function name *environment*)))
820     (mark-binding-as-declared b)
821     (push (concat "var " (binding-translation b)) *toplevel-compilations*)))
822
823 (defun %compile-defmacro (name lambda)
824   (push-to-lexenv (make-binding name 'macro lambda t) *environment* 'function))
825
826 (defvar *compilations* nil)
827
828 (defun ls-compile-block (sexps env)
829   (join-trailing
830    (remove-if (lambda (x)
831                 (or (null x)
832                     (and (stringp x)
833                          (zerop (length x)))))
834               (mapcar (lambda (x) (ls-compile x env))  sexps))
835    (concat ";" *newline*)))
836
837 (defmacro define-compilation (name args &body body)
838   ;; Creates a new primitive `name' with parameters args and
839   ;; @body. The body can access to the local environment through the
840   ;; variable ENV.
841   `(push (list ',name (lambda (env ,@args) (block ,name ,@body)))
842          *compilations*))
843
844 (define-compilation if (condition true false)
845   (concat "("
846           (ls-compile condition env) " !== " (ls-compile nil)
847           " ? "
848           (ls-compile true env)
849           " : "
850           (ls-compile false env)
851           ")"))
852
853
854 (defvar *lambda-list-keywords* '(&optional &rest))
855
856 (defun list-until-keyword (list)
857   (if (or (null list) (member (car list) *lambda-list-keywords*))
858       nil
859       (cons (car list) (list-until-keyword (cdr list)))))
860
861 (defun lambda-list-required-arguments (lambda-list)
862   (list-until-keyword lambda-list))
863
864 (defun lambda-list-optional-arguments-with-default (lambda-list)
865   (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
866
867 (defun lambda-list-optional-arguments (lambda-list)
868   (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
869
870 (defun lambda-list-rest-argument (lambda-list)
871   (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
872     (when (cdr rest)
873       (error "Bad lambda-list"))
874     (car rest)))
875
876 (define-compilation lambda (lambda-list &rest body)
877   (let ((required-arguments (lambda-list-required-arguments lambda-list))
878         (optional-arguments (lambda-list-optional-arguments lambda-list))
879         (rest-argument (lambda-list-rest-argument lambda-list)))
880     (let ((n-required-arguments (length required-arguments))
881           (n-optional-arguments (length optional-arguments))
882           (new-env (extend-local-env
883                     (append (ensure-list rest-argument)
884                             required-arguments
885                             optional-arguments)
886                     env)))
887       (concat "(function ("
888               (join (mapcar (lambda (x)
889                               (lookup-variable-translation x new-env))
890                             (append required-arguments optional-arguments))
891                     ",")
892               "){" *newline*
893               ;; Check number of arguments
894               (indent
895                (if required-arguments
896                    (concat "if (arguments.length < " (integer-to-string n-required-arguments)
897                            ") throw 'too few arguments';" *newline*)
898                    "")
899                (if (not rest-argument)
900                    (concat "if (arguments.length > "
901                            (integer-to-string (+ n-required-arguments n-optional-arguments))
902                            ") throw 'too many arguments';" *newline*)
903                    "")
904                ;; Optional arguments
905                (if optional-arguments
906                    (concat "switch(arguments.length){" *newline*
907                            (let ((optional-and-defaults
908                                   (lambda-list-optional-arguments-with-default lambda-list))
909                                  (cases nil)
910                                  (idx 0))
911                              (progn
912                                (while (< idx n-optional-arguments)
913                                  (let ((arg (nth idx optional-and-defaults)))
914                                    (push (concat "case "
915                                                  (integer-to-string (+ idx n-required-arguments)) ":" *newline*
916                                                  (lookup-variable-translation (car arg) new-env)
917                                                  "="
918                                                  (ls-compile (cadr arg) new-env)
919                                                  ";" *newline*)
920                                          cases)
921                                    (incf idx)))
922                                     (push (concat "default: break;" *newline*) cases)
923                                     (join (reverse cases))))
924                            "}" *newline*)
925                    "")
926                ;; &rest/&body argument
927                (if rest-argument
928                    (let ((js!rest (lookup-variable-translation rest-argument new-env)))
929                      (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
930                              "for (var i = arguments.length-1; i>="
931                              (integer-to-string (+ n-required-arguments n-optional-arguments))
932                              "; i--)" *newline*
933                              (indent js!rest " = "
934                                      "{car: arguments[i], cdr: ") js!rest "};"
935                                      *newline*))
936                    "")
937                ;; Body
938                (concat (ls-compile-block (butlast body) new-env)
939                        "return " (ls-compile (car (last body)) new-env) ";")) *newline*
940               "})"))))
941
942 (define-compilation fsetq (var val)
943   (concat (lookup-function-translation var env)
944           " = "
945           (ls-compile val env)))
946
947 (define-compilation setq (var val)
948   (concat (lookup-variable-translation var env)
949           " = "
950            (ls-compile val env)))
951
952 ;;; Literals
953 (defun escape-string (string)
954   (let ((output "")
955         (index 0)
956         (size (length string)))
957     (while (< index size)
958       (let ((ch (char string index)))
959         (when (or (char= ch #\") (char= ch #\\))
960           (setq output (concat output "\\")))
961         (when (or (char= ch #\newline))
962           (setq output (concat output "\\"))
963           (setq ch #\n))
964         (setq output (concat output (string ch))))
965       (incf index))
966     output))
967
968 (defun literal->js (sexp)
969   (cond
970     ((integerp sexp) (integer-to-string sexp))
971     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
972     ((symbolp sexp) (ls-compile `(intern ,(escape-string (symbol-name sexp))) *environment*))
973     ((consp sexp) (concat "{car: "
974                           (literal->js (car sexp))
975                           ", cdr: "
976                           (literal->js (cdr sexp)) "}"))))
977
978 (defvar *literal-counter* 0)
979 (defun literal (form)
980   (let ((var (concat "l" (integer-to-string (incf *literal-counter*)))))
981     (push (concat "var " var " = " (literal->js form)) *toplevel-compilations*)
982     var))
983
984 (define-compilation quote (sexp)
985   (literal sexp))
986
987 (define-compilation %while (pred &rest body)
988   (js!selfcall
989     "while(" (ls-compile pred env) " !== " (ls-compile nil) "){" *newline*
990     (indent (ls-compile-block body env))
991     "}"
992     "return " (ls-compile nil) ";" *newline*))
993
994 (define-compilation function (x)
995   (cond
996     ((and (listp x) (eq (car x) 'lambda))
997      (ls-compile x env))
998     ((symbolp x)
999      (lookup-function-translation x env))))
1000
1001 (define-compilation eval-when-compile (&rest body)
1002   (eval (cons 'progn body))
1003   "")
1004
1005 (defmacro define-transformation (name args form)
1006   `(define-compilation ,name ,args
1007      (ls-compile ,form env)))
1008
1009 (define-compilation progn (&rest body)
1010   (js!selfcall
1011     (ls-compile-block (butlast body) env)
1012     "return " (ls-compile (car (last body)) env) ";" *newline*))
1013
1014 (define-compilation let (bindings &rest body)
1015   (let ((bindings (mapcar #'ensure-list bindings)))
1016     (let ((variables (mapcar #'first bindings))
1017           (values    (mapcar #'second bindings)))
1018       (let ((new-env (extend-local-env variables env)))
1019         (concat "(function("
1020                 (join (mapcar (lambda (x)
1021                                 (lookup-variable-translation x new-env))
1022                               variables)
1023                       ",")
1024                 "){" *newline*
1025                 (indent (ls-compile-block (butlast body) new-env)
1026                         "return " (ls-compile (car (last body)) new-env)
1027                         ";" *newline*)
1028                 "})(" (join (mapcar (lambda (x) (ls-compile x env))
1029                                     values)
1030                             ",")
1031                 ")")))))
1032
1033
1034 (defvar *block-counter* 0)
1035
1036 (define-compilation block (name &rest body)
1037   (let ((tr (integer-to-string (incf *block-counter*))))
1038     (let ((b (make-binding name 'block tr t)))
1039       (js!selfcall
1040         "try {" *newline*
1041         (indent "return " (ls-compile `(progn ,@body)
1042                                       (extend-lexenv (list b) env 'block))
1043                 ";" *newline*)
1044         "}" *newline*
1045         "catch (cf){" *newline*
1046         "    if (cf.type == 'block' && cf.id == " tr ")" *newline*
1047         "        return cf.value;" *newline*
1048         "    else" *newline*
1049         "        throw cf;" *newline*
1050         "}" *newline*))))
1051
1052 (define-compilation return-from (name &optional value)
1053   (let ((b (lookup-in-lexenv name env 'block)))
1054     (if b
1055         (js!selfcall
1056           "throw ({"
1057           "type: 'block', "
1058           "id: " (binding-translation b) ", "
1059           "value: " (ls-compile value env) ", "
1060           "message: 'Return from unknown block " (symbol-name name) ".'"
1061           "})")
1062         (error (concat "Unknown block `" (symbol-name name) "'.")))))
1063
1064
1065 (define-compilation catch (id &rest body)
1066   (js!selfcall
1067     "var id = " (ls-compile id env) ";" *newline*
1068     "try {" *newline*
1069     (indent "return " (ls-compile `(progn ,@body))
1070             ";" *newline*)
1071     "}" *newline*
1072     "catch (cf){" *newline*
1073     "    if (cf.type == 'catch' && cf.id == id)" *newline*
1074     "        return cf.value;" *newline*
1075     "    else" *newline*
1076     "        throw cf;" *newline*
1077     "}" *newline*))
1078
1079 (define-compilation throw (id &optional value)
1080   (js!selfcall
1081     "throw ({"
1082     "type: 'catch', "
1083     "id: " (ls-compile id env) ", "
1084     "value: " (ls-compile value env) ", "
1085     "message: 'Throw uncatched.'"
1086     "})"))
1087
1088
1089 (defvar *tagbody-counter* 0)
1090 (defvar *go-tag-counter* 0)
1091
1092 (defun go-tag-p (x)
1093   (or (integerp x) (symbolp x)))
1094
1095 (defun declare-tagbody-tags (env tbidx body)
1096   (let ((bindings
1097          (mapcar (lambda (label)
1098                    (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1099                      (make-binding label 'gotag (list tbidx tagidx) t)))
1100                  (remove-if-not #'go-tag-p body))))
1101     (extend-lexenv bindings env 'gotag)))
1102
1103 (define-compilation tagbody (&rest body)
1104   ;; Ignore the tagbody if it does not contain any go-tag. We do this
1105   ;; because 1) it is easy and 2) many built-in forms expand to a
1106   ;; implicit tagbody, so we save some space.
1107   (unless (some #'go-tag-p body)
1108     (return-from tagbody (ls-compile `(progn ,@body nil) env)))
1109   ;; The translation assumes the first form in BODY is a label
1110   (unless (go-tag-p (car body))
1111     (push (gensym "START") body))
1112   ;; Tagbody compilation
1113   (let ((tbidx (integer-to-string *tagbody-counter*)))
1114     (let ((env (declare-tagbody-tags env tbidx body))
1115           initag)
1116       (let ((b (lookup-in-lexenv (first body) env 'gotag)))
1117         (setq initag (second (binding-translation b))))
1118       (js!selfcall
1119         "var tagbody_" tbidx " = " initag ";" *newline*
1120         "tbloop:" *newline*
1121         "while (true) {" *newline*
1122         (indent "try {" *newline*
1123                 (indent (let ((content ""))
1124                           (concat "switch(tagbody_" tbidx "){" *newline*
1125                                   "case " initag ":" *newline*
1126                                   (dolist (form (cdr body) content)
1127                                     (concatf content
1128                                       (if (not (go-tag-p form))
1129                                           (indent (ls-compile form env) ";" *newline*)
1130                                           (let ((b (lookup-in-lexenv form env 'gotag)))
1131                                             (concat "case " (second (binding-translation b)) ":" *newline*)))))
1132                                   "default:" *newline*
1133                                   "    break tbloop;" *newline*
1134                                   "}" *newline*)))
1135                 "}" *newline*
1136                 "catch (jump) {" *newline*
1137                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1138                 "        tagbody_" tbidx " = jump.label;" *newline*
1139                 "    else" *newline*
1140                 "        throw(jump);" *newline*
1141                 "}" *newline*)
1142         "}" *newline*
1143         "return " (ls-compile nil) ";" *newline*))))
1144
1145 (define-compilation go (label)
1146   (let ((b (lookup-in-lexenv label env 'gotag))
1147         (n (cond
1148              ((symbolp label) (symbol-name label))
1149              ((integerp label) (integer-to-string label)))))
1150     (if b
1151         (js!selfcall
1152           "throw ({"
1153           "type: 'tagbody', "
1154           "id: " (first (binding-translation b)) ", "
1155           "label: " (second (binding-translation b)) ", "
1156           "message: 'Attempt to GO to non-existing tag " n "'"
1157           "})" *newline*)
1158         (error (concat "Unknown tag `" n "'.")))))
1159
1160
1161 (define-compilation unwind-protect (form &rest clean-up)
1162   (js!selfcall
1163     "var ret = " (ls-compile nil) ";" *newline*
1164     "try {" *newline*
1165     (indent "ret = " (ls-compile form env) ";" *newline*)
1166     "} finally {" *newline*
1167     (indent (ls-compile-block clean-up env))
1168     "}" *newline*
1169     "return ret;" *newline*))
1170
1171
1172 ;;; A little backquote implementation without optimizations of any
1173 ;;; kind for ecmalisp.
1174 (defun backquote-expand-1 (form)
1175   (cond
1176     ((symbolp form)
1177      (list 'quote form))
1178     ((atom form)
1179      form)
1180     ((eq (car form) 'unquote)
1181      (car form))
1182     ((eq (car form) 'backquote)
1183      (backquote-expand-1 (backquote-expand-1 (cadr form))))
1184     (t
1185      (cons 'append
1186            (mapcar (lambda (s)
1187                      (cond
1188                        ((and (listp s) (eq (car s) 'unquote))
1189                         (list 'list (cadr s)))
1190                        ((and (listp s) (eq (car s) 'unquote-splicing))
1191                         (cadr s))
1192                        (t
1193                         (list 'list (backquote-expand-1 s)))))
1194                    form)))))
1195
1196 (defun backquote-expand (form)
1197   (if (and (listp form) (eq (car form) 'backquote))
1198       (backquote-expand-1 (cadr form))
1199       form))
1200
1201 (defmacro backquote (form)
1202   (backquote-expand-1 form))
1203
1204 (define-transformation backquote (form)
1205   (backquote-expand-1 form))
1206
1207 ;;; Primitives
1208
1209 (defmacro define-builtin (name args &body body)
1210   `(define-compilation ,name ,args
1211      (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg env))) args)
1212        ,@body)))
1213
1214 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1215 (defmacro type-check (decls &body body)
1216   `(js!selfcall
1217      ,@(mapcar (lambda (decl)
1218                    `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1219                  decls)
1220      ,@(mapcar (lambda (decl)
1221                  `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1222                           (indent "throw 'The value ' + "
1223                                   ,(first decl)
1224                                   " + ' is not a type "
1225                                   ,(second decl)
1226                                   ".';"
1227                                   *newline*)))
1228                decls)
1229      (concat "return " (progn ,@body) ";" *newline*)))
1230
1231 (defun num-op-num (x op y)
1232   (type-check (("x" "number" x) ("y" "number" y))
1233     (concat "x" op "y")))
1234
1235 (define-builtin + (x y) (num-op-num x "+" y))
1236 (define-builtin - (x y) (num-op-num x "-" y))
1237 (define-builtin * (x y) (num-op-num x "*" y))
1238 (define-builtin / (x y) (num-op-num x "/" y))
1239
1240 (define-builtin mod (x y) (num-op-num x "%" y))
1241
1242 (define-builtin < (x y)  (js!bool (num-op-num x "<" y)))
1243 (define-builtin > (x y)  (js!bool (num-op-num x ">" y)))
1244 (define-builtin = (x y)  (js!bool (num-op-num x "==" y)))
1245 (define-builtin <= (x y) (js!bool (num-op-num x "<=" y)))
1246 (define-builtin >= (x y) (js!bool (num-op-num x ">=" y)))
1247
1248 (define-builtin numberp (x)
1249   (js!bool (concat "(typeof (" x ") == \"number\")")))
1250
1251 (define-builtin floor (x)
1252   (type-check (("x" "number" x))
1253     "Math.floor(x)"))
1254
1255 (define-builtin cons (x y) (concat "({car: " x ", cdr: " y "})"))
1256 (define-builtin consp (x)
1257   (js!bool
1258    (js!selfcall
1259      "var tmp = " x ";" *newline*
1260      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1261
1262 (define-builtin car (x)
1263   (js!selfcall
1264     "var tmp = " x ";" *newline*
1265     "return tmp === " (ls-compile nil)
1266     "? " (ls-compile nil)
1267     ": tmp.car;" *newline*))
1268
1269 (define-builtin cdr (x)
1270   (js!selfcall
1271     "var tmp = " x ";" *newline*
1272     "return tmp === " (ls-compile nil) "? "
1273     (ls-compile nil)
1274     ": tmp.cdr;" *newline*))
1275
1276 (define-builtin setcar (x new)
1277   (type-check (("x" "object" x))
1278     (concat "(x.car = " new ")")))
1279
1280 (define-builtin setcdr (x new)
1281   (type-check (("x" "object" x))
1282     (concat "(x.cdr = " new ")")))
1283
1284 (define-builtin symbolp (x)
1285   (js!bool
1286    (js!selfcall
1287      "var tmp = " x ";" *newline*
1288      "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1289
1290 (define-builtin make-symbol (name)
1291   (type-check (("name" "string" name))
1292     "({name: name})"))
1293
1294 (define-builtin symbol-name (x)
1295   (concat "(" x ").name"))
1296
1297 (define-builtin eq    (x y) (js!bool (concat "(" x " === " y ")")))
1298 (define-builtin equal (x y) (js!bool (concat "(" x  " == " y ")")))
1299
1300 (define-builtin string (x)
1301   (type-check (("x" "number" x))
1302     "String.fromCharCode(x)"))
1303
1304 (define-builtin stringp (x)
1305   (js!bool (concat "(typeof(" x ") == \"string\")")))
1306
1307 (define-builtin string-upcase (x)
1308   (type-check (("x" "string" x))
1309     "x.toUpperCase()"))
1310
1311 (define-builtin string-length (x)
1312   (type-check (("x" "string" x))
1313     "x.length"))
1314
1315 (define-compilation slice (string a &optional b)
1316   (js!selfcall
1317     "var str = " (ls-compile string env) ";" *newline*
1318     "var a = " (ls-compile a env) ";" *newline*
1319     "var b;" *newline*
1320     (if b
1321         (concat "b = " (ls-compile b env) ";" *newline*)
1322         "")
1323     "return str.slice(a,b);" *newline*))
1324
1325 (define-builtin char (string index)
1326   (type-check (("string" "string" string)
1327                ("index" "number" index))
1328     "string.charCodeAt(index)"))
1329
1330 (define-builtin concat-two (string1 string2)
1331   (type-check (("string1" "string" string1)
1332                ("string2" "string" string2))
1333     "string1.concat(string2)"))
1334
1335 (define-compilation funcall (func &rest args)
1336   (concat "(" (ls-compile func env) ")("
1337           (join (mapcar (lambda (x)
1338                           (ls-compile x env))
1339                         args)
1340                 ", ")
1341           ")"))
1342
1343 (define-compilation apply (func &rest args)
1344   (if (null args)
1345       (concat "(" (ls-compile func env) ")()")
1346       (let ((args (butlast args))
1347             (last (car (last args))))
1348         (js!selfcall
1349           "var f = " (ls-compile func env) ";" *newline*
1350           "var args = [" (join (mapcar (lambda (x)
1351                                          (ls-compile x env))
1352                                        args)
1353                                ", ")
1354           "];" *newline*
1355           "var tail = (" (ls-compile last env) ");" *newline*
1356           "while (tail != " (ls-compile nil) "){" *newline*
1357           "    args.push(tail.car);" *newline*
1358           "    tail = tail.cdr;" *newline*
1359           "}" *newline*
1360           "return f.apply(this, args);" *newline*))))
1361
1362 (define-builtin js-eval (string)
1363   (type-check (("string" "string" string))
1364     "eval.apply(window, [string])"))
1365
1366 (define-builtin error (string)
1367   (js!selfcall "throw " string ";" *newline*))
1368
1369 (define-builtin new () "{}")
1370
1371 (define-builtin get (object key)
1372   (js!selfcall
1373     "var tmp = " "(" object ")[" key "];" *newline*
1374     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1375
1376 (define-builtin set (object key value)
1377   (concat "((" object ")[" key "] = " value ")"))
1378
1379 (define-builtin in (key object)
1380   (js!bool (concat "((" key ") in (" object "))")))
1381
1382 (define-builtin functionp (x)
1383   (js!bool (concat "(typeof " x " == 'function')")))
1384
1385 (define-builtin write-string (x)
1386   (type-check (("x" "string" x))
1387     "lisp.write(x)"))
1388
1389 (defun macrop (x)
1390   (and (symbolp x) (eq (binding-type (lookup-function x *environment*)) 'macro)))
1391
1392 (defun ls-macroexpand-1 (form env)
1393   (if (macrop (car form))
1394       (let ((binding (lookup-function (car form) *environment*)))
1395         (if (eq (binding-type binding) 'macro)
1396             (apply (eval (binding-translation binding)) (cdr form))
1397             form))
1398       form))
1399
1400 (defun compile-funcall (function args env)
1401   (cond
1402     ((symbolp function)
1403      (concat (lookup-function-translation function env)
1404              "("
1405              (join (mapcar (lambda (x) (ls-compile x env)) args)
1406                    ", ")
1407              ")"))
1408     ((and (listp function) (eq (car function) 'lambda))
1409      (concat "(" (ls-compile function env) ")("
1410              (join (mapcar (lambda (x) (ls-compile x env)) args)
1411                    ", ")
1412              ")"))
1413     (t
1414      (error (concat "Invalid function designator " (symbol-name function))))))
1415
1416 (defun ls-compile (sexp &optional (env (make-lexenv)))
1417   (cond
1418     ((symbolp sexp) (lookup-variable-translation sexp env))
1419     ((integerp sexp) (integer-to-string sexp))
1420     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1421     ((listp sexp)
1422      (if (assoc (car sexp) *compilations*)
1423          (let ((comp (second (assoc (car sexp) *compilations*))))
1424            (apply comp env (cdr sexp)))
1425          (if (macrop (car sexp))
1426              (ls-compile (ls-macroexpand-1 sexp env) env)
1427              (compile-funcall (car sexp) (cdr sexp) env))))))
1428
1429 (defun ls-compile-toplevel (sexp)
1430   (setq *toplevel-compilations* nil)
1431   (let ((code (ls-compile sexp)))
1432     (prog1
1433         (concat (join (mapcar (lambda (x) (concat x ";" *newline*))
1434                               *toplevel-compilations*))
1435                 code)
1436       (setq *toplevel-compilations* nil))))
1437
1438
1439 ;;; Once we have the compiler, we define the runtime environment and
1440 ;;; interactive development (eval), which works calling the compiler
1441 ;;; and evaluating the Javascript result globally.
1442
1443 #+ecmalisp
1444 (progn
1445   (defmacro with-compilation-unit (&body body)
1446     `(prog1
1447          (progn
1448            (setq *compilation-unit-checks* nil)
1449            (clear-undeclared-global-bindings)
1450            ,@body)
1451        (dolist (check *compilation-unit-checks*)
1452          (funcall check))))
1453
1454   (defun eval (x)
1455     (let ((code
1456            (with-compilation-unit
1457                (ls-compile-toplevel x))))
1458       (js-eval code)))
1459
1460   ;; Set the initial global environment to be equal to the host global
1461   ;; environment at this point of the compilation.
1462   (eval-when-compile
1463     (let ((tmp (ls-compile
1464                 `(progn
1465                    (setq *environment* ',*environment*)
1466                    (setq *variable-counter* ',*variable-counter*)
1467                    (setq *function-counter* ',*function-counter*)
1468                    (setq *literal-counter* ',*literal-counter*)
1469                    (setq *gensym-counter* ',*gensym-counter*)
1470                    (setq *block-counter* ',*block-counter*)))))
1471       (setq *toplevel-compilations*
1472             (append *toplevel-compilations* (list tmp)))))
1473
1474   (js-eval
1475    (concat "var lisp = {};"
1476            "lisp.read = " (lookup-function-translation 'ls-read-from-string nil) ";" *newline*
1477            "lisp.print = " (lookup-function-translation 'prin1-to-string nil) ";" *newline*
1478            "lisp.eval = " (lookup-function-translation 'eval nil) ";" *newline*
1479            "lisp.compile = " (lookup-function-translation 'ls-compile-toplevel nil) ";" *newline*
1480            "lisp.evalString = function(str){" *newline*
1481            "   return lisp.eval(lisp.read(str));" *newline*
1482            "}" *newline*
1483            "lisp.compileString = function(str){" *newline*
1484            "   return lisp.compile(lisp.read(str));" *newline*
1485            "}" *newline*)))
1486
1487
1488 ;;; Finally, we provide a couple of functions to easily bootstrap
1489 ;;; this. It just calls the compiler with this file as input.
1490
1491 #+common-lisp
1492 (progn
1493   (defun read-whole-file (filename)
1494     (with-open-file (in filename)
1495       (let ((seq (make-array (file-length in) :element-type 'character)))
1496         (read-sequence seq in)
1497         seq)))
1498
1499   (defun ls-compile-file (filename output)
1500     (setq *compilation-unit-checks* nil)
1501     (with-open-file (out output :direction :output :if-exists :supersede)
1502       (let* ((source (read-whole-file filename))
1503              (in (make-string-stream source)))
1504         (loop
1505            for x = (ls-read in)
1506            until (eq x *eof*)
1507            for compilation = (ls-compile-toplevel x)
1508            when (plusp (length compilation))
1509            do (write-line (concat compilation "; ") out))
1510         (dolist (check *compilation-unit-checks*)
1511           (funcall check))
1512         (setq *compilation-unit-checks* nil))))
1513
1514   (defun bootstrap ()
1515     (setq *environment* (make-lexenv))
1516     (setq *variable-counter* 0
1517           *gensym-counter* 0
1518           *function-counter* 0
1519           *literal-counter* 0
1520           *block-counter* 0)
1521     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))