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