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