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