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