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