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