Merge branch 'psetq' into gh-pages
[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
601 ;;; The compiler offers some primitives and special forms which are
602 ;;; not found in Common Lisp, for instance, while. So, we grow Common
603 ;;; Lisp a bit to it can execute the rest of the file.
604 #+common-lisp
605 (progn
606   (defmacro while (condition &body body)
607     `(do ()
608          ((not ,condition))
609        ,@body))
610
611   (defmacro eval-when-compile (&body body)
612     `(eval-when (:compile-toplevel :load-toplevel :execute)
613        ,@body))
614
615   (defun concat-two (s1 s2)
616     (concatenate 'string s1 s2))
617
618   (defun setcar (cons new)
619     (setf (car cons) new))
620   (defun setcdr (cons new)
621     (setf (cdr cons) new))
622
623   (defun aset (array idx value)
624     (setf (aref array idx) value)))
625
626 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
627 ;;; from here, this code will compile on both. We define some helper
628 ;;; functions now for string manipulation and so on. They will be
629 ;;; useful in the compiler, mostly.
630
631 (defvar *newline* (string (code-char 10)))
632
633 (defun concat (&rest strs)
634   (!reduce #'concat-two strs ""))
635
636 (defmacro concatf (variable &body form)
637   `(setq ,variable (concat ,variable (progn ,@form))))
638
639 ;;; Concatenate a list of strings, with a separator
640 (defun join (list &optional (separator ""))
641   (cond
642     ((null list)
643      "")
644     ((null (cdr list))
645      (car list))
646     (t
647      (concat (car list)
648              separator
649              (join (cdr list) separator)))))
650
651 (defun join-trailing (list &optional (separator ""))
652   (if (null list)
653       ""
654       (concat (car list) separator (join-trailing (cdr list) separator))))
655
656 (defun mapconcat (func list)
657   (join (mapcar func list)))
658
659 (defun vector-to-list (vector)
660   (let ((list nil)
661         (size (length vector)))
662     (dotimes (i size (reverse list))
663       (push (aref vector i) list))))
664
665 (defun list-to-vector (list)
666   (let ((v (make-array (length list)))
667         (i 0))
668     (dolist (x list v)
669       (aset v i x)
670       (incf i))))
671
672 ;;; Like CONCAT, but prefix each line with four spaces. Two versions
673 ;;; of this function are available, because the Ecmalisp version is
674 ;;; very slow and bootstraping was annoying.
675
676 #+ecmalisp
677 (defun indent (&rest string)
678   (let ((input (join string)))
679     (let ((output "")
680           (index 0)
681           (size (length input)))
682       (when (plusp (length input)) (concatf output "    "))
683       (while (< index size)
684         (let ((str
685                (if (and (char= (char input index) #\newline)
686                         (< index (1- size))
687                         (not (char= (char input (1+ index)) #\newline)))
688                    (concat (string #\newline) "    ")
689                    (string (char input index)))))
690           (concatf output str))
691         (incf index))
692       output)))
693
694 #+common-lisp
695 (defun indent (&rest string)
696   (with-output-to-string (*standard-output*)
697     (with-input-from-string (input (join string))
698       (loop
699          for line = (read-line input nil)
700          while line
701          do (write-string "    ")
702          do (write-line line)))))
703
704
705 (defun integer-to-string (x)
706   (cond
707     ((zerop x)
708      "0")
709     ((minusp x)
710      (concat "-" (integer-to-string (- 0 x))))
711     (t
712      (let ((digits nil))
713        (while (not (zerop x))
714          (push (mod x 10) digits)
715          (setq x (truncate x 10)))
716        (join (mapcar (lambda (d) (string (char "0123456789" d)))
717                      digits))))))
718
719
720 ;;; Wrap X with a Javascript code to convert the result from
721 ;;; Javascript generalized booleans to T or NIL.
722 (defun js!bool (x)
723   (concat "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
724
725 ;;; Concatenate the arguments and wrap them with a self-calling
726 ;;; Javascript anonymous function. It is used to make some Javascript
727 ;;; statements valid expressions and provide a private scope as well.
728 ;;; It could be defined as function, but we could do some
729 ;;; preprocessing in the future.
730 (defmacro js!selfcall (&body body)
731   `(concat "(function(){" *newline* (indent ,@body) "})()"))
732
733
734 ;;; Printer
735
736 #+ecmalisp
737 (progn
738   (defun prin1-to-string (form)
739     (cond
740       ((symbolp form)
741        (if (cdr (%find-symbol (symbol-name form) *package*))
742            (symbol-name form)
743            (let ((package (symbol-package form))
744                  (name (symbol-name form)))
745              (concat (if (eq package (find-package "KEYWORD"))
746                          ""
747                          (package-name package))
748                      ":" name))))
749       ((integerp form) (integer-to-string form))
750       ((stringp form) (concat "\"" (escape-string form) "\""))
751       ((functionp form)
752        (let ((name (oget form "fname")))
753          (if name
754              (concat "#<FUNCTION " name ">")
755              (concat "#<FUNCTION>"))))
756       ((listp form)
757        (concat "("
758                (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
759                (let ((last (last form)))
760                  (if (null (cdr last))
761                      (prin1-to-string (car last))
762                      (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
763                ")"))
764       ((arrayp form)
765        (concat "#" (prin1-to-string (vector-to-list form))))
766       ((packagep form)
767        (concat "#<PACKAGE " (package-name form) ">"))))
768
769   (defun write-line (x)
770     (write-string x)
771     (write-string *newline*)
772     x)
773
774   (defun warn (string)
775     (write-string "WARNING: ")
776     (write-line string))
777
778   (defun print (x)
779     (write-line (prin1-to-string x))
780     x))
781
782
783 ;;;; Reader
784
785 ;;; The Lisp reader, parse strings and return Lisp objects. The main
786 ;;; entry points are `ls-read' and `ls-read-from-string'.
787
788 (defun make-string-stream (string)
789   (cons string 0))
790
791 (defun %peek-char (stream)
792   (and (< (cdr stream) (length (car stream)))
793        (char (car stream) (cdr stream))))
794
795 (defun %read-char (stream)
796   (and (< (cdr stream) (length (car stream)))
797        (prog1 (char (car stream) (cdr stream))
798          (setcdr stream (1+ (cdr stream))))))
799
800 (defun whitespacep (ch)
801   (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
802
803 (defun skip-whitespaces (stream)
804   (let (ch)
805     (setq ch (%peek-char stream))
806     (while (and ch (whitespacep ch))
807       (%read-char stream)
808       (setq ch (%peek-char stream)))))
809
810 (defun terminalp (ch)
811   (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
812
813 (defun read-until (stream func)
814   (let ((string "")
815         (ch))
816     (setq ch (%peek-char stream))
817     (while (and ch (not (funcall func ch)))
818       (setq string (concat string (string ch)))
819       (%read-char stream)
820       (setq ch (%peek-char stream)))
821     string))
822
823 (defun skip-whitespaces-and-comments (stream)
824   (let (ch)
825     (skip-whitespaces stream)
826     (setq ch (%peek-char stream))
827     (while (and ch (char= ch #\;))
828       (read-until stream (lambda (x) (char= x #\newline)))
829       (skip-whitespaces stream)
830       (setq ch (%peek-char stream)))))
831
832 (defun %read-list (stream)
833   (skip-whitespaces-and-comments stream)
834   (let ((ch (%peek-char stream)))
835     (cond
836       ((null ch)
837        (error "Unspected EOF"))
838       ((char= ch #\))
839        (%read-char stream)
840        nil)
841       ((char= ch #\.)
842        (%read-char stream)
843        (prog1 (ls-read stream)
844          (skip-whitespaces-and-comments stream)
845          (unless (char= (%read-char stream) #\))
846            (error "')' was expected."))))
847       (t
848        (cons (ls-read stream) (%read-list stream))))))
849
850 (defun read-string (stream)
851   (let ((string "")
852         (ch nil))
853     (setq ch (%read-char stream))
854     (while (not (eql ch #\"))
855       (when (null ch)
856         (error "Unexpected EOF"))
857       (when (eql ch #\\)
858         (setq ch (%read-char stream)))
859       (setq string (concat string (string ch)))
860       (setq ch (%read-char stream)))
861     string))
862
863 (defun read-sharp (stream)
864   (%read-char stream)
865   (ecase (%read-char stream)
866     (#\'
867      (list 'function (ls-read stream)))
868     (#\( (list-to-vector (%read-list stream)))
869     (#\\
870      (let ((cname
871             (concat (string (%read-char stream))
872                     (read-until stream #'terminalp))))
873        (cond
874          ((string= cname "space") (char-code #\space))
875          ((string= cname "tab") (char-code #\tab))
876          ((string= cname "newline") (char-code #\newline))
877          (t (char-code (char cname 0))))))
878     (#\+
879      (let ((feature (read-until stream #'terminalp)))
880        (cond
881          ((string= feature "common-lisp")
882           (ls-read stream)              ;ignore
883           (ls-read stream))
884          ((string= feature "ecmalisp")
885           (ls-read stream))
886          (t
887           (error "Unknown reader form.")))))))
888
889 ;;; Parse a string of the form NAME, PACKAGE:NAME or
890 ;;; PACKAGE::NAME and return the name. If the string is of the
891 ;;; form 1) or 3), but the symbol does not exist, it will be created
892 ;;; and interned in that package.
893 (defun read-symbol (string)
894   (let ((size (length string))
895         package name internalp index)
896     (setq index 0)
897     (while (and (< index size)
898                 (not (char= (char string index) #\:)))
899       (incf index))
900     (cond
901       ;; No package prefix
902       ((= index size)
903        (setq name string)
904        (setq package *package*)
905        (setq internalp t))
906       (t
907        ;; Package prefix
908        (if (zerop index)
909            (setq package "KEYWORD")
910            (setq package (string-upcase (subseq string 0 index))))
911        (incf index)
912        (when (char= (char string index) #\:)
913          (setq internalp t)
914          (incf index))
915        (setq name (subseq string index))))
916     ;; Canonalize symbol name and package
917     (setq name (string-upcase name))
918     (setq package (find-package package))
919     ;; TODO: PACKAGE:SYMBOL should signal error if SYMBOL is not an
920     ;; external symbol from PACKAGE.
921     (if (or internalp (eq package (find-package "KEYWORD")))
922         (intern name package)
923         (find-symbol name package))))
924
925 (defvar *eof* (gensym))
926 (defun ls-read (stream)
927   (skip-whitespaces-and-comments stream)
928   (let ((ch (%peek-char stream)))
929     (cond
930       ((or (null ch) (char= ch #\)))
931        *eof*)
932       ((char= ch #\()
933        (%read-char stream)
934        (%read-list stream))
935       ((char= ch #\')
936        (%read-char stream)
937        (list 'quote (ls-read stream)))
938       ((char= ch #\`)
939        (%read-char stream)
940        (list 'backquote (ls-read stream)))
941       ((char= ch #\")
942        (%read-char stream)
943        (read-string stream))
944       ((char= ch #\,)
945        (%read-char stream)
946        (if (eql (%peek-char stream) #\@)
947            (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
948            (list 'unquote (ls-read stream))))
949       ((char= ch #\#)
950        (read-sharp stream))
951       (t
952        (let ((string (read-until stream #'terminalp)))
953          (if (every #'digit-char-p string)
954              (parse-integer string)
955              (read-symbol string)))))))
956
957 (defun ls-read-from-string (string)
958   (ls-read (make-string-stream string)))
959
960
961 ;;;; Compiler
962
963 ;;; Translate the Lisp code to Javascript. It will compile the special
964 ;;; forms. Some primitive functions are compiled as special forms
965 ;;; too. The respective real functions are defined in the target (see
966 ;;; the beginning of this file) as well as some primitive functions.
967
968 (defvar *compilation-unit-checks* '())
969
970 (defun make-binding (name type value &optional declarations)
971   (list name type value declarations))
972
973 (defun binding-name (b) (first b))
974 (defun binding-type (b) (second b))
975 (defun binding-value (b) (third b))
976 (defun binding-declarations (b) (fourth b))
977
978 (defun set-binding-value (b value)
979   (setcar (cddr b) value))
980
981 (defun set-binding-declarations (b value)
982   (setcar (cdddr b) value))
983
984 (defun push-binding-declaration (decl b)
985   (set-binding-declarations b (cons decl (binding-declarations b))))
986
987
988 (defun make-lexenv ()
989   (list nil nil nil nil))
990
991 (defun copy-lexenv (lexenv)
992   (copy-list lexenv))
993
994 (defun push-to-lexenv (binding lexenv namespace)
995   (ecase namespace
996     (variable   (setcar        lexenv  (cons binding (car lexenv))))
997     (function   (setcar   (cdr lexenv) (cons binding (cadr lexenv))))
998     (block      (setcar  (cddr lexenv) (cons binding (caddr lexenv))))
999     (gotag      (setcar (cdddr lexenv) (cons binding (cadddr lexenv))))))
1000
1001 (defun extend-lexenv (bindings lexenv namespace)
1002   (let ((env (copy-lexenv lexenv)))
1003     (dolist (binding (reverse bindings) env)
1004       (push-to-lexenv binding env namespace))))
1005
1006 (defun lookup-in-lexenv (name lexenv namespace)
1007   (assoc name (ecase namespace
1008                 (variable (first lexenv))
1009                 (function (second lexenv))
1010                 (block (third lexenv))
1011                 (gotag (fourth lexenv)))))
1012
1013 (defvar *environment* (make-lexenv))
1014
1015 (defvar *variable-counter* 0)
1016 (defun gvarname (symbol)
1017   (concat "v" (integer-to-string (incf *variable-counter*))))
1018
1019 (defun translate-variable (symbol)
1020   (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
1021
1022 (defun extend-local-env (args)
1023   (let ((new (copy-lexenv *environment*)))
1024     (dolist (symbol args new)
1025       (let ((b (make-binding symbol 'lexical-variable (gvarname symbol))))
1026         (push-to-lexenv b new 'variable)))))
1027
1028 ;;; Toplevel compilations
1029 (defvar *toplevel-compilations* nil)
1030
1031 (defun toplevel-compilation (string)
1032   (push string *toplevel-compilations*))
1033
1034 (defun null-or-empty-p (x)
1035   (zerop (length x)))
1036
1037 (defun get-toplevel-compilations ()
1038   (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
1039
1040 (defun %compile-defmacro (name lambda)
1041   (toplevel-compilation (ls-compile `',name))
1042   (push-to-lexenv (make-binding name 'macro lambda) *environment* 'function))
1043
1044 (defun global-binding (name type namespace)
1045   (or (lookup-in-lexenv name *environment* namespace)
1046       (let ((b (make-binding name type nil)))
1047         (push-to-lexenv b *environment* namespace)
1048         b)))
1049
1050 (defun claimp (symbol namespace claim)
1051   (let ((b (lookup-in-lexenv symbol *environment* namespace)))
1052     (and b (member claim (binding-declarations b)))))
1053
1054 (defun !proclaim (decl)
1055   (case (car decl)
1056     (special
1057      (dolist (name (cdr decl))
1058        (let ((b (global-binding name 'variable 'variable)))
1059          (push-binding-declaration 'special b))))
1060     (notinline
1061      (dolist (name (cdr decl))
1062        (let ((b (global-binding name 'function 'function)))
1063          (push-binding-declaration 'notinline b))))
1064     (constant
1065      (dolist (name (cdr decl))
1066        (let ((b (global-binding name 'variable 'variable)))
1067          (push-binding-declaration 'constant b))))
1068     (non-overridable
1069      (dolist (name (cdr decl))
1070        (let ((b (global-binding name 'function 'function)))
1071          (push-binding-declaration 'non-overridable b))))))
1072
1073 #+ecmalisp
1074 (fset 'proclaim #'!proclaim)
1075
1076 ;;; Special forms
1077
1078 (defvar *compilations* nil)
1079
1080 (defmacro define-compilation (name args &body body)
1081   ;; Creates a new primitive `name' with parameters args and
1082   ;; @body. The body can access to the local environment through the
1083   ;; variable *ENVIRONMENT*.
1084   `(push (list ',name (lambda ,args (block ,name ,@body)))
1085          *compilations*))
1086
1087 (define-compilation if (condition true false)
1088   (concat "(" (ls-compile condition) " !== " (ls-compile nil)
1089           " ? " (ls-compile true)
1090           " : " (ls-compile false)
1091           ")"))
1092
1093 (defvar *lambda-list-keywords* '(&optional &rest))
1094
1095 (defun list-until-keyword (list)
1096   (if (or (null list) (member (car list) *lambda-list-keywords*))
1097       nil
1098       (cons (car list) (list-until-keyword (cdr list)))))
1099
1100 (defun lambda-list-required-arguments (lambda-list)
1101   (list-until-keyword lambda-list))
1102
1103 (defun lambda-list-optional-arguments-with-default (lambda-list)
1104   (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
1105
1106 (defun lambda-list-optional-arguments (lambda-list)
1107   (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
1108
1109 (defun lambda-list-rest-argument (lambda-list)
1110   (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
1111     (when (cdr rest)
1112       (error "Bad lambda-list"))
1113     (car rest)))
1114
1115
1116 (defun lambda-docstring-wrapper (docstring &rest strs)
1117   (if docstring
1118       (js!selfcall
1119         "var func = " (join strs) ";" *newline*
1120         "func.docstring = '" docstring "';" *newline*
1121         "return func;" *newline*)
1122       (join strs)))
1123
1124 (define-compilation lambda (lambda-list &rest body)
1125   (let ((required-arguments (lambda-list-required-arguments lambda-list))
1126         (optional-arguments (lambda-list-optional-arguments lambda-list))
1127         (rest-argument (lambda-list-rest-argument lambda-list))
1128         documentation)
1129     ;; Get the documentation string for the lambda function
1130     (when (and (stringp (car body))
1131                (not (null (cdr body))))
1132       (setq documentation (car body))
1133       (setq body (cdr body)))
1134     (let ((n-required-arguments (length required-arguments))
1135           (n-optional-arguments (length optional-arguments))
1136           (*environment* (extend-local-env
1137                           (append (ensure-list rest-argument)
1138                                   required-arguments
1139                                   optional-arguments))))
1140       (lambda-docstring-wrapper
1141        documentation
1142        "(function ("
1143        (join (mapcar #'translate-variable
1144                      (append required-arguments optional-arguments))
1145              ",")
1146        "){" *newline*
1147        ;; Check number of arguments
1148        (indent
1149         (if required-arguments
1150             (concat "if (arguments.length < " (integer-to-string n-required-arguments)
1151                     ") throw 'too few arguments';" *newline*)
1152             "")
1153         (if (not rest-argument)
1154             (concat "if (arguments.length > "
1155                     (integer-to-string (+ n-required-arguments n-optional-arguments))
1156                     ") throw 'too many arguments';" *newline*)
1157             "")
1158         ;; Optional arguments
1159         (if optional-arguments
1160             (concat "switch(arguments.length){" *newline*
1161                     (let ((optional-and-defaults
1162                            (lambda-list-optional-arguments-with-default lambda-list))
1163                           (cases nil)
1164                           (idx 0))
1165                       (progn
1166                         (while (< idx n-optional-arguments)
1167                           (let ((arg (nth idx optional-and-defaults)))
1168                             (push (concat "case "
1169                                           (integer-to-string (+ idx n-required-arguments)) ":" *newline*
1170                                           (translate-variable (car arg))
1171                                           "="
1172                                           (ls-compile (cadr arg))
1173                                           ";" *newline*)
1174                                   cases)
1175                             (incf idx)))
1176                         (push (concat "default: break;" *newline*) cases)
1177                         (join (reverse cases))))
1178                     "}" *newline*)
1179             "")
1180         ;; &rest/&body argument
1181         (if rest-argument
1182             (let ((js!rest (translate-variable rest-argument)))
1183               (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
1184                       "for (var i = arguments.length-1; i>="
1185                       (integer-to-string (+ n-required-arguments n-optional-arguments))
1186                       "; i--)" *newline*
1187                       (indent js!rest " = "
1188                               "{car: arguments[i], cdr: ") js!rest "};"
1189                       *newline*))
1190             "")
1191         ;; Body
1192         (ls-compile-block body t)) *newline*
1193        "})"))))
1194
1195
1196 (defun setq-pair (var val)
1197   (let ((b (lookup-in-lexenv var *environment* 'variable)))
1198     (if (eq (binding-type b) 'lexical-variable)
1199         (concat (binding-value b) " = " (ls-compile val))
1200         (ls-compile `(set ',var ,val)))))
1201
1202 (define-compilation setq (&rest pairs)
1203   (let ((result ""))
1204     (while t
1205       (cond
1206         ((null pairs) (return))
1207         ((null (cdr pairs))
1208          (error "Odd paris in SETQ"))
1209         (t
1210          (concatf result
1211            (concat (setq-pair (car pairs) (cadr pairs))
1212                    (if (null (cddr pairs)) "" ", ")))
1213          (setq pairs (cddr pairs)))))
1214     (concat "(" result ")")))
1215
1216 ;;; FFI Variable accessors
1217 (define-compilation js-vref (var)
1218   var)
1219
1220 (define-compilation js-vset (var val)
1221   (concat "(" var " = " (ls-compile val) ")"))
1222
1223
1224 ;;; Literals
1225 (defun escape-string (string)
1226   (let ((output "")
1227         (index 0)
1228         (size (length string)))
1229     (while (< index size)
1230       (let ((ch (char string index)))
1231         (when (or (char= ch #\") (char= ch #\\))
1232           (setq output (concat output "\\")))
1233         (when (or (char= ch #\newline))
1234           (setq output (concat output "\\"))
1235           (setq ch #\n))
1236         (setq output (concat output (string ch))))
1237       (incf index))
1238     output))
1239
1240
1241 (defvar *literal-symbols* nil)
1242 (defvar *literal-counter* 0)
1243
1244 (defun genlit ()
1245   (concat "l" (integer-to-string (incf *literal-counter*))))
1246
1247 (defun literal (sexp &optional recursive)
1248   (cond
1249     ((integerp sexp) (integer-to-string sexp))
1250     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1251     ((symbolp sexp)
1252      (or (cdr (assoc sexp *literal-symbols*))
1253          (let ((v (genlit))
1254                (s #+common-lisp (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1255                   #+ecmalisp (ls-compile
1256                               `(intern ,(symbol-name sexp)
1257                                        ,(package-name (symbol-package sexp))))))
1258            (push (cons sexp v) *literal-symbols*)
1259            (toplevel-compilation (concat "var " v " = " s))
1260            v)))
1261     ((consp sexp)
1262      (let ((c (concat "{car: " (literal (car sexp) t) ", "
1263                       "cdr: " (literal (cdr sexp) t) "}")))
1264        (if recursive
1265            c
1266            (let ((v (genlit)))
1267              (toplevel-compilation (concat "var " v " = " c))
1268              v))))
1269     ((arrayp sexp)
1270      (let ((elements (vector-to-list sexp)))
1271        (let ((c (concat "[" (join (mapcar #'literal elements) ", ") "]")))
1272          (if recursive
1273              c
1274              (let ((v (genlit)))
1275                (toplevel-compilation (concat "var " v " = " c))
1276                v)))))))
1277
1278 (define-compilation quote (sexp)
1279   (literal sexp))
1280
1281 (define-compilation %while (pred &rest body)
1282   (js!selfcall
1283     "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1284     (indent (ls-compile-block body))
1285     "}"
1286     "return " (ls-compile nil) ";" *newline*))
1287
1288 (define-compilation function (x)
1289   (cond
1290     ((and (listp x) (eq (car x) 'lambda))
1291      (ls-compile x))
1292     ((symbolp x)
1293      (ls-compile `(symbol-function ',x)))))
1294
1295 (define-compilation eval-when-compile (&rest body)
1296   (eval (cons 'progn body))
1297   nil)
1298
1299 (defmacro define-transformation (name args form)
1300   `(define-compilation ,name ,args
1301      (ls-compile ,form)))
1302
1303 (define-compilation progn (&rest body)
1304   (js!selfcall (ls-compile-block body t)))
1305
1306 (defun special-variable-p (x)
1307   (claimp x 'variable 'special))
1308
1309 ;;; Wrap CODE to restore the symbol values of the dynamic
1310 ;;; bindings. BINDINGS is a list of pairs of the form
1311 ;;; (SYMBOL . PLACE),  where PLACE is a Javascript variable
1312 ;;; name to initialize the symbol value and where to stored
1313 ;;; the old value.
1314 (defun let-binding-wrapper (bindings body)
1315   (when (null bindings)
1316     (return-from let-binding-wrapper body))
1317   (concat
1318    "try {" *newline*
1319    (indent "var tmp;" *newline*
1320            (mapconcat
1321             (lambda (b)
1322               (let ((s (ls-compile `(quote ,(car b)))))
1323                 (concat "tmp = " s ".value;" *newline*
1324                         s ".value = " (cdr b) ";" *newline*
1325                         (cdr b) " = tmp;" *newline*)))
1326             bindings)
1327            body *newline*)
1328    "}" *newline*
1329    "finally {"  *newline*
1330    (indent
1331     (mapconcat (lambda (b)
1332                  (let ((s (ls-compile `(quote ,(car b)))))
1333                    (concat s ".value" " = " (cdr b) ";" *newline*)))
1334                bindings))
1335    "}" *newline*))
1336
1337 (define-compilation let (bindings &rest body)
1338   (let ((bindings (mapcar #'ensure-list bindings)))
1339     (let ((variables (mapcar #'first bindings)))
1340       (let ((cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
1341             (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
1342             (dynamic-bindings))
1343         (concat "(function("
1344                 (join (mapcar (lambda (x)
1345                                 (if (special-variable-p x)
1346                                     (let ((v (gvarname x)))
1347                                       (push (cons x v) dynamic-bindings)
1348                                       v)
1349                                     (translate-variable x)))
1350                               variables)
1351                       ",")
1352                 "){" *newline*
1353                 (let ((body (ls-compile-block body t)))
1354                   (indent (let-binding-wrapper dynamic-bindings body)))
1355                 "})(" (join cvalues ",") ")")))))
1356
1357
1358 ;;; Return the code to initialize BINDING, and push it extending the
1359 ;;; current lexical environment if the variable is special.
1360 (defun let*-initialize-value (binding)
1361   (let ((var (first binding))
1362         (value (second binding)))
1363     (if (special-variable-p var)
1364         (concat (ls-compile `(setq ,var ,value)) ";" *newline*)
1365         (let ((v (gvarname var)))
1366           (let ((b (make-binding var 'variable v)))
1367             (prog1 (concat "var " v " = " (ls-compile value) ";" *newline*)
1368               (push-to-lexenv b *environment* 'variable)))))))
1369
1370 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
1371 ;;; DOES NOT generate code to initialize the value of the symbols,
1372 ;;; unlike let-binding-wrapper.
1373 (defun let*-binding-wrapper (symbols body)
1374   (when (null symbols)
1375     (return-from let*-binding-wrapper body))
1376   (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
1377                        (remove-if-not #'special-variable-p symbols))))
1378     (concat
1379      "try {" *newline*
1380      (indent
1381       (mapconcat (lambda (b)
1382                    (let ((s (ls-compile `(quote ,(car b)))))
1383                      (concat "var " (cdr b) " = " s ".value;" *newline*)))
1384                  store)
1385       body)
1386      "}" *newline*
1387      "finally {" *newline*
1388      (indent
1389       (mapconcat (lambda (b)
1390                    (let ((s (ls-compile `(quote ,(car b)))))
1391                      (concat s ".value" " = " (cdr b) ";" *newline*)))
1392                  store))
1393      "}" *newline*)))
1394
1395
1396 (define-compilation let* (bindings &rest body)
1397   (let ((bindings (mapcar #'ensure-list bindings))
1398         (*environment* (copy-lexenv *environment*)))
1399     (js!selfcall
1400       (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
1401             (body (concat (mapconcat #'let*-initialize-value bindings)
1402                           (ls-compile-block body t))))
1403         (let*-binding-wrapper specials body)))))
1404
1405
1406 (defvar *block-counter* 0)
1407
1408 (define-compilation block (name &rest body)
1409   (let ((tr (integer-to-string (incf *block-counter*))))
1410     (let ((b (make-binding name 'block tr)))
1411       (js!selfcall
1412         "try {" *newline*
1413         (let ((*environment* (extend-lexenv (list b) *environment* 'block)))
1414           (indent "return " (ls-compile `(progn ,@body)) ";" *newline*))
1415         "}" *newline*
1416         "catch (cf){" *newline*
1417         "    if (cf.type == 'block' && cf.id == " tr ")" *newline*
1418         "        return cf.value;" *newline*
1419         "    else" *newline*
1420         "        throw cf;" *newline*
1421         "}" *newline*))))
1422
1423 (define-compilation return-from (name &optional value)
1424   (let ((b (lookup-in-lexenv name *environment* 'block)))
1425     (if b
1426         (js!selfcall
1427           "throw ({"
1428           "type: 'block', "
1429           "id: " (binding-value b) ", "
1430           "value: " (ls-compile value) ", "
1431           "message: 'Return from unknown block " (symbol-name name) ".'"
1432           "})")
1433         (error (concat "Unknown block `" (symbol-name name) "'.")))))
1434
1435
1436 (define-compilation catch (id &rest body)
1437   (js!selfcall
1438     "var id = " (ls-compile id) ";" *newline*
1439     "try {" *newline*
1440     (indent "return " (ls-compile `(progn ,@body))
1441             ";" *newline*)
1442     "}" *newline*
1443     "catch (cf){" *newline*
1444     "    if (cf.type == 'catch' && cf.id == id)" *newline*
1445     "        return cf.value;" *newline*
1446     "    else" *newline*
1447     "        throw cf;" *newline*
1448     "}" *newline*))
1449
1450 (define-compilation throw (id value)
1451   (js!selfcall
1452     "throw ({"
1453     "type: 'catch', "
1454     "id: " (ls-compile id) ", "
1455     "value: " (ls-compile value) ", "
1456     "message: 'Throw uncatched.'"
1457     "})"))
1458
1459
1460 (defvar *tagbody-counter* 0)
1461 (defvar *go-tag-counter* 0)
1462
1463 (defun go-tag-p (x)
1464   (or (integerp x) (symbolp x)))
1465
1466 (defun declare-tagbody-tags (tbidx body)
1467   (let ((bindings
1468          (mapcar (lambda (label)
1469                    (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1470                      (make-binding label 'gotag (list tbidx tagidx))))
1471                  (remove-if-not #'go-tag-p body))))
1472     (extend-lexenv bindings *environment* 'gotag)))
1473
1474 (define-compilation tagbody (&rest body)
1475   ;; Ignore the tagbody if it does not contain any go-tag. We do this
1476   ;; because 1) it is easy and 2) many built-in forms expand to a
1477   ;; implicit tagbody, so we save some space.
1478   (unless (some #'go-tag-p body)
1479     (return-from tagbody (ls-compile `(progn ,@body nil))))
1480   ;; The translation assumes the first form in BODY is a label
1481   (unless (go-tag-p (car body))
1482     (push (gensym "START") body))
1483   ;; Tagbody compilation
1484   (let ((tbidx (integer-to-string *tagbody-counter*)))
1485     (let ((*environment* (declare-tagbody-tags tbidx body))
1486           initag)
1487       (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1488         (setq initag (second (binding-value b))))
1489       (js!selfcall
1490         "var tagbody_" tbidx " = " initag ";" *newline*
1491         "tbloop:" *newline*
1492         "while (true) {" *newline*
1493         (indent "try {" *newline*
1494                 (indent (let ((content ""))
1495                           (concat "switch(tagbody_" tbidx "){" *newline*
1496                                   "case " initag ":" *newline*
1497                                   (dolist (form (cdr body) content)
1498                                     (concatf content
1499                                       (if (not (go-tag-p form))
1500                                           (indent (ls-compile form) ";" *newline*)
1501                                           (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1502                                             (concat "case " (second (binding-value b)) ":" *newline*)))))
1503                                   "default:" *newline*
1504                                   "    break tbloop;" *newline*
1505                                   "}" *newline*)))
1506                 "}" *newline*
1507                 "catch (jump) {" *newline*
1508                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1509                 "        tagbody_" tbidx " = jump.label;" *newline*
1510                 "    else" *newline*
1511                 "        throw(jump);" *newline*
1512                 "}" *newline*)
1513         "}" *newline*
1514         "return " (ls-compile nil) ";" *newline*))))
1515
1516 (define-compilation go (label)
1517   (let ((b (lookup-in-lexenv label *environment* 'gotag))
1518         (n (cond
1519              ((symbolp label) (symbol-name label))
1520              ((integerp label) (integer-to-string label)))))
1521     (if b
1522         (js!selfcall
1523           "throw ({"
1524           "type: 'tagbody', "
1525           "id: " (first (binding-value b)) ", "
1526           "label: " (second (binding-value b)) ", "
1527           "message: 'Attempt to GO to non-existing tag " n "'"
1528           "})" *newline*)
1529         (error (concat "Unknown tag `" n "'.")))))
1530
1531
1532 (define-compilation unwind-protect (form &rest clean-up)
1533   (js!selfcall
1534     "var ret = " (ls-compile nil) ";" *newline*
1535     "try {" *newline*
1536     (indent "ret = " (ls-compile form) ";" *newline*)
1537     "} finally {" *newline*
1538     (indent (ls-compile-block clean-up))
1539     "}" *newline*
1540     "return ret;" *newline*))
1541
1542
1543 ;;; A little backquote implementation without optimizations of any
1544 ;;; kind for ecmalisp.
1545 (defun backquote-expand-1 (form)
1546   (cond
1547     ((symbolp form)
1548      (list 'quote form))
1549     ((atom form)
1550      form)
1551     ((eq (car form) 'unquote)
1552      (car form))
1553     ((eq (car form) 'backquote)
1554      (backquote-expand-1 (backquote-expand-1 (cadr form))))
1555     (t
1556      (cons 'append
1557            (mapcar (lambda (s)
1558                      (cond
1559                        ((and (listp s) (eq (car s) 'unquote))
1560                         (list 'list (cadr s)))
1561                        ((and (listp s) (eq (car s) 'unquote-splicing))
1562                         (cadr s))
1563                        (t
1564                         (list 'list (backquote-expand-1 s)))))
1565                    form)))))
1566
1567 (defun backquote-expand (form)
1568   (if (and (listp form) (eq (car form) 'backquote))
1569       (backquote-expand-1 (cadr form))
1570       form))
1571
1572 (defmacro backquote (form)
1573   (backquote-expand-1 form))
1574
1575 (define-transformation backquote (form)
1576   (backquote-expand-1 form))
1577
1578 ;;; Primitives
1579
1580 (defvar *builtins* nil)
1581
1582 (defmacro define-raw-builtin (name args &body body)
1583   ;; Creates a new primitive function `name' with parameters args and
1584   ;; @body. The body can access to the local environment through the
1585   ;; variable *ENVIRONMENT*.
1586   `(push (list ',name (lambda ,args (block ,name ,@body)))
1587          *builtins*))
1588
1589 (defmacro define-builtin (name args &body body)
1590   `(progn
1591      (define-raw-builtin ,name ,args
1592        (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1593          ,@body))))
1594
1595 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1596 (defmacro type-check (decls &body body)
1597   `(js!selfcall
1598      ,@(mapcar (lambda (decl)
1599                    `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1600                  decls)
1601      ,@(mapcar (lambda (decl)
1602                  `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1603                           (indent "throw 'The value ' + "
1604                                   ,(first decl)
1605                                   " + ' is not a type "
1606                                   ,(second decl)
1607                                   ".';"
1608                                   *newline*)))
1609                decls)
1610      (concat "return " (progn ,@body) ";" *newline*)))
1611
1612 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
1613 ;;; a variable which holds a list of forms. It will compile them and
1614 ;;; store the result in some Javascript variables. BODY is evaluated
1615 ;;; with ARGS bound to the list of these variables to generate the
1616 ;;; code which performs the transformation on these variables.
1617
1618 (defun variable-arity-call (args function)
1619   (unless (consp args)
1620     (error "ARGS must be a non-empty list"))
1621   (let ((counter 0)
1622         (variables '())
1623         (prelude ""))
1624     (dolist (x args)
1625       (let ((v (concat "x" (integer-to-string (incf counter)))))
1626         (push v variables)
1627         (concatf prelude
1628                  (concat "var " v " = " (ls-compile x) ";" *newline*
1629                          "if (typeof " v " !== 'number') throw 'Not a number!';"
1630                          *newline*))))
1631     (js!selfcall prelude (funcall function (reverse variables)))))
1632
1633
1634 (defmacro variable-arity (args &body body)
1635   (unless (symbolp args)
1636     (error "Bad usage of VARIABLE-ARITY, you must pass a symbol"))
1637   `(variable-arity-call ,args
1638                         (lambda (,args)
1639                           (concat "return " ,@body ";" *newline*))))
1640
1641 (defun num-op-num (x op y)
1642   (type-check (("x" "number" x) ("y" "number" y))
1643     (concat "x" op "y")))
1644
1645 (define-raw-builtin + (&rest numbers)
1646   (if (null numbers)
1647       "0"
1648       (variable-arity numbers
1649         (join numbers "+"))))
1650
1651 (define-raw-builtin - (x &rest others)
1652   (let ((args (cons x others)))
1653     (variable-arity args
1654       (if (null others)
1655           (concat "-" (car args))
1656           (join args "-")))))
1657
1658 (define-raw-builtin * (&rest numbers)
1659   (if (null numbers)
1660       "1"
1661       (variable-arity numbers
1662         (join numbers "*"))))
1663
1664 (define-raw-builtin / (x &rest others)
1665   (let ((args (cons x others)))
1666     (variable-arity args
1667       (if (null others)
1668           (concat "1 /" (car args))
1669           (join args "/")))))
1670
1671 (define-builtin mod (x y) (num-op-num x "%" y))
1672
1673
1674 (defun comparison-conjuntion (vars op)
1675   (cond
1676     ((null (cdr vars))
1677      "true")
1678     ((null (cddr vars))
1679      (concat (car vars) op (cadr vars)))
1680     (t
1681      (concat (car vars) op (cadr vars)
1682              " && "
1683              (comparison-conjuntion (cdr vars) op)))))
1684
1685 (defmacro define-builtin-comparison (op sym)
1686   `(define-raw-builtin ,op (x &rest args)
1687      (let ((args (cons x args)))
1688        (variable-arity args
1689          (js!bool (comparison-conjuntion args ,sym))))))
1690
1691 (define-builtin-comparison > ">")
1692 (define-builtin-comparison < "<")
1693 (define-builtin-comparison >= ">=")
1694 (define-builtin-comparison <= "<=")
1695 (define-builtin-comparison = "==")
1696
1697 (define-builtin numberp (x)
1698   (js!bool (concat "(typeof (" x ") == \"number\")")))
1699
1700 (define-builtin floor (x)
1701   (type-check (("x" "number" x))
1702     "Math.floor(x)"))
1703
1704 (define-builtin cons (x y)
1705   (concat "({car: " x ", cdr: " y "})"))
1706
1707 (define-builtin consp (x)
1708   (js!bool
1709    (js!selfcall
1710      "var tmp = " x ";" *newline*
1711      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1712
1713 (define-builtin car (x)
1714   (js!selfcall
1715     "var tmp = " x ";" *newline*
1716     "return tmp === " (ls-compile nil)
1717     "? " (ls-compile nil)
1718     ": tmp.car;" *newline*))
1719
1720 (define-builtin cdr (x)
1721   (js!selfcall
1722     "var tmp = " x ";" *newline*
1723     "return tmp === " (ls-compile nil) "? "
1724     (ls-compile nil)
1725     ": tmp.cdr;" *newline*))
1726
1727 (define-builtin setcar (x new)
1728   (type-check (("x" "object" x))
1729     (concat "(x.car = " new ")")))
1730
1731 (define-builtin setcdr (x new)
1732   (type-check (("x" "object" x))
1733     (concat "(x.cdr = " new ")")))
1734
1735 (define-builtin symbolp (x)
1736   (js!bool
1737    (js!selfcall
1738      "var tmp = " x ";" *newline*
1739      "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1740
1741 (define-builtin make-symbol (name)
1742   (type-check (("name" "string" name))
1743     "({name: name})"))
1744
1745 (define-builtin symbol-name (x)
1746   (concat "(" x ").name"))
1747
1748 (define-builtin set (symbol value)
1749   (concat "(" symbol ").value = " value))
1750
1751 (define-builtin fset (symbol value)
1752   (concat "(" symbol ").function = " value))
1753
1754 (define-builtin boundp (x)
1755   (js!bool (concat "(" x ".value !== undefined)")))
1756
1757 (define-builtin symbol-value (x)
1758   (js!selfcall
1759     "var symbol = " x ";" *newline*
1760     "var value = symbol.value;" *newline*
1761     "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1762     "return value;" *newline*))
1763
1764 (define-builtin symbol-function (x)
1765   (js!selfcall
1766     "var symbol = " x ";" *newline*
1767     "var func = symbol.function;" *newline*
1768     "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1769     "return func;" *newline*))
1770
1771 (define-builtin symbol-plist (x)
1772   (concat "((" x ").plist || " (ls-compile nil) ")"))
1773
1774 (define-builtin lambda-code (x)
1775   (concat "(" x ").toString()"))
1776
1777 (define-builtin eq    (x y) (js!bool (concat "(" x " === " y ")")))
1778 (define-builtin equal (x y) (js!bool (concat "(" x  " == " y ")")))
1779
1780 (define-builtin char-to-string (x)
1781   (type-check (("x" "number" x))
1782     "String.fromCharCode(x)"))
1783
1784 (define-builtin stringp (x)
1785   (js!bool (concat "(typeof(" x ") == \"string\")")))
1786
1787 (define-builtin string-upcase (x)
1788   (type-check (("x" "string" x))
1789     "x.toUpperCase()"))
1790
1791 (define-builtin string-length (x)
1792   (type-check (("x" "string" x))
1793     "x.length"))
1794
1795 (define-raw-builtin slice (string a &optional b)
1796   (js!selfcall
1797     "var str = " (ls-compile string) ";" *newline*
1798     "var a = " (ls-compile a) ";" *newline*
1799     "var b;" *newline*
1800     (if b
1801         (concat "b = " (ls-compile b) ";" *newline*)
1802         "")
1803     "return str.slice(a,b);" *newline*))
1804
1805 (define-builtin char (string index)
1806   (type-check (("string" "string" string)
1807                ("index" "number" index))
1808     "string.charCodeAt(index)"))
1809
1810 (define-builtin concat-two (string1 string2)
1811   (type-check (("string1" "string" string1)
1812                ("string2" "string" string2))
1813     "string1.concat(string2)"))
1814
1815 (define-raw-builtin funcall (func &rest args)
1816   (concat "(" (ls-compile func) ")("
1817           (join (mapcar #'ls-compile args)
1818                 ", ")
1819           ")"))
1820
1821 (define-raw-builtin apply (func &rest args)
1822   (if (null args)
1823       (concat "(" (ls-compile func) ")()")
1824       (let ((args (butlast args))
1825             (last (car (last args))))
1826         (js!selfcall
1827           "var f = " (ls-compile func) ";" *newline*
1828           "var args = [" (join (mapcar #'ls-compile args)
1829                                ", ")
1830           "];" *newline*
1831           "var tail = (" (ls-compile last) ");" *newline*
1832           "while (tail != " (ls-compile nil) "){" *newline*
1833           "    args.push(tail.car);" *newline*
1834           "    tail = tail.cdr;" *newline*
1835           "}" *newline*
1836           "return f.apply(this, args);" *newline*))))
1837
1838 (define-builtin js-eval (string)
1839   (type-check (("string" "string" string))
1840     "eval.apply(window, [string])"))
1841
1842 (define-builtin error (string)
1843   (js!selfcall "throw " string ";" *newline*))
1844
1845 (define-builtin new () "{}")
1846
1847 (define-builtin objectp (x)
1848   (js!bool (concat "(typeof (" x ") === 'object')")))
1849
1850 (define-builtin oget (object key)
1851   (js!selfcall
1852     "var tmp = " "(" object ")[" key "];" *newline*
1853     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1854
1855 (define-builtin oset (object key value)
1856   (concat "((" object ")[" key "] = " value ")"))
1857
1858 (define-builtin in (key object)
1859   (js!bool (concat "((" key ") in (" object "))")))
1860
1861 (define-builtin functionp (x)
1862   (js!bool (concat "(typeof " x " == 'function')")))
1863
1864 (define-builtin write-string (x)
1865   (type-check (("x" "string" x))
1866     "lisp.write(x)"))
1867
1868 (define-builtin make-array (n)
1869   (js!selfcall
1870     "var r = [];" *newline*
1871     "for (var i = 0; i < " n "; i++)" *newline*
1872     (indent "r.push(" (ls-compile nil) ");" *newline*)
1873     "return r;" *newline*))
1874
1875 (define-builtin arrayp (x)
1876   (js!bool
1877    (js!selfcall
1878      "var x = " x ";" *newline*
1879      "return typeof x === 'object' && 'length' in x;")))
1880
1881 (define-builtin aref (array n)
1882   (js!selfcall
1883     "var x = " "(" array ")[" n "];" *newline*
1884     "if (x === undefined) throw 'Out of range';" *newline*
1885     "return x;" *newline*))
1886
1887 (define-builtin aset (array n value)
1888   (js!selfcall
1889     "var x = " array ";" *newline*
1890     "var i = " n ";" *newline*
1891     "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
1892     "return x[i] = " value ";" *newline*))
1893
1894
1895 (defun macro (x)
1896   (and (symbolp x)
1897        (let ((b (lookup-in-lexenv x *environment* 'function)))
1898          (and (eq (binding-type b) 'macro)
1899               b))))
1900
1901 (defun ls-macroexpand-1 (form)
1902   (let ((macro-binding (macro (car form))))
1903     (if macro-binding
1904         (let ((expander (binding-value macro-binding)))
1905           (when (listp expander)
1906             (let ((compiled (eval expander)))
1907               ;; The list representation are useful while
1908               ;; bootstrapping, as we can dump the definition of the
1909               ;; macros easily, but they are slow because we have to
1910               ;; evaluate them and compile them now and again. So, let
1911               ;; us replace the list representation version of the
1912               ;; function with the compiled one.
1913               ;;
1914               #+ecmalisp (set-binding-value macro-binding compiled)
1915               (setq expander compiled)))
1916           (apply expander (cdr form)))
1917         form)))
1918
1919 (defun compile-funcall (function args)
1920   (if (and (symbolp function)
1921            (claimp function 'function 'non-overridable))
1922       (concat (ls-compile `',function) ".function("
1923               (join (mapcar #'ls-compile args)
1924                     ", ")
1925               ")")
1926       (concat (ls-compile `#',function) "("
1927               (join (mapcar #'ls-compile args)
1928                     ", ")
1929               ")")))
1930
1931 (defun ls-compile-block (sexps &optional return-last-p)
1932   (if return-last-p
1933       (concat (ls-compile-block (butlast sexps))
1934               "return " (ls-compile (car (last sexps))) ";")
1935       (join-trailing
1936        (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
1937        (concat ";" *newline*))))
1938
1939 (defun ls-compile (sexp)
1940   (cond
1941     ((symbolp sexp)
1942      (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1943        (cond
1944          ((and b (not (member 'special (binding-declarations b))))
1945           (binding-value b))
1946          ((or (keywordp sexp)
1947               (member 'constant (binding-declarations b)))
1948           (concat (ls-compile `',sexp) ".value"))
1949          (t
1950           (ls-compile `(symbol-value ',sexp))))))
1951     ((integerp sexp) (integer-to-string sexp))
1952     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1953     ((arrayp sexp) (literal sexp))
1954     ((listp sexp)
1955      (let ((name (car sexp))
1956            (args (cdr sexp)))
1957        (cond
1958          ;; Special forms
1959          ((assoc name *compilations*)
1960           (let ((comp (second (assoc name *compilations*))))
1961             (apply comp args)))
1962          ;; Built-in functions
1963          ((and (assoc name *builtins*)
1964                (not (claimp name 'function 'notinline)))
1965           (let ((comp (second (assoc name *builtins*))))
1966             (apply comp args)))
1967          (t
1968           (if (macro name)
1969               (ls-compile (ls-macroexpand-1 sexp))
1970               (compile-funcall name args))))))
1971     (t
1972      (error "How should I compile this?"))))
1973
1974 (defun ls-compile-toplevel (sexp)
1975   (let ((*toplevel-compilations* nil))
1976     (cond
1977       ((and (consp sexp) (eq (car sexp) 'progn))
1978        (let ((subs (mapcar #'ls-compile-toplevel (cdr sexp))))
1979          (join (remove-if #'null-or-empty-p subs))))
1980       (t
1981        (let ((code (ls-compile sexp)))
1982          (concat (join-trailing (get-toplevel-compilations)
1983                                 (concat ";" *newline*))
1984                  (if code
1985                      (concat code ";" *newline*)
1986                      "")))))))
1987
1988
1989 ;;; Once we have the compiler, we define the runtime environment and
1990 ;;; interactive development (eval), which works calling the compiler
1991 ;;; and evaluating the Javascript result globally.
1992
1993 #+ecmalisp
1994 (progn
1995   (defmacro with-compilation-unit (&body body)
1996     `(prog1
1997          (progn
1998            (setq *compilation-unit-checks* nil)
1999            ,@body)
2000        (dolist (check *compilation-unit-checks*)
2001          (funcall check))))
2002
2003   (defun eval (x)
2004     (let ((code
2005            (with-compilation-unit
2006                (ls-compile-toplevel x))))
2007       (js-eval code)))
2008
2009   (export '(&rest &optional &body * *gensym-counter* *package* + - /
2010             1+ 1- < <= = = > >= and append apply aref arrayp aset
2011             assoc atom block boundp boundp butlast caar cadddr caddr
2012             cadr car car case catch cdar cdddr cddr cdr cdr char
2013             char-code char= code-char cond cons consp copy-list decf
2014             declaim defparameter defun defvar digit-char-p disassemble
2015             documentation dolist dotimes ecase eq eql equal error eval
2016             every export fdefinition find-package find-symbol first
2017             fourth fset funcall function functionp gensym go identity
2018             if in-package incf integerp integerp intern keywordp
2019             lambda last length let let* list-all-packages list listp
2020             make-array make-package make-symbol mapcar member minusp
2021             mod nil not nth nthcdr null numberp or package-name
2022             package-use-list packagep plusp prin1-to-string print
2023             proclaim prog1 prog2 pron push quote remove remove-if
2024             remove-if-not return return-from revappend reverse second
2025             set setq some string-upcase string string= stringp subseq
2026             symbol-function symbol-name symbol-package symbol-plist
2027             symbol-value symbolp t tagbody third throw truncate unless
2028             unwind-protect variable warn when write-line write-string
2029             zerop))
2030
2031   (setq *package* *user-package*)
2032
2033   (js-eval "var lisp")
2034   (js-vset "lisp" (new))
2035   (js-vset "lisp.read" #'ls-read-from-string)
2036   (js-vset "lisp.print" #'prin1-to-string)
2037   (js-vset "lisp.eval" #'eval)
2038   (js-vset "lisp.compile" #'ls-compile-toplevel)
2039   (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
2040   (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str))))
2041
2042   ;; Set the initial global environment to be equal to the host global
2043   ;; environment at this point of the compilation.
2044   (eval-when-compile
2045     (toplevel-compilation
2046      (ls-compile
2047       `(progn
2048          ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
2049                    *literal-symbols*)
2050          (setq *literal-symbols* ',*literal-symbols*)
2051          (setq *environment* ',*environment*)
2052          (setq *variable-counter* ,*variable-counter*)
2053          (setq *gensym-counter* ,*gensym-counter*)
2054          (setq *block-counter* ,*block-counter*)))))
2055
2056   (eval-when-compile
2057     (toplevel-compilation
2058      (ls-compile
2059       `(setq *literal-counter* ,*literal-counter*)))))
2060
2061
2062 ;;; Finally, we provide a couple of functions to easily bootstrap
2063 ;;; this. It just calls the compiler with this file as input.
2064
2065 #+common-lisp
2066 (progn
2067   (defun read-whole-file (filename)
2068     (with-open-file (in filename)
2069       (let ((seq (make-array (file-length in) :element-type 'character)))
2070         (read-sequence seq in)
2071         seq)))
2072
2073   (defun ls-compile-file (filename output)
2074     (setq *compilation-unit-checks* nil)
2075     (with-open-file (out output :direction :output :if-exists :supersede)
2076       (let* ((source (read-whole-file filename))
2077              (in (make-string-stream source)))
2078         (loop
2079            for x = (ls-read in)
2080            until (eq x *eof*)
2081            for compilation = (ls-compile-toplevel x)
2082            when (plusp (length compilation))
2083            do (write-string compilation out))
2084         (dolist (check *compilation-unit-checks*)
2085           (funcall check))
2086         (setq *compilation-unit-checks* nil))))
2087
2088   (defun bootstrap ()
2089     (setq *environment* (make-lexenv))
2090     (setq *literal-symbols* nil)
2091     (setq *variable-counter* 0
2092           *gensym-counter* 0
2093           *literal-counter* 0
2094           *block-counter* 0)
2095     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))