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