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