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