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