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