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