Prepend prelude.js automatically
[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                     ");")
1175             "")
1176         (if (not rest-argument)
1177             (concat "checkArgsAtLeast("
1178                     (integer-to-string (+ 1 n-required-arguments n-optional-arguments))
1179                     ");")
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        *newline*
1217        "})"))))
1218
1219
1220 (defun setq-pair (var val)
1221   (let ((b (lookup-in-lexenv var *environment* 'variable)))
1222     (if (eq (binding-type b) 'lexical-variable)
1223         (concat (binding-value b) " = " (ls-compile val))
1224         (ls-compile `(set ',var ,val)))))
1225
1226 (define-compilation setq (&rest pairs)
1227   (let ((result ""))
1228     (while t
1229       (cond
1230         ((null pairs) (return))
1231         ((null (cdr pairs))
1232          (error "Odd paris in SETQ"))
1233         (t
1234          (concatf result
1235            (concat (setq-pair (car pairs) (cadr pairs))
1236                    (if (null (cddr pairs)) "" ", ")))
1237          (setq pairs (cddr pairs)))))
1238     (concat "(" result ")")))
1239
1240 ;;; FFI Variable accessors
1241 (define-compilation js-vref (var)
1242   var)
1243
1244 (define-compilation js-vset (var val)
1245   (concat "(" var " = " (ls-compile val) ")"))
1246
1247
1248
1249 ;;; Literals
1250 (defun escape-string (string)
1251   (let ((output "")
1252         (index 0)
1253         (size (length string)))
1254     (while (< index size)
1255       (let ((ch (char string index)))
1256         (when (or (char= ch #\") (char= ch #\\))
1257           (setq output (concat output "\\")))
1258         (when (or (char= ch #\newline))
1259           (setq output (concat output "\\"))
1260           (setq ch #\n))
1261         (setq output (concat output (string ch))))
1262       (incf index))
1263     output))
1264
1265
1266 (defvar *literal-symbols* nil)
1267 (defvar *literal-counter* 0)
1268
1269 (defun genlit ()
1270   (concat "l" (integer-to-string (incf *literal-counter*))))
1271
1272 (defun literal (sexp &optional recursive)
1273   (cond
1274     ((integerp sexp) (integer-to-string sexp))
1275     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1276     ((symbolp sexp)
1277      (or (cdr (assoc sexp *literal-symbols*))
1278          (let ((v (genlit))
1279                (s #+common-lisp (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1280                   #+ecmalisp
1281                   (let ((package (symbol-package sexp)))
1282                     (if (null package)
1283                         (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1284                         (ls-compile `(intern ,(symbol-name sexp) ,(package-name package)))))))
1285            (push (cons sexp v) *literal-symbols*)
1286            (toplevel-compilation (concat "var " v " = " s))
1287            v)))
1288     ((consp sexp)
1289      (let ((c (concat "{car: " (literal (car sexp) t) ", "
1290                       "cdr: " (literal (cdr sexp) t) "}")))
1291        (if recursive
1292            c
1293            (let ((v (genlit)))
1294              (toplevel-compilation (concat "var " v " = " c))
1295              v))))
1296     ((arrayp sexp)
1297      (let ((elements (vector-to-list sexp)))
1298        (let ((c (concat "[" (join (mapcar #'literal elements) ", ") "]")))
1299          (if recursive
1300              c
1301              (let ((v (genlit)))
1302                (toplevel-compilation (concat "var " v " = " c))
1303                v)))))))
1304
1305 (define-compilation quote (sexp)
1306   (literal sexp))
1307
1308 (define-compilation %while (pred &rest body)
1309   (js!selfcall
1310     "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1311     (indent (ls-compile-block body))
1312     "}"
1313     "return " (ls-compile nil) ";" *newline*))
1314
1315 (define-compilation function (x)
1316   (cond
1317     ((and (listp x) (eq (car x) 'lambda))
1318      (ls-compile x))
1319     ((symbolp x)
1320      (ls-compile `(symbol-function ',x)))))
1321
1322 (define-compilation eval-when-compile (&rest body)
1323   (eval (cons 'progn body))
1324   nil)
1325
1326 (defmacro define-transformation (name args form)
1327   `(define-compilation ,name ,args
1328      (ls-compile ,form)))
1329
1330 (define-compilation progn (&rest body)
1331   (if (null (cdr body))
1332       (ls-compile (car body) *multiple-value-p*)
1333       (js!selfcall (ls-compile-block body t))))
1334
1335 (defun special-variable-p (x)
1336   (and (claimp x 'variable 'special) t))
1337
1338 ;;; Wrap CODE to restore the symbol values of the dynamic
1339 ;;; bindings. BINDINGS is a list of pairs of the form
1340 ;;; (SYMBOL . PLACE),  where PLACE is a Javascript variable
1341 ;;; name to initialize the symbol value and where to stored
1342 ;;; the old value.
1343 (defun let-binding-wrapper (bindings body)
1344   (when (null bindings)
1345     (return-from let-binding-wrapper body))
1346   (concat
1347    "try {" *newline*
1348    (indent "var tmp;" *newline*
1349            (mapconcat
1350             (lambda (b)
1351               (let ((s (ls-compile `(quote ,(car b)))))
1352                 (concat "tmp = " s ".value;" *newline*
1353                         s ".value = " (cdr b) ";" *newline*
1354                         (cdr b) " = tmp;" *newline*)))
1355             bindings)
1356            body *newline*)
1357    "}" *newline*
1358    "finally {"  *newline*
1359    (indent
1360     (mapconcat (lambda (b)
1361                  (let ((s (ls-compile `(quote ,(car b)))))
1362                    (concat s ".value" " = " (cdr b) ";" *newline*)))
1363                bindings))
1364    "}" *newline*))
1365
1366 (define-compilation let (bindings &rest body)
1367   (let* ((bindings (mapcar #'ensure-list bindings))
1368          (variables (mapcar #'first bindings))
1369          (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
1370          (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
1371          (dynamic-bindings))
1372     (concat "(function("
1373             (join (mapcar (lambda (x)
1374                             (if (special-variable-p x)
1375                                 (let ((v (gvarname x)))
1376                                   (push (cons x v) dynamic-bindings)
1377                                   v)
1378                                 (translate-variable x)))
1379                           variables)
1380                   ",")
1381             "){" *newline*
1382             (let ((body (ls-compile-block body t)))
1383               (indent (let-binding-wrapper dynamic-bindings body)))
1384             "})(" (join cvalues ",") ")")))
1385
1386
1387 ;;; Return the code to initialize BINDING, and push it extending the
1388 ;;; current lexical environment if the variable is special.
1389 (defun let*-initialize-value (binding)
1390   (let ((var (first binding))
1391         (value (second binding)))
1392     (if (special-variable-p var)
1393         (concat (ls-compile `(setq ,var ,value)) ";" *newline*)
1394         (let* ((v (gvarname var))
1395                (b (make-binding var 'variable v)))
1396           (prog1 (concat "var " v " = " (ls-compile value) ";" *newline*)
1397             (push-to-lexenv b *environment* 'variable))))))
1398
1399 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
1400 ;;; DOES NOT generate code to initialize the value of the symbols,
1401 ;;; unlike let-binding-wrapper.
1402 (defun let*-binding-wrapper (symbols body)
1403   (when (null symbols)
1404     (return-from let*-binding-wrapper body))
1405   (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
1406                        (remove-if-not #'special-variable-p symbols))))
1407     (concat
1408      "try {" *newline*
1409      (indent
1410       (mapconcat (lambda (b)
1411                    (let ((s (ls-compile `(quote ,(car b)))))
1412                      (concat "var " (cdr b) " = " s ".value;" *newline*)))
1413                  store)
1414       body)
1415      "}" *newline*
1416      "finally {" *newline*
1417      (indent
1418       (mapconcat (lambda (b)
1419                    (let ((s (ls-compile `(quote ,(car b)))))
1420                      (concat s ".value" " = " (cdr b) ";" *newline*)))
1421                  store))
1422      "}" *newline*)))
1423
1424 (define-compilation let* (bindings &rest body)
1425   (let ((bindings (mapcar #'ensure-list bindings))
1426         (*environment* (copy-lexenv *environment*)))
1427     (js!selfcall
1428       (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
1429             (body (concat (mapconcat #'let*-initialize-value bindings)
1430                           (ls-compile-block body t))))
1431         (let*-binding-wrapper specials body)))))
1432
1433
1434 (defvar *block-counter* 0)
1435
1436 (define-compilation block (name &rest body)
1437   (let* ((tr (integer-to-string (incf *block-counter*)))
1438          (b (make-binding name 'block tr))
1439          (*environment* (extend-lexenv (list b) *environment* 'block))
1440          (cbody (ls-compile-block body t)))
1441     (if (member 'used (binding-declarations b))
1442         (js!selfcall
1443           "try {" *newline*
1444           (indent cbody)
1445           "}" *newline*
1446           "catch (cf){" *newline*
1447           "    if (cf.type == 'block' && cf.id == " tr ")" *newline*
1448           "        return cf.value;" *newline*
1449           "    else" *newline*
1450           "        throw cf;" *newline*
1451           "}" *newline*)
1452         (js!selfcall
1453           (indent cbody)))))
1454
1455 (define-compilation return-from (name &optional value)
1456   (let ((b (lookup-in-lexenv name *environment* 'block)))
1457     (when (null b)
1458       (error (concat "Unknown block `" (symbol-name name) "'.")))
1459     (push-binding-declaration 'used b)
1460     (js!selfcall
1461       "throw ({"
1462       "type: 'block', "
1463       "id: " (binding-value b) ", "
1464       "value: " (ls-compile value) ", "
1465       "message: 'Return from unknown block " (symbol-name name) ".'"
1466       "})")))
1467
1468 (define-compilation catch (id &rest body)
1469   (js!selfcall
1470     "var id = " (ls-compile id) ";" *newline*
1471     "try {" *newline*
1472     (indent "return " (ls-compile `(progn ,@body))
1473             ";" *newline*)
1474     "}" *newline*
1475     "catch (cf){" *newline*
1476     "    if (cf.type == 'catch' && cf.id == id)" *newline*
1477     "        return cf.value;" *newline*
1478     "    else" *newline*
1479     "        throw cf;" *newline*
1480     "}" *newline*))
1481
1482 (define-compilation throw (id value)
1483   (js!selfcall
1484     "throw ({"
1485     "type: 'catch', "
1486     "id: " (ls-compile id) ", "
1487     "value: " (ls-compile value) ", "
1488     "message: 'Throw uncatched.'"
1489     "})"))
1490
1491
1492 (defvar *tagbody-counter* 0)
1493 (defvar *go-tag-counter* 0)
1494
1495 (defun go-tag-p (x)
1496   (or (integerp x) (symbolp x)))
1497
1498 (defun declare-tagbody-tags (tbidx body)
1499   (let ((bindings
1500          (mapcar (lambda (label)
1501                    (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1502                      (make-binding label 'gotag (list tbidx tagidx))))
1503                  (remove-if-not #'go-tag-p body))))
1504     (extend-lexenv bindings *environment* 'gotag)))
1505
1506 (define-compilation tagbody (&rest body)
1507   ;; Ignore the tagbody if it does not contain any go-tag. We do this
1508   ;; because 1) it is easy and 2) many built-in forms expand to a
1509   ;; implicit tagbody, so we save some space.
1510   (unless (some #'go-tag-p body)
1511     (return-from tagbody (ls-compile `(progn ,@body nil))))
1512   ;; The translation assumes the first form in BODY is a label
1513   (unless (go-tag-p (car body))
1514     (push (gensym "START") body))
1515   ;; Tagbody compilation
1516   (let ((tbidx (integer-to-string *tagbody-counter*)))
1517     (let ((*environment* (declare-tagbody-tags tbidx body))
1518           initag)
1519       (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1520         (setq initag (second (binding-value b))))
1521       (js!selfcall
1522         "var tagbody_" tbidx " = " initag ";" *newline*
1523         "tbloop:" *newline*
1524         "while (true) {" *newline*
1525         (indent "try {" *newline*
1526                 (indent (let ((content ""))
1527                           (concat "switch(tagbody_" tbidx "){" *newline*
1528                                   "case " initag ":" *newline*
1529                                   (dolist (form (cdr body) content)
1530                                     (concatf content
1531                                       (if (not (go-tag-p form))
1532                                           (indent (ls-compile form) ";" *newline*)
1533                                           (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1534                                             (concat "case " (second (binding-value b)) ":" *newline*)))))
1535                                   "default:" *newline*
1536                                   "    break tbloop;" *newline*
1537                                   "}" *newline*)))
1538                 "}" *newline*
1539                 "catch (jump) {" *newline*
1540                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1541                 "        tagbody_" tbidx " = jump.label;" *newline*
1542                 "    else" *newline*
1543                 "        throw(jump);" *newline*
1544                 "}" *newline*)
1545         "}" *newline*
1546         "return " (ls-compile nil) ";" *newline*))))
1547
1548 (define-compilation go (label)
1549   (let ((b (lookup-in-lexenv label *environment* 'gotag))
1550         (n (cond
1551              ((symbolp label) (symbol-name label))
1552              ((integerp label) (integer-to-string label)))))
1553     (if b
1554         (js!selfcall
1555           "throw ({"
1556           "type: 'tagbody', "
1557           "id: " (first (binding-value b)) ", "
1558           "label: " (second (binding-value b)) ", "
1559           "message: 'Attempt to GO to non-existing tag " n "'"
1560           "})" *newline*)
1561         (error (concat "Unknown tag `" n "'.")))))
1562
1563 (define-compilation unwind-protect (form &rest clean-up)
1564   (js!selfcall
1565     "var ret = " (ls-compile nil) ";" *newline*
1566     "try {" *newline*
1567     (indent "ret = " (ls-compile form) ";" *newline*)
1568     "} finally {" *newline*
1569     (indent (ls-compile-block clean-up))
1570     "}" *newline*
1571     "return ret;" *newline*))
1572
1573 (define-compilation multiple-value-call (func-form &rest forms)
1574   (js!selfcall
1575     "var func = " (ls-compile func-form) ";" *newline*
1576     "var args = [" (if *multiple-value-p* "values" "pv") "];" *newline*
1577     "return "
1578     (js!selfcall
1579       "var values = mv;" *newline*
1580       "var vs;" *newline*
1581       (mapconcat (lambda (form)
1582                    (concat "vs = " (ls-compile form t) ";" *newline*
1583                            "if (typeof vs === 'object' && 'multiple-value' in vs)" *newline*
1584                            (indent "args = args.concat(vs);" *newline*)
1585                            "else" *newline*
1586                            (indent "args.push(vs);" *newline*)))
1587                  forms)
1588       "return func.apply(window, args);" *newline*) ";" *newline*))
1589
1590 (define-compilation multiple-value-prog1 (first-form &rest forms)
1591   (js!selfcall
1592     "var args = " (ls-compile first-form *multiple-value-p*) ";" *newline*
1593     (ls-compile-block forms)
1594     "return args;" *newline*))
1595
1596
1597 #+common-lisp
1598 (progn
1599
1600   )
1601
1602
1603 ;;; A little backquote implementation without optimizations of any
1604 ;;; kind for ecmalisp.
1605 (defun backquote-expand-1 (form)
1606   (cond
1607     ((symbolp form)
1608      (list 'quote form))
1609     ((atom form)
1610      form)
1611     ((eq (car form) 'unquote)
1612      (car form))
1613     ((eq (car form) 'backquote)
1614      (backquote-expand-1 (backquote-expand-1 (cadr form))))
1615     (t
1616      (cons 'append
1617            (mapcar (lambda (s)
1618                      (cond
1619                        ((and (listp s) (eq (car s) 'unquote))
1620                         (list 'list (cadr s)))
1621                        ((and (listp s) (eq (car s) 'unquote-splicing))
1622                         (cadr s))
1623                        (t
1624                         (list 'list (backquote-expand-1 s)))))
1625                    form)))))
1626
1627 (defun backquote-expand (form)
1628   (if (and (listp form) (eq (car form) 'backquote))
1629       (backquote-expand-1 (cadr form))
1630       form))
1631
1632 (defmacro backquote (form)
1633   (backquote-expand-1 form))
1634
1635 (define-transformation backquote (form)
1636   (backquote-expand-1 form))
1637
1638 ;;; Primitives
1639
1640 (defvar *builtins* nil)
1641
1642 (defmacro define-raw-builtin (name args &body body)
1643   ;; Creates a new primitive function `name' with parameters args and
1644   ;; @body. The body can access to the local environment through the
1645   ;; variable *ENVIRONMENT*.
1646   `(push (list ',name (lambda ,args (block ,name ,@body)))
1647          *builtins*))
1648
1649 (defmacro define-builtin (name args &body body)
1650   `(progn
1651      (define-raw-builtin ,name ,args
1652        (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1653          ,@body))))
1654
1655 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1656 (defmacro type-check (decls &body body)
1657   `(js!selfcall
1658      ,@(mapcar (lambda (decl)
1659                    `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1660                  decls)
1661      ,@(mapcar (lambda (decl)
1662                  `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1663                           (indent "throw 'The value ' + "
1664                                   ,(first decl)
1665                                   " + ' is not a type "
1666                                   ,(second decl)
1667                                   ".';"
1668                                   *newline*)))
1669                decls)
1670      (concat "return " (progn ,@body) ";" *newline*)))
1671
1672 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
1673 ;;; a variable which holds a list of forms. It will compile them and
1674 ;;; store the result in some Javascript variables. BODY is evaluated
1675 ;;; with ARGS bound to the list of these variables to generate the
1676 ;;; code which performs the transformation on these variables.
1677
1678 (defun variable-arity-call (args function)
1679   (unless (consp args)
1680     (error "ARGS must be a non-empty list"))
1681   (let ((counter 0)
1682         (variables '())
1683         (prelude ""))
1684     (dolist (x args)
1685       (let ((v (concat "x" (integer-to-string (incf counter)))))
1686         (push v variables)
1687         (concatf prelude
1688                  (concat "var " v " = " (ls-compile x) ";" *newline*
1689                          "if (typeof " v " !== 'number') throw 'Not a number!';"
1690                          *newline*))))
1691     (js!selfcall prelude (funcall function (reverse variables)))))
1692
1693
1694 (defmacro variable-arity (args &body body)
1695   (unless (symbolp args)
1696     (error "Bad usage of VARIABLE-ARITY, you must pass a symbol"))
1697   `(variable-arity-call ,args
1698                         (lambda (,args)
1699                           (concat "return " ,@body ";" *newline*))))
1700
1701 (defun num-op-num (x op y)
1702   (type-check (("x" "number" x) ("y" "number" y))
1703     (concat "x" op "y")))
1704
1705 (define-raw-builtin + (&rest numbers)
1706   (if (null numbers)
1707       "0"
1708       (variable-arity numbers
1709         (join numbers "+"))))
1710
1711 (define-raw-builtin - (x &rest others)
1712   (let ((args (cons x others)))
1713     (variable-arity args
1714       (if (null others)
1715           (concat "-" (car args))
1716           (join args "-")))))
1717
1718 (define-raw-builtin * (&rest numbers)
1719   (if (null numbers)
1720       "1"
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 "1 /" (car args))
1729           (join args "/")))))
1730
1731 (define-builtin mod (x y) (num-op-num x "%" y))
1732
1733
1734 (defun comparison-conjuntion (vars op)
1735   (cond
1736     ((null (cdr vars))
1737      "true")
1738     ((null (cddr vars))
1739      (concat (car vars) op (cadr vars)))
1740     (t
1741      (concat (car vars) op (cadr vars)
1742              " && "
1743              (comparison-conjuntion (cdr vars) op)))))
1744
1745 (defmacro define-builtin-comparison (op sym)
1746   `(define-raw-builtin ,op (x &rest args)
1747      (let ((args (cons x args)))
1748        (variable-arity args
1749          (js!bool (comparison-conjuntion args ,sym))))))
1750
1751 (define-builtin-comparison > ">")
1752 (define-builtin-comparison < "<")
1753 (define-builtin-comparison >= ">=")
1754 (define-builtin-comparison <= "<=")
1755 (define-builtin-comparison = "==")
1756
1757 (define-builtin numberp (x)
1758   (js!bool (concat "(typeof (" x ") == \"number\")")))
1759
1760 (define-builtin floor (x)
1761   (type-check (("x" "number" x))
1762     "Math.floor(x)"))
1763
1764 (define-builtin cons (x y)
1765   (concat "({car: " x ", cdr: " y "})"))
1766
1767 (define-builtin consp (x)
1768   (js!bool
1769    (js!selfcall
1770      "var tmp = " x ";" *newline*
1771      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1772
1773 (define-builtin car (x)
1774   (js!selfcall
1775     "var tmp = " x ";" *newline*
1776     "return tmp === " (ls-compile nil)
1777     "? " (ls-compile nil)
1778     ": tmp.car;" *newline*))
1779
1780 (define-builtin cdr (x)
1781   (js!selfcall
1782     "var tmp = " x ";" *newline*
1783     "return tmp === " (ls-compile nil) "? "
1784     (ls-compile nil)
1785     ": tmp.cdr;" *newline*))
1786
1787 (define-builtin setcar (x new)
1788   (type-check (("x" "object" x))
1789     (concat "(x.car = " new ")")))
1790
1791 (define-builtin setcdr (x new)
1792   (type-check (("x" "object" x))
1793     (concat "(x.cdr = " new ")")))
1794
1795 (define-builtin symbolp (x)
1796   (js!bool
1797    (js!selfcall
1798      "var tmp = " x ";" *newline*
1799      "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1800
1801 (define-builtin make-symbol (name)
1802   (type-check (("name" "string" name))
1803     "({name: name})"))
1804
1805 (define-builtin symbol-name (x)
1806   (concat "(" x ").name"))
1807
1808 (define-builtin set (symbol value)
1809   (concat "(" symbol ").value = " value))
1810
1811 (define-builtin fset (symbol value)
1812   (concat "(" symbol ").fvalue = " value))
1813
1814 (define-builtin boundp (x)
1815   (js!bool (concat "(" x ".value !== undefined)")))
1816
1817 (define-builtin symbol-value (x)
1818   (js!selfcall
1819     "var symbol = " x ";" *newline*
1820     "var value = symbol.value;" *newline*
1821     "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1822     "return value;" *newline*))
1823
1824 (define-builtin symbol-function (x)
1825   (js!selfcall
1826     "var symbol = " x ";" *newline*
1827     "var func = symbol.fvalue;" *newline*
1828     "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1829     "return func;" *newline*))
1830
1831 (define-builtin symbol-plist (x)
1832   (concat "((" x ").plist || " (ls-compile nil) ")"))
1833
1834 (define-builtin lambda-code (x)
1835   (concat "(" x ").toString()"))
1836
1837 (define-builtin eq    (x y) (js!bool (concat "(" x " === " y ")")))
1838 (define-builtin equal (x y) (js!bool (concat "(" x  " == " y ")")))
1839
1840 (define-builtin char-to-string (x)
1841   (type-check (("x" "number" x))
1842     "String.fromCharCode(x)"))
1843
1844 (define-builtin stringp (x)
1845   (js!bool (concat "(typeof(" x ") == \"string\")")))
1846
1847 (define-builtin string-upcase (x)
1848   (type-check (("x" "string" x))
1849     "x.toUpperCase()"))
1850
1851 (define-builtin string-length (x)
1852   (type-check (("x" "string" x))
1853     "x.length"))
1854
1855 (define-raw-builtin slice (string a &optional b)
1856   (js!selfcall
1857     "var str = " (ls-compile string) ";" *newline*
1858     "var a = " (ls-compile a) ";" *newline*
1859     "var b;" *newline*
1860     (if b
1861         (concat "b = " (ls-compile b) ";" *newline*)
1862         "")
1863     "return str.slice(a,b);" *newline*))
1864
1865 (define-builtin char (string index)
1866   (type-check (("string" "string" string)
1867                ("index" "number" index))
1868     "string.charCodeAt(index)"))
1869
1870 (define-builtin concat-two (string1 string2)
1871   (type-check (("string1" "string" string1)
1872                ("string2" "string" string2))
1873     "string1.concat(string2)"))
1874
1875 (define-raw-builtin funcall (func &rest args)
1876   (concat "(" (ls-compile func) ")("
1877           (join (cons (if *multiple-value-p* "values" "pv")
1878                       (mapcar #'ls-compile args))
1879                 ", ")
1880           ")"))
1881
1882 (define-raw-builtin apply (func &rest args)
1883   (if (null args)
1884       (concat "(" (ls-compile func) ")()")
1885       (let ((args (butlast args))
1886             (last (car (last args))))
1887         (js!selfcall
1888           "var f = " (ls-compile func) ";" *newline*
1889           "var args = [" (join (cons (if *multiple-value-p* "values" "pv")
1890                                      (mapcar #'ls-compile args))
1891                                ", ")
1892           "];" *newline*
1893           "var tail = (" (ls-compile last) ");" *newline*
1894           "while (tail != " (ls-compile nil) "){" *newline*
1895           "    args.push(tail.car);" *newline*
1896           "    tail = tail.cdr;" *newline*
1897           "}" *newline*
1898           "return f.apply(this, args);" *newline*))))
1899
1900 (define-builtin js-eval (string)
1901   (type-check (("string" "string" string))
1902     (if *multiple-value-p*
1903         (js!selfcall
1904           "var v = eval.apply(window, [string]);" *newline*
1905           "if (typeof v !== 'object' || !('multiple-value' in v)){" *newline*
1906           (indent "v = [v];" *newline*
1907                   "v['multiple-value'] = true;" *newline*)
1908           "}" *newline*
1909           "return values.apply(this, v);" *newline*)
1910         "eval.apply(window, [string])")))
1911
1912 (define-builtin error (string)
1913   (js!selfcall "throw " string ";" *newline*))
1914
1915 (define-builtin new () "{}")
1916
1917 (define-builtin objectp (x)
1918   (js!bool (concat "(typeof (" x ") === 'object')")))
1919
1920 (define-builtin oget (object key)
1921   (js!selfcall
1922     "var tmp = " "(" object ")[" key "];" *newline*
1923     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1924
1925 (define-builtin oset (object key value)
1926   (concat "((" object ")[" key "] = " value ")"))
1927
1928 (define-builtin in (key object)
1929   (js!bool (concat "((" key ") in (" object "))")))
1930
1931 (define-builtin functionp (x)
1932   (js!bool (concat "(typeof " x " == 'function')")))
1933
1934 (define-builtin write-string (x)
1935   (type-check (("x" "string" x))
1936     "lisp.write(x)"))
1937
1938 (define-builtin make-array (n)
1939   (js!selfcall
1940     "var r = [];" *newline*
1941     "for (var i = 0; i < " n "; i++)" *newline*
1942     (indent "r.push(" (ls-compile nil) ");" *newline*)
1943     "return r;" *newline*))
1944
1945 (define-builtin arrayp (x)
1946   (js!bool
1947    (js!selfcall
1948      "var x = " x ";" *newline*
1949      "return typeof x === 'object' && 'length' in x;")))
1950
1951 (define-builtin aref (array n)
1952   (js!selfcall
1953     "var x = " "(" array ")[" n "];" *newline*
1954     "if (x === undefined) throw 'Out of range';" *newline*
1955     "return x;" *newline*))
1956
1957 (define-builtin aset (array n value)
1958   (js!selfcall
1959     "var x = " array ";" *newline*
1960     "var i = " n ";" *newline*
1961     "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
1962     "return x[i] = " value ";" *newline*))
1963
1964 (define-builtin get-unix-time ()
1965   (concat "(Math.round(new Date() / 1000))"))
1966
1967 (define-builtin values-array (array)
1968   (if *multiple-value-p*
1969       (concat "values.apply(this, " array ")")
1970       (concat "pv.apply(this, " array ")")))
1971
1972 (define-raw-builtin values (&rest args)
1973   (if *multiple-value-p*
1974       (concat "values(" (join (mapcar #'ls-compile args) ", ") ")")
1975       (concat "pv(" (join (mapcar #'ls-compile args) ", ") ")")))
1976
1977 (defun macro (x)
1978   (and (symbolp x)
1979        (let ((b (lookup-in-lexenv x *environment* 'function)))
1980          (and (eq (binding-type b) 'macro)
1981               b))))
1982
1983 (defun ls-macroexpand-1 (form)
1984   (let ((macro-binding (macro (car form))))
1985     (if macro-binding
1986         (let ((expander (binding-value macro-binding)))
1987           (when (listp expander)
1988             (let ((compiled (eval expander)))
1989               ;; The list representation are useful while
1990               ;; bootstrapping, as we can dump the definition of the
1991               ;; macros easily, but they are slow because we have to
1992               ;; evaluate them and compile them now and again. So, let
1993               ;; us replace the list representation version of the
1994               ;; function with the compiled one.
1995               ;;
1996               #+ecmalisp (set-binding-value macro-binding compiled)
1997               (setq expander compiled)))
1998           (apply expander (cdr form)))
1999         form)))
2000
2001 (defun compile-funcall (function args)
2002   (let ((values-funcs (if *multiple-value-p* "values" "pv")))
2003     (if (and (symbolp function)
2004              #+ecmalisp (eq (symbol-package function) (find-package "COMMON-LISP"))
2005              #+common-lisp t)
2006         (concat (ls-compile `',function) ".fvalue("
2007                 (join (cons values-funcs (mapcar #'ls-compile args))
2008                       ", ")
2009                 ")")
2010         (concat (ls-compile `#',function) "("
2011                 (join (cons values-funcs (mapcar #'ls-compile args))
2012                       ", ")
2013                 ")"))))
2014
2015 (defun ls-compile-block (sexps &optional return-last-p)
2016   (if return-last-p
2017       (concat (ls-compile-block (butlast sexps))
2018               "return " (ls-compile (car (last sexps)) *multiple-value-p*) ";")
2019       (join-trailing
2020        (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
2021        (concat ";" *newline*))))
2022
2023 (defun ls-compile (sexp &optional multiple-value-p)
2024   (let ((*multiple-value-p* multiple-value-p))
2025     (cond
2026       ((symbolp sexp)
2027        (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
2028          (cond
2029            ((and b (not (member 'special (binding-declarations b))))
2030             (binding-value b))
2031            ((or (keywordp sexp)
2032                 (member 'constant (binding-declarations b)))
2033             (concat (ls-compile `',sexp) ".value"))
2034            (t
2035             (ls-compile `(symbol-value ',sexp))))))
2036       ((integerp sexp) (integer-to-string sexp))
2037       ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
2038       ((arrayp sexp) (literal sexp))
2039       ((listp sexp)
2040        (let ((name (car sexp))
2041              (args (cdr sexp)))
2042          (cond
2043            ;; Special forms
2044            ((assoc name *compilations*)
2045             (let ((comp (second (assoc name *compilations*))))
2046               (apply comp args)))
2047            ;; Built-in functions
2048            ((and (assoc name *builtins*)
2049                  (not (claimp name 'function 'notinline)))
2050             (let ((comp (second (assoc name *builtins*))))
2051               (apply comp args)))
2052            (t
2053             (if (macro name)
2054                 (ls-compile (ls-macroexpand-1 sexp) multiple-value-p)
2055                 (compile-funcall name args))))))
2056       (t
2057        (error "How should I compile this?")))))
2058
2059 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
2060   (let ((*toplevel-compilations* nil))
2061     (cond
2062       ((and (consp sexp) (eq (car sexp) 'progn))
2063        (let ((subs (mapcar (lambda (s)
2064                              (ls-compile-toplevel s t))
2065                            (cdr sexp))))
2066          (join (remove-if #'null-or-empty-p subs))))
2067       (t
2068        (let ((code (ls-compile sexp multiple-value-p)))
2069          (concat (join-trailing (get-toplevel-compilations)
2070                                 (concat ";" *newline*))
2071                  (if code
2072                      (concat code ";" *newline*)
2073                      "")))))))
2074
2075
2076 ;;; Once we have the compiler, we define the runtime environment and
2077 ;;; interactive development (eval), which works calling the compiler
2078 ;;; and evaluating the Javascript result globally.
2079
2080 #+ecmalisp
2081 (progn
2082   (defun eval (x)
2083     (js-eval (ls-compile-toplevel x t)))
2084
2085   (export '(&rest &optional &body * *gensym-counter* *package* + - / 1+ 1- < <= =
2086             = > >= and append apply aref arrayp aset assoc atom block boundp
2087             boundp butlast caar cadddr caddr cadr car car case catch cdar cdddr
2088             cddr cdr cdr char char-code char= code-char cond cons consp copy-list
2089             decf declaim defparameter defun defmacro defvar digit-char-p
2090             disassemble documentation dolist dotimes ecase eq eql equal error eval
2091             every export fdefinition find-package find-symbol first fourth fset
2092             funcall function functionp gensym get-universal-time go identity if
2093             in-package incf integerp integerp intern keywordp lambda last length
2094             let let* list-all-packages list listp make-array make-package
2095             make-symbol mapcar member minusp mod multiple-value-bind
2096             multiple-value-call multiple-value-list multiple-value-prog1 nil not
2097             nth nthcdr null numberp or package-name package-use-list packagep
2098             plusp prin1-to-string print proclaim prog1 prog2 progn psetq push
2099             quote remove remove-if remove-if-not return return-from revappend
2100             reverse second set setq some string-upcase string string= stringp
2101             subseq symbol-function symbol-name symbol-package symbol-plist
2102             symbol-value symbolp t tagbody third throw truncate unless
2103             unwind-protect values values-list variable warn when write-line
2104             write-string zerop))
2105
2106   (setq *package* *user-package*)
2107
2108   (js-eval "var lisp")
2109   (js-vset "lisp" (new))
2110   (js-vset "lisp.read" #'ls-read-from-string)
2111   (js-vset "lisp.print" #'prin1-to-string)
2112   (js-vset "lisp.eval" #'eval)
2113   (js-vset "lisp.compile" (lambda (s) (ls-compile-toplevel s t)))
2114   (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
2115   (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str) t)))
2116
2117   ;; Set the initial global environment to be equal to the host global
2118   ;; environment at this point of the compilation.
2119   (eval-when-compile
2120     (toplevel-compilation
2121      (ls-compile
2122       `(progn
2123          ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
2124                    *literal-symbols*)
2125          (setq *literal-symbols* ',*literal-symbols*)
2126          (setq *environment* ',*environment*)
2127          (setq *variable-counter* ,*variable-counter*)
2128          (setq *gensym-counter* ,*gensym-counter*)
2129          (setq *block-counter* ,*block-counter*)))))
2130
2131   (eval-when-compile
2132     (toplevel-compilation
2133      (ls-compile
2134       `(setq *literal-counter* ,*literal-counter*)))))
2135
2136
2137 ;;; Finally, we provide a couple of functions to easily bootstrap
2138 ;;; this. It just calls the compiler with this file as input.
2139
2140 #+common-lisp
2141 (progn
2142   (defun read-whole-file (filename)
2143     (with-open-file (in filename)
2144       (let ((seq (make-array (file-length in) :element-type 'character)))
2145         (read-sequence seq in)
2146         seq)))
2147
2148   (defun ls-compile-file (filename output)
2149     (setq *compilation-unit-checks* nil)
2150     (with-open-file (out output :direction :output :if-exists :supersede)
2151       (write-string (read-whole-file "prelude.js") out)
2152       (let* ((source (read-whole-file filename))
2153              (in (make-string-stream source)))
2154         (loop
2155            for x = (ls-read in)
2156            until (eq x *eof*)
2157            for compilation = (ls-compile-toplevel x)
2158            when (plusp (length compilation))
2159            do (write-string compilation out))
2160         (dolist (check *compilation-unit-checks*)
2161           (funcall check))
2162         (setq *compilation-unit-checks* nil))))
2163
2164   (defun bootstrap ()
2165     (setq *environment* (make-lexenv))
2166     (setq *literal-symbols* nil)
2167     (setq *variable-counter* 0
2168           *gensym-counter* 0
2169           *literal-counter* 0
2170           *block-counter* 0)
2171     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))