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