Fix DOTIMES and DOLIST implicit NIL to ignore the optional result form
[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))) ";" *newline*
997                       "}" *newline*
998                       "catch (cf){" *newline*
999                       "    if (cf.type == 'block' && cf.id == " tr ")" *newline*
1000                       "        return cf.value;" *newline*
1001                       "    else" *newline*
1002                       "        throw cf;" *newline*
1003                       "}" *newline*)
1004               "})()"))))
1005
1006 (define-compilation return-from (name &optional value)
1007   (let ((b (lookup-in-lexenv name env 'block)))
1008     (if b
1009         (concat "(function(){ throw ({"
1010                 "type: 'block', "
1011                 "id: " (binding-translation b) ", "
1012                 "value: " (ls-compile value env) ", "
1013                 "message: 'Return from unknown block " (symbol-name name) ".'"
1014                 "})})()")
1015         (error (concat "Unknown block `" (symbol-name name) "'.")))))
1016
1017 ;;; A little backquote implementation without optimizations of any
1018 ;;; kind for ecmalisp.
1019 (defun backquote-expand-1 (form)
1020   (cond
1021     ((symbolp form)
1022      (list 'quote form))
1023     ((atom form)
1024      form)
1025     ((eq (car form) 'unquote)
1026      (car form))
1027     ((eq (car form) 'backquote)
1028      (backquote-expand-1 (backquote-expand-1 (cadr form))))
1029     (t
1030      (cons 'append
1031            (mapcar (lambda (s)
1032                      (cond
1033                        ((and (listp s) (eq (car s) 'unquote))
1034                         (list 'list (cadr s)))
1035                        ((and (listp s) (eq (car s) 'unquote-splicing))
1036                         (cadr s))
1037                        (t
1038                         (list 'list (backquote-expand-1 s)))))
1039                    form)))))
1040
1041 (defun backquote-expand (form)
1042   (if (and (listp form) (eq (car form) 'backquote))
1043       (backquote-expand-1 (cadr form))
1044       form))
1045
1046 (defmacro backquote (form)
1047   (backquote-expand-1 form))
1048
1049 (define-transformation backquote (form)
1050   (backquote-expand-1 form))
1051
1052 ;;; Primitives
1053
1054 (defmacro define-builtin (name args &body body)
1055   `(define-compilation ,name ,args
1056      (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg env))) args)
1057        ,@body)))
1058
1059 (defun compile-bool (x)
1060   (concat "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
1061
1062 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1063 (defmacro type-check (decls &body body)
1064   `(concat "(function(){" *newline*
1065            (indent ,@(mapcar (lambda (decl)
1066                                `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1067                              decls)
1068
1069                    ,@(mapcar (lambda (decl)
1070                                `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1071                                         (indent "throw 'The value ' + "
1072                                                 ,(first decl)
1073                                                 " + ' is not a type "
1074                                                 ,(second decl)
1075                                                 ".';"
1076                                                 *newline*)))
1077                              decls)
1078                    (concat "return " (progn ,@body) ";" *newline*))
1079            "})()"))
1080
1081 (defun num-op-num (x op y)
1082   (type-check (("x" "number" x) ("y" "number" y))
1083     (concat "x" op "y")))
1084
1085 (define-builtin + (x y) (num-op-num x "+" y))
1086 (define-builtin - (x y) (num-op-num x "-" y))
1087 (define-builtin * (x y) (num-op-num x "*" y))
1088 (define-builtin / (x y) (num-op-num x "/" y))
1089
1090 (define-builtin mod (x y) (num-op-num x "%" y))
1091
1092 (define-builtin < (x y)  (compile-bool (num-op-num x "<" y)))
1093 (define-builtin > (x y)  (compile-bool (num-op-num x ">" y)))
1094 (define-builtin = (x y)  (compile-bool (num-op-num x "==" y)))
1095 (define-builtin <= (x y) (compile-bool (num-op-num x "<=" y)))
1096 (define-builtin >= (x y) (compile-bool (num-op-num x ">=" y)))
1097
1098 (define-builtin numberp (x)
1099   (compile-bool (concat "(typeof (" x ") == \"number\")")))
1100
1101 (define-builtin floor (x)
1102   (type-check (("x" "number" x))
1103     "Math.floor(x)"))
1104
1105 (define-builtin cons (x y) (concat "({car: " x ", cdr: " y "})"))
1106 (define-builtin consp (x)
1107   (compile-bool
1108    (concat "(function(){" *newline*
1109            (indent "var tmp = " x ";" *newline*
1110                    "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)
1111            "})()")))
1112
1113 (define-builtin car (x)
1114   (concat "(function(){" *newline*
1115           (indent "var tmp = " x ";" *newline*
1116                   "return tmp === " (ls-compile nil)
1117                   "? " (ls-compile nil)
1118                   ": tmp.car;" *newline*)
1119           "})()"))
1120
1121 (define-builtin cdr (x)
1122   (concat "(function(){" *newline*
1123           (indent "var tmp = " x ";" *newline*
1124                   "return tmp === " (ls-compile nil) "? "
1125                   (ls-compile nil)
1126                   ": tmp.cdr;" *newline*)
1127           "})()"))
1128
1129 (define-builtin setcar (x new)
1130   (type-check (("x" "object" x))
1131     (concat "(x.car = " new ")")))
1132
1133 (define-builtin setcdr (x new)
1134   (type-check (("x" "object" x))
1135     (concat "(x.cdr = " new ")")))
1136
1137 (define-builtin symbolp (x)
1138   (compile-bool
1139    (concat "(function(){" *newline*
1140            (indent "var tmp = " x ";" *newline*
1141                    "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)
1142            "})()")))
1143
1144 (define-builtin make-symbol (name)
1145   (type-check (("name" "string" name))
1146     "({name: name})"))
1147
1148 (define-builtin symbol-name (x)
1149   (concat "(" x ").name"))
1150
1151 (define-builtin eq    (x y) (compile-bool (concat "(" x " === " y ")")))
1152 (define-builtin equal (x y) (compile-bool (concat "(" x  " == " y ")")))
1153
1154 (define-builtin string (x)
1155   (type-check (("x" "number" x))
1156     "String.fromCharCode(x)"))
1157
1158 (define-builtin stringp (x)
1159   (compile-bool (concat "(typeof(" x ") == \"string\")")))
1160
1161 (define-builtin string-upcase (x)
1162   (type-check (("x" "string" x))
1163     "x.toUpperCase()"))
1164
1165 (define-builtin string-length (x)
1166   (type-check (("x" "string" x))
1167     "x.length"))
1168
1169 (define-compilation slice (string a &optional b)
1170   (concat "(function(){" *newline*
1171           (indent "var str = " (ls-compile string env) ";" *newline*
1172                   "var a = " (ls-compile a env) ";" *newline*
1173                   "var b;" *newline*
1174                   (if b
1175                       (concat "b = " (ls-compile b env) ";" *newline*)
1176                       "")
1177                   "return str.slice(a,b);" *newline*)
1178           "})()"))
1179
1180 (define-builtin char (string index)
1181   (type-check (("string" "string" string)
1182                ("index" "number" index))
1183     "string.charCodeAt(index)"))
1184
1185 (define-builtin concat-two (string1 string2)
1186   (type-check (("string1" "string" string1)
1187                ("string2" "string" string2))
1188     "string1.concat(string2)"))
1189
1190 (define-compilation funcall (func &rest args)
1191   (concat "(" (ls-compile func env) ")("
1192           (join (mapcar (lambda (x)
1193                           (ls-compile x env))
1194                         args)
1195                 ", ")
1196           ")"))
1197
1198 (define-compilation apply (func &rest args)
1199   (if (null args)
1200       (concat "(" (ls-compile func env) ")()")
1201       (let ((args (butlast args))
1202             (last (car (last args))))
1203         (concat "(function(){" *newline*
1204                 (indent "var f = " (ls-compile func env) ";" *newline*
1205                         "var args = [" (join (mapcar (lambda (x)
1206                                                        (ls-compile x env))
1207                                                      args)
1208                                              ", ")
1209                         "];" *newline*
1210                         "var tail = (" (ls-compile last env) ");" *newline*
1211                         (indent "while (tail != " (ls-compile nil) "){" *newline*
1212                                 "    args.push(tail.car);" *newline*
1213                                 "    tail = tail.cdr;" *newline*
1214                                 "}" *newline*
1215                                 "return f.apply(this, args);" *newline*)
1216                         "})()")))))
1217
1218 (define-builtin js-eval (string)
1219   (type-check (("string" "string" string))
1220     "eval.apply(window, [string])"))
1221
1222 (define-builtin error (string)
1223   (concat "(function (){ throw " string "; })()"))
1224
1225 (define-builtin new () "{}")
1226
1227 (define-builtin get (object key)
1228   (concat "(function(){" *newline*
1229           (indent "var tmp = " "(" object ")[" key "];" *newline*
1230                   "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*)
1231           "})()"))
1232
1233 (define-builtin set (object key value)
1234   (concat "((" object ")[" key "] = " value ")"))
1235
1236 (define-builtin in (key object)
1237   (compile-bool (concat "((" key ") in (" object "))")))
1238
1239 (define-builtin functionp (x)
1240   (compile-bool (concat "(typeof " x " == 'function')")))
1241
1242 (define-builtin write-string (x)
1243   (type-check (("x" "string" x))
1244     "lisp.write(x)"))
1245
1246 (defun macrop (x)
1247   (and (symbolp x) (eq (binding-type (lookup-function x *environment*)) 'macro)))
1248
1249 (defun ls-macroexpand-1 (form env)
1250   (if (macrop (car form))
1251       (let ((binding (lookup-function (car form) *environment*)))
1252         (if (eq (binding-type binding) 'macro)
1253             (apply (eval (binding-translation binding)) (cdr form))
1254             form))
1255       form))
1256
1257 (defun compile-funcall (function args env)
1258   (cond
1259     ((symbolp function)
1260      (concat (lookup-function-translation function env)
1261              "("
1262              (join (mapcar (lambda (x) (ls-compile x env)) args)
1263                    ", ")
1264              ")"))
1265     ((and (listp function) (eq (car function) 'lambda))
1266      (concat "(" (ls-compile function env) ")("
1267              (join (mapcar (lambda (x) (ls-compile x env)) args)
1268                    ", ")
1269              ")"))
1270     (t
1271      (error (concat "Invalid function designator " (symbol-name function))))))
1272
1273 (defun ls-compile (sexp &optional (env (make-lexenv)))
1274   (cond
1275     ((symbolp sexp) (lookup-variable-translation sexp env))
1276     ((integerp sexp) (integer-to-string sexp))
1277     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1278     ((listp sexp)
1279      (if (assoc (car sexp) *compilations*)
1280          (let ((comp (second (assoc (car sexp) *compilations*))))
1281            (apply comp env (cdr sexp)))
1282          (if (macrop (car sexp))
1283              (ls-compile (ls-macroexpand-1 sexp env) env)
1284              (compile-funcall (car sexp) (cdr sexp) env))))))
1285
1286 (defun ls-compile-toplevel (sexp)
1287   (setq *toplevel-compilations* nil)
1288   (let ((code (ls-compile sexp)))
1289     (prog1
1290         (concat (join (mapcar (lambda (x) (concat x ";" *newline*))
1291                               *toplevel-compilations*))
1292                 code)
1293       (setq *toplevel-compilations* nil))))
1294
1295
1296 ;;; Once we have the compiler, we define the runtime environment and
1297 ;;; interactive development (eval), which works calling the compiler
1298 ;;; and evaluating the Javascript result globally.
1299
1300 #+ecmalisp
1301 (progn
1302   (defmacro with-compilation-unit (&body body)
1303     `(prog1
1304          (progn
1305            (setq *compilation-unit-checks* nil)
1306            (clear-undeclared-global-bindings)
1307            ,@body)
1308        (dolist (check *compilation-unit-checks*)
1309          (funcall check))))
1310
1311   (defun eval (x)
1312     (let ((code
1313            (with-compilation-unit
1314                (ls-compile-toplevel x))))
1315       (js-eval code)))
1316
1317   ;; Set the initial global environment to be equal to the host global
1318   ;; environment at this point of the compilation.
1319   (eval-when-compile
1320     (let ((tmp (ls-compile
1321                 `(progn
1322                    (setq *environment* ',*environment*)
1323                    (setq *variable-counter* ',*variable-counter*)
1324                    (setq *function-counter* ',*function-counter*)
1325                    (setq *literal-counter* ',*literal-counter*)
1326                    (setq *gensym-counter* ',*gensym-counter*)
1327                    (setq *block-counter* ',*block-counter*)))))
1328       (setq *toplevel-compilations*
1329             (append *toplevel-compilations* (list tmp)))))
1330
1331   (js-eval
1332    (concat "var lisp = {};"
1333            "lisp.read = " (lookup-function-translation 'ls-read-from-string nil) ";" *newline*
1334            "lisp.print = " (lookup-function-translation 'print-to-string nil) ";" *newline*
1335            "lisp.eval = " (lookup-function-translation 'eval nil) ";" *newline*
1336            "lisp.compile = " (lookup-function-translation 'ls-compile-toplevel nil) ";" *newline*
1337            "lisp.evalString = function(str){" *newline*
1338            "   return lisp.eval(lisp.read(str));" *newline*
1339            "}" *newline*
1340            "lisp.compileString = function(str){" *newline*
1341            "   return lisp.compile(lisp.read(str));" *newline*
1342            "}" *newline*)))
1343
1344
1345 ;;; Finally, we provide a couple of functions to easily bootstrap
1346 ;;; this. It just calls the compiler with this file as input.
1347
1348 #+common-lisp
1349 (progn
1350   (defun read-whole-file (filename)
1351     (with-open-file (in filename)
1352       (let ((seq (make-array (file-length in) :element-type 'character)))
1353         (read-sequence seq in)
1354         seq)))
1355
1356   (defun ls-compile-file (filename output)
1357     (setq *compilation-unit-checks* nil)
1358     (with-open-file (out output :direction :output :if-exists :supersede)
1359       (let* ((source (read-whole-file filename))
1360              (in (make-string-stream source)))
1361         (loop
1362            for x = (ls-read in)
1363            until (eq x *eof*)
1364            for compilation = (ls-compile-toplevel x)
1365            when (plusp (length compilation))
1366            do (write-line (concat compilation "; ") out))
1367         (dolist (check *compilation-unit-checks*)
1368           (funcall check))
1369         (setq *compilation-unit-checks* nil))))
1370
1371   (defun bootstrap ()
1372     (setq *environment* (make-lexenv))
1373     (setq *variable-counter* 0
1374           *gensym-counter* 0
1375           *function-counter* 0
1376           *literal-counter* 0
1377           *block-counter* 0)
1378     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))