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