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