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