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