7611d73a94982396ef6cebfd00e1c3e6f28a22b2
[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 set-binding-value (b value)
1368   (setf (binding-value b) value))
1369
1370 (defun set-binding-declarations (b value)
1371   (setf (binding-declarations b) value))
1372
1373 (defun push-binding-declaration (decl b)
1374   (set-binding-declarations b (cons decl (binding-declarations b))))
1375
1376
1377 (defun make-lexenv ()
1378   (list nil nil nil nil))
1379
1380 (defun copy-lexenv (lexenv)
1381   (copy-list lexenv))
1382
1383 (defun push-to-lexenv (binding lexenv namespace)
1384   (ecase namespace
1385     (variable   (rplaca        lexenv  (cons binding (car lexenv))))
1386     (function   (rplaca   (cdr lexenv) (cons binding (cadr lexenv))))
1387     (block      (rplaca  (cddr lexenv) (cons binding (caddr lexenv))))
1388     (gotag      (rplaca (cdddr lexenv) (cons binding (cadddr lexenv))))))
1389
1390 (defun extend-lexenv (bindings lexenv namespace)
1391   (let ((env (copy-lexenv lexenv)))
1392     (dolist (binding (reverse bindings) env)
1393       (push-to-lexenv binding env namespace))))
1394
1395 (defun lookup-in-lexenv (name lexenv namespace)
1396   (find name (ecase namespace
1397                 (variable (first lexenv))
1398                 (function (second lexenv))
1399                 (block (third lexenv))
1400                 (gotag (fourth lexenv)))
1401         :key #'binding-name))
1402
1403 (defvar *environment* (make-lexenv))
1404
1405 (defvar *variable-counter* 0)
1406
1407 (defun gvarname (symbol)
1408   (code "v" (incf *variable-counter*)))
1409
1410 (defun translate-variable (symbol)
1411   (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
1412
1413 (defun extend-local-env (args)
1414   (let ((new (copy-lexenv *environment*)))
1415     (dolist (symbol args new)
1416       (let ((b (make-binding :name symbol :type 'variable :value (gvarname symbol))))
1417         (push-to-lexenv b new 'variable)))))
1418
1419 ;;; Toplevel compilations
1420 (defvar *toplevel-compilations* nil)
1421
1422 (defun toplevel-compilation (string)
1423   (push string *toplevel-compilations*))
1424
1425 (defun null-or-empty-p (x)
1426   (zerop (length x)))
1427
1428 (defun get-toplevel-compilations ()
1429   (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
1430
1431 (defun %compile-defmacro (name lambda)
1432   (toplevel-compilation (ls-compile `',name))
1433   (push-to-lexenv (make-binding :name name :type 'macro :value lambda) *environment* 'function)
1434   name)
1435
1436 (defun global-binding (name type namespace)
1437   (or (lookup-in-lexenv name *environment* namespace)
1438       (let ((b (make-binding :name name :type type :value nil)))
1439         (push-to-lexenv b *environment* namespace)
1440         b)))
1441
1442 (defun claimp (symbol namespace claim)
1443   (let ((b (lookup-in-lexenv symbol *environment* namespace)))
1444     (and b (member claim (binding-declarations b)))))
1445
1446 (defun !proclaim (decl)
1447   (case (car decl)
1448     (special
1449      (dolist (name (cdr decl))
1450        (let ((b (global-binding name 'variable 'variable)))
1451          (push-binding-declaration 'special b))))
1452     (notinline
1453      (dolist (name (cdr decl))
1454        (let ((b (global-binding name 'function 'function)))
1455          (push-binding-declaration 'notinline b))))
1456     (constant
1457      (dolist (name (cdr decl))
1458        (let ((b (global-binding name 'variable 'variable)))
1459          (push-binding-declaration 'constant b))))))
1460
1461 #+ecmalisp
1462 (fset 'proclaim #'!proclaim)
1463
1464 ;;; Special forms
1465
1466 (defvar *compilations* nil)
1467
1468 (defmacro define-compilation (name args &body body)
1469   ;; Creates a new primitive `name' with parameters args and
1470   ;; @body. The body can access to the local environment through the
1471   ;; variable *ENVIRONMENT*.
1472   `(push (list ',name (lambda ,args (block ,name ,@body)))
1473          *compilations*))
1474
1475 (define-compilation if (condition true false)
1476   (code "(" (ls-compile condition) " !== " (ls-compile nil)
1477         " ? " (ls-compile true *multiple-value-p*)
1478         " : " (ls-compile false *multiple-value-p*)
1479         ")"))
1480
1481 (defvar *ll-keywords* '(&optional &rest &key))
1482
1483 (defun list-until-keyword (list)
1484   (if (or (null list) (member (car list) *ll-keywords*))
1485       nil
1486       (cons (car list) (list-until-keyword (cdr list)))))
1487
1488 (defun ll-section (keyword ll)
1489   (list-until-keyword (cdr (member keyword ll))))
1490
1491 (defun ll-required-arguments (ll)
1492   (list-until-keyword ll))
1493
1494 (defun ll-optional-arguments-canonical (ll)
1495   (mapcar #'ensure-list (ll-section '&optional ll)))
1496
1497 (defun ll-optional-arguments (ll)
1498   (mapcar #'car (ll-optional-arguments-canonical ll)))
1499
1500 (defun ll-rest-argument (ll)
1501   (let ((rest (ll-section '&rest ll)))
1502     (when (cdr rest)
1503       (error "Bad lambda-list"))
1504     (car rest)))
1505
1506 (defun ll-keyword-arguments-canonical (ll)
1507   (flet ((canonicalize (keyarg)
1508            ;; Build a canonical keyword argument descriptor, filling
1509            ;; the optional fields. The result is a list of the form
1510            ;; ((keyword-name var) init-form).
1511            (let ((arg (ensure-list keyarg)))
1512              (cons (if (listp (car arg))
1513                        (car arg)
1514                        (list (intern (symbol-name (car arg)) "KEYWORD") (car arg)))
1515                    (cdr arg)))))
1516     (mapcar #'canonicalize (ll-section '&key ll))))
1517
1518 (defun ll-keyword-arguments (ll)
1519   (mapcar (lambda (keyarg) (second (first keyarg)))
1520           (ll-keyword-arguments-canonical ll)))
1521
1522 (defun ll-svars (lambda-list)
1523   (let ((args
1524          (append
1525           (ll-keyword-arguments-canonical lambda-list)
1526           (ll-optional-arguments-canonical lambda-list))))
1527     (remove nil (mapcar #'third args))))
1528
1529 (defun lambda-docstring-wrapper (docstring &rest strs)
1530   (if docstring
1531       (js!selfcall
1532         "var func = " (join strs) ";" *newline*
1533         "func.docstring = '" docstring "';" *newline*
1534         "return func;" *newline*)
1535       (apply #'code strs)))
1536
1537 (defun lambda-check-argument-count
1538     (n-required-arguments n-optional-arguments rest-p)
1539   ;; Note: Remember that we assume that the number of arguments of a
1540   ;; call is at least 1 (the values argument).
1541   (let ((min (1+ n-required-arguments))
1542         (max (if rest-p 'n/a (+ 1 n-required-arguments n-optional-arguments))))
1543     (block nil
1544       ;; Special case: a positive exact number of arguments.
1545       (when (and (< 1 min) (eql min max))
1546         (return (code "checkArgs(arguments, " min ");" *newline*)))
1547       ;; General case:
1548       (code
1549        (when (< 1 min)
1550          (code "checkArgsAtLeast(arguments, " min ");" *newline*))
1551        (when (numberp max)
1552          (code "checkArgsAtMost(arguments, " max ");" *newline*))))))
1553
1554 (defun compile-lambda-optional (ll)
1555   (let* ((optional-arguments (ll-optional-arguments-canonical ll))
1556          (n-required-arguments (length (ll-required-arguments ll)))
1557          (n-optional-arguments (length optional-arguments)))
1558     (when optional-arguments
1559       (code (mapconcat (lambda (arg)
1560                          (code "var " (translate-variable (first arg)) "; " *newline*
1561                                (when (third arg)
1562                                  (code "var " (translate-variable (third arg))
1563                                        " = " (ls-compile t)
1564                                        "; " *newline*))))
1565                        optional-arguments)
1566             "switch(arguments.length-1){" *newline*
1567             (let ((cases nil)
1568                   (idx 0))
1569               (progn
1570                 (while (< idx n-optional-arguments)
1571                   (let ((arg (nth idx optional-arguments)))
1572                     (push (code "case " (+ idx n-required-arguments) ":" *newline*
1573                                 (indent (translate-variable (car arg))
1574                                         "="
1575                                         (ls-compile (cadr arg)) ";" *newline*)
1576                                 (when (third arg)
1577                                   (indent (translate-variable (third arg))
1578                                           "="
1579                                           (ls-compile nil)
1580                                           ";" *newline*)))
1581                           cases)
1582                     (incf idx)))
1583                 (push (code "default: break;" *newline*) cases)
1584                 (join (reverse cases))))
1585             "}" *newline*))))
1586
1587 (defun compile-lambda-rest (ll)
1588   (let ((n-required-arguments (length (ll-required-arguments ll)))
1589         (n-optional-arguments (length (ll-optional-arguments ll)))
1590         (rest-argument (ll-rest-argument ll)))
1591     (when rest-argument
1592       (let ((js!rest (translate-variable rest-argument)))
1593         (code "var " js!rest "= " (ls-compile nil) ";" *newline*
1594               "for (var i = arguments.length-1; i>="
1595               (+ 1 n-required-arguments n-optional-arguments)
1596               "; i--)" *newline*
1597               (indent js!rest " = {car: arguments[i], cdr: ") js!rest "};"
1598               *newline*)))))
1599
1600 (defun compile-lambda-parse-keywords (ll)
1601   (let ((n-required-arguments
1602          (length (ll-required-arguments ll)))
1603         (n-optional-arguments
1604          (length (ll-optional-arguments ll)))
1605         (keyword-arguments
1606          (ll-keyword-arguments-canonical ll)))
1607     (code
1608      ;; Declare variables
1609      (mapconcat (lambda (arg)
1610                   (let ((var (second (car arg))))
1611                     (code "var " (translate-variable var) "; " *newline*
1612                           (when (third arg)
1613                             (code "var " (translate-variable (third arg))
1614                                   " = " (ls-compile nil)
1615                                   ";" *newline*)))))
1616                 keyword-arguments)
1617      ;; Parse keywords
1618      (flet ((parse-keyword (keyarg)
1619               ;; ((keyword-name var) init-form)
1620               (code "for (i=" (+ 1 n-required-arguments n-optional-arguments)
1621                     "; i<arguments.length; i+=2){" *newline*
1622                     (indent
1623                      "if (arguments[i] === " (ls-compile (caar keyarg)) "){" *newline*
1624                      (indent (translate-variable (cadr (car keyarg)))
1625                              " = arguments[i+1];"
1626                              *newline*
1627                              (let ((svar (third keyarg)))
1628                                (when svar
1629                                  (code (translate-variable svar) " = " (ls-compile t) ";" *newline*)))
1630                              "break;" *newline*)
1631                      "}" *newline*)
1632                     "}" *newline*
1633                     ;; Default value
1634                     "if (i == arguments.length){" *newline*
1635                     (indent (translate-variable (cadr (car keyarg))) " = " (ls-compile (cadr keyarg)) ";" *newline*)
1636                     "}" *newline*)))
1637        (when keyword-arguments
1638          (code "var i;" *newline*
1639                (mapconcat #'parse-keyword keyword-arguments))))
1640      ;; Check for unknown keywords
1641      (when keyword-arguments
1642        (code "for (i=" (+ 1 n-required-arguments n-optional-arguments)
1643              "; i<arguments.length; i+=2){" *newline*
1644              (indent "if ("
1645                      (join (mapcar (lambda (x)
1646                                      (concat "arguments[i] !== " (ls-compile (caar x))))
1647                                    keyword-arguments)
1648                            " && ")
1649                      ")" *newline*
1650                      (indent
1651                       "throw 'Unknown keyword argument ' + arguments[i].name;" *newline*))
1652              "}" *newline*)))))
1653
1654 (defun compile-lambda (ll body)
1655   (let ((required-arguments (ll-required-arguments ll))
1656         (optional-arguments (ll-optional-arguments ll))
1657         (keyword-arguments  (ll-keyword-arguments  ll))
1658         (rest-argument      (ll-rest-argument      ll))
1659         documentation)
1660     ;; Get the documentation string for the lambda function
1661     (when (and (stringp (car body))
1662                (not (null (cdr body))))
1663       (setq documentation (car body))
1664       (setq body (cdr body)))
1665     (let ((n-required-arguments (length required-arguments))
1666           (n-optional-arguments (length optional-arguments))
1667           (*environment* (extend-local-env
1668                           (append (ensure-list rest-argument)
1669                                   required-arguments
1670                                   optional-arguments
1671                                   keyword-arguments
1672                                   (ll-svars ll)))))
1673       (lambda-docstring-wrapper
1674        documentation
1675        "(function ("
1676        (join (cons "values"
1677                    (mapcar #'translate-variable
1678                            (append required-arguments optional-arguments)))
1679              ",")
1680        "){" *newline*
1681        (indent
1682         ;; Check number of arguments
1683         (lambda-check-argument-count n-required-arguments
1684                                      n-optional-arguments
1685                                      (or rest-argument keyword-arguments))
1686         (compile-lambda-optional ll)
1687         (compile-lambda-rest ll)
1688         (compile-lambda-parse-keywords ll)
1689         (let ((*multiple-value-p* t))
1690           (ls-compile-block body t)))
1691        "})"))))
1692
1693
1694 (defun setq-pair (var val)
1695   (let ((b (lookup-in-lexenv var *environment* 'variable)))
1696     (if (and (binding-p b)
1697              (eq (binding-type b) 'variable)
1698              (not (member 'special (binding-declarations b)))
1699              (not (member 'constant (binding-declarations b))))
1700         (code (binding-value b) " = " (ls-compile val))
1701         (ls-compile `(set ',var ,val)))))
1702
1703
1704 (define-compilation setq (&rest pairs)
1705   (let ((result ""))
1706     (while t
1707       (cond
1708         ((null pairs) (return))
1709         ((null (cdr pairs))
1710          (error "Odd paris in SETQ"))
1711         (t
1712          (concatf result
1713            (concat (setq-pair (car pairs) (cadr pairs))
1714                    (if (null (cddr pairs)) "" ", ")))
1715          (setq pairs (cddr pairs)))))
1716     (code "(" result ")")))
1717
1718
1719 ;;; Literals
1720 (defun escape-string (string)
1721   (let ((output "")
1722         (index 0)
1723         (size (length string)))
1724     (while (< index size)
1725       (let ((ch (char string index)))
1726         (when (or (char= ch #\") (char= ch #\\))
1727           (setq output (concat output "\\")))
1728         (when (or (char= ch #\newline))
1729           (setq output (concat output "\\"))
1730           (setq ch #\n))
1731         (setq output (concat output (string ch))))
1732       (incf index))
1733     output))
1734
1735
1736 (defvar *literal-symbols* nil)
1737 (defvar *literal-counter* 0)
1738
1739 (defun genlit ()
1740   (code "l" (incf *literal-counter*)))
1741
1742 (defun literal (sexp &optional recursive)
1743   (cond
1744     ((integerp sexp) (integer-to-string sexp))
1745     ((stringp sexp) (code "\"" (escape-string sexp) "\""))
1746     ((symbolp sexp)
1747      (or (cdr (assoc sexp *literal-symbols*))
1748          (let ((v (genlit))
1749                (s #+common-lisp
1750                  (let ((package (symbol-package sexp)))
1751                    (if (eq package (find-package "KEYWORD"))
1752                        (code "{name: \"" (escape-string (symbol-name sexp))
1753                              "\", 'package': '" (package-name package) "'}")
1754                        (code "{name: \"" (escape-string (symbol-name sexp)) "\"}")))
1755                  #+ecmalisp
1756                  (let ((package (symbol-package sexp)))
1757                    (if (null package)
1758                        (code "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1759                        (ls-compile `(intern ,(symbol-name sexp) ,(package-name package)))))))
1760            (push (cons sexp v) *literal-symbols*)
1761            (toplevel-compilation (code "var " v " = " s))
1762            v)))
1763     ((consp sexp)
1764      (let* ((head (butlast sexp))
1765             (tail (last sexp))
1766             (c (code "QIList("
1767                      (join-trailing (mapcar (lambda (x) (literal x t)) head) ",")
1768                      (literal (car tail) t)
1769                      ","
1770                      (literal (cdr tail) t)
1771                      ")")))
1772        (if recursive
1773            c
1774            (let ((v (genlit)))
1775              (toplevel-compilation (code "var " v " = " c))
1776              v))))
1777     ((arrayp sexp)
1778      (let ((elements (vector-to-list sexp)))
1779        (let ((c (concat "[" (join (mapcar #'literal elements) ", ") "]")))
1780          (if recursive
1781              c
1782              (let ((v (genlit)))
1783                (toplevel-compilation (code "var " v " = " c))
1784                v)))))))
1785
1786 (define-compilation quote (sexp)
1787   (literal sexp))
1788
1789 (define-compilation %while (pred &rest body)
1790   (js!selfcall
1791     "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1792     (indent (ls-compile-block body))
1793     "}"
1794     "return " (ls-compile nil) ";" *newline*))
1795
1796 (define-compilation function (x)
1797   (cond
1798     ((and (listp x) (eq (car x) 'lambda))
1799      (compile-lambda (cadr x) (cddr x)))
1800     ((symbolp x)
1801      (let ((b (lookup-in-lexenv x *environment* 'function)))
1802        (if b
1803            (binding-value b)
1804            (ls-compile `(symbol-function ',x)))))))
1805
1806
1807 (defun make-function-binding (fname)
1808   (make-binding :name fname :type 'function :value (gvarname fname)))
1809
1810 (defun compile-function-definition (list)
1811   (compile-lambda (car list) (cdr list)))
1812
1813 (defun translate-function (name)
1814   (let ((b (lookup-in-lexenv name *environment* 'function)))
1815     (and b (binding-value b))))
1816
1817 (define-compilation flet (definitions &rest body)
1818   (let* ((fnames (mapcar #'car definitions))
1819          (fbody  (mapcar #'cdr definitions))
1820          (cfuncs (mapcar #'compile-function-definition fbody))
1821          (*environment*
1822           (extend-lexenv (mapcar #'make-function-binding fnames)
1823                          *environment*
1824                          'function)))
1825     (code "(function("
1826           (join (mapcar #'translate-function fnames) ",")
1827           "){" *newline*
1828           (let ((body (ls-compile-block body t)))
1829             (indent body))
1830           "})(" (join cfuncs ",") ")")))
1831
1832 (define-compilation labels (definitions &rest body)
1833   (let* ((fnames (mapcar #'car definitions))
1834          (*environment*
1835           (extend-lexenv (mapcar #'make-function-binding fnames)
1836                          *environment*
1837                          'function)))
1838     (js!selfcall
1839       (mapconcat (lambda (func)
1840                    (code "var " (translate-function (car func))
1841                          " = " (compile-lambda (cadr func) (cddr func))
1842                          ";" *newline*))
1843                  definitions)
1844       (ls-compile-block body t))))
1845
1846
1847 (defvar *compiling-file* nil)
1848 (define-compilation eval-when-compile (&rest body)
1849   (if *compiling-file*
1850       (progn
1851         (eval (cons 'progn body))
1852         nil)
1853       (ls-compile `(progn ,@body))))
1854
1855 (defmacro define-transformation (name args form)
1856   `(define-compilation ,name ,args
1857      (ls-compile ,form)))
1858
1859 (define-compilation progn (&rest body)
1860   (if (null (cdr body))
1861       (ls-compile (car body) *multiple-value-p*)
1862       (js!selfcall (ls-compile-block body t))))
1863
1864 (defun special-variable-p (x)
1865   (and (claimp x 'variable 'special) t))
1866
1867 ;;; Wrap CODE to restore the symbol values of the dynamic
1868 ;;; bindings. BINDINGS is a list of pairs of the form
1869 ;;; (SYMBOL . PLACE),  where PLACE is a Javascript variable
1870 ;;; name to initialize the symbol value and where to stored
1871 ;;; the old value.
1872 (defun let-binding-wrapper (bindings body)
1873   (when (null bindings)
1874     (return-from let-binding-wrapper body))
1875   (code
1876    "try {" *newline*
1877    (indent "var tmp;" *newline*
1878            (mapconcat
1879             (lambda (b)
1880               (let ((s (ls-compile `(quote ,(car b)))))
1881                 (code "tmp = " s ".value;" *newline*
1882                       s ".value = " (cdr b) ";" *newline*
1883                       (cdr b) " = tmp;" *newline*)))
1884             bindings)
1885            body *newline*)
1886    "}" *newline*
1887    "finally {"  *newline*
1888    (indent
1889     (mapconcat (lambda (b)
1890                  (let ((s (ls-compile `(quote ,(car b)))))
1891                    (code s ".value" " = " (cdr b) ";" *newline*)))
1892                bindings))
1893    "}" *newline*))
1894
1895 (define-compilation let (bindings &rest body)
1896   (let* ((bindings (mapcar #'ensure-list bindings))
1897          (variables (mapcar #'first bindings))
1898          (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
1899          (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
1900          (dynamic-bindings))
1901     (code "(function("
1902           (join (mapcar (lambda (x)
1903                           (if (special-variable-p x)
1904                               (let ((v (gvarname x)))
1905                                 (push (cons x v) dynamic-bindings)
1906                                 v)
1907                               (translate-variable x)))
1908                         variables)
1909                 ",")
1910           "){" *newline*
1911           (let ((body (ls-compile-block body t)))
1912             (indent (let-binding-wrapper dynamic-bindings body)))
1913           "})(" (join cvalues ",") ")")))
1914
1915
1916 ;;; Return the code to initialize BINDING, and push it extending the
1917 ;;; current lexical environment if the variable is not special.
1918 (defun let*-initialize-value (binding)
1919   (let ((var (first binding))
1920         (value (second binding)))
1921     (if (special-variable-p var)
1922         (code (ls-compile `(setq ,var ,value)) ";" *newline*)
1923         (let* ((v (gvarname var))
1924                (b (make-binding :name var :type 'variable :value v)))
1925           (prog1 (code "var " v " = " (ls-compile value) ";" *newline*)
1926             (push-to-lexenv b *environment* 'variable))))))
1927
1928 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
1929 ;;; DOES NOT generate code to initialize the value of the symbols,
1930 ;;; unlike let-binding-wrapper.
1931 (defun let*-binding-wrapper (symbols body)
1932   (when (null symbols)
1933     (return-from let*-binding-wrapper body))
1934   (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
1935                        (remove-if-not #'special-variable-p symbols))))
1936     (code
1937      "try {" *newline*
1938      (indent
1939       (mapconcat (lambda (b)
1940                    (let ((s (ls-compile `(quote ,(car b)))))
1941                      (code "var " (cdr b) " = " s ".value;" *newline*)))
1942                  store)
1943       body)
1944      "}" *newline*
1945      "finally {" *newline*
1946      (indent
1947       (mapconcat (lambda (b)
1948                    (let ((s (ls-compile `(quote ,(car b)))))
1949                      (code s ".value" " = " (cdr b) ";" *newline*)))
1950                  store))
1951      "}" *newline*)))
1952
1953 (define-compilation let* (bindings &rest body)
1954   (let ((bindings (mapcar #'ensure-list bindings))
1955         (*environment* (copy-lexenv *environment*)))
1956     (js!selfcall
1957       (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
1958             (body (concat (mapconcat #'let*-initialize-value bindings)
1959                           (ls-compile-block body t))))
1960         (let*-binding-wrapper specials body)))))
1961
1962
1963 (defvar *block-counter* 0)
1964
1965 (define-compilation block (name &rest body)
1966   (let* ((tr (incf *block-counter*))
1967          (b (make-binding :name name :type 'block :value tr)))
1968     (when *multiple-value-p*
1969       (push-binding-declaration 'multiple-value b))
1970     (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
1971            (cbody (ls-compile-block body t)))
1972       (if (member 'used (binding-declarations b))
1973           (js!selfcall
1974             "try {" *newline*
1975             (indent cbody)
1976             "}" *newline*
1977             "catch (cf){" *newline*
1978             "    if (cf.type == 'block' && cf.id == " tr ")" *newline*
1979             (if *multiple-value-p*
1980                 "        return values.apply(this, forcemv(cf.values));"
1981                 "        return cf.values;")
1982             *newline*
1983             "    else" *newline*
1984             "        throw cf;" *newline*
1985             "}" *newline*)
1986           (js!selfcall cbody)))))
1987
1988 (define-compilation return-from (name &optional value)
1989   (let* ((b (lookup-in-lexenv name *environment* 'block))
1990          (multiple-value-p (member 'multiple-value (binding-declarations b))))
1991     (when (null b)
1992       (error (concat "Unknown block `" (symbol-name name) "'.")))
1993     (push-binding-declaration 'used b)
1994     (js!selfcall
1995       (when multiple-value-p (code "var values = mv;" *newline*))
1996       "throw ({"
1997       "type: 'block', "
1998       "id: " (binding-value b) ", "
1999       "values: " (ls-compile value multiple-value-p) ", "
2000       "message: 'Return from unknown block " (symbol-name name) ".'"
2001       "})")))
2002
2003 (define-compilation catch (id &rest body)
2004   (js!selfcall
2005     "var id = " (ls-compile id) ";" *newline*
2006     "try {" *newline*
2007     (indent (ls-compile-block body t)) *newline*
2008     "}" *newline*
2009     "catch (cf){" *newline*
2010     "    if (cf.type == 'catch' && cf.id == id)" *newline*
2011     (if *multiple-value-p*
2012         "        return values.apply(this, forcemv(cf.values));"
2013         "        return pv.apply(this, forcemv(cf.values));")
2014     *newline*
2015     "    else" *newline*
2016     "        throw cf;" *newline*
2017     "}" *newline*))
2018
2019 (define-compilation throw (id value)
2020   (js!selfcall
2021     "var values = mv;" *newline*
2022     "throw ({"
2023     "type: 'catch', "
2024     "id: " (ls-compile id) ", "
2025     "values: " (ls-compile value t) ", "
2026     "message: 'Throw uncatched.'"
2027     "})"))
2028
2029
2030 (defvar *tagbody-counter* 0)
2031 (defvar *go-tag-counter* 0)
2032
2033 (defun go-tag-p (x)
2034   (or (integerp x) (symbolp x)))
2035
2036 (defun declare-tagbody-tags (tbidx body)
2037   (let ((bindings
2038          (mapcar (lambda (label)
2039                    (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
2040                      (make-binding :name label :type 'gotag :value (list tbidx tagidx))))
2041                  (remove-if-not #'go-tag-p body))))
2042     (extend-lexenv bindings *environment* 'gotag)))
2043
2044 (define-compilation tagbody (&rest body)
2045   ;; Ignore the tagbody if it does not contain any go-tag. We do this
2046   ;; because 1) it is easy and 2) many built-in forms expand to a
2047   ;; implicit tagbody, so we save some space.
2048   (unless (some #'go-tag-p body)
2049     (return-from tagbody (ls-compile `(progn ,@body nil))))
2050   ;; The translation assumes the first form in BODY is a label
2051   (unless (go-tag-p (car body))
2052     (push (gensym "START") body))
2053   ;; Tagbody compilation
2054   (let ((tbidx *tagbody-counter*))
2055     (let ((*environment* (declare-tagbody-tags tbidx body))
2056           initag)
2057       (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
2058         (setq initag (second (binding-value b))))
2059       (js!selfcall
2060         "var tagbody_" tbidx " = " initag ";" *newline*
2061         "tbloop:" *newline*
2062         "while (true) {" *newline*
2063         (indent "try {" *newline*
2064                 (indent (let ((content ""))
2065                           (code "switch(tagbody_" tbidx "){" *newline*
2066                                 "case " initag ":" *newline*
2067                                 (dolist (form (cdr body) content)
2068                                   (concatf content
2069                                     (if (not (go-tag-p form))
2070                                         (indent (ls-compile form) ";" *newline*)
2071                                         (let ((b (lookup-in-lexenv form *environment* 'gotag)))
2072                                           (code "case " (second (binding-value b)) ":" *newline*)))))
2073                                 "default:" *newline*
2074                                 "    break tbloop;" *newline*
2075                                 "}" *newline*)))
2076                 "}" *newline*
2077                 "catch (jump) {" *newline*
2078                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
2079                 "        tagbody_" tbidx " = jump.label;" *newline*
2080                 "    else" *newline*
2081                 "        throw(jump);" *newline*
2082                 "}" *newline*)
2083         "}" *newline*
2084         "return " (ls-compile nil) ";" *newline*))))
2085
2086 (define-compilation go (label)
2087   (let ((b (lookup-in-lexenv label *environment* 'gotag))
2088         (n (cond
2089              ((symbolp label) (symbol-name label))
2090              ((integerp label) (integer-to-string label)))))
2091     (when (null b)
2092       (error (concat "Unknown tag `" n "'.")))
2093     (js!selfcall
2094       "throw ({"
2095       "type: 'tagbody', "
2096       "id: " (first (binding-value b)) ", "
2097       "label: " (second (binding-value b)) ", "
2098       "message: 'Attempt to GO to non-existing tag " n "'"
2099       "})" *newline*)))
2100
2101 (define-compilation unwind-protect (form &rest clean-up)
2102   (js!selfcall
2103     "var ret = " (ls-compile nil) ";" *newline*
2104     "try {" *newline*
2105     (indent "ret = " (ls-compile form) ";" *newline*)
2106     "} finally {" *newline*
2107     (indent (ls-compile-block clean-up))
2108     "}" *newline*
2109     "return ret;" *newline*))
2110
2111 (define-compilation multiple-value-call (func-form &rest forms)
2112   (js!selfcall
2113     "var func = " (ls-compile func-form) ";" *newline*
2114     "var args = [" (if *multiple-value-p* "values" "pv") "];" *newline*
2115     "return "
2116     (js!selfcall
2117       "var values = mv;" *newline*
2118       "var vs;" *newline*
2119       (mapconcat (lambda (form)
2120                    (code "vs = " (ls-compile form t) ";" *newline*
2121                          "if (typeof vs === 'object' && 'multiple-value' in vs)" *newline*
2122                          (indent "args = args.concat(vs);" *newline*)
2123                          "else" *newline*
2124                          (indent "args.push(vs);" *newline*)))
2125                  forms)
2126       "return func.apply(window, args);" *newline*) ";" *newline*))
2127
2128 (define-compilation multiple-value-prog1 (first-form &rest forms)
2129   (js!selfcall
2130     "var args = " (ls-compile first-form *multiple-value-p*) ";" *newline*
2131     (ls-compile-block forms)
2132     "return args;" *newline*))
2133
2134
2135 ;;; Javascript FFI
2136
2137 (define-compilation %js-vref (var) var)
2138
2139 (define-compilation %js-vset (var val)
2140   (code "(" var " = " (ls-compile val) ")"))
2141
2142
2143 ;;; Backquote implementation.
2144 ;;;
2145 ;;;    Author: Guy L. Steele Jr.     Date: 27 December 1985
2146 ;;;    Tested under Symbolics Common Lisp and Lucid Common Lisp.
2147 ;;;    This software is in the public domain.
2148
2149 ;;;    The following are unique tokens used during processing.
2150 ;;;    They need not be symbols; they need not even be atoms.
2151 (defvar *comma* 'unquote)
2152 (defvar *comma-atsign* 'unquote-splicing)
2153
2154 (defvar *bq-list* (make-symbol "BQ-LIST"))
2155 (defvar *bq-append* (make-symbol "BQ-APPEND"))
2156 (defvar *bq-list** (make-symbol "BQ-LIST*"))
2157 (defvar *bq-nconc* (make-symbol "BQ-NCONC"))
2158 (defvar *bq-clobberable* (make-symbol "BQ-CLOBBERABLE"))
2159 (defvar *bq-quote* (make-symbol "BQ-QUOTE"))
2160 (defvar *bq-quote-nil* (list *bq-quote* nil))
2161
2162 ;;; BACKQUOTE is an ordinary macro (not a read-macro) that processes
2163 ;;; the expression foo, looking for occurrences of #:COMMA,
2164 ;;; #:COMMA-ATSIGN, and #:COMMA-DOT.  It constructs code in strict
2165 ;;; accordance with the rules on pages 349-350 of the first edition
2166 ;;; (pages 528-529 of this second edition).  It then optionally
2167 ;;; applies a code simplifier.
2168
2169 ;;; If the value of *BQ-SIMPLIFY* is non-NIL, then BACKQUOTE
2170 ;;; processing applies the code simplifier.  If the value is NIL,
2171 ;;; then the code resulting from BACKQUOTE is exactly that
2172 ;;; specified by the official rules.
2173 (defparameter *bq-simplify* t)
2174
2175 (defmacro backquote (x)
2176   (bq-completely-process x))
2177
2178 ;;; Backquote processing proceeds in three stages:
2179 ;;;
2180 ;;; (1) BQ-PROCESS applies the rules to remove occurrences of
2181 ;;; #:COMMA, #:COMMA-ATSIGN, and #:COMMA-DOT corresponding to
2182 ;;; this level of BACKQUOTE.  (It also causes embedded calls to
2183 ;;; BACKQUOTE to be expanded so that nesting is properly handled.)
2184 ;;; Code is produced that is expressed in terms of functions
2185 ;;; #:BQ-LIST, #:BQ-APPEND, and #:BQ-CLOBBERABLE.  This is done
2186 ;;; so that the simplifier will simplify only list construction
2187 ;;; functions actually generated by BACKQUOTE and will not involve
2188 ;;; any user code in the simplification.  #:BQ-LIST means LIST,
2189 ;;; #:BQ-APPEND means APPEND, and #:BQ-CLOBBERABLE means IDENTITY
2190 ;;; but indicates places where "%." was used and where NCONC may
2191 ;;; therefore be introduced by the simplifier for efficiency.
2192 ;;;
2193 ;;; (2) BQ-SIMPLIFY, if used, rewrites the code produced by
2194 ;;; BQ-PROCESS to produce equivalent but faster code.  The
2195 ;;; additional functions #:BQ-LIST* and #:BQ-NCONC may be
2196 ;;; introduced into the code.
2197 ;;;
2198 ;;; (3) BQ-REMOVE-TOKENS goes through the code and replaces
2199 ;;; #:BQ-LIST with LIST, #:BQ-APPEND with APPEND, and so on.
2200 ;;; #:BQ-CLOBBERABLE is simply eliminated (a call to it being
2201 ;;; replaced by its argument).  #:BQ-LIST* is replaced by either
2202 ;;; LIST* or CONS (the latter is used in the two-argument case,
2203 ;;; purely to make the resulting code a tad more readable).
2204
2205 (defun bq-completely-process (x)
2206   (let ((raw-result (bq-process x)))
2207     (bq-remove-tokens (if *bq-simplify*
2208                           (bq-simplify raw-result)
2209                           raw-result))))
2210
2211 (defun bq-process (x)
2212   (cond ((atom x)
2213          (list *bq-quote* x))
2214         ((eq (car x) 'backquote)
2215          (bq-process (bq-completely-process (cadr x))))
2216         ((eq (car x) *comma*) (cadr x))
2217         ((eq (car x) *comma-atsign*)
2218          ;; (error ",@~S after `" (cadr x))
2219          (error "ill-formed"))
2220         ;; ((eq (car x) *comma-dot*)
2221         ;;  ;; (error ",.~S after `" (cadr x))
2222         ;;  (error "ill-formed"))
2223         (t (do ((p x (cdr p))
2224                 (q '() (cons (bracket (car p)) q)))
2225                ((atom p)
2226                 (cons *bq-append*
2227                       (nreconc q (list (list *bq-quote* p)))))
2228              (when (eq (car p) *comma*)
2229                (unless (null (cddr p))
2230                  ;; (error "Malformed ,~S" p)
2231                  (error "Malformed"))
2232                (return (cons *bq-append*
2233                              (nreconc q (list (cadr p))))))
2234              (when (eq (car p) *comma-atsign*)
2235                ;; (error "Dotted ,@~S" p)
2236                (error "Dotted"))
2237              ;; (when (eq (car p) *comma-dot*)
2238              ;;   ;; (error "Dotted ,.~S" p)
2239              ;;   (error "Dotted"))
2240              ))))
2241
2242 ;;; This implements the bracket operator of the formal rules.
2243 (defun bracket (x)
2244   (cond ((atom x)
2245          (list *bq-list* (bq-process x)))
2246         ((eq (car x) *comma*)
2247          (list *bq-list* (cadr x)))
2248         ((eq (car x) *comma-atsign*)
2249          (cadr x))
2250         ;; ((eq (car x) *comma-dot*)
2251         ;;  (list *bq-clobberable* (cadr x)))
2252         (t (list *bq-list* (bq-process x)))))
2253
2254 ;;; This auxiliary function is like MAPCAR but has two extra
2255 ;;; purposes: (1) it handles dotted lists; (2) it tries to make
2256 ;;; the result share with the argument x as much as possible.
2257 (defun maptree (fn x)
2258   (if (atom x)
2259       (funcall fn x)
2260       (let ((a (funcall fn (car x)))
2261             (d (maptree fn (cdr x))))
2262         (if (and (eql a (car x)) (eql d (cdr x)))
2263             x
2264             (cons a d)))))
2265
2266 ;;; This predicate is true of a form that when read looked
2267 ;;; like %@foo or %.foo.
2268 (defun bq-splicing-frob (x)
2269   (and (consp x)
2270        (or (eq (car x) *comma-atsign*)
2271            ;; (eq (car x) *comma-dot*)
2272            )))
2273
2274 ;;; This predicate is true of a form that when read
2275 ;;; looked like %@foo or %.foo or just plain %foo.
2276 (defun bq-frob (x)
2277   (and (consp x)
2278        (or (eq (car x) *comma*)
2279            (eq (car x) *comma-atsign*)
2280            ;; (eq (car x) *comma-dot*)
2281            )))
2282
2283 ;;; The simplifier essentially looks for calls to #:BQ-APPEND and
2284 ;;; tries to simplify them.  The arguments to #:BQ-APPEND are
2285 ;;; processed from right to left, building up a replacement form.
2286 ;;; At each step a number of special cases are handled that,
2287 ;;; loosely speaking, look like this:
2288 ;;;
2289 ;;;  (APPEND (LIST a b c) foo) => (LIST* a b c foo)
2290 ;;;       provided a, b, c are not splicing frobs
2291 ;;;  (APPEND (LIST* a b c) foo) => (LIST* a b (APPEND c foo))
2292 ;;;       provided a, b, c are not splicing frobs
2293 ;;;  (APPEND (QUOTE (x)) foo) => (LIST* (QUOTE x) foo)
2294 ;;;  (APPEND (CLOBBERABLE x) foo) => (NCONC x foo)
2295 (defun bq-simplify (x)
2296   (if (atom x)
2297       x
2298       (let ((x (if (eq (car x) *bq-quote*)
2299                    x
2300                    (maptree #'bq-simplify x))))
2301         (if (not (eq (car x) *bq-append*))
2302             x
2303             (bq-simplify-args x)))))
2304
2305 (defun bq-simplify-args (x)
2306   (do ((args (reverse (cdr x)) (cdr args))
2307        (result
2308          nil
2309          (cond ((atom (car args))
2310                 (bq-attach-append *bq-append* (car args) result))
2311                ((and (eq (caar args) *bq-list*)
2312                      (notany #'bq-splicing-frob (cdar args)))
2313                 (bq-attach-conses (cdar args) result))
2314                ((and (eq (caar args) *bq-list**)
2315                      (notany #'bq-splicing-frob (cdar args)))
2316                 (bq-attach-conses
2317                   (reverse (cdr (reverse (cdar args))))
2318                   (bq-attach-append *bq-append*
2319                                     (car (last (car args)))
2320                                     result)))
2321                ((and (eq (caar args) *bq-quote*)
2322                      (consp (cadar args))
2323                      (not (bq-frob (cadar args)))
2324                      (null (cddar args)))
2325                 (bq-attach-conses (list (list *bq-quote*
2326                                               (caadar args)))
2327                                   result))
2328                ((eq (caar args) *bq-clobberable*)
2329                 (bq-attach-append *bq-nconc* (cadar args) result))
2330                (t (bq-attach-append *bq-append*
2331                                     (car args)
2332                                     result)))))
2333       ((null args) result)))
2334
2335 (defun null-or-quoted (x)
2336   (or (null x) (and (consp x) (eq (car x) *bq-quote*))))
2337
2338 ;;; When BQ-ATTACH-APPEND is called, the OP should be #:BQ-APPEND
2339 ;;; or #:BQ-NCONC.  This produces a form (op item result) but
2340 ;;; some simplifications are done on the fly:
2341 ;;;
2342 ;;;  (op '(a b c) '(d e f g)) => '(a b c d e f g)
2343 ;;;  (op item 'nil) => item, provided item is not a splicable frob
2344 ;;;  (op item 'nil) => (op item), if item is a splicable frob
2345 ;;;  (op item (op a b c)) => (op item a b c)
2346 (defun bq-attach-append (op item result)
2347   (cond ((and (null-or-quoted item) (null-or-quoted result))
2348          (list *bq-quote* (append (cadr item) (cadr result))))
2349         ((or (null result) (equal result *bq-quote-nil*))
2350          (if (bq-splicing-frob item) (list op item) item))
2351         ((and (consp result) (eq (car result) op))
2352          (list* (car result) item (cdr result)))
2353         (t (list op item result))))
2354
2355 ;;; The effect of BQ-ATTACH-CONSES is to produce a form as if by
2356 ;;; `(LIST* ,@items ,result) but some simplifications are done
2357 ;;; on the fly.
2358 ;;;
2359 ;;;  (LIST* 'a 'b 'c 'd) => '(a b c . d)
2360 ;;;  (LIST* a b c 'nil) => (LIST a b c)
2361 ;;;  (LIST* a b c (LIST* d e f g)) => (LIST* a b c d e f g)
2362 ;;;  (LIST* a b c (LIST d e f g)) => (LIST a b c d e f g)
2363 (defun bq-attach-conses (items result)
2364   (cond ((and (every #'null-or-quoted items)
2365               (null-or-quoted result))
2366          (list *bq-quote*
2367                (append (mapcar #'cadr items) (cadr result))))
2368         ((or (null result) (equal result *bq-quote-nil*))
2369          (cons *bq-list* items))
2370         ((and (consp result)
2371               (or (eq (car result) *bq-list*)
2372                   (eq (car result) *bq-list**)))
2373          (cons (car result) (append items (cdr result))))
2374         (t (cons *bq-list** (append items (list result))))))
2375
2376 ;;; Removes funny tokens and changes (#:BQ-LIST* a b) into
2377 ;;; (CONS a b) instead of (LIST* a b), purely for readability.
2378 (defun bq-remove-tokens (x)
2379   (cond ((eq x *bq-list*) 'list)
2380         ((eq x *bq-append*) 'append)
2381         ((eq x *bq-nconc*) 'nconc)
2382         ((eq x *bq-list**) 'list*)
2383         ((eq x *bq-quote*) 'quote)
2384         ((atom x) x)
2385         ((eq (car x) *bq-clobberable*)
2386          (bq-remove-tokens (cadr x)))
2387         ((and (eq (car x) *bq-list**)
2388               (consp (cddr x))
2389               (null (cdddr x)))
2390          (cons 'cons (maptree #'bq-remove-tokens (cdr x))))
2391         (t (maptree #'bq-remove-tokens x))))
2392
2393 (define-transformation backquote (form)
2394   (bq-completely-process form))
2395
2396
2397 ;;; Primitives
2398
2399 (defvar *builtins* nil)
2400
2401 (defmacro define-raw-builtin (name args &body body)
2402   ;; Creates a new primitive function `name' with parameters args and
2403   ;; @body. The body can access to the local environment through the
2404   ;; variable *ENVIRONMENT*.
2405   `(push (list ',name (lambda ,args (block ,name ,@body)))
2406          *builtins*))
2407
2408 (defmacro define-builtin (name args &body body)
2409   `(define-raw-builtin ,name ,args
2410      (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
2411        ,@body)))
2412
2413 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
2414 (defmacro type-check (decls &body body)
2415   `(js!selfcall
2416      ,@(mapcar (lambda (decl)
2417                  `(code "var " ,(first decl) " = " ,(third decl) ";" *newline*))
2418                decls)
2419      ,@(mapcar (lambda (decl)
2420                  `(code "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
2421                         (indent "throw 'The value ' + "
2422                                 ,(first decl)
2423                                 " + ' is not a type "
2424                                 ,(second decl)
2425                                 ".';"
2426                                 *newline*)))
2427                decls)
2428      (code "return " (progn ,@body) ";" *newline*)))
2429
2430 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
2431 ;;; a variable which holds a list of forms. It will compile them and
2432 ;;; store the result in some Javascript variables. BODY is evaluated
2433 ;;; with ARGS bound to the list of these variables to generate the
2434 ;;; code which performs the transformation on these variables.
2435
2436 (defun variable-arity-call (args function)
2437   (unless (consp args)
2438     (error "ARGS must be a non-empty list"))
2439   (let ((counter 0)
2440         (fargs '())
2441         (prelude ""))
2442     (dolist (x args)
2443       (if (numberp x)
2444           (push (integer-to-string x) fargs)
2445           (let ((v (code "x" (incf counter))))
2446             (push v fargs)
2447             (concatf prelude
2448               (code "var " v " = " (ls-compile x) ";" *newline*
2449                     "if (typeof " v " !== 'number') throw 'Not a number!';"
2450                     *newline*)))))
2451     (js!selfcall prelude (funcall function (reverse fargs)))))
2452
2453
2454 (defmacro variable-arity (args &body body)
2455   (unless (symbolp args)
2456     (error "Bad usage of VARIABLE-ARITY, you must pass a symbol"))
2457   `(variable-arity-call ,args
2458                         (lambda (,args)
2459                           (code "return " ,@body ";" *newline*))))
2460
2461 (defun num-op-num (x op y)
2462   (type-check (("x" "number" x) ("y" "number" y))
2463     (code "x" op "y")))
2464
2465 (define-raw-builtin + (&rest numbers)
2466   (if (null numbers)
2467       "0"
2468       (variable-arity numbers
2469         (join numbers "+"))))
2470
2471 (define-raw-builtin - (x &rest others)
2472   (let ((args (cons x others)))
2473     (variable-arity args
2474       (if (null others)
2475           (concat "-" (car args))
2476           (join args "-")))))
2477
2478 (define-raw-builtin * (&rest numbers)
2479   (if (null numbers)
2480       "1"
2481       (variable-arity numbers
2482         (join numbers "*"))))
2483
2484 (define-raw-builtin / (x &rest others)
2485   (let ((args (cons x others)))
2486     (variable-arity args
2487       (if (null others)
2488           (concat "1 /" (car args))
2489           (join args "/")))))
2490
2491 (define-builtin mod (x y) (num-op-num x "%" y))
2492
2493
2494 (defun comparison-conjuntion (vars op)
2495   (cond
2496     ((null (cdr vars))
2497      "true")
2498     ((null (cddr vars))
2499      (concat (car vars) op (cadr vars)))
2500     (t
2501      (concat (car vars) op (cadr vars)
2502              " && "
2503              (comparison-conjuntion (cdr vars) op)))))
2504
2505 (defmacro define-builtin-comparison (op sym)
2506   `(define-raw-builtin ,op (x &rest args)
2507      (let ((args (cons x args)))
2508        (variable-arity args
2509          (js!bool (comparison-conjuntion args ,sym))))))
2510
2511 (define-builtin-comparison > ">")
2512 (define-builtin-comparison < "<")
2513 (define-builtin-comparison >= ">=")
2514 (define-builtin-comparison <= "<=")
2515 (define-builtin-comparison = "==")
2516
2517 (define-builtin numberp (x)
2518   (js!bool (code "(typeof (" x ") == \"number\")")))
2519
2520 (define-builtin floor (x)
2521   (type-check (("x" "number" x))
2522     "Math.floor(x)"))
2523
2524 (define-builtin cons (x y)
2525   (code "({car: " x ", cdr: " y "})"))
2526
2527 (define-builtin consp (x)
2528   (js!bool
2529    (js!selfcall
2530      "var tmp = " x ";" *newline*
2531      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
2532
2533 (define-builtin car (x)
2534   (js!selfcall
2535     "var tmp = " x ";" *newline*
2536     "return tmp === " (ls-compile nil)
2537     "? " (ls-compile nil)
2538     ": tmp.car;" *newline*))
2539
2540 (define-builtin cdr (x)
2541   (js!selfcall
2542     "var tmp = " x ";" *newline*
2543     "return tmp === " (ls-compile nil) "? "
2544     (ls-compile nil)
2545     ": tmp.cdr;" *newline*))
2546
2547 (define-builtin rplaca (x new)
2548   (type-check (("x" "object" x))
2549     (code "(x.car = " new ", x)")))
2550
2551 (define-builtin rplacd (x new)
2552   (type-check (("x" "object" x))
2553     (code "(x.cdr = " new ", x)")))
2554
2555 (define-builtin symbolp (x)
2556   (js!bool
2557    (js!selfcall
2558      "var tmp = " x ";" *newline*
2559      "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
2560
2561 (define-builtin make-symbol (name)
2562   (type-check (("name" "string" name))
2563     "({name: name})"))
2564
2565 (define-builtin symbol-name (x)
2566   (code "(" x ").name"))
2567
2568 (define-builtin set (symbol value)
2569   (code "(" symbol ").value = " value))
2570
2571 (define-builtin fset (symbol value)
2572   (code "(" symbol ").fvalue = " value))
2573
2574 (define-builtin boundp (x)
2575   (js!bool (code "(" x ".value !== undefined)")))
2576
2577 (define-builtin symbol-value (x)
2578   (js!selfcall
2579     "var symbol = " x ";" *newline*
2580     "var value = symbol.value;" *newline*
2581     "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
2582     "return value;" *newline*))
2583
2584 (define-builtin symbol-function (x)
2585   (js!selfcall
2586     "var symbol = " x ";" *newline*
2587     "var func = symbol.fvalue;" *newline*
2588     "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
2589     "return func;" *newline*))
2590
2591 (define-builtin symbol-plist (x)
2592   (code "((" x ").plist || " (ls-compile nil) ")"))
2593
2594 (define-builtin lambda-code (x)
2595   (code "(" x ").toString()"))
2596
2597 (define-builtin eq    (x y) (js!bool (code "(" x " === " y ")")))
2598 (define-builtin equal (x y) (js!bool (code "(" x  " == " y ")")))
2599
2600 (define-builtin char-to-string (x)
2601   (type-check (("x" "number" x))
2602     "String.fromCharCode(x)"))
2603
2604 (define-builtin stringp (x)
2605   (js!bool (code "(typeof(" x ") == \"string\")")))
2606
2607 (define-builtin string-upcase (x)
2608   (type-check (("x" "string" x))
2609     "x.toUpperCase()"))
2610
2611 (define-builtin string-length (x)
2612   (type-check (("x" "string" x))
2613     "x.length"))
2614
2615 (define-raw-builtin slice (string a &optional b)
2616   (js!selfcall
2617     "var str = " (ls-compile string) ";" *newline*
2618     "var a = " (ls-compile a) ";" *newline*
2619     "var b;" *newline*
2620     (when b (code "b = " (ls-compile b) ";" *newline*))
2621     "return str.slice(a,b);" *newline*))
2622
2623 (define-builtin char (string index)
2624   (type-check (("string" "string" string)
2625                ("index" "number" index))
2626     "string.charCodeAt(index)"))
2627
2628 (define-builtin concat-two (string1 string2)
2629   (type-check (("string1" "string" string1)
2630                ("string2" "string" string2))
2631     "string1.concat(string2)"))
2632
2633 (define-raw-builtin funcall (func &rest args)
2634   (js!selfcall
2635     "var f = " (ls-compile func) ";" *newline*
2636     "return (typeof f === 'function'? f: f.fvalue)("
2637     (join (cons (if *multiple-value-p* "values" "pv")
2638                 (mapcar #'ls-compile args))
2639           ", ")
2640     ")"))
2641
2642 (define-raw-builtin apply (func &rest args)
2643   (if (null args)
2644       (code "(" (ls-compile func) ")()")
2645       (let ((args (butlast args))
2646             (last (car (last args))))
2647         (js!selfcall
2648           "var f = " (ls-compile func) ";" *newline*
2649           "var args = [" (join (cons (if *multiple-value-p* "values" "pv")
2650                                      (mapcar #'ls-compile args))
2651                                ", ")
2652           "];" *newline*
2653           "var tail = (" (ls-compile last) ");" *newline*
2654           "while (tail != " (ls-compile nil) "){" *newline*
2655           "    args.push(tail.car);" *newline*
2656           "    tail = tail.cdr;" *newline*
2657           "}" *newline*
2658           "return (typeof f === 'function'? f : f.fvalue).apply(this, args);" *newline*))))
2659
2660 (define-builtin js-eval (string)
2661   (type-check (("string" "string" string))
2662     (if *multiple-value-p*
2663         (js!selfcall
2664           "var v = eval.apply(window, [string]);" *newline*
2665           "if (typeof v !== 'object' || !('multiple-value' in v)){" *newline*
2666           (indent "v = [v];" *newline*
2667                   "v['multiple-value'] = true;" *newline*)
2668           "}" *newline*
2669           "return values.apply(this, v);" *newline*)
2670         "eval.apply(window, [string])")))
2671
2672 (define-builtin error (string)
2673   (js!selfcall "throw " string ";" *newline*))
2674
2675 (define-builtin new () "{}")
2676
2677 (define-builtin objectp (x)
2678   (js!bool (code "(typeof (" x ") === 'object')")))
2679
2680 (define-builtin oget (object key)
2681   (js!selfcall
2682     "var tmp = " "(" object ")[" key "];" *newline*
2683     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
2684
2685 (define-builtin oset (object key value)
2686   (code "((" object ")[" key "] = " value ")"))
2687
2688 (define-builtin in (key object)
2689   (js!bool (code "((" key ") in (" object "))")))
2690
2691 (define-builtin functionp (x)
2692   (js!bool (code "(typeof " x " == 'function')")))
2693
2694 (define-builtin write-string (x)
2695   (type-check (("x" "string" x))
2696     "lisp.write(x)"))
2697
2698 (define-builtin make-array (n)
2699   (js!selfcall
2700     "var r = [];" *newline*
2701     "for (var i = 0; i < " n "; i++)" *newline*
2702     (indent "r.push(" (ls-compile nil) ");" *newline*)
2703     "return r;" *newline*))
2704
2705 (define-builtin arrayp (x)
2706   (js!bool
2707    (js!selfcall
2708      "var x = " x ";" *newline*
2709      "return typeof x === 'object' && 'length' in x;")))
2710
2711 (define-builtin aref (array n)
2712   (js!selfcall
2713     "var x = " "(" array ")[" n "];" *newline*
2714     "if (x === undefined) throw 'Out of range';" *newline*
2715     "return x;" *newline*))
2716
2717 (define-builtin aset (array n value)
2718   (js!selfcall
2719     "var x = " array ";" *newline*
2720     "var i = " n ";" *newline*
2721     "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
2722     "return x[i] = " value ";" *newline*))
2723
2724 (define-builtin get-unix-time ()
2725   (code "(Math.round(new Date() / 1000))"))
2726
2727 (define-builtin values-array (array)
2728   (if *multiple-value-p*
2729       (code "values.apply(this, " array ")")
2730       (code "pv.apply(this, " array ")")))
2731
2732 (define-raw-builtin values (&rest args)
2733   (if *multiple-value-p*
2734       (code "values(" (join (mapcar #'ls-compile args) ", ") ")")
2735       (code "pv(" (join (mapcar #'ls-compile args) ", ") ")")))
2736
2737 ;; Receives the JS function as first argument as a literal string. The
2738 ;; second argument is compiled and should evaluate to a vector of
2739 ;; values to apply to the the function. The result returned.
2740 (define-builtin %js-call (fun args)
2741   (code fun ".apply(this, " args ")"))
2742
2743 (defun macro (x)
2744   (and (symbolp x)
2745        (let ((b (lookup-in-lexenv x *environment* 'function)))
2746          (if (and b (eq (binding-type b) 'macro))
2747              b
2748              nil))))
2749
2750 (defun ls-macroexpand-1 (form)
2751   (let ((macro-binding (macro (car form))))
2752     (if macro-binding
2753         (let ((expander (binding-value macro-binding)))
2754           (when (listp expander)
2755             (let ((compiled (eval expander)))
2756               ;; The list representation are useful while
2757               ;; bootstrapping, as we can dump the definition of the
2758               ;; macros easily, but they are slow because we have to
2759               ;; evaluate them and compile them now and again. So, let
2760               ;; us replace the list representation version of the
2761               ;; function with the compiled one.
2762               ;;
2763               #+ecmalisp (set-binding-value macro-binding compiled)
2764               (setq expander compiled)))
2765           (apply expander (cdr form)))
2766         form)))
2767
2768 (defun compile-funcall (function args)
2769   (let* ((values-funcs (if *multiple-value-p* "values" "pv"))
2770          (arglist (concat "(" (join (cons values-funcs (mapcar #'ls-compile args)) ", ") ")")))
2771     (cond
2772       ((translate-function function)
2773        (concat (translate-function function) arglist))
2774       ((and (symbolp function)
2775             #+ecmalisp (eq (symbol-package function) (find-package "COMMON-LISP"))
2776             #+common-lisp t)
2777        (code (ls-compile `',function) ".fvalue" arglist))
2778       (t
2779        (code (ls-compile `#',function) arglist)))))
2780
2781 (defun ls-compile-block (sexps &optional return-last-p)
2782   (if return-last-p
2783       (code (ls-compile-block (butlast sexps))
2784             "return " (ls-compile (car (last sexps)) *multiple-value-p*) ";")
2785       (join-trailing
2786        (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
2787        (concat ";" *newline*))))
2788
2789 (defun ls-compile (sexp &optional multiple-value-p)
2790   (let ((*multiple-value-p* multiple-value-p))
2791     (cond
2792       ((symbolp sexp)
2793        (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
2794          (cond
2795            ((and b (not (member 'special (binding-declarations b))))
2796             (binding-value b))
2797            ((or (keywordp sexp)
2798                 (and b (member 'constant (binding-declarations b))))
2799             (code (ls-compile `',sexp) ".value"))
2800            (t
2801             (ls-compile `(symbol-value ',sexp))))))
2802       ((integerp sexp) (integer-to-string sexp))
2803       ((stringp sexp) (code "\"" (escape-string sexp) "\""))
2804       ((arrayp sexp) (literal sexp))
2805       ((listp sexp)
2806        (let ((name (car sexp))
2807              (args (cdr sexp)))
2808          (cond
2809            ;; Special forms
2810            ((assoc name *compilations*)
2811             (let ((comp (second (assoc name *compilations*))))
2812               (apply comp args)))
2813            ;; Built-in functions
2814            ((and (assoc name *builtins*)
2815                  (not (claimp name 'function 'notinline)))
2816             (let ((comp (second (assoc name *builtins*))))
2817               (apply comp args)))
2818            (t
2819             (if (macro name)
2820                 (ls-compile (ls-macroexpand-1 sexp) multiple-value-p)
2821                 (compile-funcall name args))))))
2822       (t
2823        (error (concat "How should I compile " (prin1-to-string sexp) "?"))))))
2824
2825
2826 (defvar *compile-print-toplevels* nil)
2827
2828 (defun truncate-string (string &optional (width 60))
2829   (let ((n (or (position #\newline string)
2830                (min width (length string)))))
2831     (subseq string 0 n)))
2832
2833 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
2834   (let ((*toplevel-compilations* nil))
2835     (cond
2836       ((and (consp sexp) (eq (car sexp) 'progn))
2837        (let ((subs (mapcar (lambda (s)
2838                              (ls-compile-toplevel s t))
2839                            (cdr sexp))))
2840          (join (remove-if #'null-or-empty-p subs))))
2841       (t
2842        (when *compile-print-toplevels*
2843          (let ((form-string (prin1-to-string sexp)))
2844            (write-string "Compiling ")
2845            (write-string (truncate-string form-string))
2846            (write-line "...")))
2847
2848        (let ((code (ls-compile sexp multiple-value-p)))
2849          (code (join-trailing (get-toplevel-compilations)
2850                               (code ";" *newline*))
2851                (when code
2852                  (code code ";" *newline*))))))))
2853
2854
2855 ;;; Once we have the compiler, we define the runtime environment and
2856 ;;; interactive development (eval), which works calling the compiler
2857 ;;; and evaluating the Javascript result globally.
2858
2859 #+ecmalisp
2860 (progn
2861   (defun eval (x)
2862     (js-eval (ls-compile-toplevel x t)))
2863
2864   (export '(&rest &key &optional &body * *gensym-counter* *package* + - / 1+ 1- <
2865             <= = = > >= and append apply aref arrayp assoc atom block boundp
2866             boundp butlast caar cadddr caddr cadr car car case catch cdar cdddr
2867             cddr cdr cdr char char-code fdefinition find-package find-symbol first
2868             flet fourth fset funcall function functionp gensym get-setf-expansion
2869             get-universal-time go identity if in-package incf integerp integerp
2870             intern keywordp labels lambda last length let let* char= code-char
2871             cond cons consp constantly copy-list decf declaim define-setf-expander
2872             defconstant defparameter defun defmacro defvar digit-char digit-char-p
2873             disassemble do do* documentation dolist dotimes ecase eq eql equal
2874             error eval every export list-all-packages list list* listp loop make-array
2875             make-package make-symbol mapcar member minusp mod multiple-value-bind
2876             multiple-value-call multiple-value-list multiple-value-prog1 nconc nil not
2877             nth nthcdr null numberp or package-name package-use-list packagep
2878             parse-integer plusp prin1-to-string print proclaim prog1 prog2 progn
2879             psetq push quote nreconc remove remove-if remove-if-not return return-from
2880             revappend reverse rplaca rplacd second set setf setq some
2881             string-upcase string string= stringp subseq symbol-function
2882             symbol-name symbol-package symbol-plist symbol-value symbolp t tagbody
2883             third throw truncate unless unwind-protect values values-list variable
2884             warn when write-line write-string zerop))
2885
2886   (setq *package* *user-package*)
2887
2888   (js-eval "var lisp")
2889   (%js-vset "lisp" (new))
2890   (%js-vset "lisp.read" #'ls-read-from-string)
2891   (%js-vset "lisp.print" #'prin1-to-string)
2892   (%js-vset "lisp.eval" #'eval)
2893   (%js-vset "lisp.compile" (lambda (s) (ls-compile-toplevel s t)))
2894   (%js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
2895   (%js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str) t)))
2896
2897   ;; Set the initial global environment to be equal to the host global
2898   ;; environment at this point of the compilation.
2899   (eval-when-compile
2900     (toplevel-compilation
2901      (ls-compile `(setq *environment* ',*environment*))))
2902
2903   (eval-when-compile
2904     (toplevel-compilation
2905      (ls-compile
2906       `(progn
2907          ,@(mapcar (lambda (s) `(%intern-symbol (%js-vref ,(cdr s))))
2908                    *literal-symbols*)
2909          (setq *literal-symbols* ',*literal-symbols*)
2910          (setq *variable-counter* ,*variable-counter*)
2911          (setq *gensym-counter* ,*gensym-counter*)
2912          (setq *block-counter* ,*block-counter*)))))
2913
2914   (eval-when-compile
2915     (toplevel-compilation
2916      (ls-compile
2917       `(setq *literal-counter* ,*literal-counter*)))))
2918
2919
2920 ;;; Finally, we provide a couple of functions to easily bootstrap
2921 ;;; this. It just calls the compiler with this file as input.
2922
2923 #+common-lisp
2924 (progn
2925   (defun read-whole-file (filename)
2926     (with-open-file (in filename)
2927       (let ((seq (make-array (file-length in) :element-type 'character)))
2928         (read-sequence seq in)
2929         seq)))
2930
2931   (defun ls-compile-file (filename output &key print)
2932     (let ((*compiling-file* t)
2933           (*compile-print-toplevels* print))
2934       (with-open-file (out output :direction :output :if-exists :supersede)
2935         (write-string (read-whole-file "prelude.js") out)
2936         (let* ((source (read-whole-file filename))
2937                (in (make-string-stream source)))
2938           (loop
2939              for x = (ls-read in)
2940              until (eq x *eof*)
2941              for compilation = (ls-compile-toplevel x)
2942              when (plusp (length compilation))
2943              do (write-string compilation out))))))
2944
2945   (defun bootstrap ()
2946     (setq *environment* (make-lexenv))
2947     (setq *literal-symbols* nil)
2948     (setq *variable-counter* 0
2949           *gensym-counter* 0
2950           *literal-counter* 0
2951           *block-counter* 0)
2952     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js" :print t)))