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