Implicit tagbody in DOTIMES and DOLIST
[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   (let ((variables (first *environment*))
759         (functions (second *environment*)))
760     (setq *environment* (list variables functions (third *environment*)))))
761
762
763 (defvar *variable-counter* 0)
764 (defun gvarname (symbol)
765   (concat "v" (integer-to-string (incf *variable-counter*))))
766
767 (defun lookup-variable (symbol env)
768   (or (lookup-in-lexenv symbol env 'variable)
769       (lookup-in-lexenv symbol *environment* 'variable)
770       (let ((name (symbol-name symbol))
771             (binding (make-binding symbol 'variable (gvarname symbol) nil)))
772         (push-to-lexenv binding *environment* 'variable)
773         (push (lambda ()
774                 (unless (lookup-in-lexenv symbol *environment* 'variable)
775                   (error (concat "Undefined variable `" name "'"))))
776               *compilation-unit-checks*)
777         binding)))
778
779 (defun lookup-variable-translation (symbol env)
780   (binding-translation (lookup-variable symbol env)))
781
782 (defun extend-local-env (args env)
783   (let ((new (copy-lexenv env)))
784     (dolist (symbol args new)
785       (let ((b (make-binding symbol 'variable (gvarname symbol) t)))
786         (push-to-lexenv b new 'variable)))))
787
788 (defvar *function-counter* 0)
789 (defun lookup-function (symbol env)
790   (or (lookup-in-lexenv symbol env 'function)
791       (lookup-in-lexenv symbol *environment* 'function)
792       (let ((name (symbol-name symbol))
793             (binding
794              (make-binding symbol
795                            'function
796                            (concat "f" (integer-to-string (incf *function-counter*)))
797                            nil)))
798         (push-to-lexenv binding *environment* 'function)
799         (push (lambda ()
800                 (unless (binding-declared (lookup-in-lexenv symbol *environment* 'function))
801                   (error (concat "Undefined function `" name "'"))))
802               *compilation-unit-checks*)
803         binding)))
804
805 (defun lookup-function-translation (symbol env)
806   (binding-translation (lookup-function symbol env)))
807
808 (defvar *toplevel-compilations* nil)
809
810 (defun %compile-defvar (name)
811   (let ((b (lookup-variable name *environment*)))
812     (mark-binding-as-declared b)
813     (push (concat "var " (binding-translation b)) *toplevel-compilations*)))
814
815 (defun %compile-defun (name)
816   (let ((b (lookup-function name *environment*)))
817     (mark-binding-as-declared b)
818     (push (concat "var " (binding-translation b)) *toplevel-compilations*)))
819
820 (defun %compile-defmacro (name lambda)
821   (push-to-lexenv (make-binding name 'macro lambda t) *environment* 'function))
822
823 (defvar *compilations* nil)
824
825 (defun ls-compile-block (sexps env)
826   (join-trailing
827    (remove-if (lambda (x)
828                 (or (null x)
829                     (and (stringp x)
830                          (zerop (length x)))))
831               (mapcar (lambda (x) (ls-compile x env))  sexps))
832    (concat ";" *newline*)))
833
834 (defmacro define-compilation (name args &body body)
835   ;; Creates a new primitive `name' with parameters args and
836   ;; @body. The body can access to the local environment through the
837   ;; variable ENV.
838   `(push (list ',name (lambda (env ,@args) (block ,name ,@body)))
839          *compilations*))
840
841 (define-compilation if (condition true false)
842   (concat "("
843           (ls-compile condition env) " !== " (ls-compile nil)
844           " ? "
845           (ls-compile true env)
846           " : "
847           (ls-compile false env)
848           ")"))
849
850
851 (defvar *lambda-list-keywords* '(&optional &rest))
852
853 (defun list-until-keyword (list)
854   (if (or (null list) (member (car list) *lambda-list-keywords*))
855       nil
856       (cons (car list) (list-until-keyword (cdr list)))))
857
858 (defun lambda-list-required-arguments (lambda-list)
859   (list-until-keyword lambda-list))
860
861 (defun lambda-list-optional-arguments-with-default (lambda-list)
862   (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
863
864 (defun lambda-list-optional-arguments (lambda-list)
865   (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
866
867 (defun lambda-list-rest-argument (lambda-list)
868   (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
869     (when (cdr rest)
870       (error "Bad lambda-list"))
871     (car rest)))
872
873 (define-compilation lambda (lambda-list &rest body)
874   (let ((required-arguments (lambda-list-required-arguments lambda-list))
875         (optional-arguments (lambda-list-optional-arguments lambda-list))
876         (rest-argument (lambda-list-rest-argument lambda-list)))
877     (let ((n-required-arguments (length required-arguments))
878           (n-optional-arguments (length optional-arguments))
879           (new-env (extend-local-env
880                     (append (ensure-list rest-argument)
881                             required-arguments
882                             optional-arguments)
883                     env)))
884       (concat "(function ("
885               (join (mapcar (lambda (x)
886                               (lookup-variable-translation x new-env))
887                             (append required-arguments optional-arguments))
888                     ",")
889               "){" *newline*
890               ;; Check number of arguments
891               (indent
892                (if required-arguments
893                    (concat "if (arguments.length < " (integer-to-string n-required-arguments)
894                            ") throw 'too few arguments';" *newline*)
895                    "")
896                (if (not rest-argument)
897                    (concat "if (arguments.length > "
898                            (integer-to-string (+ n-required-arguments n-optional-arguments))
899                            ") throw 'too many arguments';" *newline*)
900                    "")
901                ;; Optional arguments
902                (if optional-arguments
903                    (concat "switch(arguments.length){" *newline*
904                            (let ((optional-and-defaults
905                                   (lambda-list-optional-arguments-with-default lambda-list))
906                                  (cases nil)
907                                  (idx 0))
908                              (progn
909                                (while (< idx n-optional-arguments)
910                                  (let ((arg (nth idx optional-and-defaults)))
911                                    (push (concat "case "
912                                                  (integer-to-string (+ idx n-required-arguments)) ":" *newline*
913                                                  (lookup-variable-translation (car arg) new-env)
914                                                  "="
915                                                  (ls-compile (cadr arg) new-env)
916                                                  ";" *newline*)
917                                          cases)
918                                    (incf idx)))
919                                     (push (concat "default: break;" *newline*) cases)
920                                     (join (reverse cases))))
921                            "}" *newline*)
922                    "")
923                ;; &rest/&body argument
924                (if rest-argument
925                    (let ((js!rest (lookup-variable-translation rest-argument new-env)))
926                      (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
927                              "for (var i = arguments.length-1; i>="
928                              (integer-to-string (+ n-required-arguments n-optional-arguments))
929                              "; i--)" *newline*
930                              (indent js!rest " = "
931                                      "{car: arguments[i], cdr: ") js!rest "};"
932                                      *newline*))
933                    "")
934                ;; Body
935                (concat (ls-compile-block (butlast body) new-env)
936                        "return " (ls-compile (car (last body)) new-env) ";")) *newline*
937               "})"))))
938
939 (define-compilation fsetq (var val)
940   (concat (lookup-function-translation var env)
941           " = "
942           (ls-compile val env)))
943
944 (define-compilation setq (var val)
945   (concat (lookup-variable-translation var env)
946           " = "
947            (ls-compile val env)))
948
949 ;;; Literals
950 (defun escape-string (string)
951   (let ((output "")
952         (index 0)
953         (size (length string)))
954     (while (< index size)
955       (let ((ch (char string index)))
956         (when (or (char= ch #\") (char= ch #\\))
957           (setq output (concat output "\\")))
958         (when (or (char= ch #\newline))
959           (setq output (concat output "\\"))
960           (setq ch #\n))
961         (setq output (concat output (string ch))))
962       (incf index))
963     output))
964
965 (defun literal->js (sexp)
966   (cond
967     ((integerp sexp) (integer-to-string sexp))
968     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
969     ((symbolp sexp) (ls-compile `(intern ,(escape-string (symbol-name sexp))) *environment*))
970     ((consp sexp) (concat "{car: "
971                           (literal->js (car sexp))
972                           ", cdr: "
973                           (literal->js (cdr sexp)) "}"))))
974
975 (defvar *literal-counter* 0)
976 (defun literal (form)
977   (let ((var (concat "l" (integer-to-string (incf *literal-counter*)))))
978     (push (concat "var " var " = " (literal->js form)) *toplevel-compilations*)
979     var))
980
981 (define-compilation quote (sexp)
982   (literal sexp))
983
984 (define-compilation %while (pred &rest body)
985   (js!selfcall
986     "while(" (ls-compile pred env) " !== " (ls-compile nil) "){" *newline*
987     (indent (ls-compile-block body env))
988     "}"
989     "return " (ls-compile nil) ";" *newline*))
990
991 (define-compilation function (x)
992   (cond
993     ((and (listp x) (eq (car x) 'lambda))
994      (ls-compile x env))
995     ((symbolp x)
996      (lookup-function-translation x env))))
997
998 (define-compilation eval-when-compile (&rest body)
999   (eval (cons 'progn body))
1000   "")
1001
1002 (defmacro define-transformation (name args form)
1003   `(define-compilation ,name ,args
1004      (ls-compile ,form env)))
1005
1006 (define-compilation progn (&rest body)
1007   (js!selfcall
1008     (ls-compile-block (butlast body) env)
1009     "return " (ls-compile (car (last body)) env) ";" *newline*))
1010
1011 (define-compilation let (bindings &rest body)
1012   (let ((bindings (mapcar #'ensure-list bindings)))
1013     (let ((variables (mapcar #'first bindings))
1014           (values    (mapcar #'second bindings)))
1015       (let ((new-env (extend-local-env variables env)))
1016         (concat "(function("
1017                 (join (mapcar (lambda (x)
1018                                 (lookup-variable-translation x new-env))
1019                               variables)
1020                       ",")
1021                 "){" *newline*
1022                 (indent (ls-compile-block (butlast body) new-env)
1023                         "return " (ls-compile (car (last body)) new-env)
1024                         ";" *newline*)
1025                 "})(" (join (mapcar (lambda (x) (ls-compile x env))
1026                                     values)
1027                             ",")
1028                 ")")))))
1029
1030
1031 (defvar *block-counter* 0)
1032
1033 (define-compilation block (name &rest body)
1034   (let ((tr (integer-to-string (incf *block-counter*))))
1035     (let ((b (make-binding name 'block tr t)))
1036       (js!selfcall
1037         "try {" *newline*
1038         (indent "return " (ls-compile `(progn ,@body)
1039                                       (extend-lexenv (list b) env 'block))
1040                 ";" *newline*)
1041         "}" *newline*
1042         "catch (cf){" *newline*
1043         "    if (cf.type == 'block' && cf.id == " tr ")" *newline*
1044         "        return cf.value;" *newline*
1045         "    else" *newline*
1046         "        throw cf;" *newline*
1047         "}" *newline*))))
1048
1049 (define-compilation return-from (name &optional value)
1050   (let ((b (lookup-in-lexenv name env 'block)))
1051     (if b
1052         (js!selfcall
1053           "throw ({"
1054           "type: 'block', "
1055           "id: " (binding-translation b) ", "
1056           "value: " (ls-compile value env) ", "
1057           "message: 'Return from unknown block " (symbol-name name) ".'"
1058           "})")
1059         (error (concat "Unknown block `" (symbol-name name) "'.")))))
1060
1061
1062 (define-compilation catch (id &rest body)
1063   (js!selfcall
1064     "var id = " (ls-compile id env) ";" *newline*
1065     "try {" *newline*
1066     (indent "return " (ls-compile `(progn ,@body))
1067             ";" *newline*)
1068     "}" *newline*
1069     "catch (cf){" *newline*
1070     "    if (cf.type == 'catch' && cf.id == id)" *newline*
1071     "        return cf.value;" *newline*
1072     "    else" *newline*
1073     "        throw cf;" *newline*
1074     "}" *newline*))
1075
1076 (define-compilation throw (id &optional value)
1077   (js!selfcall
1078     "throw ({"
1079     "type: 'catch', "
1080     "id: " (ls-compile id env) ", "
1081     "value: " (ls-compile value env) ", "
1082     "message: 'Throw uncatched.'"
1083     "})"))
1084
1085
1086 (defvar *tagbody-counter* 0)
1087 (defvar *go-tag-counter* 0)
1088
1089 (defun go-tag-p (x)
1090   (or (integerp x) (symbolp x)))
1091
1092 (defun declare-tagbody-tags (env tbidx body)
1093   (let ((bindings
1094          (mapcar (lambda (label)
1095                    (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1096                      (make-binding label 'gotag (list tbidx tagidx) t)))
1097                  (remove-if-not #'go-tag-p body))))
1098     (extend-lexenv bindings env 'gotag)))
1099
1100 (define-compilation tagbody (&rest body)
1101   ;; Ignore the tagbody if it does not contain any go-tag. We do this
1102   ;; because 1) it is easy and 2) many built-in forms expand to a
1103   ;; implicit tagbody, so we save some space.
1104   (unless (some #'go-tag-p body)
1105     (return-from tagbody (ls-compile `(progn ,@body nil) env)))
1106   ;; The translation assumes the first form in BODY is a label
1107   (unless (go-tag-p (car body))
1108     (push (gensym "START") body))
1109   ;; Tagbody compilation
1110   (let ((tbidx (integer-to-string *tagbody-counter*)))
1111     (let ((env (declare-tagbody-tags env tbidx body))
1112           initag)
1113       (let ((b (lookup-in-lexenv (first body) env 'gotag)))
1114         (setq initag (second (binding-translation b))))
1115       (js!selfcall
1116         "var tagbody_" tbidx " = " initag ";" *newline*
1117         "tbloop:" *newline*
1118         "while (true) {" *newline*
1119         (indent "try {" *newline*
1120                 (indent (let ((content ""))
1121                           (concat "switch(tagbody_" tbidx "){" *newline*
1122                                   "case " initag ":" *newline*
1123                                   (dolist (form (cdr body) content)
1124                                     (concatf content
1125                                       (if (not (go-tag-p form))
1126                                           (indent (ls-compile form env) ";" *newline*)
1127                                           (let ((b (lookup-in-lexenv form env 'gotag)))
1128                                             (concat "case " (second (binding-translation b)) ":" *newline*)))))
1129                                   "default:" *newline*
1130                                   "    break tbloop;" *newline*
1131                                   "}" *newline*)))
1132                 "}" *newline*
1133                 "catch (jump) {" *newline*
1134                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1135                 "        tagbody_" tbidx " = jump.label;" *newline*
1136                 "    else" *newline*
1137                 "        throw(jump);" *newline*
1138                 "}" *newline*)
1139         "}" *newline*
1140         "return " (ls-compile nil) ";" *newline*))))
1141
1142 (define-compilation go (label)
1143   (let ((b (lookup-in-lexenv label env 'gotag))
1144         (n (cond
1145              ((symbolp label) (symbol-name label))
1146              ((integerp label) (integer-to-string label)))))
1147     (if b
1148         (js!selfcall
1149           "throw ({"
1150           "type: 'tagbody', "
1151           "id: " (first (binding-translation b)) ", "
1152           "label: " (second (binding-translation b)) ", "
1153           "message: 'Attempt to GO to non-existing tag " n "'"
1154           "})" *newline*)
1155         (error (concat "Unknown tag `" n "'.")))))
1156
1157
1158 (define-compilation unwind-protect (form &rest clean-up)
1159   (js!selfcall
1160     "var ret = " (ls-compile nil) ";" *newline*
1161     "try {" *newline*
1162     (indent "ret = " (ls-compile form env) ";" *newline*)
1163     "} finally {" *newline*
1164     (indent (ls-compile-block clean-up env))
1165     "}" *newline*
1166     "return ret;" *newline*))
1167
1168
1169 ;;; A little backquote implementation without optimizations of any
1170 ;;; kind for ecmalisp.
1171 (defun backquote-expand-1 (form)
1172   (cond
1173     ((symbolp form)
1174      (list 'quote form))
1175     ((atom form)
1176      form)
1177     ((eq (car form) 'unquote)
1178      (car form))
1179     ((eq (car form) 'backquote)
1180      (backquote-expand-1 (backquote-expand-1 (cadr form))))
1181     (t
1182      (cons 'append
1183            (mapcar (lambda (s)
1184                      (cond
1185                        ((and (listp s) (eq (car s) 'unquote))
1186                         (list 'list (cadr s)))
1187                        ((and (listp s) (eq (car s) 'unquote-splicing))
1188                         (cadr s))
1189                        (t
1190                         (list 'list (backquote-expand-1 s)))))
1191                    form)))))
1192
1193 (defun backquote-expand (form)
1194   (if (and (listp form) (eq (car form) 'backquote))
1195       (backquote-expand-1 (cadr form))
1196       form))
1197
1198 (defmacro backquote (form)
1199   (backquote-expand-1 form))
1200
1201 (define-transformation backquote (form)
1202   (backquote-expand-1 form))
1203
1204 ;;; Primitives
1205
1206 (defmacro define-builtin (name args &body body)
1207   `(define-compilation ,name ,args
1208      (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg env))) args)
1209        ,@body)))
1210
1211 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1212 (defmacro type-check (decls &body body)
1213   `(js!selfcall
1214      ,@(mapcar (lambda (decl)
1215                    `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1216                  decls)
1217      ,@(mapcar (lambda (decl)
1218                  `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1219                           (indent "throw 'The value ' + "
1220                                   ,(first decl)
1221                                   " + ' is not a type "
1222                                   ,(second decl)
1223                                   ".';"
1224                                   *newline*)))
1225                decls)
1226      (concat "return " (progn ,@body) ";" *newline*)))
1227
1228 (defun num-op-num (x op y)
1229   (type-check (("x" "number" x) ("y" "number" y))
1230     (concat "x" op "y")))
1231
1232 (define-builtin + (x y) (num-op-num x "+" y))
1233 (define-builtin - (x y) (num-op-num x "-" y))
1234 (define-builtin * (x y) (num-op-num x "*" y))
1235 (define-builtin / (x y) (num-op-num x "/" y))
1236
1237 (define-builtin mod (x y) (num-op-num x "%" y))
1238
1239 (define-builtin < (x y)  (js!bool (num-op-num x "<" y)))
1240 (define-builtin > (x y)  (js!bool (num-op-num x ">" y)))
1241 (define-builtin = (x y)  (js!bool (num-op-num x "==" y)))
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
1245 (define-builtin numberp (x)
1246   (js!bool (concat "(typeof (" x ") == \"number\")")))
1247
1248 (define-builtin floor (x)
1249   (type-check (("x" "number" x))
1250     "Math.floor(x)"))
1251
1252 (define-builtin cons (x y) (concat "({car: " x ", cdr: " y "})"))
1253 (define-builtin consp (x)
1254   (js!bool
1255    (js!selfcall
1256      "var tmp = " x ";" *newline*
1257      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1258
1259 (define-builtin car (x)
1260   (js!selfcall
1261     "var tmp = " x ";" *newline*
1262     "return tmp === " (ls-compile nil)
1263     "? " (ls-compile nil)
1264     ": tmp.car;" *newline*))
1265
1266 (define-builtin cdr (x)
1267   (js!selfcall
1268     "var tmp = " x ";" *newline*
1269     "return tmp === " (ls-compile nil) "? "
1270     (ls-compile nil)
1271     ": tmp.cdr;" *newline*))
1272
1273 (define-builtin setcar (x new)
1274   (type-check (("x" "object" x))
1275     (concat "(x.car = " new ")")))
1276
1277 (define-builtin setcdr (x new)
1278   (type-check (("x" "object" x))
1279     (concat "(x.cdr = " new ")")))
1280
1281 (define-builtin symbolp (x)
1282   (js!bool
1283    (js!selfcall
1284      "var tmp = " x ";" *newline*
1285      "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1286
1287 (define-builtin make-symbol (name)
1288   (type-check (("name" "string" name))
1289     "({name: name})"))
1290
1291 (define-builtin symbol-name (x)
1292   (concat "(" x ").name"))
1293
1294 (define-builtin eq    (x y) (js!bool (concat "(" x " === " y ")")))
1295 (define-builtin equal (x y) (js!bool (concat "(" x  " == " y ")")))
1296
1297 (define-builtin string (x)
1298   (type-check (("x" "number" x))
1299     "String.fromCharCode(x)"))
1300
1301 (define-builtin stringp (x)
1302   (js!bool (concat "(typeof(" x ") == \"string\")")))
1303
1304 (define-builtin string-upcase (x)
1305   (type-check (("x" "string" x))
1306     "x.toUpperCase()"))
1307
1308 (define-builtin string-length (x)
1309   (type-check (("x" "string" x))
1310     "x.length"))
1311
1312 (define-compilation slice (string a &optional b)
1313   (js!selfcall
1314     "var str = " (ls-compile string env) ";" *newline*
1315     "var a = " (ls-compile a env) ";" *newline*
1316     "var b;" *newline*
1317     (if b
1318         (concat "b = " (ls-compile b env) ";" *newline*)
1319         "")
1320     "return str.slice(a,b);" *newline*))
1321
1322 (define-builtin char (string index)
1323   (type-check (("string" "string" string)
1324                ("index" "number" index))
1325     "string.charCodeAt(index)"))
1326
1327 (define-builtin concat-two (string1 string2)
1328   (type-check (("string1" "string" string1)
1329                ("string2" "string" string2))
1330     "string1.concat(string2)"))
1331
1332 (define-compilation funcall (func &rest args)
1333   (concat "(" (ls-compile func env) ")("
1334           (join (mapcar (lambda (x)
1335                           (ls-compile x env))
1336                         args)
1337                 ", ")
1338           ")"))
1339
1340 (define-compilation apply (func &rest args)
1341   (if (null args)
1342       (concat "(" (ls-compile func env) ")()")
1343       (let ((args (butlast args))
1344             (last (car (last args))))
1345         (js!selfcall
1346           "var f = " (ls-compile func env) ";" *newline*
1347           "var args = [" (join (mapcar (lambda (x)
1348                                          (ls-compile x env))
1349                                        args)
1350                                ", ")
1351           "];" *newline*
1352           "var tail = (" (ls-compile last env) ");" *newline*
1353           "while (tail != " (ls-compile nil) "){" *newline*
1354           "    args.push(tail.car);" *newline*
1355           "    tail = tail.cdr;" *newline*
1356           "}" *newline*
1357           "return f.apply(this, args);" *newline*))))
1358
1359 (define-builtin js-eval (string)
1360   (type-check (("string" "string" string))
1361     "eval.apply(window, [string])"))
1362
1363 (define-builtin error (string)
1364   (js!selfcall "throw " string ";" *newline*))
1365
1366 (define-builtin new () "{}")
1367
1368 (define-builtin get (object key)
1369   (js!selfcall
1370     "var tmp = " "(" object ")[" key "];" *newline*
1371     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1372
1373 (define-builtin set (object key value)
1374   (concat "((" object ")[" key "] = " value ")"))
1375
1376 (define-builtin in (key object)
1377   (js!bool (concat "((" key ") in (" object "))")))
1378
1379 (define-builtin functionp (x)
1380   (js!bool (concat "(typeof " x " == 'function')")))
1381
1382 (define-builtin write-string (x)
1383   (type-check (("x" "string" x))
1384     "lisp.write(x)"))
1385
1386 (defun macrop (x)
1387   (and (symbolp x) (eq (binding-type (lookup-function x *environment*)) 'macro)))
1388
1389 (defun ls-macroexpand-1 (form env)
1390   (if (macrop (car form))
1391       (let ((binding (lookup-function (car form) *environment*)))
1392         (if (eq (binding-type binding) 'macro)
1393             (apply (eval (binding-translation binding)) (cdr form))
1394             form))
1395       form))
1396
1397 (defun compile-funcall (function args env)
1398   (cond
1399     ((symbolp function)
1400      (concat (lookup-function-translation function env)
1401              "("
1402              (join (mapcar (lambda (x) (ls-compile x env)) args)
1403                    ", ")
1404              ")"))
1405     ((and (listp function) (eq (car function) 'lambda))
1406      (concat "(" (ls-compile function env) ")("
1407              (join (mapcar (lambda (x) (ls-compile x env)) args)
1408                    ", ")
1409              ")"))
1410     (t
1411      (error (concat "Invalid function designator " (symbol-name function))))))
1412
1413 (defun ls-compile (sexp &optional (env (make-lexenv)))
1414   (cond
1415     ((symbolp sexp) (lookup-variable-translation sexp env))
1416     ((integerp sexp) (integer-to-string sexp))
1417     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1418     ((listp sexp)
1419      (if (assoc (car sexp) *compilations*)
1420          (let ((comp (second (assoc (car sexp) *compilations*))))
1421            (apply comp env (cdr sexp)))
1422          (if (macrop (car sexp))
1423              (ls-compile (ls-macroexpand-1 sexp env) env)
1424              (compile-funcall (car sexp) (cdr sexp) env))))))
1425
1426 (defun ls-compile-toplevel (sexp)
1427   (setq *toplevel-compilations* nil)
1428   (let ((code (ls-compile sexp)))
1429     (prog1
1430         (concat (join (mapcar (lambda (x) (concat x ";" *newline*))
1431                               *toplevel-compilations*))
1432                 code)
1433       (setq *toplevel-compilations* nil))))
1434
1435
1436 ;;; Once we have the compiler, we define the runtime environment and
1437 ;;; interactive development (eval), which works calling the compiler
1438 ;;; and evaluating the Javascript result globally.
1439
1440 #+ecmalisp
1441 (progn
1442   (defmacro with-compilation-unit (&body body)
1443     `(prog1
1444          (progn
1445            (setq *compilation-unit-checks* nil)
1446            (clear-undeclared-global-bindings)
1447            ,@body)
1448        (dolist (check *compilation-unit-checks*)
1449          (funcall check))))
1450
1451   (defun eval (x)
1452     (let ((code
1453            (with-compilation-unit
1454                (ls-compile-toplevel x))))
1455       (js-eval code)))
1456
1457   ;; Set the initial global environment to be equal to the host global
1458   ;; environment at this point of the compilation.
1459   (eval-when-compile
1460     (let ((tmp (ls-compile
1461                 `(progn
1462                    (setq *environment* ',*environment*)
1463                    (setq *variable-counter* ',*variable-counter*)
1464                    (setq *function-counter* ',*function-counter*)
1465                    (setq *literal-counter* ',*literal-counter*)
1466                    (setq *gensym-counter* ',*gensym-counter*)
1467                    (setq *block-counter* ',*block-counter*)))))
1468       (setq *toplevel-compilations*
1469             (append *toplevel-compilations* (list tmp)))))
1470
1471   (js-eval
1472    (concat "var lisp = {};"
1473            "lisp.read = " (lookup-function-translation 'ls-read-from-string nil) ";" *newline*
1474            "lisp.print = " (lookup-function-translation 'prin1-to-string nil) ";" *newline*
1475            "lisp.eval = " (lookup-function-translation 'eval nil) ";" *newline*
1476            "lisp.compile = " (lookup-function-translation 'ls-compile-toplevel nil) ";" *newline*
1477            "lisp.evalString = function(str){" *newline*
1478            "   return lisp.eval(lisp.read(str));" *newline*
1479            "}" *newline*
1480            "lisp.compileString = function(str){" *newline*
1481            "   return lisp.compile(lisp.read(str));" *newline*
1482            "}" *newline*)))
1483
1484
1485 ;;; Finally, we provide a couple of functions to easily bootstrap
1486 ;;; this. It just calls the compiler with this file as input.
1487
1488 #+common-lisp
1489 (progn
1490   (defun read-whole-file (filename)
1491     (with-open-file (in filename)
1492       (let ((seq (make-array (file-length in) :element-type 'character)))
1493         (read-sequence seq in)
1494         seq)))
1495
1496   (defun ls-compile-file (filename output)
1497     (setq *compilation-unit-checks* nil)
1498     (with-open-file (out output :direction :output :if-exists :supersede)
1499       (let* ((source (read-whole-file filename))
1500              (in (make-string-stream source)))
1501         (loop
1502            for x = (ls-read in)
1503            until (eq x *eof*)
1504            for compilation = (ls-compile-toplevel x)
1505            when (plusp (length compilation))
1506            do (write-line (concat compilation "; ") out))
1507         (dolist (check *compilation-unit-checks*)
1508           (funcall check))
1509         (setq *compilation-unit-checks* nil))))
1510
1511   (defun bootstrap ()
1512     (setq *environment* (make-lexenv))
1513     (setq *variable-counter* 0
1514           *gensym-counter* 0
1515           *function-counter* 0
1516           *literal-counter* 0
1517           *block-counter* 0)
1518     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))