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