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