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