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