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