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