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