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