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