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