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) (setq ,name ,value))
56 ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
59 (defmacro defparameter (name value &optional docstring)
62 ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
65 (defmacro named-lambda (name args &rest body)
66 (let ((x (gensym "FN")))
67 `(let ((,x (lambda ,args ,@body)))
68 (oset ,x "fname" ,name)
71 (defmacro defun (name args &rest body)
73 (declaim (non-overridable ,name))
75 (named-lambda ,(symbol-name name) ,args
76 ,@(if (and (stringp (car body)) (not (null (cdr body))))
77 `(,(car body) (block ,name ,@(cdr body)))
78 `((block ,name ,@body)))))
81 (defvar *package* (new))
86 (defmacro return (&optional value)
87 `(return-from nil ,value))
89 (defmacro while (condition &body body)
90 `(block nil (%while ,condition ,@body)))
98 (oset *package* name (make-symbol name))))
100 (defun find-symbol (name)
101 (oget *package* name))
103 (defvar *gensym-counter* 0)
104 (defun gensym (&optional (prefix "G"))
105 (setq *gensym-counter* (+ *gensym-counter* 1))
106 (make-symbol (concat-two prefix (integer-to-string *gensym-counter*))))
112 (defun = (x y) (= x y))
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 1+ (x) (+ x 1))
118 (defun 1- (x) (- x 1))
119 (defun zerop (x) (= x 0))
120 (defun truncate (x y) (floor (/ x y)))
122 (defun eql (x y) (eq x y))
124 (defun not (x) (if x nil t))
126 (defun cons (x y ) (cons x y))
127 (defun consp (x) (consp x))
130 "Return the CAR part of a cons, or NIL if X is null."
133 (defun cdr (x) (cdr x))
134 (defun caar (x) (car (car x)))
135 (defun cadr (x) (car (cdr x)))
136 (defun cdar (x) (cdr (car x)))
137 (defun cddr (x) (cdr (cdr x)))
138 (defun caddr (x) (car (cdr (cdr x))))
139 (defun cdddr (x) (cdr (cdr (cdr x))))
140 (defun cadddr (x) (car (cdr (cdr (cdr x)))))
141 (defun first (x) (car x))
142 (defun second (x) (cadr x))
143 (defun third (x) (caddr x))
144 (defun fourth (x) (cadddr x))
146 (defun list (&rest args) args)
152 (defmacro incf (x &optional (delta 1))
153 `(setq ,x (+ ,x ,delta)))
155 (defmacro decf (x &optional (delta 1))
156 `(setq ,x (- ,x ,delta)))
158 (defmacro push (x place)
159 `(setq ,place (cons ,x ,place)))
161 (defmacro dolist (iter &body body)
162 (let ((var (first iter))
165 (let ((,g!list ,(second iter))
168 (setq ,var (car ,g!list))
170 (setq ,g!list (cdr ,g!list)))
173 (defmacro dotimes (iter &body body)
174 (let ((g!to (gensym))
177 (result (third iter)))
181 (%while (< ,var ,g!to)
186 (defmacro cond (&rest clausules)
189 (if (eq (caar clausules) t)
190 `(progn ,@(cdar clausules))
191 `(if ,(caar clausules)
192 (progn ,@(cdar clausules))
193 (cond ,@(cdr clausules))))))
195 (defmacro case (form &rest clausules)
196 (let ((!form (gensym)))
197 `(let ((,!form ,form))
199 ,@(mapcar (lambda (clausule)
200 (if (eq (car clausule) t)
202 `((eql ,!form ',(car clausule))
206 (defmacro ecase (form &rest clausules)
211 (error "ECASE expression failed."))))))
213 (defmacro and (&rest forms)
224 (defmacro or (&rest forms)
232 `(let ((,g ,(car forms)))
233 (if ,g ,g (or ,@(cdr forms))))))))
235 (defmacro prog1 (form &body body)
236 (let ((value (gensym)))
237 `(let ((,value ,form))
241 (defmacro prog2 (form1 result &body body)
242 `(prog1 (progn ,form1 ,result) ,@body)))
245 ;;; This couple of helper functions will be defined in both Common
246 ;;; Lisp and in Ecmalisp.
247 (defun ensure-list (x)
252 (defun !reduce (func list initial)
257 (funcall func initial (car list)))))
259 ;;; Go on growing the Lisp language in Ecmalisp, with more high
260 ;;; level utilities as well as correct versions of other
264 (defun append-two (list1 list2)
268 (append (cdr list1) list2))))
270 (defun append (&rest lists)
271 (!reduce #'append-two lists '()))
273 (defun revappend (list1 list2)
275 (push (car list1) list2)
276 (setq list1 (cdr list1)))
279 (defun reverse (list)
280 (revappend list '()))
282 (defun list-length (list)
284 (while (not (null list))
286 (setq list (cdr list)))
294 (defun concat-two (s1 s2)
297 (defun mapcar (func list)
300 (cons (funcall func (car list))
301 (mapcar func (cdr list)))))
303 (defun identity (x) x)
306 (mapcar #'identity x))
308 (defun code-char (x) x)
309 (defun char-code (x) x)
310 (defun char= (x y) (= x y))
313 (and (numberp x) (= (floor x) x)))
315 (defun plusp (x) (< 0 x))
316 (defun minusp (x) (< x 0))
319 (or (consp x) (null x)))
321 (defun nthcdr (n list)
322 (while (and (plusp n) list)
324 (setq list (cdr list)))
328 (car (nthcdr n list)))
331 (while (consp (cdr x))
337 (cons (car x) (butlast (cdr x)))))
339 (defun member (x list)
341 (when (eql x (car list))
343 (setq list (cdr list))))
345 (defun remove (x list)
350 (remove x (cdr list)))
352 (cons (car list) (remove x (cdr list))))))
354 (defun remove-if (func list)
358 ((funcall func (car list))
359 (remove-if func (cdr list)))
361 (cons (car list) (remove-if func (cdr list))))))
363 (defun remove-if-not (func list)
367 ((funcall func (car list))
368 (cons (car list) (remove-if-not func (cdr list))))
370 (remove-if-not func (cdr list)))))
372 (defun digit-char-p (x)
373 (if (and (<= #\0 x) (<= x #\9))
377 (defun subseq (seq a &optional b)
384 (error "Unsupported argument."))))
386 (defun parse-integer (string)
389 (size (length string)))
390 (while (< index size)
391 (setq value (+ (* value 10) (digit-char-p (char string index))))
395 (defun some (function seq)
400 (while (< index size)
401 (when (funcall function (char seq index))
402 (return-from some t))
407 (when (funcall function x)
410 (error "Unknown sequence."))))
412 (defun every (function seq)
417 (while (< index size)
418 (unless (funcall function (char seq index))
419 (return-from every nil))
424 (unless (funcall function x)
427 (error "Unknown sequence."))))
429 (defun assoc (x alist)
431 (if (eql x (caar alist))
433 (setq alist (cdr alist))))
436 (defun string= (s1 s2)
439 (defun fdefinition (x)
446 (error "Invalid function"))))
448 (defun disassemble (function)
449 (write-line (lambda-code (fdefinition function)))
452 (defun documentation (x type)
453 "Return the documentation of X. TYPE must be the symbol VARIABLE or FUNCTION."
456 (let ((func (fdefinition x)))
457 (oget func "docstring")))
460 (error "Wrong argument type! it should be a symbol"))
464 ;;; The compiler offers some primitives and special forms which are
465 ;;; not found in Common Lisp, for instance, while. So, we grow Common
466 ;;; Lisp a bit to it can execute the rest of the file.
469 (defmacro while (condition &body body)
474 (defmacro eval-when-compile (&body body)
475 `(eval-when (:compile-toplevel :load-toplevel :execute)
478 (defun concat-two (s1 s2)
479 (concatenate 'string s1 s2))
481 (defun setcar (cons new)
482 (setf (car cons) new))
483 (defun setcdr (cons new)
484 (setf (cdr cons) new)))
486 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
487 ;;; from here, this code will compile on both. We define some helper
488 ;;; functions now for string manipulation and so on. They will be
489 ;;; useful in the compiler, mostly.
491 (defvar *newline* (string (code-char 10)))
493 (defun concat (&rest strs)
494 (!reduce #'concat-two strs ""))
496 (defmacro concatf (variable &body form)
497 `(setq ,variable (concat ,variable (progn ,@form))))
499 ;;; Concatenate a list of strings, with a separator
500 (defun join (list &optional (separator ""))
509 (join (cdr list) separator)))))
511 (defun join-trailing (list &optional (separator ""))
514 (concat (car list) separator (join-trailing (cdr list) separator))))
516 (defun mapconcat (func list)
517 (join (mapcar func list)))
519 ;;; Like CONCAT, but prefix each line with four spaces. Two versions
520 ;;; of this function are available, because the Ecmalisp version is
521 ;;; very slow and bootstraping was annoying.
524 (defun indent (&rest string)
525 (let ((input (join string)))
528 (size (length input)))
529 (when (plusp (length input)) (concatf output " "))
530 (while (< index size)
532 (if (and (char= (char input index) #\newline)
534 (not (char= (char input (1+ index)) #\newline)))
535 (concat (string #\newline) " ")
536 (string (char input index)))))
537 (concatf output str))
542 (defun indent (&rest string)
543 (with-output-to-string (*standard-output*)
544 (with-input-from-string (input (join string))
546 for line = (read-line input nil)
548 do (write-string " ")
549 do (write-line line)))))
552 (defun integer-to-string (x)
557 (concat "-" (integer-to-string (- 0 x))))
560 (while (not (zerop x))
561 (push (mod x 10) digits)
562 (setq x (truncate x 10)))
563 (join (mapcar (lambda (d) (string (char "0123456789" d)))
567 ;;; Wrap X with a Javascript code to convert the result from
568 ;;; Javascript generalized booleans to T or NIL.
570 (concat "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
572 ;;; Concatenate the arguments and wrap them with a self-calling
573 ;;; Javascript anonymous function. It is used to make some Javascript
574 ;;; statements valid expressions and provide a private scope as well.
575 ;;; It could be defined as function, but we could do some
576 ;;; preprocessing in the future.
577 (defmacro js!selfcall (&body body)
578 `(concat "(function(){" *newline* (indent ,@body) "})()"))
585 (defun prin1-to-string (form)
587 ((symbolp form) (symbol-name form))
588 ((integerp form) (integer-to-string form))
589 ((stringp form) (concat "\"" (escape-string form) "\""))
591 (let ((name (oget form "fname")))
593 (concat "#<FUNCTION " name ">")
594 (concat "#<FUNCTION>"))))
597 (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
598 (let ((last (last form)))
599 (if (null (cdr last))
600 (prin1-to-string (car last))
601 (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
604 (defun write-line (x)
606 (write-string *newline*)
610 (write-string "WARNING: ")
614 (write-line (prin1-to-string x))
620 ;;; The Lisp reader, parse strings and return Lisp objects. The main
621 ;;; entry points are `ls-read' and `ls-read-from-string'.
623 (defun make-string-stream (string)
626 (defun %peek-char (stream)
627 (and (< (cdr stream) (length (car stream)))
628 (char (car stream) (cdr stream))))
630 (defun %read-char (stream)
631 (and (< (cdr stream) (length (car stream)))
632 (prog1 (char (car stream) (cdr stream))
633 (setcdr stream (1+ (cdr stream))))))
635 (defun whitespacep (ch)
636 (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
638 (defun skip-whitespaces (stream)
640 (setq ch (%peek-char stream))
641 (while (and ch (whitespacep ch))
643 (setq ch (%peek-char stream)))))
645 (defun terminalp (ch)
646 (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
648 (defun read-until (stream func)
651 (setq ch (%peek-char stream))
652 (while (and ch (not (funcall func ch)))
653 (setq string (concat string (string ch)))
655 (setq ch (%peek-char stream)))
658 (defun skip-whitespaces-and-comments (stream)
660 (skip-whitespaces stream)
661 (setq ch (%peek-char stream))
662 (while (and ch (char= ch #\;))
663 (read-until stream (lambda (x) (char= x #\newline)))
664 (skip-whitespaces stream)
665 (setq ch (%peek-char stream)))))
667 (defun %read-list (stream)
668 (skip-whitespaces-and-comments stream)
669 (let ((ch (%peek-char stream)))
672 (error "Unspected EOF"))
678 (prog1 (ls-read stream)
679 (skip-whitespaces-and-comments stream)
680 (unless (char= (%read-char stream) #\))
681 (error "')' was expected."))))
683 (cons (ls-read stream) (%read-list stream))))))
685 (defun read-string (stream)
688 (setq ch (%read-char stream))
689 (while (not (eql ch #\"))
691 (error "Unexpected EOF"))
693 (setq ch (%read-char stream)))
694 (setq string (concat string (string ch)))
695 (setq ch (%read-char stream)))
698 (defun read-sharp (stream)
700 (ecase (%read-char stream)
702 (list 'function (ls-read stream)))
705 (concat (string (%read-char stream))
706 (read-until stream #'terminalp))))
708 ((string= cname "space") (char-code #\space))
709 ((string= cname "tab") (char-code #\tab))
710 ((string= cname "newline") (char-code #\newline))
711 (t (char-code (char cname 0))))))
713 (let ((feature (read-until stream #'terminalp)))
715 ((string= feature "common-lisp")
716 (ls-read stream) ;ignore
718 ((string= feature "ecmalisp")
721 (error "Unknown reader form.")))))))
723 (defvar *eof* (make-symbol "EOF"))
724 (defun ls-read (stream)
725 (skip-whitespaces-and-comments stream)
726 (let ((ch (%peek-char stream)))
735 (list 'quote (ls-read stream)))
738 (list 'backquote (ls-read stream)))
741 (read-string stream))
744 (if (eql (%peek-char stream) #\@)
745 (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
746 (list 'unquote (ls-read stream))))
750 (let ((string (read-until stream #'terminalp)))
751 (if (every #'digit-char-p string)
752 (parse-integer string)
753 (intern (string-upcase string))))))))
755 (defun ls-read-from-string (string)
756 (ls-read (make-string-stream string)))
761 ;;; Translate the Lisp code to Javascript. It will compile the special
762 ;;; forms. Some primitive functions are compiled as special forms
763 ;;; too. The respective real functions are defined in the target (see
764 ;;; the beginning of this file) as well as some primitive functions.
766 (defvar *compilation-unit-checks* '())
768 (defun make-binding (name type value &optional declarations)
769 (list name type value declarations))
771 (defun binding-name (b) (first b))
772 (defun binding-type (b) (second b))
773 (defun binding-value (b) (third b))
774 (defun binding-declarations (b) (fourth b))
776 (defun set-binding-value (b value)
777 (setcar (cddr b) value))
779 (defun set-binding-declarations (b value)
780 (setcar (cdddr b) value))
782 (defun push-binding-declaration (decl b)
783 (set-binding-declarations b (cons decl (binding-declarations b))))
786 (defun make-lexenv ()
787 (list nil nil nil nil))
789 (defun copy-lexenv (lexenv)
792 (defun push-to-lexenv (binding lexenv namespace)
794 (variable (setcar lexenv (cons binding (car lexenv))))
795 (function (setcar (cdr lexenv) (cons binding (cadr lexenv))))
796 (block (setcar (cddr lexenv) (cons binding (caddr lexenv))))
797 (gotag (setcar (cdddr lexenv) (cons binding (cadddr lexenv))))))
799 (defun extend-lexenv (bindings lexenv namespace)
800 (let ((env (copy-lexenv lexenv)))
801 (dolist (binding (reverse bindings) env)
802 (push-to-lexenv binding env namespace))))
804 (defun lookup-in-lexenv (name lexenv namespace)
805 (assoc name (ecase namespace
806 (variable (first lexenv))
807 (function (second lexenv))
808 (block (third lexenv))
809 (gotag (fourth lexenv)))))
811 (defvar *environment* (make-lexenv))
813 (defvar *variable-counter* 0)
814 (defun gvarname (symbol)
815 (concat "v" (integer-to-string (incf *variable-counter*))))
817 (defun translate-variable (symbol)
818 (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
820 (defun extend-local-env (args)
821 (let ((new (copy-lexenv *environment*)))
822 (dolist (symbol args new)
823 (let ((b (make-binding symbol 'lexical-variable (gvarname symbol))))
824 (push-to-lexenv b new 'variable)))))
826 ;;; Toplevel compilations
827 (defvar *toplevel-compilations* nil)
829 (defun toplevel-compilation (string)
830 (push string *toplevel-compilations*))
832 (defun null-or-empty-p (x)
835 (defun get-toplevel-compilations ()
836 (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
838 (defun %compile-defmacro (name lambda)
839 (toplevel-compilation (ls-compile `',name))
840 (push-to-lexenv (make-binding name 'macro lambda) *environment* 'function))
842 (defun global-binding (name type namespace)
843 (or (lookup-in-lexenv name *environment* namespace)
844 (let ((b (make-binding name type nil)))
845 (push-to-lexenv b *environment* namespace)
848 (defun claimp (symbol namespace claim)
849 (let ((b (lookup-in-lexenv symbol *environment* namespace)))
850 (and b (member claim (binding-declarations b)))))
852 (defun !proclaim (decl)
855 (dolist (name (cdr decl))
856 (let ((b (global-binding name 'function 'function)))
857 (push-binding-declaration 'notinline b))))
859 (dolist (name (cdr decl))
860 (let ((b (global-binding name 'variable 'variable)))
861 (push-binding-declaration 'constant b))))
863 (dolist (name (cdr decl))
864 (let ((b (global-binding name 'function 'function)))
865 (push-binding-declaration 'non-overridable b))))))
870 (defvar *compilations* nil)
872 (defmacro define-compilation (name args &body body)
873 ;; Creates a new primitive `name' with parameters args and
874 ;; @body. The body can access to the local environment through the
875 ;; variable *ENVIRONMENT*.
876 `(push (list ',name (lambda ,args (block ,name ,@body)))
879 (define-compilation if (condition true false)
880 (concat "(" (ls-compile condition) " !== " (ls-compile nil)
881 " ? " (ls-compile true)
882 " : " (ls-compile false)
885 (defvar *lambda-list-keywords* '(&optional &rest))
887 (defun list-until-keyword (list)
888 (if (or (null list) (member (car list) *lambda-list-keywords*))
890 (cons (car list) (list-until-keyword (cdr list)))))
892 (defun lambda-list-required-arguments (lambda-list)
893 (list-until-keyword lambda-list))
895 (defun lambda-list-optional-arguments-with-default (lambda-list)
896 (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
898 (defun lambda-list-optional-arguments (lambda-list)
899 (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
901 (defun lambda-list-rest-argument (lambda-list)
902 (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
904 (error "Bad lambda-list"))
908 (defun lambda-docstring-wrapper (docstring &rest strs)
911 "var func = " (join strs) ";" *newline*
912 "func.docstring = '" docstring "';" *newline*
913 "return func;" *newline*)
916 (define-compilation lambda (lambda-list &rest body)
917 (let ((required-arguments (lambda-list-required-arguments lambda-list))
918 (optional-arguments (lambda-list-optional-arguments lambda-list))
919 (rest-argument (lambda-list-rest-argument lambda-list))
921 ;; Get the documentation string for the lambda function
922 (when (and (stringp (car body))
923 (not (null (cdr body))))
924 (setq documentation (car body))
925 (setq body (cdr body)))
926 (let ((n-required-arguments (length required-arguments))
927 (n-optional-arguments (length optional-arguments))
928 (*environment* (extend-local-env
929 (append (ensure-list rest-argument)
931 optional-arguments))))
932 (lambda-docstring-wrapper
935 (join (mapcar #'translate-variable
936 (append required-arguments optional-arguments))
939 ;; Check number of arguments
941 (if required-arguments
942 (concat "if (arguments.length < " (integer-to-string n-required-arguments)
943 ") throw 'too few arguments';" *newline*)
945 (if (not rest-argument)
946 (concat "if (arguments.length > "
947 (integer-to-string (+ n-required-arguments n-optional-arguments))
948 ") throw 'too many arguments';" *newline*)
950 ;; Optional arguments
951 (if optional-arguments
952 (concat "switch(arguments.length){" *newline*
953 (let ((optional-and-defaults
954 (lambda-list-optional-arguments-with-default lambda-list))
958 (while (< idx n-optional-arguments)
959 (let ((arg (nth idx optional-and-defaults)))
960 (push (concat "case "
961 (integer-to-string (+ idx n-required-arguments)) ":" *newline*
962 (translate-variable (car arg))
964 (ls-compile (cadr arg))
968 (push (concat "default: break;" *newline*) cases)
969 (join (reverse cases))))
972 ;; &rest/&body argument
974 (let ((js!rest (translate-variable rest-argument)))
975 (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
976 "for (var i = arguments.length-1; i>="
977 (integer-to-string (+ n-required-arguments n-optional-arguments))
979 (indent js!rest " = "
980 "{car: arguments[i], cdr: ") js!rest "};"
984 (ls-compile-block body t)) *newline*
987 (define-compilation setq (var val)
988 (let ((b (lookup-in-lexenv var *environment* 'variable)))
989 (if (eq (binding-type b) 'lexical-variable)
990 (concat (binding-value b) " = " (ls-compile val))
991 (ls-compile `(set ',var ,val)))))
993 ;;; FFI Variable accessors
994 (define-compilation js-vref (var)
997 (define-compilation js-vset (var val)
998 (concat "(" var " = " (ls-compile val) ")"))
1002 (defun escape-string (string)
1005 (size (length string)))
1006 (while (< index size)
1007 (let ((ch (char string index)))
1008 (when (or (char= ch #\") (char= ch #\\))
1009 (setq output (concat output "\\")))
1010 (when (or (char= ch #\newline))
1011 (setq output (concat output "\\"))
1013 (setq output (concat output (string ch))))
1018 (defvar *literal-symbols* nil)
1019 (defvar *literal-counter* 0)
1022 (concat "l" (integer-to-string (incf *literal-counter*))))
1024 (defun literal (sexp &optional recursive)
1026 ((integerp sexp) (integer-to-string sexp))
1027 ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1029 (or (cdr (assoc sexp *literal-symbols*))
1031 (s #+common-lisp (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1032 #+ecmalisp (ls-compile `(intern ,(symbol-name sexp)))))
1033 (push (cons sexp v) *literal-symbols*)
1034 (toplevel-compilation (concat "var " v " = " s))
1037 (let ((c (concat "{car: " (literal (car sexp) t) ", "
1038 "cdr: " (literal (cdr sexp) t) "}")))
1042 (toplevel-compilation (concat "var " v " = " c))
1045 (define-compilation quote (sexp)
1048 (define-compilation %while (pred &rest body)
1050 "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1051 (indent (ls-compile-block body))
1053 "return " (ls-compile nil) ";" *newline*))
1055 (define-compilation function (x)
1057 ((and (listp x) (eq (car x) 'lambda))
1060 (ls-compile `(symbol-function ',x)))))
1062 (define-compilation eval-when-compile (&rest body)
1063 (eval (cons 'progn body))
1066 (defmacro define-transformation (name args form)
1067 `(define-compilation ,name ,args
1068 (ls-compile ,form)))
1070 (define-compilation progn (&rest body)
1071 (js!selfcall (ls-compile-block body t)))
1073 (defun dynamic-binding-wrapper (bindings body)
1079 "var tmp;" *newline*
1082 (let ((s (ls-compile `(quote ,(car b)))))
1083 (concat "tmp = " s ".value;" *newline*
1084 s ".value = " (cdr b) ";" *newline*
1085 (cdr b) " = tmp;" *newline*)))
1089 "finally {" *newline*
1093 (let ((s (ls-compile `(quote ,(car b)))))
1094 (concat s ".value" " = " (cdr b))))
1096 (concat ";" *newline*)))
1100 (define-compilation let (bindings &rest body)
1101 (let ((bindings (mapcar #'ensure-list bindings)))
1102 (let ((variables (mapcar #'first bindings))
1103 (values (mapcar #'second bindings)))
1104 (let ((cvalues (mapcar #'ls-compile values))
1105 (*environment* (extend-local-env (remove-if #'boundp variables)))
1107 (concat "(function("
1108 (join (mapcar (lambda (x)
1110 (let ((v (gvarname x)))
1111 (push (cons x v) dynamic-bindings)
1113 (translate-variable x)))
1117 (let ((body (ls-compile-block body t)))
1118 (indent (dynamic-binding-wrapper dynamic-bindings body)))
1119 "})(" (join cvalues ",") ")")))))
1122 (defvar *block-counter* 0)
1124 (define-compilation block (name &rest body)
1125 (let ((tr (integer-to-string (incf *block-counter*))))
1126 (let ((b (make-binding name 'block tr)))
1129 (let ((*environment* (extend-lexenv (list b) *environment* 'block)))
1130 (indent "return " (ls-compile `(progn ,@body)) ";" *newline*))
1132 "catch (cf){" *newline*
1133 " if (cf.type == 'block' && cf.id == " tr ")" *newline*
1134 " return cf.value;" *newline*
1136 " throw cf;" *newline*
1139 (define-compilation return-from (name &optional value)
1140 (let ((b (lookup-in-lexenv name *environment* 'block)))
1145 "id: " (binding-value b) ", "
1146 "value: " (ls-compile value) ", "
1147 "message: 'Return from unknown block " (symbol-name name) ".'"
1149 (error (concat "Unknown block `" (symbol-name name) "'.")))))
1152 (define-compilation catch (id &rest body)
1154 "var id = " (ls-compile id) ";" *newline*
1156 (indent "return " (ls-compile `(progn ,@body))
1159 "catch (cf){" *newline*
1160 " if (cf.type == 'catch' && cf.id == id)" *newline*
1161 " return cf.value;" *newline*
1163 " throw cf;" *newline*
1166 (define-compilation throw (id &optional value)
1170 "id: " (ls-compile id) ", "
1171 "value: " (ls-compile value) ", "
1172 "message: 'Throw uncatched.'"
1176 (defvar *tagbody-counter* 0)
1177 (defvar *go-tag-counter* 0)
1180 (or (integerp x) (symbolp x)))
1182 (defun declare-tagbody-tags (tbidx body)
1184 (mapcar (lambda (label)
1185 (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1186 (make-binding label 'gotag (list tbidx tagidx))))
1187 (remove-if-not #'go-tag-p body))))
1188 (extend-lexenv bindings *environment* 'gotag)))
1190 (define-compilation tagbody (&rest body)
1191 ;; Ignore the tagbody if it does not contain any go-tag. We do this
1192 ;; because 1) it is easy and 2) many built-in forms expand to a
1193 ;; implicit tagbody, so we save some space.
1194 (unless (some #'go-tag-p body)
1195 (return-from tagbody (ls-compile `(progn ,@body nil))))
1196 ;; The translation assumes the first form in BODY is a label
1197 (unless (go-tag-p (car body))
1198 (push (gensym "START") body))
1199 ;; Tagbody compilation
1200 (let ((tbidx (integer-to-string *tagbody-counter*)))
1201 (let ((*environment* (declare-tagbody-tags tbidx body))
1203 (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1204 (setq initag (second (binding-value b))))
1206 "var tagbody_" tbidx " = " initag ";" *newline*
1208 "while (true) {" *newline*
1209 (indent "try {" *newline*
1210 (indent (let ((content ""))
1211 (concat "switch(tagbody_" tbidx "){" *newline*
1212 "case " initag ":" *newline*
1213 (dolist (form (cdr body) content)
1215 (if (not (go-tag-p form))
1216 (indent (ls-compile form) ";" *newline*)
1217 (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1218 (concat "case " (second (binding-value b)) ":" *newline*)))))
1219 "default:" *newline*
1220 " break tbloop;" *newline*
1223 "catch (jump) {" *newline*
1224 " if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1225 " tagbody_" tbidx " = jump.label;" *newline*
1227 " throw(jump);" *newline*
1230 "return " (ls-compile nil) ";" *newline*))))
1232 (define-compilation go (label)
1233 (let ((b (lookup-in-lexenv label *environment* 'gotag))
1235 ((symbolp label) (symbol-name label))
1236 ((integerp label) (integer-to-string label)))))
1241 "id: " (first (binding-value b)) ", "
1242 "label: " (second (binding-value b)) ", "
1243 "message: 'Attempt to GO to non-existing tag " n "'"
1245 (error (concat "Unknown tag `" n "'.")))))
1248 (define-compilation unwind-protect (form &rest clean-up)
1250 "var ret = " (ls-compile nil) ";" *newline*
1252 (indent "ret = " (ls-compile form) ";" *newline*)
1253 "} finally {" *newline*
1254 (indent (ls-compile-block clean-up))
1256 "return ret;" *newline*))
1259 ;;; A little backquote implementation without optimizations of any
1260 ;;; kind for ecmalisp.
1261 (defun backquote-expand-1 (form)
1267 ((eq (car form) 'unquote)
1269 ((eq (car form) 'backquote)
1270 (backquote-expand-1 (backquote-expand-1 (cadr form))))
1275 ((and (listp s) (eq (car s) 'unquote))
1276 (list 'list (cadr s)))
1277 ((and (listp s) (eq (car s) 'unquote-splicing))
1280 (list 'list (backquote-expand-1 s)))))
1283 (defun backquote-expand (form)
1284 (if (and (listp form) (eq (car form) 'backquote))
1285 (backquote-expand-1 (cadr form))
1288 (defmacro backquote (form)
1289 (backquote-expand-1 form))
1291 (define-transformation backquote (form)
1292 (backquote-expand-1 form))
1296 (defvar *builtins* nil)
1298 (defmacro define-raw-builtin (name args &body body)
1299 ;; Creates a new primitive function `name' with parameters args and
1300 ;; @body. The body can access to the local environment through the
1301 ;; variable *ENVIRONMENT*.
1302 `(push (list ',name (lambda ,args (block ,name ,@body)))
1305 (defmacro define-builtin (name args &body body)
1307 (define-raw-builtin ,name ,args
1308 (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1311 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1312 (defmacro type-check (decls &body body)
1314 ,@(mapcar (lambda (decl)
1315 `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1317 ,@(mapcar (lambda (decl)
1318 `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1319 (indent "throw 'The value ' + "
1321 " + ' is not a type "
1326 (concat "return " (progn ,@body) ";" *newline*)))
1328 (defun num-op-num (x op y)
1329 (type-check (("x" "number" x) ("y" "number" y))
1330 (concat "x" op "y")))
1332 (define-builtin + (x y) (num-op-num x "+" 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))
1337 (define-builtin mod (x y) (num-op-num x "%" y))
1339 (define-builtin < (x y) (js!bool (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)))
1345 (define-builtin numberp (x)
1346 (js!bool (concat "(typeof (" x ") == \"number\")")))
1348 (define-builtin floor (x)
1349 (type-check (("x" "number" x))
1352 (define-builtin cons (x y)
1353 (concat "({car: " x ", cdr: " y "})"))
1355 (define-builtin consp (x)
1358 "var tmp = " x ";" *newline*
1359 "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1361 (define-builtin car (x)
1363 "var tmp = " x ";" *newline*
1364 "return tmp === " (ls-compile nil)
1365 "? " (ls-compile nil)
1366 ": tmp.car;" *newline*))
1368 (define-builtin cdr (x)
1370 "var tmp = " x ";" *newline*
1371 "return tmp === " (ls-compile nil) "? "
1373 ": tmp.cdr;" *newline*))
1375 (define-builtin setcar (x new)
1376 (type-check (("x" "object" x))
1377 (concat "(x.car = " new ")")))
1379 (define-builtin setcdr (x new)
1380 (type-check (("x" "object" x))
1381 (concat "(x.cdr = " new ")")))
1383 (define-builtin symbolp (x)
1386 "var tmp = " x ";" *newline*
1387 "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1389 (define-builtin make-symbol (name)
1390 (type-check (("name" "string" name))
1393 (define-builtin symbol-name (x)
1394 (concat "(" x ").name"))
1396 (define-builtin set (symbol value)
1397 (concat "(" symbol ").value = " value))
1399 (define-builtin fset (symbol value)
1400 (concat "(" symbol ").function = " value))
1402 (define-builtin boundp (x)
1403 (js!bool (concat "(" x ".value !== undefined)")))
1405 (define-builtin symbol-value (x)
1407 "var symbol = " x ";" *newline*
1408 "var value = symbol.value;" *newline*
1409 "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1410 "return value;" *newline*))
1412 (define-builtin symbol-function (x)
1414 "var symbol = " x ";" *newline*
1415 "var func = symbol.function;" *newline*
1416 "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1417 "return func;" *newline*))
1419 (define-builtin symbol-plist (x)
1420 (concat "((" x ").plist || " (ls-compile nil) ")"))
1422 (define-builtin lambda-code (x)
1423 (concat "(" x ").toString()"))
1426 (define-builtin eq (x y) (js!bool (concat "(" x " === " y ")")))
1427 (define-builtin equal (x y) (js!bool (concat "(" x " == " y ")")))
1429 (define-builtin string (x)
1430 (type-check (("x" "number" x))
1431 "String.fromCharCode(x)"))
1433 (define-builtin stringp (x)
1434 (js!bool (concat "(typeof(" x ") == \"string\")")))
1436 (define-builtin string-upcase (x)
1437 (type-check (("x" "string" x))
1440 (define-builtin string-length (x)
1441 (type-check (("x" "string" x))
1444 (define-raw-builtin slice (string a &optional b)
1446 "var str = " (ls-compile string) ";" *newline*
1447 "var a = " (ls-compile a) ";" *newline*
1450 (concat "b = " (ls-compile b) ";" *newline*)
1452 "return str.slice(a,b);" *newline*))
1454 (define-builtin char (string index)
1455 (type-check (("string" "string" string)
1456 ("index" "number" index))
1457 "string.charCodeAt(index)"))
1459 (define-builtin concat-two (string1 string2)
1460 (type-check (("string1" "string" string1)
1461 ("string2" "string" string2))
1462 "string1.concat(string2)"))
1464 (define-raw-builtin funcall (func &rest args)
1465 (concat "(" (ls-compile func) ")("
1466 (join (mapcar #'ls-compile args)
1470 (define-raw-builtin apply (func &rest args)
1472 (concat "(" (ls-compile func) ")()")
1473 (let ((args (butlast args))
1474 (last (car (last args))))
1476 "var f = " (ls-compile func) ";" *newline*
1477 "var args = [" (join (mapcar #'ls-compile args)
1480 "var tail = (" (ls-compile last) ");" *newline*
1481 "while (tail != " (ls-compile nil) "){" *newline*
1482 " args.push(tail.car);" *newline*
1483 " tail = tail.cdr;" *newline*
1485 "return f.apply(this, args);" *newline*))))
1487 (define-builtin js-eval (string)
1488 (type-check (("string" "string" string))
1489 "eval.apply(window, [string])"))
1491 (define-builtin error (string)
1492 (js!selfcall "throw " string ";" *newline*))
1494 (define-builtin new () "{}")
1496 (define-builtin oget (object key)
1498 "var tmp = " "(" object ")[" key "];" *newline*
1499 "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1501 (define-builtin oset (object key value)
1502 (concat "((" object ")[" key "] = " value ")"))
1504 (define-builtin in (key object)
1505 (js!bool (concat "((" key ") in (" object "))")))
1507 (define-builtin functionp (x)
1508 (js!bool (concat "(typeof " x " == 'function')")))
1510 (define-builtin write-string (x)
1511 (type-check (("x" "string" x))
1516 (let ((b (lookup-in-lexenv x *environment* 'function)))
1517 (and (eq (binding-type b) 'macro)
1520 (defun ls-macroexpand-1 (form)
1521 (let ((macro-binding (macro (car form))))
1523 (let ((expander (binding-value macro-binding)))
1524 (when (listp expander)
1525 (let ((compiled (eval expander)))
1526 ;; The list representation are useful while
1527 ;; bootstrapping, as we can dump the definition of the
1528 ;; macros easily, but they are slow because we have to
1529 ;; evaluate them and compile them now and again. So, let
1530 ;; us replace the list representation version of the
1531 ;; function with the compiled one.
1533 #+ecmalisp (set-binding-value macro-binding compiled)
1534 (setq expander compiled)))
1535 (apply expander (cdr form)))
1538 (defun compile-funcall (function args)
1539 (if (and (symbolp function)
1540 (claimp function 'function 'non-overridable))
1541 (concat (ls-compile `',function) ".function("
1542 (join (mapcar #'ls-compile args)
1545 (concat (ls-compile `#',function) "("
1546 (join (mapcar #'ls-compile args)
1550 (defun ls-compile-block (sexps &optional return-last-p)
1552 (concat (ls-compile-block (butlast sexps))
1553 "return " (ls-compile (car (last sexps))) ";")
1555 (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
1556 (concat ";" *newline*))))
1558 (defun ls-compile (sexp)
1561 (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1563 ((eq (binding-type b) 'lexical-variable)
1565 ((claimp sexp 'variable 'constant)
1566 (concat (ls-compile `',sexp) ".value"))
1568 (ls-compile `(symbol-value ',sexp))))))
1569 ((integerp sexp) (integer-to-string sexp))
1570 ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1572 (let ((name (car sexp))
1576 ((assoc name *compilations*)
1577 (let ((comp (second (assoc name *compilations*))))
1579 ;; Built-in functions
1580 ((and (assoc name *builtins*)
1581 (not (claimp name 'function 'notinline)))
1582 (let ((comp (second (assoc name *builtins*))))
1586 (ls-compile (ls-macroexpand-1 sexp))
1587 (compile-funcall name args))))))))
1589 (defun ls-compile-toplevel (sexp)
1590 (let ((*toplevel-compilations* nil))
1592 ((and (consp sexp) (eq (car sexp) 'progn))
1593 (let ((subs (mapcar #'ls-compile-toplevel (cdr sexp))))
1594 (join (remove-if #'null-or-empty-p subs))))
1596 (let ((code (ls-compile sexp)))
1597 (concat (join-trailing (get-toplevel-compilations)
1598 (concat ";" *newline*))
1600 (concat code ";" *newline*)
1604 ;;; Once we have the compiler, we define the runtime environment and
1605 ;;; interactive development (eval), which works calling the compiler
1606 ;;; and evaluating the Javascript result globally.
1610 (defmacro with-compilation-unit (&body body)
1613 (setq *compilation-unit-checks* nil)
1615 (dolist (check *compilation-unit-checks*)
1620 (with-compilation-unit
1621 (ls-compile-toplevel x))))
1624 (js-eval "var lisp")
1625 (js-vset "lisp" (new))
1626 (js-vset "lisp.read" #'ls-read-from-string)
1627 (js-vset "lisp.print" #'prin1-to-string)
1628 (js-vset "lisp.eval" #'eval)
1629 (js-vset "lisp.compile" #'ls-compile-toplevel)
1630 (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
1631 (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str))))
1633 ;; Set the initial global environment to be equal to the host global
1634 ;; environment at this point of the compilation.
1636 (toplevel-compilation
1639 ,@(mapcar (lambda (s)
1640 `(oset *package* ,(symbol-name (car s))
1641 (js-vref ,(cdr s))))
1643 (setq *literal-symbols* ',*literal-symbols*)
1644 (setq *environment* ',*environment*)
1645 (setq *variable-counter* ,*variable-counter*)
1646 (setq *gensym-counter* ,*gensym-counter*)
1647 (setq *block-counter* ,*block-counter*)))))
1650 (toplevel-compilation
1652 `(setq *literal-counter* ,*literal-counter*)))))
1655 ;;; Finally, we provide a couple of functions to easily bootstrap
1656 ;;; this. It just calls the compiler with this file as input.
1660 (defun read-whole-file (filename)
1661 (with-open-file (in filename)
1662 (let ((seq (make-array (file-length in) :element-type 'character)))
1663 (read-sequence seq in)
1666 (defun ls-compile-file (filename output)
1667 (setq *compilation-unit-checks* nil)
1668 (with-open-file (out output :direction :output :if-exists :supersede)
1669 (let* ((source (read-whole-file filename))
1670 (in (make-string-stream source)))
1672 for x = (ls-read in)
1674 for compilation = (ls-compile-toplevel x)
1675 when (plusp (length compilation))
1676 do (write-string compilation out))
1677 (dolist (check *compilation-unit-checks*)
1679 (setq *compilation-unit-checks* nil))))
1682 (setq *environment* (make-lexenv))
1683 (setq *literal-symbols* nil)
1684 (setq *variable-counter* 0
1688 (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))