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