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