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