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