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