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