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