a8eb5727b09d52a390df8ded51b4ba52077eca2e
[jscl.git] / ecmalisp.lisp
1 ;;; ecmalisp.lisp ---
2
3 ;; Copyright (C) 2012 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 #+ecmalisp
25 (progn
26  (eval-when-compile
27    (%compile-defmacro 'defmacro
28                       '(lambda (name args &rest body)
29                         `(eval-when-compile
30                            (%compile-defmacro ',name
31                                               '(lambda ,(mapcar (lambda (x)
32                                                                   (if (eq x '&body)
33                                                                       '&rest
34                                                                       x))
35                                                                 args)
36                                                 ,@body))))))
37
38  (defmacro %defvar (name value)
39    `(progn
40       (eval-when-compile
41         (%compile-defvar ',name))
42       (setq ,name ,value)))
43
44   (defmacro defvar (name &optional value)
45     `(%defvar ,name ,value))
46
47   (defmacro named-lambda (name args &rest body)
48     (let ((x (gensym "FN")))
49       `(let ((,x (lambda ,args ,@body)))
50          (set ,x "fname" ,name)
51          ,x)))
52
53   (defmacro %defun (name args &rest body)
54     `(progn
55        (eval-when-compile
56          (%compile-defun ',name))
57        (fsetq ,name (named-lambda ,(symbol-name name) ,args
58                       ,@body))))
59
60   (defmacro defun (name args &rest body)
61     `(%defun ,name ,args ,@body))
62
63  (defvar *package* (new))
64
65  (defvar nil (make-symbol "NIL"))
66  (set *package* "NIL" nil)
67
68  (defvar t (make-symbol "T"))
69  (set *package* "T" t)
70
71  (defun null (x)
72    (eq x nil))
73
74  (defmacro return (value)
75    `(return-from nil ,value))
76
77  (defun internp (name)
78    (in name *package*))
79
80  (defun intern (name)
81    (if (internp name)
82        (get *package* name)
83        (set *package* name (make-symbol name))))
84
85  (defun find-symbol (name)
86    (get *package* name))
87
88  (defvar *gensym-counter* 0)
89  (defun gensym (&optional (prefix "G"))
90    (setq *gensym-counter* (+ *gensym-counter* 1))
91    (make-symbol (concat-two prefix (integer-to-string *gensym-counter*))))
92
93  ;; Basic functions
94  (defun = (x y) (= x y))
95  (defun + (x y) (+ x y))
96  (defun - (x y) (- x y))
97  (defun * (x y) (* x y))
98  (defun / (x y) (/ x y))
99  (defun 1+ (x) (+ x 1))
100  (defun 1- (x) (- x 1))
101  (defun zerop (x) (= x 0))
102  (defun truncate (x y) (floor (/ x y)))
103
104  (defun eql (x y) (eq x y))
105
106  (defun not (x) (if x nil t))
107
108  (defun cons (x y ) (cons x y))
109  (defun consp (x) (consp x))
110  (defun car (x) (car x))
111  (defun cdr (x) (cdr x))
112  (defun caar (x) (car (car x)))
113  (defun cadr (x) (car (cdr x)))
114  (defun cdar (x) (cdr (car x)))
115  (defun cddr (x) (cdr (cdr x)))
116  (defun caddr (x) (car (cdr (cdr x))))
117  (defun cdddr (x) (cdr (cdr (cdr x))))
118  (defun cadddr (x) (car (cdr (cdr (cdr x)))))
119  (defun first (x) (car x))
120  (defun second (x) (cadr x))
121  (defun third (x) (caddr x))
122  (defun fourth (x) (cadddr x))
123
124  (defun list (&rest args) args)
125  (defun atom (x)
126    (not (consp x)))
127
128  ;; Basic macros
129
130   (defmacro incf (x &optional (delta 1))
131     `(setq ,x (+ ,x ,delta)))
132
133   (defmacro decf (x &optional (delta 1))
134     `(setq ,x (- ,x ,delta)))
135
136  (defmacro push (x place)
137    `(setq ,place (cons ,x ,place)))
138
139  (defmacro when (condition &body body)
140    `(if ,condition (progn ,@body) nil))
141
142  (defmacro unless (condition &body body)
143    `(if ,condition nil (progn ,@body)))
144
145  (defmacro dolist (iter &body body)
146    (let ((var (first iter))
147          (g!list (gensym)))
148      `(let ((,g!list ,(second iter))
149             (,var nil))
150         (while ,g!list
151           (setq ,var (car ,g!list))
152           ,@body
153           (setq ,g!list (cdr ,g!list)))
154         ,(third iter))))
155
156  (defmacro dotimes (iter &body body)
157    (let ((g!to (gensym))
158          (var (first iter))
159          (to (second iter))
160          (result (third iter)))
161      `(let ((,var 0)
162             (,g!to ,to))
163         (while (< ,var ,g!to)
164           ,@body
165           (incf ,var))
166         ,result)))
167
168  (defmacro cond (&rest clausules)
169    (if (null clausules)
170        nil
171        (if (eq (caar clausules) t)
172            `(progn ,@(cdar clausules))
173            `(if ,(caar clausules)
174                 (progn ,@(cdar clausules))
175                 (cond ,@(cdr clausules))))))
176
177  (defmacro case (form &rest clausules)
178    (let ((!form (gensym)))
179      `(let ((,!form ,form))
180         (cond
181           ,@(mapcar (lambda (clausule)
182                       (if (eq (car clausule) t)
183                           clausule
184                           `((eql ,!form ',(car clausule))
185                             ,@(cdr clausule))))
186                     clausules)))))
187
188   (defmacro ecase (form &rest clausules)
189     `(case ,form
190        ,@(append
191           clausules
192           `((t
193              (error "ECASE expression failed."))))))
194
195   (defmacro and (&rest forms)
196     (cond
197       ((null forms)
198        t)
199       ((null (cdr forms))
200        (car forms))
201       (t
202        `(if ,(car forms)
203             (and ,@(cdr forms))
204             nil))))
205
206   (defmacro or (&rest forms)
207     (cond
208       ((null forms)
209        nil)
210       ((null (cdr forms))
211        (car forms))
212       (t
213        (let ((g (gensym)))
214          `(let ((,g ,(car forms)))
215             (if ,g ,g (or ,@(cdr forms))))))))
216
217    (defmacro prog1 (form &body body)
218    (let ((value (gensym)))
219      `(let ((,value ,form))
220         ,@body
221         ,value))))
222
223 ;;; This couple of helper functions will be defined in both Common
224 ;;; Lisp and in Ecmalisp.
225 (defun ensure-list (x)
226   (if (listp x)
227       x
228       (list x)))
229
230 (defun !reduce (func list initial)
231   (if (null list)
232       initial
233       (!reduce func
234                (cdr list)
235                (funcall func initial (car list)))))
236
237 ;;; Go on growing the Lisp language in Ecmalisp, with more high
238 ;;; level utilities as well as correct versions of other
239 ;;; constructions.
240 #+ecmalisp
241 (progn
242   (defmacro defun (name args &body body)
243     `(progn
244        (%defun ,name ,args ,@body)
245        ',name))
246
247   (defmacro defvar (name &optional value)
248     `(progn
249        (%defvar ,name ,value)
250        ',name))
251
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 reverse-aux (list acc)
262     (if (null list)
263         acc
264         (reverse-aux (cdr list) (cons (car list) acc))))
265
266   (defun reverse (list)
267     (reverse-aux list '()))
268
269   (defun list-length (list)
270     (let ((l 0))
271       (while (not (null list))
272         (incf l)
273         (setq list (cdr list)))
274       l))
275
276   (defun length (seq)
277     (if (stringp seq)
278         (string-length seq)
279         (list-length seq)))
280
281   (defun concat-two (s1 s2)
282     (concat-two s1 s2))
283
284   (defun mapcar (func list)
285     (if (null list)
286         '()
287         (cons (funcall func (car list))
288               (mapcar func (cdr list)))))
289
290   (defun identity (x) x)
291
292   (defun copy-list (x)
293     (mapcar #'identity x))
294
295   (defun code-char (x) x)
296   (defun char-code (x) x)
297   (defun char= (x y) (= x y))
298
299   (defun integerp (x)
300     (and (numberp x) (= (floor x) x)))
301
302   (defun plusp (x) (< 0 x))
303   (defun minusp (x) (< x 0))
304
305   (defun listp (x)
306     (or (consp x) (null x)))
307
308   (defun nth (n list)
309     (cond
310       ((null list) list)
311       ((zerop n) (car list))
312       (t (nth (1- n) (cdr list)))))
313
314   (defun last (x)
315     (if (consp (cdr x))
316         (last (cdr x))
317         x))
318
319   (defun butlast (x)
320     (and (consp (cdr x))
321          (cons (car x) (butlast (cdr x)))))
322
323   (defun member (x list)
324     (cond
325       ((null list)
326        nil)
327       ((eql x (car list))
328        list)
329       (t
330        (member x (cdr list)))))
331
332   (defun remove (x list)
333     (cond
334       ((null list)
335        nil)
336       ((eql x (car list))
337        (remove x (cdr list)))
338       (t
339        (cons (car list) (remove x (cdr list))))))
340
341   (defun remove-if (func list)
342     (cond
343       ((null list)
344        nil)
345       ((funcall func (car list))
346        (remove-if func (cdr list)))
347       (t
348        (cons (car list) (remove-if func (cdr list))))))
349
350   (defun remove-if-not (func list)
351     (cond
352       ((null list)
353        nil)
354       ((funcall func (car list))
355        (cons (car list) (remove-if-not func (cdr list))))
356       (t
357        (remove-if-not func (cdr list)))))
358
359   (defun digit-char-p (x)
360     (if (and (<= #\0 x) (<= x #\9))
361         (- x #\0)
362         nil))
363
364   (defun subseq (seq a &optional b)
365     (cond
366      ((stringp seq)
367       (if b
368           (slice seq a b)
369           (slice seq a)))
370      (t
371       (error "Unsupported argument."))))
372
373   (defun parse-integer (string)
374     (let ((value 0)
375           (index 0)
376           (size (length string)))
377       (while (< index size)
378         (setq value (+ (* value 10) (digit-char-p (char string index))))
379         (incf index))
380       value))
381
382   (defun every (function seq)
383     ;; string
384     (let ((ret t)
385           (index 0)
386           (size (length seq)))
387       (while (and ret (< index size))
388         (unless (funcall function (char seq index))
389           (setq ret nil))
390         (incf index))
391       ret))
392
393   (defun assoc (x alist)
394     (let ((found nil))
395       (while (and alist (not found))
396         (if (eql x (caar alist))
397             (setq found t)
398             (setq alist (cdr alist))))
399       (car alist)))
400
401   (defun string= (s1 s2)
402     (equal s1 s2)))
403
404
405 ;;; The compiler offers some primitives and special forms which are
406 ;;; not found in Common Lisp, for instance, while. So, we grow Common
407 ;;; Lisp a bit to it can execute the rest of the file.
408 #+common-lisp
409 (progn
410   (defmacro while (condition &body body)
411     `(do ()
412          ((not ,condition))
413        ,@body))
414
415   (defmacro eval-when-compile (&body body)
416     `(eval-when (:compile-toplevel :load-toplevel :execute)
417        ,@body))
418
419   (defun concat-two (s1 s2)
420     (concatenate 'string s1 s2))
421
422   (defun setcar (cons new)
423     (setf (car cons) new))
424   (defun setcdr (cons new)
425     (setf (cdr cons) new)))
426
427 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
428 ;;; from here, this code will compile on both. We define some helper
429 ;;; functions now for string manipulation and so on. They will be
430 ;;; useful in the compiler, mostly.
431
432 (defvar *newline* (string (code-char 10)))
433
434 (defun concat (&rest strs)
435   (!reduce #'concat-two strs ""))
436
437 ;;; Concatenate a list of strings, with a separator
438 (defun join (list &optional (separator ""))
439   (cond
440     ((null list)
441      "")
442     ((null (cdr list))
443      (car list))
444     (t
445      (concat (car list)
446              separator
447              (join (cdr list) separator)))))
448
449 (defun join-trailing (list &optional (separator ""))
450   (if (null list)
451       ""
452       (concat (car list) separator (join-trailing (cdr list) separator))))
453
454 ;;; Like CONCAT, but prefix each line with four spaces.
455 (defun indent (&rest string)
456   (let ((input (join string)))
457     (let ((output "")
458           (index 0)
459           (size (length input)))
460       (when (plusp size)
461         (setq output "    "))
462       (while (< index size)
463         (setq output
464               (concat output
465                       (if (and (char= (char input index) #\newline)
466                                (< index (1- size))
467                                (not (char= (char input (1+ index)) #\newline)))
468                           (concat (string #\newline) "    ")
469                           (subseq input index (1+ index)))))
470         (incf index))
471       output)))
472
473 (defun integer-to-string (x)
474   (cond
475     ((zerop x)
476      "0")
477     ((minusp x)
478      (concat "-" (integer-to-string (- 0 x))))
479     (t
480      (let ((digits nil))
481        (while (not (zerop x))
482          (push (mod x 10) digits)
483          (setq x (truncate x 10)))
484        (join (mapcar (lambda (d) (string (char "0123456789" d)))
485                      digits))))))
486
487 ;;; Printer
488
489 #+ecmalisp
490 (progn
491   (defun print-to-string (form)
492     (cond
493       ((symbolp form) (symbol-name form))
494       ((integerp form) (integer-to-string form))
495       ((stringp form) (concat "\"" (escape-string form) "\""))
496       ((functionp form)
497        (let ((name (get form "fname")))
498          (if name
499              (concat "#<FUNCTION " name ">")
500              (concat "#<FUNCTION>"))))
501       ((listp form)
502        (concat "("
503                (join-trailing (mapcar #'print-to-string (butlast form)) " ")
504                (let ((last (last form)))
505                  (if (null (cdr last))
506                      (print-to-string (car last))
507                      (concat (print-to-string (car last)) " . " (print-to-string (cdr last)))))
508                ")"))))
509
510   (defun write-line (x)
511     (write-string x)
512     (write-string *newline*)
513     x)
514
515   (defun print (x)
516     (write-line (print-to-string x))
517     x))
518
519
520 ;;;; Reader
521
522 ;;; The Lisp reader, parse strings and return Lisp objects. The main
523 ;;; entry points are `ls-read' and `ls-read-from-string'.
524
525 (defun make-string-stream (string)
526   (cons string 0))
527
528 (defun %peek-char (stream)
529   (and (< (cdr stream) (length (car stream)))
530        (char (car stream) (cdr stream))))
531
532 (defun %read-char (stream)
533   (and (< (cdr stream) (length (car stream)))
534        (prog1 (char (car stream) (cdr stream))
535          (setcdr stream (1+ (cdr stream))))))
536
537 (defun whitespacep (ch)
538   (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
539
540 (defun skip-whitespaces (stream)
541   (let (ch)
542     (setq ch (%peek-char stream))
543     (while (and ch (whitespacep ch))
544       (%read-char stream)
545       (setq ch (%peek-char stream)))))
546
547 (defun terminalp (ch)
548   (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
549
550 (defun read-until (stream func)
551   (let ((string "")
552         (ch))
553     (setq ch (%peek-char stream))
554     (while (and ch (not (funcall func ch)))
555       (setq string (concat string (string ch)))
556       (%read-char stream)
557       (setq ch (%peek-char stream)))
558     string))
559
560 (defun skip-whitespaces-and-comments (stream)
561   (let (ch)
562     (skip-whitespaces stream)
563     (setq ch (%peek-char stream))
564     (while (and ch (char= ch #\;))
565       (read-until stream (lambda (x) (char= x #\newline)))
566       (skip-whitespaces stream)
567       (setq ch (%peek-char stream)))))
568
569 (defun %read-list (stream)
570   (skip-whitespaces-and-comments stream)
571   (let ((ch (%peek-char stream)))
572     (cond
573       ((null ch)
574        (error "Unspected EOF"))
575       ((char= ch #\))
576        (%read-char stream)
577        nil)
578       ((char= ch #\.)
579        (%read-char stream)
580        (prog1 (ls-read stream)
581          (skip-whitespaces-and-comments stream)
582          (unless (char= (%read-char stream) #\))
583            (error "')' was expected."))))
584       (t
585        (cons (ls-read stream) (%read-list stream))))))
586
587 (defun read-string (stream)
588   (let ((string "")
589         (ch nil))
590     (setq ch (%read-char stream))
591     (while (not (eql ch #\"))
592       (when (null ch)
593         (error "Unexpected EOF"))
594       (when (eql ch #\\)
595         (setq ch (%read-char stream)))
596       (setq string (concat string (string ch)))
597       (setq ch (%read-char stream)))
598     string))
599
600 (defun read-sharp (stream)
601   (%read-char stream)
602   (ecase (%read-char stream)
603     (#\'
604      (list 'function (ls-read stream)))
605     (#\\
606      (let ((cname
607             (concat (string (%read-char stream))
608                     (read-until stream #'terminalp))))
609        (cond
610          ((string= cname "space") (char-code #\space))
611          ((string= cname "tab") (char-code #\tab))
612          ((string= cname "newline") (char-code #\newline))
613          (t (char-code (char cname 0))))))
614     (#\+
615      (let ((feature (read-until stream #'terminalp)))
616        (cond
617          ((string= feature "common-lisp")
618           (ls-read stream)              ;ignore
619           (ls-read stream))
620          ((string= feature "ecmalisp")
621           (ls-read stream))
622          (t
623           (error "Unknown reader form.")))))))
624
625 (defvar *eof* (make-symbol "EOF"))
626 (defun ls-read (stream)
627   (skip-whitespaces-and-comments stream)
628   (let ((ch (%peek-char stream)))
629     (cond
630       ((null ch)
631        *eof*)
632       ((char= ch #\()
633        (%read-char stream)
634        (%read-list stream))
635       ((char= ch #\')
636        (%read-char stream)
637        (list 'quote (ls-read stream)))
638       ((char= ch #\`)
639        (%read-char stream)
640        (list 'backquote (ls-read stream)))
641       ((char= ch #\")
642        (%read-char stream)
643        (read-string stream))
644       ((char= ch #\,)
645        (%read-char stream)
646        (if (eql (%peek-char stream) #\@)
647            (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
648            (list 'unquote (ls-read stream))))
649       ((char= ch #\#)
650        (read-sharp stream))
651       (t
652        (let ((string (read-until stream #'terminalp)))
653          (if (every #'digit-char-p string)
654              (parse-integer string)
655              (intern (string-upcase string))))))))
656
657 (defun ls-read-from-string (string)
658   (ls-read (make-string-stream string)))
659
660
661 ;;;; Compiler
662
663 ;;; Translate the Lisp code to Javascript. It will compile the special
664 ;;; forms. Some primitive functions are compiled as special forms
665 ;;; too. The respective real functions are defined in the target (see
666 ;;; the beginning of this file) as well as some primitive functions.
667
668 (defvar *compilation-unit-checks* '())
669
670 (defun make-binding (name type js declared)
671   (list name type js declared))
672
673 (defun binding-name (b) (first b))
674 (defun binding-type (b) (second b))
675 (defun binding-translation (b) (third b))
676 (defun binding-declared (b)
677   (and b (fourth b)))
678 (defun mark-binding-as-declared (b)
679   (setcar (cdddr b) t))
680
681 (defun make-lexenv ()
682   (list nil nil nil))
683
684 (defun copy-lexenv (lexenv)
685   (copy-list lexenv))
686
687 (defun push-to-lexenv (binding lexenv namespace)
688   (ecase namespace
689     (variable
690      (setcar lexenv (cons binding (car lexenv))))
691     (function
692      (setcar (cdr lexenv) (cons binding (cadr lexenv))))
693     (block
694      (setcar (cddr lexenv) (cons binding (caddr lexenv))))))
695
696 (defun extend-lexenv (binding lexenv namespace)
697   (let ((env (copy-lexenv lexenv)))
698     (push-to-lexenv binding env namespace)
699     env))
700
701 (defun lookup-in-lexenv (name lexenv namespace)
702   (assoc name (ecase namespace
703                 (variable (first lexenv))
704                 (function (second lexenv))
705                 (block (third lexenv)))))
706
707 (defvar *environment* (make-lexenv))
708
709 (defun clear-undeclared-global-bindings ()
710   (let ((variables (first *environment*))
711         (functions (second *environment*)))
712     (setq *environment* (list variables functions (third *environment*)))))
713
714
715 (defvar *variable-counter* 0)
716 (defun gvarname (symbol)
717   (concat "v" (integer-to-string (incf *variable-counter*))))
718
719 (defun lookup-variable (symbol env)
720   (or (lookup-in-lexenv symbol env 'variable)
721       (lookup-in-lexenv symbol *environment* 'variable)
722       (let ((name (symbol-name symbol))
723             (binding (make-binding symbol 'variable (gvarname symbol) nil)))
724         (push-to-lexenv binding *environment* 'variable)
725         (push (lambda ()
726                 (unless (lookup-in-lexenv symbol *environment* 'variable)
727                   (error (concat "Undefined variable `" name "'"))))
728               *compilation-unit-checks*)
729         binding)))
730
731 (defun lookup-variable-translation (symbol env)
732   (binding-translation (lookup-variable symbol env)))
733
734 (defun extend-local-env (args env)
735   (let ((new (copy-lexenv env)))
736     (dolist (symbol args new)
737       (let ((b (make-binding symbol 'variable (gvarname symbol) t)))
738         (push-to-lexenv b new 'variable)))))
739
740 (defvar *function-counter* 0)
741 (defun lookup-function (symbol env)
742   (or (lookup-in-lexenv symbol env 'function)
743       (lookup-in-lexenv symbol *environment* 'function)
744       (let ((name (symbol-name symbol))
745             (binding
746              (make-binding symbol
747                            'function
748                            (concat "f" (integer-to-string (incf *function-counter*)))
749                            nil)))
750         (push-to-lexenv binding *environment* 'function)
751         (push (lambda ()
752                 (unless (binding-declared (lookup-in-lexenv symbol *environment* 'function))
753                   (error (concat "Undefined function `" name "'"))))
754               *compilation-unit-checks*)
755         binding)))
756
757 (defun lookup-function-translation (symbol env)
758   (binding-translation (lookup-function symbol env)))
759
760 (defvar *toplevel-compilations* nil)
761
762 (defun %compile-defvar (name)
763   (let ((b (lookup-variable name *environment*)))
764     (mark-binding-as-declared b)
765     (push (concat "var " (binding-translation b)) *toplevel-compilations*)))
766
767 (defun %compile-defun (name)
768   (let ((b (lookup-function name *environment*)))
769     (mark-binding-as-declared b)
770     (push (concat "var " (binding-translation b)) *toplevel-compilations*)))
771
772 (defun %compile-defmacro (name lambda)
773   (push-to-lexenv (make-binding name 'macro lambda t) *environment* 'function))
774
775 (defvar *compilations* nil)
776
777 (defun ls-compile-block (sexps env)
778   (join-trailing
779    (remove-if (lambda (x)
780                 (or (null x)
781                     (and (stringp x)
782                          (zerop (length x)))))
783               (mapcar (lambda (x) (ls-compile x env))  sexps))
784    (concat ";" *newline*)))
785
786 (defmacro define-compilation (name args &body body)
787   ;; Creates a new primitive `name' with parameters args and
788   ;; @body. The body can access to the local environment through the
789   ;; variable ENV.
790   `(push (list ',name (lambda (env ,@args) ,@body))
791          *compilations*))
792
793 (define-compilation if (condition true false)
794   (concat "("
795           (ls-compile condition env) " !== " (ls-compile nil)
796           " ? "
797           (ls-compile true env)
798           " : "
799           (ls-compile false env)
800           ")"))
801
802
803 (defvar *lambda-list-keywords* '(&optional &rest))
804
805 (defun list-until-keyword (list)
806   (if (or (null list) (member (car list) *lambda-list-keywords*))
807       nil
808       (cons (car list) (list-until-keyword (cdr list)))))
809
810 (defun lambda-list-required-arguments (lambda-list)
811   (list-until-keyword lambda-list))
812
813 (defun lambda-list-optional-arguments-with-default (lambda-list)
814   (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
815
816 (defun lambda-list-optional-arguments (lambda-list)
817   (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
818
819 (defun lambda-list-rest-argument (lambda-list)
820   (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
821     (when (cdr rest)
822       (error "Bad lambda-list"))
823     (car rest)))
824
825 (define-compilation lambda (lambda-list &rest body)
826   (let ((required-arguments (lambda-list-required-arguments lambda-list))
827         (optional-arguments (lambda-list-optional-arguments lambda-list))
828         (rest-argument (lambda-list-rest-argument lambda-list)))
829     (let ((n-required-arguments (length required-arguments))
830           (n-optional-arguments (length optional-arguments))
831           (new-env (extend-local-env
832                     (append (ensure-list rest-argument)
833                             required-arguments
834                             optional-arguments)
835                     env)))
836       (concat "(function ("
837               (join (mapcar (lambda (x)
838                               (lookup-variable-translation x new-env))
839                             (append required-arguments optional-arguments))
840                     ",")
841               "){" *newline*
842               ;; Check number of arguments
843               (indent
844                (if required-arguments
845                    (concat "if (arguments.length < " (integer-to-string n-required-arguments)
846                            ") throw 'too few arguments';" *newline*)
847                    "")
848                (if (not rest-argument)
849                    (concat "if (arguments.length > "
850                            (integer-to-string (+ n-required-arguments n-optional-arguments))
851                            ") throw 'too many arguments';" *newline*)
852                    "")
853                ;; Optional arguments
854                (if optional-arguments
855                    (concat "switch(arguments.length){" *newline*
856                            (let ((optional-and-defaults
857                                   (lambda-list-optional-arguments-with-default lambda-list))
858                                  (cases nil)
859                                  (idx 0))
860                              (progn
861                                (while (< idx n-optional-arguments)
862                                  (let ((arg (nth idx optional-and-defaults)))
863                                    (push (concat "case "
864                                                  (integer-to-string (+ idx n-required-arguments)) ":" *newline*
865                                                  (lookup-variable-translation (car arg) new-env)
866                                                  "="
867                                                  (ls-compile (cadr arg) new-env)
868                                                  ";" *newline*)
869                                          cases)
870                                    (incf idx)))
871                                     (push (concat "default: break;" *newline*) cases)
872                                     (join (reverse cases))))
873                            "}" *newline*)
874                    "")
875                ;; &rest/&body argument
876                (if rest-argument
877                    (let ((js!rest (lookup-variable-translation rest-argument new-env)))
878                      (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
879                              "for (var i = arguments.length-1; i>="
880                              (integer-to-string (+ n-required-arguments n-optional-arguments))
881                              "; i--)" *newline*
882                              (indent js!rest " = "
883                                      "{car: arguments[i], cdr: ") js!rest "};"
884                                      *newline*))
885                    "")
886                ;; Body
887                (concat (ls-compile-block (butlast body) new-env)
888                        "return " (ls-compile (car (last body)) new-env) ";")) *newline*
889               "})"))))
890
891 (define-compilation fsetq (var val)
892   (concat (lookup-function-translation var env)
893           " = "
894           (ls-compile val env)))
895
896 (define-compilation setq (var val)
897   (concat (lookup-variable-translation var env)
898           " = "
899            (ls-compile val env)))
900
901 ;;; Literals
902 (defun escape-string (string)
903   (let ((output "")
904         (index 0)
905         (size (length string)))
906     (while (< index size)
907       (let ((ch (char string index)))
908         (when (or (char= ch #\") (char= ch #\\))
909           (setq output (concat output "\\")))
910         (when (or (char= ch #\newline))
911           (setq output (concat output "\\"))
912           (setq ch #\n))
913         (setq output (concat output (string ch))))
914       (incf index))
915     output))
916
917 (defun literal->js (sexp)
918   (cond
919     ((integerp sexp) (integer-to-string sexp))
920     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
921     ((symbolp sexp) (ls-compile `(intern ,(escape-string (symbol-name sexp))) *environment*))
922     ((consp sexp) (concat "{car: "
923                           (literal->js (car sexp))
924                           ", cdr: "
925                           (literal->js (cdr sexp)) "}"))))
926
927 (defvar *literal-counter* 0)
928 (defun literal (form)
929   (let ((var (concat "l" (integer-to-string (incf *literal-counter*)))))
930     (push (concat "var " var " = " (literal->js form)) *toplevel-compilations*)
931     var))
932
933 (define-compilation quote (sexp)
934   (literal sexp))
935
936 (define-compilation while (pred &rest body)
937   (concat "(function(){" *newline*
938           (indent "while("
939                   (ls-compile pred env)
940                   " !== "
941                   (ls-compile nil) "){" *newline*
942                   (indent (ls-compile-block body env)))
943           "}})()"))
944
945 (define-compilation function (x)
946   (cond
947     ((and (listp x) (eq (car x) 'lambda))
948      (ls-compile x env))
949     ((symbolp x)
950      (lookup-function-translation x env))))
951
952 (define-compilation eval-when-compile (&rest body)
953   (eval (cons 'progn body))
954   "")
955
956 (defmacro define-transformation (name args form)
957   `(define-compilation ,name ,args
958      (ls-compile ,form env)))
959
960 (define-compilation progn (&rest body)
961   (concat "(function(){" *newline*
962           (indent (ls-compile-block (butlast body) env)
963                   "return " (ls-compile (car (last body)) env) ";" *newline*)
964           "})()"))
965
966 (define-compilation let (bindings &rest body)
967   (let ((bindings (mapcar #'ensure-list bindings)))
968     (let ((variables (mapcar #'first bindings))
969           (values    (mapcar #'second bindings)))
970       (let ((new-env (extend-local-env variables env)))
971         (concat "(function("
972                 (join (mapcar (lambda (x)
973                                 (lookup-variable-translation x new-env))
974                               variables)
975                       ",")
976                 "){" *newline*
977                 (indent (ls-compile-block (butlast body) new-env)
978                         "return " (ls-compile (car (last body)) new-env)
979                         ";" *newline*)
980                 "})(" (join (mapcar (lambda (x) (ls-compile x env))
981                                     values)
982                             ",")
983                 ")")))))
984
985
986 (defvar *block-counter* 0)
987
988 (define-compilation block (name &rest body)
989   (let ((tr (integer-to-string (incf *block-counter*))))
990     (let ((b (make-binding name 'block tr t)))
991       (concat "(function(){" *newline*
992               (indent "try {" *newline*
993                       (indent "return " (ls-compile `(progn ,@body)
994                                                     (extend-lexenv b env 'block))) ";" *newline*
995                       "}" *newline*
996                       "catch (cf){" *newline*
997                       "    if (cf.type == 'block' && cf.id == " tr ")" *newline*
998                       "        return cf.value;" *newline*
999                       "    else" *newline*
1000                       "        throw cf;" *newline*
1001                       "}" *newline*)
1002               "})()" *newline*))))
1003
1004 (define-compilation return-from (name &optional value)
1005   (let ((b (lookup-in-lexenv name env 'block)))
1006     (if b
1007         (concat "(function(){ throw ({"
1008                 "type: 'block', "
1009                 "id: " (binding-translation b) ", "
1010                 "value: " (ls-compile value env) ", "
1011                 "message: 'Return from unknown block " (symbol-name name) ".'"
1012                 "})})()")
1013         (error (concat "Unknown block `" (symbol-name name) "'.")))))
1014
1015 ;;; A little backquote implementation without optimizations of any
1016 ;;; kind for ecmalisp.
1017 (defun backquote-expand-1 (form)
1018   (cond
1019     ((symbolp form)
1020      (list 'quote form))
1021     ((atom form)
1022      form)
1023     ((eq (car form) 'unquote)
1024      (car form))
1025     ((eq (car form) 'backquote)
1026      (backquote-expand-1 (backquote-expand-1 (cadr form))))
1027     (t
1028      (cons 'append
1029            (mapcar (lambda (s)
1030                      (cond
1031                        ((and (listp s) (eq (car s) 'unquote))
1032                         (list 'list (cadr s)))
1033                        ((and (listp s) (eq (car s) 'unquote-splicing))
1034                         (cadr s))
1035                        (t
1036                         (list 'list (backquote-expand-1 s)))))
1037                    form)))))
1038
1039 (defun backquote-expand (form)
1040   (if (and (listp form) (eq (car form) 'backquote))
1041       (backquote-expand-1 (cadr form))
1042       form))
1043
1044 (defmacro backquote (form)
1045   (backquote-expand-1 form))
1046
1047 (define-transformation backquote (form)
1048   (backquote-expand-1 form))
1049
1050 ;;; Primitives
1051
1052 (defmacro define-builtin (name args &body body)
1053   `(define-compilation ,name ,args
1054      (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg env))) args)
1055        ,@body)))
1056
1057 (defun compile-bool (x)
1058   (concat "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
1059
1060 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1061 (defmacro type-check (decls &body body)
1062   `(concat "(function(){" *newline*
1063            (indent ,@(mapcar (lambda (decl)
1064                                `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1065                              decls)
1066
1067                    ,@(mapcar (lambda (decl)
1068                                `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1069                                         (indent "throw 'The value ' + "
1070                                                 ,(first decl)
1071                                                 " + ' is not a type "
1072                                                 ,(second decl)
1073                                                 ".';"
1074                                                 *newline*)))
1075                              decls)
1076                    (concat "return " (progn ,@body) ";" *newline*))
1077            "})()"))
1078
1079 (defun num-op-num (x op y)
1080   (type-check (("x" "number" x) ("y" "number" y))
1081     (concat "x" op "y")))
1082
1083 (define-builtin + (x y) (num-op-num x "+" y))
1084 (define-builtin - (x y) (num-op-num x "-" y))
1085 (define-builtin * (x y) (num-op-num x "*" y))
1086 (define-builtin / (x y) (num-op-num x "/" y))
1087
1088 (define-builtin mod (x y) (num-op-num x "%" y))
1089
1090 (define-builtin < (x y)  (compile-bool (num-op-num x "<" y)))
1091 (define-builtin > (x y)  (compile-bool (num-op-num x ">" y)))
1092 (define-builtin = (x y)  (compile-bool (num-op-num x "==" y)))
1093 (define-builtin <= (x y) (compile-bool (num-op-num x "<=" y)))
1094 (define-builtin >= (x y) (compile-bool (num-op-num x ">=" y)))
1095
1096 (define-builtin numberp (x)
1097   (compile-bool (concat "(typeof (" x ") == \"number\")")))
1098
1099 (define-builtin floor (x)
1100   (type-check (("x" "number" x))
1101     "Math.floor(x)"))
1102
1103 (define-builtin cons (x y) (concat "({car: " x ", cdr: " y "})"))
1104 (define-builtin consp (x)
1105   (compile-bool
1106    (concat "(function(){" *newline*
1107            (indent "var tmp = " x ";" *newline*
1108                    "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)
1109            "})()")))
1110
1111 (define-builtin car (x)
1112   (concat "(function(){" *newline*
1113           (indent "var tmp = " x ";" *newline*
1114                   "return tmp === " (ls-compile nil)
1115                   "? " (ls-compile nil)
1116                   ": tmp.car;" *newline*)
1117           "})()"))
1118
1119 (define-builtin cdr (x)
1120   (concat "(function(){" *newline*
1121           (indent "var tmp = " x ";" *newline*
1122                   "return tmp === " (ls-compile nil) "? "
1123                   (ls-compile nil)
1124                   ": tmp.cdr;" *newline*)
1125           "})()"))
1126
1127 (define-builtin setcar (x new)
1128   (type-check (("x" "object" x))
1129     (concat "(x.car = " new ")")))
1130
1131 (define-builtin setcdr (x new)
1132   (type-check (("x" "object" x))
1133     (concat "(x.cdr = " new ")")))
1134
1135 (define-builtin symbolp (x)
1136   (compile-bool
1137    (concat "(function(){" *newline*
1138            (indent "var tmp = " x ";" *newline*
1139                    "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)
1140            "})()")))
1141
1142 (define-builtin make-symbol (name)
1143   (type-check (("name" "string" name))
1144     "({name: name})"))
1145
1146 (define-builtin symbol-name (x)
1147   (concat "(" x ").name"))
1148
1149 (define-builtin eq    (x y) (compile-bool (concat "(" x " === " y ")")))
1150 (define-builtin equal (x y) (compile-bool (concat "(" x  " == " y ")")))
1151
1152 (define-builtin string (x)
1153   (type-check (("x" "number" x))
1154     "String.fromCharCode(x)"))
1155
1156 (define-builtin stringp (x)
1157   (compile-bool (concat "(typeof(" x ") == \"string\")")))
1158
1159 (define-builtin string-upcase (x)
1160   (type-check (("x" "string" x))
1161     "x.toUpperCase()"))
1162
1163 (define-builtin string-length (x)
1164   (type-check (("x" "string" x))
1165     "x.length"))
1166
1167 (define-compilation slice (string a &optional b)
1168   (concat "(function(){" *newline*
1169           (indent "var str = " (ls-compile string env) ";" *newline*
1170                   "var a = " (ls-compile a env) ";" *newline*
1171                   "var b;" *newline*
1172                   (if b
1173                       (concat "b = " (ls-compile b env) ";" *newline*)
1174                       "")
1175                   "return str.slice(a,b);" *newline*)
1176           "})()"))
1177
1178 (define-builtin char (string index)
1179   (type-check (("string" "string" string)
1180                ("index" "number" index))
1181     "string.charCodeAt(index)"))
1182
1183 (define-builtin concat-two (string1 string2)
1184   (type-check (("string1" "string" string1)
1185                ("string2" "string" string2))
1186     "string1.concat(string2)"))
1187
1188 (define-compilation funcall (func &rest args)
1189   (concat "(" (ls-compile func env) ")("
1190           (join (mapcar (lambda (x)
1191                           (ls-compile x env))
1192                         args)
1193                 ", ")
1194           ")"))
1195
1196 (define-compilation apply (func &rest args)
1197   (if (null args)
1198       (concat "(" (ls-compile func env) ")()")
1199       (let ((args (butlast args))
1200             (last (car (last args))))
1201         (concat "(function(){" *newline*
1202                 (indent "var f = " (ls-compile func env) ";" *newline*
1203                         "var args = [" (join (mapcar (lambda (x)
1204                                                        (ls-compile x env))
1205                                                      args)
1206                                              ", ")
1207                         "];" *newline*
1208                         "var tail = (" (ls-compile last env) ");" *newline*
1209                         (indent "while (tail != " (ls-compile nil) "){" *newline*
1210                                 "    args.push(tail.car);" *newline*
1211                                 "    tail = tail.cdr;" *newline*
1212                                 "}" *newline*
1213                                 "return f.apply(this, args);" *newline*)
1214                         "})()")))))
1215
1216 (define-builtin js-eval (string)
1217   (type-check (("string" "string" string))
1218     "eval.apply(window, [string])"))
1219
1220 (define-builtin error (string)
1221   (concat "(function (){ throw " string "; })()"))
1222
1223 (define-builtin new () "{}")
1224
1225 (define-builtin get (object key)
1226   (concat "(function(){" *newline*
1227           (indent "var tmp = " "(" object ")[" key "];" *newline*
1228                   "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*)
1229           "})()"))
1230
1231 (define-builtin set (object key value)
1232   (concat "((" object ")[" key "] = " value ")"))
1233
1234 (define-builtin in (key object)
1235   (compile-bool (concat "((" key ") in (" object "))")))
1236
1237 (define-builtin functionp (x)
1238   (compile-bool (concat "(typeof " x " == 'function')")))
1239
1240 (define-builtin write-string (x)
1241   (type-check (("x" "string" x))
1242     "lisp.write(x)"))
1243
1244 (defun macrop (x)
1245   (and (symbolp x) (eq (binding-type (lookup-function x *environment*)) 'macro)))
1246
1247 (defun ls-macroexpand-1 (form env)
1248   (if (macrop (car form))
1249       (let ((binding (lookup-function (car form) *environment*)))
1250         (if (eq (binding-type binding) 'macro)
1251             (apply (eval (binding-translation binding)) (cdr form))
1252             form))
1253       form))
1254
1255 (defun compile-funcall (function args env)
1256   (cond
1257     ((symbolp function)
1258      (concat (lookup-function-translation function env)
1259              "("
1260              (join (mapcar (lambda (x) (ls-compile x env)) args)
1261                    ", ")
1262              ")"))
1263     ((and (listp function) (eq (car function) 'lambda))
1264      (concat "(" (ls-compile function env) ")("
1265              (join (mapcar (lambda (x) (ls-compile x env)) args)
1266                    ", ")
1267              ")"))
1268     (t
1269      (error (concat "Invalid function designator " (symbol-name function))))))
1270
1271 (defun ls-compile (sexp &optional (env (make-lexenv)))
1272   (cond
1273     ((symbolp sexp) (lookup-variable-translation sexp env))
1274     ((integerp sexp) (integer-to-string sexp))
1275     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1276     ((listp sexp)
1277      (if (assoc (car sexp) *compilations*)
1278          (let ((comp (second (assoc (car sexp) *compilations*))))
1279            (apply comp env (cdr sexp)))
1280          (if (macrop (car sexp))
1281              (ls-compile (ls-macroexpand-1 sexp env) env)
1282              (compile-funcall (car sexp) (cdr sexp) env))))))
1283
1284 (defun ls-compile-toplevel (sexp)
1285   (setq *toplevel-compilations* nil)
1286   (let ((code (ls-compile sexp)))
1287     (prog1
1288         (concat (join (mapcar (lambda (x) (concat x ";" *newline*))
1289                               *toplevel-compilations*))
1290                 code)
1291       (setq *toplevel-compilations* nil))))
1292
1293
1294 ;;; Once we have the compiler, we define the runtime environment and
1295 ;;; interactive development (eval), which works calling the compiler
1296 ;;; and evaluating the Javascript result globally.
1297
1298 #+ecmalisp
1299 (progn
1300   (defmacro with-compilation-unit (&body body)
1301     `(prog1
1302          (progn
1303            (setq *compilation-unit-checks* nil)
1304            (clear-undeclared-global-bindings)
1305            ,@body)
1306        (dolist (check *compilation-unit-checks*)
1307          (funcall check))))
1308
1309   (defun eval (x)
1310     (let ((code
1311            (with-compilation-unit
1312                (ls-compile-toplevel x))))
1313       (js-eval code)))
1314
1315   ;; Set the initial global environment to be equal to the host global
1316   ;; environment at this point of the compilation.
1317   (eval-when-compile
1318     (let ((tmp (ls-compile
1319                 `(progn
1320                    (setq *environment* ',*environment*)
1321                    (setq *variable-counter* ',*variable-counter*)
1322                    (setq *function-counter* ',*function-counter*)
1323                    (setq *literal-counter* ',*literal-counter*)
1324                    (setq *gensym-counter* ',*gensym-counter*)
1325                    (setq *block-counter* ',*block-counter*)))))
1326       (setq *toplevel-compilations*
1327             (append *toplevel-compilations* (list tmp)))))
1328
1329   (js-eval
1330    (concat "var lisp = {};"
1331            "lisp.read = " (lookup-function-translation 'ls-read-from-string nil) ";" *newline*
1332            "lisp.print = " (lookup-function-translation 'print-to-string nil) ";" *newline*
1333            "lisp.eval = " (lookup-function-translation 'eval nil) ";" *newline*
1334            "lisp.compile = " (lookup-function-translation 'ls-compile-toplevel nil) ";" *newline*
1335            "lisp.evalString = function(str){" *newline*
1336            "   return lisp.eval(lisp.read(str));" *newline*
1337            "}" *newline*
1338            "lisp.compileString = function(str){" *newline*
1339            "   return lisp.compile(lisp.read(str));" *newline*
1340            "}" *newline*)))
1341
1342
1343 ;;; Finally, we provide a couple of functions to easily bootstrap
1344 ;;; this. It just calls the compiler with this file as input.
1345
1346 #+common-lisp
1347 (progn
1348   (defun read-whole-file (filename)
1349     (with-open-file (in filename)
1350       (let ((seq (make-array (file-length in) :element-type 'character)))
1351         (read-sequence seq in)
1352         seq)))
1353
1354   (defun ls-compile-file (filename output)
1355     (setq *compilation-unit-checks* nil)
1356     (with-open-file (out output :direction :output :if-exists :supersede)
1357       (let* ((source (read-whole-file filename))
1358              (in (make-string-stream source)))
1359         (loop
1360            for x = (ls-read in)
1361            until (eq x *eof*)
1362            for compilation = (ls-compile-toplevel x)
1363            when (plusp (length compilation))
1364            do (write-line (concat compilation "; ") out))
1365         (dolist (check *compilation-unit-checks*)
1366           (funcall check))
1367         (setq *compilation-unit-checks* nil))))
1368
1369   (defun bootstrap ()
1370     (setq *environment* (make-lexenv))
1371     (setq *variable-counter* 0
1372           *gensym-counter* 0
1373           *function-counter* 0
1374           *literal-counter* 0
1375           *block-counter* 0)
1376     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))