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