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