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