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