3 ;; Copyright (C) 2012, 2013 David Vazquez
4 ;; Copyright (C) 2012 Raimon Grau
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.
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.
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/>.
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.
28 (%compile-defmacro 'defmacro
29 '(lambda (name args &rest body)
31 (%compile-defmacro ',name
32 '(lambda ,(mapcar (lambda (x)
42 (defmacro when (condition &body body)
43 `(if ,condition (progn ,@body) nil))
45 (defmacro unless (condition &body body)
46 `(if ,condition nil (progn ,@body)))
48 (defmacro defvar (name value)
50 (unless (boundp ',name)
54 (defmacro defparameter (name value)
59 (defmacro named-lambda (name args &rest body)
60 (let ((x (gensym "FN")))
61 `(let ((,x (lambda ,args ,@body)))
62 (oset ,x "fname" ,name)
65 (defmacro defun (name args &rest body)
68 (named-lambda ,(symbol-name name)
70 (block ,name ,@body)))
73 (defvar *package* (new))
78 (defmacro return (&optional value)
79 `(return-from nil ,value))
81 (defmacro while (condition &body body)
82 `(block nil (%while ,condition ,@body)))
90 (oset *package* name (make-symbol name))))
92 (defun find-symbol (name)
93 (oget *package* name))
95 (defvar *gensym-counter* 0)
96 (defun gensym (&optional (prefix "G"))
97 (setq *gensym-counter* (+ *gensym-counter* 1))
98 (make-symbol (concat-two prefix (integer-to-string *gensym-counter*))))
104 (defun = (x y) (= x y))
105 (defun + (x y) (+ x y))
106 (defun - (x y) (- x y))
107 (defun * (x y) (* x y))
108 (defun / (x y) (/ x y))
109 (defun 1+ (x) (+ x 1))
110 (defun 1- (x) (- x 1))
111 (defun zerop (x) (= x 0))
112 (defun truncate (x y) (floor (/ x y)))
114 (defun eql (x y) (eq x y))
116 (defun not (x) (if x nil t))
118 (defun cons (x y ) (cons x y))
119 (defun consp (x) (consp x))
120 (defun car (x) (car x))
121 (defun cdr (x) (cdr x))
122 (defun caar (x) (car (car x)))
123 (defun cadr (x) (car (cdr x)))
124 (defun cdar (x) (cdr (car x)))
125 (defun cddr (x) (cdr (cdr x)))
126 (defun caddr (x) (car (cdr (cdr x))))
127 (defun cdddr (x) (cdr (cdr (cdr x))))
128 (defun cadddr (x) (car (cdr (cdr (cdr x)))))
129 (defun first (x) (car x))
130 (defun second (x) (cadr x))
131 (defun third (x) (caddr x))
132 (defun fourth (x) (cadddr x))
134 (defun list (&rest args) args)
140 (defmacro incf (x &optional (delta 1))
141 `(setq ,x (+ ,x ,delta)))
143 (defmacro decf (x &optional (delta 1))
144 `(setq ,x (- ,x ,delta)))
146 (defmacro push (x place)
147 `(setq ,place (cons ,x ,place)))
149 (defmacro dolist (iter &body body)
150 (let ((var (first iter))
153 (let ((,g!list ,(second iter))
156 (setq ,var (car ,g!list))
158 (setq ,g!list (cdr ,g!list)))
161 (defmacro dotimes (iter &body body)
162 (let ((g!to (gensym))
165 (result (third iter)))
169 (%while (< ,var ,g!to)
174 (defmacro cond (&rest clausules)
177 (if (eq (caar clausules) t)
178 `(progn ,@(cdar clausules))
179 `(if ,(caar clausules)
180 (progn ,@(cdar clausules))
181 (cond ,@(cdr clausules))))))
183 (defmacro case (form &rest clausules)
184 (let ((!form (gensym)))
185 `(let ((,!form ,form))
187 ,@(mapcar (lambda (clausule)
188 (if (eq (car clausule) t)
190 `((eql ,!form ',(car clausule))
194 (defmacro ecase (form &rest clausules)
199 (error "ECASE expression failed."))))))
201 (defmacro and (&rest forms)
212 (defmacro or (&rest forms)
220 `(let ((,g ,(car forms)))
221 (if ,g ,g (or ,@(cdr forms))))))))
223 (defmacro prog1 (form &body body)
224 (let ((value (gensym)))
225 `(let ((,value ,form))
229 (defmacro prog2 (form1 result &body body)
230 `(prog1 (progn ,form1 ,result) ,@body)))
234 ;;; This couple of helper functions will be defined in both Common
235 ;;; Lisp and in Ecmalisp.
236 (defun ensure-list (x)
241 (defun !reduce (func list initial)
246 (funcall func initial (car list)))))
248 ;;; Go on growing the Lisp language in Ecmalisp, with more high
249 ;;; level utilities as well as correct versions of other
253 (defun append-two (list1 list2)
257 (append (cdr list1) list2))))
259 (defun append (&rest lists)
260 (!reduce #'append-two lists '()))
262 (defun revappend (list1 list2)
264 (push (car list1) list2)
265 (setq list1 (cdr list1)))
268 (defun reverse (list)
269 (revappend list '()))
271 (defun list-length (list)
273 (while (not (null list))
275 (setq list (cdr list)))
283 (defun concat-two (s1 s2)
286 (defun mapcar (func list)
289 (cons (funcall func (car list))
290 (mapcar func (cdr list)))))
292 (defun identity (x) x)
295 (mapcar #'identity x))
297 (defun code-char (x) x)
298 (defun char-code (x) x)
299 (defun char= (x y) (= x y))
302 (and (numberp x) (= (floor x) x)))
304 (defun plusp (x) (< 0 x))
305 (defun minusp (x) (< x 0))
308 (or (consp x) (null x)))
310 (defun nthcdr (n list)
311 (while (and (plusp n) list)
313 (setq list (cdr list)))
317 (car (nthcdr n list)))
320 (while (consp (cdr x))
326 (cons (car x) (butlast (cdr x)))))
328 (defun member (x list)
330 (when (eql x (car list))
332 (setq list (cdr list))))
334 (defun remove (x list)
339 (remove x (cdr list)))
341 (cons (car list) (remove x (cdr list))))))
343 (defun remove-if (func list)
347 ((funcall func (car list))
348 (remove-if func (cdr list)))
350 (cons (car list) (remove-if func (cdr list))))))
352 (defun remove-if-not (func list)
356 ((funcall func (car list))
357 (cons (car list) (remove-if-not func (cdr list))))
359 (remove-if-not func (cdr list)))))
361 (defun digit-char-p (x)
362 (if (and (<= #\0 x) (<= x #\9))
366 (defun subseq (seq a &optional b)
373 (error "Unsupported argument."))))
375 (defun parse-integer (string)
378 (size (length string)))
379 (while (< index size)
380 (setq value (+ (* value 10) (digit-char-p (char string index))))
384 (defun some (function seq)
389 (while (< index size)
390 (when (funcall function (char seq index))
391 (return-from some t))
396 (when (funcall function x)
399 (error "Unknown sequence."))))
401 (defun every (function seq)
406 (while (< index size)
407 (unless (funcall function (char seq index))
408 (return-from every nil))
413 (unless (funcall function x)
416 (error "Unknown sequence."))))
418 (defun assoc (x alist)
420 (if (eql x (caar alist))
422 (setq alist (cdr alist))))
425 (defun string= (s1 s2)
428 (defun fdefinition (x)
435 (error "Invalid function"))))
437 (defun disassemble (function)
438 (write-line (lambda-code (fdefinition function)))
442 ;;; The compiler offers some primitives and special forms which are
443 ;;; not found in Common Lisp, for instance, while. So, we grow Common
444 ;;; Lisp a bit to it can execute the rest of the file.
447 (defmacro while (condition &body body)
452 (defmacro eval-when-compile (&body body)
453 `(eval-when (:compile-toplevel :load-toplevel :execute)
456 (defun concat-two (s1 s2)
457 (concatenate 'string s1 s2))
459 (defun setcar (cons new)
460 (setf (car cons) new))
461 (defun setcdr (cons new)
462 (setf (cdr cons) new)))
464 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
465 ;;; from here, this code will compile on both. We define some helper
466 ;;; functions now for string manipulation and so on. They will be
467 ;;; useful in the compiler, mostly.
469 (defvar *newline* (string (code-char 10)))
471 (defun concat (&rest strs)
472 (!reduce #'concat-two strs ""))
474 (defmacro concatf (variable &body form)
475 `(setq ,variable (concat ,variable (progn ,@form))))
477 ;;; Concatenate a list of strings, with a separator
478 (defun join (list &optional (separator ""))
487 (join (cdr list) separator)))))
489 (defun join-trailing (list &optional (separator ""))
492 (concat (car list) separator (join-trailing (cdr list) separator))))
494 (defun mapconcat (func list)
495 (join (mapcar func list)))
497 ;;; Like CONCAT, but prefix each line with four spaces. Two versions
498 ;;; of this function are available, because the Ecmalisp version is
499 ;;; very slow and bootstraping was annoying.
502 (defun indent (&rest string)
503 (let ((input (join string)))
506 (size (length input)))
507 (when (plusp (length input)) (concatf output " "))
508 (while (< index size)
510 (if (and (char= (char input index) #\newline)
512 (not (char= (char input (1+ index)) #\newline)))
513 (concat (string #\newline) " ")
514 (string (char input index)))))
515 (concatf output str))
520 (defun indent (&rest string)
521 (with-output-to-string (*standard-output*)
522 (with-input-from-string (input (join string))
524 for line = (read-line input nil)
526 do (write-string " ")
527 do (write-line line)))))
530 (defun integer-to-string (x)
535 (concat "-" (integer-to-string (- 0 x))))
538 (while (not (zerop x))
539 (push (mod x 10) digits)
540 (setq x (truncate x 10)))
541 (join (mapcar (lambda (d) (string (char "0123456789" d)))
545 ;;; Wrap X with a Javascript code to convert the result from
546 ;;; Javascript generalized booleans to T or NIL.
548 (concat "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
550 ;;; Concatenate the arguments and wrap them with a self-calling
551 ;;; Javascript anonymous function. It is used to make some Javascript
552 ;;; statements valid expressions and provide a private scope as well.
553 ;;; It could be defined as function, but we could do some
554 ;;; preprocessing in the future.
555 (defmacro js!selfcall (&body body)
556 `(concat "(function(){" *newline* (indent ,@body) "})()"))
563 (defun prin1-to-string (form)
565 ((symbolp form) (symbol-name form))
566 ((integerp form) (integer-to-string form))
567 ((stringp form) (concat "\"" (escape-string form) "\""))
569 (let ((name (oget form "fname")))
571 (concat "#<FUNCTION " name ">")
572 (concat "#<FUNCTION>"))))
575 (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
576 (let ((last (last form)))
577 (if (null (cdr last))
578 (prin1-to-string (car last))
579 (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
582 (defun write-line (x)
584 (write-string *newline*)
588 (write-string "WARNING: ")
592 (write-line (prin1-to-string x))
598 ;;; The Lisp reader, parse strings and return Lisp objects. The main
599 ;;; entry points are `ls-read' and `ls-read-from-string'.
601 (defun make-string-stream (string)
604 (defun %peek-char (stream)
605 (and (< (cdr stream) (length (car stream)))
606 (char (car stream) (cdr stream))))
608 (defun %read-char (stream)
609 (and (< (cdr stream) (length (car stream)))
610 (prog1 (char (car stream) (cdr stream))
611 (setcdr stream (1+ (cdr stream))))))
613 (defun whitespacep (ch)
614 (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
616 (defun skip-whitespaces (stream)
618 (setq ch (%peek-char stream))
619 (while (and ch (whitespacep ch))
621 (setq ch (%peek-char stream)))))
623 (defun terminalp (ch)
624 (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
626 (defun read-until (stream func)
629 (setq ch (%peek-char stream))
630 (while (and ch (not (funcall func ch)))
631 (setq string (concat string (string ch)))
633 (setq ch (%peek-char stream)))
636 (defun skip-whitespaces-and-comments (stream)
638 (skip-whitespaces stream)
639 (setq ch (%peek-char stream))
640 (while (and ch (char= ch #\;))
641 (read-until stream (lambda (x) (char= x #\newline)))
642 (skip-whitespaces stream)
643 (setq ch (%peek-char stream)))))
645 (defun %read-list (stream)
646 (skip-whitespaces-and-comments stream)
647 (let ((ch (%peek-char stream)))
650 (error "Unspected EOF"))
656 (prog1 (ls-read stream)
657 (skip-whitespaces-and-comments stream)
658 (unless (char= (%read-char stream) #\))
659 (error "')' was expected."))))
661 (cons (ls-read stream) (%read-list stream))))))
663 (defun read-string (stream)
666 (setq ch (%read-char stream))
667 (while (not (eql ch #\"))
669 (error "Unexpected EOF"))
671 (setq ch (%read-char stream)))
672 (setq string (concat string (string ch)))
673 (setq ch (%read-char stream)))
676 (defun read-sharp (stream)
678 (ecase (%read-char stream)
680 (list 'function (ls-read stream)))
683 (concat (string (%read-char stream))
684 (read-until stream #'terminalp))))
686 ((string= cname "space") (char-code #\space))
687 ((string= cname "tab") (char-code #\tab))
688 ((string= cname "newline") (char-code #\newline))
689 (t (char-code (char cname 0))))))
691 (let ((feature (read-until stream #'terminalp)))
693 ((string= feature "common-lisp")
694 (ls-read stream) ;ignore
696 ((string= feature "ecmalisp")
699 (error "Unknown reader form.")))))))
701 (defvar *eof* (make-symbol "EOF"))
702 (defun ls-read (stream)
703 (skip-whitespaces-and-comments stream)
704 (let ((ch (%peek-char stream)))
713 (list 'quote (ls-read stream)))
716 (list 'backquote (ls-read stream)))
719 (read-string stream))
722 (if (eql (%peek-char stream) #\@)
723 (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
724 (list 'unquote (ls-read stream))))
728 (let ((string (read-until stream #'terminalp)))
729 (if (every #'digit-char-p string)
730 (parse-integer string)
731 (intern (string-upcase string))))))))
733 (defun ls-read-from-string (string)
734 (ls-read (make-string-stream string)))
739 ;;; Translate the Lisp code to Javascript. It will compile the special
740 ;;; forms. Some primitive functions are compiled as special forms
741 ;;; too. The respective real functions are defined in the target (see
742 ;;; the beginning of this file) as well as some primitive functions.
744 (defvar *compilation-unit-checks* '())
746 (defun make-binding (name type translation declared)
747 (list name type translation declared))
749 (defun binding-name (b) (first b))
750 (defun binding-type (b) (second b))
751 (defun binding-value (b) (third b))
752 (defun binding-declared (b)
754 (defun mark-binding-as-declared (b)
755 (setcar (cdddr b) t))
757 (defun make-lexenv ()
758 (list nil nil nil nil))
760 (defun copy-lexenv (lexenv)
763 (defun push-to-lexenv (binding lexenv namespace)
765 (variable (setcar lexenv (cons binding (car lexenv))))
766 (function (setcar (cdr lexenv) (cons binding (cadr lexenv))))
767 (block (setcar (cddr lexenv) (cons binding (caddr lexenv))))
768 (gotag (setcar (cdddr lexenv) (cons binding (cadddr lexenv))))))
770 (defun extend-lexenv (bindings lexenv namespace)
771 (let ((env (copy-lexenv lexenv)))
772 (dolist (binding (reverse bindings) env)
773 (push-to-lexenv binding env namespace))))
775 (defun lookup-in-lexenv (name lexenv namespace)
776 (assoc name (ecase namespace
777 (variable (first lexenv))
778 (function (second lexenv))
779 (block (third lexenv))
780 (gotag (fourth lexenv)))))
782 (defvar *global-environment* (make-lexenv))
783 (defvar *environment* (make-lexenv))
785 (defun clear-undeclared-global-bindings ()
787 (mapcar (lambda (namespace)
788 (remove-if-not #'binding-declared namespace))
792 (defvar *variable-counter* 0)
793 (defun gvarname (symbol)
794 (concat "v" (integer-to-string (incf *variable-counter*))))
796 (defun translate-variable (symbol)
797 (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
799 (defun extend-local-env (args)
800 (let ((new (copy-lexenv *environment*)))
801 (dolist (symbol args new)
802 (let ((b (make-binding symbol 'lexical-variable (gvarname symbol) t)))
803 (push-to-lexenv b new 'variable)))))
805 ;;; Toplevel compilations
806 (defvar *toplevel-compilations* nil)
808 (defun toplevel-compilation (string)
809 (push string *toplevel-compilations*))
811 (defun null-or-empty-p (x)
814 (defun get-toplevel-compilations ()
815 (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
817 (defun %compile-defmacro (name lambda)
818 (toplevel-compilation (ls-compile `',name))
819 (push-to-lexenv (make-binding name 'macro lambda t) *environment* 'function))
821 (defvar *compilations* nil)
823 (defun ls-compile-block (sexps &optional return-last-p)
825 (concat (ls-compile-block (butlast sexps))
826 "return " (ls-compile (car (last sexps))) ";")
828 (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
829 (concat ";" *newline*))))
831 (defmacro define-compilation (name args &body body)
832 ;; Creates a new primitive `name' with parameters args and
833 ;; @body. The body can access to the local environment through the
834 ;; variable *ENVIRONMENT*.
835 `(push (list ',name (lambda ,args (block ,name ,@body)))
838 (define-compilation if (condition true false)
839 (concat "(" (ls-compile condition) " !== " (ls-compile nil)
840 " ? " (ls-compile true)
841 " : " (ls-compile false)
844 (defvar *lambda-list-keywords* '(&optional &rest))
846 (defun list-until-keyword (list)
847 (if (or (null list) (member (car list) *lambda-list-keywords*))
849 (cons (car list) (list-until-keyword (cdr list)))))
851 (defun lambda-list-required-arguments (lambda-list)
852 (list-until-keyword lambda-list))
854 (defun lambda-list-optional-arguments-with-default (lambda-list)
855 (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
857 (defun lambda-list-optional-arguments (lambda-list)
858 (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
860 (defun lambda-list-rest-argument (lambda-list)
861 (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
863 (error "Bad lambda-list"))
866 (define-compilation lambda (lambda-list &rest body)
867 (let ((required-arguments (lambda-list-required-arguments lambda-list))
868 (optional-arguments (lambda-list-optional-arguments lambda-list))
869 (rest-argument (lambda-list-rest-argument lambda-list)))
870 (let ((n-required-arguments (length required-arguments))
871 (n-optional-arguments (length optional-arguments))
872 (*environment* (extend-local-env
873 (append (ensure-list rest-argument)
875 optional-arguments))))
876 (concat "(function ("
877 (join (mapcar #'translate-variable
878 (append required-arguments optional-arguments))
881 ;; Check number of arguments
883 (if required-arguments
884 (concat "if (arguments.length < " (integer-to-string n-required-arguments)
885 ") throw 'too few arguments';" *newline*)
887 (if (not rest-argument)
888 (concat "if (arguments.length > "
889 (integer-to-string (+ n-required-arguments n-optional-arguments))
890 ") throw 'too many arguments';" *newline*)
892 ;; Optional arguments
893 (if optional-arguments
894 (concat "switch(arguments.length){" *newline*
895 (let ((optional-and-defaults
896 (lambda-list-optional-arguments-with-default lambda-list))
900 (while (< idx n-optional-arguments)
901 (let ((arg (nth idx optional-and-defaults)))
902 (push (concat "case "
903 (integer-to-string (+ idx n-required-arguments)) ":" *newline*
904 (translate-variable (car arg))
906 (ls-compile (cadr arg))
910 (push (concat "default: break;" *newline*) cases)
911 (join (reverse cases))))
914 ;; &rest/&body argument
916 (let ((js!rest (translate-variable rest-argument)))
917 (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
918 "for (var i = arguments.length-1; i>="
919 (integer-to-string (+ n-required-arguments n-optional-arguments))
921 (indent js!rest " = "
922 "{car: arguments[i], cdr: ") js!rest "};"
926 (ls-compile-block body t)) *newline*
929 (define-compilation setq (var val)
930 (let ((b (lookup-in-lexenv var *environment* 'variable)))
931 (if (eq (binding-type b) 'lexical-variable)
932 (concat (binding-value b) " = " (ls-compile val))
933 (ls-compile `(set ',var ,val)))))
935 ;;; FFI Variable accessors
936 (define-compilation js-vref (var)
939 (define-compilation js-vset (var val)
940 (concat "(" var " = " (ls-compile val) ")"))
944 (defun escape-string (string)
947 (size (length string)))
948 (while (< index size)
949 (let ((ch (char string index)))
950 (when (or (char= ch #\") (char= ch #\\))
951 (setq output (concat output "\\")))
952 (when (or (char= ch #\newline))
953 (setq output (concat output "\\"))
955 (setq output (concat output (string ch))))
960 (defvar *literal-symbols* nil)
961 (defvar *literal-counter* 0)
964 (concat "l" (integer-to-string (incf *literal-counter*))))
966 (defun literal (sexp &optional recursive)
968 ((integerp sexp) (integer-to-string sexp))
969 ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
971 (or (cdr (assoc sexp *literal-symbols*))
973 (s #+common-lisp (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
974 #+ecmalisp (ls-compile `(intern ,(symbol-name sexp)))))
975 (push (cons sexp v) *literal-symbols*)
976 (toplevel-compilation (concat "var " v " = " s))
979 (let ((c (concat "{car: " (literal (car sexp) t) ", "
980 "cdr: " (literal (cdr sexp) t) "}")))
984 (toplevel-compilation (concat "var " v " = " c))
987 (define-compilation quote (sexp)
990 (define-compilation %while (pred &rest body)
992 "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
993 (indent (ls-compile-block body))
995 "return " (ls-compile nil) ";" *newline*))
997 (define-compilation function (x)
999 ((and (listp x) (eq (car x) 'lambda))
1002 (ls-compile `(symbol-function ',x)))))
1004 (define-compilation eval-when-compile (&rest body)
1005 (eval (cons 'progn body))
1008 (defmacro define-transformation (name args form)
1009 `(define-compilation ,name ,args
1010 (ls-compile ,form)))
1012 (define-compilation progn (&rest body)
1013 (js!selfcall (ls-compile-block body t)))
1015 (defun dynamic-binding-wrapper (bindings body)
1021 "var tmp;" *newline*
1024 (let ((s (ls-compile `(quote ,(car b)))))
1025 (concat "tmp = " s ".value;" *newline*
1026 s ".value = " (cdr b) ";" *newline*
1027 (cdr b) " = tmp;" *newline*)))
1031 "finally {" *newline*
1035 (let ((s (ls-compile `(quote ,(car b)))))
1036 (concat s ".value" " = " (cdr b))))
1038 (concat ";" *newline*)))
1042 (define-compilation let (bindings &rest body)
1043 (let ((bindings (mapcar #'ensure-list bindings)))
1044 (let ((variables (mapcar #'first bindings))
1045 (values (mapcar #'second bindings)))
1046 (let ((cvalues (mapcar #'ls-compile values))
1047 (*environment* (extend-local-env (remove-if #'boundp variables)))
1049 (concat "(function("
1050 (join (mapcar (lambda (x)
1052 (let ((v (gvarname x)))
1053 (push (cons x v) dynamic-bindings)
1055 (translate-variable x)))
1059 (let ((body (ls-compile-block body t)))
1060 (indent (dynamic-binding-wrapper dynamic-bindings body)))
1061 "})(" (join cvalues ",") ")")))))
1064 (defvar *block-counter* 0)
1066 (define-compilation block (name &rest body)
1067 (let ((tr (integer-to-string (incf *block-counter*))))
1068 (let ((b (make-binding name 'block tr t)))
1071 (let ((*environment* (extend-lexenv (list b) *environment* 'block)))
1072 (indent "return " (ls-compile `(progn ,@body)) ";" *newline*))
1074 "catch (cf){" *newline*
1075 " if (cf.type == 'block' && cf.id == " tr ")" *newline*
1076 " return cf.value;" *newline*
1078 " throw cf;" *newline*
1081 (define-compilation return-from (name &optional value)
1082 (let ((b (lookup-in-lexenv name *environment* 'block)))
1087 "id: " (binding-value b) ", "
1088 "value: " (ls-compile value) ", "
1089 "message: 'Return from unknown block " (symbol-name name) ".'"
1091 (error (concat "Unknown block `" (symbol-name name) "'.")))))
1094 (define-compilation catch (id &rest body)
1096 "var id = " (ls-compile id) ";" *newline*
1098 (indent "return " (ls-compile `(progn ,@body))
1101 "catch (cf){" *newline*
1102 " if (cf.type == 'catch' && cf.id == id)" *newline*
1103 " return cf.value;" *newline*
1105 " throw cf;" *newline*
1108 (define-compilation throw (id &optional value)
1112 "id: " (ls-compile id) ", "
1113 "value: " (ls-compile value) ", "
1114 "message: 'Throw uncatched.'"
1118 (defvar *tagbody-counter* 0)
1119 (defvar *go-tag-counter* 0)
1122 (or (integerp x) (symbolp x)))
1124 (defun declare-tagbody-tags (tbidx body)
1126 (mapcar (lambda (label)
1127 (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1128 (make-binding label 'gotag (list tbidx tagidx) t)))
1129 (remove-if-not #'go-tag-p body))))
1130 (extend-lexenv bindings *environment* 'gotag)))
1132 (define-compilation tagbody (&rest body)
1133 ;; Ignore the tagbody if it does not contain any go-tag. We do this
1134 ;; because 1) it is easy and 2) many built-in forms expand to a
1135 ;; implicit tagbody, so we save some space.
1136 (unless (some #'go-tag-p body)
1137 (return-from tagbody (ls-compile `(progn ,@body nil))))
1138 ;; The translation assumes the first form in BODY is a label
1139 (unless (go-tag-p (car body))
1140 (push (gensym "START") body))
1141 ;; Tagbody compilation
1142 (let ((tbidx (integer-to-string *tagbody-counter*)))
1143 (let ((*environment* (declare-tagbody-tags tbidx body))
1145 (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1146 (setq initag (second (binding-value b))))
1148 "var tagbody_" tbidx " = " initag ";" *newline*
1150 "while (true) {" *newline*
1151 (indent "try {" *newline*
1152 (indent (let ((content ""))
1153 (concat "switch(tagbody_" tbidx "){" *newline*
1154 "case " initag ":" *newline*
1155 (dolist (form (cdr body) content)
1157 (if (not (go-tag-p form))
1158 (indent (ls-compile form) ";" *newline*)
1159 (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1160 (concat "case " (second (binding-value b)) ":" *newline*)))))
1161 "default:" *newline*
1162 " break tbloop;" *newline*
1165 "catch (jump) {" *newline*
1166 " if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1167 " tagbody_" tbidx " = jump.label;" *newline*
1169 " throw(jump);" *newline*
1172 "return " (ls-compile nil) ";" *newline*))))
1174 (define-compilation go (label)
1175 (let ((b (lookup-in-lexenv label *environment* 'gotag))
1177 ((symbolp label) (symbol-name label))
1178 ((integerp label) (integer-to-string label)))))
1183 "id: " (first (binding-value b)) ", "
1184 "label: " (second (binding-value b)) ", "
1185 "message: 'Attempt to GO to non-existing tag " n "'"
1187 (error (concat "Unknown tag `" n "'.")))))
1190 (define-compilation unwind-protect (form &rest clean-up)
1192 "var ret = " (ls-compile nil) ";" *newline*
1194 (indent "ret = " (ls-compile form) ";" *newline*)
1195 "} finally {" *newline*
1196 (indent (ls-compile-block clean-up))
1198 "return ret;" *newline*))
1201 ;;; A little backquote implementation without optimizations of any
1202 ;;; kind for ecmalisp.
1203 (defun backquote-expand-1 (form)
1209 ((eq (car form) 'unquote)
1211 ((eq (car form) 'backquote)
1212 (backquote-expand-1 (backquote-expand-1 (cadr form))))
1217 ((and (listp s) (eq (car s) 'unquote))
1218 (list 'list (cadr s)))
1219 ((and (listp s) (eq (car s) 'unquote-splicing))
1222 (list 'list (backquote-expand-1 s)))))
1225 (defun backquote-expand (form)
1226 (if (and (listp form) (eq (car form) 'backquote))
1227 (backquote-expand-1 (cadr form))
1230 (defmacro backquote (form)
1231 (backquote-expand-1 form))
1233 (define-transformation backquote (form)
1234 (backquote-expand-1 form))
1238 (defmacro define-builtin (name args &body body)
1240 (define-compilation ,name ,args
1241 (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1244 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1245 (defmacro type-check (decls &body body)
1247 ,@(mapcar (lambda (decl)
1248 `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1250 ,@(mapcar (lambda (decl)
1251 `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1252 (indent "throw 'The value ' + "
1254 " + ' is not a type "
1259 (concat "return " (progn ,@body) ";" *newline*)))
1261 (defun num-op-num (x op y)
1262 (type-check (("x" "number" x) ("y" "number" y))
1263 (concat "x" op "y")))
1265 (define-builtin + (x y) (num-op-num x "+" y))
1266 (define-builtin - (x y) (num-op-num x "-" y))
1267 (define-builtin * (x y) (num-op-num x "*" y))
1268 (define-builtin / (x y) (num-op-num x "/" y))
1270 (define-builtin mod (x y) (num-op-num x "%" y))
1272 (define-builtin < (x y) (js!bool (num-op-num x "<" y)))
1273 (define-builtin > (x y) (js!bool (num-op-num x ">" y)))
1274 (define-builtin = (x y) (js!bool (num-op-num x "==" y)))
1275 (define-builtin <= (x y) (js!bool (num-op-num x "<=" y)))
1276 (define-builtin >= (x y) (js!bool (num-op-num x ">=" y)))
1278 (define-builtin numberp (x)
1279 (js!bool (concat "(typeof (" x ") == \"number\")")))
1281 (define-builtin floor (x)
1282 (type-check (("x" "number" x))
1285 (define-builtin cons (x y)
1286 (concat "({car: " x ", cdr: " y "})"))
1288 (define-builtin consp (x)
1291 "var tmp = " x ";" *newline*
1292 "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1294 (define-builtin car (x)
1296 "var tmp = " x ";" *newline*
1297 "return tmp === " (ls-compile nil)
1298 "? " (ls-compile nil)
1299 ": tmp.car;" *newline*))
1301 (define-builtin cdr (x)
1303 "var tmp = " x ";" *newline*
1304 "return tmp === " (ls-compile nil) "? "
1306 ": tmp.cdr;" *newline*))
1308 (define-builtin setcar (x new)
1309 (type-check (("x" "object" x))
1310 (concat "(x.car = " new ")")))
1312 (define-builtin setcdr (x new)
1313 (type-check (("x" "object" x))
1314 (concat "(x.cdr = " new ")")))
1316 (define-builtin symbolp (x)
1319 "var tmp = " x ";" *newline*
1320 "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1322 (define-builtin make-symbol (name)
1323 (type-check (("name" "string" name))
1326 (define-builtin symbol-name (x)
1327 (concat "(" x ").name"))
1329 (define-builtin set (symbol value)
1330 (concat "(" symbol ").value = " value))
1332 (define-builtin fset (symbol value)
1333 (concat "(" symbol ").function = " value))
1335 (define-builtin boundp (x)
1336 (js!bool (concat "(" x ".value !== undefined)")))
1338 (define-builtin symbol-value (x)
1340 "var symbol = " x ";" *newline*
1341 "var value = symbol.value;" *newline*
1342 "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1343 "return value;" *newline*))
1345 (define-builtin symbol-function (x)
1347 "var symbol = " x ";" *newline*
1348 "var func = symbol.function;" *newline*
1349 "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1350 "return func;" *newline*))
1352 (define-builtin symbol-plist (x)
1353 (concat "((" x ").plist || " (ls-compile nil) ")"))
1355 (define-builtin lambda-code (x)
1356 (concat "(" x ").toString()"))
1359 (define-builtin eq (x y) (js!bool (concat "(" x " === " y ")")))
1360 (define-builtin equal (x y) (js!bool (concat "(" x " == " y ")")))
1362 (define-builtin string (x)
1363 (type-check (("x" "number" x))
1364 "String.fromCharCode(x)"))
1366 (define-builtin stringp (x)
1367 (js!bool (concat "(typeof(" x ") == \"string\")")))
1369 (define-builtin string-upcase (x)
1370 (type-check (("x" "string" x))
1373 (define-builtin string-length (x)
1374 (type-check (("x" "string" x))
1377 (define-compilation slice (string a &optional b)
1379 "var str = " (ls-compile string) ";" *newline*
1380 "var a = " (ls-compile a) ";" *newline*
1383 (concat "b = " (ls-compile b) ";" *newline*)
1385 "return str.slice(a,b);" *newline*))
1387 (define-builtin char (string index)
1388 (type-check (("string" "string" string)
1389 ("index" "number" index))
1390 "string.charCodeAt(index)"))
1392 (define-builtin concat-two (string1 string2)
1393 (type-check (("string1" "string" string1)
1394 ("string2" "string" string2))
1395 "string1.concat(string2)"))
1397 (define-compilation funcall (func &rest args)
1398 (concat "(" (ls-compile func) ")("
1399 (join (mapcar #'ls-compile args)
1403 (define-compilation apply (func &rest args)
1405 (concat "(" (ls-compile func) ")()")
1406 (let ((args (butlast args))
1407 (last (car (last args))))
1409 "var f = " (ls-compile func) ";" *newline*
1410 "var args = [" (join (mapcar #'ls-compile args)
1413 "var tail = (" (ls-compile last) ");" *newline*
1414 "while (tail != " (ls-compile nil) "){" *newline*
1415 " args.push(tail.car);" *newline*
1416 " tail = tail.cdr;" *newline*
1418 "return f.apply(this, args);" *newline*))))
1420 (define-builtin js-eval (string)
1421 (type-check (("string" "string" string))
1422 "eval.apply(window, [string])"))
1424 (define-builtin error (string)
1425 (js!selfcall "throw " string ";" *newline*))
1427 (define-builtin new () "{}")
1429 (define-builtin oget (object key)
1431 "var tmp = " "(" object ")[" key "];" *newline*
1432 "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1434 (define-builtin oset (object key value)
1435 (concat "((" object ")[" key "] = " value ")"))
1437 (define-builtin in (key object)
1438 (js!bool (concat "((" key ") in (" object "))")))
1440 (define-builtin functionp (x)
1441 (js!bool (concat "(typeof " x " == 'function')")))
1443 (define-builtin write-string (x)
1444 (type-check (("x" "string" x))
1449 (let ((b (lookup-in-lexenv x *environment* 'function)))
1450 (and (eq (binding-type b) 'macro)
1453 (defun ls-macroexpand-1 (form)
1454 (let ((macro-binding (macro (car form))))
1456 (apply (eval (binding-value macro-binding)) (cdr form))
1459 (defun compile-funcall (function args)
1460 (concat (ls-compile `#',function) "("
1461 (join (mapcar #'ls-compile args)
1465 (defun ls-compile (sexp)
1468 (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1469 (if (eq (binding-type b) 'lexical-variable)
1471 (ls-compile `(symbol-value ',sexp)))))
1472 ((integerp sexp) (integer-to-string sexp))
1473 ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1475 (if (assoc (car sexp) *compilations*)
1476 (let ((comp (second (assoc (car sexp) *compilations*))))
1477 (apply comp (cdr sexp)))
1478 (if (macro (car sexp))
1479 (ls-compile (ls-macroexpand-1 sexp))
1480 (compile-funcall (car sexp) (cdr sexp)))))))
1482 (defun ls-compile-toplevel (sexp)
1483 (let ((*toplevel-compilations* nil))
1485 ((and (consp sexp) (eq (car sexp) 'progn))
1486 (let ((subs (mapcar #'ls-compile-toplevel (cdr sexp))))
1487 (join (remove-if #'null-or-empty-p subs))))
1489 (let ((code (ls-compile sexp)))
1490 (concat (join-trailing (get-toplevel-compilations)
1491 (concat ";" *newline*))
1493 (concat code ";" *newline*)
1497 ;;; Once we have the compiler, we define the runtime environment and
1498 ;;; interactive development (eval), which works calling the compiler
1499 ;;; and evaluating the Javascript result globally.
1503 (defmacro with-compilation-unit (&body body)
1506 (setq *compilation-unit-checks* nil)
1507 (clear-undeclared-global-bindings)
1509 (dolist (check *compilation-unit-checks*)
1514 (with-compilation-unit
1515 (ls-compile-toplevel x))))
1518 (js-eval "var lisp")
1519 (js-vset "lisp" (new))
1520 (js-vset "lisp.read" #'ls-read-from-string)
1521 (js-vset "lisp.print" #'prin1-to-string)
1522 (js-vset "lisp.eval" #'eval)
1523 (js-vset "lisp.compile" #'ls-compile-toplevel)
1524 (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
1525 (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str))))
1527 ;; Set the initial global environment to be equal to the host global
1528 ;; environment at this point of the compilation.
1530 (toplevel-compilation
1533 ,@(mapcar (lambda (s)
1534 `(oset *package* ,(symbol-name (car s))
1535 (js-vref ,(cdr s))))
1537 (setq *literal-symbols* ',*literal-symbols*)
1538 (setq *environment* ',*environment*)
1539 (setq *variable-counter* ,*variable-counter*)
1540 (setq *gensym-counter* ,*gensym-counter*)
1541 (setq *block-counter* ,*block-counter*)))))
1544 (toplevel-compilation
1546 `(setq *literal-counter* ,*literal-counter*)))))
1549 ;;; Finally, we provide a couple of functions to easily bootstrap
1550 ;;; this. It just calls the compiler with this file as input.
1554 (defun read-whole-file (filename)
1555 (with-open-file (in filename)
1556 (let ((seq (make-array (file-length in) :element-type 'character)))
1557 (read-sequence seq in)
1560 (defun ls-compile-file (filename output)
1561 (setq *compilation-unit-checks* nil)
1562 (with-open-file (out output :direction :output :if-exists :supersede)
1563 (let* ((source (read-whole-file filename))
1564 (in (make-string-stream source)))
1566 for x = (ls-read in)
1568 for compilation = (ls-compile-toplevel x)
1569 when (plusp (length compilation))
1570 do (write-string compilation out))
1571 (dolist (check *compilation-unit-checks*)
1573 (setq *compilation-unit-checks* nil))))
1576 (setq *environment* (make-lexenv))
1577 (setq *literal-symbols* nil)
1578 (setq *variable-counter* 0
1582 (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))