Print returns object itself
[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     x))
515
516
517 ;;;; Reader
518
519 ;;; The Lisp reader, parse strings and return Lisp objects. The main
520 ;;; entry points are `ls-read' and `ls-read-from-string'.
521
522 (defun make-string-stream (string)
523   (cons string 0))
524
525 (defun %peek-char (stream)
526   (and (< (cdr stream) (length (car stream)))
527        (char (car stream) (cdr stream))))
528
529 (defun %read-char (stream)
530   (and (< (cdr stream) (length (car stream)))
531        (prog1 (char (car stream) (cdr stream))
532          (setcdr stream (1+ (cdr stream))))))
533
534 (defun whitespacep (ch)
535   (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
536
537 (defun skip-whitespaces (stream)
538   (let (ch)
539     (setq ch (%peek-char stream))
540     (while (and ch (whitespacep ch))
541       (%read-char stream)
542       (setq ch (%peek-char stream)))))
543
544 (defun terminalp (ch)
545   (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
546
547 (defun read-until (stream func)
548   (let ((string "")
549         (ch))
550     (setq ch (%peek-char stream))
551     (while (and ch (not (funcall func ch)))
552       (setq string (concat string (string ch)))
553       (%read-char stream)
554       (setq ch (%peek-char stream)))
555     string))
556
557 (defun skip-whitespaces-and-comments (stream)
558   (let (ch)
559     (skip-whitespaces stream)
560     (setq ch (%peek-char stream))
561     (while (and ch (char= ch #\;))
562       (read-until stream (lambda (x) (char= x #\newline)))
563       (skip-whitespaces stream)
564       (setq ch (%peek-char stream)))))
565
566 (defun %read-list (stream)
567   (skip-whitespaces-and-comments stream)
568   (let ((ch (%peek-char stream)))
569     (cond
570       ((null ch)
571        (error "Unspected EOF"))
572       ((char= ch #\))
573        (%read-char stream)
574        nil)
575       ((char= ch #\.)
576        (%read-char stream)
577        (prog1 (ls-read stream)
578          (skip-whitespaces-and-comments stream)
579          (unless (char= (%read-char stream) #\))
580            (error "')' was expected."))))
581       (t
582        (cons (ls-read stream) (%read-list stream))))))
583
584 (defun read-string (stream)
585   (let ((string "")
586         (ch nil))
587     (setq ch (%read-char stream))
588     (while (not (eql ch #\"))
589       (when (null ch)
590         (error "Unexpected EOF"))
591       (when (eql ch #\\)
592         (setq ch (%read-char stream)))
593       (setq string (concat string (string ch)))
594       (setq ch (%read-char stream)))
595     string))
596
597 (defun read-sharp (stream)
598   (%read-char stream)
599   (ecase (%read-char stream)
600     (#\'
601      (list 'function (ls-read stream)))
602     (#\\
603      (let ((cname
604             (concat (string (%read-char stream))
605                     (read-until stream #'terminalp))))
606        (cond
607          ((string= cname "space") (char-code #\space))
608          ((string= cname "tab") (char-code #\tab))
609          ((string= cname "newline") (char-code #\newline))
610          (t (char-code (char cname 0))))))
611     (#\+
612      (let ((feature (read-until stream #'terminalp)))
613        (cond
614          ((string= feature "common-lisp")
615           (ls-read stream)              ;ignore
616           (ls-read stream))
617          ((string= feature "ecmalisp")
618           (ls-read stream))
619          (t
620           (error "Unknown reader form.")))))))
621
622 (defvar *eof* (make-symbol "EOF"))
623 (defun ls-read (stream)
624   (skip-whitespaces-and-comments stream)
625   (let ((ch (%peek-char stream)))
626     (cond
627       ((null ch)
628        *eof*)
629       ((char= ch #\()
630        (%read-char stream)
631        (%read-list stream))
632       ((char= ch #\')
633        (%read-char stream)
634        (list 'quote (ls-read stream)))
635       ((char= ch #\`)
636        (%read-char stream)
637        (list 'backquote (ls-read stream)))
638       ((char= ch #\")
639        (%read-char stream)
640        (read-string stream))
641       ((char= ch #\,)
642        (%read-char stream)
643        (if (eql (%peek-char stream) #\@)
644            (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
645            (list 'unquote (ls-read stream))))
646       ((char= ch #\#)
647        (read-sharp stream))
648       (t
649        (let ((string (read-until stream #'terminalp)))
650          (if (every #'digit-char-p string)
651              (parse-integer string)
652              (intern (string-upcase string))))))))
653
654 (defun ls-read-from-string (string)
655   (ls-read (make-string-stream string)))
656
657
658 ;;;; Compiler
659
660 ;;; Translate the Lisp code to Javascript. It will compile the special
661 ;;; forms. Some primitive functions are compiled as special forms
662 ;;; too. The respective real functions are defined in the target (see
663 ;;; the beginning of this file) as well as some primitive functions.
664
665 (defvar *compilation-unit-checks* '())
666
667 (defun make-binding (name type js declared)
668   (list name type js declared))
669
670 (defun binding-name (b) (first b))
671 (defun binding-type (b) (second b))
672 (defun binding-translation (b) (third b))
673 (defun binding-declared (b)
674   (and b (fourth b)))
675 (defun mark-binding-as-declared (b)
676   (setcar (cdddr b) t))
677
678 (defun make-lexenv ()
679   (list nil nil))
680
681 (defun copy-lexenv (lexenv)
682   (copy-list lexenv))
683
684 (defun push-to-lexenv (binding lexenv namespace)
685   (ecase namespace
686     (variable
687      (setcar lexenv (cons binding (car lexenv))))
688     (function
689      (setcar (cdr lexenv) (cons binding (cadr lexenv))))))
690
691 (defun extend-lexenv (binding lexenv namespace)
692   (let ((env (copy-lexenv lexenv)))
693     (push-to-lexenv binding env namespace)
694     env))
695
696 (defun lookup-in-lexenv (name lexenv namespace)
697   (assoc name (ecase namespace
698                 (variable (car lexenv))
699                 (function (cadr lexenv)))))
700
701 (defvar *environment* (make-lexenv))
702
703 (defun clear-undeclared-global-bindings ()
704   (let ((variables (first *environment*))
705         (functions (second *environment*)))
706     (list variables functions)))
707
708
709 (defvar *variable-counter* 0)
710 (defun gvarname (symbol)
711   (concat "v" (integer-to-string (incf *variable-counter*))))
712
713 (defun lookup-variable (symbol env)
714   (or (lookup-in-lexenv symbol env 'variable)
715       (lookup-in-lexenv symbol *environment* 'variable)
716       (let ((name (symbol-name symbol))
717             (binding (make-binding symbol 'variable (gvarname symbol) nil)))
718         (push-to-lexenv binding *environment* 'variable)
719         (push (lambda ()
720                 (unless (lookup-in-lexenv symbol *environment* 'variable)
721                   (error (concat "Undefined variable `" name "'"))))
722               *compilation-unit-checks*)
723         binding)))
724
725 (defun lookup-variable-translation (symbol env)
726   (binding-translation (lookup-variable symbol env)))
727
728 (defun extend-local-env (args env)
729   (let ((new (copy-lexenv env)))
730     (dolist (symbol args new)
731       (let ((b (make-binding symbol 'variable (gvarname symbol) t)))
732         (push-to-lexenv b new 'variable)))))
733
734 (defvar *function-counter* 0)
735 (defun lookup-function (symbol env)
736   (or (lookup-in-lexenv symbol env 'function)
737       (lookup-in-lexenv symbol *environment* 'function)
738       (let ((name (symbol-name symbol))
739             (binding
740              (make-binding symbol
741                            'function
742                            (concat "f" (integer-to-string (incf *function-counter*)))
743                            nil)))
744         (push-to-lexenv binding *environment* 'function)
745         (push (lambda ()
746                 (unless (binding-declared (lookup-in-lexenv symbol *environment* 'function))
747                   (error (concat "Undefined function `" name "'"))))
748               *compilation-unit-checks*)
749         binding)))
750
751 (defun lookup-function-translation (symbol env)
752   (binding-translation (lookup-function symbol env)))
753
754 (defvar *toplevel-compilations* nil)
755
756 (defun %compile-defvar (name)
757   (let ((b (lookup-variable name *environment*)))
758     (mark-binding-as-declared b)
759     (push (concat "var " (binding-translation b)) *toplevel-compilations*)))
760
761 (defun %compile-defun (name)
762   (let ((b (lookup-function name *environment*)))
763     (mark-binding-as-declared b)
764     (push (concat "var " (binding-translation b)) *toplevel-compilations*)))
765
766 (defun %compile-defmacro (name lambda)
767   (push-to-lexenv (make-binding name 'macro lambda t) *environment* 'function))
768
769 (defvar *compilations* nil)
770
771 (defun ls-compile-block (sexps env)
772   (join-trailing
773    (remove-if (lambda (x)
774                 (or (null x)
775                     (and (stringp x)
776                          (zerop (length x)))))
777               (mapcar (lambda (x) (ls-compile x env))  sexps))
778    (concat ";" *newline*)))
779
780 (defmacro define-compilation (name args &body body)
781   ;; Creates a new primitive `name' with parameters args and
782   ;; @body. The body can access to the local environment through the
783   ;; variable ENV.
784   `(push (list ',name (lambda (env ,@args) ,@body))
785          *compilations*))
786
787 (define-compilation if (condition true false)
788   (concat "("
789           (ls-compile condition env) " !== " (ls-compile nil)
790           " ? "
791           (ls-compile true env)
792           " : "
793           (ls-compile false env)
794           ")"))
795
796
797 (defvar *lambda-list-keywords* '(&optional &rest))
798
799 (defun list-until-keyword (list)
800   (if (or (null list) (member (car list) *lambda-list-keywords*))
801       nil
802       (cons (car list) (list-until-keyword (cdr list)))))
803
804 (defun lambda-list-required-arguments (lambda-list)
805   (list-until-keyword lambda-list))
806
807 (defun lambda-list-optional-arguments-with-default (lambda-list)
808   (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
809
810 (defun lambda-list-optional-arguments (lambda-list)
811   (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
812
813 (defun lambda-list-rest-argument (lambda-list)
814   (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
815     (when (cdr rest)
816       (error "Bad lambda-list"))
817     (car rest)))
818
819 (define-compilation lambda (lambda-list &rest body)
820   (let ((required-arguments (lambda-list-required-arguments lambda-list))
821         (optional-arguments (lambda-list-optional-arguments lambda-list))
822         (rest-argument (lambda-list-rest-argument lambda-list)))
823     (let ((n-required-arguments (length required-arguments))
824           (n-optional-arguments (length optional-arguments))
825           (new-env (extend-local-env
826                     (append (ensure-list rest-argument)
827                             required-arguments
828                             optional-arguments)
829                     env)))
830       (concat "(function ("
831               (join (mapcar (lambda (x)
832                               (lookup-variable-translation x new-env))
833                             (append required-arguments optional-arguments))
834                     ",")
835               "){" *newline*
836               ;; Check number of arguments
837               (indent
838                (if required-arguments
839                    (concat "if (arguments.length < " (integer-to-string n-required-arguments)
840                            ") throw 'too few arguments';" *newline*)
841                    "")
842                (if (not rest-argument)
843                    (concat "if (arguments.length > "
844                            (integer-to-string (+ n-required-arguments n-optional-arguments))
845                            ") throw 'too many arguments';" *newline*)
846                    "")
847                ;; Optional arguments
848                (if optional-arguments
849                    (concat "switch(arguments.length){" *newline*
850                            (let ((optional-and-defaults
851                                   (lambda-list-optional-arguments-with-default lambda-list))
852                                  (cases nil)
853                                  (idx 0))
854                              (progn
855                                (while (< idx n-optional-arguments)
856                                  (let ((arg (nth idx optional-and-defaults)))
857                                    (push (concat "case "
858                                                  (integer-to-string (+ idx n-required-arguments)) ":" *newline*
859                                                  (lookup-variable-translation (car arg) new-env)
860                                                  "="
861                                                  (ls-compile (cadr arg) new-env)
862                                                  ";" *newline*)
863                                          cases)
864                                    (incf idx)))
865                                     (push (concat "default: break;" *newline*) cases)
866                                     (join (reverse cases))))
867                            "}" *newline*)
868                    "")
869                ;; &rest/&body argument
870                (if rest-argument
871                    (let ((js!rest (lookup-variable-translation rest-argument new-env)))
872                      (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
873                              "for (var i = arguments.length-1; i>="
874                              (integer-to-string (+ n-required-arguments n-optional-arguments))
875                              "; i--)" *newline*
876                              (indent js!rest " = "
877                                      "{car: arguments[i], cdr: ") js!rest "};"
878                                      *newline*))
879                    "")
880                ;; Body
881                (concat (ls-compile-block (butlast body) new-env)
882                        "return " (ls-compile (car (last body)) new-env) ";")) *newline*
883               "})"))))
884
885 (define-compilation fsetq (var val)
886   (concat (lookup-function-translation var env)
887           " = "
888           (ls-compile val env)))
889
890 (define-compilation setq (var val)
891   (concat (lookup-variable-translation var env)
892           " = "
893            (ls-compile val env)))
894
895 ;;; Literals
896 (defun escape-string (string)
897   (let ((output "")
898         (index 0)
899         (size (length string)))
900     (while (< index size)
901       (let ((ch (char string index)))
902         (when (or (char= ch #\") (char= ch #\\))
903           (setq output (concat output "\\")))
904         (when (or (char= ch #\newline))
905           (setq output (concat output "\\"))
906           (setq ch #\n))
907         (setq output (concat output (string ch))))
908       (incf index))
909     output))
910
911 (defun literal->js (sexp)
912   (cond
913     ((integerp sexp) (integer-to-string sexp))
914     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
915     ((symbolp sexp) (ls-compile `(intern ,(escape-string (symbol-name sexp))) *environment*))
916     ((consp sexp) (concat "{car: "
917                           (literal->js (car sexp))
918                           ", cdr: "
919                           (literal->js (cdr sexp)) "}"))))
920
921 (defvar *literal-counter* 0)
922 (defun literal (form)
923   (let ((var (concat "l" (integer-to-string (incf *literal-counter*)))))
924     (push (concat "var " var " = " (literal->js form)) *toplevel-compilations*)
925     var))
926
927 (define-compilation quote (sexp)
928   (literal sexp))
929
930 (define-compilation while (pred &rest body)
931   (concat "(function(){" *newline*
932           (indent "while("
933                   (ls-compile pred env)
934                   " !== "
935                   (ls-compile nil) "){" *newline*
936                   (indent (ls-compile-block body env)))
937           "}})()"))
938
939 (define-compilation function (x)
940   (cond
941     ((and (listp x) (eq (car x) 'lambda))
942      (ls-compile x env))
943     ((symbolp x)
944      (lookup-function-translation x env))))
945
946 (define-compilation eval-when-compile (&rest body)
947   (eval (cons 'progn body))
948   "")
949
950 (defmacro define-transformation (name args form)
951   `(define-compilation ,name ,args
952      (ls-compile ,form env)))
953
954 (define-compilation progn (&rest body)
955   (concat "(function(){" *newline*
956           (indent (ls-compile-block (butlast body) env)
957                   "return " (ls-compile (car (last body)) env) ";" *newline*)
958           "})()"))
959
960 (define-compilation let (bindings &rest body)
961   (let ((bindings (mapcar #'ensure-list bindings)))
962     (let ((variables (mapcar #'first bindings))
963           (values    (mapcar #'second bindings)))
964       (let ((new-env (extend-local-env variables env)))
965         (concat "(function("
966                 (join (mapcar (lambda (x)
967                                 (lookup-variable-translation x new-env))
968                               variables)
969                       ",")
970                 "){" *newline*
971                 (indent (ls-compile-block (butlast body) new-env)
972                         "return " (ls-compile (car (last body)) new-env)
973                         ";" *newline*)
974                 "})(" (join (mapcar (lambda (x) (ls-compile x env))
975                                     values)
976                             ",")
977                 ")")))))
978
979 ;;; A little backquote implementation without optimizations of any
980 ;;; kind for ecmalisp.
981 (defun backquote-expand-1 (form)
982   (cond
983     ((symbolp form)
984      (list 'quote form))
985     ((atom form)
986      form)
987     ((eq (car form) 'unquote)
988      (car form))
989     ((eq (car form) 'backquote)
990      (backquote-expand-1 (backquote-expand-1 (cadr form))))
991     (t
992      (cons 'append
993            (mapcar (lambda (s)
994                      (cond
995                        ((and (listp s) (eq (car s) 'unquote))
996                         (list 'list (cadr s)))
997                        ((and (listp s) (eq (car s) 'unquote-splicing))
998                         (cadr s))
999                        (t
1000                         (list 'list (backquote-expand-1 s)))))
1001                    form)))))
1002
1003 (defun backquote-expand (form)
1004   (if (and (listp form) (eq (car form) 'backquote))
1005       (backquote-expand-1 (cadr form))
1006       form))
1007
1008 (defmacro backquote (form)
1009   (backquote-expand-1 form))
1010
1011 (define-transformation backquote (form)
1012   (backquote-expand-1 form))
1013
1014 ;;; Primitives
1015
1016 (defmacro define-builtin (name args &body body)
1017   `(define-compilation ,name ,args
1018      (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg env))) args)
1019        ,@body)))
1020
1021 (defun compile-bool (x)
1022   (concat "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
1023
1024 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1025 (defmacro type-check (decls &body body)
1026   `(concat "(function(){" *newline*
1027            (indent ,@(mapcar (lambda (decl)
1028                                `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1029                              decls)
1030
1031                    ,@(mapcar (lambda (decl)
1032                                `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1033                                         (indent "throw 'The value ' + "
1034                                                 ,(first decl)
1035                                                 " + ' is not a type "
1036                                                 ,(second decl)
1037                                                 ".';"
1038                                                 *newline*)))
1039                              decls)
1040                    (concat "return " (progn ,@body) ";" *newline*))
1041            "})()"))
1042
1043 (defun num-op-num (x op y)
1044   (type-check (("x" "number" x) ("y" "number" y))
1045     (concat "x" op "y")))
1046
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 (define-builtin / (x y) (num-op-num x "/" y))
1051
1052 (define-builtin mod (x y) (num-op-num x "%" y))
1053
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 (define-builtin >= (x y) (compile-bool (num-op-num x ">=" y)))
1059
1060 (define-builtin numberp (x)
1061   (compile-bool (concat "(typeof (" x ") == \"number\")")))
1062
1063 (define-builtin floor (x)
1064   (type-check (("x" "number" x))
1065     "Math.floor(x)"))
1066
1067 (define-builtin cons (x y) (concat "({car: " x ", cdr: " y "})"))
1068 (define-builtin consp (x)
1069   (compile-bool
1070    (concat "(function(){" *newline*
1071            (indent "var tmp = " x ";" *newline*
1072                    "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)
1073            "})()")))
1074
1075 (define-builtin car (x)
1076   (concat "(function(){" *newline*
1077           (indent "var tmp = " x ";" *newline*
1078                   "return tmp === " (ls-compile nil)
1079                   "? " (ls-compile nil)
1080                   ": tmp.car;" *newline*)
1081           "})()"))
1082
1083 (define-builtin cdr (x)
1084   (concat "(function(){" *newline*
1085           (indent "var tmp = " x ";" *newline*
1086                   "return tmp === " (ls-compile nil) "? "
1087                   (ls-compile nil)
1088                   ": tmp.cdr;" *newline*)
1089           "})()"))
1090
1091 (define-builtin setcar (x new)
1092   (type-check (("x" "object" x))
1093     (concat "(x.car = " new ")")))
1094
1095 (define-builtin setcdr (x new)
1096   (type-check (("x" "object" x))
1097     (concat "(x.cdr = " new ")")))
1098
1099 (define-builtin symbolp (x)
1100   (compile-bool
1101    (concat "(function(){" *newline*
1102            (indent "var tmp = " x ";" *newline*
1103                    "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)
1104            "})()")))
1105
1106 (define-builtin make-symbol (name)
1107   (type-check (("name" "string" name))
1108     "({name: name})"))
1109
1110 (define-builtin symbol-name (x)
1111   (concat "(" x ").name"))
1112
1113 (define-builtin eq    (x y) (compile-bool (concat "(" x " === " y ")")))
1114 (define-builtin equal (x y) (compile-bool (concat "(" x  " == " y ")")))
1115
1116 (define-builtin string (x)
1117   (type-check (("x" "number" x))
1118     "String.fromCharCode(x)"))
1119
1120 (define-builtin stringp (x)
1121   (compile-bool (concat "(typeof(" x ") == \"string\")")))
1122
1123 (define-builtin string-upcase (x)
1124   (type-check (("x" "string" x))
1125     "x.toUpperCase()"))
1126
1127 (define-builtin string-length (x)
1128   (type-check (("x" "string" x))
1129     "x.length"))
1130
1131 (define-compilation slice (string a &optional b)
1132   (concat "(function(){" *newline*
1133           (indent "var str = " (ls-compile string env) ";" *newline*
1134                   "var a = " (ls-compile a env) ";" *newline*
1135                   "var b;" *newline*
1136                   (if b
1137                       (concat "b = " (ls-compile b env) ";" *newline*)
1138                       "")
1139                   "return str.slice(a,b);" *newline*)
1140           "})()"))
1141
1142 (define-builtin char (string index)
1143   (type-check (("string" "string" string)
1144                ("index" "number" index))
1145     "string.charCodeAt(index)"))
1146
1147 (define-builtin concat-two (string1 string2)
1148   (type-check (("string1" "string" string1)
1149                ("string2" "string" string2))
1150     "string1.concat(string2)"))
1151
1152 (define-compilation funcall (func &rest args)
1153   (concat "(" (ls-compile func env) ")("
1154           (join (mapcar (lambda (x)
1155                           (ls-compile x env))
1156                         args)
1157                 ", ")
1158           ")"))
1159
1160 (define-compilation apply (func &rest args)
1161   (if (null args)
1162       (concat "(" (ls-compile func env) ")()")
1163       (let ((args (butlast args))
1164             (last (car (last args))))
1165         (concat "(function(){" *newline*
1166                 (indent "var f = " (ls-compile func env) ";" *newline*
1167                         "var args = [" (join (mapcar (lambda (x)
1168                                                        (ls-compile x env))
1169                                                      args)
1170                                              ", ")
1171                         "];" *newline*
1172                         "var tail = (" (ls-compile last env) ");" *newline*
1173                         (indent "while (tail != " (ls-compile nil) "){" *newline*
1174                                 "    args.push(tail.car);" *newline*
1175                                 "    tail = tail.cdr;" *newline*
1176                                 "}" *newline*
1177                                 "return f.apply(this, args);" *newline*)
1178                         "})()")))))
1179
1180 (define-builtin js-eval (string)
1181   (type-check (("string" "string" string))
1182     "eval.apply(window, [string])"))
1183
1184 (define-builtin error (string)
1185   (concat "(function (){ throw " string "; })()"))
1186
1187 (define-builtin new () "{}")
1188
1189 (define-builtin get (object key)
1190   (concat "(function(){" *newline*
1191           (indent "var tmp = " "(" object ")[" key "];" *newline*
1192                   "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*)
1193           "})()"))
1194
1195 (define-builtin set (object key value)
1196   (concat "((" object ")[" key "] = " value ")"))
1197
1198 (define-builtin in (key object)
1199   (compile-bool (concat "((" key ") in (" object "))")))
1200
1201 (define-builtin functionp (x)
1202   (compile-bool (concat "(typeof " x " == 'function')")))
1203
1204 (define-builtin write-string (x)
1205   (type-check (("x" "string" x))
1206     "lisp.write(x)"))
1207
1208 (defun macrop (x)
1209   (and (symbolp x) (eq (binding-type (lookup-function x *environment*)) 'macro)))
1210
1211 (defun ls-macroexpand-1 (form env)
1212   (if (macrop (car form))
1213       (let ((binding (lookup-function (car form) *environment*)))
1214         (if (eq (binding-type binding) 'macro)
1215             (apply (eval (binding-translation binding)) (cdr form))
1216             form))
1217       form))
1218
1219 (defun compile-funcall (function args env)
1220   (cond
1221     ((symbolp function)
1222      (concat (lookup-function-translation function env)
1223              "("
1224              (join (mapcar (lambda (x) (ls-compile x env)) args)
1225                    ", ")
1226              ")"))
1227     ((and (listp function) (eq (car function) 'lambda))
1228      (concat "(" (ls-compile function env) ")("
1229              (join (mapcar (lambda (x) (ls-compile x env)) args)
1230                    ", ")
1231              ")"))
1232     (t
1233      (error (concat "Invalid function designator " (symbol-name function))))))
1234
1235 (defun ls-compile (sexp &optional (env (make-lexenv)))
1236   (cond
1237     ((symbolp sexp) (lookup-variable-translation sexp env))
1238     ((integerp sexp) (integer-to-string sexp))
1239     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1240     ((listp sexp)
1241      (if (assoc (car sexp) *compilations*)
1242          (let ((comp (second (assoc (car sexp) *compilations*))))
1243            (apply comp env (cdr sexp)))
1244          (if (macrop (car sexp))
1245              (ls-compile (ls-macroexpand-1 sexp env) env)
1246              (compile-funcall (car sexp) (cdr sexp) env))))))
1247
1248 (defun ls-compile-toplevel (sexp)
1249   (setq *toplevel-compilations* nil)
1250   (let ((code (ls-compile sexp)))
1251     (prog1
1252         (concat (join (mapcar (lambda (x) (concat x ";" *newline*))
1253                               *toplevel-compilations*))
1254                 code)
1255       (setq *toplevel-compilations* nil))))
1256
1257
1258 ;;; Once we have the compiler, we define the runtime environment and
1259 ;;; interactive development (eval), which works calling the compiler
1260 ;;; and evaluating the Javascript result globally.
1261
1262 #+ecmalisp
1263 (progn
1264   (defmacro with-compilation-unit (&body body)
1265     `(prog1
1266          (progn
1267            (setq *compilation-unit-checks* nil)
1268            (clear-undeclared-global-bindings)
1269            ,@body)
1270        (dolist (check *compilation-unit-checks*)
1271          (funcall check))))
1272
1273   (defun eval (x)
1274     (let ((code
1275            (with-compilation-unit
1276                (ls-compile-toplevel x))))
1277       (js-eval code)))
1278
1279   ;; Set the initial global environment to be equal to the host global
1280   ;; environment at this point of the compilation.
1281   (eval-when-compile
1282     (let ((tmp (ls-compile
1283                 `(progn
1284                    (setq *environment* ',*environment*)
1285                    (setq *variable-counter* ',*variable-counter*)
1286                    (setq *function-counter* ',*function-counter*)
1287                    (setq *literal-counter* ',*literal-counter*)
1288                    (setq *gensym-counter* ',*gensym-counter*)))))
1289       (setq *toplevel-compilations*
1290             (append *toplevel-compilations* (list tmp)))))
1291
1292   (js-eval
1293    (concat "var lisp = {};"
1294            "lisp.read = " (lookup-function-translation 'ls-read-from-string nil) ";" *newline*
1295            "lisp.print = " (lookup-function-translation 'print-to-string nil) ";" *newline*
1296            "lisp.eval = " (lookup-function-translation 'eval nil) ";" *newline*
1297            "lisp.compile = " (lookup-function-translation 'ls-compile-toplevel nil) ";" *newline*
1298            "lisp.evalString = function(str){" *newline*
1299            "   return lisp.eval(lisp.read(str));" *newline*
1300            "}" *newline*
1301            "lisp.compileString = function(str){" *newline*
1302            "   return lisp.compile(lisp.read(str));" *newline*
1303            "}" *newline*)))
1304
1305
1306 ;;; Finally, we provide a couple of functions to easily bootstrap
1307 ;;; this. It just calls the compiler with this file as input.
1308
1309 #+common-lisp
1310 (progn
1311   (defun read-whole-file (filename)
1312     (with-open-file (in filename)
1313       (let ((seq (make-array (file-length in) :element-type 'character)))
1314         (read-sequence seq in)
1315         seq)))
1316
1317   (defun ls-compile-file (filename output)
1318     (setq *compilation-unit-checks* nil)
1319     (with-open-file (out output :direction :output :if-exists :supersede)
1320       (let* ((source (read-whole-file filename))
1321              (in (make-string-stream source)))
1322         (loop
1323            for x = (ls-read in)
1324            until (eq x *eof*)
1325            for compilation = (ls-compile-toplevel x)
1326            when (plusp (length compilation))
1327            do (write-line (concat compilation "; ") out))
1328         (dolist (check *compilation-unit-checks*)
1329           (funcall check))
1330         (setq *compilation-unit-checks* nil))))
1331
1332   (defun bootstrap ()
1333     (setq *environment* (make-lexenv))
1334     (setq *variable-counter* 0
1335           *gensym-counter* 0
1336           *function-counter* 0
1337           *literal-counter* 0)
1338     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))