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