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