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