12ee19d8b342ef372d1441869bf280d1a0666c60
[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 (defun dynamic-binding-wrapper (bindings body)
1232   (if (null bindings)
1233       body
1234       (concat
1235        "try {" *newline*
1236        (indent
1237         "var tmp;" *newline*
1238         (join
1239          (mapcar (lambda (b)
1240                    (let ((s (ls-compile `(quote ,(car b)))))
1241                      (concat "tmp = " s ".value;" *newline*
1242                              s ".value = " (cdr b) ";" *newline*
1243                              (cdr b) " = tmp;" *newline*)))
1244                  bindings))
1245         body)
1246        "}" *newline*
1247        "finally {"  *newline*
1248        (indent
1249         (join-trailing
1250          (mapcar (lambda (b)
1251                    (let ((s (ls-compile `(quote ,(car b)))))
1252                      (concat s ".value" " = " (cdr b))))
1253                  bindings)
1254          (concat ";" *newline*)))
1255        "}" *newline*)))
1256
1257
1258 (define-compilation let (bindings &rest body)
1259   (let ((bindings (mapcar #'ensure-list bindings)))
1260     (let ((variables (mapcar #'first bindings))
1261           (values    (mapcar #'second bindings)))
1262       (let ((cvalues (mapcar #'ls-compile values))
1263             (*environment*
1264              (extend-local-env (remove-if (lambda (v)(claimp v 'variable 'special))
1265                                           variables)))
1266             (dynamic-bindings))
1267         (concat "(function("
1268                 (join (mapcar (lambda (x)
1269                                 (if (claimp x 'variable 'special)
1270                                     (let ((v (gvarname x)))
1271                                       (push (cons x v) dynamic-bindings)
1272                                       v)
1273                                     (translate-variable x)))
1274                               variables)
1275                       ",")
1276                 "){" *newline*
1277                 (let ((body (ls-compile-block body t)))
1278                   (indent (dynamic-binding-wrapper dynamic-bindings body)))
1279                 "})(" (join cvalues ",") ")")))))
1280
1281
1282 (defvar *block-counter* 0)
1283
1284 (define-compilation block (name &rest body)
1285   (let ((tr (integer-to-string (incf *block-counter*))))
1286     (let ((b (make-binding name 'block tr)))
1287       (js!selfcall
1288         "try {" *newline*
1289         (let ((*environment* (extend-lexenv (list b) *environment* 'block)))
1290           (indent "return " (ls-compile `(progn ,@body)) ";" *newline*))
1291         "}" *newline*
1292         "catch (cf){" *newline*
1293         "    if (cf.type == 'block' && cf.id == " tr ")" *newline*
1294         "        return cf.value;" *newline*
1295         "    else" *newline*
1296         "        throw cf;" *newline*
1297         "}" *newline*))))
1298
1299 (define-compilation return-from (name &optional value)
1300   (let ((b (lookup-in-lexenv name *environment* 'block)))
1301     (if b
1302         (js!selfcall
1303           "throw ({"
1304           "type: 'block', "
1305           "id: " (binding-value b) ", "
1306           "value: " (ls-compile value) ", "
1307           "message: 'Return from unknown block " (symbol-name name) ".'"
1308           "})")
1309         (error (concat "Unknown block `" (symbol-name name) "'.")))))
1310
1311
1312 (define-compilation catch (id &rest body)
1313   (js!selfcall
1314     "var id = " (ls-compile id) ";" *newline*
1315     "try {" *newline*
1316     (indent "return " (ls-compile `(progn ,@body))
1317             ";" *newline*)
1318     "}" *newline*
1319     "catch (cf){" *newline*
1320     "    if (cf.type == 'catch' && cf.id == id)" *newline*
1321     "        return cf.value;" *newline*
1322     "    else" *newline*
1323     "        throw cf;" *newline*
1324     "}" *newline*))
1325
1326 (define-compilation throw (id value)
1327   (js!selfcall
1328     "throw ({"
1329     "type: 'catch', "
1330     "id: " (ls-compile id) ", "
1331     "value: " (ls-compile value) ", "
1332     "message: 'Throw uncatched.'"
1333     "})"))
1334
1335
1336 (defvar *tagbody-counter* 0)
1337 (defvar *go-tag-counter* 0)
1338
1339 (defun go-tag-p (x)
1340   (or (integerp x) (symbolp x)))
1341
1342 (defun declare-tagbody-tags (tbidx body)
1343   (let ((bindings
1344          (mapcar (lambda (label)
1345                    (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1346                      (make-binding label 'gotag (list tbidx tagidx))))
1347                  (remove-if-not #'go-tag-p body))))
1348     (extend-lexenv bindings *environment* 'gotag)))
1349
1350 (define-compilation tagbody (&rest body)
1351   ;; Ignore the tagbody if it does not contain any go-tag. We do this
1352   ;; because 1) it is easy and 2) many built-in forms expand to a
1353   ;; implicit tagbody, so we save some space.
1354   (unless (some #'go-tag-p body)
1355     (return-from tagbody (ls-compile `(progn ,@body nil))))
1356   ;; The translation assumes the first form in BODY is a label
1357   (unless (go-tag-p (car body))
1358     (push (gensym "START") body))
1359   ;; Tagbody compilation
1360   (let ((tbidx (integer-to-string *tagbody-counter*)))
1361     (let ((*environment* (declare-tagbody-tags tbidx body))
1362           initag)
1363       (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1364         (setq initag (second (binding-value b))))
1365       (js!selfcall
1366         "var tagbody_" tbidx " = " initag ";" *newline*
1367         "tbloop:" *newline*
1368         "while (true) {" *newline*
1369         (indent "try {" *newline*
1370                 (indent (let ((content ""))
1371                           (concat "switch(tagbody_" tbidx "){" *newline*
1372                                   "case " initag ":" *newline*
1373                                   (dolist (form (cdr body) content)
1374                                     (concatf content
1375                                       (if (not (go-tag-p form))
1376                                           (indent (ls-compile form) ";" *newline*)
1377                                           (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1378                                             (concat "case " (second (binding-value b)) ":" *newline*)))))
1379                                   "default:" *newline*
1380                                   "    break tbloop;" *newline*
1381                                   "}" *newline*)))
1382                 "}" *newline*
1383                 "catch (jump) {" *newline*
1384                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1385                 "        tagbody_" tbidx " = jump.label;" *newline*
1386                 "    else" *newline*
1387                 "        throw(jump);" *newline*
1388                 "}" *newline*)
1389         "}" *newline*
1390         "return " (ls-compile nil) ";" *newline*))))
1391
1392 (define-compilation go (label)
1393   (let ((b (lookup-in-lexenv label *environment* 'gotag))
1394         (n (cond
1395              ((symbolp label) (symbol-name label))
1396              ((integerp label) (integer-to-string label)))))
1397     (if b
1398         (js!selfcall
1399           "throw ({"
1400           "type: 'tagbody', "
1401           "id: " (first (binding-value b)) ", "
1402           "label: " (second (binding-value b)) ", "
1403           "message: 'Attempt to GO to non-existing tag " n "'"
1404           "})" *newline*)
1405         (error (concat "Unknown tag `" n "'.")))))
1406
1407
1408 (define-compilation unwind-protect (form &rest clean-up)
1409   (js!selfcall
1410     "var ret = " (ls-compile nil) ";" *newline*
1411     "try {" *newline*
1412     (indent "ret = " (ls-compile form) ";" *newline*)
1413     "} finally {" *newline*
1414     (indent (ls-compile-block clean-up))
1415     "}" *newline*
1416     "return ret;" *newline*))
1417
1418
1419 ;;; A little backquote implementation without optimizations of any
1420 ;;; kind for ecmalisp.
1421 (defun backquote-expand-1 (form)
1422   (cond
1423     ((symbolp form)
1424      (list 'quote form))
1425     ((atom form)
1426      form)
1427     ((eq (car form) 'unquote)
1428      (car form))
1429     ((eq (car form) 'backquote)
1430      (backquote-expand-1 (backquote-expand-1 (cadr form))))
1431     (t
1432      (cons 'append
1433            (mapcar (lambda (s)
1434                      (cond
1435                        ((and (listp s) (eq (car s) 'unquote))
1436                         (list 'list (cadr s)))
1437                        ((and (listp s) (eq (car s) 'unquote-splicing))
1438                         (cadr s))
1439                        (t
1440                         (list 'list (backquote-expand-1 s)))))
1441                    form)))))
1442
1443 (defun backquote-expand (form)
1444   (if (and (listp form) (eq (car form) 'backquote))
1445       (backquote-expand-1 (cadr form))
1446       form))
1447
1448 (defmacro backquote (form)
1449   (backquote-expand-1 form))
1450
1451 (define-transformation backquote (form)
1452   (backquote-expand-1 form))
1453
1454 ;;; Primitives
1455
1456 (defvar *builtins* nil)
1457
1458 (defmacro define-raw-builtin (name args &body body)
1459   ;; Creates a new primitive function `name' with parameters args and
1460   ;; @body. The body can access to the local environment through the
1461   ;; variable *ENVIRONMENT*.
1462   `(push (list ',name (lambda ,args (block ,name ,@body)))
1463          *builtins*))
1464
1465 (defmacro define-builtin (name args &body body)
1466   `(progn
1467      (define-raw-builtin ,name ,args
1468        (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1469          ,@body))))
1470
1471 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1472 (defmacro type-check (decls &body body)
1473   `(js!selfcall
1474      ,@(mapcar (lambda (decl)
1475                    `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1476                  decls)
1477      ,@(mapcar (lambda (decl)
1478                  `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1479                           (indent "throw 'The value ' + "
1480                                   ,(first decl)
1481                                   " + ' is not a type "
1482                                   ,(second decl)
1483                                   ".';"
1484                                   *newline*)))
1485                decls)
1486      (concat "return " (progn ,@body) ";" *newline*)))
1487
1488 (defun num-op-num (x op y)
1489   (type-check (("x" "number" x) ("y" "number" y))
1490     (concat "x" op "y")))
1491
1492 (define-builtin + (x y) (num-op-num x "+" y))
1493 (define-builtin - (x y) (num-op-num x "-" y))
1494 (define-builtin * (x y) (num-op-num x "*" y))
1495 (define-builtin / (x y) (num-op-num x "/" y))
1496
1497 (define-builtin mod (x y) (num-op-num x "%" y))
1498
1499 (define-builtin < (x y)  (js!bool (num-op-num x "<" y)))
1500 (define-builtin > (x y)  (js!bool (num-op-num x ">" y)))
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
1505 (define-builtin numberp (x)
1506   (js!bool (concat "(typeof (" x ") == \"number\")")))
1507
1508 (define-builtin floor (x)
1509   (type-check (("x" "number" x))
1510     "Math.floor(x)"))
1511
1512 (define-builtin cons (x y)
1513   (concat "({car: " x ", cdr: " y "})"))
1514
1515 (define-builtin consp (x)
1516   (js!bool
1517    (js!selfcall
1518      "var tmp = " x ";" *newline*
1519      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1520
1521 (define-builtin car (x)
1522   (js!selfcall
1523     "var tmp = " x ";" *newline*
1524     "return tmp === " (ls-compile nil)
1525     "? " (ls-compile nil)
1526     ": tmp.car;" *newline*))
1527
1528 (define-builtin cdr (x)
1529   (js!selfcall
1530     "var tmp = " x ";" *newline*
1531     "return tmp === " (ls-compile nil) "? "
1532     (ls-compile nil)
1533     ": tmp.cdr;" *newline*))
1534
1535 (define-builtin setcar (x new)
1536   (type-check (("x" "object" x))
1537     (concat "(x.car = " new ")")))
1538
1539 (define-builtin setcdr (x new)
1540   (type-check (("x" "object" x))
1541     (concat "(x.cdr = " new ")")))
1542
1543 (define-builtin symbolp (x)
1544   (js!bool
1545    (js!selfcall
1546      "var tmp = " x ";" *newline*
1547      "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1548
1549 (define-builtin make-symbol (name)
1550   (type-check (("name" "string" name))
1551     "({name: name})"))
1552
1553 (define-builtin symbol-name (x)
1554   (concat "(" x ").name"))
1555
1556 (define-builtin set (symbol value)
1557   (concat "(" symbol ").value = " value))
1558
1559 (define-builtin fset (symbol value)
1560   (concat "(" symbol ").function = " value))
1561
1562 (define-builtin boundp (x)
1563   (js!bool (concat "(" x ".value !== undefined)")))
1564
1565 (define-builtin symbol-value (x)
1566   (js!selfcall
1567     "var symbol = " x ";" *newline*
1568     "var value = symbol.value;" *newline*
1569     "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1570     "return value;" *newline*))
1571
1572 (define-builtin symbol-function (x)
1573   (js!selfcall
1574     "var symbol = " x ";" *newline*
1575     "var func = symbol.function;" *newline*
1576     "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1577     "return func;" *newline*))
1578
1579 (define-builtin symbol-plist (x)
1580   (concat "((" x ").plist || " (ls-compile nil) ")"))
1581
1582 (define-builtin lambda-code (x)
1583   (concat "(" x ").toString()"))
1584
1585
1586 (define-builtin eq    (x y) (js!bool (concat "(" x " === " y ")")))
1587 (define-builtin equal (x y) (js!bool (concat "(" x  " == " y ")")))
1588
1589 (define-builtin char-to-string (x)
1590   (type-check (("x" "number" x))
1591     "String.fromCharCode(x)"))
1592
1593 (define-builtin stringp (x)
1594   (js!bool (concat "(typeof(" x ") == \"string\")")))
1595
1596 (define-builtin string-upcase (x)
1597   (type-check (("x" "string" x))
1598     "x.toUpperCase()"))
1599
1600 (define-builtin string-length (x)
1601   (type-check (("x" "string" x))
1602     "x.length"))
1603
1604 (define-raw-builtin slice (string a &optional b)
1605   (js!selfcall
1606     "var str = " (ls-compile string) ";" *newline*
1607     "var a = " (ls-compile a) ";" *newline*
1608     "var b;" *newline*
1609     (if b
1610         (concat "b = " (ls-compile b) ";" *newline*)
1611         "")
1612     "return str.slice(a,b);" *newline*))
1613
1614 (define-builtin char (string index)
1615   (type-check (("string" "string" string)
1616                ("index" "number" index))
1617     "string.charCodeAt(index)"))
1618
1619 (define-builtin concat-two (string1 string2)
1620   (type-check (("string1" "string" string1)
1621                ("string2" "string" string2))
1622     "string1.concat(string2)"))
1623
1624 (define-raw-builtin funcall (func &rest args)
1625   (concat "(" (ls-compile func) ")("
1626           (join (mapcar #'ls-compile args)
1627                 ", ")
1628           ")"))
1629
1630 (define-raw-builtin apply (func &rest args)
1631   (if (null args)
1632       (concat "(" (ls-compile func) ")()")
1633       (let ((args (butlast args))
1634             (last (car (last args))))
1635         (js!selfcall
1636           "var f = " (ls-compile func) ";" *newline*
1637           "var args = [" (join (mapcar #'ls-compile args)
1638                                ", ")
1639           "];" *newline*
1640           "var tail = (" (ls-compile last) ");" *newline*
1641           "while (tail != " (ls-compile nil) "){" *newline*
1642           "    args.push(tail.car);" *newline*
1643           "    tail = tail.cdr;" *newline*
1644           "}" *newline*
1645           "return f.apply(this, args);" *newline*))))
1646
1647 (define-builtin js-eval (string)
1648   (type-check (("string" "string" string))
1649     "eval.apply(window, [string])"))
1650
1651 (define-builtin error (string)
1652   (js!selfcall "throw " string ";" *newline*))
1653
1654 (define-builtin new () "{}")
1655
1656 (define-builtin objectp (x)
1657   (js!bool (concat "(typeof (" x ") === 'object')")))
1658
1659 (define-builtin oget (object key)
1660   (js!selfcall
1661     "var tmp = " "(" object ")[" key "];" *newline*
1662     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1663
1664 (define-builtin oset (object key value)
1665   (concat "((" object ")[" key "] = " value ")"))
1666
1667 (define-builtin in (key object)
1668   (js!bool (concat "((" key ") in (" object "))")))
1669
1670 (define-builtin functionp (x)
1671   (js!bool (concat "(typeof " x " == 'function')")))
1672
1673 (define-builtin write-string (x)
1674   (type-check (("x" "string" x))
1675     "lisp.write(x)"))
1676
1677 (defun macro (x)
1678   (and (symbolp x)
1679        (let ((b (lookup-in-lexenv x *environment* 'function)))
1680          (and (eq (binding-type b) 'macro)
1681               b))))
1682
1683 (defun ls-macroexpand-1 (form)
1684   (let ((macro-binding (macro (car form))))
1685     (if macro-binding
1686         (let ((expander (binding-value macro-binding)))
1687           (when (listp expander)
1688             (let ((compiled (eval expander)))
1689               ;; The list representation are useful while
1690               ;; bootstrapping, as we can dump the definition of the
1691               ;; macros easily, but they are slow because we have to
1692               ;; evaluate them and compile them now and again. So, let
1693               ;; us replace the list representation version of the
1694               ;; function with the compiled one.
1695               ;;
1696               #+ecmalisp (set-binding-value macro-binding compiled)
1697               (setq expander compiled)))
1698           (apply expander (cdr form)))
1699         form)))
1700
1701 (defun compile-funcall (function args)
1702   (if (and (symbolp function)
1703            (claimp function 'function 'non-overridable))
1704       (concat (ls-compile `',function) ".function("
1705               (join (mapcar #'ls-compile args)
1706                     ", ")
1707               ")")
1708       (concat (ls-compile `#',function) "("
1709               (join (mapcar #'ls-compile args)
1710                     ", ")
1711               ")")))
1712
1713 (defun ls-compile-block (sexps &optional return-last-p)
1714   (if return-last-p
1715       (concat (ls-compile-block (butlast sexps))
1716               "return " (ls-compile (car (last sexps))) ";")
1717       (join-trailing
1718        (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
1719        (concat ";" *newline*))))
1720
1721 (defun ls-compile (sexp)
1722   (cond
1723     ((symbolp sexp)
1724      (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1725        (cond
1726          ((eq (binding-type b) 'lexical-variable)
1727           (binding-value b))
1728          ((or (keywordp sexp) (claimp sexp 'variable 'constant))
1729           (concat (ls-compile `',sexp) ".value"))
1730          (t
1731           (ls-compile `(symbol-value ',sexp))))))
1732     ((integerp sexp) (integer-to-string sexp))
1733     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1734     ((listp sexp)
1735      (let ((name (car sexp))
1736            (args (cdr sexp)))
1737        (cond
1738          ;; Special forms
1739          ((assoc name *compilations*)
1740           (let ((comp (second (assoc name *compilations*))))
1741             (apply comp args)))
1742          ;; Built-in functions
1743          ((and (assoc name *builtins*)
1744                (not (claimp name 'function 'notinline)))
1745           (let ((comp (second (assoc name *builtins*))))
1746             (apply comp args)))
1747          (t
1748           (if (macro name)
1749               (ls-compile (ls-macroexpand-1 sexp))
1750               (compile-funcall name args))))))))
1751
1752 (defun ls-compile-toplevel (sexp)
1753   (let ((*toplevel-compilations* nil))
1754     (cond
1755       ((and (consp sexp) (eq (car sexp) 'progn))
1756        (let ((subs (mapcar #'ls-compile-toplevel (cdr sexp))))
1757          (join (remove-if #'null-or-empty-p subs))))
1758       (t
1759        (let ((code (ls-compile sexp)))
1760          (concat (join-trailing (get-toplevel-compilations)
1761                                 (concat ";" *newline*))
1762                  (if code
1763                      (concat code ";" *newline*)
1764                      "")))))))
1765
1766
1767 ;;; Once we have the compiler, we define the runtime environment and
1768 ;;; interactive development (eval), which works calling the compiler
1769 ;;; and evaluating the Javascript result globally.
1770
1771 #+ecmalisp
1772 (progn
1773   (defmacro with-compilation-unit (&body body)
1774     `(prog1
1775          (progn
1776            (setq *compilation-unit-checks* nil)
1777            ,@body)
1778        (dolist (check *compilation-unit-checks*)
1779          (funcall check))))
1780
1781   (defun eval (x)
1782     (let ((code
1783            (with-compilation-unit
1784                (ls-compile-toplevel x))))
1785       (js-eval code)))
1786
1787   (export '(* *gensym-counter* *package* + - / 1+ 1- < <= = = > >= and append
1788             apply assoc atom block boundp boundp butlast caar cadddr
1789             caddr cadr car car case catch cdar cdddr cddr cdr cdr char
1790             char-code char= code-char cond cons consp copy-list decf
1791             declaim defparameter defun defvar digit-char-p disassemble
1792             documentation dolist dotimes ecase eq eql equal error eval
1793             every export fdefinition find-package find-symbol first
1794             fourth fset funcall function functionp gensym go identity
1795             in-package incf integerp integerp intern keywordp
1796             lambda-code last length let list-all-packages list listp
1797             make-package make-symbol mapcar member minusp mod nil not
1798             nth nthcdr null numberp or package-name package-use-list
1799             packagep plusp prin1-to-string print proclaim prog1 prog2
1800             pron push quote remove remove-if remove-if-not return
1801             return-from revappend reverse second set setq some
1802             string-upcase string string= stringp subseq
1803             symbol-function symbol-name symbol-package symbol-plist
1804             symbol-value symbolp t tagbody third throw truncate unless
1805             unwind-protect variable warn when write-line write-string
1806             zerop))
1807
1808   (setq *package* *user-package*)
1809
1810   (js-eval "var lisp")
1811   (js-vset "lisp" (new))
1812   (js-vset "lisp.read" #'ls-read-from-string)
1813   (js-vset "lisp.print" #'prin1-to-string)
1814   (js-vset "lisp.eval" #'eval)
1815   (js-vset "lisp.compile" #'ls-compile-toplevel)
1816   (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
1817   (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str))))
1818
1819   ;; Set the initial global environment to be equal to the host global
1820   ;; environment at this point of the compilation.
1821   (eval-when-compile
1822     (toplevel-compilation
1823      (ls-compile
1824       `(progn
1825          ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
1826                    *literal-symbols*)
1827          (setq *literal-symbols* ',*literal-symbols*)
1828          (setq *environment* ',*environment*)
1829          (setq *variable-counter* ,*variable-counter*)
1830          (setq *gensym-counter* ,*gensym-counter*)
1831          (setq *block-counter* ,*block-counter*)))))
1832
1833   (eval-when-compile
1834     (toplevel-compilation
1835      (ls-compile
1836       `(setq *literal-counter* ,*literal-counter*)))))
1837
1838
1839 ;;; Finally, we provide a couple of functions to easily bootstrap
1840 ;;; this. It just calls the compiler with this file as input.
1841
1842 #+common-lisp
1843 (progn
1844   (defun read-whole-file (filename)
1845     (with-open-file (in filename)
1846       (let ((seq (make-array (file-length in) :element-type 'character)))
1847         (read-sequence seq in)
1848         seq)))
1849
1850   (defun ls-compile-file (filename output)
1851     (setq *compilation-unit-checks* nil)
1852     (with-open-file (out output :direction :output :if-exists :supersede)
1853       (let* ((source (read-whole-file filename))
1854              (in (make-string-stream source)))
1855         (loop
1856            for x = (ls-read in)
1857            until (eq x *eof*)
1858            for compilation = (ls-compile-toplevel x)
1859            when (plusp (length compilation))
1860            do (write-string compilation out))
1861         (dolist (check *compilation-unit-checks*)
1862           (funcall check))
1863         (setq *compilation-unit-checks* nil))))
1864
1865   (defun bootstrap ()
1866     (setq *environment* (make-lexenv))
1867     (setq *literal-symbols* nil)
1868     (setq *variable-counter* 0
1869           *gensym-counter* 0
1870           *literal-counter* 0
1871           *block-counter* 0)
1872     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))