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)
39 (defmacro declaim (&rest decls)
41 ,@(mapcar (lambda (decl) `(!proclaim ',decl)) decls)))
43 (declaim (constant nil t))
47 (defmacro when (condition &body body)
48 `(if ,condition (progn ,@body) nil))
50 (defmacro unless (condition &body body)
51 `(if ,condition nil (progn ,@body)))
53 (defmacro defvar (name value &optional docstring)
55 (unless (boundp ',name)
57 ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
60 (defmacro defparameter (name value &optional docstring)
63 ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
66 (defmacro named-lambda (name args &rest body)
67 (let ((x (gensym "FN")))
68 `(let ((,x (lambda ,args ,@body)))
69 (oset ,x "fname" ,name)
72 (defmacro defun (name args &rest body)
74 (declaim (non-overridable ,name))
76 (named-lambda ,(symbol-name name) ,args
77 ,@(if (and (stringp (car body)) (not (null (cdr body))))
78 `(,(car body) (block ,name ,@(cdr body)))
79 `((block ,name ,@body)))))
82 (defvar *package* (new))
87 (defmacro return (&optional value)
88 `(return-from nil ,value))
90 (defmacro while (condition &body body)
91 `(block nil (%while ,condition ,@body)))
99 (oset *package* name (make-symbol name))))
101 (defun find-symbol (name)
102 (oget *package* name))
104 (defvar *gensym-counter* 0)
105 (defun gensym (&optional (prefix "G"))
106 (setq *gensym-counter* (+ *gensym-counter* 1))
107 (make-symbol (concat-two prefix (integer-to-string *gensym-counter*))))
113 (defun = (x y) (= x y))
114 (defun + (x y) (+ x y))
115 (defun - (x y) (- x y))
116 (defun * (x y) (* x y))
117 (defun / (x y) (/ x y))
118 (defun 1+ (x) (+ x 1))
119 (defun 1- (x) (- x 1))
120 (defun zerop (x) (= x 0))
121 (defun truncate (x y) (floor (/ x y)))
123 (defun eql (x y) (eq x y))
125 (defun not (x) (if x nil t))
127 (defun cons (x y ) (cons x y))
128 (defun consp (x) (consp x))
131 "Return the CAR part of a cons, or NIL if X is null."
134 (defun cdr (x) (cdr x))
135 (defun caar (x) (car (car x)))
136 (defun cadr (x) (car (cdr x)))
137 (defun cdar (x) (cdr (car x)))
138 (defun cddr (x) (cdr (cdr x)))
139 (defun caddr (x) (car (cdr (cdr x))))
140 (defun cdddr (x) (cdr (cdr (cdr x))))
141 (defun cadddr (x) (car (cdr (cdr (cdr x)))))
142 (defun first (x) (car x))
143 (defun second (x) (cadr x))
144 (defun third (x) (caddr x))
145 (defun fourth (x) (cadddr x))
147 (defun list (&rest args) args)
153 (defmacro incf (x &optional (delta 1))
154 `(setq ,x (+ ,x ,delta)))
156 (defmacro decf (x &optional (delta 1))
157 `(setq ,x (- ,x ,delta)))
159 (defmacro push (x place)
160 `(setq ,place (cons ,x ,place)))
162 (defmacro dolist (iter &body body)
163 (let ((var (first iter))
166 (let ((,g!list ,(second iter))
169 (setq ,var (car ,g!list))
171 (setq ,g!list (cdr ,g!list)))
174 (defmacro dotimes (iter &body body)
175 (let ((g!to (gensym))
178 (result (third iter)))
182 (%while (< ,var ,g!to)
187 (defmacro cond (&rest clausules)
190 (if (eq (caar clausules) t)
191 `(progn ,@(cdar clausules))
192 `(if ,(caar clausules)
193 (progn ,@(cdar clausules))
194 (cond ,@(cdr clausules))))))
196 (defmacro case (form &rest clausules)
197 (let ((!form (gensym)))
198 `(let ((,!form ,form))
200 ,@(mapcar (lambda (clausule)
201 (if (eq (car clausule) t)
203 `((eql ,!form ',(car clausule))
207 (defmacro ecase (form &rest clausules)
212 (error "ECASE expression failed."))))))
214 (defmacro and (&rest forms)
225 (defmacro or (&rest forms)
233 `(let ((,g ,(car forms)))
234 (if ,g ,g (or ,@(cdr forms))))))))
236 (defmacro prog1 (form &body body)
237 (let ((value (gensym)))
238 `(let ((,value ,form))
242 (defmacro prog2 (form1 result &body body)
243 `(prog1 (progn ,form1 ,result) ,@body)))
246 ;;; This couple of helper functions will be defined in both Common
247 ;;; Lisp and in Ecmalisp.
248 (defun ensure-list (x)
253 (defun !reduce (func list initial)
258 (funcall func initial (car list)))))
260 ;;; Go on growing the Lisp language in Ecmalisp, with more high
261 ;;; level utilities as well as correct versions of other
265 (defun append-two (list1 list2)
269 (append (cdr list1) list2))))
271 (defun append (&rest lists)
272 (!reduce #'append-two lists '()))
274 (defun revappend (list1 list2)
276 (push (car list1) list2)
277 (setq list1 (cdr list1)))
280 (defun reverse (list)
281 (revappend list '()))
283 (defun list-length (list)
285 (while (not (null list))
287 (setq list (cdr list)))
295 (defun concat-two (s1 s2)
298 (defun mapcar (func list)
301 (cons (funcall func (car list))
302 (mapcar func (cdr list)))))
304 (defun identity (x) x)
307 (mapcar #'identity x))
309 (defun code-char (x) x)
310 (defun char-code (x) x)
311 (defun char= (x y) (= x y))
314 (and (numberp x) (= (floor x) x)))
316 (defun plusp (x) (< 0 x))
317 (defun minusp (x) (< x 0))
320 (or (consp x) (null x)))
322 (defun nthcdr (n list)
323 (while (and (plusp n) list)
325 (setq list (cdr list)))
329 (car (nthcdr n list)))
332 (while (consp (cdr x))
338 (cons (car x) (butlast (cdr x)))))
340 (defun member (x list)
342 (when (eql x (car list))
344 (setq list (cdr list))))
346 (defun remove (x list)
351 (remove x (cdr list)))
353 (cons (car list) (remove x (cdr list))))))
355 (defun remove-if (func list)
359 ((funcall func (car list))
360 (remove-if func (cdr list)))
362 (cons (car list) (remove-if func (cdr list))))))
364 (defun remove-if-not (func list)
368 ((funcall func (car list))
369 (cons (car list) (remove-if-not func (cdr list))))
371 (remove-if-not func (cdr list)))))
373 (defun digit-char-p (x)
374 (if (and (<= #\0 x) (<= x #\9))
378 (defun subseq (seq a &optional b)
385 (error "Unsupported argument."))))
387 (defun parse-integer (string)
390 (size (length string)))
391 (while (< index size)
392 (setq value (+ (* value 10) (digit-char-p (char string index))))
396 (defun some (function seq)
401 (while (< index size)
402 (when (funcall function (char seq index))
403 (return-from some t))
408 (when (funcall function x)
411 (error "Unknown sequence."))))
413 (defun every (function seq)
418 (while (< index size)
419 (unless (funcall function (char seq index))
420 (return-from every nil))
425 (unless (funcall function x)
428 (error "Unknown sequence."))))
430 (defun assoc (x alist)
432 (if (eql x (caar alist))
434 (setq alist (cdr alist))))
437 (defun string= (s1 s2)
440 (defun fdefinition (x)
447 (error "Invalid function"))))
449 (defun disassemble (function)
450 (write-line (lambda-code (fdefinition function)))
453 (defun documentation (x type)
454 "Return the documentation of X. TYPE must be the symbol VARIABLE or FUNCTION."
457 (let ((func (fdefinition x)))
458 (oget func "docstring")))
461 (error "Wrong argument type! it should be a symbol"))
465 ;;; The compiler offers some primitives and special forms which are
466 ;;; not found in Common Lisp, for instance, while. So, we grow Common
467 ;;; Lisp a bit to it can execute the rest of the file.
470 (defmacro while (condition &body body)
475 (defmacro eval-when-compile (&body body)
476 `(eval-when (:compile-toplevel :load-toplevel :execute)
479 (defun concat-two (s1 s2)
480 (concatenate 'string s1 s2))
482 (defun setcar (cons new)
483 (setf (car cons) new))
484 (defun setcdr (cons new)
485 (setf (cdr cons) new)))
487 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
488 ;;; from here, this code will compile on both. We define some helper
489 ;;; functions now for string manipulation and so on. They will be
490 ;;; useful in the compiler, mostly.
492 (defvar *newline* (string (code-char 10)))
494 (defun concat (&rest strs)
495 (!reduce #'concat-two strs ""))
497 (defmacro concatf (variable &body form)
498 `(setq ,variable (concat ,variable (progn ,@form))))
500 ;;; Concatenate a list of strings, with a separator
501 (defun join (list &optional (separator ""))
510 (join (cdr list) separator)))))
512 (defun join-trailing (list &optional (separator ""))
515 (concat (car list) separator (join-trailing (cdr list) separator))))
517 (defun mapconcat (func list)
518 (join (mapcar func list)))
520 ;;; Like CONCAT, but prefix each line with four spaces. Two versions
521 ;;; of this function are available, because the Ecmalisp version is
522 ;;; very slow and bootstraping was annoying.
525 (defun indent (&rest string)
526 (let ((input (join string)))
529 (size (length input)))
530 (when (plusp (length input)) (concatf output " "))
531 (while (< index size)
533 (if (and (char= (char input index) #\newline)
535 (not (char= (char input (1+ index)) #\newline)))
536 (concat (string #\newline) " ")
537 (string (char input index)))))
538 (concatf output str))
543 (defun indent (&rest string)
544 (with-output-to-string (*standard-output*)
545 (with-input-from-string (input (join string))
547 for line = (read-line input nil)
549 do (write-string " ")
550 do (write-line line)))))
553 (defun integer-to-string (x)
558 (concat "-" (integer-to-string (- 0 x))))
561 (while (not (zerop x))
562 (push (mod x 10) digits)
563 (setq x (truncate x 10)))
564 (join (mapcar (lambda (d) (string (char "0123456789" d)))
568 ;;; Wrap X with a Javascript code to convert the result from
569 ;;; Javascript generalized booleans to T or NIL.
571 (concat "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
573 ;;; Concatenate the arguments and wrap them with a self-calling
574 ;;; Javascript anonymous function. It is used to make some Javascript
575 ;;; statements valid expressions and provide a private scope as well.
576 ;;; It could be defined as function, but we could do some
577 ;;; preprocessing in the future.
578 (defmacro js!selfcall (&body body)
579 `(concat "(function(){" *newline* (indent ,@body) "})()"))
586 (defun prin1-to-string (form)
588 ((symbolp form) (symbol-name form))
589 ((integerp form) (integer-to-string form))
590 ((stringp form) (concat "\"" (escape-string form) "\""))
592 (let ((name (oget form "fname")))
594 (concat "#<FUNCTION " name ">")
595 (concat "#<FUNCTION>"))))
598 (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
599 (let ((last (last form)))
600 (if (null (cdr last))
601 (prin1-to-string (car last))
602 (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
605 (defun write-line (x)
607 (write-string *newline*)
611 (write-string "WARNING: ")
615 (write-line (prin1-to-string x))
621 ;;; The Lisp reader, parse strings and return Lisp objects. The main
622 ;;; entry points are `ls-read' and `ls-read-from-string'.
624 (defun make-string-stream (string)
627 (defun %peek-char (stream)
628 (and (< (cdr stream) (length (car stream)))
629 (char (car stream) (cdr stream))))
631 (defun %read-char (stream)
632 (and (< (cdr stream) (length (car stream)))
633 (prog1 (char (car stream) (cdr stream))
634 (setcdr stream (1+ (cdr stream))))))
636 (defun whitespacep (ch)
637 (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
639 (defun skip-whitespaces (stream)
641 (setq ch (%peek-char stream))
642 (while (and ch (whitespacep ch))
644 (setq ch (%peek-char stream)))))
646 (defun terminalp (ch)
647 (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
649 (defun read-until (stream func)
652 (setq ch (%peek-char stream))
653 (while (and ch (not (funcall func ch)))
654 (setq string (concat string (string ch)))
656 (setq ch (%peek-char stream)))
659 (defun skip-whitespaces-and-comments (stream)
661 (skip-whitespaces stream)
662 (setq ch (%peek-char stream))
663 (while (and ch (char= ch #\;))
664 (read-until stream (lambda (x) (char= x #\newline)))
665 (skip-whitespaces stream)
666 (setq ch (%peek-char stream)))))
668 (defun %read-list (stream)
669 (skip-whitespaces-and-comments stream)
670 (let ((ch (%peek-char stream)))
673 (error "Unspected EOF"))
679 (prog1 (ls-read stream)
680 (skip-whitespaces-and-comments stream)
681 (unless (char= (%read-char stream) #\))
682 (error "')' was expected."))))
684 (cons (ls-read stream) (%read-list stream))))))
686 (defun read-string (stream)
689 (setq ch (%read-char stream))
690 (while (not (eql ch #\"))
692 (error "Unexpected EOF"))
694 (setq ch (%read-char stream)))
695 (setq string (concat string (string ch)))
696 (setq ch (%read-char stream)))
699 (defun read-sharp (stream)
701 (ecase (%read-char stream)
703 (list 'function (ls-read stream)))
706 (concat (string (%read-char stream))
707 (read-until stream #'terminalp))))
709 ((string= cname "space") (char-code #\space))
710 ((string= cname "tab") (char-code #\tab))
711 ((string= cname "newline") (char-code #\newline))
712 (t (char-code (char cname 0))))))
714 (let ((feature (read-until stream #'terminalp)))
716 ((string= feature "common-lisp")
717 (ls-read stream) ;ignore
719 ((string= feature "ecmalisp")
722 (error "Unknown reader form.")))))))
724 (defvar *eof* (make-symbol "EOF"))
725 (defun ls-read (stream)
726 (skip-whitespaces-and-comments stream)
727 (let ((ch (%peek-char stream)))
736 (list 'quote (ls-read stream)))
739 (list 'backquote (ls-read stream)))
742 (read-string stream))
745 (if (eql (%peek-char stream) #\@)
746 (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
747 (list 'unquote (ls-read stream))))
751 (let ((string (read-until stream #'terminalp)))
752 (if (every #'digit-char-p string)
753 (parse-integer string)
754 (intern (string-upcase string))))))))
756 (defun ls-read-from-string (string)
757 (ls-read (make-string-stream string)))
762 ;;; Translate the Lisp code to Javascript. It will compile the special
763 ;;; forms. Some primitive functions are compiled as special forms
764 ;;; too. The respective real functions are defined in the target (see
765 ;;; the beginning of this file) as well as some primitive functions.
767 (defvar *compilation-unit-checks* '())
769 (defun make-binding (name type value &optional declarations)
770 (list name type value declarations))
772 (defun binding-name (b) (first b))
773 (defun binding-type (b) (second b))
774 (defun binding-value (b) (third b))
775 (defun binding-declarations (b) (fourth b))
777 (defun set-binding-value (b value)
778 (setcar (cddr b) value))
780 (defun set-binding-declarations (b value)
781 (setcar (cdddr b) value))
783 (defun push-binding-declaration (decl b)
784 (set-binding-declarations b (cons decl (binding-declarations b))))
787 (defun make-lexenv ()
788 (list nil nil nil nil))
790 (defun copy-lexenv (lexenv)
793 (defun push-to-lexenv (binding lexenv namespace)
795 (variable (setcar lexenv (cons binding (car lexenv))))
796 (function (setcar (cdr lexenv) (cons binding (cadr lexenv))))
797 (block (setcar (cddr lexenv) (cons binding (caddr lexenv))))
798 (gotag (setcar (cdddr lexenv) (cons binding (cadddr lexenv))))))
800 (defun extend-lexenv (bindings lexenv namespace)
801 (let ((env (copy-lexenv lexenv)))
802 (dolist (binding (reverse bindings) env)
803 (push-to-lexenv binding env namespace))))
805 (defun lookup-in-lexenv (name lexenv namespace)
806 (assoc name (ecase namespace
807 (variable (first lexenv))
808 (function (second lexenv))
809 (block (third lexenv))
810 (gotag (fourth lexenv)))))
812 (defvar *environment* (make-lexenv))
814 (defvar *variable-counter* 0)
815 (defun gvarname (symbol)
816 (concat "v" (integer-to-string (incf *variable-counter*))))
818 (defun translate-variable (symbol)
819 (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
821 (defun extend-local-env (args)
822 (let ((new (copy-lexenv *environment*)))
823 (dolist (symbol args new)
824 (let ((b (make-binding symbol 'lexical-variable (gvarname symbol))))
825 (push-to-lexenv b new 'variable)))))
827 ;;; Toplevel compilations
828 (defvar *toplevel-compilations* nil)
830 (defun toplevel-compilation (string)
831 (push string *toplevel-compilations*))
833 (defun null-or-empty-p (x)
836 (defun get-toplevel-compilations ()
837 (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
839 (defun %compile-defmacro (name lambda)
840 (toplevel-compilation (ls-compile `',name))
841 (push-to-lexenv (make-binding name 'macro lambda) *environment* 'function))
843 (defun global-binding (name type namespace)
844 (or (lookup-in-lexenv name *environment* namespace)
845 (let ((b (make-binding name type nil)))
846 (push-to-lexenv b *environment* namespace)
849 (defun claims (symbol namespace)
850 (let ((b (lookup-in-lexenv symbol *environment* namespace)))
851 (and b (binding-declarations b))))
853 (defun !proclaim (decl)
856 (dolist (name (cdr decl))
857 (let ((b (global-binding name 'function 'function)))
858 (push-binding-declaration 'notinline b))))
860 (dolist (name (cdr decl))
861 (let ((b (global-binding name 'variable 'variable)))
862 (push-binding-declaration 'constant b))))
864 (dolist (name (cdr decl))
865 (let ((b (global-binding name 'function 'function)))
866 (push-binding-declaration 'non-overridable b))))))
871 (defvar *compilations* nil)
873 (defmacro define-compilation (name args &body body)
874 ;; Creates a new primitive `name' with parameters args and
875 ;; @body. The body can access to the local environment through the
876 ;; variable *ENVIRONMENT*.
877 `(push (list ',name (lambda ,args (block ,name ,@body)))
880 (define-compilation if (condition true false)
881 (concat "(" (ls-compile condition) " !== " (ls-compile nil)
882 " ? " (ls-compile true)
883 " : " (ls-compile false)
886 (defvar *lambda-list-keywords* '(&optional &rest))
888 (defun list-until-keyword (list)
889 (if (or (null list) (member (car list) *lambda-list-keywords*))
891 (cons (car list) (list-until-keyword (cdr list)))))
893 (defun lambda-list-required-arguments (lambda-list)
894 (list-until-keyword lambda-list))
896 (defun lambda-list-optional-arguments-with-default (lambda-list)
897 (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
899 (defun lambda-list-optional-arguments (lambda-list)
900 (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
902 (defun lambda-list-rest-argument (lambda-list)
903 (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
905 (error "Bad lambda-list"))
909 (defun lambda-docstring-wrapper (docstring &rest strs)
912 "var func = " (join strs) ";" *newline*
913 "func.docstring = '" docstring "';" *newline*
914 "return func;" *newline*)
917 (define-compilation lambda (lambda-list &rest body)
918 (let ((required-arguments (lambda-list-required-arguments lambda-list))
919 (optional-arguments (lambda-list-optional-arguments lambda-list))
920 (rest-argument (lambda-list-rest-argument lambda-list))
922 ;; Get the documentation string for the lambda function
923 (when (and (stringp (car body))
924 (not (null (cdr body))))
925 (setq documentation (car body))
926 (setq body (cdr body)))
927 (let ((n-required-arguments (length required-arguments))
928 (n-optional-arguments (length optional-arguments))
929 (*environment* (extend-local-env
930 (append (ensure-list rest-argument)
932 optional-arguments))))
933 (lambda-docstring-wrapper
936 (join (mapcar #'translate-variable
937 (append required-arguments optional-arguments))
940 ;; Check number of arguments
942 (if required-arguments
943 (concat "if (arguments.length < " (integer-to-string n-required-arguments)
944 ") throw 'too few arguments';" *newline*)
946 (if (not rest-argument)
947 (concat "if (arguments.length > "
948 (integer-to-string (+ n-required-arguments n-optional-arguments))
949 ") throw 'too many arguments';" *newline*)
951 ;; Optional arguments
952 (if optional-arguments
953 (concat "switch(arguments.length){" *newline*
954 (let ((optional-and-defaults
955 (lambda-list-optional-arguments-with-default lambda-list))
959 (while (< idx n-optional-arguments)
960 (let ((arg (nth idx optional-and-defaults)))
961 (push (concat "case "
962 (integer-to-string (+ idx n-required-arguments)) ":" *newline*
963 (translate-variable (car arg))
965 (ls-compile (cadr arg))
969 (push (concat "default: break;" *newline*) cases)
970 (join (reverse cases))))
973 ;; &rest/&body argument
975 (let ((js!rest (translate-variable rest-argument)))
976 (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
977 "for (var i = arguments.length-1; i>="
978 (integer-to-string (+ n-required-arguments n-optional-arguments))
980 (indent js!rest " = "
981 "{car: arguments[i], cdr: ") js!rest "};"
985 (ls-compile-block body t)) *newline*
988 (define-compilation setq (var val)
989 (let ((b (lookup-in-lexenv var *environment* 'variable)))
990 (if (eq (binding-type b) 'lexical-variable)
991 (concat (binding-value b) " = " (ls-compile val))
992 (ls-compile `(set ',var ,val)))))
994 ;;; FFI Variable accessors
995 (define-compilation js-vref (var)
998 (define-compilation js-vset (var val)
999 (concat "(" var " = " (ls-compile val) ")"))
1003 (defun escape-string (string)
1006 (size (length string)))
1007 (while (< index size)
1008 (let ((ch (char string index)))
1009 (when (or (char= ch #\") (char= ch #\\))
1010 (setq output (concat output "\\")))
1011 (when (or (char= ch #\newline))
1012 (setq output (concat output "\\"))
1014 (setq output (concat output (string ch))))
1019 (defvar *literal-symbols* nil)
1020 (defvar *literal-counter* 0)
1023 (concat "l" (integer-to-string (incf *literal-counter*))))
1025 (defun literal (sexp &optional recursive)
1027 ((integerp sexp) (integer-to-string sexp))
1028 ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1030 (or (cdr (assoc sexp *literal-symbols*))
1032 (s #+common-lisp (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1033 #+ecmalisp (ls-compile `(intern ,(symbol-name sexp)))))
1034 (push (cons sexp v) *literal-symbols*)
1035 (toplevel-compilation (concat "var " v " = " s))
1038 (let ((c (concat "{car: " (literal (car sexp) t) ", "
1039 "cdr: " (literal (cdr sexp) t) "}")))
1043 (toplevel-compilation (concat "var " v " = " c))
1046 (define-compilation quote (sexp)
1049 (define-compilation %while (pred &rest body)
1051 "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1052 (indent (ls-compile-block body))
1054 "return " (ls-compile nil) ";" *newline*))
1056 (define-compilation function (x)
1058 ((and (listp x) (eq (car x) 'lambda))
1061 (ls-compile `(symbol-function ',x)))))
1063 (define-compilation eval-when-compile (&rest body)
1064 (eval (cons 'progn body))
1067 (defmacro define-transformation (name args form)
1068 `(define-compilation ,name ,args
1069 (ls-compile ,form)))
1071 (define-compilation progn (&rest body)
1072 (js!selfcall (ls-compile-block body t)))
1074 (defun dynamic-binding-wrapper (bindings body)
1080 "var tmp;" *newline*
1083 (let ((s (ls-compile `(quote ,(car b)))))
1084 (concat "tmp = " s ".value;" *newline*
1085 s ".value = " (cdr b) ";" *newline*
1086 (cdr b) " = tmp;" *newline*)))
1090 "finally {" *newline*
1094 (let ((s (ls-compile `(quote ,(car b)))))
1095 (concat s ".value" " = " (cdr b))))
1097 (concat ";" *newline*)))
1101 (define-compilation let (bindings &rest body)
1102 (let ((bindings (mapcar #'ensure-list bindings)))
1103 (let ((variables (mapcar #'first bindings))
1104 (values (mapcar #'second bindings)))
1105 (let ((cvalues (mapcar #'ls-compile values))
1106 (*environment* (extend-local-env (remove-if #'boundp variables)))
1108 (concat "(function("
1109 (join (mapcar (lambda (x)
1111 (let ((v (gvarname x)))
1112 (push (cons x v) dynamic-bindings)
1114 (translate-variable x)))
1118 (let ((body (ls-compile-block body t)))
1119 (indent (dynamic-binding-wrapper dynamic-bindings body)))
1120 "})(" (join cvalues ",") ")")))))
1123 (defvar *block-counter* 0)
1125 (define-compilation block (name &rest body)
1126 (let ((tr (integer-to-string (incf *block-counter*))))
1127 (let ((b (make-binding name 'block tr)))
1130 (let ((*environment* (extend-lexenv (list b) *environment* 'block)))
1131 (indent "return " (ls-compile `(progn ,@body)) ";" *newline*))
1133 "catch (cf){" *newline*
1134 " if (cf.type == 'block' && cf.id == " tr ")" *newline*
1135 " return cf.value;" *newline*
1137 " throw cf;" *newline*
1140 (define-compilation return-from (name &optional value)
1141 (let ((b (lookup-in-lexenv name *environment* 'block)))
1146 "id: " (binding-value b) ", "
1147 "value: " (ls-compile value) ", "
1148 "message: 'Return from unknown block " (symbol-name name) ".'"
1150 (error (concat "Unknown block `" (symbol-name name) "'.")))))
1153 (define-compilation catch (id &rest body)
1155 "var id = " (ls-compile id) ";" *newline*
1157 (indent "return " (ls-compile `(progn ,@body))
1160 "catch (cf){" *newline*
1161 " if (cf.type == 'catch' && cf.id == id)" *newline*
1162 " return cf.value;" *newline*
1164 " throw cf;" *newline*
1167 (define-compilation throw (id &optional value)
1171 "id: " (ls-compile id) ", "
1172 "value: " (ls-compile value) ", "
1173 "message: 'Throw uncatched.'"
1177 (defvar *tagbody-counter* 0)
1178 (defvar *go-tag-counter* 0)
1181 (or (integerp x) (symbolp x)))
1183 (defun declare-tagbody-tags (tbidx body)
1185 (mapcar (lambda (label)
1186 (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1187 (make-binding label 'gotag (list tbidx tagidx))))
1188 (remove-if-not #'go-tag-p body))))
1189 (extend-lexenv bindings *environment* 'gotag)))
1191 (define-compilation tagbody (&rest body)
1192 ;; Ignore the tagbody if it does not contain any go-tag. We do this
1193 ;; because 1) it is easy and 2) many built-in forms expand to a
1194 ;; implicit tagbody, so we save some space.
1195 (unless (some #'go-tag-p body)
1196 (return-from tagbody (ls-compile `(progn ,@body nil))))
1197 ;; The translation assumes the first form in BODY is a label
1198 (unless (go-tag-p (car body))
1199 (push (gensym "START") body))
1200 ;; Tagbody compilation
1201 (let ((tbidx (integer-to-string *tagbody-counter*)))
1202 (let ((*environment* (declare-tagbody-tags tbidx body))
1204 (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1205 (setq initag (second (binding-value b))))
1207 "var tagbody_" tbidx " = " initag ";" *newline*
1209 "while (true) {" *newline*
1210 (indent "try {" *newline*
1211 (indent (let ((content ""))
1212 (concat "switch(tagbody_" tbidx "){" *newline*
1213 "case " initag ":" *newline*
1214 (dolist (form (cdr body) content)
1216 (if (not (go-tag-p form))
1217 (indent (ls-compile form) ";" *newline*)
1218 (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1219 (concat "case " (second (binding-value b)) ":" *newline*)))))
1220 "default:" *newline*
1221 " break tbloop;" *newline*
1224 "catch (jump) {" *newline*
1225 " if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1226 " tagbody_" tbidx " = jump.label;" *newline*
1228 " throw(jump);" *newline*
1231 "return " (ls-compile nil) ";" *newline*))))
1233 (define-compilation go (label)
1234 (let ((b (lookup-in-lexenv label *environment* 'gotag))
1236 ((symbolp label) (symbol-name label))
1237 ((integerp label) (integer-to-string label)))))
1242 "id: " (first (binding-value b)) ", "
1243 "label: " (second (binding-value b)) ", "
1244 "message: 'Attempt to GO to non-existing tag " n "'"
1246 (error (concat "Unknown tag `" n "'.")))))
1249 (define-compilation unwind-protect (form &rest clean-up)
1251 "var ret = " (ls-compile nil) ";" *newline*
1253 (indent "ret = " (ls-compile form) ";" *newline*)
1254 "} finally {" *newline*
1255 (indent (ls-compile-block clean-up))
1257 "return ret;" *newline*))
1260 ;;; A little backquote implementation without optimizations of any
1261 ;;; kind for ecmalisp.
1262 (defun backquote-expand-1 (form)
1268 ((eq (car form) 'unquote)
1270 ((eq (car form) 'backquote)
1271 (backquote-expand-1 (backquote-expand-1 (cadr form))))
1276 ((and (listp s) (eq (car s) 'unquote))
1277 (list 'list (cadr s)))
1278 ((and (listp s) (eq (car s) 'unquote-splicing))
1281 (list 'list (backquote-expand-1 s)))))
1284 (defun backquote-expand (form)
1285 (if (and (listp form) (eq (car form) 'backquote))
1286 (backquote-expand-1 (cadr form))
1289 (defmacro backquote (form)
1290 (backquote-expand-1 form))
1292 (define-transformation backquote (form)
1293 (backquote-expand-1 form))
1297 (defvar *builtins* nil)
1299 (defmacro define-raw-builtin (name args &body body)
1300 ;; Creates a new primitive function `name' with parameters args and
1301 ;; @body. The body can access to the local environment through the
1302 ;; variable *ENVIRONMENT*.
1303 `(push (list ',name (lambda ,args (block ,name ,@body)))
1306 (defmacro define-builtin (name args &body body)
1308 (define-raw-builtin ,name ,args
1309 (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1312 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1313 (defmacro type-check (decls &body body)
1315 ,@(mapcar (lambda (decl)
1316 `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1318 ,@(mapcar (lambda (decl)
1319 `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1320 (indent "throw 'The value ' + "
1322 " + ' is not a type "
1327 (concat "return " (progn ,@body) ";" *newline*)))
1329 (defun num-op-num (x op y)
1330 (type-check (("x" "number" x) ("y" "number" y))
1331 (concat "x" op "y")))
1333 (define-builtin + (x y) (num-op-num x "+" y))
1334 (define-builtin - (x y) (num-op-num x "-" y))
1335 (define-builtin * (x y) (num-op-num x "*" y))
1336 (define-builtin / (x y) (num-op-num x "/" y))
1338 (define-builtin mod (x y) (num-op-num x "%" y))
1340 (define-builtin < (x y) (js!bool (num-op-num x "<" y)))
1341 (define-builtin > (x y) (js!bool (num-op-num x ">" y)))
1342 (define-builtin = (x y) (js!bool (num-op-num x "==" y)))
1343 (define-builtin <= (x y) (js!bool (num-op-num x "<=" y)))
1344 (define-builtin >= (x y) (js!bool (num-op-num x ">=" y)))
1346 (define-builtin numberp (x)
1347 (js!bool (concat "(typeof (" x ") == \"number\")")))
1349 (define-builtin floor (x)
1350 (type-check (("x" "number" x))
1353 (define-builtin cons (x y)
1354 (concat "({car: " x ", cdr: " y "})"))
1356 (define-builtin consp (x)
1359 "var tmp = " x ";" *newline*
1360 "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1362 (define-builtin car (x)
1364 "var tmp = " x ";" *newline*
1365 "return tmp === " (ls-compile nil)
1366 "? " (ls-compile nil)
1367 ": tmp.car;" *newline*))
1369 (define-builtin cdr (x)
1371 "var tmp = " x ";" *newline*
1372 "return tmp === " (ls-compile nil) "? "
1374 ": tmp.cdr;" *newline*))
1376 (define-builtin setcar (x new)
1377 (type-check (("x" "object" x))
1378 (concat "(x.car = " new ")")))
1380 (define-builtin setcdr (x new)
1381 (type-check (("x" "object" x))
1382 (concat "(x.cdr = " new ")")))
1384 (define-builtin symbolp (x)
1387 "var tmp = " x ";" *newline*
1388 "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1390 (define-builtin make-symbol (name)
1391 (type-check (("name" "string" name))
1394 (define-builtin symbol-name (x)
1395 (concat "(" x ").name"))
1397 (define-builtin set (symbol value)
1398 (concat "(" symbol ").value = " value))
1400 (define-builtin fset (symbol value)
1401 (concat "(" symbol ").function = " value))
1403 (define-builtin boundp (x)
1404 (js!bool (concat "(" x ".value !== undefined)")))
1406 (define-builtin symbol-value (x)
1408 "var symbol = " x ";" *newline*
1409 "var value = symbol.value;" *newline*
1410 "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1411 "return value;" *newline*))
1413 (define-builtin symbol-function (x)
1415 "var symbol = " x ";" *newline*
1416 "var func = symbol.function;" *newline*
1417 "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1418 "return func;" *newline*))
1420 (define-builtin symbol-plist (x)
1421 (concat "((" x ").plist || " (ls-compile nil) ")"))
1423 (define-builtin lambda-code (x)
1424 (concat "(" x ").toString()"))
1427 (define-builtin eq (x y) (js!bool (concat "(" x " === " y ")")))
1428 (define-builtin equal (x y) (js!bool (concat "(" x " == " y ")")))
1430 (define-builtin string (x)
1431 (type-check (("x" "number" x))
1432 "String.fromCharCode(x)"))
1434 (define-builtin stringp (x)
1435 (js!bool (concat "(typeof(" x ") == \"string\")")))
1437 (define-builtin string-upcase (x)
1438 (type-check (("x" "string" x))
1441 (define-builtin string-length (x)
1442 (type-check (("x" "string" x))
1445 (define-raw-builtin slice (string a &optional b)
1447 "var str = " (ls-compile string) ";" *newline*
1448 "var a = " (ls-compile a) ";" *newline*
1451 (concat "b = " (ls-compile b) ";" *newline*)
1453 "return str.slice(a,b);" *newline*))
1455 (define-builtin char (string index)
1456 (type-check (("string" "string" string)
1457 ("index" "number" index))
1458 "string.charCodeAt(index)"))
1460 (define-builtin concat-two (string1 string2)
1461 (type-check (("string1" "string" string1)
1462 ("string2" "string" string2))
1463 "string1.concat(string2)"))
1465 (define-raw-builtin funcall (func &rest args)
1466 (concat "(" (ls-compile func) ")("
1467 (join (mapcar #'ls-compile args)
1471 (define-raw-builtin apply (func &rest args)
1473 (concat "(" (ls-compile func) ")()")
1474 (let ((args (butlast args))
1475 (last (car (last args))))
1477 "var f = " (ls-compile func) ";" *newline*
1478 "var args = [" (join (mapcar #'ls-compile args)
1481 "var tail = (" (ls-compile last) ");" *newline*
1482 "while (tail != " (ls-compile nil) "){" *newline*
1483 " args.push(tail.car);" *newline*
1484 " tail = tail.cdr;" *newline*
1486 "return f.apply(this, args);" *newline*))))
1488 (define-builtin js-eval (string)
1489 (type-check (("string" "string" string))
1490 "eval.apply(window, [string])"))
1492 (define-builtin error (string)
1493 (js!selfcall "throw " string ";" *newline*))
1495 (define-builtin new () "{}")
1497 (define-builtin oget (object key)
1499 "var tmp = " "(" object ")[" key "];" *newline*
1500 "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1502 (define-builtin oset (object key value)
1503 (concat "((" object ")[" key "] = " value ")"))
1505 (define-builtin in (key object)
1506 (js!bool (concat "((" key ") in (" object "))")))
1508 (define-builtin functionp (x)
1509 (js!bool (concat "(typeof " x " == 'function')")))
1511 (define-builtin write-string (x)
1512 (type-check (("x" "string" x))
1517 (let ((b (lookup-in-lexenv x *environment* 'function)))
1518 (and (eq (binding-type b) 'macro)
1521 (defun ls-macroexpand-1 (form)
1522 (let ((macro-binding (macro (car form))))
1524 (let ((expander (binding-value macro-binding)))
1525 (when (listp expander)
1526 (let ((compiled (eval expander)))
1527 ;; The list representation are useful while
1528 ;; bootstrapping, as we can dump the definition of the
1529 ;; macros easily, but they are slow because we have to
1530 ;; evaluate them and compile them now and again. So, let
1531 ;; us replace the list representation version of the
1532 ;; function with the compiled one.
1534 #+ecmalisp (set-binding-value macro-binding compiled)
1535 (setq expander compiled)))
1536 (apply expander (cdr form)))
1539 (defun compile-funcall (function args)
1540 (if (and (symbolp function)
1541 (member 'non-overridable (claims function 'function)))
1542 (concat (ls-compile `',function) ".function("
1543 (join (mapcar #'ls-compile args)
1546 (concat (ls-compile `#',function) "("
1547 (join (mapcar #'ls-compile args)
1551 (defun ls-compile-block (sexps &optional return-last-p)
1553 (concat (ls-compile-block (butlast sexps))
1554 "return " (ls-compile (car (last sexps))) ";")
1556 (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
1557 (concat ";" *newline*))))
1559 (defun ls-compile (sexp)
1562 (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1564 ((eq (binding-type b) 'lexical-variable)
1566 ((member 'constant (binding-declarations b))
1567 (concat (ls-compile `',sexp) ".value"))
1569 (ls-compile `(symbol-value ',sexp))))))
1570 ((integerp sexp) (integer-to-string sexp))
1571 ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1573 (let ((name (car sexp))
1577 ((assoc name *compilations*)
1578 (let ((comp (second (assoc name *compilations*))))
1580 ;; Built-in functions
1581 ((and (assoc name *builtins*)
1582 (or (not (lookup-in-lexenv name *environment* 'function))
1583 (member 'notinline (claims name 'function))))
1584 (let ((comp (second (assoc name *builtins*))))
1588 (ls-compile (ls-macroexpand-1 sexp))
1589 (compile-funcall name args))))))))
1591 (defun ls-compile-toplevel (sexp)
1592 (let ((*toplevel-compilations* nil))
1594 ((and (consp sexp) (eq (car sexp) 'progn))
1595 (let ((subs (mapcar #'ls-compile-toplevel (cdr sexp))))
1596 (join (remove-if #'null-or-empty-p subs))))
1598 (let ((code (ls-compile sexp)))
1599 (concat (join-trailing (get-toplevel-compilations)
1600 (concat ";" *newline*))
1602 (concat code ";" *newline*)
1606 ;;; Once we have the compiler, we define the runtime environment and
1607 ;;; interactive development (eval), which works calling the compiler
1608 ;;; and evaluating the Javascript result globally.
1612 (defmacro with-compilation-unit (&body body)
1615 (setq *compilation-unit-checks* nil)
1617 (dolist (check *compilation-unit-checks*)
1622 (with-compilation-unit
1623 (ls-compile-toplevel x))))
1626 (js-eval "var lisp")
1627 (js-vset "lisp" (new))
1628 (js-vset "lisp.read" #'ls-read-from-string)
1629 (js-vset "lisp.print" #'prin1-to-string)
1630 (js-vset "lisp.eval" #'eval)
1631 (js-vset "lisp.compile" #'ls-compile-toplevel)
1632 (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
1633 (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str))))
1635 ;; Set the initial global environment to be equal to the host global
1636 ;; environment at this point of the compilation.
1638 (toplevel-compilation
1641 ,@(mapcar (lambda (s)
1642 `(oset *package* ,(symbol-name (car s))
1643 (js-vref ,(cdr s))))
1645 (setq *literal-symbols* ',*literal-symbols*)
1646 (setq *environment* ',*environment*)
1647 (setq *variable-counter* ,*variable-counter*)
1648 (setq *gensym-counter* ,*gensym-counter*)
1649 (setq *block-counter* ,*block-counter*)))))
1652 (toplevel-compilation
1654 `(setq *literal-counter* ,*literal-counter*)))))
1657 ;;; Finally, we provide a couple of functions to easily bootstrap
1658 ;;; this. It just calls the compiler with this file as input.
1662 (defun read-whole-file (filename)
1663 (with-open-file (in filename)
1664 (let ((seq (make-array (file-length in) :element-type 'character)))
1665 (read-sequence seq in)
1668 (defun ls-compile-file (filename output)
1669 (setq *compilation-unit-checks* nil)
1670 (with-open-file (out output :direction :output :if-exists :supersede)
1671 (let* ((source (read-whole-file filename))
1672 (in (make-string-stream source)))
1674 for x = (ls-read in)
1676 for compilation = (ls-compile-toplevel x)
1677 when (plusp (length compilation))
1678 do (write-string compilation out))
1679 (dolist (check *compilation-unit-checks*)
1681 (setq *compilation-unit-checks* nil))))
1684 (setq *environment* (make-lexenv))
1685 (setq *literal-symbols* nil)
1686 (setq *variable-counter* 0
1690 (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))