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