9f3e726ab4960886a648d215a36ff26fdad0667c
[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                   (in-package :js
822                               `(defun ,symbol (args)
823                                 (apply #'%js-call ,(symbol-name symbol)
824                                        args)))
825                   (export (list symbol) package))
826                 (oset symbols name symbol)
827                 (values symbol nil)))))))
828
829   (defun symbol-package (symbol)
830     (unless (symbolp symbol)
831       (error "it is not a symbol"))
832     (oget symbol "package"))
833
834   (defun export (symbols &optional (package *package*))
835     (let ((exports (%package-external-symbols package)))
836       (dolist (symb symbols t)
837         (oset exports (symbol-name symb) symb))))
838
839   (defun get-universal-time ()
840     (+ (get-unix-time) 2208988800)))
841
842
843 ;;; The compiler offers some primitives and special forms which are
844 ;;; not found in Common Lisp, for instance, while. So, we grow Common
845 ;;; Lisp a bit to it can execute the rest of the file.
846 #+common-lisp
847 (progn
848   (defmacro while (condition &body body)
849     `(do ()
850          ((not ,condition))
851        ,@body))
852
853   (defmacro eval-when-compile (&body body)
854     `(eval-when (:compile-toplevel :load-toplevel :execute)
855        ,@body))
856
857   (defun concat-two (s1 s2)
858     (concatenate 'string s1 s2))
859
860   (defun aset (array idx value)
861     (setf (aref array idx) value)))
862
863 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
864 ;;; from here, this code will compile on both. We define some helper
865 ;;; functions now for string manipulation and so on. They will be
866 ;;; useful in the compiler, mostly.
867
868 (defvar *newline* (string (code-char 10)))
869
870 (defun concat (&rest strs)
871   (!reduce #'concat-two strs :initial-value ""))
872
873 (defmacro concatf (variable &body form)
874   `(setq ,variable (concat ,variable (progn ,@form))))
875
876 ;;; Concatenate a list of strings, with a separator
877 (defun join (list &optional (separator ""))
878   (cond
879     ((null list)
880      "")
881     ((null (cdr list))
882      (car list))
883     (t
884      (concat (car list)
885              separator
886              (join (cdr list) separator)))))
887
888 (defun join-trailing (list &optional (separator ""))
889   (if (null list)
890       ""
891       (concat (car list) separator (join-trailing (cdr list) separator))))
892
893 (defun mapconcat (func list)
894   (join (mapcar func list)))
895
896 (defun vector-to-list (vector)
897   (let ((list nil)
898         (size (length vector)))
899     (dotimes (i size (reverse list))
900       (push (aref vector i) list))))
901
902 (defun list-to-vector (list)
903   (let ((v (make-array (length list)))
904         (i 0))
905     (dolist (x list v)
906       (aset v i x)
907       (incf i))))
908
909 #+ecmalisp
910 (progn
911   (defun values-list (list)
912     (values-array (list-to-vector list)))
913
914   (defun values (&rest args)
915     (values-list args)))
916
917 (defun integer-to-string (x)
918   (cond
919     ((zerop x)
920      "0")
921     ((minusp x)
922      (concat "-" (integer-to-string (- 0 x))))
923     (t
924      (let ((digits nil))
925        (while (not (zerop x))
926          (push (mod x 10) digits)
927          (setq x (truncate x 10)))
928        (mapconcat (lambda (x) (string (digit-char x)))
929                   digits)))))
930
931
932 ;;; Printer
933
934 #+ecmalisp
935 (progn
936   (defun prin1-to-string (form)
937     (cond
938       ((symbolp form)
939        (multiple-value-bind (symbol foundp)
940            (find-symbol (symbol-name form) *package*)
941          (if (and foundp (eq symbol form))
942              (symbol-name form)
943              (let ((package (symbol-package form))
944                    (name (symbol-name form)))
945                (concat (cond
946                          ((null package) "#")
947                          ((eq package (find-package "KEYWORD")) "")
948                          (t (package-name package)))
949                        ":" name)))))
950       ((integerp form) (integer-to-string form))
951       ((stringp form) (concat "\"" (escape-string form) "\""))
952       ((functionp form)
953        (let ((name (oget form "fname")))
954          (if name
955              (concat "#<FUNCTION " name ">")
956              (concat "#<FUNCTION>"))))
957       ((listp form)
958        (concat "("
959                (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
960                (let ((last (last form)))
961                  (if (null (cdr last))
962                      (prin1-to-string (car last))
963                      (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
964                ")"))
965       ((arrayp form)
966        (concat "#" (if (zerop (length form))
967                        "()"
968                        (prin1-to-string (vector-to-list form)))))
969       ((packagep form)
970        (concat "#<PACKAGE " (package-name form) ">"))))
971
972   (defun write-line (x)
973     (write-string x)
974     (write-string *newline*)
975     x)
976
977   (defun warn (string)
978     (write-string "WARNING: ")
979     (write-line string))
980
981   (defun print (x)
982     (write-line (prin1-to-string x))
983     x))
984
985
986
987 ;;;; Reader
988
989 ;;; The Lisp reader, parse strings and return Lisp objects. The main
990 ;;; entry points are `ls-read' and `ls-read-from-string'.
991
992 (defun make-string-stream (string)
993   (cons string 0))
994
995 (defun %peek-char (stream)
996   (and (< (cdr stream) (length (car stream)))
997        (char (car stream) (cdr stream))))
998
999 (defun %read-char (stream)
1000   (and (< (cdr stream) (length (car stream)))
1001        (prog1 (char (car stream) (cdr stream))
1002          (rplacd stream (1+ (cdr stream))))))
1003
1004 (defun whitespacep (ch)
1005   (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
1006
1007 (defun skip-whitespaces (stream)
1008   (let (ch)
1009     (setq ch (%peek-char stream))
1010     (while (and ch (whitespacep ch))
1011       (%read-char stream)
1012       (setq ch (%peek-char stream)))))
1013
1014 (defun terminalp (ch)
1015   (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
1016
1017 (defun read-until (stream func)
1018   (let ((string "")
1019         (ch))
1020     (setq ch (%peek-char stream))
1021     (while (and ch (not (funcall func ch)))
1022       (setq string (concat string (string ch)))
1023       (%read-char stream)
1024       (setq ch (%peek-char stream)))
1025     string))
1026
1027 (defun skip-whitespaces-and-comments (stream)
1028   (let (ch)
1029     (skip-whitespaces stream)
1030     (setq ch (%peek-char stream))
1031     (while (and ch (char= ch #\;))
1032       (read-until stream (lambda (x) (char= x #\newline)))
1033       (skip-whitespaces stream)
1034       (setq ch (%peek-char stream)))))
1035
1036 (defun %read-list (stream)
1037   (skip-whitespaces-and-comments stream)
1038   (let ((ch (%peek-char stream)))
1039     (cond
1040       ((null ch)
1041        (error "Unspected EOF"))
1042       ((char= ch #\))
1043        (%read-char stream)
1044        nil)
1045       ((char= ch #\.)
1046        (%read-char stream)
1047        (prog1 (ls-read stream)
1048          (skip-whitespaces-and-comments stream)
1049          (unless (char= (%read-char stream) #\))
1050            (error "')' was expected."))))
1051       (t
1052        (cons (ls-read stream) (%read-list stream))))))
1053
1054 (defun read-string (stream)
1055   (let ((string "")
1056         (ch nil))
1057     (setq ch (%read-char stream))
1058     (while (not (eql ch #\"))
1059       (when (null ch)
1060         (error "Unexpected EOF"))
1061       (when (eql ch #\\)
1062         (setq ch (%read-char stream)))
1063       (setq string (concat string (string ch)))
1064       (setq ch (%read-char stream)))
1065     string))
1066
1067 (defun read-sharp (stream)
1068   (%read-char stream)
1069   (ecase (%read-char stream)
1070     (#\'
1071      (list 'function (ls-read stream)))
1072     (#\( (list-to-vector (%read-list stream)))
1073     (#\: (make-symbol (string-upcase (read-until stream #'terminalp))))
1074     (#\\
1075      (let ((cname
1076             (concat (string (%read-char stream))
1077                     (read-until stream #'terminalp))))
1078        (cond
1079          ((string= cname "space") (char-code #\space))
1080          ((string= cname "tab") (char-code #\tab))
1081          ((string= cname "newline") (char-code #\newline))
1082          (t (char-code (char cname 0))))))
1083     (#\+
1084      (let ((feature (read-until stream #'terminalp)))
1085        (cond
1086          ((string= feature "common-lisp")
1087           (ls-read stream)              ;ignore
1088           (ls-read stream))
1089          ((string= feature "ecmalisp")
1090           (ls-read stream))
1091          (t
1092           (error "Unknown reader form.")))))))
1093
1094 ;;; Parse a string of the form NAME, PACKAGE:NAME or
1095 ;;; PACKAGE::NAME and return the name. If the string is of the
1096 ;;; form 1) or 3), but the symbol does not exist, it will be created
1097 ;;; and interned in that package.
1098 (defun read-symbol (string)
1099   (let ((size (length string))
1100         package name internalp index)
1101     (setq index 0)
1102     (while (and (< index size)
1103                 (not (char= (char string index) #\:)))
1104       (incf index))
1105     (cond
1106       ;; No package prefix
1107       ((= index size)
1108        (setq name string)
1109        (setq package *package*)
1110        (setq internalp t))
1111       (t
1112        ;; Package prefix
1113        (if (zerop index)
1114            (setq package "KEYWORD")
1115            (setq package (string-upcase (subseq string 0 index))))
1116        (incf index)
1117        (when (char= (char string index) #\:)
1118          (setq internalp t)
1119          (incf index))
1120        (setq name (subseq string index))))
1121     ;; Canonalize symbol name and package
1122     (when (not (eq package "JS"))
1123       (setq name (string-upcase name)))
1124     (setq package (find-package package))
1125     ;; TODO: PACKAGE:SYMBOL should signal error if SYMBOL is not an
1126     ;; external symbol from PACKAGE.
1127     (if (or internalp (eq package (or (find-package "KEYWORD")
1128                                       (find-package "JS"))))
1129         (intern name package)
1130         (find-symbol name package))))
1131
1132
1133 (defun !parse-integer (string junk-allow)
1134   (block nil
1135     (let ((value 0)
1136           (index 0)
1137           (size (length string))
1138           (sign 1))
1139       (when (zerop size) (return (values nil 0)))
1140       ;; Optional sign
1141       (case (char string 0)
1142         (#\+ (incf index))
1143         (#\- (setq sign -1)
1144              (incf index)))
1145       ;; First digit
1146       (unless (and (< index size)
1147                    (setq value (digit-char-p (char string index))))
1148         (return (values nil index)))
1149       (incf index)
1150       ;; Other digits
1151       (while (< index size)
1152         (let ((digit (digit-char-p (char string index))))
1153           (unless digit (return))
1154           (setq value (+ (* value 10) digit))
1155           (incf index)))
1156       (if (or junk-allow
1157               (= index size)
1158               (char= (char string index) #\space))
1159           (values (* sign value) index)
1160           (values nil index)))))
1161
1162 #+ecmalisp
1163 (defun parse-integer (string)
1164   (!parse-integer string nil))
1165
1166 (defvar *eof* (gensym))
1167 (defun ls-read (stream)
1168   (skip-whitespaces-and-comments stream)
1169   (let ((ch (%peek-char stream)))
1170     (cond
1171       ((or (null ch) (char= ch #\)))
1172        *eof*)
1173       ((char= ch #\()
1174        (%read-char stream)
1175        (%read-list stream))
1176       ((char= ch #\')
1177        (%read-char stream)
1178        (list 'quote (ls-read stream)))
1179       ((char= ch #\`)
1180        (%read-char stream)
1181        (list 'backquote (ls-read stream)))
1182       ((char= ch #\")
1183        (%read-char stream)
1184        (read-string stream))
1185       ((char= ch #\,)
1186        (%read-char stream)
1187        (if (eql (%peek-char stream) #\@)
1188            (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
1189            (list 'unquote (ls-read stream))))
1190       ((char= ch #\#)
1191        (read-sharp stream))
1192       (t
1193        (let ((string (read-until stream #'terminalp)))
1194          (or (values (!parse-integer string nil))
1195              (read-symbol string)))))))
1196
1197 (defun ls-read-from-string (string)
1198   (ls-read (make-string-stream string)))
1199
1200
1201 ;;;; Compiler
1202
1203 ;;; Translate the Lisp code to Javascript. It will compile the special
1204 ;;; forms. Some primitive functions are compiled as special forms
1205 ;;; too. The respective real functions are defined in the target (see
1206 ;;; the beginning of this file) as well as some primitive functions.
1207
1208 (defun code (&rest args)
1209   (mapconcat (lambda (arg)
1210                (cond
1211                  ((null arg) "")
1212                  ((integerp arg) (integer-to-string arg))
1213                  ((stringp arg) arg)
1214                  (t (error "Unknown argument."))))
1215              args))
1216
1217 ;;; Wrap X with a Javascript code to convert the result from
1218 ;;; Javascript generalized booleans to T or NIL.
1219 (defun js!bool (x)
1220   (code "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
1221
1222 ;;; Concatenate the arguments and wrap them with a self-calling
1223 ;;; Javascript anonymous function. It is used to make some Javascript
1224 ;;; statements valid expressions and provide a private scope as well.
1225 ;;; It could be defined as function, but we could do some
1226 ;;; preprocessing in the future.
1227 (defmacro js!selfcall (&body body)
1228   `(code "(function(){" *newline* (indent ,@body) "})()"))
1229
1230 ;;; Like CODE, but prefix each line with four spaces. Two versions
1231 ;;; of this function are available, because the Ecmalisp version is
1232 ;;; very slow and bootstraping was annoying.
1233
1234 #+ecmalisp
1235 (defun indent (&rest string)
1236   (let ((input (apply #'code string)))
1237     (let ((output "")
1238           (index 0)
1239           (size (length input)))
1240       (when (plusp (length input)) (concatf output "    "))
1241       (while (< index size)
1242         (let ((str
1243                (if (and (char= (char input index) #\newline)
1244                         (< index (1- size))
1245                         (not (char= (char input (1+ index)) #\newline)))
1246                    (concat (string #\newline) "    ")
1247                    (string (char input index)))))
1248           (concatf output str))
1249         (incf index))
1250       output)))
1251
1252 #+common-lisp
1253 (defun indent (&rest string)
1254   (with-output-to-string (*standard-output*)
1255     (with-input-from-string (input (apply #'code string))
1256       (loop
1257          for line = (read-line input nil)
1258          while line
1259          do (write-string "    ")
1260          do (write-line line)))))
1261
1262
1263 ;;; A Form can return a multiple values object calling VALUES, like
1264 ;;; values(arg1, arg2, ...). It will work in any context, as well as
1265 ;;; returning an individual object. However, if the special variable
1266 ;;; `*multiple-value-p*' is NIL, is granted that only the primary
1267 ;;; value will be used, so we can optimize to avoid the VALUES
1268 ;;; function call.
1269 (defvar *multiple-value-p* nil)
1270
1271 (defun make-binding (name type value &optional declarations)
1272   (list name type value declarations))
1273
1274 (defun binding-name (b) (first b))
1275 (defun binding-type (b) (second b))
1276 (defun binding-value (b) (third b))
1277 (defun binding-declarations (b) (fourth b))
1278
1279 (defun set-binding-value (b value)
1280   (rplaca (cddr b) value))
1281
1282 (defun set-binding-declarations (b value)
1283   (rplaca (cdddr b) value))
1284
1285 (defun push-binding-declaration (decl b)
1286   (set-binding-declarations b (cons decl (binding-declarations b))))
1287
1288
1289 (defun make-lexenv ()
1290   (list nil nil nil nil))
1291
1292 (defun copy-lexenv (lexenv)
1293   (copy-list lexenv))
1294
1295 (defun push-to-lexenv (binding lexenv namespace)
1296   (ecase namespace
1297     (variable   (rplaca        lexenv  (cons binding (car lexenv))))
1298     (function   (rplaca   (cdr lexenv) (cons binding (cadr lexenv))))
1299     (block      (rplaca  (cddr lexenv) (cons binding (caddr lexenv))))
1300     (gotag      (rplaca (cdddr lexenv) (cons binding (cadddr lexenv))))))
1301
1302 (defun extend-lexenv (bindings lexenv namespace)
1303   (let ((env (copy-lexenv lexenv)))
1304     (dolist (binding (reverse bindings) env)
1305       (push-to-lexenv binding env namespace))))
1306
1307 (defun lookup-in-lexenv (name lexenv namespace)
1308   (assoc name (ecase namespace
1309                 (variable (first lexenv))
1310                 (function (second lexenv))
1311                 (block (third lexenv))
1312                 (gotag (fourth lexenv)))))
1313
1314 (defvar *environment* (make-lexenv))
1315
1316 (defvar *variable-counter* 0)
1317
1318 (defun gvarname (symbol)
1319   (code "v" (incf *variable-counter*)))
1320
1321 (defun translate-variable (symbol)
1322   (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
1323
1324 (defun extend-local-env (args)
1325   (let ((new (copy-lexenv *environment*)))
1326     (dolist (symbol args new)
1327       (let ((b (make-binding symbol 'variable (gvarname symbol))))
1328         (push-to-lexenv b new 'variable)))))
1329
1330 ;;; Toplevel compilations
1331 (defvar *toplevel-compilations* nil)
1332
1333 (defun toplevel-compilation (string)
1334   (push string *toplevel-compilations*))
1335
1336 (defun null-or-empty-p (x)
1337   (zerop (length x)))
1338
1339 (defun get-toplevel-compilations ()
1340   (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
1341
1342 (defun %compile-defmacro (name lambda)
1343   (toplevel-compilation (ls-compile `',name))
1344   (push-to-lexenv (make-binding name 'macro lambda) *environment* 'function)
1345   name)
1346
1347 (defun global-binding (name type namespace)
1348   (or (lookup-in-lexenv name *environment* namespace)
1349       (let ((b (make-binding name type nil)))
1350         (push-to-lexenv b *environment* namespace)
1351         b)))
1352
1353 (defun claimp (symbol namespace claim)
1354   (let ((b (lookup-in-lexenv symbol *environment* namespace)))
1355     (and b (member claim (binding-declarations b)))))
1356
1357 (defun !proclaim (decl)
1358   (case (car decl)
1359     (special
1360      (dolist (name (cdr decl))
1361        (let ((b (global-binding name 'variable 'variable)))
1362          (push-binding-declaration 'special b))))
1363     (notinline
1364      (dolist (name (cdr decl))
1365        (let ((b (global-binding name 'function 'function)))
1366          (push-binding-declaration 'notinline b))))
1367     (constant
1368      (dolist (name (cdr decl))
1369        (let ((b (global-binding name 'variable 'variable)))
1370          (push-binding-declaration 'constant b))))))
1371
1372 #+ecmalisp
1373 (fset 'proclaim #'!proclaim)
1374
1375 ;;; Special forms
1376
1377 (defvar *compilations* nil)
1378
1379 (defmacro define-compilation (name args &body body)
1380   ;; Creates a new primitive `name' with parameters args and
1381   ;; @body. The body can access to the local environment through the
1382   ;; variable *ENVIRONMENT*.
1383   `(push (list ',name (lambda ,args (block ,name ,@body)))
1384          *compilations*))
1385
1386 (define-compilation if (condition true false)
1387   (code "(" (ls-compile condition) " !== " (ls-compile nil)
1388         " ? " (ls-compile true *multiple-value-p*)
1389         " : " (ls-compile false *multiple-value-p*)
1390         ")"))
1391
1392 (defvar *ll-keywords* '(&optional &rest &key))
1393
1394 (defun list-until-keyword (list)
1395   (if (or (null list) (member (car list) *ll-keywords*))
1396       nil
1397       (cons (car list) (list-until-keyword (cdr list)))))
1398
1399 (defun ll-section (keyword ll)
1400   (list-until-keyword (cdr (member keyword ll))))
1401
1402 (defun ll-required-arguments (ll)
1403   (list-until-keyword ll))
1404
1405 (defun ll-optional-arguments-canonical (ll)
1406   (mapcar #'ensure-list (ll-section '&optional ll)))
1407
1408 (defun ll-optional-arguments (ll)
1409   (mapcar #'car (ll-optional-arguments-canonical ll)))
1410
1411 (defun ll-rest-argument (ll)
1412   (let ((rest (ll-section '&rest ll)))
1413     (when (cdr rest)
1414       (error "Bad lambda-list"))
1415     (car rest)))
1416
1417 (defun ll-keyword-arguments-canonical (ll)
1418   (flet ((canonicalize (keyarg)
1419            ;; Build a canonical keyword argument descriptor, filling
1420            ;; the optional fields. The result is a list of the form
1421            ;; ((keyword-name var) init-form).
1422            (let ((arg (ensure-list keyarg)))
1423              (cons (if (listp (car arg))
1424                        (car arg)
1425                        (list (intern (symbol-name (car arg)) "KEYWORD") (car arg)))
1426                    (cdr arg)))))
1427     (mapcar #'canonicalize (ll-section '&key ll))))
1428
1429 (defun ll-keyword-arguments (ll)
1430   (mapcar (lambda (keyarg) (second (first keyarg)))
1431           (ll-keyword-arguments-canonical ll)))
1432
1433 (defun ll-svars (lambda-list)
1434   (let ((args
1435          (append
1436           (ll-keyword-arguments-canonical lambda-list)
1437           (ll-optional-arguments-canonical lambda-list))))
1438     (remove nil (mapcar #'third args))))
1439
1440 (defun lambda-docstring-wrapper (docstring &rest strs)
1441   (if docstring
1442       (js!selfcall
1443         "var func = " (join strs) ";" *newline*
1444         "func.docstring = '" docstring "';" *newline*
1445         "return func;" *newline*)
1446       (apply #'code strs)))
1447
1448 (defun lambda-check-argument-count
1449     (n-required-arguments n-optional-arguments rest-p)
1450   ;; Note: Remember that we assume that the number of arguments of a
1451   ;; call is at least 1 (the values argument).
1452   (let ((min (1+ n-required-arguments))
1453         (max (if rest-p 'n/a (+ 1 n-required-arguments n-optional-arguments))))
1454     (block nil
1455       ;; Special case: a positive exact number of arguments.
1456       (when (and (< 1 min) (eql min max))
1457         (return (code "checkArgs(arguments, " min ");" *newline*)))
1458       ;; General case:
1459       (code
1460        (when (< 1 min)
1461          (code "checkArgsAtLeast(arguments, " min ");" *newline*))
1462        (when (numberp max)
1463          (code "checkArgsAtMost(arguments, " max ");" *newline*))))))
1464
1465 (defun compile-lambda-optional (ll)
1466   (let* ((optional-arguments (ll-optional-arguments-canonical ll))
1467          (n-required-arguments (length (ll-required-arguments ll)))
1468          (n-optional-arguments (length optional-arguments)))
1469     (when optional-arguments
1470       (code (mapconcat (lambda (arg)
1471                          (code "var " (translate-variable (first arg)) "; " *newline*
1472                                (when (third arg)
1473                                  (code "var " (translate-variable (third arg))
1474                                        " = " (ls-compile t)
1475                                        "; " *newline*))))
1476                        optional-arguments)
1477             "switch(arguments.length-1){" *newline*
1478             (let ((cases nil)
1479                   (idx 0))
1480               (progn
1481                 (while (< idx n-optional-arguments)
1482                   (let ((arg (nth idx optional-arguments)))
1483                     (push (code "case " (+ idx n-required-arguments) ":" *newline*
1484                                 (indent (translate-variable (car arg))
1485                                         "="
1486                                         (ls-compile (cadr arg)) ";" *newline*)
1487                                 (when (third arg)
1488                                   (indent (translate-variable (third arg))
1489                                           "="
1490                                           (ls-compile nil)
1491                                           ";" *newline*)))
1492                           cases)
1493                     (incf idx)))
1494                 (push (code "default: break;" *newline*) cases)
1495                 (join (reverse cases))))
1496             "}" *newline*))))
1497
1498 (defun compile-lambda-rest (ll)
1499   (let ((n-required-arguments (length (ll-required-arguments ll)))
1500         (n-optional-arguments (length (ll-optional-arguments ll)))
1501         (rest-argument (ll-rest-argument ll)))
1502     (when rest-argument
1503       (let ((js!rest (translate-variable rest-argument)))
1504         (code "var " js!rest "= " (ls-compile nil) ";" *newline*
1505               "for (var i = arguments.length-1; i>="
1506               (+ 1 n-required-arguments n-optional-arguments)
1507               "; i--)" *newline*
1508               (indent js!rest " = {car: arguments[i], cdr: ") js!rest "};"
1509               *newline*)))))
1510
1511 (defun compile-lambda-parse-keywords (ll)
1512   (let ((n-required-arguments
1513          (length (ll-required-arguments ll)))
1514         (n-optional-arguments
1515          (length (ll-optional-arguments ll)))
1516         (keyword-arguments
1517          (ll-keyword-arguments-canonical ll)))
1518     (code
1519      ;; Declare variables
1520      (mapconcat (lambda (arg)
1521                   (let ((var (second (car arg))))
1522                     (code "var " (translate-variable var) "; " *newline*
1523                           (when (third arg)
1524                             (code "var " (translate-variable (third arg))
1525                                   " = " (ls-compile nil)
1526                                   ";" *newline*)))))
1527                 keyword-arguments)
1528      ;; Parse keywords
1529      (flet ((parse-keyword (keyarg)
1530               ;; ((keyword-name var) init-form)
1531               (code "for (i=" (+ 1 n-required-arguments n-optional-arguments)
1532                     "; i<arguments.length; i+=2){" *newline*
1533                     (indent
1534                      "if (arguments[i] === " (ls-compile (caar keyarg)) "){" *newline*
1535                      (indent (translate-variable (cadr (car keyarg)))
1536                              " = arguments[i+1];"
1537                              *newline*
1538                              (let ((svar (third keyarg)))
1539                                (when svar
1540                                  (code (translate-variable svar) " = " (ls-compile t) ";" *newline*)))
1541                              "break;" *newline*)
1542                      "}" *newline*)
1543                     "}" *newline*
1544                     ;; Default value
1545                     "if (i == arguments.length){" *newline*
1546                     (indent (translate-variable (cadr (car keyarg))) " = " (ls-compile (cadr keyarg)) ";" *newline*)
1547                     "}" *newline*)))
1548        (when keyword-arguments
1549          (code "var i;" *newline*
1550                (mapconcat #'parse-keyword keyword-arguments))))
1551      ;; Check for unknown keywords
1552      (when keyword-arguments
1553        (code "for (i=" (+ 1 n-required-arguments n-optional-arguments)
1554              "; i<arguments.length; i+=2){" *newline*
1555              (indent "if ("
1556                      (join (mapcar (lambda (x)
1557                                      (concat "arguments[i] !== " (ls-compile (caar x))))
1558                                    keyword-arguments)
1559                            " && ")
1560                      ")" *newline*
1561                      (indent
1562                       "throw 'Unknown keyword argument ' + arguments[i].name;" *newline*))
1563              "}" *newline*)))))
1564
1565 (defun compile-lambda (ll body)
1566   (let ((required-arguments (ll-required-arguments ll))
1567         (optional-arguments (ll-optional-arguments ll))
1568         (keyword-arguments  (ll-keyword-arguments  ll))
1569         (rest-argument      (ll-rest-argument      ll))
1570         documentation)
1571     ;; Get the documentation string for the lambda function
1572     (when (and (stringp (car body))
1573                (not (null (cdr body))))
1574       (setq documentation (car body))
1575       (setq body (cdr body)))
1576     (let ((n-required-arguments (length required-arguments))
1577           (n-optional-arguments (length optional-arguments))
1578           (*environment* (extend-local-env
1579                           (append (ensure-list rest-argument)
1580                                   required-arguments
1581                                   optional-arguments
1582                                   keyword-arguments
1583                                   (ll-svars ll)))))
1584       (lambda-docstring-wrapper
1585        documentation
1586        "(function ("
1587        (join (cons "values"
1588                    (mapcar #'translate-variable
1589                            (append required-arguments optional-arguments)))
1590              ",")
1591        "){" *newline*
1592        (indent
1593         ;; Check number of arguments
1594         (lambda-check-argument-count n-required-arguments
1595                                      n-optional-arguments
1596                                      (or rest-argument keyword-arguments))
1597         (compile-lambda-optional ll)
1598         (compile-lambda-rest ll)
1599         (compile-lambda-parse-keywords ll)
1600         (let ((*multiple-value-p* t))
1601           (ls-compile-block body t)))
1602        "})"))))
1603
1604
1605
1606 (defun setq-pair (var val)
1607   (let ((b (lookup-in-lexenv var *environment* 'variable)))
1608     (if (and (eq (binding-type b) 'variable)
1609              (not (member 'special (binding-declarations b)))
1610              (not (member 'constant (binding-declarations b))))
1611         (code (binding-value b) " = " (ls-compile val))
1612         (ls-compile `(set ',var ,val)))))
1613
1614
1615 (define-compilation %js-call (fun &rest args)
1616   (let ((evaled-args (mapcar #'ls-compile args)))
1617     (code fun "(" (join evaled-args ", ") ")")))
1618
1619 (define-compilation setq (&rest pairs)
1620   (let ((result ""))
1621     (while t
1622       (cond
1623         ((null pairs) (return))
1624         ((null (cdr pairs))
1625          (error "Odd paris in SETQ"))
1626         (t
1627          (concatf result
1628            (concat (setq-pair (car pairs) (cadr pairs))
1629                    (if (null (cddr pairs)) "" ", ")))
1630          (setq pairs (cddr pairs)))))
1631     (code "(" result ")")))
1632
1633 ;;; FFI Variable accessors
1634 (define-compilation js-vref (var)
1635   var)
1636
1637 (define-compilation js-vset (var val)
1638   (code "(" var " = " (ls-compile val) ")"))
1639
1640
1641 ;;; Literals
1642 (defun escape-string (string)
1643   (let ((output "")
1644         (index 0)
1645         (size (length string)))
1646     (while (< index size)
1647       (let ((ch (char string index)))
1648         (when (or (char= ch #\") (char= ch #\\))
1649           (setq output (concat output "\\")))
1650         (when (or (char= ch #\newline))
1651           (setq output (concat output "\\"))
1652           (setq ch #\n))
1653         (setq output (concat output (string ch))))
1654       (incf index))
1655     output))
1656
1657
1658 (defvar *literal-symbols* nil)
1659 (defvar *literal-counter* 0)
1660
1661 (defun genlit ()
1662   (code "l" (incf *literal-counter*)))
1663
1664 (defun literal (sexp &optional recursive)
1665   (cond
1666     ((integerp sexp) (integer-to-string sexp))
1667     ((stringp sexp) (code "\"" (escape-string sexp) "\""))
1668     ((symbolp sexp)
1669      (or (cdr (assoc sexp *literal-symbols*))
1670          (let ((v (genlit))
1671                (s #+common-lisp
1672                  (let ((package (symbol-package sexp)))
1673                    (if (eq package (find-package "KEYWORD"))
1674                        (code "{name: \"" (escape-string (symbol-name sexp))
1675                              "\", 'package': '" (package-name package) "'}")
1676                        (code "{name: \"" (escape-string (symbol-name sexp)) "\"}")))
1677                  #+ecmalisp
1678                  (let ((package (symbol-package sexp)))
1679                    (if (null package)
1680                        (code "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1681                        (ls-compile `(intern ,(symbol-name sexp) ,(package-name package)))))))
1682            (push (cons sexp v) *literal-symbols*)
1683            (toplevel-compilation (code "var " v " = " s))
1684            v)))
1685     ((consp sexp)
1686      (let* ((head (butlast sexp))
1687             (tail (last sexp))
1688             (c (code "QIList("
1689                      (join-trailing (mapcar (lambda (x) (literal x t)) head) ",")
1690                      (literal (car tail) t)
1691                      ","
1692                      (literal (cdr tail) t)
1693                      ")")))
1694        (if recursive
1695            c
1696            (let ((v (genlit)))
1697              (toplevel-compilation (code "var " v " = " c))
1698              v))))
1699     ((arrayp sexp)
1700      (let ((elements (vector-to-list sexp)))
1701        (let ((c (concat "[" (join (mapcar #'literal elements) ", ") "]")))
1702          (if recursive
1703              c
1704              (let ((v (genlit)))
1705                (toplevel-compilation (code "var " v " = " c))
1706                v)))))))
1707
1708 (define-compilation quote (sexp)
1709   (literal sexp))
1710
1711 (define-compilation %while (pred &rest body)
1712   (js!selfcall
1713     "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1714     (indent (ls-compile-block body))
1715     "}"
1716     "return " (ls-compile nil) ";" *newline*))
1717
1718 (define-compilation function (x)
1719   (cond
1720     ((and (listp x) (eq (car x) 'lambda))
1721      (compile-lambda (cadr x) (cddr x)))
1722     ((symbolp x)
1723      (let ((b (lookup-in-lexenv x *environment* 'function)))
1724        (if b
1725            (binding-value b)
1726            (ls-compile `(symbol-function ',x)))))))
1727
1728
1729 (defun make-function-binding (fname)
1730   (make-binding fname 'function (gvarname fname)))
1731
1732 (defun compile-function-definition (list)
1733   (compile-lambda (car list) (cdr list)))
1734
1735 (defun translate-function (name)
1736   (let ((b (lookup-in-lexenv name *environment* 'function)))
1737     (binding-value b)))
1738
1739 (define-compilation flet (definitions &rest body)
1740   (let* ((fnames (mapcar #'car definitions))
1741          (fbody  (mapcar #'cdr definitions))
1742          (cfuncs (mapcar #'compile-function-definition fbody))
1743          (*environment*
1744           (extend-lexenv (mapcar #'make-function-binding fnames)
1745                          *environment*
1746                          'function)))
1747     (code "(function("
1748           (join (mapcar #'translate-function fnames) ",")
1749           "){" *newline*
1750           (let ((body (ls-compile-block body t)))
1751             (indent body))
1752           "})(" (join cfuncs ",") ")")))
1753
1754 (define-compilation labels (definitions &rest body)
1755   (let* ((fnames (mapcar #'car definitions))
1756          (*environment*
1757           (extend-lexenv (mapcar #'make-function-binding fnames)
1758                          *environment*
1759                          'function)))
1760     (js!selfcall
1761       (mapconcat (lambda (func)
1762                    (code "var " (translate-function (car func))
1763                          " = " (compile-lambda (cadr func) (cddr func))
1764                          ";" *newline*))
1765                  definitions)
1766       (ls-compile-block body t))))
1767
1768
1769 (defvar *compiling-file* nil)
1770 (define-compilation eval-when-compile (&rest body)
1771   (if *compiling-file*
1772       (progn
1773         (eval (cons 'progn body))
1774         nil)
1775       (ls-compile `(progn ,@body))))
1776
1777 (defmacro define-transformation (name args form)
1778   `(define-compilation ,name ,args
1779      (ls-compile ,form)))
1780
1781 (define-compilation progn (&rest body)
1782   (if (null (cdr body))
1783       (ls-compile (car body) *multiple-value-p*)
1784       (js!selfcall (ls-compile-block body t))))
1785
1786 (defun special-variable-p (x)
1787   (and (claimp x 'variable 'special) t))
1788
1789 ;;; Wrap CODE to restore the symbol values of the dynamic
1790 ;;; bindings. BINDINGS is a list of pairs of the form
1791 ;;; (SYMBOL . PLACE),  where PLACE is a Javascript variable
1792 ;;; name to initialize the symbol value and where to stored
1793 ;;; the old value.
1794 (defun let-binding-wrapper (bindings body)
1795   (when (null bindings)
1796     (return-from let-binding-wrapper body))
1797   (code
1798    "try {" *newline*
1799    (indent "var tmp;" *newline*
1800            (mapconcat
1801             (lambda (b)
1802               (let ((s (ls-compile `(quote ,(car b)))))
1803                 (code "tmp = " s ".value;" *newline*
1804                       s ".value = " (cdr b) ";" *newline*
1805                       (cdr b) " = tmp;" *newline*)))
1806             bindings)
1807            body *newline*)
1808    "}" *newline*
1809    "finally {"  *newline*
1810    (indent
1811     (mapconcat (lambda (b)
1812                  (let ((s (ls-compile `(quote ,(car b)))))
1813                    (code s ".value" " = " (cdr b) ";" *newline*)))
1814                bindings))
1815    "}" *newline*))
1816
1817 (define-compilation let (bindings &rest body)
1818   (let* ((bindings (mapcar #'ensure-list bindings))
1819          (variables (mapcar #'first bindings))
1820          (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
1821          (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
1822          (dynamic-bindings))
1823     (code "(function("
1824           (join (mapcar (lambda (x)
1825                           (if (special-variable-p x)
1826                               (let ((v (gvarname x)))
1827                                 (push (cons x v) dynamic-bindings)
1828                                 v)
1829                               (translate-variable x)))
1830                         variables)
1831                 ",")
1832           "){" *newline*
1833           (let ((body (ls-compile-block body t)))
1834             (indent (let-binding-wrapper dynamic-bindings body)))
1835           "})(" (join cvalues ",") ")")))
1836
1837
1838 ;;; Return the code to initialize BINDING, and push it extending the
1839 ;;; current lexical environment if the variable is not special.
1840 (defun let*-initialize-value (binding)
1841   (let ((var (first binding))
1842         (value (second binding)))
1843     (if (special-variable-p var)
1844         (code (ls-compile `(setq ,var ,value)) ";" *newline*)
1845         (let* ((v (gvarname var))
1846                (b (make-binding var 'variable v)))
1847           (prog1 (code "var " v " = " (ls-compile value) ";" *newline*)
1848             (push-to-lexenv b *environment* 'variable))))))
1849
1850 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
1851 ;;; DOES NOT generate code to initialize the value of the symbols,
1852 ;;; unlike let-binding-wrapper.
1853 (defun let*-binding-wrapper (symbols body)
1854   (when (null symbols)
1855     (return-from let*-binding-wrapper body))
1856   (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
1857                        (remove-if-not #'special-variable-p symbols))))
1858     (code
1859      "try {" *newline*
1860      (indent
1861       (mapconcat (lambda (b)
1862                    (let ((s (ls-compile `(quote ,(car b)))))
1863                      (code "var " (cdr b) " = " s ".value;" *newline*)))
1864                  store)
1865       body)
1866      "}" *newline*
1867      "finally {" *newline*
1868      (indent
1869       (mapconcat (lambda (b)
1870                    (let ((s (ls-compile `(quote ,(car b)))))
1871                      (code s ".value" " = " (cdr b) ";" *newline*)))
1872                  store))
1873      "}" *newline*)))
1874
1875 (define-compilation let* (bindings &rest body)
1876   (let ((bindings (mapcar #'ensure-list bindings))
1877         (*environment* (copy-lexenv *environment*)))
1878     (js!selfcall
1879       (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
1880             (body (concat (mapconcat #'let*-initialize-value bindings)
1881                           (ls-compile-block body t))))
1882         (let*-binding-wrapper specials body)))))
1883
1884
1885 (defvar *block-counter* 0)
1886
1887 (define-compilation block (name &rest body)
1888   (let* ((tr (incf *block-counter*))
1889          (b (make-binding name 'block tr)))
1890     (when *multiple-value-p*
1891       (push-binding-declaration 'multiple-value b))
1892     (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
1893            (cbody (ls-compile-block body t)))
1894       (if (member 'used (binding-declarations b))
1895           (js!selfcall
1896             "try {" *newline*
1897             (indent cbody)
1898             "}" *newline*
1899             "catch (cf){" *newline*
1900             "    if (cf.type == 'block' && cf.id == " tr ")" *newline*
1901             (if *multiple-value-p*
1902                 "        return values.apply(this, forcemv(cf.values));"
1903                 "        return cf.values;")
1904             *newline*
1905             "    else" *newline*
1906             "        throw cf;" *newline*
1907             "}" *newline*)
1908           (js!selfcall cbody)))))
1909
1910 (define-compilation return-from (name &optional value)
1911   (let* ((b (lookup-in-lexenv name *environment* 'block))
1912          (multiple-value-p (member 'multiple-value (binding-declarations b))))
1913     (when (null b)
1914       (error (concat "Unknown block `" (symbol-name name) "'.")))
1915     (push-binding-declaration 'used b)
1916     (js!selfcall
1917       (when multiple-value-p (code "var values = mv;" *newline*))
1918       "throw ({"
1919       "type: 'block', "
1920       "id: " (binding-value b) ", "
1921       "values: " (ls-compile value multiple-value-p) ", "
1922       "message: 'Return from unknown block " (symbol-name name) ".'"
1923       "})")))
1924
1925 (define-compilation catch (id &rest body)
1926   (js!selfcall
1927     "var id = " (ls-compile id) ";" *newline*
1928     "try {" *newline*
1929     (indent (ls-compile-block body t)) *newline*
1930     "}" *newline*
1931     "catch (cf){" *newline*
1932     "    if (cf.type == 'catch' && cf.id == id)" *newline*
1933     (if *multiple-value-p*
1934         "        return values.apply(this, forcemv(cf.values));"
1935         "        return pv.apply(this, forcemv(cf.values));")
1936     *newline*
1937     "    else" *newline*
1938     "        throw cf;" *newline*
1939     "}" *newline*))
1940
1941 (define-compilation throw (id value)
1942   (js!selfcall
1943     "var values = mv;" *newline*
1944     "throw ({"
1945     "type: 'catch', "
1946     "id: " (ls-compile id) ", "
1947     "values: " (ls-compile value t) ", "
1948     "message: 'Throw uncatched.'"
1949     "})"))
1950
1951
1952 (defvar *tagbody-counter* 0)
1953 (defvar *go-tag-counter* 0)
1954
1955 (defun go-tag-p (x)
1956   (or (integerp x) (symbolp x)))
1957
1958 (defun declare-tagbody-tags (tbidx body)
1959   (let ((bindings
1960          (mapcar (lambda (label)
1961                    (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1962                      (make-binding label 'gotag (list tbidx tagidx))))
1963                  (remove-if-not #'go-tag-p body))))
1964     (extend-lexenv bindings *environment* 'gotag)))
1965
1966 (define-compilation tagbody (&rest body)
1967   ;; Ignore the tagbody if it does not contain any go-tag. We do this
1968   ;; because 1) it is easy and 2) many built-in forms expand to a
1969   ;; implicit tagbody, so we save some space.
1970   (unless (some #'go-tag-p body)
1971     (return-from tagbody (ls-compile `(progn ,@body nil))))
1972   ;; The translation assumes the first form in BODY is a label
1973   (unless (go-tag-p (car body))
1974     (push (gensym "START") body))
1975   ;; Tagbody compilation
1976   (let ((tbidx *tagbody-counter*))
1977     (let ((*environment* (declare-tagbody-tags tbidx body))
1978           initag)
1979       (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1980         (setq initag (second (binding-value b))))
1981       (js!selfcall
1982         "var tagbody_" tbidx " = " initag ";" *newline*
1983         "tbloop:" *newline*
1984         "while (true) {" *newline*
1985         (indent "try {" *newline*
1986                 (indent (let ((content ""))
1987                           (code "switch(tagbody_" tbidx "){" *newline*
1988                                 "case " initag ":" *newline*
1989                                 (dolist (form (cdr body) content)
1990                                   (concatf content
1991                                     (if (not (go-tag-p form))
1992                                         (indent (ls-compile form) ";" *newline*)
1993                                         (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1994                                           (code "case " (second (binding-value b)) ":" *newline*)))))
1995                                 "default:" *newline*
1996                                 "    break tbloop;" *newline*
1997                                 "}" *newline*)))
1998                 "}" *newline*
1999                 "catch (jump) {" *newline*
2000                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
2001                 "        tagbody_" tbidx " = jump.label;" *newline*
2002                 "    else" *newline*
2003                 "        throw(jump);" *newline*
2004                 "}" *newline*)
2005         "}" *newline*
2006         "return " (ls-compile nil) ";" *newline*))))
2007
2008 (define-compilation go (label)
2009   (let ((b (lookup-in-lexenv label *environment* 'gotag))
2010         (n (cond
2011              ((symbolp label) (symbol-name label))
2012              ((integerp label) (integer-to-string label)))))
2013     (when (null b)
2014       (error (concat "Unknown tag `" n "'.")))
2015     (js!selfcall
2016       "throw ({"
2017       "type: 'tagbody', "
2018       "id: " (first (binding-value b)) ", "
2019       "label: " (second (binding-value b)) ", "
2020       "message: 'Attempt to GO to non-existing tag " n "'"
2021       "})" *newline*)))
2022
2023 (define-compilation unwind-protect (form &rest clean-up)
2024   (js!selfcall
2025     "var ret = " (ls-compile nil) ";" *newline*
2026     "try {" *newline*
2027     (indent "ret = " (ls-compile form) ";" *newline*)
2028     "} finally {" *newline*
2029     (indent (ls-compile-block clean-up))
2030     "}" *newline*
2031     "return ret;" *newline*))
2032
2033 (define-compilation multiple-value-call (func-form &rest forms)
2034   (js!selfcall
2035     "var func = " (ls-compile func-form) ";" *newline*
2036     "var args = [" (if *multiple-value-p* "values" "pv") "];" *newline*
2037     "return "
2038     (js!selfcall
2039       "var values = mv;" *newline*
2040       "var vs;" *newline*
2041       (mapconcat (lambda (form)
2042                    (code "vs = " (ls-compile form t) ";" *newline*
2043                          "if (typeof vs === 'object' && 'multiple-value' in vs)" *newline*
2044                          (indent "args = args.concat(vs);" *newline*)
2045                          "else" *newline*
2046                          (indent "args.push(vs);" *newline*)))
2047                  forms)
2048       "return func.apply(window, args);" *newline*) ";" *newline*))
2049
2050 (define-compilation multiple-value-prog1 (first-form &rest forms)
2051   (js!selfcall
2052     "var args = " (ls-compile first-form *multiple-value-p*) ";" *newline*
2053     (ls-compile-block forms)
2054     "return args;" *newline*))
2055
2056
2057 ;;; Backquote implementation.
2058 ;;;
2059 ;;;    Author: Guy L. Steele Jr.     Date: 27 December 1985
2060 ;;;    Tested under Symbolics Common Lisp and Lucid Common Lisp.
2061 ;;;    This software is in the public domain.
2062
2063 ;;;    The following are unique tokens used during processing.
2064 ;;;    They need not be symbols; they need not even be atoms.
2065 (defvar *comma* 'unquote)
2066 (defvar *comma-atsign* 'unquote-splicing)
2067
2068 (defvar *bq-list* (make-symbol "BQ-LIST"))
2069 (defvar *bq-append* (make-symbol "BQ-APPEND"))
2070 (defvar *bq-list** (make-symbol "BQ-LIST*"))
2071 (defvar *bq-nconc* (make-symbol "BQ-NCONC"))
2072 (defvar *bq-clobberable* (make-symbol "BQ-CLOBBERABLE"))
2073 (defvar *bq-quote* (make-symbol "BQ-QUOTE"))
2074 (defvar *bq-quote-nil* (list *bq-quote* nil))
2075
2076 ;;; BACKQUOTE is an ordinary macro (not a read-macro) that processes
2077 ;;; the expression foo, looking for occurrences of #:COMMA,
2078 ;;; #:COMMA-ATSIGN, and #:COMMA-DOT.  It constructs code in strict
2079 ;;; accordance with the rules on pages 349-350 of the first edition
2080 ;;; (pages 528-529 of this second edition).  It then optionally
2081 ;;; applies a code simplifier.
2082
2083 ;;; If the value of *BQ-SIMPLIFY* is non-NIL, then BACKQUOTE
2084 ;;; processing applies the code simplifier.  If the value is NIL,
2085 ;;; then the code resulting from BACKQUOTE is exactly that
2086 ;;; specified by the official rules.
2087 (defparameter *bq-simplify* t)
2088
2089 (defmacro backquote (x)
2090   (bq-completely-process x))
2091
2092 ;;; Backquote processing proceeds in three stages:
2093 ;;;
2094 ;;; (1) BQ-PROCESS applies the rules to remove occurrences of
2095 ;;; #:COMMA, #:COMMA-ATSIGN, and #:COMMA-DOT corresponding to
2096 ;;; this level of BACKQUOTE.  (It also causes embedded calls to
2097 ;;; BACKQUOTE to be expanded so that nesting is properly handled.)
2098 ;;; Code is produced that is expressed in terms of functions
2099 ;;; #:BQ-LIST, #:BQ-APPEND, and #:BQ-CLOBBERABLE.  This is done
2100 ;;; so that the simplifier will simplify only list construction
2101 ;;; functions actually generated by BACKQUOTE and will not involve
2102 ;;; any user code in the simplification.  #:BQ-LIST means LIST,
2103 ;;; #:BQ-APPEND means APPEND, and #:BQ-CLOBBERABLE means IDENTITY
2104 ;;; but indicates places where "%." was used and where NCONC may
2105 ;;; therefore be introduced by the simplifier for efficiency.
2106 ;;;
2107 ;;; (2) BQ-SIMPLIFY, if used, rewrites the code produced by
2108 ;;; BQ-PROCESS to produce equivalent but faster code.  The
2109 ;;; additional functions #:BQ-LIST* and #:BQ-NCONC may be
2110 ;;; introduced into the code.
2111 ;;;
2112 ;;; (3) BQ-REMOVE-TOKENS goes through the code and replaces
2113 ;;; #:BQ-LIST with LIST, #:BQ-APPEND with APPEND, and so on.
2114 ;;; #:BQ-CLOBBERABLE is simply eliminated (a call to it being
2115 ;;; replaced by its argument).  #:BQ-LIST* is replaced by either
2116 ;;; LIST* or CONS (the latter is used in the two-argument case,
2117 ;;; purely to make the resulting code a tad more readable).
2118
2119 (defun bq-completely-process (x)
2120   (let ((raw-result (bq-process x)))
2121     (bq-remove-tokens (if *bq-simplify*
2122                           (bq-simplify raw-result)
2123                           raw-result))))
2124
2125 (defun bq-process (x)
2126   (cond ((atom x)
2127          (list *bq-quote* x))
2128         ((eq (car x) 'backquote)
2129          (bq-process (bq-completely-process (cadr x))))
2130         ((eq (car x) *comma*) (cadr x))
2131         ((eq (car x) *comma-atsign*)
2132          ;; (error ",@~S after `" (cadr x))
2133          (error "ill-formed"))
2134         ;; ((eq (car x) *comma-dot*)
2135         ;;  ;; (error ",.~S after `" (cadr x))
2136         ;;  (error "ill-formed"))
2137         (t (do ((p x (cdr p))
2138                 (q '() (cons (bracket (car p)) q)))
2139                ((atom p)
2140                 (cons *bq-append*
2141                       (nreconc q (list (list *bq-quote* p)))))
2142              (when (eq (car p) *comma*)
2143                (unless (null (cddr p))
2144                  ;; (error "Malformed ,~S" p)
2145                  (error "Malformed"))
2146                (return (cons *bq-append*
2147                              (nreconc q (list (cadr p))))))
2148              (when (eq (car p) *comma-atsign*)
2149                ;; (error "Dotted ,@~S" p)
2150                (error "Dotted"))
2151              ;; (when (eq (car p) *comma-dot*)
2152              ;;   ;; (error "Dotted ,.~S" p)
2153              ;;   (error "Dotted"))
2154              ))))
2155
2156 ;;; This implements the bracket operator of the formal rules.
2157 (defun bracket (x)
2158   (cond ((atom x)
2159          (list *bq-list* (bq-process x)))
2160         ((eq (car x) *comma*)
2161          (list *bq-list* (cadr x)))
2162         ((eq (car x) *comma-atsign*)
2163          (cadr x))
2164         ;; ((eq (car x) *comma-dot*)
2165         ;;  (list *bq-clobberable* (cadr x)))
2166         (t (list *bq-list* (bq-process x)))))
2167
2168 ;;; This auxiliary function is like MAPCAR but has two extra
2169 ;;; purposes: (1) it handles dotted lists; (2) it tries to make
2170 ;;; the result share with the argument x as much as possible.
2171 (defun maptree (fn x)
2172   (if (atom x)
2173       (funcall fn x)
2174       (let ((a (funcall fn (car x)))
2175             (d (maptree fn (cdr x))))
2176         (if (and (eql a (car x)) (eql d (cdr x)))
2177             x
2178             (cons a d)))))
2179
2180 ;;; This predicate is true of a form that when read looked
2181 ;;; like %@foo or %.foo.
2182 (defun bq-splicing-frob (x)
2183   (and (consp x)
2184        (or (eq (car x) *comma-atsign*)
2185            ;; (eq (car x) *comma-dot*)
2186            )))
2187
2188 ;;; This predicate is true of a form that when read
2189 ;;; looked like %@foo or %.foo or just plain %foo.
2190 (defun bq-frob (x)
2191   (and (consp x)
2192        (or (eq (car x) *comma*)
2193            (eq (car x) *comma-atsign*)
2194            ;; (eq (car x) *comma-dot*)
2195            )))
2196
2197 ;;; The simplifier essentially looks for calls to #:BQ-APPEND and
2198 ;;; tries to simplify them.  The arguments to #:BQ-APPEND are
2199 ;;; processed from right to left, building up a replacement form.
2200 ;;; At each step a number of special cases are handled that,
2201 ;;; loosely speaking, look like this:
2202 ;;;
2203 ;;;  (APPEND (LIST a b c) foo) => (LIST* a b c foo)
2204 ;;;       provided a, b, c are not splicing frobs
2205 ;;;  (APPEND (LIST* a b c) foo) => (LIST* a b (APPEND c foo))
2206 ;;;       provided a, b, c are not splicing frobs
2207 ;;;  (APPEND (QUOTE (x)) foo) => (LIST* (QUOTE x) foo)
2208 ;;;  (APPEND (CLOBBERABLE x) foo) => (NCONC x foo)
2209 (defun bq-simplify (x)
2210   (if (atom x)
2211       x
2212       (let ((x (if (eq (car x) *bq-quote*)
2213                    x
2214                    (maptree #'bq-simplify x))))
2215         (if (not (eq (car x) *bq-append*))
2216             x
2217             (bq-simplify-args x)))))
2218
2219 (defun bq-simplify-args (x)
2220   (do ((args (reverse (cdr x)) (cdr args))
2221        (result
2222          nil
2223          (cond ((atom (car args))
2224                 (bq-attach-append *bq-append* (car args) result))
2225                ((and (eq (caar args) *bq-list*)
2226                      (notany #'bq-splicing-frob (cdar args)))
2227                 (bq-attach-conses (cdar args) result))
2228                ((and (eq (caar args) *bq-list**)
2229                      (notany #'bq-splicing-frob (cdar args)))
2230                 (bq-attach-conses
2231                   (reverse (cdr (reverse (cdar args))))
2232                   (bq-attach-append *bq-append*
2233                                     (car (last (car args)))
2234                                     result)))
2235                ((and (eq (caar args) *bq-quote*)
2236                      (consp (cadar args))
2237                      (not (bq-frob (cadar args)))
2238                      (null (cddar args)))
2239                 (bq-attach-conses (list (list *bq-quote*
2240                                               (caadar args)))
2241                                   result))
2242                ((eq (caar args) *bq-clobberable*)
2243                 (bq-attach-append *bq-nconc* (cadar args) result))
2244                (t (bq-attach-append *bq-append*
2245                                     (car args)
2246                                     result)))))
2247       ((null args) result)))
2248
2249 (defun null-or-quoted (x)
2250   (or (null x) (and (consp x) (eq (car x) *bq-quote*))))
2251
2252 ;;; When BQ-ATTACH-APPEND is called, the OP should be #:BQ-APPEND
2253 ;;; or #:BQ-NCONC.  This produces a form (op item result) but
2254 ;;; some simplifications are done on the fly:
2255 ;;;
2256 ;;;  (op '(a b c) '(d e f g)) => '(a b c d e f g)
2257 ;;;  (op item 'nil) => item, provided item is not a splicable frob
2258 ;;;  (op item 'nil) => (op item), if item is a splicable frob
2259 ;;;  (op item (op a b c)) => (op item a b c)
2260 (defun bq-attach-append (op item result)
2261   (cond ((and (null-or-quoted item) (null-or-quoted result))
2262          (list *bq-quote* (append (cadr item) (cadr result))))
2263         ((or (null result) (equal result *bq-quote-nil*))
2264          (if (bq-splicing-frob item) (list op item) item))
2265         ((and (consp result) (eq (car result) op))
2266          (list* (car result) item (cdr result)))
2267         (t (list op item result))))
2268
2269 ;;; The effect of BQ-ATTACH-CONSES is to produce a form as if by
2270 ;;; `(LIST* ,@items ,result) but some simplifications are done
2271 ;;; on the fly.
2272 ;;;
2273 ;;;  (LIST* 'a 'b 'c 'd) => '(a b c . d)
2274 ;;;  (LIST* a b c 'nil) => (LIST a b c)
2275 ;;;  (LIST* a b c (LIST* d e f g)) => (LIST* a b c d e f g)
2276 ;;;  (LIST* a b c (LIST d e f g)) => (LIST a b c d e f g)
2277 (defun bq-attach-conses (items result)
2278   (cond ((and (every #'null-or-quoted items)
2279               (null-or-quoted result))
2280          (list *bq-quote*
2281                (append (mapcar #'cadr items) (cadr result))))
2282         ((or (null result) (equal result *bq-quote-nil*))
2283          (cons *bq-list* items))
2284         ((and (consp result)
2285               (or (eq (car result) *bq-list*)
2286                   (eq (car result) *bq-list**)))
2287          (cons (car result) (append items (cdr result))))
2288         (t (cons *bq-list** (append items (list result))))))
2289
2290 ;;; Removes funny tokens and changes (#:BQ-LIST* a b) into
2291 ;;; (CONS a b) instead of (LIST* a b), purely for readability.
2292 (defun bq-remove-tokens (x)
2293   (cond ((eq x *bq-list*) 'list)
2294         ((eq x *bq-append*) 'append)
2295         ((eq x *bq-nconc*) 'nconc)
2296         ((eq x *bq-list**) 'list*)
2297         ((eq x *bq-quote*) 'quote)
2298         ((atom x) x)
2299         ((eq (car x) *bq-clobberable*)
2300          (bq-remove-tokens (cadr x)))
2301         ((and (eq (car x) *bq-list**)
2302               (consp (cddr x))
2303               (null (cdddr x)))
2304          (cons 'cons (maptree #'bq-remove-tokens (cdr x))))
2305         (t (maptree #'bq-remove-tokens x))))
2306
2307 (define-transformation backquote (form)
2308   (bq-completely-process form))
2309
2310
2311 ;;; Primitives
2312
2313 (defvar *builtins* nil)
2314
2315 (defmacro define-raw-builtin (name args &body body)
2316   ;; Creates a new primitive function `name' with parameters args and
2317   ;; @body. The body can access to the local environment through the
2318   ;; variable *ENVIRONMENT*.
2319   `(push (list ',name (lambda ,args (block ,name ,@body)))
2320          *builtins*))
2321
2322 (defmacro define-builtin (name args &body body)
2323   `(define-raw-builtin ,name ,args
2324      (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
2325        ,@body)))
2326
2327 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
2328 (defmacro type-check (decls &body body)
2329   `(js!selfcall
2330      ,@(mapcar (lambda (decl)
2331                  `(code "var " ,(first decl) " = " ,(third decl) ";" *newline*))
2332                decls)
2333      ,@(mapcar (lambda (decl)
2334                  `(code "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
2335                         (indent "throw 'The value ' + "
2336                                 ,(first decl)
2337                                 " + ' is not a type "
2338                                 ,(second decl)
2339                                 ".';"
2340                                 *newline*)))
2341                decls)
2342      (code "return " (progn ,@body) ";" *newline*)))
2343
2344 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
2345 ;;; a variable which holds a list of forms. It will compile them and
2346 ;;; store the result in some Javascript variables. BODY is evaluated
2347 ;;; with ARGS bound to the list of these variables to generate the
2348 ;;; code which performs the transformation on these variables.
2349
2350 (defun variable-arity-call (args function)
2351   (unless (consp args)
2352     (error "ARGS must be a non-empty list"))
2353   (let ((counter 0)
2354         (fargs '())
2355         (prelude ""))
2356     (dolist (x args)
2357       (if (numberp x)
2358           (push (integer-to-string x) fargs)
2359           (let ((v (code "x" (incf counter))))
2360             (push v fargs)
2361             (concatf prelude
2362               (code "var " v " = " (ls-compile x) ";" *newline*
2363                     "if (typeof " v " !== 'number') throw 'Not a number!';"
2364                     *newline*)))))
2365     (js!selfcall prelude (funcall function (reverse fargs)))))
2366
2367
2368 (defmacro variable-arity (args &body body)
2369   (unless (symbolp args)
2370     (error "Bad usage of VARIABLE-ARITY, you must pass a symbol"))
2371   `(variable-arity-call ,args
2372                         (lambda (,args)
2373                           (code "return " ,@body ";" *newline*))))
2374
2375 (defun num-op-num (x op y)
2376   (type-check (("x" "number" x) ("y" "number" y))
2377     (code "x" op "y")))
2378
2379 (define-raw-builtin + (&rest numbers)
2380   (if (null numbers)
2381       "0"
2382       (variable-arity numbers
2383         (join numbers "+"))))
2384
2385 (define-raw-builtin - (x &rest others)
2386   (let ((args (cons x others)))
2387     (variable-arity args
2388       (if (null others)
2389           (concat "-" (car args))
2390           (join args "-")))))
2391
2392 (define-raw-builtin * (&rest numbers)
2393   (if (null numbers)
2394       "1"
2395       (variable-arity numbers
2396         (join numbers "*"))))
2397
2398 (define-raw-builtin / (x &rest others)
2399   (let ((args (cons x others)))
2400     (variable-arity args
2401       (if (null others)
2402           (concat "1 /" (car args))
2403           (join args "/")))))
2404
2405 (define-builtin mod (x y) (num-op-num x "%" y))
2406
2407
2408 (defun comparison-conjuntion (vars op)
2409   (cond
2410     ((null (cdr vars))
2411      "true")
2412     ((null (cddr vars))
2413      (concat (car vars) op (cadr vars)))
2414     (t
2415      (concat (car vars) op (cadr vars)
2416              " && "
2417              (comparison-conjuntion (cdr vars) op)))))
2418
2419 (defmacro define-builtin-comparison (op sym)
2420   `(define-raw-builtin ,op (x &rest args)
2421      (let ((args (cons x args)))
2422        (variable-arity args
2423          (js!bool (comparison-conjuntion args ,sym))))))
2424
2425 (define-builtin-comparison > ">")
2426 (define-builtin-comparison < "<")
2427 (define-builtin-comparison >= ">=")
2428 (define-builtin-comparison <= "<=")
2429 (define-builtin-comparison = "==")
2430
2431 (define-builtin numberp (x)
2432   (js!bool (code "(typeof (" x ") == \"number\")")))
2433
2434 (define-builtin floor (x)
2435   (type-check (("x" "number" x))
2436     "Math.floor(x)"))
2437
2438 (define-builtin cons (x y)
2439   (code "({car: " x ", cdr: " y "})"))
2440
2441 (define-builtin consp (x)
2442   (js!bool
2443    (js!selfcall
2444      "var tmp = " x ";" *newline*
2445      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
2446
2447 (define-builtin car (x)
2448   (js!selfcall
2449     "var tmp = " x ";" *newline*
2450     "return tmp === " (ls-compile nil)
2451     "? " (ls-compile nil)
2452     ": tmp.car;" *newline*))
2453
2454 (define-builtin cdr (x)
2455   (js!selfcall
2456     "var tmp = " x ";" *newline*
2457     "return tmp === " (ls-compile nil) "? "
2458     (ls-compile nil)
2459     ": tmp.cdr;" *newline*))
2460
2461 (define-builtin rplaca (x new)
2462   (type-check (("x" "object" x))
2463     (code "(x.car = " new ", x)")))
2464
2465 (define-builtin rplacd (x new)
2466   (type-check (("x" "object" x))
2467     (code "(x.cdr = " new ", x)")))
2468
2469 (define-builtin symbolp (x)
2470   (js!bool
2471    (js!selfcall
2472      "var tmp = " x ";" *newline*
2473      "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
2474
2475 (define-builtin make-symbol (name)
2476   (type-check (("name" "string" name))
2477     "({name: name})"))
2478
2479 (define-builtin symbol-name (x)
2480   (code "(" x ").name"))
2481
2482 (define-builtin set (symbol value)
2483   (code "(" symbol ").value = " value))
2484
2485 (define-builtin fset (symbol value)
2486   (code "(" symbol ").fvalue = " value))
2487
2488 (define-builtin boundp (x)
2489   (js!bool (code "(" x ".value !== undefined)")))
2490
2491 (define-builtin symbol-value (x)
2492   (js!selfcall
2493     "var symbol = " x ";" *newline*
2494     "var value = symbol.value;" *newline*
2495     "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
2496     "return value;" *newline*))
2497
2498 (define-builtin symbol-function (x)
2499   (js!selfcall
2500     "var symbol = " x ";" *newline*
2501     "var func = symbol.fvalue;" *newline*
2502     "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
2503     "return func;" *newline*))
2504
2505 (define-builtin symbol-plist (x)
2506   (code "((" x ").plist || " (ls-compile nil) ")"))
2507
2508 (define-builtin lambda-code (x)
2509   (code "(" x ").toString()"))
2510
2511 (define-builtin eq    (x y) (js!bool (code "(" x " === " y ")")))
2512 (define-builtin equal (x y) (js!bool (code "(" x  " == " y ")")))
2513
2514 (define-builtin char-to-string (x)
2515   (type-check (("x" "number" x))
2516     "String.fromCharCode(x)"))
2517
2518 (define-builtin stringp (x)
2519   (js!bool (code "(typeof(" x ") == \"string\")")))
2520
2521 (define-builtin string-upcase (x)
2522   (type-check (("x" "string" x))
2523     "x.toUpperCase()"))
2524
2525 (define-builtin string-length (x)
2526   (type-check (("x" "string" x))
2527     "x.length"))
2528
2529 (define-raw-builtin slice (string a &optional b)
2530   (js!selfcall
2531     "var str = " (ls-compile string) ";" *newline*
2532     "var a = " (ls-compile a) ";" *newline*
2533     "var b;" *newline*
2534     (when b (code "b = " (ls-compile b) ";" *newline*))
2535     "return str.slice(a,b);" *newline*))
2536
2537 (define-builtin char (string index)
2538   (type-check (("string" "string" string)
2539                ("index" "number" index))
2540     "string.charCodeAt(index)"))
2541
2542 (define-builtin concat-two (string1 string2)
2543   (type-check (("string1" "string" string1)
2544                ("string2" "string" string2))
2545     "string1.concat(string2)"))
2546
2547 (define-raw-builtin funcall (func &rest args)
2548   (js!selfcall
2549     "var f = " (ls-compile func) ";" *newline*
2550     "return (typeof f === 'function'? f: f.fvalue)("
2551     (join (cons (if *multiple-value-p* "values" "pv")
2552                 (mapcar #'ls-compile args))
2553           ", ")
2554     ")"))
2555
2556 (define-raw-builtin apply (func &rest args)
2557   (if (null args)
2558       (code "(" (ls-compile func) ")()")
2559       (let ((args (butlast args))
2560             (last (car (last args))))
2561         (js!selfcall
2562           "var f = " (ls-compile func) ";" *newline*
2563           "var args = [" (join (cons (if *multiple-value-p* "values" "pv")
2564                                      (mapcar #'ls-compile args))
2565                                ", ")
2566           "];" *newline*
2567           "var tail = (" (ls-compile last) ");" *newline*
2568           "while (tail != " (ls-compile nil) "){" *newline*
2569           "    args.push(tail.car);" *newline*
2570           "    tail = tail.cdr;" *newline*
2571           "}" *newline*
2572           "return (typeof f === 'function'? f : f.fvalue).apply(this, args);" *newline*))))
2573
2574 (define-builtin js-eval (string)
2575   (type-check (("string" "string" string))
2576     (if *multiple-value-p*
2577         (js!selfcall
2578           "var v = eval.apply(window, [string]);" *newline*
2579           "if (typeof v !== 'object' || !('multiple-value' in v)){" *newline*
2580           (indent "v = [v];" *newline*
2581                   "v['multiple-value'] = true;" *newline*)
2582           "}" *newline*
2583           "return values.apply(this, v);" *newline*)
2584         "eval.apply(window, [string])")))
2585
2586 (define-builtin error (string)
2587   (js!selfcall "throw " string ";" *newline*))
2588
2589 (define-builtin new () "{}")
2590
2591 (define-builtin objectp (x)
2592   (js!bool (code "(typeof (" x ") === 'object')")))
2593
2594 (define-builtin oget (object key)
2595   (js!selfcall
2596     "var tmp = " "(" object ")[" key "];" *newline*
2597     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
2598
2599 (define-builtin oset (object key value)
2600   (code "((" object ")[" key "] = " value ")"))
2601
2602 (define-builtin in (key object)
2603   (js!bool (code "((" key ") in (" object "))")))
2604
2605 (define-builtin functionp (x)
2606   (js!bool (code "(typeof " x " == 'function')")))
2607
2608 (define-builtin write-string (x)
2609   (type-check (("x" "string" x))
2610     "lisp.write(x)"))
2611
2612 (define-builtin make-array (n)
2613   (js!selfcall
2614     "var r = [];" *newline*
2615     "for (var i = 0; i < " n "; i++)" *newline*
2616     (indent "r.push(" (ls-compile nil) ");" *newline*)
2617     "return r;" *newline*))
2618
2619 (define-builtin arrayp (x)
2620   (js!bool
2621    (js!selfcall
2622      "var x = " x ";" *newline*
2623      "return typeof x === 'object' && 'length' in x;")))
2624
2625 (define-builtin aref (array n)
2626   (js!selfcall
2627     "var x = " "(" array ")[" n "];" *newline*
2628     "if (x === undefined) throw 'Out of range';" *newline*
2629     "return x;" *newline*))
2630
2631 (define-builtin aset (array n value)
2632   (js!selfcall
2633     "var x = " array ";" *newline*
2634     "var i = " n ";" *newline*
2635     "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
2636     "return x[i] = " value ";" *newline*))
2637
2638 (define-builtin get-unix-time ()
2639   (code "(Math.round(new Date() / 1000))"))
2640
2641 (define-builtin values-array (array)
2642   (if *multiple-value-p*
2643       (code "values.apply(this, " array ")")
2644       (code "pv.apply(this, " array ")")))
2645
2646 (define-raw-builtin values (&rest args)
2647   (if *multiple-value-p*
2648       (code "values(" (join (mapcar #'ls-compile args) ", ") ")")
2649       (code "pv(" (join (mapcar #'ls-compile args) ", ") ")")))
2650
2651 (defun macro (x)
2652   (and (symbolp x)
2653        (let ((b (lookup-in-lexenv x *environment* 'function)))
2654          (and (eq (binding-type b) 'macro)
2655               b))))
2656
2657 (defun ls-macroexpand-1 (form)
2658   (let ((macro-binding (macro (car form))))
2659     (if macro-binding
2660         (let ((expander (binding-value macro-binding)))
2661           (when (listp expander)
2662             (let ((compiled (eval expander)))
2663               ;; The list representation are useful while
2664               ;; bootstrapping, as we can dump the definition of the
2665               ;; macros easily, but they are slow because we have to
2666               ;; evaluate them and compile them now and again. So, let
2667               ;; us replace the list representation version of the
2668               ;; function with the compiled one.
2669               ;;
2670               #+ecmalisp (set-binding-value macro-binding compiled)
2671               (setq expander compiled)))
2672           (apply expander (cdr form)))
2673         form)))
2674
2675 (defun compile-funcall (function args)
2676   (let* ((values-funcs (if *multiple-value-p* "values" "pv"))
2677          (arglist (concat "(" (join (cons values-funcs (mapcar #'ls-compile args)) ", ") ")")))
2678     (cond
2679       ((translate-function function)
2680        (concat (translate-function function) arglist))
2681       ((and (symbolp function)
2682             #+ecmalisp (eq (symbol-package function) (find-package "COMMON-LISP"))
2683             #+common-lisp t)
2684        (code (ls-compile `',function) ".fvalue" arglist))
2685       (t
2686        (code (ls-compile `#',function) arglist)))))
2687
2688 (defun ls-compile-block (sexps &optional return-last-p)
2689   (if return-last-p
2690       (code (ls-compile-block (butlast sexps))
2691             "return " (ls-compile (car (last sexps)) *multiple-value-p*) ";")
2692       (join-trailing
2693        (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
2694        (concat ";" *newline*))))
2695
2696 (defun ls-compile (sexp &optional multiple-value-p)
2697   (let ((*multiple-value-p* multiple-value-p))
2698     (cond
2699       ((symbolp sexp)
2700        (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
2701          (cond
2702            ((and b (not (member 'special (binding-declarations b))))
2703             (binding-value b))
2704            ((or (keywordp sexp)
2705                 (member 'constant (binding-declarations b)))
2706             (code (ls-compile `',sexp) ".value"))
2707            (t
2708             (ls-compile `(symbol-value ',sexp))))))
2709       ((integerp sexp) (integer-to-string sexp))
2710       ((stringp sexp) (code "\"" (escape-string sexp) "\""))
2711       ((arrayp sexp) (literal sexp))
2712       ((listp sexp)
2713        (let ((name (car sexp))
2714              (args (cdr sexp)))
2715          (cond
2716            ;; Special forms
2717            ((assoc name *compilations*)
2718             (let ((comp (second (assoc name *compilations*))))
2719               (apply comp args)))
2720            ;; Built-in functions
2721            ((and (assoc name *builtins*)
2722                  (not (claimp name 'function 'notinline)))
2723             (let ((comp (second (assoc name *builtins*))))
2724               (apply comp args)))
2725            (t
2726             (if (macro name)
2727                 (ls-compile (ls-macroexpand-1 sexp) multiple-value-p)
2728                 (compile-funcall name args))))))
2729       (t
2730        (error (concat "How should I compile " (prin1-to-string sexp) "?"))))))
2731
2732 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
2733   (let ((*toplevel-compilations* nil))
2734     (cond
2735       ((and (consp sexp) (eq (car sexp) 'progn))
2736        (let ((subs (mapcar (lambda (s)
2737                              (ls-compile-toplevel s t))
2738                            (cdr sexp))))
2739          (join (remove-if #'null-or-empty-p subs))))
2740       (t
2741        (let ((code (ls-compile sexp multiple-value-p)))
2742          (code (join-trailing (get-toplevel-compilations)
2743                               (code ";" *newline*))
2744                (when code
2745                  (code code ";" *newline*))))))))
2746
2747
2748 ;;; Once we have the compiler, we define the runtime environment and
2749 ;;; interactive development (eval), which works calling the compiler
2750 ;;; and evaluating the Javascript result globally.
2751
2752 #+ecmalisp
2753 (progn
2754   (defun eval (x)
2755     (js-eval (ls-compile-toplevel x t)))
2756
2757   (export '(&rest &key &optional &body * *gensym-counter* *package* + - / 1+ 1- <
2758             <= = = > >= and append apply aref arrayp assoc atom block boundp
2759             boundp butlast caar cadddr caddr cadr car car case catch cdar cdddr
2760             cddr cdr cdr char char-code fdefinition find-package find-symbol first
2761             flet fourth fset funcall function functionp gensym get-setf-expansion
2762             get-universal-time go identity if in-package incf integerp integerp
2763             intern keywordp labels lambda last length let let* char= code-char
2764             cond cons consp constantly copy-list decf declaim define-setf-expander
2765             defconstant defparameter defun defmacro defvar digit-char digit-char-p
2766             disassemble do do* documentation dolist dotimes ecase eq eql equal
2767             error eval every export list-all-packages list list* listp loop make-array
2768             make-package make-symbol mapcar member minusp mod multiple-value-bind
2769             multiple-value-call multiple-value-list multiple-value-prog1 nconc nil not
2770             nth nthcdr null numberp or package-name package-use-list packagep
2771             parse-integer plusp prin1-to-string print proclaim prog1 prog2 progn
2772             psetq push quote nreconc remove remove-if remove-if-not return return-from
2773             revappend reverse rplaca rplacd second set setf setq some
2774             string-upcase string string= stringp subseq symbol-function
2775             symbol-name symbol-package symbol-plist symbol-value symbolp t tagbody
2776             third throw truncate unless unwind-protect values values-list variable
2777             warn when write-line write-string zerop))
2778
2779   (setq *package* *user-package*)
2780
2781   (js-eval "var lisp")
2782   (js-vset "lisp" (new))
2783   (js-vset "lisp.read" #'ls-read-from-string)
2784   (js-vset "lisp.print" #'prin1-to-string)
2785   (js-vset "lisp.eval" #'eval)
2786   (js-vset "lisp.compile" (lambda (s) (ls-compile-toplevel s t)))
2787   (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
2788   (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str) t)))
2789
2790   ;; Set the initial global environment to be equal to the host global
2791   ;; environment at this point of the compilation.
2792   (eval-when-compile
2793     (toplevel-compilation
2794      (ls-compile `(setq *environment* ',*environment*))))
2795
2796   (eval-when-compile
2797     (toplevel-compilation
2798      (ls-compile
2799       `(progn
2800          ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
2801                    *literal-symbols*)
2802          (setq *literal-symbols* ',*literal-symbols*)
2803          (setq *variable-counter* ,*variable-counter*)
2804          (setq *gensym-counter* ,*gensym-counter*)
2805          (setq *block-counter* ,*block-counter*)))))
2806
2807   (eval-when-compile
2808     (toplevel-compilation
2809      (ls-compile
2810       `(setq *literal-counter* ,*literal-counter*)))))
2811
2812
2813 ;;; Finally, we provide a couple of functions to easily bootstrap
2814 ;;; this. It just calls the compiler with this file as input.
2815
2816 #+common-lisp
2817 (progn
2818   (defun read-whole-file (filename)
2819     (with-open-file (in filename)
2820       (let ((seq (make-array (file-length in) :element-type 'character)))
2821         (read-sequence seq in)
2822         seq)))
2823
2824   (defun ls-compile-file (filename output)
2825     (let ((*compiling-file* t))
2826       (with-open-file (out output :direction :output :if-exists :supersede)
2827         (write-string (read-whole-file "prelude.js") out)
2828         (let* ((source (read-whole-file filename))
2829                (in (make-string-stream source)))
2830           (loop
2831              for x = (ls-read in)
2832              until (eq x *eof*)
2833              for compilation = (ls-compile-toplevel x)
2834              when (plusp (length compilation))
2835              do (write-string compilation out))))))
2836
2837   (defun bootstrap ()
2838     (setq *environment* (make-lexenv))
2839     (setq *literal-symbols* nil)
2840     (setq *variable-counter* 0
2841           *gensym-counter* 0
2842           *literal-counter* 0
2843           *block-counter* 0)
2844     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))