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