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