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