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