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