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