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