56a70c670070e4d6451c1b2eebeac7726833e750
[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   (setcar        lexenv  (cons binding (car lexenv))))
768     (function   (setcar   (cdr lexenv) (cons binding (cadr lexenv))))
769     (block      (setcar  (cddr lexenv) (cons binding (caddr lexenv))))
770     (gotag      (setcar (cdddr lexenv) (cons binding (cadddr lexenv))))))
771
772 (defun extend-lexenv (bindings lexenv namespace)
773   (let ((env (copy-lexenv lexenv)))
774     (dolist (binding (reverse bindings) env)
775       (push-to-lexenv binding env namespace))))
776
777 (defun lookup-in-lexenv (name lexenv namespace)
778   (assoc name (ecase namespace
779                 (variable (first lexenv))
780                 (function (second lexenv))
781                 (block (third lexenv))
782                 (gotag (fourth lexenv)))))
783
784 (defvar *global-environment* (make-lexenv))
785 (defvar *environment* (make-lexenv))
786
787 (defun clear-undeclared-global-bindings ()
788   (setq *environment*
789         (mapcar (lambda (namespace)
790                   (remove-if-not #'binding-declared namespace))
791                 *environment*)))
792
793
794 (defvar *variable-counter* 0)
795 (defun gvarname (symbol)
796   (concat "v" (integer-to-string (incf *variable-counter*))))
797
798 (defun translate-variable (symbol)
799   (binding-translation (lookup-in-lexenv symbol *environment* 'variable)))
800
801 (defun extend-local-env (args)
802   (let ((new (copy-lexenv *environment*)))
803     (dolist (symbol args new)
804       (let ((b (make-binding symbol 'lexical-variable (gvarname symbol) t)))
805         (push-to-lexenv b new 'variable)))))
806
807 ;;; Toplevel compilations
808 (defvar *toplevel-compilations* nil)
809
810 (defun toplevel-compilation (string)
811   (push string *toplevel-compilations*))
812
813 (defun null-or-empty-p (x)
814   (zerop (length x)))
815
816 (defun get-toplevel-compilations ()
817   (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
818
819 (defun %compile-defmacro (name lambda)
820   (toplevel-compilation (ls-compile `',name))
821   (push-to-lexenv (make-binding name 'macro lambda t) *environment* 'function))
822
823 (defvar *compilations* nil)
824
825 (defun ls-compile-block (sexps)
826   (join-trailing
827    (remove-if #'null-or-empty-p  (mapcar #'ls-compile sexps))
828    (concat ";" *newline*)))
829
830 (defmacro define-compilation (name args &body body)
831   ;; Creates a new primitive `name' with parameters args and
832   ;; @body. The body can access to the local environment through the
833   ;; variable *ENVIRONMENT*.
834   `(push (list ',name (lambda ,args (block ,name ,@body)))
835          *compilations*))
836
837 (define-compilation if (condition true false)
838   (concat "(" (ls-compile condition) " !== " (ls-compile nil)
839           " ? " (ls-compile true)
840           " : " (ls-compile false)
841           ")"))
842
843 (defvar *lambda-list-keywords* '(&optional &rest))
844
845 (defun list-until-keyword (list)
846   (if (or (null list) (member (car list) *lambda-list-keywords*))
847       nil
848       (cons (car list) (list-until-keyword (cdr list)))))
849
850 (defun lambda-list-required-arguments (lambda-list)
851   (list-until-keyword lambda-list))
852
853 (defun lambda-list-optional-arguments-with-default (lambda-list)
854   (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
855
856 (defun lambda-list-optional-arguments (lambda-list)
857   (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
858
859 (defun lambda-list-rest-argument (lambda-list)
860   (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
861     (when (cdr rest)
862       (error "Bad lambda-list"))
863     (car rest)))
864
865 (define-compilation lambda (lambda-list &rest body)
866   (let ((required-arguments (lambda-list-required-arguments lambda-list))
867         (optional-arguments (lambda-list-optional-arguments lambda-list))
868         (rest-argument (lambda-list-rest-argument lambda-list)))
869     (let ((n-required-arguments (length required-arguments))
870           (n-optional-arguments (length optional-arguments))
871           (*environment* (extend-local-env
872                           (append (ensure-list rest-argument)
873                                   required-arguments
874                                   optional-arguments))))
875       (concat "(function ("
876               (join (mapcar #'translate-variable
877                             (append required-arguments optional-arguments))
878                     ",")
879               "){" *newline*
880               ;; Check number of arguments
881               (indent
882                (if required-arguments
883                    (concat "if (arguments.length < " (integer-to-string n-required-arguments)
884                            ") throw 'too few arguments';" *newline*)
885                    "")
886                (if (not rest-argument)
887                    (concat "if (arguments.length > "
888                            (integer-to-string (+ n-required-arguments n-optional-arguments))
889                            ") throw 'too many arguments';" *newline*)
890                    "")
891                ;; Optional arguments
892                (if optional-arguments
893                    (concat "switch(arguments.length){" *newline*
894                            (let ((optional-and-defaults
895                                   (lambda-list-optional-arguments-with-default lambda-list))
896                                  (cases nil)
897                                  (idx 0))
898                              (progn
899                                (while (< idx n-optional-arguments)
900                                  (let ((arg (nth idx optional-and-defaults)))
901                                    (push (concat "case "
902                                                  (integer-to-string (+ idx n-required-arguments)) ":" *newline*
903                                                  (translate-variable (car arg))
904                                                  "="
905                                                  (ls-compile (cadr arg))
906                                                  ";" *newline*)
907                                          cases)
908                                    (incf idx)))
909                                (push (concat "default: break;" *newline*) cases)
910                                (join (reverse cases))))
911                            "}" *newline*)
912                    "")
913                ;; &rest/&body argument
914                (if rest-argument
915                    (let ((js!rest (translate-variable rest-argument)))
916                      (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
917                              "for (var i = arguments.length-1; i>="
918                              (integer-to-string (+ n-required-arguments n-optional-arguments))
919                              "; i--)" *newline*
920                              (indent js!rest " = "
921                                      "{car: arguments[i], cdr: ") js!rest "};"
922                              *newline*))
923                    "")
924                ;; Body
925                (concat (ls-compile-block (butlast body))
926                        "return " (ls-compile (car (last body))) ";")) *newline*
927               "})"))))
928
929 (define-compilation setq (var val)
930   (let ((b (lookup-in-lexenv var *environment* 'variable)))
931     (if (eq (binding-type b) 'lexical-variable)
932         (concat (binding-translation b) " = " (ls-compile val))
933         (ls-compile `(set ',var ,val)))))
934
935 ;;; FFI Variable accessors
936 (define-compilation js-vref (var)
937   var)
938
939 (define-compilation js-vset (var val)
940   (concat "(" var " = " (ls-compile val) ")"))
941
942
943 ;;; Literals
944 (defun escape-string (string)
945   (let ((output "")
946         (index 0)
947         (size (length string)))
948     (while (< index size)
949       (let ((ch (char string index)))
950         (when (or (char= ch #\") (char= ch #\\))
951           (setq output (concat output "\\")))
952         (when (or (char= ch #\newline))
953           (setq output (concat output "\\"))
954           (setq ch #\n))
955         (setq output (concat output (string ch))))
956       (incf index))
957     output))
958
959
960 (defvar *literal-symbols* nil)
961 (defvar *literal-counter* 0)
962
963 (defun genlit ()
964   (concat "l" (integer-to-string (incf *literal-counter*))))
965
966 (defun literal (sexp &optional recursive)
967   (cond
968     ((integerp sexp) (integer-to-string sexp))
969     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
970     ((symbolp sexp)
971      (or (cdr (assoc sexp *literal-symbols*))
972          (let ((v (genlit))
973                (s #+common-lisp (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
974                   #+ecmalisp (ls-compile `(intern ,(symbol-name sexp)))))
975            (push (cons sexp v) *literal-symbols*)
976            (toplevel-compilation (concat "var " v " = " s))
977            v)))
978     ((consp sexp)
979      (let ((c (concat "{car: " (literal (car sexp) t) ", "
980                       "cdr: " (literal (cdr sexp) t) "}")))
981        (if recursive
982            c
983            (let ((v (genlit)))
984              (toplevel-compilation (concat "var " v " = " c))
985              v))))))
986
987 (define-compilation quote (sexp)
988   (literal sexp))
989
990 (define-compilation %while (pred &rest body)
991   (js!selfcall
992     "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
993     (indent (ls-compile-block body))
994     "}"
995     "return " (ls-compile nil) ";" *newline*))
996
997 (define-compilation function (x)
998   (cond
999     ((and (listp x) (eq (car x) 'lambda))
1000      (ls-compile x))
1001     ((symbolp x)
1002      (ls-compile `(symbol-function ',x)))))
1003
1004 (define-compilation eval-when-compile (&rest body)
1005   (eval (cons 'progn body))
1006   nil)
1007
1008 (defmacro define-transformation (name args form)
1009   `(define-compilation ,name ,args
1010      (ls-compile ,form)))
1011
1012 (define-compilation progn (&rest body)
1013   (js!selfcall
1014     (ls-compile-block (butlast body))
1015     "return " (ls-compile (car (last body))) ";" *newline*))
1016
1017
1018 (defun dynamic-binding-wrapper (bindings body)
1019   (if (null bindings)
1020       body
1021       (concat
1022        "try {" *newline*
1023        (indent
1024         "var tmp;" *newline*
1025         (join
1026          (mapcar (lambda (b)
1027                    (let ((s (ls-compile `(quote ,(car b)))))
1028                      (concat "tmp = " s ".value;" *newline*
1029                              s ".value = " (cdr b) ";" *newline*
1030                              (cdr b) " = tmp;" *newline*)))
1031                  bindings))
1032         body)
1033        "}" *newline*
1034        "finally {"  *newline*
1035        (indent
1036         (join-trailing
1037          (mapcar (lambda (b)
1038                    (let ((s (ls-compile `(quote ,(car b)))))
1039                      (concat s ".value" " = " (cdr b))))
1040                  bindings)
1041          (concat ";" *newline*)))
1042        "}" *newline*)))
1043
1044
1045 (define-compilation let (bindings &rest body)
1046   (let ((bindings (mapcar #'ensure-list bindings)))
1047     (let ((variables (mapcar #'first bindings))
1048           (values    (mapcar #'second bindings)))
1049       (let ((cvalues (mapcar #'ls-compile values))
1050             (*environment* (extend-local-env (remove-if #'boundp variables)))
1051             (dynamic-bindings))
1052         (concat "(function("
1053                 (join (mapcar (lambda (x)
1054                                 (if (boundp x)
1055                                     (let ((v (gvarname x)))
1056                                       (push (cons x v) dynamic-bindings)
1057                                       v)
1058                                     (translate-variable x)))
1059                               variables)
1060                       ",")
1061                 "){" *newline*
1062                 (let ((body
1063                        (concat (ls-compile-block (butlast body))
1064                                "return " (ls-compile (car (last body)))
1065                                ";" *newline*)))
1066                   (indent (dynamic-binding-wrapper dynamic-bindings body)))
1067                 "})(" (join cvalues ",") ")")))))
1068
1069
1070 (defvar *block-counter* 0)
1071
1072 (define-compilation block (name &rest body)
1073   (let ((tr (integer-to-string (incf *block-counter*))))
1074     (let ((b (make-binding name 'block tr t)))
1075       (js!selfcall
1076         "try {" *newline*
1077         (let ((*environment* (extend-lexenv (list b) *environment* 'block)))
1078           (indent "return " (ls-compile `(progn ,@body)) ";" *newline*))
1079         "}" *newline*
1080         "catch (cf){" *newline*
1081         "    if (cf.type == 'block' && cf.id == " tr ")" *newline*
1082         "        return cf.value;" *newline*
1083         "    else" *newline*
1084         "        throw cf;" *newline*
1085         "}" *newline*))))
1086
1087 (define-compilation return-from (name &optional value)
1088   (let ((b (lookup-in-lexenv name *environment* 'block)))
1089     (if b
1090         (js!selfcall
1091           "throw ({"
1092           "type: 'block', "
1093           "id: " (binding-translation b) ", "
1094           "value: " (ls-compile value) ", "
1095           "message: 'Return from unknown block " (symbol-name name) ".'"
1096           "})")
1097         (error (concat "Unknown block `" (symbol-name name) "'.")))))
1098
1099
1100 (define-compilation catch (id &rest body)
1101   (js!selfcall
1102     "var id = " (ls-compile id) ";" *newline*
1103     "try {" *newline*
1104     (indent "return " (ls-compile `(progn ,@body))
1105             ";" *newline*)
1106     "}" *newline*
1107     "catch (cf){" *newline*
1108     "    if (cf.type == 'catch' && cf.id == id)" *newline*
1109     "        return cf.value;" *newline*
1110     "    else" *newline*
1111     "        throw cf;" *newline*
1112     "}" *newline*))
1113
1114 (define-compilation throw (id &optional value)
1115   (js!selfcall
1116     "throw ({"
1117     "type: 'catch', "
1118     "id: " (ls-compile id) ", "
1119     "value: " (ls-compile value) ", "
1120     "message: 'Throw uncatched.'"
1121     "})"))
1122
1123
1124 (defvar *tagbody-counter* 0)
1125 (defvar *go-tag-counter* 0)
1126
1127 (defun go-tag-p (x)
1128   (or (integerp x) (symbolp x)))
1129
1130 (defun declare-tagbody-tags (tbidx body)
1131   (let ((bindings
1132          (mapcar (lambda (label)
1133                    (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1134                      (make-binding label 'gotag (list tbidx tagidx) t)))
1135                  (remove-if-not #'go-tag-p body))))
1136     (extend-lexenv bindings *environment* 'gotag)))
1137
1138 (define-compilation tagbody (&rest body)
1139   ;; Ignore the tagbody if it does not contain any go-tag. We do this
1140   ;; because 1) it is easy and 2) many built-in forms expand to a
1141   ;; implicit tagbody, so we save some space.
1142   (unless (some #'go-tag-p body)
1143     (return-from tagbody (ls-compile `(progn ,@body nil))))
1144   ;; The translation assumes the first form in BODY is a label
1145   (unless (go-tag-p (car body))
1146     (push (gensym "START") body))
1147   ;; Tagbody compilation
1148   (let ((tbidx (integer-to-string *tagbody-counter*)))
1149     (let ((*environment* (declare-tagbody-tags tbidx body))
1150           initag)
1151       (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1152         (setq initag (second (binding-translation b))))
1153       (js!selfcall
1154         "var tagbody_" tbidx " = " initag ";" *newline*
1155         "tbloop:" *newline*
1156         "while (true) {" *newline*
1157         (indent "try {" *newline*
1158                 (indent (let ((content ""))
1159                           (concat "switch(tagbody_" tbidx "){" *newline*
1160                                   "case " initag ":" *newline*
1161                                   (dolist (form (cdr body) content)
1162                                     (concatf content
1163                                       (if (not (go-tag-p form))
1164                                           (indent (ls-compile form) ";" *newline*)
1165                                           (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1166                                             (concat "case " (second (binding-translation b)) ":" *newline*)))))
1167                                   "default:" *newline*
1168                                   "    break tbloop;" *newline*
1169                                   "}" *newline*)))
1170                 "}" *newline*
1171                 "catch (jump) {" *newline*
1172                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1173                 "        tagbody_" tbidx " = jump.label;" *newline*
1174                 "    else" *newline*
1175                 "        throw(jump);" *newline*
1176                 "}" *newline*)
1177         "}" *newline*
1178         "return " (ls-compile nil) ";" *newline*))))
1179
1180 (define-compilation go (label)
1181   (let ((b (lookup-in-lexenv label *environment* 'gotag))
1182         (n (cond
1183              ((symbolp label) (symbol-name label))
1184              ((integerp label) (integer-to-string label)))))
1185     (if b
1186         (js!selfcall
1187           "throw ({"
1188           "type: 'tagbody', "
1189           "id: " (first (binding-translation b)) ", "
1190           "label: " (second (binding-translation b)) ", "
1191           "message: 'Attempt to GO to non-existing tag " n "'"
1192           "})" *newline*)
1193         (error (concat "Unknown tag `" n "'.")))))
1194
1195
1196 (define-compilation unwind-protect (form &rest clean-up)
1197   (js!selfcall
1198     "var ret = " (ls-compile nil) ";" *newline*
1199     "try {" *newline*
1200     (indent "ret = " (ls-compile form) ";" *newline*)
1201     "} finally {" *newline*
1202     (indent (ls-compile-block clean-up))
1203     "}" *newline*
1204     "return ret;" *newline*))
1205
1206
1207 ;;; A little backquote implementation without optimizations of any
1208 ;;; kind for ecmalisp.
1209 (defun backquote-expand-1 (form)
1210   (cond
1211     ((symbolp form)
1212      (list 'quote form))
1213     ((atom form)
1214      form)
1215     ((eq (car form) 'unquote)
1216      (car form))
1217     ((eq (car form) 'backquote)
1218      (backquote-expand-1 (backquote-expand-1 (cadr form))))
1219     (t
1220      (cons 'append
1221            (mapcar (lambda (s)
1222                      (cond
1223                        ((and (listp s) (eq (car s) 'unquote))
1224                         (list 'list (cadr s)))
1225                        ((and (listp s) (eq (car s) 'unquote-splicing))
1226                         (cadr s))
1227                        (t
1228                         (list 'list (backquote-expand-1 s)))))
1229                    form)))))
1230
1231 (defun backquote-expand (form)
1232   (if (and (listp form) (eq (car form) 'backquote))
1233       (backquote-expand-1 (cadr form))
1234       form))
1235
1236 (defmacro backquote (form)
1237   (backquote-expand-1 form))
1238
1239 (define-transformation backquote (form)
1240   (backquote-expand-1 form))
1241
1242 ;;; Primitives
1243
1244 (defmacro define-builtin (name args &body body)
1245   `(progn
1246      (define-compilation ,name ,args
1247        (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1248          ,@body))))
1249
1250 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1251 (defmacro type-check (decls &body body)
1252   `(js!selfcall
1253      ,@(mapcar (lambda (decl)
1254                    `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1255                  decls)
1256      ,@(mapcar (lambda (decl)
1257                  `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1258                           (indent "throw 'The value ' + "
1259                                   ,(first decl)
1260                                   " + ' is not a type "
1261                                   ,(second decl)
1262                                   ".';"
1263                                   *newline*)))
1264                decls)
1265      (concat "return " (progn ,@body) ";" *newline*)))
1266
1267 (defun num-op-num (x op y)
1268   (type-check (("x" "number" x) ("y" "number" y))
1269     (concat "x" op "y")))
1270
1271 (define-builtin + (x y) (num-op-num x "+" y))
1272 (define-builtin - (x y) (num-op-num x "-" y))
1273 (define-builtin * (x y) (num-op-num x "*" y))
1274 (define-builtin / (x y) (num-op-num x "/" y))
1275
1276 (define-builtin mod (x y) (num-op-num x "%" y))
1277
1278 (define-builtin < (x y)  (js!bool (num-op-num x "<" y)))
1279 (define-builtin > (x y)  (js!bool (num-op-num x ">" y)))
1280 (define-builtin = (x y)  (js!bool (num-op-num x "==" y)))
1281 (define-builtin <= (x y) (js!bool (num-op-num x "<=" y)))
1282 (define-builtin >= (x y) (js!bool (num-op-num x ">=" y)))
1283
1284 (define-builtin numberp (x)
1285   (js!bool (concat "(typeof (" x ") == \"number\")")))
1286
1287 (define-builtin floor (x)
1288   (type-check (("x" "number" x))
1289     "Math.floor(x)"))
1290
1291 (define-builtin cons (x y)
1292   (concat "({car: " x ", cdr: " y "})"))
1293
1294 (define-builtin consp (x)
1295   (js!bool
1296    (js!selfcall
1297      "var tmp = " x ";" *newline*
1298      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1299
1300 (define-builtin car (x)
1301   (js!selfcall
1302     "var tmp = " x ";" *newline*
1303     "return tmp === " (ls-compile nil)
1304     "? " (ls-compile nil)
1305     ": tmp.car;" *newline*))
1306
1307 (define-builtin cdr (x)
1308   (js!selfcall
1309     "var tmp = " x ";" *newline*
1310     "return tmp === " (ls-compile nil) "? "
1311     (ls-compile nil)
1312     ": tmp.cdr;" *newline*))
1313
1314 (define-builtin setcar (x new)
1315   (type-check (("x" "object" x))
1316     (concat "(x.car = " new ")")))
1317
1318 (define-builtin setcdr (x new)
1319   (type-check (("x" "object" x))
1320     (concat "(x.cdr = " new ")")))
1321
1322 (define-builtin symbolp (x)
1323   (js!bool
1324    (js!selfcall
1325      "var tmp = " x ";" *newline*
1326      "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1327
1328 (define-builtin make-symbol (name)
1329   (type-check (("name" "string" name))
1330     "({name: name})"))
1331
1332 (define-builtin symbol-name (x)
1333   (concat "(" x ").name"))
1334
1335 (define-builtin set (symbol value)
1336   (concat "(" symbol ").value = " value))
1337
1338 (define-builtin fset (symbol value)
1339   (concat "(" symbol ").function = " value))
1340
1341 (define-builtin boundp (x)
1342   (js!bool (concat "(" x ".value !== undefined)")))
1343
1344 (define-builtin symbol-value (x)
1345   (js!selfcall
1346     "var symbol = " x ";" *newline*
1347     "var value = symbol.value;" *newline*
1348     "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1349     "return value;" *newline*))
1350
1351 (define-builtin symbol-function (x)
1352   (js!selfcall
1353     "var symbol = " x ";" *newline*
1354     "var func = symbol.function;" *newline*
1355     "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1356     "return func;" *newline*))
1357
1358 (define-builtin symbol-plist (x)
1359   (concat "((" x ").plist || " (ls-compile nil) ")"))
1360
1361 (define-builtin lambda-code (x)
1362   (concat "(" x ").toString()"))
1363
1364
1365 (define-builtin eq    (x y) (js!bool (concat "(" x " === " y ")")))
1366 (define-builtin equal (x y) (js!bool (concat "(" x  " == " y ")")))
1367
1368 (define-builtin string (x)
1369   (type-check (("x" "number" x))
1370     "String.fromCharCode(x)"))
1371
1372 (define-builtin stringp (x)
1373   (js!bool (concat "(typeof(" x ") == \"string\")")))
1374
1375 (define-builtin string-upcase (x)
1376   (type-check (("x" "string" x))
1377     "x.toUpperCase()"))
1378
1379 (define-builtin string-length (x)
1380   (type-check (("x" "string" x))
1381     "x.length"))
1382
1383 (define-compilation slice (string a &optional b)
1384   (js!selfcall
1385     "var str = " (ls-compile string) ";" *newline*
1386     "var a = " (ls-compile a) ";" *newline*
1387     "var b;" *newline*
1388     (if b
1389         (concat "b = " (ls-compile b) ";" *newline*)
1390         "")
1391     "return str.slice(a,b);" *newline*))
1392
1393 (define-builtin char (string index)
1394   (type-check (("string" "string" string)
1395                ("index" "number" index))
1396     "string.charCodeAt(index)"))
1397
1398 (define-builtin concat-two (string1 string2)
1399   (type-check (("string1" "string" string1)
1400                ("string2" "string" string2))
1401     "string1.concat(string2)"))
1402
1403 (define-compilation funcall (func &rest args)
1404   (concat "(" (ls-compile func) ")("
1405           (join (mapcar #'ls-compile args)
1406                 ", ")
1407           ")"))
1408
1409 (define-compilation apply (func &rest args)
1410   (if (null args)
1411       (concat "(" (ls-compile func) ")()")
1412       (let ((args (butlast args))
1413             (last (car (last args))))
1414         (js!selfcall
1415           "var f = " (ls-compile func) ";" *newline*
1416           "var args = [" (join (mapcar #'ls-compile args)
1417                                ", ")
1418           "];" *newline*
1419           "var tail = (" (ls-compile last) ");" *newline*
1420           "while (tail != " (ls-compile nil) "){" *newline*
1421           "    args.push(tail.car);" *newline*
1422           "    tail = tail.cdr;" *newline*
1423           "}" *newline*
1424           "return f.apply(this, args);" *newline*))))
1425
1426 (define-builtin js-eval (string)
1427   (type-check (("string" "string" string))
1428     "eval.apply(window, [string])"))
1429
1430 (define-builtin error (string)
1431   (js!selfcall "throw " string ";" *newline*))
1432
1433 (define-builtin new () "{}")
1434
1435 (define-builtin oget (object key)
1436   (js!selfcall
1437     "var tmp = " "(" object ")[" key "];" *newline*
1438     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1439
1440 (define-builtin oset (object key value)
1441   (concat "((" object ")[" key "] = " value ")"))
1442
1443 (define-builtin in (key object)
1444   (js!bool (concat "((" key ") in (" object "))")))
1445
1446 (define-builtin functionp (x)
1447   (js!bool (concat "(typeof " x " == 'function')")))
1448
1449 (define-builtin write-string (x)
1450   (type-check (("x" "string" x))
1451     "lisp.write(x)"))
1452
1453 (defun macro (x)
1454   (and (symbolp x)
1455        (let ((b (lookup-in-lexenv x *environment* 'function)))
1456          (and (eq (binding-type b) 'macro)
1457               b))))
1458
1459 (defun ls-macroexpand-1 (form)
1460   (let ((macro-binding (macro (car form))))
1461     (if macro-binding
1462         (apply (eval (binding-translation macro-binding)) (cdr form))
1463         form)))
1464
1465 (defun compile-funcall (function args)
1466   (concat (ls-compile `#',function) "("
1467           (join (mapcar #'ls-compile args)
1468                 ", ")
1469           ")"))
1470
1471 (defun ls-compile (sexp)
1472   (cond
1473     ((symbolp sexp)
1474      (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1475        (if (eq (binding-type b) 'lexical-variable)
1476            (binding-translation b)
1477            (ls-compile `(symbol-value ',sexp)))))
1478     ((integerp sexp) (integer-to-string sexp))
1479     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1480     ((listp sexp)
1481      (if (assoc (car sexp) *compilations*)
1482          (let ((comp (second (assoc (car sexp) *compilations*))))
1483            (apply comp (cdr sexp)))
1484          (if (macro (car sexp))
1485              (ls-compile (ls-macroexpand-1 sexp))
1486              (compile-funcall (car sexp) (cdr sexp)))))))
1487
1488 (defun ls-compile-toplevel (sexp)
1489   (let ((*toplevel-compilations* nil))
1490     (cond
1491       ((and (consp sexp) (eq (car sexp) 'progn))
1492        (let ((subs (mapcar #'ls-compile-toplevel (cdr sexp))))
1493          (join (remove-if #'null-or-empty-p subs))))
1494       (t
1495        (let ((code (ls-compile sexp)))
1496          (concat (join-trailing (get-toplevel-compilations)
1497                                 (concat ";" *newline*))
1498                  (if code
1499                      (concat code ";" *newline*)
1500                      "")))))))
1501
1502
1503 ;;; Once we have the compiler, we define the runtime environment and
1504 ;;; interactive development (eval), which works calling the compiler
1505 ;;; and evaluating the Javascript result globally.
1506
1507 #+ecmalisp
1508 (progn
1509   (defmacro with-compilation-unit (&body body)
1510     `(prog1
1511          (progn
1512            (setq *compilation-unit-checks* nil)
1513            (clear-undeclared-global-bindings)
1514            ,@body)
1515        (dolist (check *compilation-unit-checks*)
1516          (funcall check))))
1517
1518   (defun eval (x)
1519     (let ((code
1520            (with-compilation-unit
1521                (ls-compile-toplevel x))))
1522       (js-eval code)))
1523
1524   (js-eval "var lisp")
1525   (js-vset "lisp" (new))
1526   (js-vset "lisp.read" #'ls-read-from-string)
1527   (js-vset "lisp.print" #'prin1-to-string)
1528   (js-vset "lisp.eval" #'eval)
1529   (js-vset "lisp.compile" #'ls-compile-toplevel)
1530   (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
1531   (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str))))
1532
1533   ;; Set the initial global environment to be equal to the host global
1534   ;; environment at this point of the compilation.
1535   (eval-when-compile
1536     (toplevel-compilation
1537      (ls-compile
1538       `(progn
1539          ,@(mapcar (lambda (s)
1540                      `(oset *package* ,(symbol-name (car s))
1541                             (js-vref ,(cdr s))))
1542                    *literal-symbols*)
1543          (setq *literal-symbols* ',*literal-symbols*)
1544          (setq *environment* ',*environment*)
1545          (setq *variable-counter* ,*variable-counter*)
1546          (setq *gensym-counter* ,*gensym-counter*)
1547          (setq *block-counter* ,*block-counter*)))))
1548
1549   (eval-when-compile
1550     (toplevel-compilation
1551      (ls-compile
1552       `(setq *literal-counter* ,*literal-counter*)))))
1553
1554
1555 ;;; Finally, we provide a couple of functions to easily bootstrap
1556 ;;; this. It just calls the compiler with this file as input.
1557
1558 #+common-lisp
1559 (progn
1560   (defun read-whole-file (filename)
1561     (with-open-file (in filename)
1562       (let ((seq (make-array (file-length in) :element-type 'character)))
1563         (read-sequence seq in)
1564         seq)))
1565
1566   (defun ls-compile-file (filename output)
1567     (setq *compilation-unit-checks* nil)
1568     (with-open-file (out output :direction :output :if-exists :supersede)
1569       (let* ((source (read-whole-file filename))
1570              (in (make-string-stream source)))
1571         (loop
1572            for x = (ls-read in)
1573            until (eq x *eof*)
1574            for compilation = (ls-compile-toplevel x)
1575            when (plusp (length compilation))
1576            do (write-string compilation out))
1577         (dolist (check *compilation-unit-checks*)
1578           (funcall check))
1579         (setq *compilation-unit-checks* nil))))
1580
1581   (defun bootstrap ()
1582     (setq *environment* (make-lexenv))
1583     (setq *literal-symbols* nil)
1584     (setq *variable-counter* 0
1585           *gensym-counter* 0
1586           *literal-counter* 0
1587           *block-counter* 0)
1588     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))