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