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