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