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