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