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