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