562f1f80aa5c829dbf2405022022295c87dde221
[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 (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")))
970            (push (cons sexp v) *literal-symbols*)
971            (toplevel-compilation (concat "var " v " = " s))
972            v)))
973     ((consp sexp)
974      (let ((c (concat "{car: " (literal (car sexp) t) ", "
975                       "cdr: " (literal (cdr sexp) t) "}")))
976        (if recursive
977            c
978            (let ((v (genlit)))
979              (toplevel-compilation (concat "var " v " = " c))
980              v))))))
981
982 (define-compilation quote (sexp)
983   (literal sexp))
984
985
986 (define-compilation %while (pred &rest body)
987   (js!selfcall
988     "while(" (ls-compile pred env) " !== " (ls-compile nil) "){" *newline*
989     (indent (ls-compile-block body env))
990     "}"
991     "return " (ls-compile nil) ";" *newline*))
992
993 (define-compilation function (x)
994   (cond
995     ((and (listp x) (eq (car x) 'lambda))
996      (ls-compile x env))
997     ((symbolp x)
998      (ls-compile `(symbol-function ',x))
999      ;; TODO: Add lexical functions
1000      ;;(lookup-function-translation x env)
1001      )))
1002
1003 (define-compilation eval-when-compile (&rest body)
1004   (eval (cons 'progn body))
1005   nil)
1006
1007 (defmacro define-transformation (name args form)
1008   `(define-compilation ,name ,args
1009      (ls-compile ,form env)))
1010
1011 (define-compilation progn (&rest body)
1012   (js!selfcall
1013     (ls-compile-block (butlast body) env)
1014     "return " (ls-compile (car (last body)) env) ";" *newline*))
1015
1016 (define-compilation let (bindings &rest body)
1017   (let ((bindings (mapcar #'ensure-list bindings)))
1018     (let ((variables (mapcar #'first bindings))
1019           (values    (mapcar #'second bindings)))
1020       (let ((new-env (extend-local-env variables env)))
1021         (concat "(function("
1022                 (join (mapcar (lambda (x)
1023                                 (translate-variable x new-env))
1024                               variables)
1025                       ",")
1026                 "){" *newline*
1027                 (indent (ls-compile-block (butlast body) new-env)
1028                         "return " (ls-compile (car (last body)) new-env)
1029                         ";" *newline*)
1030                 "})(" (join (mapcar (lambda (x) (ls-compile x env))
1031                                     values)
1032                             ",")
1033                 ")")))))
1034
1035
1036 (defvar *block-counter* 0)
1037
1038 (define-compilation block (name &rest body)
1039   (let ((tr (integer-to-string (incf *block-counter*))))
1040     (let ((b (make-binding name 'block tr t)))
1041       (js!selfcall
1042         "try {" *newline*
1043         (indent "return " (ls-compile `(progn ,@body)
1044                                       (extend-lexenv (list b) env 'block))
1045                 ";" *newline*)
1046         "}" *newline*
1047         "catch (cf){" *newline*
1048         "    if (cf.type == 'block' && cf.id == " tr ")" *newline*
1049         "        return cf.value;" *newline*
1050         "    else" *newline*
1051         "        throw cf;" *newline*
1052         "}" *newline*))))
1053
1054 (define-compilation return-from (name &optional value)
1055   (let ((b (lookup-in-lexenv name env 'block)))
1056     (if b
1057         (js!selfcall
1058           "throw ({"
1059           "type: 'block', "
1060           "id: " (binding-translation b) ", "
1061           "value: " (ls-compile value env) ", "
1062           "message: 'Return from unknown block " (symbol-name name) ".'"
1063           "})")
1064         (error (concat "Unknown block `" (symbol-name name) "'.")))))
1065
1066
1067 (define-compilation catch (id &rest body)
1068   (js!selfcall
1069     "var id = " (ls-compile id env) ";" *newline*
1070     "try {" *newline*
1071     (indent "return " (ls-compile `(progn ,@body))
1072             ";" *newline*)
1073     "}" *newline*
1074     "catch (cf){" *newline*
1075     "    if (cf.type == 'catch' && cf.id == id)" *newline*
1076     "        return cf.value;" *newline*
1077     "    else" *newline*
1078     "        throw cf;" *newline*
1079     "}" *newline*))
1080
1081 (define-compilation throw (id &optional value)
1082   (js!selfcall
1083     "throw ({"
1084     "type: 'catch', "
1085     "id: " (ls-compile id env) ", "
1086     "value: " (ls-compile value env) ", "
1087     "message: 'Throw uncatched.'"
1088     "})"))
1089
1090
1091 (defvar *tagbody-counter* 0)
1092 (defvar *go-tag-counter* 0)
1093
1094 (defun go-tag-p (x)
1095   (or (integerp x) (symbolp x)))
1096
1097 (defun declare-tagbody-tags (env tbidx body)
1098   (let ((bindings
1099          (mapcar (lambda (label)
1100                    (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1101                      (make-binding label 'gotag (list tbidx tagidx) t)))
1102                  (remove-if-not #'go-tag-p body))))
1103     (extend-lexenv bindings env 'gotag)))
1104
1105 (define-compilation tagbody (&rest body)
1106   ;; Ignore the tagbody if it does not contain any go-tag. We do this
1107   ;; because 1) it is easy and 2) many built-in forms expand to a
1108   ;; implicit tagbody, so we save some space.
1109   (unless (some #'go-tag-p body)
1110     (return-from tagbody (ls-compile `(progn ,@body nil) env)))
1111   ;; The translation assumes the first form in BODY is a label
1112   (unless (go-tag-p (car body))
1113     (push (gensym "START") body))
1114   ;; Tagbody compilation
1115   (let ((tbidx (integer-to-string *tagbody-counter*)))
1116     (let ((env (declare-tagbody-tags env tbidx body))
1117           initag)
1118       (let ((b (lookup-in-lexenv (first body) env 'gotag)))
1119         (setq initag (second (binding-translation b))))
1120       (js!selfcall
1121         "var tagbody_" tbidx " = " initag ";" *newline*
1122         "tbloop:" *newline*
1123         "while (true) {" *newline*
1124         (indent "try {" *newline*
1125                 (indent (let ((content ""))
1126                           (concat "switch(tagbody_" tbidx "){" *newline*
1127                                   "case " initag ":" *newline*
1128                                   (dolist (form (cdr body) content)
1129                                     (concatf content
1130                                       (if (not (go-tag-p form))
1131                                           (indent (ls-compile form env) ";" *newline*)
1132                                           (let ((b (lookup-in-lexenv form env 'gotag)))
1133                                             (concat "case " (second (binding-translation b)) ":" *newline*)))))
1134                                   "default:" *newline*
1135                                   "    break tbloop;" *newline*
1136                                   "}" *newline*)))
1137                 "}" *newline*
1138                 "catch (jump) {" *newline*
1139                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1140                 "        tagbody_" tbidx " = jump.label;" *newline*
1141                 "    else" *newline*
1142                 "        throw(jump);" *newline*
1143                 "}" *newline*)
1144         "}" *newline*
1145         "return " (ls-compile nil) ";" *newline*))))
1146
1147 (define-compilation go (label)
1148   (let ((b (lookup-in-lexenv label env 'gotag))
1149         (n (cond
1150              ((symbolp label) (symbol-name label))
1151              ((integerp label) (integer-to-string label)))))
1152     (if b
1153         (js!selfcall
1154           "throw ({"
1155           "type: 'tagbody', "
1156           "id: " (first (binding-translation b)) ", "
1157           "label: " (second (binding-translation b)) ", "
1158           "message: 'Attempt to GO to non-existing tag " n "'"
1159           "})" *newline*)
1160         (error (concat "Unknown tag `" n "'.")))))
1161
1162
1163 (define-compilation unwind-protect (form &rest clean-up)
1164   (js!selfcall
1165     "var ret = " (ls-compile nil) ";" *newline*
1166     "try {" *newline*
1167     (indent "ret = " (ls-compile form env) ";" *newline*)
1168     "} finally {" *newline*
1169     (indent (ls-compile-block clean-up env))
1170     "}" *newline*
1171     "return ret;" *newline*))
1172
1173
1174 ;;; A little backquote implementation without optimizations of any
1175 ;;; kind for ecmalisp.
1176 (defun backquote-expand-1 (form)
1177   (cond
1178     ((symbolp form)
1179      (list 'quote form))
1180     ((atom form)
1181      form)
1182     ((eq (car form) 'unquote)
1183      (car form))
1184     ((eq (car form) 'backquote)
1185      (backquote-expand-1 (backquote-expand-1 (cadr form))))
1186     (t
1187      (cons 'append
1188            (mapcar (lambda (s)
1189                      (cond
1190                        ((and (listp s) (eq (car s) 'unquote))
1191                         (list 'list (cadr s)))
1192                        ((and (listp s) (eq (car s) 'unquote-splicing))
1193                         (cadr s))
1194                        (t
1195                         (list 'list (backquote-expand-1 s)))))
1196                    form)))))
1197
1198 (defun backquote-expand (form)
1199   (if (and (listp form) (eq (car form) 'backquote))
1200       (backquote-expand-1 (cadr form))
1201       form))
1202
1203 (defmacro backquote (form)
1204   (backquote-expand-1 form))
1205
1206 (define-transformation backquote (form)
1207   (backquote-expand-1 form))
1208
1209 ;;; Primitives
1210
1211 (defmacro define-builtin (name args &body body)
1212   `(progn
1213      (define-compilation ,name ,args
1214        (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg env))) args)
1215          ,@body))))
1216
1217 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1218 (defmacro type-check (decls &body body)
1219   `(js!selfcall
1220      ,@(mapcar (lambda (decl)
1221                    `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1222                  decls)
1223      ,@(mapcar (lambda (decl)
1224                  `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1225                           (indent "throw 'The value ' + "
1226                                   ,(first decl)
1227                                   " + ' is not a type "
1228                                   ,(second decl)
1229                                   ".';"
1230                                   *newline*)))
1231                decls)
1232      (concat "return " (progn ,@body) ";" *newline*)))
1233
1234 (defun num-op-num (x op y)
1235   (type-check (("x" "number" x) ("y" "number" y))
1236     (concat "x" op "y")))
1237
1238 (define-builtin + (x y) (num-op-num x "+" y))
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
1243 (define-builtin mod (x y) (num-op-num x "%" y))
1244
1245 (define-builtin < (x y)  (js!bool (num-op-num x "<" y)))
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
1251 (define-builtin numberp (x)
1252   (js!bool (concat "(typeof (" x ") == \"number\")")))
1253
1254 (define-builtin floor (x)
1255   (type-check (("x" "number" x))
1256     "Math.floor(x)"))
1257
1258 (define-builtin cons (x y)
1259   (concat "({car: " x ", cdr: " y "})"))
1260
1261 (define-builtin consp (x)
1262   (js!bool
1263    (js!selfcall
1264      "var tmp = " x ";" *newline*
1265      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1266
1267 (define-builtin car (x)
1268   (js!selfcall
1269     "var tmp = " x ";" *newline*
1270     "return tmp === " (ls-compile nil)
1271     "? " (ls-compile nil)
1272     ": tmp.car;" *newline*))
1273
1274 (define-builtin cdr (x)
1275   (js!selfcall
1276     "var tmp = " x ";" *newline*
1277     "return tmp === " (ls-compile nil) "? "
1278     (ls-compile nil)
1279     ": tmp.cdr;" *newline*))
1280
1281 (define-builtin setcar (x new)
1282   (type-check (("x" "object" x))
1283     (concat "(x.car = " new ")")))
1284
1285 (define-builtin setcdr (x new)
1286   (type-check (("x" "object" x))
1287     (concat "(x.cdr = " new ")")))
1288
1289 (define-builtin symbolp (x)
1290   (js!bool
1291    (js!selfcall
1292      "var tmp = " x ";" *newline*
1293      "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1294
1295 (define-builtin make-symbol (name)
1296   (type-check (("name" "string" name))
1297     "({name: name})"))
1298
1299 (define-builtin symbol-name (x)
1300   (concat "(" x ").name"))
1301
1302 (define-builtin set (symbol value)
1303   (concat "(" symbol ").value =" value))
1304
1305 (define-builtin fset (symbol value)
1306   (concat "(" symbol ").function =" value))
1307
1308 (define-builtin symbol-value (x)
1309   (js!selfcall
1310     "var symbol = " x ";" *newline*
1311     "var value = symbol.value;" *newline*
1312     "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1313     "return value;" *newline*))
1314
1315 (define-builtin symbol-function (x)
1316   (js!selfcall
1317     "var symbol = " x ";" *newline*
1318     "var func = symbol.function;" *newline*
1319     "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1320     "return func;" *newline*))
1321
1322 (define-builtin symbol-plist (x)
1323   (concat "((" x ").plist || " (ls-compile nil) ")"))
1324
1325 (define-builtin lambda-code (x)
1326   (concat "(" x ").toString()"))
1327
1328
1329 (define-builtin eq    (x y) (js!bool (concat "(" x " === " y ")")))
1330 (define-builtin equal (x y) (js!bool (concat "(" x  " == " y ")")))
1331
1332 (define-builtin string (x)
1333   (type-check (("x" "number" x))
1334     "String.fromCharCode(x)"))
1335
1336 (define-builtin stringp (x)
1337   (js!bool (concat "(typeof(" x ") == \"string\")")))
1338
1339 (define-builtin string-upcase (x)
1340   (type-check (("x" "string" x))
1341     "x.toUpperCase()"))
1342
1343 (define-builtin string-length (x)
1344   (type-check (("x" "string" x))
1345     "x.length"))
1346
1347 (define-compilation slice (string a &optional b)
1348   (js!selfcall
1349     "var str = " (ls-compile string env) ";" *newline*
1350     "var a = " (ls-compile a env) ";" *newline*
1351     "var b;" *newline*
1352     (if b
1353         (concat "b = " (ls-compile b env) ";" *newline*)
1354         "")
1355     "return str.slice(a,b);" *newline*))
1356
1357 (define-builtin char (string index)
1358   (type-check (("string" "string" string)
1359                ("index" "number" index))
1360     "string.charCodeAt(index)"))
1361
1362 (define-builtin concat-two (string1 string2)
1363   (type-check (("string1" "string" string1)
1364                ("string2" "string" string2))
1365     "string1.concat(string2)"))
1366
1367 (define-compilation funcall (func &rest args)
1368   (concat "(" (ls-compile func env) ")("
1369           (join (mapcar (lambda (x)
1370                           (ls-compile x env))
1371                         args)
1372                 ", ")
1373           ")"))
1374
1375 (define-compilation apply (func &rest args)
1376   (if (null args)
1377       (concat "(" (ls-compile func env) ")()")
1378       (let ((args (butlast args))
1379             (last (car (last args))))
1380         (js!selfcall
1381           "var f = " (ls-compile func env) ";" *newline*
1382           "var args = [" (join (mapcar (lambda (x)
1383                                          (ls-compile x env))
1384                                        args)
1385                                ", ")
1386           "];" *newline*
1387           "var tail = (" (ls-compile last env) ");" *newline*
1388           "while (tail != " (ls-compile nil) "){" *newline*
1389           "    args.push(tail.car);" *newline*
1390           "    tail = tail.cdr;" *newline*
1391           "}" *newline*
1392           "return f.apply(this, args);" *newline*))))
1393
1394 (define-builtin js-eval (string)
1395   (type-check (("string" "string" string))
1396     "eval.apply(window, [string])"))
1397
1398 (define-builtin error (string)
1399   (js!selfcall "throw " string ";" *newline*))
1400
1401 (define-builtin new () "{}")
1402
1403 (define-builtin oget (object key)
1404   (js!selfcall
1405     "var tmp = " "(" object ")[" key "];" *newline*
1406     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1407
1408 (define-builtin oset (object key value)
1409   (concat "((" object ")[" key "] = " value ")"))
1410
1411 (define-builtin in (key object)
1412   (js!bool (concat "((" key ") in (" object "))")))
1413
1414 (define-builtin functionp (x)
1415   (js!bool (concat "(typeof " x " == 'function')")))
1416
1417 (define-builtin write-string (x)
1418   (type-check (("x" "string" x))
1419     "lisp.write(x)"))
1420
1421 (defun macro (x)
1422   (and (symbolp x)
1423        (let ((b (lookup-in-lexenv x *environment* 'function)))
1424          (and (eq (binding-type b) 'macro)
1425               b))))
1426
1427 (defun ls-macroexpand-1 (form)
1428   (let ((macro-binding (macro (car form))))
1429     (if macro-binding
1430         (apply (eval (binding-translation macro-binding)) (cdr form))
1431         form)))
1432
1433 (defun compile-funcall (function args env)
1434   (concat (ls-compile `#',function) "("
1435           (join (mapcar (lambda (x) (ls-compile x env)) args)
1436                 ", ")
1437           ")"))
1438
1439 (defun ls-compile (sexp &optional (env (make-lexenv)))
1440   (cond
1441     ((symbolp sexp)
1442      (let ((b (lookup-in-lexenv sexp env 'variable)))
1443        (if (eq (binding-type b) 'lexical-variable)
1444            (binding-translation b)
1445            (ls-compile `(symbol-value ',sexp) env))))
1446     ((integerp sexp) (integer-to-string sexp))
1447     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1448     ((listp sexp)
1449      (if (assoc (car sexp) *compilations*)
1450          (let ((comp (second (assoc (car sexp) *compilations*))))
1451            (apply comp env (cdr sexp)))
1452          (if (macro (car sexp))
1453              (ls-compile (ls-macroexpand-1 sexp) env)
1454              (compile-funcall (car sexp) (cdr sexp) env))))))
1455
1456 (defun ls-compile-toplevel (sexp)
1457   (setq *toplevel-compilations* nil)
1458   (cond
1459     ((and (consp sexp) (eq (car sexp) 'progn))
1460      (let ((subs (mapcar #'ls-compile-toplevel (cdr sexp))))
1461        (join (remove-if #'null-or-empty-p subs))))
1462     (t
1463      (let ((code (ls-compile sexp)))
1464        (prog1
1465            (concat (join-trailing (get-toplevel-compilations) (concat ";" *newline*))
1466                    (if code
1467                        (concat code ";" *newline*)
1468                        ""))
1469          (setq *toplevel-compilations* nil))))))
1470
1471
1472 ;;; Once we have the compiler, we define the runtime environment and
1473 ;;; interactive development (eval), which works calling the compiler
1474 ;;; and evaluating the Javascript result globally.
1475
1476 #+ecmalisp
1477 (progn
1478   (defmacro with-compilation-unit (&body body)
1479     `(prog1
1480          (progn
1481            (setq *compilation-unit-checks* nil)
1482            (clear-undeclared-global-bindings)
1483            ,@body)
1484        (dolist (check *compilation-unit-checks*)
1485          (funcall check))))
1486
1487   (defun eval (x)
1488     (let ((code
1489            (with-compilation-unit
1490                (ls-compile-toplevel x))))
1491       (js-eval code)))
1492
1493   (js-eval "var lisp")
1494   (js-vset "lisp" (new))
1495   (js-vset "lisp.read" #'ls-read-from-string)
1496   (js-vset "lisp.print" #'prin1-to-string)
1497   (js-vset "lisp.eval" #'eval)
1498   (js-vset "lisp.compile" #'ls-compile-toplevel)
1499   (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
1500   (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str))))
1501
1502   ;; Set the initial global environment to be equal to the host global
1503   ;; environment at this point of the compilation.
1504   (eval-when-compile
1505     (toplevel-compilation
1506      (ls-compile
1507       `(progn
1508          ,@(mapcar (lambda (s)
1509                      `(oset *package* ,(symbol-name (car s))
1510                             (js-vref ,(cdr s))))
1511                    *literal-symbols*)
1512          (setq *literal-symbols* ',*literal-symbols*)
1513          (setq *environment* ',*environment*)
1514          (setq *variable-counter* ,*variable-counter*)
1515          (setq *gensym-counter* ,*gensym-counter*)
1516          (setq *block-counter* ,*block-counter*)))))
1517
1518   (eval-when-compile
1519     (toplevel-compilation
1520      (ls-compile
1521       `(setq *literal-counter* ,*literal-counter*)))))
1522
1523
1524 ;;; Finally, we provide a couple of functions to easily bootstrap
1525 ;;; this. It just calls the compiler with this file as input.
1526
1527 #+common-lisp
1528 (progn
1529   (defun read-whole-file (filename)
1530     (with-open-file (in filename)
1531       (let ((seq (make-array (file-length in) :element-type 'character)))
1532         (read-sequence seq in)
1533         seq)))
1534
1535   (defun ls-compile-file (filename output)
1536     (setq *compilation-unit-checks* nil)
1537     (with-open-file (out output :direction :output :if-exists :supersede)
1538       (let* ((source (read-whole-file filename))
1539              (in (make-string-stream source)))
1540         (loop
1541            for x = (ls-read in)
1542            until (eq x *eof*)
1543            for compilation = (ls-compile-toplevel x)
1544            when (plusp (length compilation))
1545            do (write-string compilation out))
1546         (dolist (check *compilation-unit-checks*)
1547           (funcall check))
1548         (setq *compilation-unit-checks* nil))))
1549
1550   (defun bootstrap ()
1551     (setq *environment* (make-lexenv))
1552     (setq *literal-symbols* nil)
1553     (setq *variable-counter* 0
1554           *gensym-counter* 0
1555           *literal-counter* 0
1556           *block-counter* 0)
1557     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))