de2fe683cda20cb449e317daaeb1366b6f0b985d
[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   (defun aset (array idx value)
605     (setf (aref array idx) value)))
606
607 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
608 ;;; from here, this code will compile on both. We define some helper
609 ;;; functions now for string manipulation and so on. They will be
610 ;;; useful in the compiler, mostly.
611
612 (defvar *newline* (string (code-char 10)))
613
614 (defun concat (&rest strs)
615   (!reduce #'concat-two strs ""))
616
617 (defmacro concatf (variable &body form)
618   `(setq ,variable (concat ,variable (progn ,@form))))
619
620 ;;; Concatenate a list of strings, with a separator
621 (defun join (list &optional (separator ""))
622   (cond
623     ((null list)
624      "")
625     ((null (cdr list))
626      (car list))
627     (t
628      (concat (car list)
629              separator
630              (join (cdr list) separator)))))
631
632 (defun join-trailing (list &optional (separator ""))
633   (if (null list)
634       ""
635       (concat (car list) separator (join-trailing (cdr list) separator))))
636
637 (defun mapconcat (func list)
638   (join (mapcar func list)))
639
640 (defun vector-to-list (vector)
641   (let ((list nil)
642         (size (length vector)))
643     (dotimes (i size (reverse list))
644       (push (aref vector i) list))))
645
646 (defun list-to-vector (list)
647   (let ((v (make-array (length list)))
648         (i 0))
649     (dolist (x list v)
650       (aset v i x)
651       (incf i))))
652
653 ;;; Like CONCAT, but prefix each line with four spaces. Two versions
654 ;;; of this function are available, because the Ecmalisp version is
655 ;;; very slow and bootstraping was annoying.
656
657 #+ecmalisp
658 (defun indent (&rest string)
659   (let ((input (join string)))
660     (let ((output "")
661           (index 0)
662           (size (length input)))
663       (when (plusp (length input)) (concatf output "    "))
664       (while (< index size)
665         (let ((str
666                (if (and (char= (char input index) #\newline)
667                         (< index (1- size))
668                         (not (char= (char input (1+ index)) #\newline)))
669                    (concat (string #\newline) "    ")
670                    (string (char input index)))))
671           (concatf output str))
672         (incf index))
673       output)))
674
675 #+common-lisp
676 (defun indent (&rest string)
677   (with-output-to-string (*standard-output*)
678     (with-input-from-string (input (join string))
679       (loop
680          for line = (read-line input nil)
681          while line
682          do (write-string "    ")
683          do (write-line line)))))
684
685
686 (defun integer-to-string (x)
687   (cond
688     ((zerop x)
689      "0")
690     ((minusp x)
691      (concat "-" (integer-to-string (- 0 x))))
692     (t
693      (let ((digits nil))
694        (while (not (zerop x))
695          (push (mod x 10) digits)
696          (setq x (truncate x 10)))
697        (join (mapcar (lambda (d) (string (char "0123456789" d)))
698                      digits))))))
699
700
701 ;;; Wrap X with a Javascript code to convert the result from
702 ;;; Javascript generalized booleans to T or NIL.
703 (defun js!bool (x)
704   (concat "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
705
706 ;;; Concatenate the arguments and wrap them with a self-calling
707 ;;; Javascript anonymous function. It is used to make some Javascript
708 ;;; statements valid expressions and provide a private scope as well.
709 ;;; It could be defined as function, but we could do some
710 ;;; preprocessing in the future.
711 (defmacro js!selfcall (&body body)
712   `(concat "(function(){" *newline* (indent ,@body) "})()"))
713
714
715 ;;; Printer
716
717 #+ecmalisp
718 (progn
719   (defun prin1-to-string (form)
720     (cond
721       ((symbolp form)
722        (if (cdr (%find-symbol (symbol-name form) *package*))
723            (symbol-name form)
724            (let ((package (symbol-package form))
725                  (name (symbol-name form)))
726              (concat (if (eq package (find-package "KEYWORD"))
727                          ""
728                          (package-name package))
729                      ":" name))))
730       ((integerp form) (integer-to-string form))
731       ((stringp form) (concat "\"" (escape-string form) "\""))
732       ((functionp form)
733        (let ((name (oget form "fname")))
734          (if name
735              (concat "#<FUNCTION " name ">")
736              (concat "#<FUNCTION>"))))
737       ((listp form)
738        (concat "("
739                (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
740                (let ((last (last form)))
741                  (if (null (cdr last))
742                      (prin1-to-string (car last))
743                      (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
744                ")"))
745       ((arrayp form)
746        (concat "#" (prin1-to-string (vector-to-list form))))
747       ((packagep form)
748        (concat "#<PACKAGE " (package-name form) ">"))))
749
750   (defun write-line (x)
751     (write-string x)
752     (write-string *newline*)
753     x)
754
755   (defun warn (string)
756     (write-string "WARNING: ")
757     (write-line string))
758
759   (defun print (x)
760     (write-line (prin1-to-string x))
761     x))
762
763
764 ;;;; Reader
765
766 ;;; The Lisp reader, parse strings and return Lisp objects. The main
767 ;;; entry points are `ls-read' and `ls-read-from-string'.
768
769 (defun make-string-stream (string)
770   (cons string 0))
771
772 (defun %peek-char (stream)
773   (and (< (cdr stream) (length (car stream)))
774        (char (car stream) (cdr stream))))
775
776 (defun %read-char (stream)
777   (and (< (cdr stream) (length (car stream)))
778        (prog1 (char (car stream) (cdr stream))
779          (setcdr stream (1+ (cdr stream))))))
780
781 (defun whitespacep (ch)
782   (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
783
784 (defun skip-whitespaces (stream)
785   (let (ch)
786     (setq ch (%peek-char stream))
787     (while (and ch (whitespacep ch))
788       (%read-char stream)
789       (setq ch (%peek-char stream)))))
790
791 (defun terminalp (ch)
792   (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
793
794 (defun read-until (stream func)
795   (let ((string "")
796         (ch))
797     (setq ch (%peek-char stream))
798     (while (and ch (not (funcall func ch)))
799       (setq string (concat string (string ch)))
800       (%read-char stream)
801       (setq ch (%peek-char stream)))
802     string))
803
804 (defun skip-whitespaces-and-comments (stream)
805   (let (ch)
806     (skip-whitespaces stream)
807     (setq ch (%peek-char stream))
808     (while (and ch (char= ch #\;))
809       (read-until stream (lambda (x) (char= x #\newline)))
810       (skip-whitespaces stream)
811       (setq ch (%peek-char stream)))))
812
813 (defun %read-list (stream)
814   (skip-whitespaces-and-comments stream)
815   (let ((ch (%peek-char stream)))
816     (cond
817       ((null ch)
818        (error "Unspected EOF"))
819       ((char= ch #\))
820        (%read-char stream)
821        nil)
822       ((char= ch #\.)
823        (%read-char stream)
824        (prog1 (ls-read stream)
825          (skip-whitespaces-and-comments stream)
826          (unless (char= (%read-char stream) #\))
827            (error "')' was expected."))))
828       (t
829        (cons (ls-read stream) (%read-list stream))))))
830
831 (defun read-string (stream)
832   (let ((string "")
833         (ch nil))
834     (setq ch (%read-char stream))
835     (while (not (eql ch #\"))
836       (when (null ch)
837         (error "Unexpected EOF"))
838       (when (eql ch #\\)
839         (setq ch (%read-char stream)))
840       (setq string (concat string (string ch)))
841       (setq ch (%read-char stream)))
842     string))
843
844 (defun read-sharp (stream)
845   (%read-char stream)
846   (ecase (%read-char stream)
847     (#\'
848      (list 'function (ls-read stream)))
849     (#\( (list-to-vector (%read-list stream)))
850     (#\\
851      (let ((cname
852             (concat (string (%read-char stream))
853                     (read-until stream #'terminalp))))
854        (cond
855          ((string= cname "space") (char-code #\space))
856          ((string= cname "tab") (char-code #\tab))
857          ((string= cname "newline") (char-code #\newline))
858          (t (char-code (char cname 0))))))
859     (#\+
860      (let ((feature (read-until stream #'terminalp)))
861        (cond
862          ((string= feature "common-lisp")
863           (ls-read stream)              ;ignore
864           (ls-read stream))
865          ((string= feature "ecmalisp")
866           (ls-read stream))
867          (t
868           (error "Unknown reader form.")))))))
869
870 ;;; Parse a string of the form NAME, PACKAGE:NAME or
871 ;;; PACKAGE::NAME and return the name. If the string is of the
872 ;;; form 1) or 3), but the symbol does not exist, it will be created
873 ;;; and interned in that package.
874 (defun read-symbol (string)
875   (let ((size (length string))
876         package name internalp index)
877     (setq index 0)
878     (while (and (< index size)
879                 (not (char= (char string index) #\:)))
880       (incf index))
881     (cond
882       ;; No package prefix
883       ((= index size)
884        (setq name string)
885        (setq package *package*)
886        (setq internalp t))
887       (t
888        ;; Package prefix
889        (if (zerop index)
890            (setq package "KEYWORD")
891            (setq package (string-upcase (subseq string 0 index))))
892        (incf index)
893        (when (char= (char string index) #\:)
894          (setq internalp t)
895          (incf index))
896        (setq name (subseq string index))))
897     ;; Canonalize symbol name and package
898     (setq name (string-upcase name))
899     (setq package (find-package package))
900     ;; TODO: PACKAGE:SYMBOL should signal error if SYMBOL is not an
901     ;; external symbol from PACKAGE.
902     (if (or internalp (eq package (find-package "KEYWORD")))
903         (intern name package)
904         (find-symbol name package))))
905
906 (defvar *eof* (gensym))
907 (defun ls-read (stream)
908   (skip-whitespaces-and-comments stream)
909   (let ((ch (%peek-char stream)))
910     (cond
911       ((or (null ch) (char= ch #\)))
912        *eof*)
913       ((char= ch #\()
914        (%read-char stream)
915        (%read-list stream))
916       ((char= ch #\')
917        (%read-char stream)
918        (list 'quote (ls-read stream)))
919       ((char= ch #\`)
920        (%read-char stream)
921        (list 'backquote (ls-read stream)))
922       ((char= ch #\")
923        (%read-char stream)
924        (read-string stream))
925       ((char= ch #\,)
926        (%read-char stream)
927        (if (eql (%peek-char stream) #\@)
928            (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
929            (list 'unquote (ls-read stream))))
930       ((char= ch #\#)
931        (read-sharp stream))
932       (t
933        (let ((string (read-until stream #'terminalp)))
934          (if (every #'digit-char-p string)
935              (parse-integer string)
936              (read-symbol string)))))))
937
938 (defun ls-read-from-string (string)
939   (ls-read (make-string-stream string)))
940
941
942 ;;;; Compiler
943
944 ;;; Translate the Lisp code to Javascript. It will compile the special
945 ;;; forms. Some primitive functions are compiled as special forms
946 ;;; too. The respective real functions are defined in the target (see
947 ;;; the beginning of this file) as well as some primitive functions.
948
949 (defvar *compilation-unit-checks* '())
950
951 (defun make-binding (name type value &optional declarations)
952   (list name type value declarations))
953
954 (defun binding-name (b) (first b))
955 (defun binding-type (b) (second b))
956 (defun binding-value (b) (third b))
957 (defun binding-declarations (b) (fourth b))
958
959 (defun set-binding-value (b value)
960   (setcar (cddr b) value))
961
962 (defun set-binding-declarations (b value)
963   (setcar (cdddr b) value))
964
965 (defun push-binding-declaration (decl b)
966   (set-binding-declarations b (cons decl (binding-declarations b))))
967
968
969 (defun make-lexenv ()
970   (list nil nil nil nil))
971
972 (defun copy-lexenv (lexenv)
973   (copy-list lexenv))
974
975 (defun push-to-lexenv (binding lexenv namespace)
976   (ecase namespace
977     (variable   (setcar        lexenv  (cons binding (car lexenv))))
978     (function   (setcar   (cdr lexenv) (cons binding (cadr lexenv))))
979     (block      (setcar  (cddr lexenv) (cons binding (caddr lexenv))))
980     (gotag      (setcar (cdddr lexenv) (cons binding (cadddr lexenv))))))
981
982 (defun extend-lexenv (bindings lexenv namespace)
983   (let ((env (copy-lexenv lexenv)))
984     (dolist (binding (reverse bindings) env)
985       (push-to-lexenv binding env namespace))))
986
987 (defun lookup-in-lexenv (name lexenv namespace)
988   (assoc name (ecase namespace
989                 (variable (first lexenv))
990                 (function (second lexenv))
991                 (block (third lexenv))
992                 (gotag (fourth lexenv)))))
993
994 (defvar *environment* (make-lexenv))
995
996 (defvar *variable-counter* 0)
997 (defun gvarname (symbol)
998   (concat "v" (integer-to-string (incf *variable-counter*))))
999
1000 (defun translate-variable (symbol)
1001   (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
1002
1003 (defun extend-local-env (args)
1004   (let ((new (copy-lexenv *environment*)))
1005     (dolist (symbol args new)
1006       (let ((b (make-binding symbol 'lexical-variable (gvarname symbol))))
1007         (push-to-lexenv b new 'variable)))))
1008
1009 ;;; Toplevel compilations
1010 (defvar *toplevel-compilations* nil)
1011
1012 (defun toplevel-compilation (string)
1013   (push string *toplevel-compilations*))
1014
1015 (defun null-or-empty-p (x)
1016   (zerop (length x)))
1017
1018 (defun get-toplevel-compilations ()
1019   (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
1020
1021 (defun %compile-defmacro (name lambda)
1022   (toplevel-compilation (ls-compile `',name))
1023   (push-to-lexenv (make-binding name 'macro lambda) *environment* 'function))
1024
1025 (defun global-binding (name type namespace)
1026   (or (lookup-in-lexenv name *environment* namespace)
1027       (let ((b (make-binding name type nil)))
1028         (push-to-lexenv b *environment* namespace)
1029         b)))
1030
1031 (defun claimp (symbol namespace claim)
1032   (let ((b (lookup-in-lexenv symbol *environment* namespace)))
1033     (and b (member claim (binding-declarations b)))))
1034
1035 (defun !proclaim (decl)
1036   (case (car decl)
1037     (special
1038      (dolist (name (cdr decl))
1039        (let ((b (global-binding name 'variable 'variable)))
1040          (push-binding-declaration 'special b))))
1041     (notinline
1042      (dolist (name (cdr decl))
1043        (let ((b (global-binding name 'function 'function)))
1044          (push-binding-declaration 'notinline b))))
1045     (constant
1046      (dolist (name (cdr decl))
1047        (let ((b (global-binding name 'variable 'variable)))
1048          (push-binding-declaration 'constant b))))
1049     (non-overridable
1050      (dolist (name (cdr decl))
1051        (let ((b (global-binding name 'function 'function)))
1052          (push-binding-declaration 'non-overridable b))))))
1053
1054 #+ecmalisp
1055 (fset 'proclaim #'!proclaim)
1056
1057 ;;; Special forms
1058
1059 (defvar *compilations* nil)
1060
1061 (defmacro define-compilation (name args &body body)
1062   ;; Creates a new primitive `name' with parameters args and
1063   ;; @body. The body can access to the local environment through the
1064   ;; variable *ENVIRONMENT*.
1065   `(push (list ',name (lambda ,args (block ,name ,@body)))
1066          *compilations*))
1067
1068 (define-compilation if (condition true false)
1069   (concat "(" (ls-compile condition) " !== " (ls-compile nil)
1070           " ? " (ls-compile true)
1071           " : " (ls-compile false)
1072           ")"))
1073
1074 (defvar *lambda-list-keywords* '(&optional &rest))
1075
1076 (defun list-until-keyword (list)
1077   (if (or (null list) (member (car list) *lambda-list-keywords*))
1078       nil
1079       (cons (car list) (list-until-keyword (cdr list)))))
1080
1081 (defun lambda-list-required-arguments (lambda-list)
1082   (list-until-keyword lambda-list))
1083
1084 (defun lambda-list-optional-arguments-with-default (lambda-list)
1085   (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
1086
1087 (defun lambda-list-optional-arguments (lambda-list)
1088   (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
1089
1090 (defun lambda-list-rest-argument (lambda-list)
1091   (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
1092     (when (cdr rest)
1093       (error "Bad lambda-list"))
1094     (car rest)))
1095
1096
1097 (defun lambda-docstring-wrapper (docstring &rest strs)
1098   (if docstring
1099       (js!selfcall
1100         "var func = " (join strs) ";" *newline*
1101         "func.docstring = '" docstring "';" *newline*
1102         "return func;" *newline*)
1103       (join strs)))
1104
1105 (define-compilation lambda (lambda-list &rest body)
1106   (let ((required-arguments (lambda-list-required-arguments lambda-list))
1107         (optional-arguments (lambda-list-optional-arguments lambda-list))
1108         (rest-argument (lambda-list-rest-argument lambda-list))
1109         documentation)
1110     ;; Get the documentation string for the lambda function
1111     (when (and (stringp (car body))
1112                (not (null (cdr body))))
1113       (setq documentation (car body))
1114       (setq body (cdr body)))
1115     (let ((n-required-arguments (length required-arguments))
1116           (n-optional-arguments (length optional-arguments))
1117           (*environment* (extend-local-env
1118                           (append (ensure-list rest-argument)
1119                                   required-arguments
1120                                   optional-arguments))))
1121       (lambda-docstring-wrapper
1122        documentation
1123        "(function ("
1124        (join (mapcar #'translate-variable
1125                      (append required-arguments optional-arguments))
1126              ",")
1127        "){" *newline*
1128        ;; Check number of arguments
1129        (indent
1130         (if required-arguments
1131             (concat "if (arguments.length < " (integer-to-string n-required-arguments)
1132                     ") throw 'too few arguments';" *newline*)
1133             "")
1134         (if (not rest-argument)
1135             (concat "if (arguments.length > "
1136                     (integer-to-string (+ n-required-arguments n-optional-arguments))
1137                     ") throw 'too many arguments';" *newline*)
1138             "")
1139         ;; Optional arguments
1140         (if optional-arguments
1141             (concat "switch(arguments.length){" *newline*
1142                     (let ((optional-and-defaults
1143                            (lambda-list-optional-arguments-with-default lambda-list))
1144                           (cases nil)
1145                           (idx 0))
1146                       (progn
1147                         (while (< idx n-optional-arguments)
1148                           (let ((arg (nth idx optional-and-defaults)))
1149                             (push (concat "case "
1150                                           (integer-to-string (+ idx n-required-arguments)) ":" *newline*
1151                                           (translate-variable (car arg))
1152                                           "="
1153                                           (ls-compile (cadr arg))
1154                                           ";" *newline*)
1155                                   cases)
1156                             (incf idx)))
1157                         (push (concat "default: break;" *newline*) cases)
1158                         (join (reverse cases))))
1159                     "}" *newline*)
1160             "")
1161         ;; &rest/&body argument
1162         (if rest-argument
1163             (let ((js!rest (translate-variable rest-argument)))
1164               (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
1165                       "for (var i = arguments.length-1; i>="
1166                       (integer-to-string (+ n-required-arguments n-optional-arguments))
1167                       "; i--)" *newline*
1168                       (indent js!rest " = "
1169                               "{car: arguments[i], cdr: ") js!rest "};"
1170                       *newline*))
1171             "")
1172         ;; Body
1173         (ls-compile-block body t)) *newline*
1174        "})"))))
1175
1176 (define-compilation setq (var val)
1177   (let ((b (lookup-in-lexenv var *environment* 'variable)))
1178     (if (eq (binding-type b) 'lexical-variable)
1179         (concat (binding-value b) " = " (ls-compile val))
1180         (ls-compile `(set ',var ,val)))))
1181
1182 ;;; FFI Variable accessors
1183 (define-compilation js-vref (var)
1184   var)
1185
1186 (define-compilation js-vset (var val)
1187   (concat "(" var " = " (ls-compile val) ")"))
1188
1189
1190 ;;; Literals
1191 (defun escape-string (string)
1192   (let ((output "")
1193         (index 0)
1194         (size (length string)))
1195     (while (< index size)
1196       (let ((ch (char string index)))
1197         (when (or (char= ch #\") (char= ch #\\))
1198           (setq output (concat output "\\")))
1199         (when (or (char= ch #\newline))
1200           (setq output (concat output "\\"))
1201           (setq ch #\n))
1202         (setq output (concat output (string ch))))
1203       (incf index))
1204     output))
1205
1206
1207 (defvar *literal-symbols* nil)
1208 (defvar *literal-counter* 0)
1209
1210 (defun genlit ()
1211   (concat "l" (integer-to-string (incf *literal-counter*))))
1212
1213 (defun literal (sexp &optional recursive)
1214   (cond
1215     ((integerp sexp) (integer-to-string sexp))
1216     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1217     ((symbolp sexp)
1218      (or (cdr (assoc sexp *literal-symbols*))
1219          (let ((v (genlit))
1220                (s #+common-lisp (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1221                   #+ecmalisp (ls-compile
1222                               `(intern ,(symbol-name sexp)
1223                                        ,(package-name (symbol-package sexp))))))
1224            (push (cons sexp v) *literal-symbols*)
1225            (toplevel-compilation (concat "var " v " = " s))
1226            v)))
1227     ((consp sexp)
1228      (let ((c (concat "{car: " (literal (car sexp) t) ", "
1229                       "cdr: " (literal (cdr sexp) t) "}")))
1230        (if recursive
1231            c
1232            (let ((v (genlit)))
1233              (toplevel-compilation (concat "var " v " = " c))
1234              v))))
1235     ((arrayp sexp)
1236      (let ((elements (vector-to-list sexp)))
1237        (let ((c (concat "[" (join (mapcar #'literal elements) ", ") "]")))
1238          (if recursive
1239              c
1240              (let ((v (genlit)))
1241                (toplevel-compilation (concat "var " v " = " c))
1242                v)))))))
1243
1244 (define-compilation quote (sexp)
1245   (literal sexp))
1246
1247 (define-compilation %while (pred &rest body)
1248   (js!selfcall
1249     "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1250     (indent (ls-compile-block body))
1251     "}"
1252     "return " (ls-compile nil) ";" *newline*))
1253
1254 (define-compilation function (x)
1255   (cond
1256     ((and (listp x) (eq (car x) 'lambda))
1257      (ls-compile x))
1258     ((symbolp x)
1259      (ls-compile `(symbol-function ',x)))))
1260
1261 (define-compilation eval-when-compile (&rest body)
1262   (eval (cons 'progn body))
1263   nil)
1264
1265 (defmacro define-transformation (name args form)
1266   `(define-compilation ,name ,args
1267      (ls-compile ,form)))
1268
1269 (define-compilation progn (&rest body)
1270   (js!selfcall (ls-compile-block body t)))
1271
1272 (defun special-variable-p (x)
1273   (claimp x 'variable 'special))
1274
1275 ;;; Wrap CODE to restore the symbol values of the dynamic
1276 ;;; bindings. BINDINGS is a list of pairs of the form
1277 ;;; (SYMBOL . PLACE),  where PLACE is a Javascript variable
1278 ;;; name to initialize the symbol value and where to stored
1279 ;;; the old value.
1280 (defun let-binding-wrapper (bindings body)
1281   (when (null bindings)
1282     (return-from let-binding-wrapper body))
1283   (concat
1284    "try {" *newline*
1285    (indent "var tmp;" *newline*
1286            (mapconcat
1287             (lambda (b)
1288               (let ((s (ls-compile `(quote ,(car b)))))
1289                 (concat "tmp = " s ".value;" *newline*
1290                         s ".value = " (cdr b) ";" *newline*
1291                         (cdr b) " = tmp;" *newline*)))
1292             bindings)
1293            body *newline*)
1294    "}" *newline*
1295    "finally {"  *newline*
1296    (indent
1297     (mapconcat (lambda (b)
1298                  (let ((s (ls-compile `(quote ,(car b)))))
1299                    (concat s ".value" " = " (cdr b) ";" *newline*)))
1300                bindings))
1301    "}" *newline*))
1302
1303 (define-compilation let (bindings &rest body)
1304   (let ((bindings (mapcar #'ensure-list bindings)))
1305     (let ((variables (mapcar #'first bindings)))
1306       (let ((cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
1307             (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
1308             (dynamic-bindings))
1309         (concat "(function("
1310                 (join (mapcar (lambda (x)
1311                                 (if (special-variable-p x)
1312                                     (let ((v (gvarname x)))
1313                                       (push (cons x v) dynamic-bindings)
1314                                       v)
1315                                     (translate-variable x)))
1316                               variables)
1317                       ",")
1318                 "){" *newline*
1319                 (let ((body (ls-compile-block body t)))
1320                   (indent (let-binding-wrapper dynamic-bindings body)))
1321                 "})(" (join cvalues ",") ")")))))
1322
1323
1324 ;;; Return the code to initialize BINDING, and push it extending the
1325 ;;; current lexical environment if the variable is special.
1326 (defun let*-initialize-value (binding)
1327   (let ((var (first binding))
1328         (value (second binding)))
1329     (if (special-variable-p var)
1330         (concat (ls-compile `(setq ,var ,value)) ";" *newline*)
1331         (let ((v (gvarname var)))
1332           (let ((b (make-binding var 'variable v)))
1333             (prog1 (concat "var " v " = " (ls-compile value) ";" *newline*)
1334               (push-to-lexenv b *environment* 'variable)))))))
1335
1336 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
1337 ;;; DOES NOT generate code to initialize the value of the symbols,
1338 ;;; unlike let-binding-wrapper.
1339 (defun let*-binding-wrapper (symbols body)
1340   (when (null symbols)
1341     (return-from let*-binding-wrapper body))
1342   (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
1343                        (remove-if-not #'special-variable-p symbols))))
1344     (concat
1345      "try {" *newline*
1346      (indent
1347       (mapconcat (lambda (b)
1348                    (let ((s (ls-compile `(quote ,(car b)))))
1349                      (concat "var " (cdr b) " = " s ".value;" *newline*)))
1350                  store)
1351       body)
1352      "}" *newline*
1353      "finally {" *newline*
1354      (indent
1355       (mapconcat (lambda (b)
1356                    (let ((s (ls-compile `(quote ,(car b)))))
1357                      (concat s ".value" " = " (cdr b) ";" *newline*)))
1358                  store))
1359      "}" *newline*)))
1360
1361
1362 (define-compilation let* (bindings &rest body)
1363   (let ((bindings (mapcar #'ensure-list bindings))
1364         (*environment* (copy-lexenv *environment*)))
1365     (js!selfcall
1366       (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
1367             (body (concat (mapconcat #'let*-initialize-value bindings)
1368                           (ls-compile-block body t))))
1369         (let*-binding-wrapper specials body)))))
1370
1371
1372 (defvar *block-counter* 0)
1373
1374 (define-compilation block (name &rest body)
1375   (let ((tr (integer-to-string (incf *block-counter*))))
1376     (let ((b (make-binding name 'block tr)))
1377       (js!selfcall
1378         "try {" *newline*
1379         (let ((*environment* (extend-lexenv (list b) *environment* 'block)))
1380           (indent "return " (ls-compile `(progn ,@body)) ";" *newline*))
1381         "}" *newline*
1382         "catch (cf){" *newline*
1383         "    if (cf.type == 'block' && cf.id == " tr ")" *newline*
1384         "        return cf.value;" *newline*
1385         "    else" *newline*
1386         "        throw cf;" *newline*
1387         "}" *newline*))))
1388
1389 (define-compilation return-from (name &optional value)
1390   (let ((b (lookup-in-lexenv name *environment* 'block)))
1391     (if b
1392         (js!selfcall
1393           "throw ({"
1394           "type: 'block', "
1395           "id: " (binding-value b) ", "
1396           "value: " (ls-compile value) ", "
1397           "message: 'Return from unknown block " (symbol-name name) ".'"
1398           "})")
1399         (error (concat "Unknown block `" (symbol-name name) "'.")))))
1400
1401
1402 (define-compilation catch (id &rest body)
1403   (js!selfcall
1404     "var id = " (ls-compile id) ";" *newline*
1405     "try {" *newline*
1406     (indent "return " (ls-compile `(progn ,@body))
1407             ";" *newline*)
1408     "}" *newline*
1409     "catch (cf){" *newline*
1410     "    if (cf.type == 'catch' && cf.id == id)" *newline*
1411     "        return cf.value;" *newline*
1412     "    else" *newline*
1413     "        throw cf;" *newline*
1414     "}" *newline*))
1415
1416 (define-compilation throw (id value)
1417   (js!selfcall
1418     "throw ({"
1419     "type: 'catch', "
1420     "id: " (ls-compile id) ", "
1421     "value: " (ls-compile value) ", "
1422     "message: 'Throw uncatched.'"
1423     "})"))
1424
1425
1426 (defvar *tagbody-counter* 0)
1427 (defvar *go-tag-counter* 0)
1428
1429 (defun go-tag-p (x)
1430   (or (integerp x) (symbolp x)))
1431
1432 (defun declare-tagbody-tags (tbidx body)
1433   (let ((bindings
1434          (mapcar (lambda (label)
1435                    (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1436                      (make-binding label 'gotag (list tbidx tagidx))))
1437                  (remove-if-not #'go-tag-p body))))
1438     (extend-lexenv bindings *environment* 'gotag)))
1439
1440 (define-compilation tagbody (&rest body)
1441   ;; Ignore the tagbody if it does not contain any go-tag. We do this
1442   ;; because 1) it is easy and 2) many built-in forms expand to a
1443   ;; implicit tagbody, so we save some space.
1444   (unless (some #'go-tag-p body)
1445     (return-from tagbody (ls-compile `(progn ,@body nil))))
1446   ;; The translation assumes the first form in BODY is a label
1447   (unless (go-tag-p (car body))
1448     (push (gensym "START") body))
1449   ;; Tagbody compilation
1450   (let ((tbidx (integer-to-string *tagbody-counter*)))
1451     (let ((*environment* (declare-tagbody-tags tbidx body))
1452           initag)
1453       (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1454         (setq initag (second (binding-value b))))
1455       (js!selfcall
1456         "var tagbody_" tbidx " = " initag ";" *newline*
1457         "tbloop:" *newline*
1458         "while (true) {" *newline*
1459         (indent "try {" *newline*
1460                 (indent (let ((content ""))
1461                           (concat "switch(tagbody_" tbidx "){" *newline*
1462                                   "case " initag ":" *newline*
1463                                   (dolist (form (cdr body) content)
1464                                     (concatf content
1465                                       (if (not (go-tag-p form))
1466                                           (indent (ls-compile form) ";" *newline*)
1467                                           (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1468                                             (concat "case " (second (binding-value b)) ":" *newline*)))))
1469                                   "default:" *newline*
1470                                   "    break tbloop;" *newline*
1471                                   "}" *newline*)))
1472                 "}" *newline*
1473                 "catch (jump) {" *newline*
1474                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1475                 "        tagbody_" tbidx " = jump.label;" *newline*
1476                 "    else" *newline*
1477                 "        throw(jump);" *newline*
1478                 "}" *newline*)
1479         "}" *newline*
1480         "return " (ls-compile nil) ";" *newline*))))
1481
1482 (define-compilation go (label)
1483   (let ((b (lookup-in-lexenv label *environment* 'gotag))
1484         (n (cond
1485              ((symbolp label) (symbol-name label))
1486              ((integerp label) (integer-to-string label)))))
1487     (if b
1488         (js!selfcall
1489           "throw ({"
1490           "type: 'tagbody', "
1491           "id: " (first (binding-value b)) ", "
1492           "label: " (second (binding-value b)) ", "
1493           "message: 'Attempt to GO to non-existing tag " n "'"
1494           "})" *newline*)
1495         (error (concat "Unknown tag `" n "'.")))))
1496
1497
1498 (define-compilation unwind-protect (form &rest clean-up)
1499   (js!selfcall
1500     "var ret = " (ls-compile nil) ";" *newline*
1501     "try {" *newline*
1502     (indent "ret = " (ls-compile form) ";" *newline*)
1503     "} finally {" *newline*
1504     (indent (ls-compile-block clean-up))
1505     "}" *newline*
1506     "return ret;" *newline*))
1507
1508
1509 ;;; A little backquote implementation without optimizations of any
1510 ;;; kind for ecmalisp.
1511 (defun backquote-expand-1 (form)
1512   (cond
1513     ((symbolp form)
1514      (list 'quote form))
1515     ((atom form)
1516      form)
1517     ((eq (car form) 'unquote)
1518      (car form))
1519     ((eq (car form) 'backquote)
1520      (backquote-expand-1 (backquote-expand-1 (cadr form))))
1521     (t
1522      (cons 'append
1523            (mapcar (lambda (s)
1524                      (cond
1525                        ((and (listp s) (eq (car s) 'unquote))
1526                         (list 'list (cadr s)))
1527                        ((and (listp s) (eq (car s) 'unquote-splicing))
1528                         (cadr s))
1529                        (t
1530                         (list 'list (backquote-expand-1 s)))))
1531                    form)))))
1532
1533 (defun backquote-expand (form)
1534   (if (and (listp form) (eq (car form) 'backquote))
1535       (backquote-expand-1 (cadr form))
1536       form))
1537
1538 (defmacro backquote (form)
1539   (backquote-expand-1 form))
1540
1541 (define-transformation backquote (form)
1542   (backquote-expand-1 form))
1543
1544 ;;; Primitives
1545
1546 (defvar *builtins* nil)
1547
1548 (defmacro define-raw-builtin (name args &body body)
1549   ;; Creates a new primitive function `name' with parameters args and
1550   ;; @body. The body can access to the local environment through the
1551   ;; variable *ENVIRONMENT*.
1552   `(push (list ',name (lambda ,args (block ,name ,@body)))
1553          *builtins*))
1554
1555 (defmacro define-builtin (name args &body body)
1556   `(progn
1557      (define-raw-builtin ,name ,args
1558        (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1559          ,@body))))
1560
1561 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1562 (defmacro type-check (decls &body body)
1563   `(js!selfcall
1564      ,@(mapcar (lambda (decl)
1565                    `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1566                  decls)
1567      ,@(mapcar (lambda (decl)
1568                  `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1569                           (indent "throw 'The value ' + "
1570                                   ,(first decl)
1571                                   " + ' is not a type "
1572                                   ,(second decl)
1573                                   ".';"
1574                                   *newline*)))
1575                decls)
1576      (concat "return " (progn ,@body) ";" *newline*)))
1577
1578 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
1579 ;;; a variable which holds a list of forms. It will compile them and
1580 ;;; store the result in some Javascript variables. BODY is evaluated
1581 ;;; with ARGS bound to the list of these variables to generate the
1582 ;;; code which performs the transformation on these variables.
1583
1584 (defun variable-arity-call (args function)
1585   (unless (consp args)
1586     (error "ARGS must be a non-empty list"))
1587   (let ((counter 0)
1588         (variables '())
1589         (prelude ""))
1590     (dolist (x args)
1591       (let ((v (concat "x" (integer-to-string (incf counter)))))
1592         (push v variables)
1593         (concatf prelude
1594                  (concat "var " v " = " (ls-compile x) ";" *newline*
1595                          "if (typeof " v " !== 'number') throw 'Not a number!';"
1596                          *newline*))))
1597     (js!selfcall prelude (funcall function (reverse variables)))))
1598
1599
1600 (defmacro variable-arity (args &body body)
1601   (unless (symbolp args)
1602     (error "Bad usage of VARIABLE-ARITY, yo must pass a symbol"))
1603   `(variable-arity-call ,args
1604                         (lambda (,args)
1605                           (concat "return " ,@body ";" *newline*))))
1606
1607
1608 (defun num-op-num (x op y)
1609   (type-check (("x" "number" x) ("y" "number" y))
1610     (concat "x" op "y")))
1611
1612 (define-raw-builtin + (&rest numbers)
1613   (if (null numbers)
1614       "0"
1615       (variable-arity numbers
1616         (join numbers "+"))))
1617
1618 (define-raw-builtin - (x &rest others)
1619   (let ((args (cons x others)))
1620     (variable-arity args
1621       (if (null others)
1622           (concat "-" (car args))
1623           (join args "-")))))
1624
1625
1626 (define-builtin * (x y) (num-op-num x "*" y))
1627 (define-builtin / (x y) (num-op-num x "/" y))
1628
1629 (define-builtin mod (x y) (num-op-num x "%" y))
1630
1631 (define-builtin < (x y)  (js!bool (num-op-num x "<" y)))
1632 (define-builtin > (x y)  (js!bool (num-op-num x ">" y)))
1633 (define-builtin = (x y)  (js!bool (num-op-num x "==" y)))
1634 (define-builtin <= (x y) (js!bool (num-op-num x "<=" y)))
1635 (define-builtin >= (x y) (js!bool (num-op-num x ">=" y)))
1636
1637 (define-builtin numberp (x)
1638   (js!bool (concat "(typeof (" x ") == \"number\")")))
1639
1640 (define-builtin floor (x)
1641   (type-check (("x" "number" x))
1642     "Math.floor(x)"))
1643
1644 (define-builtin cons (x y)
1645   (concat "({car: " x ", cdr: " y "})"))
1646
1647 (define-builtin consp (x)
1648   (js!bool
1649    (js!selfcall
1650      "var tmp = " x ";" *newline*
1651      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1652
1653 (define-builtin car (x)
1654   (js!selfcall
1655     "var tmp = " x ";" *newline*
1656     "return tmp === " (ls-compile nil)
1657     "? " (ls-compile nil)
1658     ": tmp.car;" *newline*))
1659
1660 (define-builtin cdr (x)
1661   (js!selfcall
1662     "var tmp = " x ";" *newline*
1663     "return tmp === " (ls-compile nil) "? "
1664     (ls-compile nil)
1665     ": tmp.cdr;" *newline*))
1666
1667 (define-builtin setcar (x new)
1668   (type-check (("x" "object" x))
1669     (concat "(x.car = " new ")")))
1670
1671 (define-builtin setcdr (x new)
1672   (type-check (("x" "object" x))
1673     (concat "(x.cdr = " new ")")))
1674
1675 (define-builtin symbolp (x)
1676   (js!bool
1677    (js!selfcall
1678      "var tmp = " x ";" *newline*
1679      "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1680
1681 (define-builtin make-symbol (name)
1682   (type-check (("name" "string" name))
1683     "({name: name})"))
1684
1685 (define-builtin symbol-name (x)
1686   (concat "(" x ").name"))
1687
1688 (define-builtin set (symbol value)
1689   (concat "(" symbol ").value = " value))
1690
1691 (define-builtin fset (symbol value)
1692   (concat "(" symbol ").function = " value))
1693
1694 (define-builtin boundp (x)
1695   (js!bool (concat "(" x ".value !== undefined)")))
1696
1697 (define-builtin symbol-value (x)
1698   (js!selfcall
1699     "var symbol = " x ";" *newline*
1700     "var value = symbol.value;" *newline*
1701     "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1702     "return value;" *newline*))
1703
1704 (define-builtin symbol-function (x)
1705   (js!selfcall
1706     "var symbol = " x ";" *newline*
1707     "var func = symbol.function;" *newline*
1708     "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1709     "return func;" *newline*))
1710
1711 (define-builtin symbol-plist (x)
1712   (concat "((" x ").plist || " (ls-compile nil) ")"))
1713
1714 (define-builtin lambda-code (x)
1715   (concat "(" x ").toString()"))
1716
1717
1718 (define-builtin eq    (x y) (js!bool (concat "(" x " === " y ")")))
1719 (define-builtin equal (x y) (js!bool (concat "(" x  " == " y ")")))
1720
1721 (define-builtin char-to-string (x)
1722   (type-check (("x" "number" x))
1723     "String.fromCharCode(x)"))
1724
1725 (define-builtin stringp (x)
1726   (js!bool (concat "(typeof(" x ") == \"string\")")))
1727
1728 (define-builtin string-upcase (x)
1729   (type-check (("x" "string" x))
1730     "x.toUpperCase()"))
1731
1732 (define-builtin string-length (x)
1733   (type-check (("x" "string" x))
1734     "x.length"))
1735
1736 (define-raw-builtin slice (string a &optional b)
1737   (js!selfcall
1738     "var str = " (ls-compile string) ";" *newline*
1739     "var a = " (ls-compile a) ";" *newline*
1740     "var b;" *newline*
1741     (if b
1742         (concat "b = " (ls-compile b) ";" *newline*)
1743         "")
1744     "return str.slice(a,b);" *newline*))
1745
1746 (define-builtin char (string index)
1747   (type-check (("string" "string" string)
1748                ("index" "number" index))
1749     "string.charCodeAt(index)"))
1750
1751 (define-builtin concat-two (string1 string2)
1752   (type-check (("string1" "string" string1)
1753                ("string2" "string" string2))
1754     "string1.concat(string2)"))
1755
1756 (define-raw-builtin funcall (func &rest args)
1757   (concat "(" (ls-compile func) ")("
1758           (join (mapcar #'ls-compile args)
1759                 ", ")
1760           ")"))
1761
1762 (define-raw-builtin apply (func &rest args)
1763   (if (null args)
1764       (concat "(" (ls-compile func) ")()")
1765       (let ((args (butlast args))
1766             (last (car (last args))))
1767         (js!selfcall
1768           "var f = " (ls-compile func) ";" *newline*
1769           "var args = [" (join (mapcar #'ls-compile args)
1770                                ", ")
1771           "];" *newline*
1772           "var tail = (" (ls-compile last) ");" *newline*
1773           "while (tail != " (ls-compile nil) "){" *newline*
1774           "    args.push(tail.car);" *newline*
1775           "    tail = tail.cdr;" *newline*
1776           "}" *newline*
1777           "return f.apply(this, args);" *newline*))))
1778
1779 (define-builtin js-eval (string)
1780   (type-check (("string" "string" string))
1781     "eval.apply(window, [string])"))
1782
1783 (define-builtin error (string)
1784   (js!selfcall "throw " string ";" *newline*))
1785
1786 (define-builtin new () "{}")
1787
1788 (define-builtin objectp (x)
1789   (js!bool (concat "(typeof (" x ") === 'object')")))
1790
1791 (define-builtin oget (object key)
1792   (js!selfcall
1793     "var tmp = " "(" object ")[" key "];" *newline*
1794     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1795
1796 (define-builtin oset (object key value)
1797   (concat "((" object ")[" key "] = " value ")"))
1798
1799 (define-builtin in (key object)
1800   (js!bool (concat "((" key ") in (" object "))")))
1801
1802 (define-builtin functionp (x)
1803   (js!bool (concat "(typeof " x " == 'function')")))
1804
1805 (define-builtin write-string (x)
1806   (type-check (("x" "string" x))
1807     "lisp.write(x)"))
1808
1809 (define-builtin make-array (n)
1810   (js!selfcall
1811     "var r = [];" *newline*
1812     "for (var i = 0; i < " n "; i++)" *newline*
1813     (indent "r.push(" (ls-compile nil) ");" *newline*)
1814     "return r;" *newline*))
1815
1816 (define-builtin arrayp (x)
1817   (js!bool
1818    (js!selfcall
1819      "var x = " x ";" *newline*
1820      "return typeof x === 'object' && 'length' in x;")))
1821
1822 (define-builtin aref (array n)
1823   (js!selfcall
1824     "var x = " "(" array ")[" n "];" *newline*
1825     "if (x === undefined) throw 'Out of range';" *newline*
1826     "return x;" *newline*))
1827
1828 (define-builtin aset (array n value)
1829   (js!selfcall
1830     "var x = " array ";" *newline*
1831     "var i = " n ";" *newline*
1832     "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
1833     "return x[i] = " value ";" *newline*))
1834
1835
1836 (defun macro (x)
1837   (and (symbolp x)
1838        (let ((b (lookup-in-lexenv x *environment* 'function)))
1839          (and (eq (binding-type b) 'macro)
1840               b))))
1841
1842 (defun ls-macroexpand-1 (form)
1843   (let ((macro-binding (macro (car form))))
1844     (if macro-binding
1845         (let ((expander (binding-value macro-binding)))
1846           (when (listp expander)
1847             (let ((compiled (eval expander)))
1848               ;; The list representation are useful while
1849               ;; bootstrapping, as we can dump the definition of the
1850               ;; macros easily, but they are slow because we have to
1851               ;; evaluate them and compile them now and again. So, let
1852               ;; us replace the list representation version of the
1853               ;; function with the compiled one.
1854               ;;
1855               #+ecmalisp (set-binding-value macro-binding compiled)
1856               (setq expander compiled)))
1857           (apply expander (cdr form)))
1858         form)))
1859
1860 (defun compile-funcall (function args)
1861   (if (and (symbolp function)
1862            (claimp function 'function 'non-overridable))
1863       (concat (ls-compile `',function) ".function("
1864               (join (mapcar #'ls-compile args)
1865                     ", ")
1866               ")")
1867       (concat (ls-compile `#',function) "("
1868               (join (mapcar #'ls-compile args)
1869                     ", ")
1870               ")")))
1871
1872 (defun ls-compile-block (sexps &optional return-last-p)
1873   (if return-last-p
1874       (concat (ls-compile-block (butlast sexps))
1875               "return " (ls-compile (car (last sexps))) ";")
1876       (join-trailing
1877        (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
1878        (concat ";" *newline*))))
1879
1880 (defun ls-compile (sexp)
1881   (cond
1882     ((symbolp sexp)
1883      (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1884        (cond
1885          ((and b (not (member 'special (binding-declarations b))))
1886           (binding-value b))
1887          ((or (keywordp sexp)
1888               (member 'constant (binding-declarations b)))
1889           (concat (ls-compile `',sexp) ".value"))
1890          (t
1891           (ls-compile `(symbol-value ',sexp))))))
1892     ((integerp sexp) (integer-to-string sexp))
1893     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1894     ((arrayp sexp) (literal sexp))
1895     ((listp sexp)
1896      (let ((name (car sexp))
1897            (args (cdr sexp)))
1898        (cond
1899          ;; Special forms
1900          ((assoc name *compilations*)
1901           (let ((comp (second (assoc name *compilations*))))
1902             (apply comp args)))
1903          ;; Built-in functions
1904          ((and (assoc name *builtins*)
1905                (not (claimp name 'function 'notinline)))
1906           (let ((comp (second (assoc name *builtins*))))
1907             (apply comp args)))
1908          (t
1909           (if (macro name)
1910               (ls-compile (ls-macroexpand-1 sexp))
1911               (compile-funcall name args))))))
1912     (t
1913      (error "How should I compile this?"))))
1914
1915 (defun ls-compile-toplevel (sexp)
1916   (let ((*toplevel-compilations* nil))
1917     (cond
1918       ((and (consp sexp) (eq (car sexp) 'progn))
1919        (let ((subs (mapcar #'ls-compile-toplevel (cdr sexp))))
1920          (join (remove-if #'null-or-empty-p subs))))
1921       (t
1922        (let ((code (ls-compile sexp)))
1923          (concat (join-trailing (get-toplevel-compilations)
1924                                 (concat ";" *newline*))
1925                  (if code
1926                      (concat code ";" *newline*)
1927                      "")))))))
1928
1929
1930 ;;; Once we have the compiler, we define the runtime environment and
1931 ;;; interactive development (eval), which works calling the compiler
1932 ;;; and evaluating the Javascript result globally.
1933
1934 #+ecmalisp
1935 (progn
1936   (defmacro with-compilation-unit (&body body)
1937     `(prog1
1938          (progn
1939            (setq *compilation-unit-checks* nil)
1940            ,@body)
1941        (dolist (check *compilation-unit-checks*)
1942          (funcall check))))
1943
1944   (defun eval (x)
1945     (let ((code
1946            (with-compilation-unit
1947                (ls-compile-toplevel x))))
1948       (js-eval code)))
1949
1950   (export '(&rest &optional &body * *gensym-counter* *package* + - / 1+ 1- < <= =
1951             = > >= and append apply aref arrayp aset assoc atom block boundp
1952             boundp butlast caar cadddr caddr cadr car car case catch cdar cdddr
1953             cddr cdr cdr char char-code char= code-char cond cons consp copy-list
1954             decf declaim defparameter defun defvar digit-char-p disassemble
1955             documentation dolist dotimes ecase eq eql equal error eval every
1956             export fdefinition find-package find-symbol first fourth fset funcall
1957             function functionp gensym go identity if in-package incf integerp
1958             integerp intern keywordp lambda last length let let* list-all-packages
1959             list listp make-array make-package make-symbol mapcar member minusp
1960             mod nil not nth nthcdr null numberp or package-name package-use-list
1961             packagep plusp prin1-to-string print proclaim prog1 prog2 pron push
1962             quote remove remove-if remove-if-not return return-from revappend
1963             reverse second set setq some string-upcase string string= stringp
1964             subseq symbol-function symbol-name symbol-package symbol-plist
1965             symbol-value symbolp t tagbody third throw truncate unless
1966             unwind-protect variable warn when write-line write-string zerop))
1967
1968   (setq *package* *user-package*)
1969
1970   (js-eval "var lisp")
1971   (js-vset "lisp" (new))
1972   (js-vset "lisp.read" #'ls-read-from-string)
1973   (js-vset "lisp.print" #'prin1-to-string)
1974   (js-vset "lisp.eval" #'eval)
1975   (js-vset "lisp.compile" #'ls-compile-toplevel)
1976   (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
1977   (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str))))
1978
1979   ;; Set the initial global environment to be equal to the host global
1980   ;; environment at this point of the compilation.
1981   (eval-when-compile
1982     (toplevel-compilation
1983      (ls-compile
1984       `(progn
1985          ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
1986                    *literal-symbols*)
1987          (setq *literal-symbols* ',*literal-symbols*)
1988          (setq *environment* ',*environment*)
1989          (setq *variable-counter* ,*variable-counter*)
1990          (setq *gensym-counter* ,*gensym-counter*)
1991          (setq *block-counter* ,*block-counter*)))))
1992
1993   (eval-when-compile
1994     (toplevel-compilation
1995      (ls-compile
1996       `(setq *literal-counter* ,*literal-counter*)))))
1997
1998
1999 ;;; Finally, we provide a couple of functions to easily bootstrap
2000 ;;; this. It just calls the compiler with this file as input.
2001
2002 #+common-lisp
2003 (progn
2004   (defun read-whole-file (filename)
2005     (with-open-file (in filename)
2006       (let ((seq (make-array (file-length in) :element-type 'character)))
2007         (read-sequence seq in)
2008         seq)))
2009
2010   (defun ls-compile-file (filename output)
2011     (setq *compilation-unit-checks* nil)
2012     (with-open-file (out output :direction :output :if-exists :supersede)
2013       (let* ((source (read-whole-file filename))
2014              (in (make-string-stream source)))
2015         (loop
2016            for x = (ls-read in)
2017            until (eq x *eof*)
2018            for compilation = (ls-compile-toplevel x)
2019            when (plusp (length compilation))
2020            do (write-string compilation out))
2021         (dolist (check *compilation-unit-checks*)
2022           (funcall check))
2023         (setq *compilation-unit-checks* nil))))
2024
2025   (defun bootstrap ()
2026     (setq *environment* (make-lexenv))
2027     (setq *literal-symbols* nil)
2028     (setq *variable-counter* 0
2029           *gensym-counter* 0
2030           *literal-counter* 0
2031           *block-counter* 0)
2032     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))