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 &optional docstring)
50 (unless (boundp ',name)
52 ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
55 (defmacro defparameter (name value &optional docstring)
58 ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
61 (defmacro lambda (args &rest body)
62 (if (stringp (car body))
63 `(let ((func (%lambda ,args ,@(cdr body))))
64 (oset func "docstring" ,(car body))
66 `(%lambda ,args ,@body)))
68 (defmacro named-lambda (name args &rest body)
69 (let ((x (gensym "FN")))
70 `(let ((,x (lambda ,args ,@body)))
71 (oset ,x "fname" ,name)
74 (defmacro defun (name args &rest body)
77 (named-lambda ,(symbol-name name) ,args
78 ,@(when (stringp (car body)) `(,(car body)))
80 ,@(if (stringp (car body))
85 (defvar *package* (new))
90 (defmacro return (&optional value)
91 `(return-from nil ,value))
93 (defmacro while (condition &body body)
94 `(block nil (%while ,condition ,@body)))
101 (oget *package* name)
102 (oset *package* name (make-symbol name))))
104 (defun find-symbol (name)
105 (oget *package* name))
107 (defvar *gensym-counter* 0)
108 (defun gensym (&optional (prefix "G"))
109 (setq *gensym-counter* (+ *gensym-counter* 1))
110 (make-symbol (concat-two prefix (integer-to-string *gensym-counter*))))
116 (defun = (x y) (= x y))
117 (defun + (x y) (+ x y))
118 (defun - (x y) (- x y))
119 (defun * (x y) (* x y))
120 (defun / (x y) (/ x y))
121 (defun 1+ (x) (+ x 1))
122 (defun 1- (x) (- x 1))
123 (defun zerop (x) (= x 0))
124 (defun truncate (x y) (floor (/ x y)))
126 (defun eql (x y) (eq x y))
128 (defun not (x) (if x nil t))
130 (defun cons (x y ) (cons x y))
131 (defun consp (x) (consp x))
134 "Return the CAR part of a cons, or NIL if X is null."
137 (defun cdr (x) (cdr x))
138 (defun caar (x) (car (car x)))
139 (defun cadr (x) (car (cdr x)))
140 (defun cdar (x) (cdr (car x)))
141 (defun cddr (x) (cdr (cdr x)))
142 (defun caddr (x) (car (cdr (cdr x))))
143 (defun cdddr (x) (cdr (cdr (cdr x))))
144 (defun cadddr (x) (car (cdr (cdr (cdr x)))))
145 (defun first (x) (car x))
146 (defun second (x) (cadr x))
147 (defun third (x) (caddr x))
148 (defun fourth (x) (cadddr x))
150 (defun list (&rest args) args)
156 (defmacro incf (x &optional (delta 1))
157 `(setq ,x (+ ,x ,delta)))
159 (defmacro decf (x &optional (delta 1))
160 `(setq ,x (- ,x ,delta)))
162 (defmacro push (x place)
163 `(setq ,place (cons ,x ,place)))
165 (defmacro dolist (iter &body body)
166 (let ((var (first iter))
169 (let ((,g!list ,(second iter))
172 (setq ,var (car ,g!list))
174 (setq ,g!list (cdr ,g!list)))
177 (defmacro dotimes (iter &body body)
178 (let ((g!to (gensym))
181 (result (third iter)))
185 (%while (< ,var ,g!to)
190 (defmacro cond (&rest clausules)
193 (if (eq (caar clausules) t)
194 `(progn ,@(cdar clausules))
195 `(if ,(caar clausules)
196 (progn ,@(cdar clausules))
197 (cond ,@(cdr clausules))))))
199 (defmacro case (form &rest clausules)
200 (let ((!form (gensym)))
201 `(let ((,!form ,form))
203 ,@(mapcar (lambda (clausule)
204 (if (eq (car clausule) t)
206 `((eql ,!form ',(car clausule))
210 (defmacro ecase (form &rest clausules)
215 (error "ECASE expression failed."))))))
217 (defmacro and (&rest forms)
228 (defmacro or (&rest forms)
236 `(let ((,g ,(car forms)))
237 (if ,g ,g (or ,@(cdr forms))))))))
239 (defmacro prog1 (form &body body)
240 (let ((value (gensym)))
241 `(let ((,value ,form))
245 (defmacro prog2 (form1 result &body body)
246 `(prog1 (progn ,form1 ,result) ,@body)))
250 ;;; This couple of helper functions will be defined in both Common
251 ;;; Lisp and in Ecmalisp.
252 (defun ensure-list (x)
257 (defun !reduce (func list initial)
262 (funcall func initial (car list)))))
264 ;;; Go on growing the Lisp language in Ecmalisp, with more high
265 ;;; level utilities as well as correct versions of other
269 (defun append-two (list1 list2)
273 (append (cdr list1) list2))))
275 (defun append (&rest lists)
276 (!reduce #'append-two lists '()))
278 (defun revappend (list1 list2)
280 (push (car list1) list2)
281 (setq list1 (cdr list1)))
284 (defun reverse (list)
285 (revappend list '()))
287 (defun list-length (list)
289 (while (not (null list))
291 (setq list (cdr list)))
299 (defun concat-two (s1 s2)
302 (defun mapcar (func list)
305 (cons (funcall func (car list))
306 (mapcar func (cdr list)))))
308 (defun identity (x) x)
311 (mapcar #'identity x))
313 (defun code-char (x) x)
314 (defun char-code (x) x)
315 (defun char= (x y) (= x y))
318 (and (numberp x) (= (floor x) x)))
320 (defun plusp (x) (< 0 x))
321 (defun minusp (x) (< x 0))
324 (or (consp x) (null x)))
326 (defun nthcdr (n list)
327 (while (and (plusp n) list)
329 (setq list (cdr list)))
333 (car (nthcdr n list)))
336 (while (consp (cdr x))
342 (cons (car x) (butlast (cdr x)))))
344 (defun member (x list)
346 (when (eql x (car list))
348 (setq list (cdr list))))
350 (defun remove (x list)
355 (remove x (cdr list)))
357 (cons (car list) (remove x (cdr list))))))
359 (defun remove-if (func list)
363 ((funcall func (car list))
364 (remove-if func (cdr list)))
366 (cons (car list) (remove-if func (cdr list))))))
368 (defun remove-if-not (func list)
372 ((funcall func (car list))
373 (cons (car list) (remove-if-not func (cdr list))))
375 (remove-if-not func (cdr list)))))
377 (defun digit-char-p (x)
378 (if (and (<= #\0 x) (<= x #\9))
382 (defun subseq (seq a &optional b)
389 (error "Unsupported argument."))))
391 (defun parse-integer (string)
394 (size (length string)))
395 (while (< index size)
396 (setq value (+ (* value 10) (digit-char-p (char string index))))
400 (defun some (function seq)
405 (while (< index size)
406 (when (funcall function (char seq index))
407 (return-from some t))
412 (when (funcall function x)
415 (error "Unknown sequence."))))
417 (defun every (function seq)
422 (while (< index size)
423 (unless (funcall function (char seq index))
424 (return-from every nil))
429 (unless (funcall function x)
432 (error "Unknown sequence."))))
434 (defun assoc (x alist)
436 (if (eql x (caar alist))
438 (setq alist (cdr alist))))
441 (defun string= (s1 s2)
444 (defun fdefinition (x)
451 (error "Invalid function"))))
453 (defun disassemble (function)
454 (write-line (lambda-code (fdefinition function)))
457 (defun documentation (x type)
458 "Return the documentation of X. TYPE must be the symbol VARIABLE or FUNCTION."
461 (let ((func (fdefinition x)))
462 (oget func "docstring")))
465 (error "Wrong argument type! it should be a symbol"))
469 ;;; The compiler offers some primitives and special forms which are
470 ;;; not found in Common Lisp, for instance, while. So, we grow Common
471 ;;; Lisp a bit to it can execute the rest of the file.
474 (defmacro while (condition &body body)
479 (defmacro eval-when-compile (&body body)
480 `(eval-when (:compile-toplevel :load-toplevel :execute)
483 (defun concat-two (s1 s2)
484 (concatenate 'string s1 s2))
486 (defun setcar (cons new)
487 (setf (car cons) new))
488 (defun setcdr (cons new)
489 (setf (cdr cons) new))
491 (defmacro %lambda (lambda-list &rest body)
492 `(lambda ,lambda-list ,@body)))
494 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
495 ;;; from here, this code will compile on both. We define some helper
496 ;;; functions now for string manipulation and so on. They will be
497 ;;; useful in the compiler, mostly.
499 (defvar *newline* (string (code-char 10)))
501 (defun concat (&rest strs)
502 (!reduce #'concat-two strs ""))
504 (defmacro concatf (variable &body form)
505 `(setq ,variable (concat ,variable (progn ,@form))))
507 ;;; Concatenate a list of strings, with a separator
508 (defun join (list &optional (separator ""))
517 (join (cdr list) separator)))))
519 (defun join-trailing (list &optional (separator ""))
522 (concat (car list) separator (join-trailing (cdr list) separator))))
524 (defun mapconcat (func list)
525 (join (mapcar func list)))
527 ;;; Like CONCAT, but prefix each line with four spaces. Two versions
528 ;;; of this function are available, because the Ecmalisp version is
529 ;;; very slow and bootstraping was annoying.
532 (defun indent (&rest string)
533 (let ((input (join string)))
536 (size (length input)))
537 (when (plusp (length input)) (concatf output " "))
538 (while (< index size)
540 (if (and (char= (char input index) #\newline)
542 (not (char= (char input (1+ index)) #\newline)))
543 (concat (string #\newline) " ")
544 (string (char input index)))))
545 (concatf output str))
550 (defun indent (&rest string)
551 (with-output-to-string (*standard-output*)
552 (with-input-from-string (input (join string))
554 for line = (read-line input nil)
556 do (write-string " ")
557 do (write-line line)))))
560 (defun integer-to-string (x)
565 (concat "-" (integer-to-string (- 0 x))))
568 (while (not (zerop x))
569 (push (mod x 10) digits)
570 (setq x (truncate x 10)))
571 (join (mapcar (lambda (d) (string (char "0123456789" d)))
575 ;;; Wrap X with a Javascript code to convert the result from
576 ;;; Javascript generalized booleans to T or NIL.
578 (concat "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
580 ;;; Concatenate the arguments and wrap them with a self-calling
581 ;;; Javascript anonymous function. It is used to make some Javascript
582 ;;; statements valid expressions and provide a private scope as well.
583 ;;; It could be defined as function, but we could do some
584 ;;; preprocessing in the future.
585 (defmacro js!selfcall (&body body)
586 `(concat "(function(){" *newline* (indent ,@body) "})()"))
593 (defun prin1-to-string (form)
595 ((symbolp form) (symbol-name form))
596 ((integerp form) (integer-to-string form))
597 ((stringp form) (concat "\"" (escape-string form) "\""))
599 (let ((name (oget form "fname")))
601 (concat "#<FUNCTION " name ">")
602 (concat "#<FUNCTION>"))))
605 (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
606 (let ((last (last form)))
607 (if (null (cdr last))
608 (prin1-to-string (car last))
609 (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
612 (defun write-line (x)
614 (write-string *newline*)
618 (write-string "WARNING: ")
622 (write-line (prin1-to-string x))
628 ;;; The Lisp reader, parse strings and return Lisp objects. The main
629 ;;; entry points are `ls-read' and `ls-read-from-string'.
631 (defun make-string-stream (string)
634 (defun %peek-char (stream)
635 (and (< (cdr stream) (length (car stream)))
636 (char (car stream) (cdr stream))))
638 (defun %read-char (stream)
639 (and (< (cdr stream) (length (car stream)))
640 (prog1 (char (car stream) (cdr stream))
641 (setcdr stream (1+ (cdr stream))))))
643 (defun whitespacep (ch)
644 (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
646 (defun skip-whitespaces (stream)
648 (setq ch (%peek-char stream))
649 (while (and ch (whitespacep ch))
651 (setq ch (%peek-char stream)))))
653 (defun terminalp (ch)
654 (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
656 (defun read-until (stream func)
659 (setq ch (%peek-char stream))
660 (while (and ch (not (funcall func ch)))
661 (setq string (concat string (string ch)))
663 (setq ch (%peek-char stream)))
666 (defun skip-whitespaces-and-comments (stream)
668 (skip-whitespaces stream)
669 (setq ch (%peek-char stream))
670 (while (and ch (char= ch #\;))
671 (read-until stream (lambda (x) (char= x #\newline)))
672 (skip-whitespaces stream)
673 (setq ch (%peek-char stream)))))
675 (defun %read-list (stream)
676 (skip-whitespaces-and-comments stream)
677 (let ((ch (%peek-char stream)))
680 (error "Unspected EOF"))
686 (prog1 (ls-read stream)
687 (skip-whitespaces-and-comments stream)
688 (unless (char= (%read-char stream) #\))
689 (error "')' was expected."))))
691 (cons (ls-read stream) (%read-list stream))))))
693 (defun read-string (stream)
696 (setq ch (%read-char stream))
697 (while (not (eql ch #\"))
699 (error "Unexpected EOF"))
701 (setq ch (%read-char stream)))
702 (setq string (concat string (string ch)))
703 (setq ch (%read-char stream)))
706 (defun read-sharp (stream)
708 (ecase (%read-char stream)
710 (list 'function (ls-read stream)))
713 (concat (string (%read-char stream))
714 (read-until stream #'terminalp))))
716 ((string= cname "space") (char-code #\space))
717 ((string= cname "tab") (char-code #\tab))
718 ((string= cname "newline") (char-code #\newline))
719 (t (char-code (char cname 0))))))
721 (let ((feature (read-until stream #'terminalp)))
723 ((string= feature "common-lisp")
724 (ls-read stream) ;ignore
726 ((string= feature "ecmalisp")
729 (error "Unknown reader form.")))))))
731 (defvar *eof* (make-symbol "EOF"))
732 (defun ls-read (stream)
733 (skip-whitespaces-and-comments stream)
734 (let ((ch (%peek-char stream)))
743 (list 'quote (ls-read stream)))
746 (list 'backquote (ls-read stream)))
749 (read-string stream))
752 (if (eql (%peek-char stream) #\@)
753 (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
754 (list 'unquote (ls-read stream))))
758 (let ((string (read-until stream #'terminalp)))
759 (if (every #'digit-char-p string)
760 (parse-integer string)
761 (intern (string-upcase string))))))))
763 (defun ls-read-from-string (string)
764 (ls-read (make-string-stream string)))
769 ;;; Translate the Lisp code to Javascript. It will compile the special
770 ;;; forms. Some primitive functions are compiled as special forms
771 ;;; too. The respective real functions are defined in the target (see
772 ;;; the beginning of this file) as well as some primitive functions.
774 (defvar *compilation-unit-checks* '())
776 (defun make-binding (name type translation declared)
777 (list name type translation declared))
779 (defun binding-name (b) (first b))
780 (defun binding-type (b) (second b))
781 (defun binding-value (b) (third b))
782 (defun binding-declared (b)
784 (defun mark-binding-as-declared (b)
785 (setcar (cdddr b) t))
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 *global-environment* (make-lexenv))
813 (defvar *environment* (make-lexenv))
815 (defun clear-undeclared-global-bindings ()
817 (mapcar (lambda (namespace)
818 (remove-if-not #'binding-declared namespace))
822 (defvar *variable-counter* 0)
823 (defun gvarname (symbol)
824 (concat "v" (integer-to-string (incf *variable-counter*))))
826 (defun translate-variable (symbol)
827 (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
829 (defun extend-local-env (args)
830 (let ((new (copy-lexenv *environment*)))
831 (dolist (symbol args new)
832 (let ((b (make-binding symbol 'lexical-variable (gvarname symbol) t)))
833 (push-to-lexenv b new 'variable)))))
835 ;;; Toplevel compilations
836 (defvar *toplevel-compilations* nil)
838 (defun toplevel-compilation (string)
839 (push string *toplevel-compilations*))
841 (defun null-or-empty-p (x)
844 (defun get-toplevel-compilations ()
845 (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
847 (defun %compile-defmacro (name lambda)
848 (toplevel-compilation (ls-compile `',name))
849 (push-to-lexenv (make-binding name 'macro lambda t) *environment* 'function))
851 (defvar *compilations* nil)
853 (defun ls-compile-block (sexps &optional return-last-p)
855 (concat (ls-compile-block (butlast sexps))
856 "return " (ls-compile (car (last sexps))) ";")
858 (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
859 (concat ";" *newline*))))
861 (defmacro define-compilation (name args &body body)
862 ;; Creates a new primitive `name' with parameters args and
863 ;; @body. The body can access to the local environment through the
864 ;; variable *ENVIRONMENT*.
865 `(push (list ',name (lambda ,args (block ,name ,@body)))
868 (define-compilation if (condition true false)
869 (concat "(" (ls-compile condition) " !== " (ls-compile nil)
870 " ? " (ls-compile true)
871 " : " (ls-compile false)
874 (defvar *lambda-list-keywords* '(&optional &rest))
876 (defun list-until-keyword (list)
877 (if (or (null list) (member (car list) *lambda-list-keywords*))
879 (cons (car list) (list-until-keyword (cdr list)))))
881 (defun lambda-list-required-arguments (lambda-list)
882 (list-until-keyword lambda-list))
884 (defun lambda-list-optional-arguments-with-default (lambda-list)
885 (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
887 (defun lambda-list-optional-arguments (lambda-list)
888 (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
890 (defun lambda-list-rest-argument (lambda-list)
891 (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
893 (error "Bad lambda-list"))
896 (define-compilation %lambda (lambda-list &rest body)
897 (let ((required-arguments (lambda-list-required-arguments lambda-list))
898 (optional-arguments (lambda-list-optional-arguments lambda-list))
899 (rest-argument (lambda-list-rest-argument lambda-list)))
900 (let ((n-required-arguments (length required-arguments))
901 (n-optional-arguments (length optional-arguments))
902 (*environment* (extend-local-env
903 (append (ensure-list rest-argument)
905 optional-arguments))))
906 (concat "(function ("
907 (join (mapcar #'translate-variable
908 (append required-arguments optional-arguments))
911 ;; Check number of arguments
913 (if required-arguments
914 (concat "if (arguments.length < " (integer-to-string n-required-arguments)
915 ") throw 'too few arguments';" *newline*)
917 (if (not rest-argument)
918 (concat "if (arguments.length > "
919 (integer-to-string (+ n-required-arguments n-optional-arguments))
920 ") throw 'too many arguments';" *newline*)
922 ;; Optional arguments
923 (if optional-arguments
924 (concat "switch(arguments.length){" *newline*
925 (let ((optional-and-defaults
926 (lambda-list-optional-arguments-with-default lambda-list))
930 (while (< idx n-optional-arguments)
931 (let ((arg (nth idx optional-and-defaults)))
932 (push (concat "case "
933 (integer-to-string (+ idx n-required-arguments)) ":" *newline*
934 (translate-variable (car arg))
936 (ls-compile (cadr arg))
940 (push (concat "default: break;" *newline*) cases)
941 (join (reverse cases))))
944 ;; &rest/&body argument
946 (let ((js!rest (translate-variable rest-argument)))
947 (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
948 "for (var i = arguments.length-1; i>="
949 (integer-to-string (+ n-required-arguments n-optional-arguments))
951 (indent js!rest " = "
952 "{car: arguments[i], cdr: ") js!rest "};"
956 (ls-compile-block body t)) *newline*
959 (define-compilation setq (var val)
960 (let ((b (lookup-in-lexenv var *environment* 'variable)))
961 (if (eq (binding-type b) 'lexical-variable)
962 (concat (binding-value b) " = " (ls-compile val))
963 (ls-compile `(set ',var ,val)))))
965 ;;; FFI Variable accessors
966 (define-compilation js-vref (var)
969 (define-compilation js-vset (var val)
970 (concat "(" var " = " (ls-compile val) ")"))
974 (defun escape-string (string)
977 (size (length string)))
978 (while (< index size)
979 (let ((ch (char string index)))
980 (when (or (char= ch #\") (char= ch #\\))
981 (setq output (concat output "\\")))
982 (when (or (char= ch #\newline))
983 (setq output (concat output "\\"))
985 (setq output (concat output (string ch))))
990 (defvar *literal-symbols* nil)
991 (defvar *literal-counter* 0)
994 (concat "l" (integer-to-string (incf *literal-counter*))))
996 (defun literal (sexp &optional recursive)
998 ((integerp sexp) (integer-to-string sexp))
999 ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1001 (or (cdr (assoc sexp *literal-symbols*))
1003 (s #+common-lisp (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1004 #+ecmalisp (ls-compile `(intern ,(symbol-name sexp)))))
1005 (push (cons sexp v) *literal-symbols*)
1006 (toplevel-compilation (concat "var " v " = " s))
1009 (let ((c (concat "{car: " (literal (car sexp) t) ", "
1010 "cdr: " (literal (cdr sexp) t) "}")))
1014 (toplevel-compilation (concat "var " v " = " c))
1017 (define-compilation quote (sexp)
1020 (define-compilation %while (pred &rest body)
1022 "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1023 (indent (ls-compile-block body))
1025 "return " (ls-compile nil) ";" *newline*))
1027 (define-compilation function (x)
1029 ((and (listp x) (eq (car x) 'lambda))
1032 (ls-compile `(symbol-function ',x)))))
1034 (define-compilation eval-when-compile (&rest body)
1035 (eval (cons 'progn body))
1038 (defmacro define-transformation (name args form)
1039 `(define-compilation ,name ,args
1040 (ls-compile ,form)))
1042 (define-compilation progn (&rest body)
1043 (js!selfcall (ls-compile-block body t)))
1045 (defun dynamic-binding-wrapper (bindings body)
1051 "var tmp;" *newline*
1054 (let ((s (ls-compile `(quote ,(car b)))))
1055 (concat "tmp = " s ".value;" *newline*
1056 s ".value = " (cdr b) ";" *newline*
1057 (cdr b) " = tmp;" *newline*)))
1061 "finally {" *newline*
1065 (let ((s (ls-compile `(quote ,(car b)))))
1066 (concat s ".value" " = " (cdr b))))
1068 (concat ";" *newline*)))
1072 (define-compilation let (bindings &rest body)
1073 (let ((bindings (mapcar #'ensure-list bindings)))
1074 (let ((variables (mapcar #'first bindings))
1075 (values (mapcar #'second bindings)))
1076 (let ((cvalues (mapcar #'ls-compile values))
1077 (*environment* (extend-local-env (remove-if #'boundp variables)))
1079 (concat "(function("
1080 (join (mapcar (lambda (x)
1082 (let ((v (gvarname x)))
1083 (push (cons x v) dynamic-bindings)
1085 (translate-variable x)))
1089 (let ((body (ls-compile-block body t)))
1090 (indent (dynamic-binding-wrapper dynamic-bindings body)))
1091 "})(" (join cvalues ",") ")")))))
1094 (defvar *block-counter* 0)
1096 (define-compilation block (name &rest body)
1097 (let ((tr (integer-to-string (incf *block-counter*))))
1098 (let ((b (make-binding name 'block tr t)))
1101 (let ((*environment* (extend-lexenv (list b) *environment* 'block)))
1102 (indent "return " (ls-compile `(progn ,@body)) ";" *newline*))
1104 "catch (cf){" *newline*
1105 " if (cf.type == 'block' && cf.id == " tr ")" *newline*
1106 " return cf.value;" *newline*
1108 " throw cf;" *newline*
1111 (define-compilation return-from (name &optional value)
1112 (let ((b (lookup-in-lexenv name *environment* 'block)))
1117 "id: " (binding-value b) ", "
1118 "value: " (ls-compile value) ", "
1119 "message: 'Return from unknown block " (symbol-name name) ".'"
1121 (error (concat "Unknown block `" (symbol-name name) "'.")))))
1124 (define-compilation catch (id &rest body)
1126 "var id = " (ls-compile id) ";" *newline*
1128 (indent "return " (ls-compile `(progn ,@body))
1131 "catch (cf){" *newline*
1132 " if (cf.type == 'catch' && cf.id == id)" *newline*
1133 " return cf.value;" *newline*
1135 " throw cf;" *newline*
1138 (define-compilation throw (id &optional value)
1142 "id: " (ls-compile id) ", "
1143 "value: " (ls-compile value) ", "
1144 "message: 'Throw uncatched.'"
1148 (defvar *tagbody-counter* 0)
1149 (defvar *go-tag-counter* 0)
1152 (or (integerp x) (symbolp x)))
1154 (defun declare-tagbody-tags (tbidx body)
1156 (mapcar (lambda (label)
1157 (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1158 (make-binding label 'gotag (list tbidx tagidx) t)))
1159 (remove-if-not #'go-tag-p body))))
1160 (extend-lexenv bindings *environment* 'gotag)))
1162 (define-compilation tagbody (&rest body)
1163 ;; Ignore the tagbody if it does not contain any go-tag. We do this
1164 ;; because 1) it is easy and 2) many built-in forms expand to a
1165 ;; implicit tagbody, so we save some space.
1166 (unless (some #'go-tag-p body)
1167 (return-from tagbody (ls-compile `(progn ,@body nil))))
1168 ;; The translation assumes the first form in BODY is a label
1169 (unless (go-tag-p (car body))
1170 (push (gensym "START") body))
1171 ;; Tagbody compilation
1172 (let ((tbidx (integer-to-string *tagbody-counter*)))
1173 (let ((*environment* (declare-tagbody-tags tbidx body))
1175 (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1176 (setq initag (second (binding-value b))))
1178 "var tagbody_" tbidx " = " initag ";" *newline*
1180 "while (true) {" *newline*
1181 (indent "try {" *newline*
1182 (indent (let ((content ""))
1183 (concat "switch(tagbody_" tbidx "){" *newline*
1184 "case " initag ":" *newline*
1185 (dolist (form (cdr body) content)
1187 (if (not (go-tag-p form))
1188 (indent (ls-compile form) ";" *newline*)
1189 (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1190 (concat "case " (second (binding-value b)) ":" *newline*)))))
1191 "default:" *newline*
1192 " break tbloop;" *newline*
1195 "catch (jump) {" *newline*
1196 " if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1197 " tagbody_" tbidx " = jump.label;" *newline*
1199 " throw(jump);" *newline*
1202 "return " (ls-compile nil) ";" *newline*))))
1204 (define-compilation go (label)
1205 (let ((b (lookup-in-lexenv label *environment* 'gotag))
1207 ((symbolp label) (symbol-name label))
1208 ((integerp label) (integer-to-string label)))))
1213 "id: " (first (binding-value b)) ", "
1214 "label: " (second (binding-value b)) ", "
1215 "message: 'Attempt to GO to non-existing tag " n "'"
1217 (error (concat "Unknown tag `" n "'.")))))
1220 (define-compilation unwind-protect (form &rest clean-up)
1222 "var ret = " (ls-compile nil) ";" *newline*
1224 (indent "ret = " (ls-compile form) ";" *newline*)
1225 "} finally {" *newline*
1226 (indent (ls-compile-block clean-up))
1228 "return ret;" *newline*))
1231 ;;; A little backquote implementation without optimizations of any
1232 ;;; kind for ecmalisp.
1233 (defun backquote-expand-1 (form)
1239 ((eq (car form) 'unquote)
1241 ((eq (car form) 'backquote)
1242 (backquote-expand-1 (backquote-expand-1 (cadr form))))
1247 ((and (listp s) (eq (car s) 'unquote))
1248 (list 'list (cadr s)))
1249 ((and (listp s) (eq (car s) 'unquote-splicing))
1252 (list 'list (backquote-expand-1 s)))))
1255 (defun backquote-expand (form)
1256 (if (and (listp form) (eq (car form) 'backquote))
1257 (backquote-expand-1 (cadr form))
1260 (defmacro backquote (form)
1261 (backquote-expand-1 form))
1263 (define-transformation backquote (form)
1264 (backquote-expand-1 form))
1268 (defmacro define-builtin (name args &body body)
1270 (define-compilation ,name ,args
1271 (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1274 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1275 (defmacro type-check (decls &body body)
1277 ,@(mapcar (lambda (decl)
1278 `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1280 ,@(mapcar (lambda (decl)
1281 `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1282 (indent "throw 'The value ' + "
1284 " + ' is not a type "
1289 (concat "return " (progn ,@body) ";" *newline*)))
1291 (defun num-op-num (x op y)
1292 (type-check (("x" "number" x) ("y" "number" y))
1293 (concat "x" op "y")))
1295 (define-builtin + (x y) (num-op-num x "+" y))
1296 (define-builtin - (x y) (num-op-num x "-" y))
1297 (define-builtin * (x y) (num-op-num x "*" y))
1298 (define-builtin / (x y) (num-op-num x "/" y))
1300 (define-builtin mod (x y) (num-op-num x "%" y))
1302 (define-builtin < (x y) (js!bool (num-op-num x "<" y)))
1303 (define-builtin > (x y) (js!bool (num-op-num x ">" y)))
1304 (define-builtin = (x y) (js!bool (num-op-num x "==" y)))
1305 (define-builtin <= (x y) (js!bool (num-op-num x "<=" y)))
1306 (define-builtin >= (x y) (js!bool (num-op-num x ">=" y)))
1308 (define-builtin numberp (x)
1309 (js!bool (concat "(typeof (" x ") == \"number\")")))
1311 (define-builtin floor (x)
1312 (type-check (("x" "number" x))
1315 (define-builtin cons (x y)
1316 (concat "({car: " x ", cdr: " y "})"))
1318 (define-builtin consp (x)
1321 "var tmp = " x ";" *newline*
1322 "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1324 (define-builtin car (x)
1326 "var tmp = " x ";" *newline*
1327 "return tmp === " (ls-compile nil)
1328 "? " (ls-compile nil)
1329 ": tmp.car;" *newline*))
1331 (define-builtin cdr (x)
1333 "var tmp = " x ";" *newline*
1334 "return tmp === " (ls-compile nil) "? "
1336 ": tmp.cdr;" *newline*))
1338 (define-builtin setcar (x new)
1339 (type-check (("x" "object" x))
1340 (concat "(x.car = " new ")")))
1342 (define-builtin setcdr (x new)
1343 (type-check (("x" "object" x))
1344 (concat "(x.cdr = " new ")")))
1346 (define-builtin symbolp (x)
1349 "var tmp = " x ";" *newline*
1350 "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1352 (define-builtin make-symbol (name)
1353 (type-check (("name" "string" name))
1356 (define-builtin symbol-name (x)
1357 (concat "(" x ").name"))
1359 (define-builtin set (symbol value)
1360 (concat "(" symbol ").value = " value))
1362 (define-builtin fset (symbol value)
1363 (concat "(" symbol ").function = " value))
1365 (define-builtin boundp (x)
1366 (js!bool (concat "(" x ".value !== undefined)")))
1368 (define-builtin symbol-value (x)
1370 "var symbol = " x ";" *newline*
1371 "var value = symbol.value;" *newline*
1372 "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1373 "return value;" *newline*))
1375 (define-builtin symbol-function (x)
1377 "var symbol = " x ";" *newline*
1378 "var func = symbol.function;" *newline*
1379 "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1380 "return func;" *newline*))
1382 (define-builtin symbol-plist (x)
1383 (concat "((" x ").plist || " (ls-compile nil) ")"))
1385 (define-builtin lambda-code (x)
1386 (concat "(" x ").toString()"))
1389 (define-builtin eq (x y) (js!bool (concat "(" x " === " y ")")))
1390 (define-builtin equal (x y) (js!bool (concat "(" x " == " y ")")))
1392 (define-builtin string (x)
1393 (type-check (("x" "number" x))
1394 "String.fromCharCode(x)"))
1396 (define-builtin stringp (x)
1397 (js!bool (concat "(typeof(" x ") == \"string\")")))
1399 (define-builtin string-upcase (x)
1400 (type-check (("x" "string" x))
1403 (define-builtin string-length (x)
1404 (type-check (("x" "string" x))
1407 (define-compilation slice (string a &optional b)
1409 "var str = " (ls-compile string) ";" *newline*
1410 "var a = " (ls-compile a) ";" *newline*
1413 (concat "b = " (ls-compile b) ";" *newline*)
1415 "return str.slice(a,b);" *newline*))
1417 (define-builtin char (string index)
1418 (type-check (("string" "string" string)
1419 ("index" "number" index))
1420 "string.charCodeAt(index)"))
1422 (define-builtin concat-two (string1 string2)
1423 (type-check (("string1" "string" string1)
1424 ("string2" "string" string2))
1425 "string1.concat(string2)"))
1427 (define-compilation funcall (func &rest args)
1428 (concat "(" (ls-compile func) ")("
1429 (join (mapcar #'ls-compile args)
1433 (define-compilation apply (func &rest args)
1435 (concat "(" (ls-compile func) ")()")
1436 (let ((args (butlast args))
1437 (last (car (last args))))
1439 "var f = " (ls-compile func) ";" *newline*
1440 "var args = [" (join (mapcar #'ls-compile args)
1443 "var tail = (" (ls-compile last) ");" *newline*
1444 "while (tail != " (ls-compile nil) "){" *newline*
1445 " args.push(tail.car);" *newline*
1446 " tail = tail.cdr;" *newline*
1448 "return f.apply(this, args);" *newline*))))
1450 (define-builtin js-eval (string)
1451 (type-check (("string" "string" string))
1452 "eval.apply(window, [string])"))
1454 (define-builtin error (string)
1455 (js!selfcall "throw " string ";" *newline*))
1457 (define-builtin new () "{}")
1459 (define-builtin oget (object key)
1461 "var tmp = " "(" object ")[" key "];" *newline*
1462 "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1464 (define-builtin oset (object key value)
1465 (concat "((" object ")[" key "] = " value ")"))
1467 (define-builtin in (key object)
1468 (js!bool (concat "((" key ") in (" object "))")))
1470 (define-builtin functionp (x)
1471 (js!bool (concat "(typeof " x " == 'function')")))
1473 (define-builtin write-string (x)
1474 (type-check (("x" "string" x))
1479 (let ((b (lookup-in-lexenv x *environment* 'function)))
1480 (and (eq (binding-type b) 'macro)
1483 (defun ls-macroexpand-1 (form)
1484 (let ((macro-binding (macro (car form))))
1486 (apply (eval (binding-value macro-binding)) (cdr form))
1489 (defun compile-funcall (function args)
1490 (concat (ls-compile `#',function) "("
1491 (join (mapcar #'ls-compile args)
1495 (defun ls-compile (sexp)
1498 (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1499 (if (eq (binding-type b) 'lexical-variable)
1501 (ls-compile `(symbol-value ',sexp)))))
1502 ((integerp sexp) (integer-to-string sexp))
1503 ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1505 (if (assoc (car sexp) *compilations*)
1506 (let ((comp (second (assoc (car sexp) *compilations*))))
1507 (apply comp (cdr sexp)))
1508 (if (macro (car sexp))
1509 (ls-compile (ls-macroexpand-1 sexp))
1510 (compile-funcall (car sexp) (cdr sexp)))))))
1512 (defun ls-compile-toplevel (sexp)
1513 (let ((*toplevel-compilations* nil))
1515 ((and (consp sexp) (eq (car sexp) 'progn))
1516 (let ((subs (mapcar #'ls-compile-toplevel (cdr sexp))))
1517 (join (remove-if #'null-or-empty-p subs))))
1519 (let ((code (ls-compile sexp)))
1520 (concat (join-trailing (get-toplevel-compilations)
1521 (concat ";" *newline*))
1523 (concat code ";" *newline*)
1527 ;;; Once we have the compiler, we define the runtime environment and
1528 ;;; interactive development (eval), which works calling the compiler
1529 ;;; and evaluating the Javascript result globally.
1533 (defmacro with-compilation-unit (&body body)
1536 (setq *compilation-unit-checks* nil)
1537 (clear-undeclared-global-bindings)
1539 (dolist (check *compilation-unit-checks*)
1544 (with-compilation-unit
1545 (ls-compile-toplevel x))))
1548 (js-eval "var lisp")
1549 (js-vset "lisp" (new))
1550 (js-vset "lisp.read" #'ls-read-from-string)
1551 (js-vset "lisp.print" #'prin1-to-string)
1552 (js-vset "lisp.eval" #'eval)
1553 (js-vset "lisp.compile" #'ls-compile-toplevel)
1554 (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
1555 (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str))))
1557 ;; Set the initial global environment to be equal to the host global
1558 ;; environment at this point of the compilation.
1560 (toplevel-compilation
1563 ,@(mapcar (lambda (s)
1564 `(oset *package* ,(symbol-name (car s))
1565 (js-vref ,(cdr s))))
1567 (setq *literal-symbols* ',*literal-symbols*)
1568 (setq *environment* ',*environment*)
1569 (setq *variable-counter* ,*variable-counter*)
1570 (setq *gensym-counter* ,*gensym-counter*)
1571 (setq *block-counter* ,*block-counter*)))))
1574 (toplevel-compilation
1576 `(setq *literal-counter* ,*literal-counter*)))))
1579 ;;; Finally, we provide a couple of functions to easily bootstrap
1580 ;;; this. It just calls the compiler with this file as input.
1584 (defun read-whole-file (filename)
1585 (with-open-file (in filename)
1586 (let ((seq (make-array (file-length in) :element-type 'character)))
1587 (read-sequence seq in)
1590 (defun ls-compile-file (filename output)
1591 (setq *compilation-unit-checks* nil)
1592 (with-open-file (out output :direction :output :if-exists :supersede)
1593 (let* ((source (read-whole-file filename))
1594 (in (make-string-stream source)))
1596 for x = (ls-read in)
1598 for compilation = (ls-compile-toplevel x)
1599 when (plusp (length compilation))
1600 do (write-string compilation out))
1601 (dolist (check *compilation-unit-checks*)
1603 (setq *compilation-unit-checks* nil))))
1606 (setq *environment* (make-lexenv))
1607 (setq *literal-symbols* nil)
1608 (setq *variable-counter* 0
1612 (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))