Merge branch 'simple-optimizations' into gh-pages
[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 declaim (&rest decls)
40     `(eval-when-compile
41        ,@(mapcar (lambda (decl) `(!proclaim ',decl)) decls)))
42
43   (declaim (constant nil t) (special t nil))
44   (setq nil 'nil)
45   (setq t 't)
46
47   (defmacro when (condition &body body)
48     `(if ,condition (progn ,@body) nil))
49
50   (defmacro unless (condition &body body)
51     `(if ,condition nil (progn ,@body)))
52
53   (defmacro defvar (name value &optional docstring)
54     `(progn
55        (declaim (special ,name))
56        (unless (boundp ',name) (setq ,name ,value))
57        ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
58        ',name))
59
60   (defmacro defparameter (name value &optional docstring)
61     `(progn
62        (setq ,name ,value)
63        ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
64        ',name))
65
66   (defmacro named-lambda (name args &rest body)
67     (let ((x (gensym "FN")))
68       `(let ((,x (lambda ,args ,@body)))
69          (oset ,x "fname" ,name)
70          ,x)))
71
72   (defmacro defun (name args &rest body)
73     `(progn
74        (fset ',name
75              (named-lambda ,(symbol-name name) ,args
76                ,@(if (and (stringp (car body)) (not (null (cdr body))))
77                      `(,(car body) (block ,name ,@(cdr body)))
78                      `((block ,name ,@body)))))
79        ',name))
80
81   (defun null (x)
82     (eq x nil))
83
84   (defmacro return (&optional value)
85     `(return-from nil ,value))
86
87   (defmacro while (condition &body body)
88     `(block nil (%while ,condition ,@body)))
89
90   (defvar *gensym-counter* 0)
91   (defun gensym (&optional (prefix "G"))
92     (setq *gensym-counter* (+ *gensym-counter* 1))
93     (make-symbol (concat-two prefix (integer-to-string *gensym-counter*))))
94
95   (defun boundp (x)
96     (boundp x))
97
98   ;; Basic functions
99   (defun = (x y) (= x y))
100   (defun * (x y) (* x y))
101   (defun / (x y) (/ x y))
102   (defun 1+ (x) (+ x 1))
103   (defun 1- (x) (- x 1))
104   (defun zerop (x) (= x 0))
105   (defun truncate (x y) (floor (/ x y)))
106
107   (defun eql (x y) (eq x y))
108
109   (defun not (x) (if x nil t))
110
111   (defun cons (x y ) (cons x y))
112   (defun consp (x) (consp x))
113
114   (defun car (x)
115     "Return the CAR part of a cons, or NIL if X is null."
116     (car x))
117
118   (defun cdr (x) (cdr x))
119   (defun caar (x) (car (car x)))
120   (defun cadr (x) (car (cdr x)))
121   (defun cdar (x) (cdr (car x)))
122   (defun cddr (x) (cdr (cdr x)))
123   (defun caddr (x) (car (cdr (cdr x))))
124   (defun cdddr (x) (cdr (cdr (cdr x))))
125   (defun cadddr (x) (car (cdr (cdr (cdr x)))))
126   (defun first (x) (car x))
127   (defun second (x) (cadr x))
128   (defun third (x) (caddr x))
129   (defun fourth (x) (cadddr x))
130
131   (defun list (&rest args) args)
132   (defun atom (x)
133     (not (consp x)))
134
135   ;; Basic macros
136
137   (defmacro incf (x &optional (delta 1))
138     `(setq ,x (+ ,x ,delta)))
139
140   (defmacro decf (x &optional (delta 1))
141     `(setq ,x (- ,x ,delta)))
142
143   (defmacro push (x place)
144     `(setq ,place (cons ,x ,place)))
145
146   (defmacro dolist (iter &body body)
147     (let ((var (first iter))
148           (g!list (gensym)))
149       `(block nil
150          (let ((,g!list ,(second iter))
151                (,var nil))
152            (%while ,g!list
153                    (setq ,var (car ,g!list))
154                    (tagbody ,@body)
155                    (setq ,g!list (cdr ,g!list)))
156            ,(third iter)))))
157
158   (defmacro dotimes (iter &body body)
159     (let ((g!to (gensym))
160           (var (first iter))
161           (to (second iter))
162           (result (third iter)))
163       `(block nil
164          (let ((,var 0)
165                (,g!to ,to))
166            (%while (< ,var ,g!to)
167                    (tagbody ,@body)
168                    (incf ,var))
169            ,result))))
170
171   (defmacro cond (&rest clausules)
172     (if (null clausules)
173         nil
174         (if (eq (caar clausules) t)
175             `(progn ,@(cdar clausules))
176             `(if ,(caar clausules)
177                  (progn ,@(cdar clausules))
178                  (cond ,@(cdr clausules))))))
179
180   (defmacro case (form &rest clausules)
181     (let ((!form (gensym)))
182       `(let ((,!form ,form))
183          (cond
184            ,@(mapcar (lambda (clausule)
185                        (if (eq (car clausule) t)
186                            clausule
187                            `((eql ,!form ',(car clausule))
188                              ,@(cdr clausule))))
189                      clausules)))))
190
191   (defmacro ecase (form &rest clausules)
192     `(case ,form
193        ,@(append
194           clausules
195           `((t
196              (error "ECASE expression failed."))))))
197
198   (defmacro and (&rest forms)
199     (cond
200       ((null forms)
201        t)
202       ((null (cdr forms))
203        (car forms))
204       (t
205        `(if ,(car forms)
206             (and ,@(cdr forms))
207             nil))))
208
209   (defmacro or (&rest forms)
210     (cond
211       ((null forms)
212        nil)
213       ((null (cdr forms))
214        (car forms))
215       (t
216        (let ((g (gensym)))
217          `(let ((,g ,(car forms)))
218             (if ,g ,g (or ,@(cdr forms))))))))
219
220   (defmacro prog1 (form &body body)
221     (let ((value (gensym)))
222       `(let ((,value ,form))
223          ,@body
224          ,value)))
225
226   (defmacro prog2 (form1 result &body body)
227     `(prog1 (progn ,form1 ,result) ,@body)))
228
229
230 ;;; This couple of helper functions will be defined in both Common
231 ;;; Lisp and in Ecmalisp.
232 (defun ensure-list (x)
233   (if (listp x)
234       x
235       (list x)))
236
237 (defun !reduce (func list initial)
238   (if (null list)
239       initial
240       (!reduce func
241                (cdr list)
242                (funcall func initial (car list)))))
243
244 ;;; Go on growing the Lisp language in Ecmalisp, with more high
245 ;;; level utilities as well as correct versions of other
246 ;;; constructions.
247 #+ecmalisp
248 (progn
249   (defun + (&rest args)
250     (let ((r 0))
251       (dolist (x args r)
252         (incf r x))))
253
254   (defun - (x &rest others)
255     (if (null others)
256         (- x)
257         (let ((r x))
258           (dolist (y others r)
259             (decf r y)))))
260
261   (defun append-two (list1 list2)
262     (if (null list1)
263         list2
264         (cons (car list1)
265               (append (cdr list1) list2))))
266
267   (defun append (&rest lists)
268     (!reduce #'append-two lists '()))
269
270   (defun revappend (list1 list2)
271     (while list1
272       (push (car list1) list2)
273       (setq list1 (cdr list1)))
274     list2)
275
276   (defun reverse (list)
277     (revappend list '()))
278
279   (defmacro psetq (&rest pairs)
280     (let ( ;; For each pair, we store here a list of the form
281           ;; (VARIABLE GENSYM VALUE).
282           (assignments '()))
283       (while t
284         (cond
285           ((null pairs) (return))
286           ((null (cdr pairs))
287            (error "Odd paris in PSETQ"))
288           (t
289            (let ((variable (car pairs))
290                  (value (cadr pairs)))
291              (push `(,variable ,(gensym) ,value)  assignments)
292              (setq pairs (cddr pairs))))))
293       (setq assignments (reverse assignments))
294       ;;
295       `(let ,(mapcar #'cdr assignments)
296          (setq ,@(!reduce #'append (mapcar #'butlast assignments) '())))))
297
298   (defun list-length (list)
299     (let ((l 0))
300       (while (not (null list))
301         (incf l)
302         (setq list (cdr list)))
303       l))
304
305   (defun length (seq)
306     (cond
307       ((stringp seq)
308        (string-length seq))
309       ((arrayp seq)
310        (oget seq "length"))
311       ((listp seq)
312        (list-length seq))))
313
314   (defun concat-two (s1 s2)
315     (concat-two s1 s2))
316
317   (defun mapcar (func list)
318     (if (null list)
319         '()
320         (cons (funcall func (car list))
321               (mapcar func (cdr list)))))
322
323   (defun identity (x) x)
324
325   (defun copy-list (x)
326     (mapcar #'identity x))
327
328   (defun code-char (x) x)
329   (defun char-code (x) x)
330   (defun char= (x y) (= x y))
331
332   (defun integerp (x)
333     (and (numberp x) (= (floor x) x)))
334
335   (defun plusp (x) (< 0 x))
336   (defun minusp (x) (< x 0))
337
338   (defun listp (x)
339     (or (consp x) (null x)))
340
341   (defun nthcdr (n list)
342     (while (and (plusp n) list)
343       (setq n (1- n))
344       (setq list (cdr list)))
345     list)
346
347   (defun nth (n list)
348     (car (nthcdr n list)))
349
350   (defun last (x)
351     (while (consp (cdr x))
352       (setq x (cdr x)))
353     x)
354
355   (defun butlast (x)
356     (and (consp (cdr x))
357          (cons (car x) (butlast (cdr x)))))
358
359   (defun member (x list)
360     (while list
361       (when (eql x (car list))
362         (return list))
363       (setq list (cdr list))))
364
365   (defun remove (x list)
366     (cond
367       ((null list)
368        nil)
369       ((eql x (car list))
370        (remove x (cdr list)))
371       (t
372        (cons (car list) (remove x (cdr list))))))
373
374   (defun remove-if (func list)
375     (cond
376       ((null list)
377        nil)
378       ((funcall func (car list))
379        (remove-if func (cdr list)))
380       (t
381        (cons (car list) (remove-if func (cdr list))))))
382
383   (defun remove-if-not (func list)
384     (cond
385       ((null list)
386        nil)
387       ((funcall func (car list))
388        (cons (car list) (remove-if-not func (cdr list))))
389       (t
390        (remove-if-not func (cdr list)))))
391
392   (defun digit-char-p (x)
393     (if (and (<= #\0 x) (<= x #\9))
394         (- x #\0)
395         nil))
396
397   (defun subseq (seq a &optional b)
398     (cond
399       ((stringp seq)
400        (if b
401            (slice seq a b)
402            (slice seq a)))
403       (t
404        (error "Unsupported argument."))))
405
406   (defun parse-integer (string)
407     (let ((value 0)
408           (index 0)
409           (size (length string)))
410       (while (< index size)
411         (setq value (+ (* value 10) (digit-char-p (char string index))))
412         (incf index))
413       value))
414
415   (defun some (function seq)
416     (cond
417       ((stringp seq)
418        (let ((index 0)
419              (size (length seq)))
420          (while (< index size)
421            (when (funcall function (char seq index))
422              (return-from some t))
423            (incf index))
424          nil))
425       ((listp seq)
426        (dolist (x seq nil)
427          (when (funcall function x)
428            (return t))))
429       (t
430        (error "Unknown sequence."))))
431
432   (defun every (function seq)
433     (cond
434       ((stringp seq)
435        (let ((index 0)
436              (size (length seq)))
437          (while (< index size)
438            (unless (funcall function (char seq index))
439              (return-from every nil))
440            (incf index))
441          t))
442       ((listp seq)
443        (dolist (x seq t)
444          (unless (funcall function x)
445            (return))))
446       (t
447        (error "Unknown sequence."))))
448
449   (defun assoc (x alist)
450     (while alist
451       (if (eql x (caar alist))
452           (return)
453           (setq alist (cdr alist))))
454     (car alist))
455
456   (defun string (x)
457     (cond ((stringp x) x)
458           ((symbolp x) (symbol-name x))
459           (t (char-to-string x))))
460
461   (defun string= (s1 s2)
462     (equal s1 s2))
463
464   (defun fdefinition (x)
465     (cond
466       ((functionp x)
467        x)
468       ((symbolp x)
469        (symbol-function x))
470       (t
471        (error "Invalid function"))))
472
473   (defun disassemble (function)
474     (write-line (lambda-code (fdefinition function)))
475     nil)
476
477   (defun documentation (x type)
478     "Return the documentation of X. TYPE must be the symbol VARIABLE or FUNCTION."
479     (ecase type
480       (function
481        (let ((func (fdefinition x)))
482          (oget func "docstring")))
483       (variable
484        (unless (symbolp x)
485          (error "Wrong argument type! it should be a symbol"))
486        (oget x "vardoc"))))
487
488   ;; Packages
489
490   (defvar *package-list* nil)
491
492   (defun list-all-packages ()
493     *package-list*)
494
495   (defun make-package (name &optional use)
496     (let ((package (new))
497           (use (mapcar #'find-package-or-fail use)))
498       (oset package "packageName" name)
499       (oset package "symbols" (new))
500       (oset package "exports" (new))
501       (oset package "use" use)
502       (push package *package-list*)
503       package))
504
505   (defun packagep (x)
506     (and (objectp x) (in "symbols" x)))
507
508   (defun find-package (package-designator)
509     (when (packagep package-designator)
510       (return-from find-package package-designator))
511     (let ((name (string package-designator)))
512       (dolist (package *package-list*)
513         (when (string= (package-name package) name)
514           (return package)))))
515
516   (defun find-package-or-fail (package-designator)
517     (or (find-package package-designator)
518         (error "Package unknown.")))
519
520   (defun package-name (package-designator)
521     (let ((package (find-package-or-fail package-designator)))
522       (oget package "packageName")))
523
524   (defun %package-symbols (package-designator)
525     (let ((package (find-package-or-fail package-designator)))
526       (oget package "symbols")))
527
528   (defun package-use-list (package-designator)
529     (let ((package (find-package-or-fail package-designator)))
530       (oget package "use")))
531
532   (defun %package-external-symbols (package-designator)
533     (let ((package (find-package-or-fail package-designator)))
534       (oget package "exports")))
535
536   (defvar *common-lisp-package*
537     (make-package "CL"))
538
539   (defvar *user-package*
540     (make-package "CL-USER" (list *common-lisp-package*)))
541
542   (defvar *keyword-package*
543     (make-package "KEYWORD"))
544
545   (defun keywordp (x)
546     (and (symbolp x) (eq (symbol-package x) *keyword-package*)))
547
548   (defvar *package* *common-lisp-package*)
549
550   (defmacro in-package (package-designator)
551     `(eval-when-compile
552        (setq *package* (find-package-or-fail ,package-designator))))
553
554   ;; This function is used internally to initialize the CL package
555   ;; with the symbols built during bootstrap.
556   (defun %intern-symbol (symbol)
557     (let ((symbols (%package-symbols *common-lisp-package*)))
558       (oset symbol "package" *common-lisp-package*)
559       (oset symbols (symbol-name symbol) symbol)))
560
561   (defun %find-symbol (name package)
562     (let ((package (find-package-or-fail package)))
563       (let ((symbols (%package-symbols package)))
564         (if (in name symbols)
565             (cons (oget symbols name) t)
566             (dolist (used (package-use-list package) (cons nil nil))
567               (let ((exports (%package-external-symbols used)))
568                 (when (in name exports)
569                   (return-from %find-symbol
570                     (cons (oget exports name) t)))))))))
571
572   (defun find-symbol (name &optional (package *package*))
573     (car (%find-symbol name package)))
574
575   (defun intern (name &optional (package *package*))
576     (let ((package (find-package-or-fail package)))
577       (let ((result (%find-symbol name package)))
578         (if (cdr result)
579             (car result)
580             (let ((symbols (%package-symbols package)))
581               (oget symbols name)
582               (let ((symbol (make-symbol name)))
583                 (oset symbol "package" package)
584                 (when (eq package *keyword-package*)
585                   (oset symbol "value" symbol)
586                   (export (list symbol) package))
587                 (oset symbols name symbol)))))))
588
589   (defun symbol-package (symbol)
590     (unless (symbolp symbol)
591       (error "it is not a symbol"))
592     (oget symbol "package"))
593
594   (defun export (symbols &optional (package *package*))
595     (let ((exports (%package-external-symbols package)))
596       (dolist (symb symbols t)
597         (oset exports (symbol-name symb) symb))))
598
599   (defun get-universal-time ()
600     (+ (get-unix-time) 2208988800)))
601
602
603 ;;; The compiler offers some primitives and special forms which are
604 ;;; not found in Common Lisp, for instance, while. So, we grow Common
605 ;;; Lisp a bit to it can execute the rest of the file.
606 #+common-lisp
607 (progn
608   (defmacro while (condition &body body)
609     `(do ()
610          ((not ,condition))
611        ,@body))
612
613   (defmacro eval-when-compile (&body body)
614     `(eval-when (:compile-toplevel :load-toplevel :execute)
615        ,@body))
616
617   (defun concat-two (s1 s2)
618     (concatenate 'string s1 s2))
619
620   (defun setcar (cons new)
621     (setf (car cons) new))
622   (defun setcdr (cons new)
623     (setf (cdr cons) new))
624
625   (defun aset (array idx value)
626     (setf (aref array idx) value)))
627
628 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
629 ;;; from here, this code will compile on both. We define some helper
630 ;;; functions now for string manipulation and so on. They will be
631 ;;; useful in the compiler, mostly.
632
633 (defvar *newline* (string (code-char 10)))
634
635 (defun concat (&rest strs)
636   (!reduce #'concat-two strs ""))
637
638 (defmacro concatf (variable &body form)
639   `(setq ,variable (concat ,variable (progn ,@form))))
640
641 ;;; Concatenate a list of strings, with a separator
642 (defun join (list &optional (separator ""))
643   (cond
644     ((null list)
645      "")
646     ((null (cdr list))
647      (car list))
648     (t
649      (concat (car list)
650              separator
651              (join (cdr list) separator)))))
652
653 (defun join-trailing (list &optional (separator ""))
654   (if (null list)
655       ""
656       (concat (car list) separator (join-trailing (cdr list) separator))))
657
658 (defun mapconcat (func list)
659   (join (mapcar func list)))
660
661 (defun vector-to-list (vector)
662   (let ((list nil)
663         (size (length vector)))
664     (dotimes (i size (reverse list))
665       (push (aref vector i) list))))
666
667 (defun list-to-vector (list)
668   (let ((v (make-array (length list)))
669         (i 0))
670     (dolist (x list v)
671       (aset v i x)
672       (incf i))))
673
674 #+ecmalisp
675 (progn
676   (defun values-list (list)
677     (values-array (list-to-vector list)))
678
679   (defun values (&rest args)
680     (values-list args))
681
682   (defmacro multiple-value-bind (variables value-from &body body)
683     `(multiple-value-call (lambda (&optional ,@variables &rest ,(gensym))
684                             ,@body)
685        ,value-from))
686
687   (defmacro multiple-value-list (value-from)
688     `(multiple-value-call #'list ,value-from)))
689
690
691 ;;; Like CONCAT, but prefix each line with four spaces. Two versions
692 ;;; of this function are available, because the Ecmalisp version is
693 ;;; very slow and bootstraping was annoying.
694
695 #+ecmalisp
696 (defun indent (&rest string)
697   (let ((input (join string)))
698     (let ((output "")
699           (index 0)
700           (size (length input)))
701       (when (plusp (length input)) (concatf output "    "))
702       (while (< index size)
703         (let ((str
704                (if (and (char= (char input index) #\newline)
705                         (< index (1- size))
706                         (not (char= (char input (1+ index)) #\newline)))
707                    (concat (string #\newline) "    ")
708                    (string (char input index)))))
709           (concatf output str))
710         (incf index))
711       output)))
712
713 #+common-lisp
714 (defun indent (&rest string)
715   (with-output-to-string (*standard-output*)
716     (with-input-from-string (input (join string))
717       (loop
718          for line = (read-line input nil)
719          while line
720          do (write-string "    ")
721          do (write-line line)))))
722
723
724 (defun integer-to-string (x)
725   (cond
726     ((zerop x)
727      "0")
728     ((minusp x)
729      (concat "-" (integer-to-string (- 0 x))))
730     (t
731      (let ((digits nil))
732        (while (not (zerop x))
733          (push (mod x 10) digits)
734          (setq x (truncate x 10)))
735        (join (mapcar (lambda (d) (string (char "0123456789" d)))
736                      digits))))))
737
738
739 ;;; Wrap X with a Javascript code to convert the result from
740 ;;; Javascript generalized booleans to T or NIL.
741 (defun js!bool (x)
742   (concat "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
743
744 ;;; Concatenate the arguments and wrap them with a self-calling
745 ;;; Javascript anonymous function. It is used to make some Javascript
746 ;;; statements valid expressions and provide a private scope as well.
747 ;;; It could be defined as function, but we could do some
748 ;;; preprocessing in the future.
749 (defmacro js!selfcall (&body body)
750   `(concat "(function(){" *newline* (indent ,@body) "})()"))
751
752
753 ;;; Printer
754
755 #+ecmalisp
756 (progn
757   (defun prin1-to-string (form)
758     (cond
759       ((symbolp form)
760        (if (cdr (%find-symbol (symbol-name form) *package*))
761            (symbol-name form)
762            (let ((package (symbol-package form))
763                  (name (symbol-name form)))
764              (concat (cond
765                        ((null package) "#")
766                        ((eq package (find-package "KEYWORD")) "")
767                        (t (package-name package)))
768                      ":" name))))
769       ((integerp form) (integer-to-string form))
770       ((stringp form) (concat "\"" (escape-string form) "\""))
771       ((functionp form)
772        (let ((name (oget form "fname")))
773          (if name
774              (concat "#<FUNCTION " name ">")
775              (concat "#<FUNCTION>"))))
776       ((listp form)
777        (concat "("
778                (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
779                (let ((last (last form)))
780                  (if (null (cdr last))
781                      (prin1-to-string (car last))
782                      (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
783                ")"))
784       ((arrayp form)
785        (concat "#" (prin1-to-string (vector-to-list form))))
786       ((packagep form)
787        (concat "#<PACKAGE " (package-name form) ">"))))
788
789   (defun write-line (x)
790     (write-string x)
791     (write-string *newline*)
792     x)
793
794   (defun warn (string)
795     (write-string "WARNING: ")
796     (write-line string))
797
798   (defun print (x)
799     (write-line (prin1-to-string x))
800     x))
801
802
803 ;;;; Reader
804
805 ;;; The Lisp reader, parse strings and return Lisp objects. The main
806 ;;; entry points are `ls-read' and `ls-read-from-string'.
807
808 (defun make-string-stream (string)
809   (cons string 0))
810
811 (defun %peek-char (stream)
812   (and (< (cdr stream) (length (car stream)))
813        (char (car stream) (cdr stream))))
814
815 (defun %read-char (stream)
816   (and (< (cdr stream) (length (car stream)))
817        (prog1 (char (car stream) (cdr stream))
818          (setcdr stream (1+ (cdr stream))))))
819
820 (defun whitespacep (ch)
821   (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
822
823 (defun skip-whitespaces (stream)
824   (let (ch)
825     (setq ch (%peek-char stream))
826     (while (and ch (whitespacep ch))
827       (%read-char stream)
828       (setq ch (%peek-char stream)))))
829
830 (defun terminalp (ch)
831   (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
832
833 (defun read-until (stream func)
834   (let ((string "")
835         (ch))
836     (setq ch (%peek-char stream))
837     (while (and ch (not (funcall func ch)))
838       (setq string (concat string (string ch)))
839       (%read-char stream)
840       (setq ch (%peek-char stream)))
841     string))
842
843 (defun skip-whitespaces-and-comments (stream)
844   (let (ch)
845     (skip-whitespaces stream)
846     (setq ch (%peek-char stream))
847     (while (and ch (char= ch #\;))
848       (read-until stream (lambda (x) (char= x #\newline)))
849       (skip-whitespaces stream)
850       (setq ch (%peek-char stream)))))
851
852 (defun %read-list (stream)
853   (skip-whitespaces-and-comments stream)
854   (let ((ch (%peek-char stream)))
855     (cond
856       ((null ch)
857        (error "Unspected EOF"))
858       ((char= ch #\))
859        (%read-char stream)
860        nil)
861       ((char= ch #\.)
862        (%read-char stream)
863        (prog1 (ls-read stream)
864          (skip-whitespaces-and-comments stream)
865          (unless (char= (%read-char stream) #\))
866            (error "')' was expected."))))
867       (t
868        (cons (ls-read stream) (%read-list stream))))))
869
870 (defun read-string (stream)
871   (let ((string "")
872         (ch nil))
873     (setq ch (%read-char stream))
874     (while (not (eql ch #\"))
875       (when (null ch)
876         (error "Unexpected EOF"))
877       (when (eql ch #\\)
878         (setq ch (%read-char stream)))
879       (setq string (concat string (string ch)))
880       (setq ch (%read-char stream)))
881     string))
882
883 (defun read-sharp (stream)
884   (%read-char stream)
885   (ecase (%read-char stream)
886     (#\'
887      (list 'function (ls-read stream)))
888     (#\( (list-to-vector (%read-list stream)))
889     (#\: (make-symbol (string-upcase (read-until stream #'terminalp))))
890     (#\\
891      (let ((cname
892             (concat (string (%read-char stream))
893                     (read-until stream #'terminalp))))
894        (cond
895          ((string= cname "space") (char-code #\space))
896          ((string= cname "tab") (char-code #\tab))
897          ((string= cname "newline") (char-code #\newline))
898          (t (char-code (char cname 0))))))
899     (#\+
900      (let ((feature (read-until stream #'terminalp)))
901        (cond
902          ((string= feature "common-lisp")
903           (ls-read stream)              ;ignore
904           (ls-read stream))
905          ((string= feature "ecmalisp")
906           (ls-read stream))
907          (t
908           (error "Unknown reader form.")))))))
909
910 ;;; Parse a string of the form NAME, PACKAGE:NAME or
911 ;;; PACKAGE::NAME and return the name. If the string is of the
912 ;;; form 1) or 3), but the symbol does not exist, it will be created
913 ;;; and interned in that package.
914 (defun read-symbol (string)
915   (let ((size (length string))
916         package name internalp index)
917     (setq index 0)
918     (while (and (< index size)
919                 (not (char= (char string index) #\:)))
920       (incf index))
921     (cond
922       ;; No package prefix
923       ((= index size)
924        (setq name string)
925        (setq package *package*)
926        (setq internalp t))
927       (t
928        ;; Package prefix
929        (if (zerop index)
930            (setq package "KEYWORD")
931            (setq package (string-upcase (subseq string 0 index))))
932        (incf index)
933        (when (char= (char string index) #\:)
934          (setq internalp t)
935          (incf index))
936        (setq name (subseq string index))))
937     ;; Canonalize symbol name and package
938     (setq name (string-upcase name))
939     (setq package (find-package package))
940     ;; TODO: PACKAGE:SYMBOL should signal error if SYMBOL is not an
941     ;; external symbol from PACKAGE.
942     (if (or internalp (eq package (find-package "KEYWORD")))
943         (intern name package)
944         (find-symbol name package))))
945
946 (defvar *eof* (gensym))
947 (defun ls-read (stream)
948   (skip-whitespaces-and-comments stream)
949   (let ((ch (%peek-char stream)))
950     (cond
951       ((or (null ch) (char= ch #\)))
952        *eof*)
953       ((char= ch #\()
954        (%read-char stream)
955        (%read-list stream))
956       ((char= ch #\')
957        (%read-char stream)
958        (list 'quote (ls-read stream)))
959       ((char= ch #\`)
960        (%read-char stream)
961        (list 'backquote (ls-read stream)))
962       ((char= ch #\")
963        (%read-char stream)
964        (read-string stream))
965       ((char= ch #\,)
966        (%read-char stream)
967        (if (eql (%peek-char stream) #\@)
968            (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
969            (list 'unquote (ls-read stream))))
970       ((char= ch #\#)
971        (read-sharp stream))
972       (t
973        (let ((string (read-until stream #'terminalp)))
974          (if (every #'digit-char-p string)
975              (parse-integer string)
976              (read-symbol string)))))))
977
978 (defun ls-read-from-string (string)
979   (ls-read (make-string-stream string)))
980
981
982 ;;;; Compiler
983
984 ;;; Translate the Lisp code to Javascript. It will compile the special
985 ;;; forms. Some primitive functions are compiled as special forms
986 ;;; too. The respective real functions are defined in the target (see
987 ;;; the beginning of this file) as well as some primitive functions.
988
989 ;;; If the special variable `*multiple-value-p*' is NON-NIL, then the
990 ;;; compilation of the current form is allowed to return multiple
991 ;;; values, using the VALUES variable.
992 (defvar *multiple-value-p* nil)
993
994 (defvar *compilation-unit-checks* '())
995
996 (defun make-binding (name type value &optional declarations)
997   (list name type value declarations))
998
999 (defun binding-name (b) (first b))
1000 (defun binding-type (b) (second b))
1001 (defun binding-value (b) (third b))
1002 (defun binding-declarations (b) (fourth b))
1003
1004 (defun set-binding-value (b value)
1005   (setcar (cddr b) value))
1006
1007 (defun set-binding-declarations (b value)
1008   (setcar (cdddr b) value))
1009
1010 (defun push-binding-declaration (decl b)
1011   (set-binding-declarations b (cons decl (binding-declarations b))))
1012
1013
1014 (defun make-lexenv ()
1015   (list nil nil nil nil))
1016
1017 (defun copy-lexenv (lexenv)
1018   (copy-list lexenv))
1019
1020 (defun push-to-lexenv (binding lexenv namespace)
1021   (ecase namespace
1022     (variable   (setcar        lexenv  (cons binding (car lexenv))))
1023     (function   (setcar   (cdr lexenv) (cons binding (cadr lexenv))))
1024     (block      (setcar  (cddr lexenv) (cons binding (caddr lexenv))))
1025     (gotag      (setcar (cdddr lexenv) (cons binding (cadddr lexenv))))))
1026
1027 (defun extend-lexenv (bindings lexenv namespace)
1028   (let ((env (copy-lexenv lexenv)))
1029     (dolist (binding (reverse bindings) env)
1030       (push-to-lexenv binding env namespace))))
1031
1032 (defun lookup-in-lexenv (name lexenv namespace)
1033   (assoc name (ecase namespace
1034                 (variable (first lexenv))
1035                 (function (second lexenv))
1036                 (block (third lexenv))
1037                 (gotag (fourth lexenv)))))
1038
1039 (defvar *environment* (make-lexenv))
1040
1041 (defvar *variable-counter* 0)
1042 (defun gvarname (symbol)
1043   (concat "v" (integer-to-string (incf *variable-counter*))))
1044
1045 (defun translate-variable (symbol)
1046   (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
1047
1048 (defun extend-local-env (args)
1049   (let ((new (copy-lexenv *environment*)))
1050     (dolist (symbol args new)
1051       (let ((b (make-binding symbol 'lexical-variable (gvarname symbol))))
1052         (push-to-lexenv b new 'variable)))))
1053
1054 ;;; Toplevel compilations
1055 (defvar *toplevel-compilations* nil)
1056
1057 (defun toplevel-compilation (string)
1058   (push string *toplevel-compilations*))
1059
1060 (defun null-or-empty-p (x)
1061   (zerop (length x)))
1062
1063 (defun get-toplevel-compilations ()
1064   (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
1065
1066 (defun %compile-defmacro (name lambda)
1067   (toplevel-compilation (ls-compile `',name))
1068   (push-to-lexenv (make-binding name 'macro lambda) *environment* 'function))
1069
1070 (defun global-binding (name type namespace)
1071   (or (lookup-in-lexenv name *environment* namespace)
1072       (let ((b (make-binding name type nil)))
1073         (push-to-lexenv b *environment* namespace)
1074         b)))
1075
1076 (defun claimp (symbol namespace claim)
1077   (let ((b (lookup-in-lexenv symbol *environment* namespace)))
1078     (and b (member claim (binding-declarations b)))))
1079
1080 (defun !proclaim (decl)
1081   (case (car decl)
1082     (special
1083      (dolist (name (cdr decl))
1084        (let ((b (global-binding name 'variable 'variable)))
1085          (push-binding-declaration 'special b))))
1086     (notinline
1087      (dolist (name (cdr decl))
1088        (let ((b (global-binding name 'function 'function)))
1089          (push-binding-declaration 'notinline b))))
1090     (constant
1091      (dolist (name (cdr decl))
1092        (let ((b (global-binding name 'variable 'variable)))
1093          (push-binding-declaration 'constant b))))))
1094
1095 #+ecmalisp
1096 (fset 'proclaim #'!proclaim)
1097
1098 ;;; Special forms
1099
1100 (defvar *compilations* nil)
1101
1102 (defmacro define-compilation (name args &body body)
1103   ;; Creates a new primitive `name' with parameters args and
1104   ;; @body. The body can access to the local environment through the
1105   ;; variable *ENVIRONMENT*.
1106   `(push (list ',name (lambda ,args (block ,name ,@body)))
1107          *compilations*))
1108
1109 (define-compilation if (condition true false)
1110   (concat "(" (ls-compile condition) " !== " (ls-compile nil)
1111           " ? " (ls-compile true *multiple-value-p*)
1112           " : " (ls-compile false *multiple-value-p*)
1113           ")"))
1114
1115 (defvar *lambda-list-keywords* '(&optional &rest))
1116
1117 (defun list-until-keyword (list)
1118   (if (or (null list) (member (car list) *lambda-list-keywords*))
1119       nil
1120       (cons (car list) (list-until-keyword (cdr list)))))
1121
1122 (defun lambda-list-required-arguments (lambda-list)
1123   (list-until-keyword lambda-list))
1124
1125 (defun lambda-list-optional-arguments-with-default (lambda-list)
1126   (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
1127
1128 (defun lambda-list-optional-arguments (lambda-list)
1129   (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
1130
1131 (defun lambda-list-rest-argument (lambda-list)
1132   (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
1133     (when (cdr rest)
1134       (error "Bad lambda-list"))
1135     (car rest)))
1136
1137 (defun lambda-docstring-wrapper (docstring &rest strs)
1138   (if docstring
1139       (js!selfcall
1140         "var func = " (join strs) ";" *newline*
1141         "func.docstring = '" docstring "';" *newline*
1142         "return func;" *newline*)
1143       (join strs)))
1144
1145 (defun lambda-check-argument-count
1146     (n-required-arguments n-optional-arguments rest-p)
1147   ;; Note: Remember that we assume that the number of arguments of a
1148   ;; call is at least 1 (the values argument).
1149   (let ((min (1+ n-required-arguments))
1150         (max (if rest-p 'n/a (+ 1 n-required-arguments n-optional-arguments))))
1151     (block nil
1152       ;; Special case: a positive exact number of arguments.
1153       (when (and (< 1 min) (eql min max))
1154         (return (concat "checkArgs(arguments, " (integer-to-string min) ");" *newline*)))
1155       ;; General case:
1156       (concat
1157        (if (< 1 min)
1158            (concat "checkArgsAtLeast(arguments, " (integer-to-string min) ");" *newline*)
1159            "")
1160        (if (numberp max)
1161            (concat "checkArgsAtMost(arguments, " (integer-to-string max) ");" *newline*)
1162            "")))))
1163
1164 (define-compilation lambda (lambda-list &rest body)
1165   (let ((required-arguments (lambda-list-required-arguments lambda-list))
1166         (optional-arguments (lambda-list-optional-arguments lambda-list))
1167         (rest-argument (lambda-list-rest-argument lambda-list))
1168         documentation)
1169     ;; Get the documentation string for the lambda function
1170     (when (and (stringp (car body))
1171                (not (null (cdr body))))
1172       (setq documentation (car body))
1173       (setq body (cdr body)))
1174     (let ((n-required-arguments (length required-arguments))
1175           (n-optional-arguments (length optional-arguments))
1176           (*environment* (extend-local-env
1177                           (append (ensure-list rest-argument)
1178                                   required-arguments
1179                                   optional-arguments))))
1180       (lambda-docstring-wrapper
1181        documentation
1182        "(function ("
1183        (join (cons "values"
1184                    (mapcar #'translate-variable
1185                            (append required-arguments optional-arguments)))
1186              ",")
1187        "){" *newline*
1188        (indent
1189         ;; Check number of arguments
1190         (lambda-check-argument-count n-required-arguments
1191                                      n-optional-arguments
1192                                      rest-argument)
1193         ;; Optional arguments
1194         (if optional-arguments
1195             (concat "switch(arguments.length-1){" *newline*
1196                     (let ((optional-and-defaults
1197                            (lambda-list-optional-arguments-with-default lambda-list))
1198                           (cases nil)
1199                           (idx 0))
1200                       (progn
1201                         (while (< idx n-optional-arguments)
1202                           (let ((arg (nth idx optional-and-defaults)))
1203                             (push (concat "case "
1204                                           (integer-to-string (+ idx n-required-arguments)) ":" *newline*
1205                                           (translate-variable (car arg))
1206                                           "="
1207                                           (ls-compile (cadr arg))
1208                                           ";" *newline*)
1209                                   cases)
1210                             (incf idx)))
1211                         (push (concat "default: break;" *newline*) cases)
1212                         (join (reverse cases))))
1213                     "}" *newline*)
1214             "")
1215         ;; &rest/&body argument
1216         (if rest-argument
1217             (let ((js!rest (translate-variable rest-argument)))
1218               (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
1219                       "for (var i = arguments.length-1; i>="
1220                       (integer-to-string (+ 1 n-required-arguments n-optional-arguments))
1221                       "; i--)" *newline*
1222                       (indent js!rest " = "
1223                               "{car: arguments[i], cdr: ") js!rest "};"
1224                       *newline*))
1225             "")
1226         ;; Body
1227         (let ((*multiple-value-p* t)) (ls-compile-block body t)))
1228        "})"))))
1229
1230
1231 (defun setq-pair (var val)
1232   (let ((b (lookup-in-lexenv var *environment* 'variable)))
1233     (if (eq (binding-type b) 'lexical-variable)
1234         (concat (binding-value b) " = " (ls-compile val))
1235         (ls-compile `(set ',var ,val)))))
1236
1237 (define-compilation setq (&rest pairs)
1238   (let ((result ""))
1239     (while t
1240       (cond
1241         ((null pairs) (return))
1242         ((null (cdr pairs))
1243          (error "Odd paris in SETQ"))
1244         (t
1245          (concatf result
1246            (concat (setq-pair (car pairs) (cadr pairs))
1247                    (if (null (cddr pairs)) "" ", ")))
1248          (setq pairs (cddr pairs)))))
1249     (concat "(" result ")")))
1250
1251 ;;; FFI Variable accessors
1252 (define-compilation js-vref (var)
1253   var)
1254
1255 (define-compilation js-vset (var val)
1256   (concat "(" var " = " (ls-compile val) ")"))
1257
1258
1259
1260 ;;; Literals
1261 (defun escape-string (string)
1262   (let ((output "")
1263         (index 0)
1264         (size (length string)))
1265     (while (< index size)
1266       (let ((ch (char string index)))
1267         (when (or (char= ch #\") (char= ch #\\))
1268           (setq output (concat output "\\")))
1269         (when (or (char= ch #\newline))
1270           (setq output (concat output "\\"))
1271           (setq ch #\n))
1272         (setq output (concat output (string ch))))
1273       (incf index))
1274     output))
1275
1276
1277 (defvar *literal-symbols* nil)
1278 (defvar *literal-counter* 0)
1279
1280 (defun genlit ()
1281   (concat "l" (integer-to-string (incf *literal-counter*))))
1282
1283 (defun literal (sexp &optional recursive)
1284   (cond
1285     ((integerp sexp) (integer-to-string sexp))
1286     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1287     ((symbolp sexp)
1288      (or (cdr (assoc sexp *literal-symbols*))
1289          (let ((v (genlit))
1290                (s #+common-lisp (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1291                   #+ecmalisp
1292                   (let ((package (symbol-package sexp)))
1293                     (if (null package)
1294                         (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1295                         (ls-compile `(intern ,(symbol-name sexp) ,(package-name package)))))))
1296            (push (cons sexp v) *literal-symbols*)
1297            (toplevel-compilation (concat "var " v " = " s))
1298            v)))
1299     ((consp sexp)
1300      (let* ((head (butlast sexp))
1301             (tail (last sexp))
1302             (c (concat "QIList("
1303                        (join-trailing (mapcar (lambda (x) (literal x t)) head) ",")
1304                        (literal (car tail) t)
1305                        ","
1306                        (literal (cdr tail) t)
1307                        ")")))
1308        (if recursive
1309            c
1310            (let ((v (genlit)))
1311              (toplevel-compilation (concat "var " v " = " c))
1312              v))))
1313     ((arrayp sexp)
1314      (let ((elements (vector-to-list sexp)))
1315        (let ((c (concat "[" (join (mapcar #'literal elements) ", ") "]")))
1316          (if recursive
1317              c
1318              (let ((v (genlit)))
1319                (toplevel-compilation (concat "var " v " = " c))
1320                v)))))))
1321
1322 (define-compilation quote (sexp)
1323   (literal sexp))
1324
1325 (define-compilation %while (pred &rest body)
1326   (js!selfcall
1327     "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1328     (indent (ls-compile-block body))
1329     "}"
1330     "return " (ls-compile nil) ";" *newline*))
1331
1332 (define-compilation function (x)
1333   (cond
1334     ((and (listp x) (eq (car x) 'lambda))
1335      (ls-compile x))
1336     ((symbolp x)
1337      (ls-compile `(symbol-function ',x)))))
1338
1339 (define-compilation eval-when-compile (&rest body)
1340   (eval (cons 'progn body))
1341   nil)
1342
1343 (defmacro define-transformation (name args form)
1344   `(define-compilation ,name ,args
1345      (ls-compile ,form)))
1346
1347 (define-compilation progn (&rest body)
1348   (if (null (cdr body))
1349       (ls-compile (car body) *multiple-value-p*)
1350       (js!selfcall (ls-compile-block body t))))
1351
1352 (defun special-variable-p (x)
1353   (and (claimp x 'variable 'special) t))
1354
1355 ;;; Wrap CODE to restore the symbol values of the dynamic
1356 ;;; bindings. BINDINGS is a list of pairs of the form
1357 ;;; (SYMBOL . PLACE),  where PLACE is a Javascript variable
1358 ;;; name to initialize the symbol value and where to stored
1359 ;;; the old value.
1360 (defun let-binding-wrapper (bindings body)
1361   (when (null bindings)
1362     (return-from let-binding-wrapper body))
1363   (concat
1364    "try {" *newline*
1365    (indent "var tmp;" *newline*
1366            (mapconcat
1367             (lambda (b)
1368               (let ((s (ls-compile `(quote ,(car b)))))
1369                 (concat "tmp = " s ".value;" *newline*
1370                         s ".value = " (cdr b) ";" *newline*
1371                         (cdr b) " = tmp;" *newline*)))
1372             bindings)
1373            body *newline*)
1374    "}" *newline*
1375    "finally {"  *newline*
1376    (indent
1377     (mapconcat (lambda (b)
1378                  (let ((s (ls-compile `(quote ,(car b)))))
1379                    (concat s ".value" " = " (cdr b) ";" *newline*)))
1380                bindings))
1381    "}" *newline*))
1382
1383 (define-compilation let (bindings &rest body)
1384   (let* ((bindings (mapcar #'ensure-list bindings))
1385          (variables (mapcar #'first bindings))
1386          (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
1387          (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
1388          (dynamic-bindings))
1389     (concat "(function("
1390             (join (mapcar (lambda (x)
1391                             (if (special-variable-p x)
1392                                 (let ((v (gvarname x)))
1393                                   (push (cons x v) dynamic-bindings)
1394                                   v)
1395                                 (translate-variable x)))
1396                           variables)
1397                   ",")
1398             "){" *newline*
1399             (let ((body (ls-compile-block body t)))
1400               (indent (let-binding-wrapper dynamic-bindings body)))
1401             "})(" (join cvalues ",") ")")))
1402
1403
1404 ;;; Return the code to initialize BINDING, and push it extending the
1405 ;;; current lexical environment if the variable is special.
1406 (defun let*-initialize-value (binding)
1407   (let ((var (first binding))
1408         (value (second binding)))
1409     (if (special-variable-p var)
1410         (concat (ls-compile `(setq ,var ,value)) ";" *newline*)
1411         (let* ((v (gvarname var))
1412                (b (make-binding var 'variable v)))
1413           (prog1 (concat "var " v " = " (ls-compile value) ";" *newline*)
1414             (push-to-lexenv b *environment* 'variable))))))
1415
1416 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
1417 ;;; DOES NOT generate code to initialize the value of the symbols,
1418 ;;; unlike let-binding-wrapper.
1419 (defun let*-binding-wrapper (symbols body)
1420   (when (null symbols)
1421     (return-from let*-binding-wrapper body))
1422   (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
1423                        (remove-if-not #'special-variable-p symbols))))
1424     (concat
1425      "try {" *newline*
1426      (indent
1427       (mapconcat (lambda (b)
1428                    (let ((s (ls-compile `(quote ,(car b)))))
1429                      (concat "var " (cdr b) " = " s ".value;" *newline*)))
1430                  store)
1431       body)
1432      "}" *newline*
1433      "finally {" *newline*
1434      (indent
1435       (mapconcat (lambda (b)
1436                    (let ((s (ls-compile `(quote ,(car b)))))
1437                      (concat s ".value" " = " (cdr b) ";" *newline*)))
1438                  store))
1439      "}" *newline*)))
1440
1441 (define-compilation let* (bindings &rest body)
1442   (let ((bindings (mapcar #'ensure-list bindings))
1443         (*environment* (copy-lexenv *environment*)))
1444     (js!selfcall
1445       (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
1446             (body (concat (mapconcat #'let*-initialize-value bindings)
1447                           (ls-compile-block body t))))
1448         (let*-binding-wrapper specials body)))))
1449
1450
1451 (defvar *block-counter* 0)
1452
1453 (define-compilation block (name &rest body)
1454   (let* ((tr (integer-to-string (incf *block-counter*)))
1455          (b (make-binding name 'block tr))
1456          (*environment* (extend-lexenv (list b) *environment* 'block))
1457          (cbody (ls-compile-block body t)))
1458     (if (member 'used (binding-declarations b))
1459         (js!selfcall
1460           "try {" *newline*
1461           (indent cbody)
1462           "}" *newline*
1463           "catch (cf){" *newline*
1464           "    if (cf.type == 'block' && cf.id == " tr ")" *newline*
1465           "        return cf.value;" *newline*
1466           "    else" *newline*
1467           "        throw cf;" *newline*
1468           "}" *newline*)
1469         (js!selfcall
1470           (indent cbody)))))
1471
1472 (define-compilation return-from (name &optional value)
1473   (let ((b (lookup-in-lexenv name *environment* 'block)))
1474     (when (null b)
1475       (error (concat "Unknown block `" (symbol-name name) "'.")))
1476     (push-binding-declaration 'used b)
1477     (js!selfcall
1478       "throw ({"
1479       "type: 'block', "
1480       "id: " (binding-value b) ", "
1481       "value: " (ls-compile value) ", "
1482       "message: 'Return from unknown block " (symbol-name name) ".'"
1483       "})")))
1484
1485 (define-compilation catch (id &rest body)
1486   (js!selfcall
1487     "var id = " (ls-compile id) ";" *newline*
1488     "try {" *newline*
1489     (indent "return " (ls-compile `(progn ,@body))
1490             ";" *newline*)
1491     "}" *newline*
1492     "catch (cf){" *newline*
1493     "    if (cf.type == 'catch' && cf.id == id)" *newline*
1494     "        return cf.value;" *newline*
1495     "    else" *newline*
1496     "        throw cf;" *newline*
1497     "}" *newline*))
1498
1499 (define-compilation throw (id value)
1500   (js!selfcall
1501     "throw ({"
1502     "type: 'catch', "
1503     "id: " (ls-compile id) ", "
1504     "value: " (ls-compile value) ", "
1505     "message: 'Throw uncatched.'"
1506     "})"))
1507
1508
1509 (defvar *tagbody-counter* 0)
1510 (defvar *go-tag-counter* 0)
1511
1512 (defun go-tag-p (x)
1513   (or (integerp x) (symbolp x)))
1514
1515 (defun declare-tagbody-tags (tbidx body)
1516   (let ((bindings
1517          (mapcar (lambda (label)
1518                    (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1519                      (make-binding label 'gotag (list tbidx tagidx))))
1520                  (remove-if-not #'go-tag-p body))))
1521     (extend-lexenv bindings *environment* 'gotag)))
1522
1523 (define-compilation tagbody (&rest body)
1524   ;; Ignore the tagbody if it does not contain any go-tag. We do this
1525   ;; because 1) it is easy and 2) many built-in forms expand to a
1526   ;; implicit tagbody, so we save some space.
1527   (unless (some #'go-tag-p body)
1528     (return-from tagbody (ls-compile `(progn ,@body nil))))
1529   ;; The translation assumes the first form in BODY is a label
1530   (unless (go-tag-p (car body))
1531     (push (gensym "START") body))
1532   ;; Tagbody compilation
1533   (let ((tbidx (integer-to-string *tagbody-counter*)))
1534     (let ((*environment* (declare-tagbody-tags tbidx body))
1535           initag)
1536       (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1537         (setq initag (second (binding-value b))))
1538       (js!selfcall
1539         "var tagbody_" tbidx " = " initag ";" *newline*
1540         "tbloop:" *newline*
1541         "while (true) {" *newline*
1542         (indent "try {" *newline*
1543                 (indent (let ((content ""))
1544                           (concat "switch(tagbody_" tbidx "){" *newline*
1545                                   "case " initag ":" *newline*
1546                                   (dolist (form (cdr body) content)
1547                                     (concatf content
1548                                       (if (not (go-tag-p form))
1549                                           (indent (ls-compile form) ";" *newline*)
1550                                           (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1551                                             (concat "case " (second (binding-value b)) ":" *newline*)))))
1552                                   "default:" *newline*
1553                                   "    break tbloop;" *newline*
1554                                   "}" *newline*)))
1555                 "}" *newline*
1556                 "catch (jump) {" *newline*
1557                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1558                 "        tagbody_" tbidx " = jump.label;" *newline*
1559                 "    else" *newline*
1560                 "        throw(jump);" *newline*
1561                 "}" *newline*)
1562         "}" *newline*
1563         "return " (ls-compile nil) ";" *newline*))))
1564
1565 (define-compilation go (label)
1566   (let ((b (lookup-in-lexenv label *environment* 'gotag))
1567         (n (cond
1568              ((symbolp label) (symbol-name label))
1569              ((integerp label) (integer-to-string label)))))
1570     (if b
1571         (js!selfcall
1572           "throw ({"
1573           "type: 'tagbody', "
1574           "id: " (first (binding-value b)) ", "
1575           "label: " (second (binding-value b)) ", "
1576           "message: 'Attempt to GO to non-existing tag " n "'"
1577           "})" *newline*)
1578         (error (concat "Unknown tag `" n "'.")))))
1579
1580 (define-compilation unwind-protect (form &rest clean-up)
1581   (js!selfcall
1582     "var ret = " (ls-compile nil) ";" *newline*
1583     "try {" *newline*
1584     (indent "ret = " (ls-compile form) ";" *newline*)
1585     "} finally {" *newline*
1586     (indent (ls-compile-block clean-up))
1587     "}" *newline*
1588     "return ret;" *newline*))
1589
1590 (define-compilation multiple-value-call (func-form &rest forms)
1591   (js!selfcall
1592     "var func = " (ls-compile func-form) ";" *newline*
1593     "var args = [" (if *multiple-value-p* "values" "pv") "];" *newline*
1594     "return "
1595     (js!selfcall
1596       "var values = mv;" *newline*
1597       "var vs;" *newline*
1598       (mapconcat (lambda (form)
1599                    (concat "vs = " (ls-compile form t) ";" *newline*
1600                            "if (typeof vs === 'object' && 'multiple-value' in vs)" *newline*
1601                            (indent "args = args.concat(vs);" *newline*)
1602                            "else" *newline*
1603                            (indent "args.push(vs);" *newline*)))
1604                  forms)
1605       "return func.apply(window, args);" *newline*) ";" *newline*))
1606
1607 (define-compilation multiple-value-prog1 (first-form &rest forms)
1608   (js!selfcall
1609     "var args = " (ls-compile first-form *multiple-value-p*) ";" *newline*
1610     (ls-compile-block forms)
1611     "return args;" *newline*))
1612
1613
1614 #+common-lisp
1615 (progn
1616
1617   )
1618
1619
1620 ;;; A little backquote implementation without optimizations of any
1621 ;;; kind for ecmalisp.
1622 (defun backquote-expand-1 (form)
1623   (cond
1624     ((symbolp form)
1625      (list 'quote form))
1626     ((atom form)
1627      form)
1628     ((eq (car form) 'unquote)
1629      (car form))
1630     ((eq (car form) 'backquote)
1631      (backquote-expand-1 (backquote-expand-1 (cadr form))))
1632     (t
1633      (cons 'append
1634            (mapcar (lambda (s)
1635                      (cond
1636                        ((and (listp s) (eq (car s) 'unquote))
1637                         (list 'list (cadr s)))
1638                        ((and (listp s) (eq (car s) 'unquote-splicing))
1639                         (cadr s))
1640                        (t
1641                         (list 'list (backquote-expand-1 s)))))
1642                    form)))))
1643
1644 (defun backquote-expand (form)
1645   (if (and (listp form) (eq (car form) 'backquote))
1646       (backquote-expand-1 (cadr form))
1647       form))
1648
1649 (defmacro backquote (form)
1650   (backquote-expand-1 form))
1651
1652 (define-transformation backquote (form)
1653   (backquote-expand-1 form))
1654
1655 ;;; Primitives
1656
1657 (defvar *builtins* nil)
1658
1659 (defmacro define-raw-builtin (name args &body body)
1660   ;; Creates a new primitive function `name' with parameters args and
1661   ;; @body. The body can access to the local environment through the
1662   ;; variable *ENVIRONMENT*.
1663   `(push (list ',name (lambda ,args (block ,name ,@body)))
1664          *builtins*))
1665
1666 (defmacro define-builtin (name args &body body)
1667   `(progn
1668      (define-raw-builtin ,name ,args
1669        (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1670          ,@body))))
1671
1672 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1673 (defmacro type-check (decls &body body)
1674   `(js!selfcall
1675      ,@(mapcar (lambda (decl)
1676                    `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1677                  decls)
1678      ,@(mapcar (lambda (decl)
1679                  `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1680                           (indent "throw 'The value ' + "
1681                                   ,(first decl)
1682                                   " + ' is not a type "
1683                                   ,(second decl)
1684                                   ".';"
1685                                   *newline*)))
1686                decls)
1687      (concat "return " (progn ,@body) ";" *newline*)))
1688
1689 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
1690 ;;; a variable which holds a list of forms. It will compile them and
1691 ;;; store the result in some Javascript variables. BODY is evaluated
1692 ;;; with ARGS bound to the list of these variables to generate the
1693 ;;; code which performs the transformation on these variables.
1694
1695 (defun variable-arity-call (args function)
1696   (unless (consp args)
1697     (error "ARGS must be a non-empty list"))
1698   (let ((counter 0)
1699         (variables '())
1700         (prelude ""))
1701     (dolist (x args)
1702       (let ((v (concat "x" (integer-to-string (incf counter)))))
1703         (push v variables)
1704         (concatf prelude
1705                  (concat "var " v " = " (ls-compile x) ";" *newline*
1706                          "if (typeof " v " !== 'number') throw 'Not a number!';"
1707                          *newline*))))
1708     (js!selfcall prelude (funcall function (reverse variables)))))
1709
1710
1711 (defmacro variable-arity (args &body body)
1712   (unless (symbolp args)
1713     (error "Bad usage of VARIABLE-ARITY, you must pass a symbol"))
1714   `(variable-arity-call ,args
1715                         (lambda (,args)
1716                           (concat "return " ,@body ";" *newline*))))
1717
1718 (defun num-op-num (x op y)
1719   (type-check (("x" "number" x) ("y" "number" y))
1720     (concat "x" op "y")))
1721
1722 (define-raw-builtin + (&rest numbers)
1723   (if (null numbers)
1724       "0"
1725       (variable-arity numbers
1726         (join numbers "+"))))
1727
1728 (define-raw-builtin - (x &rest others)
1729   (let ((args (cons x others)))
1730     (variable-arity args
1731       (if (null others)
1732           (concat "-" (car args))
1733           (join args "-")))))
1734
1735 (define-raw-builtin * (&rest numbers)
1736   (if (null numbers)
1737       "1"
1738       (variable-arity numbers
1739         (join numbers "*"))))
1740
1741 (define-raw-builtin / (x &rest others)
1742   (let ((args (cons x others)))
1743     (variable-arity args
1744       (if (null others)
1745           (concat "1 /" (car args))
1746           (join args "/")))))
1747
1748 (define-builtin mod (x y) (num-op-num x "%" y))
1749
1750
1751 (defun comparison-conjuntion (vars op)
1752   (cond
1753     ((null (cdr vars))
1754      "true")
1755     ((null (cddr vars))
1756      (concat (car vars) op (cadr vars)))
1757     (t
1758      (concat (car vars) op (cadr vars)
1759              " && "
1760              (comparison-conjuntion (cdr vars) op)))))
1761
1762 (defmacro define-builtin-comparison (op sym)
1763   `(define-raw-builtin ,op (x &rest args)
1764      (let ((args (cons x args)))
1765        (variable-arity args
1766          (js!bool (comparison-conjuntion args ,sym))))))
1767
1768 (define-builtin-comparison > ">")
1769 (define-builtin-comparison < "<")
1770 (define-builtin-comparison >= ">=")
1771 (define-builtin-comparison <= "<=")
1772 (define-builtin-comparison = "==")
1773
1774 (define-builtin numberp (x)
1775   (js!bool (concat "(typeof (" x ") == \"number\")")))
1776
1777 (define-builtin floor (x)
1778   (type-check (("x" "number" x))
1779     "Math.floor(x)"))
1780
1781 (define-builtin cons (x y)
1782   (concat "({car: " x ", cdr: " y "})"))
1783
1784 (define-builtin consp (x)
1785   (js!bool
1786    (js!selfcall
1787      "var tmp = " x ";" *newline*
1788      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1789
1790 (define-builtin car (x)
1791   (js!selfcall
1792     "var tmp = " x ";" *newline*
1793     "return tmp === " (ls-compile nil)
1794     "? " (ls-compile nil)
1795     ": tmp.car;" *newline*))
1796
1797 (define-builtin cdr (x)
1798   (js!selfcall
1799     "var tmp = " x ";" *newline*
1800     "return tmp === " (ls-compile nil) "? "
1801     (ls-compile nil)
1802     ": tmp.cdr;" *newline*))
1803
1804 (define-builtin setcar (x new)
1805   (type-check (("x" "object" x))
1806     (concat "(x.car = " new ")")))
1807
1808 (define-builtin setcdr (x new)
1809   (type-check (("x" "object" x))
1810     (concat "(x.cdr = " new ")")))
1811
1812 (define-builtin symbolp (x)
1813   (js!bool
1814    (js!selfcall
1815      "var tmp = " x ";" *newline*
1816      "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1817
1818 (define-builtin make-symbol (name)
1819   (type-check (("name" "string" name))
1820     "({name: name})"))
1821
1822 (define-builtin symbol-name (x)
1823   (concat "(" x ").name"))
1824
1825 (define-builtin set (symbol value)
1826   (concat "(" symbol ").value = " value))
1827
1828 (define-builtin fset (symbol value)
1829   (concat "(" symbol ").fvalue = " value))
1830
1831 (define-builtin boundp (x)
1832   (js!bool (concat "(" x ".value !== undefined)")))
1833
1834 (define-builtin symbol-value (x)
1835   (js!selfcall
1836     "var symbol = " x ";" *newline*
1837     "var value = symbol.value;" *newline*
1838     "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1839     "return value;" *newline*))
1840
1841 (define-builtin symbol-function (x)
1842   (js!selfcall
1843     "var symbol = " x ";" *newline*
1844     "var func = symbol.fvalue;" *newline*
1845     "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1846     "return func;" *newline*))
1847
1848 (define-builtin symbol-plist (x)
1849   (concat "((" x ").plist || " (ls-compile nil) ")"))
1850
1851 (define-builtin lambda-code (x)
1852   (concat "(" x ").toString()"))
1853
1854 (define-builtin eq    (x y) (js!bool (concat "(" x " === " y ")")))
1855 (define-builtin equal (x y) (js!bool (concat "(" x  " == " y ")")))
1856
1857 (define-builtin char-to-string (x)
1858   (type-check (("x" "number" x))
1859     "String.fromCharCode(x)"))
1860
1861 (define-builtin stringp (x)
1862   (js!bool (concat "(typeof(" x ") == \"string\")")))
1863
1864 (define-builtin string-upcase (x)
1865   (type-check (("x" "string" x))
1866     "x.toUpperCase()"))
1867
1868 (define-builtin string-length (x)
1869   (type-check (("x" "string" x))
1870     "x.length"))
1871
1872 (define-raw-builtin slice (string a &optional b)
1873   (js!selfcall
1874     "var str = " (ls-compile string) ";" *newline*
1875     "var a = " (ls-compile a) ";" *newline*
1876     "var b;" *newline*
1877     (if b
1878         (concat "b = " (ls-compile b) ";" *newline*)
1879         "")
1880     "return str.slice(a,b);" *newline*))
1881
1882 (define-builtin char (string index)
1883   (type-check (("string" "string" string)
1884                ("index" "number" index))
1885     "string.charCodeAt(index)"))
1886
1887 (define-builtin concat-two (string1 string2)
1888   (type-check (("string1" "string" string1)
1889                ("string2" "string" string2))
1890     "string1.concat(string2)"))
1891
1892 (define-raw-builtin funcall (func &rest args)
1893   (concat "(" (ls-compile func) ")("
1894           (join (cons (if *multiple-value-p* "values" "pv")
1895                       (mapcar #'ls-compile args))
1896                 ", ")
1897           ")"))
1898
1899 (define-raw-builtin apply (func &rest args)
1900   (if (null args)
1901       (concat "(" (ls-compile func) ")()")
1902       (let ((args (butlast args))
1903             (last (car (last args))))
1904         (js!selfcall
1905           "var f = " (ls-compile func) ";" *newline*
1906           "var args = [" (join (cons (if *multiple-value-p* "values" "pv")
1907                                      (mapcar #'ls-compile args))
1908                                ", ")
1909           "];" *newline*
1910           "var tail = (" (ls-compile last) ");" *newline*
1911           "while (tail != " (ls-compile nil) "){" *newline*
1912           "    args.push(tail.car);" *newline*
1913           "    tail = tail.cdr;" *newline*
1914           "}" *newline*
1915           "return f.apply(this, args);" *newline*))))
1916
1917 (define-builtin js-eval (string)
1918   (type-check (("string" "string" string))
1919     (if *multiple-value-p*
1920         (js!selfcall
1921           "var v = eval.apply(window, [string]);" *newline*
1922           "if (typeof v !== 'object' || !('multiple-value' in v)){" *newline*
1923           (indent "v = [v];" *newline*
1924                   "v['multiple-value'] = true;" *newline*)
1925           "}" *newline*
1926           "return values.apply(this, v);" *newline*)
1927         "eval.apply(window, [string])")))
1928
1929 (define-builtin error (string)
1930   (js!selfcall "throw " string ";" *newline*))
1931
1932 (define-builtin new () "{}")
1933
1934 (define-builtin objectp (x)
1935   (js!bool (concat "(typeof (" x ") === 'object')")))
1936
1937 (define-builtin oget (object key)
1938   (js!selfcall
1939     "var tmp = " "(" object ")[" key "];" *newline*
1940     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1941
1942 (define-builtin oset (object key value)
1943   (concat "((" object ")[" key "] = " value ")"))
1944
1945 (define-builtin in (key object)
1946   (js!bool (concat "((" key ") in (" object "))")))
1947
1948 (define-builtin functionp (x)
1949   (js!bool (concat "(typeof " x " == 'function')")))
1950
1951 (define-builtin write-string (x)
1952   (type-check (("x" "string" x))
1953     "lisp.write(x)"))
1954
1955 (define-builtin make-array (n)
1956   (js!selfcall
1957     "var r = [];" *newline*
1958     "for (var i = 0; i < " n "; i++)" *newline*
1959     (indent "r.push(" (ls-compile nil) ");" *newline*)
1960     "return r;" *newline*))
1961
1962 (define-builtin arrayp (x)
1963   (js!bool
1964    (js!selfcall
1965      "var x = " x ";" *newline*
1966      "return typeof x === 'object' && 'length' in x;")))
1967
1968 (define-builtin aref (array n)
1969   (js!selfcall
1970     "var x = " "(" array ")[" n "];" *newline*
1971     "if (x === undefined) throw 'Out of range';" *newline*
1972     "return x;" *newline*))
1973
1974 (define-builtin aset (array n value)
1975   (js!selfcall
1976     "var x = " array ";" *newline*
1977     "var i = " n ";" *newline*
1978     "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
1979     "return x[i] = " value ";" *newline*))
1980
1981 (define-builtin get-unix-time ()
1982   (concat "(Math.round(new Date() / 1000))"))
1983
1984 (define-builtin values-array (array)
1985   (if *multiple-value-p*
1986       (concat "values.apply(this, " array ")")
1987       (concat "pv.apply(this, " array ")")))
1988
1989 (define-raw-builtin values (&rest args)
1990   (if *multiple-value-p*
1991       (concat "values(" (join (mapcar #'ls-compile args) ", ") ")")
1992       (concat "pv(" (join (mapcar #'ls-compile args) ", ") ")")))
1993
1994 (defun macro (x)
1995   (and (symbolp x)
1996        (let ((b (lookup-in-lexenv x *environment* 'function)))
1997          (and (eq (binding-type b) 'macro)
1998               b))))
1999
2000 (defun ls-macroexpand-1 (form)
2001   (let ((macro-binding (macro (car form))))
2002     (if macro-binding
2003         (let ((expander (binding-value macro-binding)))
2004           (when (listp expander)
2005             (let ((compiled (eval expander)))
2006               ;; The list representation are useful while
2007               ;; bootstrapping, as we can dump the definition of the
2008               ;; macros easily, but they are slow because we have to
2009               ;; evaluate them and compile them now and again. So, let
2010               ;; us replace the list representation version of the
2011               ;; function with the compiled one.
2012               ;;
2013               #+ecmalisp (set-binding-value macro-binding compiled)
2014               (setq expander compiled)))
2015           (apply expander (cdr form)))
2016         form)))
2017
2018 (defun compile-funcall (function args)
2019   (let ((values-funcs (if *multiple-value-p* "values" "pv")))
2020     (if (and (symbolp function)
2021              #+ecmalisp (eq (symbol-package function) (find-package "COMMON-LISP"))
2022              #+common-lisp t)
2023         (concat (ls-compile `',function) ".fvalue("
2024                 (join (cons values-funcs (mapcar #'ls-compile args))
2025                       ", ")
2026                 ")")
2027         (concat (ls-compile `#',function) "("
2028                 (join (cons values-funcs (mapcar #'ls-compile args))
2029                       ", ")
2030                 ")"))))
2031
2032 (defun ls-compile-block (sexps &optional return-last-p)
2033   (if return-last-p
2034       (concat (ls-compile-block (butlast sexps))
2035               "return " (ls-compile (car (last sexps)) *multiple-value-p*) ";")
2036       (join-trailing
2037        (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
2038        (concat ";" *newline*))))
2039
2040 (defun ls-compile (sexp &optional multiple-value-p)
2041   (let ((*multiple-value-p* multiple-value-p))
2042     (cond
2043       ((symbolp sexp)
2044        (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
2045          (cond
2046            ((and b (not (member 'special (binding-declarations b))))
2047             (binding-value b))
2048            ((or (keywordp sexp)
2049                 (member 'constant (binding-declarations b)))
2050             (concat (ls-compile `',sexp) ".value"))
2051            (t
2052             (ls-compile `(symbol-value ',sexp))))))
2053       ((integerp sexp) (integer-to-string sexp))
2054       ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
2055       ((arrayp sexp) (literal sexp))
2056       ((listp sexp)
2057        (let ((name (car sexp))
2058              (args (cdr sexp)))
2059          (cond
2060            ;; Special forms
2061            ((assoc name *compilations*)
2062             (let ((comp (second (assoc name *compilations*))))
2063               (apply comp args)))
2064            ;; Built-in functions
2065            ((and (assoc name *builtins*)
2066                  (not (claimp name 'function 'notinline)))
2067             (let ((comp (second (assoc name *builtins*))))
2068               (apply comp args)))
2069            (t
2070             (if (macro name)
2071                 (ls-compile (ls-macroexpand-1 sexp) multiple-value-p)
2072                 (compile-funcall name args))))))
2073       (t
2074        (error "How should I compile this?")))))
2075
2076 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
2077   (let ((*toplevel-compilations* nil))
2078     (cond
2079       ((and (consp sexp) (eq (car sexp) 'progn))
2080        (let ((subs (mapcar (lambda (s)
2081                              (ls-compile-toplevel s t))
2082                            (cdr sexp))))
2083          (join (remove-if #'null-or-empty-p subs))))
2084       (t
2085        (let ((code (ls-compile sexp multiple-value-p)))
2086          (concat (join-trailing (get-toplevel-compilations)
2087                                 (concat ";" *newline*))
2088                  (if code
2089                      (concat code ";" *newline*)
2090                      "")))))))
2091
2092
2093 ;;; Once we have the compiler, we define the runtime environment and
2094 ;;; interactive development (eval), which works calling the compiler
2095 ;;; and evaluating the Javascript result globally.
2096
2097 #+ecmalisp
2098 (progn
2099   (defun eval (x)
2100     (js-eval (ls-compile-toplevel x t)))
2101
2102   (export '(&rest &optional &body * *gensym-counter* *package* + - / 1+ 1- < <= =
2103             = > >= and append apply aref arrayp aset assoc atom block boundp
2104             boundp butlast caar cadddr caddr cadr car car case catch cdar cdddr
2105             cddr cdr cdr char char-code char= code-char cond cons consp copy-list
2106             decf declaim defparameter defun defmacro defvar digit-char-p
2107             disassemble documentation dolist dotimes ecase eq eql equal error eval
2108             every export fdefinition find-package find-symbol first fourth fset
2109             funcall function functionp gensym get-universal-time go identity if
2110             in-package incf integerp integerp intern keywordp lambda last length
2111             let let* list-all-packages list listp make-array make-package
2112             make-symbol mapcar member minusp mod multiple-value-bind
2113             multiple-value-call multiple-value-list multiple-value-prog1 nil not
2114             nth nthcdr null numberp or package-name package-use-list packagep
2115             plusp prin1-to-string print proclaim prog1 prog2 progn psetq push
2116             quote remove remove-if remove-if-not return return-from revappend
2117             reverse second set setq some string-upcase string string= stringp
2118             subseq symbol-function symbol-name symbol-package symbol-plist
2119             symbol-value symbolp t tagbody third throw truncate unless
2120             unwind-protect values values-list variable warn when write-line
2121             write-string zerop))
2122
2123   (setq *package* *user-package*)
2124
2125   (js-eval "var lisp")
2126   (js-vset "lisp" (new))
2127   (js-vset "lisp.read" #'ls-read-from-string)
2128   (js-vset "lisp.print" #'prin1-to-string)
2129   (js-vset "lisp.eval" #'eval)
2130   (js-vset "lisp.compile" (lambda (s) (ls-compile-toplevel s t)))
2131   (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
2132   (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str) t)))
2133
2134   ;; Set the initial global environment to be equal to the host global
2135   ;; environment at this point of the compilation.
2136   (eval-when-compile
2137     (toplevel-compilation
2138      (ls-compile
2139       `(progn
2140          ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
2141                    *literal-symbols*)
2142          (setq *literal-symbols* ',*literal-symbols*)
2143          (setq *environment* ',*environment*)
2144          (setq *variable-counter* ,*variable-counter*)
2145          (setq *gensym-counter* ,*gensym-counter*)
2146          (setq *block-counter* ,*block-counter*)))))
2147
2148   (eval-when-compile
2149     (toplevel-compilation
2150      (ls-compile
2151       `(setq *literal-counter* ,*literal-counter*)))))
2152
2153
2154 ;;; Finally, we provide a couple of functions to easily bootstrap
2155 ;;; this. It just calls the compiler with this file as input.
2156
2157 #+common-lisp
2158 (progn
2159   (defun read-whole-file (filename)
2160     (with-open-file (in filename)
2161       (let ((seq (make-array (file-length in) :element-type 'character)))
2162         (read-sequence seq in)
2163         seq)))
2164
2165   (defun ls-compile-file (filename output)
2166     (setq *compilation-unit-checks* nil)
2167     (with-open-file (out output :direction :output :if-exists :supersede)
2168       (write-string (read-whole-file "prelude.js") out)
2169       (let* ((source (read-whole-file filename))
2170              (in (make-string-stream source)))
2171         (loop
2172            for x = (ls-read in)
2173            until (eq x *eof*)
2174            for compilation = (ls-compile-toplevel x)
2175            when (plusp (length compilation))
2176            do (write-string compilation out))
2177         (dolist (check *compilation-unit-checks*)
2178           (funcall check))
2179         (setq *compilation-unit-checks* nil))))
2180
2181   (defun bootstrap ()
2182     (setq *environment* (make-lexenv))
2183     (setq *literal-symbols* nil)
2184     (setq *variable-counter* 0
2185           *gensym-counter* 0
2186           *literal-counter* 0
2187           *block-counter* 0)
2188     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))