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