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