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