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