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