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