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