a87a86e7b9c36a84e7319c72fdba355d3f38b3c1
[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))
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-required-arguments (lambda-list)
1202   (list-until-keyword lambda-list))
1203
1204 (defun lambda-list-optional-arguments-with-default (lambda-list)
1205   (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
1206
1207 (defun lambda-list-optional-arguments (lambda-list)
1208   (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
1209
1210 (defun lambda-list-rest-argument (lambda-list)
1211   (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
1212     (when (cdr rest)
1213       (error "Bad lambda-list"))
1214     (car rest)))
1215
1216 (defun lambda-docstring-wrapper (docstring &rest strs)
1217   (if docstring
1218       (js!selfcall
1219         "var func = " (join strs) ";" *newline*
1220         "func.docstring = '" docstring "';" *newline*
1221         "return func;" *newline*)
1222       (join strs)))
1223
1224 (defun lambda-check-argument-count
1225     (n-required-arguments n-optional-arguments rest-p)
1226   ;; Note: Remember that we assume that the number of arguments of a
1227   ;; call is at least 1 (the values argument).
1228   (let ((min (1+ n-required-arguments))
1229         (max (if rest-p 'n/a (+ 1 n-required-arguments n-optional-arguments))))
1230     (block nil
1231       ;; Special case: a positive exact number of arguments.
1232       (when (and (< 1 min) (eql min max))
1233         (return (concat "checkArgs(arguments, " (integer-to-string min) ");" *newline*)))
1234       ;; General case:
1235       (concat
1236        (if (< 1 min)
1237            (concat "checkArgsAtLeast(arguments, " (integer-to-string min) ");" *newline*)
1238            "")
1239        (if (numberp max)
1240            (concat "checkArgsAtMost(arguments, " (integer-to-string max) ");" *newline*)
1241            "")))))
1242
1243 (defun compile-lambda (lambda-list body)
1244   (let ((required-arguments (lambda-list-required-arguments lambda-list))
1245         (optional-arguments (lambda-list-optional-arguments lambda-list))
1246         (rest-argument (lambda-list-rest-argument lambda-list))
1247         documentation)
1248     ;; Get the documentation string for the lambda function
1249     (when (and (stringp (car body))
1250                (not (null (cdr body))))
1251       (setq documentation (car body))
1252       (setq body (cdr body)))
1253     (let ((n-required-arguments (length required-arguments))
1254           (n-optional-arguments (length optional-arguments))
1255           (*environment* (extend-local-env
1256                           (append (ensure-list rest-argument)
1257                                   required-arguments
1258                                   optional-arguments))))
1259       (lambda-docstring-wrapper
1260        documentation
1261        "(function ("
1262        (join (cons "values"
1263                    (mapcar #'translate-variable
1264                            (append required-arguments optional-arguments)))
1265              ",")
1266        "){" *newline*
1267        (indent
1268         ;; Check number of arguments
1269         (lambda-check-argument-count n-required-arguments
1270                                      n-optional-arguments
1271                                      rest-argument)
1272         ;; Optional arguments
1273         (if optional-arguments
1274             (concat "switch(arguments.length-1){" *newline*
1275                     (let ((optional-and-defaults
1276                            (lambda-list-optional-arguments-with-default lambda-list))
1277                           (cases nil)
1278                           (idx 0))
1279                       (progn
1280                         (while (< idx n-optional-arguments)
1281                           (let ((arg (nth idx optional-and-defaults)))
1282                             (push (concat "case "
1283                                           (integer-to-string (+ idx n-required-arguments)) ":" *newline*
1284                                           (translate-variable (car arg))
1285                                           "="
1286                                           (ls-compile (cadr arg))
1287                                           ";" *newline*)
1288                                   cases)
1289                             (incf idx)))
1290                         (push (concat "default: break;" *newline*) cases)
1291                         (join (reverse cases))))
1292                     "}" *newline*)
1293             "")
1294         ;; &rest/&body argument
1295         (if rest-argument
1296             (let ((js!rest (translate-variable rest-argument)))
1297               (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
1298                       "for (var i = arguments.length-1; i>="
1299                       (integer-to-string (+ 1 n-required-arguments n-optional-arguments))
1300                       "; i--)" *newline*
1301                       (indent js!rest " = "
1302                               "{car: arguments[i], cdr: ") js!rest "};"
1303                       *newline*))
1304             "")
1305         ;; Body
1306         (let ((*multiple-value-p* t)) (ls-compile-block body t)))
1307        "})"))))
1308
1309
1310 (defun setq-pair (var val)
1311   (let ((b (lookup-in-lexenv var *environment* 'variable)))
1312     (if (and (eq (binding-type b) 'variable)
1313              (not (member 'special (binding-declarations b)))
1314              (not (member 'constant (binding-declarations b))))
1315         (concat (binding-value b) " = " (ls-compile val))
1316         (ls-compile `(set ',var ,val)))))
1317
1318 (define-compilation setq (&rest pairs)
1319   (let ((result ""))
1320     (while t
1321       (cond
1322         ((null pairs) (return))
1323         ((null (cdr pairs))
1324          (error "Odd paris in SETQ"))
1325         (t
1326          (concatf result
1327            (concat (setq-pair (car pairs) (cadr pairs))
1328                    (if (null (cddr pairs)) "" ", ")))
1329          (setq pairs (cddr pairs)))))
1330     (concat "(" result ")")))
1331
1332 ;;; FFI Variable accessors
1333 (define-compilation js-vref (var)
1334   var)
1335
1336 (define-compilation js-vset (var val)
1337   (concat "(" var " = " (ls-compile val) ")"))
1338
1339
1340
1341 ;;; Literals
1342 (defun escape-string (string)
1343   (let ((output "")
1344         (index 0)
1345         (size (length string)))
1346     (while (< index size)
1347       (let ((ch (char string index)))
1348         (when (or (char= ch #\") (char= ch #\\))
1349           (setq output (concat output "\\")))
1350         (when (or (char= ch #\newline))
1351           (setq output (concat output "\\"))
1352           (setq ch #\n))
1353         (setq output (concat output (string ch))))
1354       (incf index))
1355     output))
1356
1357
1358 (defvar *literal-symbols* nil)
1359 (defvar *literal-counter* 0)
1360
1361 (defun genlit ()
1362   (concat "l" (integer-to-string (incf *literal-counter*))))
1363
1364 (defun literal (sexp &optional recursive)
1365   (cond
1366     ((integerp sexp) (integer-to-string sexp))
1367     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1368     ((symbolp sexp)
1369      (or (cdr (assoc sexp *literal-symbols*))
1370          (let ((v (genlit))
1371                (s #+common-lisp
1372                  (let ((package (symbol-package sexp)))
1373                    (if (eq package (find-package "KEYWORD"))
1374                        (concat "{name: \"" (escape-string (symbol-name sexp))
1375                                "\", 'package': '" (package-name package) "'}")
1376                        (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")))
1377                  #+ecmalisp
1378                  (let ((package (symbol-package sexp)))
1379                    (if (null package)
1380                        (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1381                        (ls-compile `(intern ,(symbol-name sexp) ,(package-name package)))))))
1382            (push (cons sexp v) *literal-symbols*)
1383            (toplevel-compilation (concat "var " v " = " s))
1384            v)))
1385     ((consp sexp)
1386      (let* ((head (butlast sexp))
1387             (tail (last sexp))
1388             (c (concat "QIList("
1389                        (join-trailing (mapcar (lambda (x) (literal x t)) head) ",")
1390                        (literal (car tail) t)
1391                        ","
1392                        (literal (cdr tail) t)
1393                        ")")))
1394        (if recursive
1395            c
1396            (let ((v (genlit)))
1397              (toplevel-compilation (concat "var " v " = " c))
1398              v))))
1399     ((arrayp sexp)
1400      (let ((elements (vector-to-list sexp)))
1401        (let ((c (concat "[" (join (mapcar #'literal elements) ", ") "]")))
1402          (if recursive
1403              c
1404              (let ((v (genlit)))
1405                (toplevel-compilation (concat "var " v " = " c))
1406                v)))))))
1407
1408 (define-compilation quote (sexp)
1409   (literal sexp))
1410
1411 (define-compilation %while (pred &rest body)
1412   (js!selfcall
1413     "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1414     (indent (ls-compile-block body))
1415     "}"
1416     "return " (ls-compile nil) ";" *newline*))
1417
1418 (define-compilation function (x)
1419   (cond
1420     ((and (listp x) (eq (car x) 'lambda))
1421      (compile-lambda (cadr x) (cddr x)))
1422     ((symbolp x)
1423      (let ((b (lookup-in-lexenv x *environment* 'function)))
1424        (if b
1425            (binding-value b)
1426            (ls-compile `(symbol-function ',x)))))))
1427
1428
1429 (defun make-function-binding (fname)
1430   (make-binding fname 'function (gvarname fname)))
1431
1432 (defun compile-function-definition (list)
1433   (compile-lambda (car list) (cdr list)))
1434
1435 (defun translate-function (name)
1436   (let ((b (lookup-in-lexenv name *environment* 'function)))
1437     (binding-value b)))
1438
1439 (define-compilation flet (definitions &rest body)
1440   (let* ((fnames (mapcar #'car definitions))
1441          (fbody  (mapcar #'cdr definitions))
1442          (cfuncs (mapcar #'compile-function-definition fbody))
1443          (*environment*
1444           (extend-lexenv (mapcar #'make-function-binding fnames)
1445                          *environment*
1446                          'function)))
1447     (concat "(function("
1448             (join (mapcar #'translate-function fnames) ",")
1449             "){" *newline*
1450             (let ((body (ls-compile-block body t)))
1451               (indent body))
1452             "})(" (join cfuncs ",") ")")))
1453
1454 (define-compilation labels (definitions &rest body)
1455   (let* ((fnames (mapcar #'car definitions))
1456          (*environment*
1457           (extend-lexenv (mapcar #'make-function-binding fnames)
1458                          *environment*
1459                          'function)))
1460     (js!selfcall
1461       (mapconcat (lambda (func)
1462                    (concat "var " (translate-function (car func))
1463                            " = " (compile-lambda (cadr func) (cddr func))
1464                            ";" *newline*))
1465                  definitions)
1466       (ls-compile-block body t))))
1467
1468
1469
1470 (defvar *compiling-file* nil)
1471 (define-compilation eval-when-compile (&rest body)
1472   (if *compiling-file*
1473       (progn
1474         (eval (cons 'progn body))
1475         nil)
1476       (ls-compile `(progn ,@body))))
1477
1478 (defmacro define-transformation (name args form)
1479   `(define-compilation ,name ,args
1480      (ls-compile ,form)))
1481
1482 (define-compilation progn (&rest body)
1483   (if (null (cdr body))
1484       (ls-compile (car body) *multiple-value-p*)
1485       (js!selfcall (ls-compile-block body t))))
1486
1487 (defun special-variable-p (x)
1488   (and (claimp x 'variable 'special) t))
1489
1490 ;;; Wrap CODE to restore the symbol values of the dynamic
1491 ;;; bindings. BINDINGS is a list of pairs of the form
1492 ;;; (SYMBOL . PLACE),  where PLACE is a Javascript variable
1493 ;;; name to initialize the symbol value and where to stored
1494 ;;; the old value.
1495 (defun let-binding-wrapper (bindings body)
1496   (when (null bindings)
1497     (return-from let-binding-wrapper body))
1498   (concat
1499    "try {" *newline*
1500    (indent "var tmp;" *newline*
1501            (mapconcat
1502             (lambda (b)
1503               (let ((s (ls-compile `(quote ,(car b)))))
1504                 (concat "tmp = " s ".value;" *newline*
1505                         s ".value = " (cdr b) ";" *newline*
1506                         (cdr b) " = tmp;" *newline*)))
1507             bindings)
1508            body *newline*)
1509    "}" *newline*
1510    "finally {"  *newline*
1511    (indent
1512     (mapconcat (lambda (b)
1513                  (let ((s (ls-compile `(quote ,(car b)))))
1514                    (concat s ".value" " = " (cdr b) ";" *newline*)))
1515                bindings))
1516    "}" *newline*))
1517
1518 (define-compilation let (bindings &rest body)
1519   (let* ((bindings (mapcar #'ensure-list bindings))
1520          (variables (mapcar #'first bindings))
1521          (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
1522          (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
1523          (dynamic-bindings))
1524     (concat "(function("
1525             (join (mapcar (lambda (x)
1526                             (if (special-variable-p x)
1527                                 (let ((v (gvarname x)))
1528                                   (push (cons x v) dynamic-bindings)
1529                                   v)
1530                                 (translate-variable x)))
1531                           variables)
1532                   ",")
1533             "){" *newline*
1534             (let ((body (ls-compile-block body t)))
1535               (indent (let-binding-wrapper dynamic-bindings body)))
1536             "})(" (join cvalues ",") ")")))
1537
1538
1539 ;;; Return the code to initialize BINDING, and push it extending the
1540 ;;; current lexical environment if the variable is not special.
1541 (defun let*-initialize-value (binding)
1542   (let ((var (first binding))
1543         (value (second binding)))
1544     (if (special-variable-p var)
1545         (concat (ls-compile `(setq ,var ,value)) ";" *newline*)
1546         (let* ((v (gvarname var))
1547                (b (make-binding var 'variable v)))
1548           (prog1 (concat "var " v " = " (ls-compile value) ";" *newline*)
1549             (push-to-lexenv b *environment* 'variable))))))
1550
1551 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
1552 ;;; DOES NOT generate code to initialize the value of the symbols,
1553 ;;; unlike let-binding-wrapper.
1554 (defun let*-binding-wrapper (symbols body)
1555   (when (null symbols)
1556     (return-from let*-binding-wrapper body))
1557   (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
1558                        (remove-if-not #'special-variable-p symbols))))
1559     (concat
1560      "try {" *newline*
1561      (indent
1562       (mapconcat (lambda (b)
1563                    (let ((s (ls-compile `(quote ,(car b)))))
1564                      (concat "var " (cdr b) " = " s ".value;" *newline*)))
1565                  store)
1566       body)
1567      "}" *newline*
1568      "finally {" *newline*
1569      (indent
1570       (mapconcat (lambda (b)
1571                    (let ((s (ls-compile `(quote ,(car b)))))
1572                      (concat s ".value" " = " (cdr b) ";" *newline*)))
1573                  store))
1574      "}" *newline*)))
1575
1576 (define-compilation let* (bindings &rest body)
1577   (let ((bindings (mapcar #'ensure-list bindings))
1578         (*environment* (copy-lexenv *environment*)))
1579     (js!selfcall
1580       (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
1581             (body (concat (mapconcat #'let*-initialize-value bindings)
1582                           (ls-compile-block body t))))
1583         (let*-binding-wrapper specials body)))))
1584
1585
1586 (defvar *block-counter* 0)
1587
1588 (define-compilation block (name &rest body)
1589   (let* ((tr (integer-to-string (incf *block-counter*)))
1590          (b (make-binding name 'block tr)))
1591     (when *multiple-value-p*
1592       (push-binding-declaration 'multiple-value b))
1593     (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
1594            (cbody (ls-compile-block body t)))
1595       (if (member 'used (binding-declarations b))
1596           (js!selfcall
1597             "try {" *newline*
1598             (indent cbody)
1599             "}" *newline*
1600             "catch (cf){" *newline*
1601             "    if (cf.type == 'block' && cf.id == " tr ")" *newline*
1602             (if *multiple-value-p*
1603                 "        return values.apply(this, forcemv(cf.values));"
1604                 "        return cf.values;")
1605             *newline*
1606             "    else" *newline*
1607             "        throw cf;" *newline*
1608             "}" *newline*)
1609           (js!selfcall cbody)))))
1610
1611 (define-compilation return-from (name &optional value)
1612   (let* ((b (lookup-in-lexenv name *environment* 'block))
1613          (multiple-value-p (member 'multiple-value (binding-declarations b))))
1614     (when (null b)
1615       (error (concat "Unknown block `" (symbol-name name) "'.")))
1616     (push-binding-declaration 'used b)
1617     (js!selfcall
1618       (if multiple-value-p
1619           (concat "var values = mv;" *newline*)
1620           "")
1621       "throw ({"
1622       "type: 'block', "
1623       "id: " (binding-value b) ", "
1624       "values: " (ls-compile value multiple-value-p) ", "
1625       "message: 'Return from unknown block " (symbol-name name) ".'"
1626       "})")))
1627
1628 (define-compilation catch (id &rest body)
1629   (js!selfcall
1630     "var id = " (ls-compile id) ";" *newline*
1631     "try {" *newline*
1632     (indent (ls-compile-block body t)) *newline*
1633     "}" *newline*
1634     "catch (cf){" *newline*
1635     "    if (cf.type == 'catch' && cf.id == id)" *newline*
1636     (if *multiple-value-p*
1637         "        return values.apply(this, forcemv(cf.values));"
1638         "        return pv.apply(this, forcemv(cf.values));")
1639     *newline*
1640     "    else" *newline*
1641     "        throw cf;" *newline*
1642     "}" *newline*))
1643
1644 (define-compilation throw (id value)
1645   (js!selfcall
1646     "var values = mv;" *newline*
1647     "throw ({"
1648     "type: 'catch', "
1649     "id: " (ls-compile id) ", "
1650     "values: " (ls-compile value t) ", "
1651     "message: 'Throw uncatched.'"
1652     "})"))
1653
1654
1655 (defvar *tagbody-counter* 0)
1656 (defvar *go-tag-counter* 0)
1657
1658 (defun go-tag-p (x)
1659   (or (integerp x) (symbolp x)))
1660
1661 (defun declare-tagbody-tags (tbidx body)
1662   (let ((bindings
1663          (mapcar (lambda (label)
1664                    (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1665                      (make-binding label 'gotag (list tbidx tagidx))))
1666                  (remove-if-not #'go-tag-p body))))
1667     (extend-lexenv bindings *environment* 'gotag)))
1668
1669 (define-compilation tagbody (&rest body)
1670   ;; Ignore the tagbody if it does not contain any go-tag. We do this
1671   ;; because 1) it is easy and 2) many built-in forms expand to a
1672   ;; implicit tagbody, so we save some space.
1673   (unless (some #'go-tag-p body)
1674     (return-from tagbody (ls-compile `(progn ,@body nil))))
1675   ;; The translation assumes the first form in BODY is a label
1676   (unless (go-tag-p (car body))
1677     (push (gensym "START") body))
1678   ;; Tagbody compilation
1679   (let ((tbidx (integer-to-string *tagbody-counter*)))
1680     (let ((*environment* (declare-tagbody-tags tbidx body))
1681           initag)
1682       (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1683         (setq initag (second (binding-value b))))
1684       (js!selfcall
1685         "var tagbody_" tbidx " = " initag ";" *newline*
1686         "tbloop:" *newline*
1687         "while (true) {" *newline*
1688         (indent "try {" *newline*
1689                 (indent (let ((content ""))
1690                           (concat "switch(tagbody_" tbidx "){" *newline*
1691                                   "case " initag ":" *newline*
1692                                   (dolist (form (cdr body) content)
1693                                     (concatf content
1694                                       (if (not (go-tag-p form))
1695                                           (indent (ls-compile form) ";" *newline*)
1696                                           (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1697                                             (concat "case " (second (binding-value b)) ":" *newline*)))))
1698                                   "default:" *newline*
1699                                   "    break tbloop;" *newline*
1700                                   "}" *newline*)))
1701                 "}" *newline*
1702                 "catch (jump) {" *newline*
1703                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1704                 "        tagbody_" tbidx " = jump.label;" *newline*
1705                 "    else" *newline*
1706                 "        throw(jump);" *newline*
1707                 "}" *newline*)
1708         "}" *newline*
1709         "return " (ls-compile nil) ";" *newline*))))
1710
1711 (define-compilation go (label)
1712   (let ((b (lookup-in-lexenv label *environment* 'gotag))
1713         (n (cond
1714              ((symbolp label) (symbol-name label))
1715              ((integerp label) (integer-to-string label)))))
1716     (if b
1717         (js!selfcall
1718           "throw ({"
1719           "type: 'tagbody', "
1720           "id: " (first (binding-value b)) ", "
1721           "label: " (second (binding-value b)) ", "
1722           "message: 'Attempt to GO to non-existing tag " n "'"
1723           "})" *newline*)
1724         (error (concat "Unknown tag `" n "'.")))))
1725
1726 (define-compilation unwind-protect (form &rest clean-up)
1727   (js!selfcall
1728     "var ret = " (ls-compile nil) ";" *newline*
1729     "try {" *newline*
1730     (indent "ret = " (ls-compile form) ";" *newline*)
1731     "} finally {" *newline*
1732     (indent (ls-compile-block clean-up))
1733     "}" *newline*
1734     "return ret;" *newline*))
1735
1736 (define-compilation multiple-value-call (func-form &rest forms)
1737   (js!selfcall
1738     "var func = " (ls-compile func-form) ";" *newline*
1739     "var args = [" (if *multiple-value-p* "values" "pv") "];" *newline*
1740     "return "
1741     (js!selfcall
1742       "var values = mv;" *newline*
1743       "var vs;" *newline*
1744       (mapconcat (lambda (form)
1745                    (concat "vs = " (ls-compile form t) ";" *newline*
1746                            "if (typeof vs === 'object' && 'multiple-value' in vs)" *newline*
1747                            (indent "args = args.concat(vs);" *newline*)
1748                            "else" *newline*
1749                            (indent "args.push(vs);" *newline*)))
1750                  forms)
1751       "return func.apply(window, args);" *newline*) ";" *newline*))
1752
1753 (define-compilation multiple-value-prog1 (first-form &rest forms)
1754   (js!selfcall
1755     "var args = " (ls-compile first-form *multiple-value-p*) ";" *newline*
1756     (ls-compile-block forms)
1757     "return args;" *newline*))
1758
1759
1760
1761 ;;; A little backquote implementation without optimizations of any
1762 ;;; kind for ecmalisp.
1763 (defun backquote-expand-1 (form)
1764   (cond
1765     ((symbolp form)
1766      (list 'quote form))
1767     ((atom form)
1768      form)
1769     ((eq (car form) 'unquote)
1770      (car form))
1771     ((eq (car form) 'backquote)
1772      (backquote-expand-1 (backquote-expand-1 (cadr form))))
1773     (t
1774      (cons 'append
1775            (mapcar (lambda (s)
1776                      (cond
1777                        ((and (listp s) (eq (car s) 'unquote))
1778                         (list 'list (cadr s)))
1779                        ((and (listp s) (eq (car s) 'unquote-splicing))
1780                         (cadr s))
1781                        (t
1782                         (list 'list (backquote-expand-1 s)))))
1783                    form)))))
1784
1785 (defun backquote-expand (form)
1786   (if (and (listp form) (eq (car form) 'backquote))
1787       (backquote-expand-1 (cadr form))
1788       form))
1789
1790 (defmacro backquote (form)
1791   (backquote-expand-1 form))
1792
1793 (define-transformation backquote (form)
1794   (backquote-expand-1 form))
1795
1796 ;;; Primitives
1797
1798 (defvar *builtins* nil)
1799
1800 (defmacro define-raw-builtin (name args &body body)
1801   ;; Creates a new primitive function `name' with parameters args and
1802   ;; @body. The body can access to the local environment through the
1803   ;; variable *ENVIRONMENT*.
1804   `(push (list ',name (lambda ,args (block ,name ,@body)))
1805          *builtins*))
1806
1807 (defmacro define-builtin (name args &body body)
1808   `(progn
1809      (define-raw-builtin ,name ,args
1810        (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1811          ,@body))))
1812
1813 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1814 (defmacro type-check (decls &body body)
1815   `(js!selfcall
1816      ,@(mapcar (lambda (decl)
1817                    `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1818                  decls)
1819      ,@(mapcar (lambda (decl)
1820                  `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1821                           (indent "throw 'The value ' + "
1822                                   ,(first decl)
1823                                   " + ' is not a type "
1824                                   ,(second decl)
1825                                   ".';"
1826                                   *newline*)))
1827                decls)
1828      (concat "return " (progn ,@body) ";" *newline*)))
1829
1830 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
1831 ;;; a variable which holds a list of forms. It will compile them and
1832 ;;; store the result in some Javascript variables. BODY is evaluated
1833 ;;; with ARGS bound to the list of these variables to generate the
1834 ;;; code which performs the transformation on these variables.
1835
1836 (defun variable-arity-call (args function)
1837   (unless (consp args)
1838     (error "ARGS must be a non-empty list"))
1839   (let ((counter 0)
1840         (variables '())
1841         (prelude ""))
1842     (dolist (x args)
1843       (let ((v (concat "x" (integer-to-string (incf counter)))))
1844         (push v variables)
1845         (concatf prelude
1846                  (concat "var " v " = " (ls-compile x) ";" *newline*
1847                          "if (typeof " v " !== 'number') throw 'Not a number!';"
1848                          *newline*))))
1849     (js!selfcall prelude (funcall function (reverse variables)))))
1850
1851
1852 (defmacro variable-arity (args &body body)
1853   (unless (symbolp args)
1854     (error "Bad usage of VARIABLE-ARITY, you must pass a symbol"))
1855   `(variable-arity-call ,args
1856                         (lambda (,args)
1857                           (concat "return " ,@body ";" *newline*))))
1858
1859 (defun num-op-num (x op y)
1860   (type-check (("x" "number" x) ("y" "number" y))
1861     (concat "x" op "y")))
1862
1863 (define-raw-builtin + (&rest numbers)
1864   (if (null numbers)
1865       "0"
1866       (variable-arity numbers
1867         (join numbers "+"))))
1868
1869 (define-raw-builtin - (x &rest others)
1870   (let ((args (cons x others)))
1871     (variable-arity args
1872       (if (null others)
1873           (concat "-" (car args))
1874           (join args "-")))))
1875
1876 (define-raw-builtin * (&rest numbers)
1877   (if (null numbers)
1878       "1"
1879       (variable-arity numbers
1880         (join numbers "*"))))
1881
1882 (define-raw-builtin / (x &rest others)
1883   (let ((args (cons x others)))
1884     (variable-arity args
1885       (if (null others)
1886           (concat "1 /" (car args))
1887           (join args "/")))))
1888
1889 (define-builtin mod (x y) (num-op-num x "%" y))
1890
1891
1892 (defun comparison-conjuntion (vars op)
1893   (cond
1894     ((null (cdr vars))
1895      "true")
1896     ((null (cddr vars))
1897      (concat (car vars) op (cadr vars)))
1898     (t
1899      (concat (car vars) op (cadr vars)
1900              " && "
1901              (comparison-conjuntion (cdr vars) op)))))
1902
1903 (defmacro define-builtin-comparison (op sym)
1904   `(define-raw-builtin ,op (x &rest args)
1905      (let ((args (cons x args)))
1906        (variable-arity args
1907          (js!bool (comparison-conjuntion args ,sym))))))
1908
1909 (define-builtin-comparison > ">")
1910 (define-builtin-comparison < "<")
1911 (define-builtin-comparison >= ">=")
1912 (define-builtin-comparison <= "<=")
1913 (define-builtin-comparison = "==")
1914
1915 (define-builtin numberp (x)
1916   (js!bool (concat "(typeof (" x ") == \"number\")")))
1917
1918 (define-builtin floor (x)
1919   (type-check (("x" "number" x))
1920     "Math.floor(x)"))
1921
1922 (define-builtin cons (x y)
1923   (concat "({car: " x ", cdr: " y "})"))
1924
1925 (define-builtin consp (x)
1926   (js!bool
1927    (js!selfcall
1928      "var tmp = " x ";" *newline*
1929      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1930
1931 (define-builtin car (x)
1932   (js!selfcall
1933     "var tmp = " x ";" *newline*
1934     "return tmp === " (ls-compile nil)
1935     "? " (ls-compile nil)
1936     ": tmp.car;" *newline*))
1937
1938 (define-builtin cdr (x)
1939   (js!selfcall
1940     "var tmp = " x ";" *newline*
1941     "return tmp === " (ls-compile nil) "? "
1942     (ls-compile nil)
1943     ": tmp.cdr;" *newline*))
1944
1945 (define-builtin rplaca (x new)
1946   (type-check (("x" "object" x))
1947     (concat "(x.car = " new ", x)")))
1948
1949 (define-builtin rplacd (x new)
1950   (type-check (("x" "object" x))
1951     (concat "(x.cdr = " new ", x)")))
1952
1953 (define-builtin symbolp (x)
1954   (js!bool
1955    (js!selfcall
1956      "var tmp = " x ";" *newline*
1957      "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1958
1959 (define-builtin make-symbol (name)
1960   (type-check (("name" "string" name))
1961     "({name: name})"))
1962
1963 (define-builtin symbol-name (x)
1964   (concat "(" x ").name"))
1965
1966 (define-builtin set (symbol value)
1967   (concat "(" symbol ").value = " value))
1968
1969 (define-builtin fset (symbol value)
1970   (concat "(" symbol ").fvalue = " value))
1971
1972 (define-builtin boundp (x)
1973   (js!bool (concat "(" x ".value !== undefined)")))
1974
1975 (define-builtin symbol-value (x)
1976   (js!selfcall
1977     "var symbol = " x ";" *newline*
1978     "var value = symbol.value;" *newline*
1979     "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1980     "return value;" *newline*))
1981
1982 (define-builtin symbol-function (x)
1983   (js!selfcall
1984     "var symbol = " x ";" *newline*
1985     "var func = symbol.fvalue;" *newline*
1986     "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1987     "return func;" *newline*))
1988
1989 (define-builtin symbol-plist (x)
1990   (concat "((" x ").plist || " (ls-compile nil) ")"))
1991
1992 (define-builtin lambda-code (x)
1993   (concat "(" x ").toString()"))
1994
1995 (define-builtin eq    (x y) (js!bool (concat "(" x " === " y ")")))
1996 (define-builtin equal (x y) (js!bool (concat "(" x  " == " y ")")))
1997
1998 (define-builtin char-to-string (x)
1999   (type-check (("x" "number" x))
2000     "String.fromCharCode(x)"))
2001
2002 (define-builtin stringp (x)
2003   (js!bool (concat "(typeof(" x ") == \"string\")")))
2004
2005 (define-builtin string-upcase (x)
2006   (type-check (("x" "string" x))
2007     "x.toUpperCase()"))
2008
2009 (define-builtin string-length (x)
2010   (type-check (("x" "string" x))
2011     "x.length"))
2012
2013 (define-raw-builtin slice (string a &optional b)
2014   (js!selfcall
2015     "var str = " (ls-compile string) ";" *newline*
2016     "var a = " (ls-compile a) ";" *newline*
2017     "var b;" *newline*
2018     (if b
2019         (concat "b = " (ls-compile b) ";" *newline*)
2020         "")
2021     "return str.slice(a,b);" *newline*))
2022
2023 (define-builtin char (string index)
2024   (type-check (("string" "string" string)
2025                ("index" "number" index))
2026     "string.charCodeAt(index)"))
2027
2028 (define-builtin concat-two (string1 string2)
2029   (type-check (("string1" "string" string1)
2030                ("string2" "string" string2))
2031     "string1.concat(string2)"))
2032
2033 (define-raw-builtin funcall (func &rest args)
2034   (concat "(" (ls-compile func) ")("
2035           (join (cons (if *multiple-value-p* "values" "pv")
2036                       (mapcar #'ls-compile args))
2037                 ", ")
2038           ")"))
2039
2040 (define-raw-builtin apply (func &rest args)
2041   (if (null args)
2042       (concat "(" (ls-compile func) ")()")
2043       (let ((args (butlast args))
2044             (last (car (last args))))
2045         (js!selfcall
2046           "var f = " (ls-compile func) ";" *newline*
2047           "var args = [" (join (cons (if *multiple-value-p* "values" "pv")
2048                                      (mapcar #'ls-compile args))
2049                                ", ")
2050           "];" *newline*
2051           "var tail = (" (ls-compile last) ");" *newline*
2052           "while (tail != " (ls-compile nil) "){" *newline*
2053           "    args.push(tail.car);" *newline*
2054           "    tail = tail.cdr;" *newline*
2055           "}" *newline*
2056           "return f.apply(this, args);" *newline*))))
2057
2058 (define-builtin js-eval (string)
2059   (type-check (("string" "string" string))
2060     (if *multiple-value-p*
2061         (js!selfcall
2062           "var v = eval.apply(window, [string]);" *newline*
2063           "if (typeof v !== 'object' || !('multiple-value' in v)){" *newline*
2064           (indent "v = [v];" *newline*
2065                   "v['multiple-value'] = true;" *newline*)
2066           "}" *newline*
2067           "return values.apply(this, v);" *newline*)
2068         "eval.apply(window, [string])")))
2069
2070 (define-builtin error (string)
2071   (js!selfcall "throw " string ";" *newline*))
2072
2073 (define-builtin new () "{}")
2074
2075 (define-builtin objectp (x)
2076   (js!bool (concat "(typeof (" x ") === 'object')")))
2077
2078 (define-builtin oget (object key)
2079   (js!selfcall
2080     "var tmp = " "(" object ")[" key "];" *newline*
2081     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
2082
2083 (define-builtin oset (object key value)
2084   (concat "((" object ")[" key "] = " value ")"))
2085
2086 (define-builtin in (key object)
2087   (js!bool (concat "((" key ") in (" object "))")))
2088
2089 (define-builtin functionp (x)
2090   (js!bool (concat "(typeof " x " == 'function')")))
2091
2092 (define-builtin write-string (x)
2093   (type-check (("x" "string" x))
2094     "lisp.write(x)"))
2095
2096 (define-builtin make-array (n)
2097   (js!selfcall
2098     "var r = [];" *newline*
2099     "for (var i = 0; i < " n "; i++)" *newline*
2100     (indent "r.push(" (ls-compile nil) ");" *newline*)
2101     "return r;" *newline*))
2102
2103 (define-builtin arrayp (x)
2104   (js!bool
2105    (js!selfcall
2106      "var x = " x ";" *newline*
2107      "return typeof x === 'object' && 'length' in x;")))
2108
2109 (define-builtin aref (array n)
2110   (js!selfcall
2111     "var x = " "(" array ")[" n "];" *newline*
2112     "if (x === undefined) throw 'Out of range';" *newline*
2113     "return x;" *newline*))
2114
2115 (define-builtin aset (array n value)
2116   (js!selfcall
2117     "var x = " array ";" *newline*
2118     "var i = " n ";" *newline*
2119     "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
2120     "return x[i] = " value ";" *newline*))
2121
2122 (define-builtin get-unix-time ()
2123   (concat "(Math.round(new Date() / 1000))"))
2124
2125 (define-builtin values-array (array)
2126   (if *multiple-value-p*
2127       (concat "values.apply(this, " array ")")
2128       (concat "pv.apply(this, " array ")")))
2129
2130 (define-raw-builtin values (&rest args)
2131   (if *multiple-value-p*
2132       (concat "values(" (join (mapcar #'ls-compile args) ", ") ")")
2133       (concat "pv(" (join (mapcar #'ls-compile args) ", ") ")")))
2134
2135 (defun macro (x)
2136   (and (symbolp x)
2137        (let ((b (lookup-in-lexenv x *environment* 'function)))
2138          (and (eq (binding-type b) 'macro)
2139               b))))
2140
2141 (defun ls-macroexpand-1 (form)
2142   (let ((macro-binding (macro (car form))))
2143     (if macro-binding
2144         (let ((expander (binding-value macro-binding)))
2145           (when (listp expander)
2146             (let ((compiled (eval expander)))
2147               ;; The list representation are useful while
2148               ;; bootstrapping, as we can dump the definition of the
2149               ;; macros easily, but they are slow because we have to
2150               ;; evaluate them and compile them now and again. So, let
2151               ;; us replace the list representation version of the
2152               ;; function with the compiled one.
2153               ;;
2154               #+ecmalisp (set-binding-value macro-binding compiled)
2155               (setq expander compiled)))
2156           (apply expander (cdr form)))
2157         form)))
2158
2159 (defun compile-funcall (function args)
2160   (let* ((values-funcs (if *multiple-value-p* "values" "pv"))
2161          (arglist (concat "(" (join (cons values-funcs (mapcar #'ls-compile args)) ", ") ")")))
2162     (cond
2163       ((translate-function function)
2164        (concat (translate-function function) arglist))
2165       ((and (symbolp function)
2166             #+ecmalisp (eq (symbol-package function) (find-package "COMMON-LISP"))
2167             #+common-lisp t)
2168        (concat (ls-compile `',function) ".fvalue" arglist))
2169       (t
2170        (concat (ls-compile `#',function) arglist)))))
2171
2172 (defun ls-compile-block (sexps &optional return-last-p)
2173   (if return-last-p
2174       (concat (ls-compile-block (butlast sexps))
2175               "return " (ls-compile (car (last sexps)) *multiple-value-p*) ";")
2176       (join-trailing
2177        (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
2178        (concat ";" *newline*))))
2179
2180 (defun ls-compile (sexp &optional multiple-value-p)
2181   (let ((*multiple-value-p* multiple-value-p))
2182     (cond
2183       ((symbolp sexp)
2184        (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
2185          (cond
2186            ((and b (not (member 'special (binding-declarations b))))
2187             (binding-value b))
2188            ((or (keywordp sexp)
2189                 (member 'constant (binding-declarations b)))
2190             (concat (ls-compile `',sexp) ".value"))
2191            (t
2192             (ls-compile `(symbol-value ',sexp))))))
2193       ((integerp sexp) (integer-to-string sexp))
2194       ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
2195       ((arrayp sexp) (literal sexp))
2196       ((listp sexp)
2197        (let ((name (car sexp))
2198              (args (cdr sexp)))
2199          (cond
2200            ;; Special forms
2201            ((assoc name *compilations*)
2202             (let ((comp (second (assoc name *compilations*))))
2203               (apply comp args)))
2204            ;; Built-in functions
2205            ((and (assoc name *builtins*)
2206                  (not (claimp name 'function 'notinline)))
2207             (let ((comp (second (assoc name *builtins*))))
2208               (apply comp args)))
2209            (t
2210             (if (macro name)
2211                 (ls-compile (ls-macroexpand-1 sexp) multiple-value-p)
2212                 (compile-funcall name args))))))
2213       (t
2214        (error "How should I compile this?")))))
2215
2216 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
2217   (let ((*toplevel-compilations* nil))
2218     (cond
2219       ((and (consp sexp) (eq (car sexp) 'progn))
2220        (let ((subs (mapcar (lambda (s)
2221                              (ls-compile-toplevel s t))
2222                            (cdr sexp))))
2223          (join (remove-if #'null-or-empty-p subs))))
2224       (t
2225        (let ((code (ls-compile sexp multiple-value-p)))
2226          (concat (join-trailing (get-toplevel-compilations)
2227                                 (concat ";" *newline*))
2228                  (if code
2229                      (concat code ";" *newline*)
2230                      "")))))))
2231
2232
2233 ;;; Once we have the compiler, we define the runtime environment and
2234 ;;; interactive development (eval), which works calling the compiler
2235 ;;; and evaluating the Javascript result globally.
2236
2237 #+ecmalisp
2238 (progn
2239   (defun eval (x)
2240     (js-eval (ls-compile-toplevel x t)))
2241
2242   (export '(&rest &optional &body * *gensym-counter* *package* + - /
2243             1+ 1- < <= = = > >= and append apply aref arrayp aset
2244             assoc atom block boundp boundp butlast caar cadddr caddr
2245             cadr car car case catch cdar cdddr cddr cdr cdr char
2246             char-code char= code-char cond cons consp constantly
2247             copy-list decf declaim defparameter defun defmacro defvar
2248             digit-char digit-char-p disassemble do do* documentation
2249             dolist dotimes ecase eq eql equal error eval every export
2250             fdefinition find-package find-symbol first flet fourth
2251             fset funcall function functionp gensym get-universal-time
2252             go identity if in-package incf integerp integerp intern
2253             keywordp labels lambda last length let let*
2254             list-all-packages list listp make-array make-package
2255             make-symbol mapcar member minusp mod multiple-value-bind
2256             multiple-value-call multiple-value-list
2257             multiple-value-prog1 nil not nth nthcdr null numberp or
2258             package-name package-use-list packagep parse-integer plusp
2259             prin1-to-string print proclaim prog1 prog2 progn psetq
2260             push quote remove remove-if remove-if-not return
2261             return-from revappend reverse rplaca rplacd second set
2262             setq some string-upcase string string= stringp subseq
2263             symbol-function symbol-name symbol-package symbol-plist
2264             symbol-value symbolp t tagbody third throw truncate unless
2265             unwind-protect values values-list variable warn when
2266             write-line write-string zerop))
2267
2268   (setq *package* *user-package*)
2269
2270   (js-eval "var lisp")
2271   (js-vset "lisp" (new))
2272   (js-vset "lisp.read" #'ls-read-from-string)
2273   (js-vset "lisp.print" #'prin1-to-string)
2274   (js-vset "lisp.eval" #'eval)
2275   (js-vset "lisp.compile" (lambda (s) (ls-compile-toplevel s t)))
2276   (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
2277   (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str) t)))
2278
2279   ;; Set the initial global environment to be equal to the host global
2280   ;; environment at this point of the compilation.
2281   (eval-when-compile
2282     (toplevel-compilation
2283      (ls-compile
2284       `(progn
2285          ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
2286                    *literal-symbols*)
2287          (setq *literal-symbols* ',*literal-symbols*)
2288          (setq *environment* ',*environment*)
2289          (setq *variable-counter* ,*variable-counter*)
2290          (setq *gensym-counter* ,*gensym-counter*)
2291          (setq *block-counter* ,*block-counter*)))))
2292
2293   (eval-when-compile
2294     (toplevel-compilation
2295      (ls-compile
2296       `(setq *literal-counter* ,*literal-counter*)))))
2297
2298
2299 ;;; Finally, we provide a couple of functions to easily bootstrap
2300 ;;; this. It just calls the compiler with this file as input.
2301
2302 #+common-lisp
2303 (progn
2304   (defun read-whole-file (filename)
2305     (with-open-file (in filename)
2306       (let ((seq (make-array (file-length in) :element-type 'character)))
2307         (read-sequence seq in)
2308         seq)))
2309
2310   (defun ls-compile-file (filename output)
2311     (let ((*compiling-file* t))
2312       (with-open-file (out output :direction :output :if-exists :supersede)
2313         (write-string (read-whole-file "prelude.js") out)
2314         (let* ((source (read-whole-file filename))
2315                (in (make-string-stream source)))
2316           (loop
2317              for x = (ls-read in)
2318              until (eq x *eof*)
2319              for compilation = (ls-compile-toplevel x)
2320              when (plusp (length compilation))
2321              do (write-string compilation out))))))
2322
2323   (defun bootstrap ()
2324     (setq *environment* (make-lexenv))
2325     (setq *literal-symbols* nil)
2326     (setq *variable-counter* 0
2327           *gensym-counter* 0
2328           *literal-counter* 0
2329           *block-counter* 0)
2330     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))