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