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