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) (special t nil))
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 (declaim (special ,name))
56 (unless (boundp ',name) (setq ,name ,value))
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)))))
85 (defmacro return (&optional value)
86 `(return-from nil ,value))
88 (defmacro while (condition &body body)
89 `(block nil (%while ,condition ,@body)))
91 (defvar *gensym-counter* 0)
92 (defun gensym (&optional (prefix "G"))
93 (setq *gensym-counter* (+ *gensym-counter* 1))
94 (make-symbol (concat-two prefix (integer-to-string *gensym-counter*))))
100 (defun = (x y) (= x y))
101 (defun + (x y) (+ x y))
102 (defun - (x y) (- x y))
103 (defun * (x y) (* x y))
104 (defun / (x y) (/ x y))
105 (defun 1+ (x) (+ x 1))
106 (defun 1- (x) (- x 1))
107 (defun zerop (x) (= x 0))
108 (defun truncate (x y) (floor (/ x y)))
110 (defun eql (x y) (eq x y))
112 (defun not (x) (if x nil t))
114 (defun cons (x y ) (cons x y))
115 (defun consp (x) (consp x))
118 "Return the CAR part of a cons, or NIL if X is null."
121 (defun cdr (x) (cdr x))
122 (defun caar (x) (car (car x)))
123 (defun cadr (x) (car (cdr x)))
124 (defun cdar (x) (cdr (car x)))
125 (defun cddr (x) (cdr (cdr x)))
126 (defun caddr (x) (car (cdr (cdr x))))
127 (defun cdddr (x) (cdr (cdr (cdr x))))
128 (defun cadddr (x) (car (cdr (cdr (cdr x)))))
129 (defun first (x) (car x))
130 (defun second (x) (cadr x))
131 (defun third (x) (caddr x))
132 (defun fourth (x) (cadddr x))
134 (defun list (&rest args) args)
140 (defmacro incf (x &optional (delta 1))
141 `(setq ,x (+ ,x ,delta)))
143 (defmacro decf (x &optional (delta 1))
144 `(setq ,x (- ,x ,delta)))
146 (defmacro push (x place)
147 `(setq ,place (cons ,x ,place)))
149 (defmacro dolist (iter &body body)
150 (let ((var (first iter))
153 (let ((,g!list ,(second iter))
156 (setq ,var (car ,g!list))
158 (setq ,g!list (cdr ,g!list)))
161 (defmacro dotimes (iter &body body)
162 (let ((g!to (gensym))
165 (result (third iter)))
169 (%while (< ,var ,g!to)
174 (defmacro cond (&rest clausules)
177 (if (eq (caar clausules) t)
178 `(progn ,@(cdar clausules))
179 `(if ,(caar clausules)
180 (progn ,@(cdar clausules))
181 (cond ,@(cdr clausules))))))
183 (defmacro case (form &rest clausules)
184 (let ((!form (gensym)))
185 `(let ((,!form ,form))
187 ,@(mapcar (lambda (clausule)
188 (if (eq (car clausule) t)
190 `((eql ,!form ',(car clausule))
194 (defmacro ecase (form &rest clausules)
199 (error "ECASE expression failed."))))))
201 (defmacro and (&rest forms)
212 (defmacro or (&rest forms)
220 `(let ((,g ,(car forms)))
221 (if ,g ,g (or ,@(cdr forms))))))))
223 (defmacro prog1 (form &body body)
224 (let ((value (gensym)))
225 `(let ((,value ,form))
229 (defmacro prog2 (form1 result &body body)
230 `(prog1 (progn ,form1 ,result) ,@body)))
233 ;;; This couple of helper functions will be defined in both Common
234 ;;; Lisp and in Ecmalisp.
235 (defun ensure-list (x)
240 (defun !reduce (func list initial)
245 (funcall func initial (car list)))))
247 ;;; Go on growing the Lisp language in Ecmalisp, with more high
248 ;;; level utilities as well as correct versions of other
252 (defun append-two (list1 list2)
256 (append (cdr list1) list2))))
258 (defun append (&rest lists)
259 (!reduce #'append-two lists '()))
261 (defun revappend (list1 list2)
263 (push (car list1) list2)
264 (setq list1 (cdr list1)))
267 (defun reverse (list)
268 (revappend list '()))
270 (defun list-length (list)
272 (while (not (null list))
274 (setq list (cdr list)))
282 (defun concat-two (s1 s2)
285 (defun mapcar (func list)
288 (cons (funcall func (car list))
289 (mapcar func (cdr list)))))
291 (defun identity (x) x)
294 (mapcar #'identity x))
296 (defun code-char (x) x)
297 (defun char-code (x) x)
298 (defun char= (x y) (= x y))
301 (and (numberp x) (= (floor x) x)))
303 (defun plusp (x) (< 0 x))
304 (defun minusp (x) (< x 0))
307 (or (consp x) (null x)))
309 (defun nthcdr (n list)
310 (while (and (plusp n) list)
312 (setq list (cdr list)))
316 (car (nthcdr n list)))
319 (while (consp (cdr x))
325 (cons (car x) (butlast (cdr x)))))
327 (defun member (x list)
329 (when (eql x (car list))
331 (setq list (cdr list))))
333 (defun remove (x list)
338 (remove x (cdr list)))
340 (cons (car list) (remove x (cdr list))))))
342 (defun remove-if (func list)
346 ((funcall func (car list))
347 (remove-if func (cdr list)))
349 (cons (car list) (remove-if func (cdr list))))))
351 (defun remove-if-not (func list)
355 ((funcall func (car list))
356 (cons (car list) (remove-if-not func (cdr list))))
358 (remove-if-not func (cdr list)))))
360 (defun digit-char-p (x)
361 (if (and (<= #\0 x) (<= x #\9))
365 (defun subseq (seq a &optional b)
372 (error "Unsupported argument."))))
374 (defun parse-integer (string)
377 (size (length string)))
378 (while (< index size)
379 (setq value (+ (* value 10) (digit-char-p (char string index))))
383 (defun some (function seq)
388 (while (< index size)
389 (when (funcall function (char seq index))
390 (return-from some t))
395 (when (funcall function x)
398 (error "Unknown sequence."))))
400 (defun every (function seq)
405 (while (< index size)
406 (unless (funcall function (char seq index))
407 (return-from every nil))
412 (unless (funcall function x)
415 (error "Unknown sequence."))))
417 (defun assoc (x alist)
419 (if (eql x (caar alist))
421 (setq alist (cdr alist))))
425 (cond ((stringp x) x)
426 ((symbolp x) (symbol-name x))
427 (t (char-to-string x))))
429 (defun string= (s1 s2)
432 (defun fdefinition (x)
439 (error "Invalid function"))))
441 (defun disassemble (function)
442 (write-line (lambda-code (fdefinition function)))
445 (defun documentation (x type)
446 "Return the documentation of X. TYPE must be the symbol VARIABLE or FUNCTION."
449 (let ((func (fdefinition x)))
450 (oget func "docstring")))
453 (error "Wrong argument type! it should be a symbol"))
458 (defvar *package-list* nil)
460 (defun list-all-packages ()
463 (defun make-package (name &optional use)
464 (let ((package (new))
465 (use (mapcar #'find-package-or-fail use)))
466 (oset package "packageName" name)
467 (oset package "symbols" (new))
468 (oset package "exports" (new))
469 (oset package "use" use)
470 (push package *package-list*)
474 (and (objectp x) (in "symbols" x)))
476 (defun find-package (package-designator)
477 (when (packagep package-designator)
478 (return-from find-package package-designator))
479 (let ((name (string package-designator)))
480 (dolist (package *package-list*)
481 (when (string= (package-name package) name)
484 (defun find-package-or-fail (package-designator)
485 (or (find-package package-designator)
486 (error "Package unknown.")))
488 (defun package-name (package-designator)
489 (let ((package (find-package-or-fail package-designator)))
490 (oget package "packageName")))
492 (defun %package-symbols (package-designator)
493 (let ((package (find-package-or-fail package-designator)))
494 (oget package "symbols")))
496 (defun package-use-list (package-designator)
497 (let ((package (find-package-or-fail package-designator)))
498 (oget package "use")))
500 (defun %package-external-symbols (package-designator)
501 (let ((package (find-package-or-fail package-designator)))
502 (oget package "exports")))
504 (defvar *common-lisp-package*
507 (defvar *user-package*
508 (make-package "CL-USER" (list *common-lisp-package*)))
510 (defvar *keyword-package*
511 (make-package "KEYWORD"))
514 (and (symbolp x) (eq (symbol-package x) *keyword-package*)))
516 (defvar *package* *common-lisp-package*)
518 (defmacro in-package (package-designator)
520 (setq *package* (find-package-or-fail ,package-designator))))
522 ;; This function is used internally to initialize the CL package
523 ;; with the symbols built during bootstrap.
524 (defun %intern-symbol (symbol)
525 (let ((symbols (%package-symbols *common-lisp-package*)))
526 (oset symbol "package" *common-lisp-package*)
527 (oset symbols (symbol-name symbol) symbol)))
529 (defun %find-symbol (name package)
530 (let ((package (find-package-or-fail package)))
531 (let ((symbols (%package-symbols package)))
532 (if (in name symbols)
533 (cons (oget symbols name) t)
534 (dolist (used (package-use-list package) (cons nil nil))
535 (let ((exports (%package-external-symbols used)))
536 (when (in name exports)
537 (return-from %find-symbol
538 (cons (oget exports name) t)))))))))
540 (defun find-symbol (name &optional (package *package*))
541 (car (%find-symbol name package)))
543 (defun intern (name &optional (package *package*))
544 (let ((package (find-package-or-fail package)))
545 (let ((result (%find-symbol name package)))
548 (let ((symbols (%package-symbols package)))
550 (let ((symbol (make-symbol name)))
551 (oset symbol "package" package)
552 (when (eq package *keyword-package*)
553 (oset symbol "value" symbol)
554 (export (list symbol) package))
555 (oset symbols name symbol)))))))
557 (defun symbol-package (symbol)
558 (unless (symbolp symbol)
559 (error "it is not a symbol"))
560 (oget symbol "package"))
562 (defun export (symbols &optional (package *package*))
563 (let ((exports (%package-external-symbols package)))
564 (dolist (symb symbols t)
565 (oset exports (symbol-name symb) symb)))))
568 ;;; The compiler offers some primitives and special forms which are
569 ;;; not found in Common Lisp, for instance, while. So, we grow Common
570 ;;; Lisp a bit to it can execute the rest of the file.
573 (defmacro while (condition &body body)
578 (defmacro eval-when-compile (&body body)
579 `(eval-when (:compile-toplevel :load-toplevel :execute)
582 (defun concat-two (s1 s2)
583 (concatenate 'string s1 s2))
585 (defun setcar (cons new)
586 (setf (car cons) new))
587 (defun setcdr (cons new)
588 (setf (cdr cons) new)))
590 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
591 ;;; from here, this code will compile on both. We define some helper
592 ;;; functions now for string manipulation and so on. They will be
593 ;;; useful in the compiler, mostly.
595 (defvar *newline* (string (code-char 10)))
597 (defun concat (&rest strs)
598 (!reduce #'concat-two strs ""))
600 (defmacro concatf (variable &body form)
601 `(setq ,variable (concat ,variable (progn ,@form))))
603 ;;; Concatenate a list of strings, with a separator
604 (defun join (list &optional (separator ""))
613 (join (cdr list) separator)))))
615 (defun join-trailing (list &optional (separator ""))
618 (concat (car list) separator (join-trailing (cdr list) separator))))
620 (defun mapconcat (func list)
621 (join (mapcar func list)))
623 ;;; Like CONCAT, but prefix each line with four spaces. Two versions
624 ;;; of this function are available, because the Ecmalisp version is
625 ;;; very slow and bootstraping was annoying.
628 (defun indent (&rest string)
629 (let ((input (join string)))
632 (size (length input)))
633 (when (plusp (length input)) (concatf output " "))
634 (while (< index size)
636 (if (and (char= (char input index) #\newline)
638 (not (char= (char input (1+ index)) #\newline)))
639 (concat (string #\newline) " ")
640 (string (char input index)))))
641 (concatf output str))
646 (defun indent (&rest string)
647 (with-output-to-string (*standard-output*)
648 (with-input-from-string (input (join string))
650 for line = (read-line input nil)
652 do (write-string " ")
653 do (write-line line)))))
656 (defun integer-to-string (x)
661 (concat "-" (integer-to-string (- 0 x))))
664 (while (not (zerop x))
665 (push (mod x 10) digits)
666 (setq x (truncate x 10)))
667 (join (mapcar (lambda (d) (string (char "0123456789" d)))
671 ;;; Wrap X with a Javascript code to convert the result from
672 ;;; Javascript generalized booleans to T or NIL.
674 (concat "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
676 ;;; Concatenate the arguments and wrap them with a self-calling
677 ;;; Javascript anonymous function. It is used to make some Javascript
678 ;;; statements valid expressions and provide a private scope as well.
679 ;;; It could be defined as function, but we could do some
680 ;;; preprocessing in the future.
681 (defmacro js!selfcall (&body body)
682 `(concat "(function(){" *newline* (indent ,@body) "})()"))
689 (defun prin1-to-string (form)
692 (if (cdr (%find-symbol (symbol-name form) *package*))
694 (let ((package (symbol-package form))
695 (name (symbol-name form)))
696 (concat (if (eq package (find-package "KEYWORD"))
698 (package-name package))
700 ((integerp form) (integer-to-string form))
701 ((stringp form) (concat "\"" (escape-string form) "\""))
703 (let ((name (oget form "fname")))
705 (concat "#<FUNCTION " name ">")
706 (concat "#<FUNCTION>"))))
709 (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
710 (let ((last (last form)))
711 (if (null (cdr last))
712 (prin1-to-string (car last))
713 (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
716 (concat "#<PACKAGE " (package-name form) ">"))))
718 (defun write-line (x)
720 (write-string *newline*)
724 (write-string "WARNING: ")
728 (write-line (prin1-to-string x))
734 ;;; The Lisp reader, parse strings and return Lisp objects. The main
735 ;;; entry points are `ls-read' and `ls-read-from-string'.
737 (defun make-string-stream (string)
740 (defun %peek-char (stream)
741 (and (< (cdr stream) (length (car stream)))
742 (char (car stream) (cdr stream))))
744 (defun %read-char (stream)
745 (and (< (cdr stream) (length (car stream)))
746 (prog1 (char (car stream) (cdr stream))
747 (setcdr stream (1+ (cdr stream))))))
749 (defun whitespacep (ch)
750 (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
752 (defun skip-whitespaces (stream)
754 (setq ch (%peek-char stream))
755 (while (and ch (whitespacep ch))
757 (setq ch (%peek-char stream)))))
759 (defun terminalp (ch)
760 (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
762 (defun read-until (stream func)
765 (setq ch (%peek-char stream))
766 (while (and ch (not (funcall func ch)))
767 (setq string (concat string (string ch)))
769 (setq ch (%peek-char stream)))
772 (defun skip-whitespaces-and-comments (stream)
774 (skip-whitespaces stream)
775 (setq ch (%peek-char stream))
776 (while (and ch (char= ch #\;))
777 (read-until stream (lambda (x) (char= x #\newline)))
778 (skip-whitespaces stream)
779 (setq ch (%peek-char stream)))))
781 (defun %read-list (stream)
782 (skip-whitespaces-and-comments stream)
783 (let ((ch (%peek-char stream)))
786 (error "Unspected EOF"))
792 (prog1 (ls-read stream)
793 (skip-whitespaces-and-comments stream)
794 (unless (char= (%read-char stream) #\))
795 (error "')' was expected."))))
797 (cons (ls-read stream) (%read-list stream))))))
799 (defun read-string (stream)
802 (setq ch (%read-char stream))
803 (while (not (eql ch #\"))
805 (error "Unexpected EOF"))
807 (setq ch (%read-char stream)))
808 (setq string (concat string (string ch)))
809 (setq ch (%read-char stream)))
812 (defun read-sharp (stream)
814 (ecase (%read-char stream)
816 (list 'function (ls-read stream)))
819 (concat (string (%read-char stream))
820 (read-until stream #'terminalp))))
822 ((string= cname "space") (char-code #\space))
823 ((string= cname "tab") (char-code #\tab))
824 ((string= cname "newline") (char-code #\newline))
825 (t (char-code (char cname 0))))))
827 (let ((feature (read-until stream #'terminalp)))
829 ((string= feature "common-lisp")
830 (ls-read stream) ;ignore
832 ((string= feature "ecmalisp")
835 (error "Unknown reader form.")))))))
837 ;;; Parse a string of the form NAME, PACKAGE:NAME or
838 ;;; PACKAGE::NAME and return the name. If the string is of the
839 ;;; form 1) or 3), but the symbol does not exist, it will be created
840 ;;; and interned in that package.
841 (defun read-symbol (string)
842 (let ((size (length string))
843 package name internalp index)
845 (while (and (< index size)
846 (not (char= (char string index) #\:)))
852 (setq package *package*)
857 (setq package "KEYWORD")
858 (setq package (string-upcase (subseq string 0 index))))
860 (when (char= (char string index) #\:)
863 (setq name (subseq string index))))
864 ;; Canonalize symbol name and package
865 (setq name (string-upcase name))
866 (setq package (find-package package))
867 ;; TODO: PACKAGE:SYMBOL should signal error if SYMBOL is not an
868 ;; external symbol from PACKAGE.
869 (if (or internalp (eq package (find-package "KEYWORD")))
870 (intern name package)
871 (find-symbol name package))))
873 (defvar *eof* (gensym))
874 (defun ls-read (stream)
875 (skip-whitespaces-and-comments stream)
876 (let ((ch (%peek-char stream)))
878 ((or (null ch) (char= ch #\)))
885 (list 'quote (ls-read stream)))
888 (list 'backquote (ls-read stream)))
891 (read-string stream))
894 (if (eql (%peek-char stream) #\@)
895 (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
896 (list 'unquote (ls-read stream))))
900 (let ((string (read-until stream #'terminalp)))
901 (if (every #'digit-char-p string)
902 (parse-integer string)
903 (read-symbol string)))))))
905 (defun ls-read-from-string (string)
906 (ls-read (make-string-stream string)))
911 ;;; Translate the Lisp code to Javascript. It will compile the special
912 ;;; forms. Some primitive functions are compiled as special forms
913 ;;; too. The respective real functions are defined in the target (see
914 ;;; the beginning of this file) as well as some primitive functions.
916 (defvar *compilation-unit-checks* '())
918 (defun make-binding (name type value &optional declarations)
919 (list name type value declarations))
921 (defun binding-name (b) (first b))
922 (defun binding-type (b) (second b))
923 (defun binding-value (b) (third b))
924 (defun binding-declarations (b) (fourth b))
926 (defun set-binding-value (b value)
927 (setcar (cddr b) value))
929 (defun set-binding-declarations (b value)
930 (setcar (cdddr b) value))
932 (defun push-binding-declaration (decl b)
933 (set-binding-declarations b (cons decl (binding-declarations b))))
936 (defun make-lexenv ()
937 (list nil nil nil nil))
939 (defun copy-lexenv (lexenv)
942 (defun push-to-lexenv (binding lexenv namespace)
944 (variable (setcar lexenv (cons binding (car lexenv))))
945 (function (setcar (cdr lexenv) (cons binding (cadr lexenv))))
946 (block (setcar (cddr lexenv) (cons binding (caddr lexenv))))
947 (gotag (setcar (cdddr lexenv) (cons binding (cadddr lexenv))))))
949 (defun extend-lexenv (bindings lexenv namespace)
950 (let ((env (copy-lexenv lexenv)))
951 (dolist (binding (reverse bindings) env)
952 (push-to-lexenv binding env namespace))))
954 (defun lookup-in-lexenv (name lexenv namespace)
955 (assoc name (ecase namespace
956 (variable (first lexenv))
957 (function (second lexenv))
958 (block (third lexenv))
959 (gotag (fourth lexenv)))))
961 (defvar *environment* (make-lexenv))
963 (defvar *variable-counter* 0)
964 (defun gvarname (symbol)
965 (concat "v" (integer-to-string (incf *variable-counter*))))
967 (defun translate-variable (symbol)
968 (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
970 (defun extend-local-env (args)
971 (let ((new (copy-lexenv *environment*)))
972 (dolist (symbol args new)
973 (let ((b (make-binding symbol 'lexical-variable (gvarname symbol))))
974 (push-to-lexenv b new 'variable)))))
976 ;;; Toplevel compilations
977 (defvar *toplevel-compilations* nil)
979 (defun toplevel-compilation (string)
980 (push string *toplevel-compilations*))
982 (defun null-or-empty-p (x)
985 (defun get-toplevel-compilations ()
986 (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
988 (defun %compile-defmacro (name lambda)
989 (toplevel-compilation (ls-compile `',name))
990 (push-to-lexenv (make-binding name 'macro lambda) *environment* 'function))
992 (defun global-binding (name type namespace)
993 (or (lookup-in-lexenv name *environment* namespace)
994 (let ((b (make-binding name type nil)))
995 (push-to-lexenv b *environment* namespace)
998 (defun claimp (symbol namespace claim)
999 (let ((b (lookup-in-lexenv symbol *environment* namespace)))
1000 (and b (member claim (binding-declarations b)))))
1002 (defun !proclaim (decl)
1005 (dolist (name (cdr decl))
1006 (let ((b (global-binding name 'variable 'variable)))
1007 (push-binding-declaration 'special b))))
1009 (dolist (name (cdr decl))
1010 (let ((b (global-binding name 'function 'function)))
1011 (push-binding-declaration 'notinline b))))
1013 (dolist (name (cdr decl))
1014 (let ((b (global-binding name 'variable 'variable)))
1015 (push-binding-declaration 'constant b))))
1017 (dolist (name (cdr decl))
1018 (let ((b (global-binding name 'function 'function)))
1019 (push-binding-declaration 'non-overridable b))))))
1022 (fset 'proclaim #'!proclaim)
1026 (defvar *compilations* nil)
1028 (defmacro define-compilation (name args &body body)
1029 ;; Creates a new primitive `name' with parameters args and
1030 ;; @body. The body can access to the local environment through the
1031 ;; variable *ENVIRONMENT*.
1032 `(push (list ',name (lambda ,args (block ,name ,@body)))
1035 (define-compilation if (condition true false)
1036 (concat "(" (ls-compile condition) " !== " (ls-compile nil)
1037 " ? " (ls-compile true)
1038 " : " (ls-compile false)
1041 (defvar *lambda-list-keywords* '(&optional &rest))
1043 (defun list-until-keyword (list)
1044 (if (or (null list) (member (car list) *lambda-list-keywords*))
1046 (cons (car list) (list-until-keyword (cdr list)))))
1048 (defun lambda-list-required-arguments (lambda-list)
1049 (list-until-keyword lambda-list))
1051 (defun lambda-list-optional-arguments-with-default (lambda-list)
1052 (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
1054 (defun lambda-list-optional-arguments (lambda-list)
1055 (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
1057 (defun lambda-list-rest-argument (lambda-list)
1058 (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
1060 (error "Bad lambda-list"))
1064 (defun lambda-docstring-wrapper (docstring &rest strs)
1067 "var func = " (join strs) ";" *newline*
1068 "func.docstring = '" docstring "';" *newline*
1069 "return func;" *newline*)
1072 (define-compilation lambda (lambda-list &rest body)
1073 (let ((required-arguments (lambda-list-required-arguments lambda-list))
1074 (optional-arguments (lambda-list-optional-arguments lambda-list))
1075 (rest-argument (lambda-list-rest-argument lambda-list))
1077 ;; Get the documentation string for the lambda function
1078 (when (and (stringp (car body))
1079 (not (null (cdr body))))
1080 (setq documentation (car body))
1081 (setq body (cdr body)))
1082 (let ((n-required-arguments (length required-arguments))
1083 (n-optional-arguments (length optional-arguments))
1084 (*environment* (extend-local-env
1085 (append (ensure-list rest-argument)
1087 optional-arguments))))
1088 (lambda-docstring-wrapper
1091 (join (mapcar #'translate-variable
1092 (append required-arguments optional-arguments))
1095 ;; Check number of arguments
1097 (if required-arguments
1098 (concat "if (arguments.length < " (integer-to-string n-required-arguments)
1099 ") throw 'too few arguments';" *newline*)
1101 (if (not rest-argument)
1102 (concat "if (arguments.length > "
1103 (integer-to-string (+ n-required-arguments n-optional-arguments))
1104 ") throw 'too many arguments';" *newline*)
1106 ;; Optional arguments
1107 (if optional-arguments
1108 (concat "switch(arguments.length){" *newline*
1109 (let ((optional-and-defaults
1110 (lambda-list-optional-arguments-with-default lambda-list))
1114 (while (< idx n-optional-arguments)
1115 (let ((arg (nth idx optional-and-defaults)))
1116 (push (concat "case "
1117 (integer-to-string (+ idx n-required-arguments)) ":" *newline*
1118 (translate-variable (car arg))
1120 (ls-compile (cadr arg))
1124 (push (concat "default: break;" *newline*) cases)
1125 (join (reverse cases))))
1128 ;; &rest/&body argument
1130 (let ((js!rest (translate-variable rest-argument)))
1131 (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
1132 "for (var i = arguments.length-1; i>="
1133 (integer-to-string (+ n-required-arguments n-optional-arguments))
1135 (indent js!rest " = "
1136 "{car: arguments[i], cdr: ") js!rest "};"
1140 (ls-compile-block body t)) *newline*
1143 (define-compilation setq (var val)
1144 (let ((b (lookup-in-lexenv var *environment* 'variable)))
1145 (if (eq (binding-type b) 'lexical-variable)
1146 (concat (binding-value b) " = " (ls-compile val))
1147 (ls-compile `(set ',var ,val)))))
1149 ;;; FFI Variable accessors
1150 (define-compilation js-vref (var)
1153 (define-compilation js-vset (var val)
1154 (concat "(" var " = " (ls-compile val) ")"))
1158 (defun escape-string (string)
1161 (size (length string)))
1162 (while (< index size)
1163 (let ((ch (char string index)))
1164 (when (or (char= ch #\") (char= ch #\\))
1165 (setq output (concat output "\\")))
1166 (when (or (char= ch #\newline))
1167 (setq output (concat output "\\"))
1169 (setq output (concat output (string ch))))
1174 (defvar *literal-symbols* nil)
1175 (defvar *literal-counter* 0)
1178 (concat "l" (integer-to-string (incf *literal-counter*))))
1180 (defun literal (sexp &optional recursive)
1182 ((integerp sexp) (integer-to-string sexp))
1183 ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1185 (or (cdr (assoc sexp *literal-symbols*))
1187 (s #+common-lisp (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1188 #+ecmalisp (ls-compile
1189 `(intern ,(symbol-name sexp)
1190 ,(package-name (symbol-package sexp))))))
1191 (push (cons sexp v) *literal-symbols*)
1192 (toplevel-compilation (concat "var " v " = " s))
1195 (let ((c (concat "{car: " (literal (car sexp) t) ", "
1196 "cdr: " (literal (cdr sexp) t) "}")))
1200 (toplevel-compilation (concat "var " v " = " c))
1203 (define-compilation quote (sexp)
1206 (define-compilation %while (pred &rest body)
1208 "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1209 (indent (ls-compile-block body))
1211 "return " (ls-compile nil) ";" *newline*))
1213 (define-compilation function (x)
1215 ((and (listp x) (eq (car x) 'lambda))
1218 (ls-compile `(symbol-function ',x)))))
1220 (define-compilation eval-when-compile (&rest body)
1221 (eval (cons 'progn body))
1224 (defmacro define-transformation (name args form)
1225 `(define-compilation ,name ,args
1226 (ls-compile ,form)))
1228 (define-compilation progn (&rest body)
1229 (js!selfcall (ls-compile-block body t)))
1231 (defun special-variable-p (x)
1232 (claimp x 'variable 'special))
1234 ;;; Wrap CODE to restore the symbol values of the dynamic
1235 ;;; bindings. BINDINGS is a list of pairs of the form
1236 ;;; (SYMBOL . PLACE), where PLACE is a Javascript variable
1237 ;;; name to initialize the symbol value and where to stored
1239 (defun let-binding-wrapper (bindings body)
1240 (when (null bindings)
1241 (return-from let-binding-wrapper body))
1244 (indent "var tmp;" *newline*
1247 (let ((s (ls-compile `(quote ,(car b)))))
1248 (concat "tmp = " s ".value;" *newline*
1249 s ".value = " (cdr b) ";" *newline*
1250 (cdr b) " = tmp;" *newline*)))
1254 "finally {" *newline*
1256 (mapconcat (lambda (b)
1257 (let ((s (ls-compile `(quote ,(car b)))))
1258 (concat s ".value" " = " (cdr b) ";" *newline*)))
1262 (define-compilation let (bindings &rest body)
1263 (let ((bindings (mapcar #'ensure-list bindings)))
1264 (let ((variables (mapcar #'first bindings)))
1265 (let ((cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
1266 (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
1268 (concat "(function("
1269 (join (mapcar (lambda (x)
1270 (if (special-variable-p x)
1271 (let ((v (gvarname x)))
1272 (push (cons x v) dynamic-bindings)
1274 (translate-variable x)))
1278 (let ((body (ls-compile-block body t)))
1279 (indent (let-binding-wrapper dynamic-bindings body)))
1280 "})(" (join cvalues ",") ")")))))
1283 ;;; Return the code to initialize BINDING, and push it extending the
1284 ;;; current lexical environment if the variable is special.
1285 (defun let*-initialize-value (binding)
1286 (let ((var (first binding))
1287 (value (second binding)))
1288 (if (special-variable-p var)
1289 (concat (ls-compile `(setq ,var ,value)) ";" *newline*)
1290 (let ((v (gvarname var)))
1291 (let ((b (make-binding var 'variable v)))
1292 (prog1 (concat "var " v " = " (ls-compile value) ";" *newline*)
1293 (push-to-lexenv b *environment* 'variable)))))))
1295 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
1296 ;;; DOES NOT generate code to initialize the value of the symbols,
1297 ;;; unlike let-binding-wrapper.
1298 (defun let*-binding-wrapper (symbols body)
1299 (when (null symbols)
1300 (return-from let*-binding-wrapper body))
1301 (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
1302 (remove-if-not #'special-variable-p symbols))))
1306 (mapconcat (lambda (b)
1307 (let ((s (ls-compile `(quote ,(car b)))))
1308 (concat "var " (cdr b) " = " s ".value;" *newline*)))
1312 "finally {" *newline*
1314 (mapconcat (lambda (b)
1315 (let ((s (ls-compile `(quote ,(car b)))))
1316 (concat s ".value" " = " (cdr b) ";" *newline*)))
1321 (define-compilation let* (bindings &rest body)
1322 (let ((bindings (mapcar #'ensure-list bindings))
1323 (*environment* (copy-lexenv *environment*)))
1325 (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
1326 (body (concat (mapconcat #'let*-initialize-value bindings)
1327 (ls-compile-block body t))))
1328 (let*-binding-wrapper specials body)))))
1331 (defvar *block-counter* 0)
1333 (define-compilation block (name &rest body)
1334 (let ((tr (integer-to-string (incf *block-counter*))))
1335 (let ((b (make-binding name 'block tr)))
1338 (let ((*environment* (extend-lexenv (list b) *environment* 'block)))
1339 (indent "return " (ls-compile `(progn ,@body)) ";" *newline*))
1341 "catch (cf){" *newline*
1342 " if (cf.type == 'block' && cf.id == " tr ")" *newline*
1343 " return cf.value;" *newline*
1345 " throw cf;" *newline*
1348 (define-compilation return-from (name &optional value)
1349 (let ((b (lookup-in-lexenv name *environment* 'block)))
1354 "id: " (binding-value b) ", "
1355 "value: " (ls-compile value) ", "
1356 "message: 'Return from unknown block " (symbol-name name) ".'"
1358 (error (concat "Unknown block `" (symbol-name name) "'.")))))
1361 (define-compilation catch (id &rest body)
1363 "var id = " (ls-compile id) ";" *newline*
1365 (indent "return " (ls-compile `(progn ,@body))
1368 "catch (cf){" *newline*
1369 " if (cf.type == 'catch' && cf.id == id)" *newline*
1370 " return cf.value;" *newline*
1372 " throw cf;" *newline*
1375 (define-compilation throw (id value)
1379 "id: " (ls-compile id) ", "
1380 "value: " (ls-compile value) ", "
1381 "message: 'Throw uncatched.'"
1385 (defvar *tagbody-counter* 0)
1386 (defvar *go-tag-counter* 0)
1389 (or (integerp x) (symbolp x)))
1391 (defun declare-tagbody-tags (tbidx body)
1393 (mapcar (lambda (label)
1394 (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1395 (make-binding label 'gotag (list tbidx tagidx))))
1396 (remove-if-not #'go-tag-p body))))
1397 (extend-lexenv bindings *environment* 'gotag)))
1399 (define-compilation tagbody (&rest body)
1400 ;; Ignore the tagbody if it does not contain any go-tag. We do this
1401 ;; because 1) it is easy and 2) many built-in forms expand to a
1402 ;; implicit tagbody, so we save some space.
1403 (unless (some #'go-tag-p body)
1404 (return-from tagbody (ls-compile `(progn ,@body nil))))
1405 ;; The translation assumes the first form in BODY is a label
1406 (unless (go-tag-p (car body))
1407 (push (gensym "START") body))
1408 ;; Tagbody compilation
1409 (let ((tbidx (integer-to-string *tagbody-counter*)))
1410 (let ((*environment* (declare-tagbody-tags tbidx body))
1412 (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1413 (setq initag (second (binding-value b))))
1415 "var tagbody_" tbidx " = " initag ";" *newline*
1417 "while (true) {" *newline*
1418 (indent "try {" *newline*
1419 (indent (let ((content ""))
1420 (concat "switch(tagbody_" tbidx "){" *newline*
1421 "case " initag ":" *newline*
1422 (dolist (form (cdr body) content)
1424 (if (not (go-tag-p form))
1425 (indent (ls-compile form) ";" *newline*)
1426 (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1427 (concat "case " (second (binding-value b)) ":" *newline*)))))
1428 "default:" *newline*
1429 " break tbloop;" *newline*
1432 "catch (jump) {" *newline*
1433 " if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1434 " tagbody_" tbidx " = jump.label;" *newline*
1436 " throw(jump);" *newline*
1439 "return " (ls-compile nil) ";" *newline*))))
1441 (define-compilation go (label)
1442 (let ((b (lookup-in-lexenv label *environment* 'gotag))
1444 ((symbolp label) (symbol-name label))
1445 ((integerp label) (integer-to-string label)))))
1450 "id: " (first (binding-value b)) ", "
1451 "label: " (second (binding-value b)) ", "
1452 "message: 'Attempt to GO to non-existing tag " n "'"
1454 (error (concat "Unknown tag `" n "'.")))))
1457 (define-compilation unwind-protect (form &rest clean-up)
1459 "var ret = " (ls-compile nil) ";" *newline*
1461 (indent "ret = " (ls-compile form) ";" *newline*)
1462 "} finally {" *newline*
1463 (indent (ls-compile-block clean-up))
1465 "return ret;" *newline*))
1468 ;;; A little backquote implementation without optimizations of any
1469 ;;; kind for ecmalisp.
1470 (defun backquote-expand-1 (form)
1476 ((eq (car form) 'unquote)
1478 ((eq (car form) 'backquote)
1479 (backquote-expand-1 (backquote-expand-1 (cadr form))))
1484 ((and (listp s) (eq (car s) 'unquote))
1485 (list 'list (cadr s)))
1486 ((and (listp s) (eq (car s) 'unquote-splicing))
1489 (list 'list (backquote-expand-1 s)))))
1492 (defun backquote-expand (form)
1493 (if (and (listp form) (eq (car form) 'backquote))
1494 (backquote-expand-1 (cadr form))
1497 (defmacro backquote (form)
1498 (backquote-expand-1 form))
1500 (define-transformation backquote (form)
1501 (backquote-expand-1 form))
1505 (defvar *builtins* nil)
1507 (defmacro define-raw-builtin (name args &body body)
1508 ;; Creates a new primitive function `name' with parameters args and
1509 ;; @body. The body can access to the local environment through the
1510 ;; variable *ENVIRONMENT*.
1511 `(push (list ',name (lambda ,args (block ,name ,@body)))
1514 (defmacro define-builtin (name args &body body)
1516 (define-raw-builtin ,name ,args
1517 (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1520 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1521 (defmacro type-check (decls &body body)
1523 ,@(mapcar (lambda (decl)
1524 `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1526 ,@(mapcar (lambda (decl)
1527 `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1528 (indent "throw 'The value ' + "
1530 " + ' is not a type "
1535 (concat "return " (progn ,@body) ";" *newline*)))
1537 (defun num-op-num (x op y)
1538 (type-check (("x" "number" x) ("y" "number" y))
1539 (concat "x" op "y")))
1541 (defmacro define-builtin-arithmetic (op)
1542 `(define-raw-builtin ,op (&rest args)
1544 (let ((res (ls-compile (car args))))
1545 (dolist (x (cdr args))
1546 (setq res (num-op-num res ,(symbol-name op) (ls-compile x))))
1550 (define-builtin-arithmetic +)
1551 (define-builtin-arithmetic -)
1552 (define-builtin-arithmetic *)
1553 (define-builtin-arithmetic /)
1555 (define-builtin mod (x y) (num-op-num x "%" y))
1557 (define-builtin < (x y) (js!bool (num-op-num x "<" y)))
1558 (define-builtin > (x y) (js!bool (num-op-num x ">" y)))
1559 (define-builtin = (x y) (js!bool (num-op-num x "==" y)))
1560 (define-builtin <= (x y) (js!bool (num-op-num x "<=" y)))
1561 (define-builtin >= (x y) (js!bool (num-op-num x ">=" y)))
1563 (define-builtin numberp (x)
1564 (js!bool (concat "(typeof (" x ") == \"number\")")))
1566 (define-builtin floor (x)
1567 (type-check (("x" "number" x))
1570 (define-builtin cons (x y)
1571 (concat "({car: " x ", cdr: " y "})"))
1573 (define-builtin consp (x)
1576 "var tmp = " x ";" *newline*
1577 "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1579 (define-builtin car (x)
1581 "var tmp = " x ";" *newline*
1582 "return tmp === " (ls-compile nil)
1583 "? " (ls-compile nil)
1584 ": tmp.car;" *newline*))
1586 (define-builtin cdr (x)
1588 "var tmp = " x ";" *newline*
1589 "return tmp === " (ls-compile nil) "? "
1591 ": tmp.cdr;" *newline*))
1593 (define-builtin setcar (x new)
1594 (type-check (("x" "object" x))
1595 (concat "(x.car = " new ")")))
1597 (define-builtin setcdr (x new)
1598 (type-check (("x" "object" x))
1599 (concat "(x.cdr = " new ")")))
1601 (define-builtin symbolp (x)
1604 "var tmp = " x ";" *newline*
1605 "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1607 (define-builtin make-symbol (name)
1608 (type-check (("name" "string" name))
1611 (define-builtin symbol-name (x)
1612 (concat "(" x ").name"))
1614 (define-builtin set (symbol value)
1615 (concat "(" symbol ").value = " value))
1617 (define-builtin fset (symbol value)
1618 (concat "(" symbol ").function = " value))
1620 (define-builtin boundp (x)
1621 (js!bool (concat "(" x ".value !== undefined)")))
1623 (define-builtin symbol-value (x)
1625 "var symbol = " x ";" *newline*
1626 "var value = symbol.value;" *newline*
1627 "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1628 "return value;" *newline*))
1630 (define-builtin symbol-function (x)
1632 "var symbol = " x ";" *newline*
1633 "var func = symbol.function;" *newline*
1634 "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1635 "return func;" *newline*))
1637 (define-builtin symbol-plist (x)
1638 (concat "((" x ").plist || " (ls-compile nil) ")"))
1640 (define-builtin lambda-code (x)
1641 (concat "(" x ").toString()"))
1644 (define-builtin eq (x y) (js!bool (concat "(" x " === " y ")")))
1645 (define-builtin equal (x y) (js!bool (concat "(" x " == " y ")")))
1647 (define-builtin char-to-string (x)
1648 (type-check (("x" "number" x))
1649 "String.fromCharCode(x)"))
1651 (define-builtin stringp (x)
1652 (js!bool (concat "(typeof(" x ") == \"string\")")))
1654 (define-builtin string-upcase (x)
1655 (type-check (("x" "string" x))
1658 (define-builtin string-length (x)
1659 (type-check (("x" "string" x))
1662 (define-raw-builtin slice (string a &optional b)
1664 "var str = " (ls-compile string) ";" *newline*
1665 "var a = " (ls-compile a) ";" *newline*
1668 (concat "b = " (ls-compile b) ";" *newline*)
1670 "return str.slice(a,b);" *newline*))
1672 (define-builtin char (string index)
1673 (type-check (("string" "string" string)
1674 ("index" "number" index))
1675 "string.charCodeAt(index)"))
1677 (define-builtin concat-two (string1 string2)
1678 (type-check (("string1" "string" string1)
1679 ("string2" "string" string2))
1680 "string1.concat(string2)"))
1682 (define-raw-builtin funcall (func &rest args)
1683 (concat "(" (ls-compile func) ")("
1684 (join (mapcar #'ls-compile args)
1688 (define-raw-builtin apply (func &rest args)
1690 (concat "(" (ls-compile func) ")()")
1691 (let ((args (butlast args))
1692 (last (car (last args))))
1694 "var f = " (ls-compile func) ";" *newline*
1695 "var args = [" (join (mapcar #'ls-compile args)
1698 "var tail = (" (ls-compile last) ");" *newline*
1699 "while (tail != " (ls-compile nil) "){" *newline*
1700 " args.push(tail.car);" *newline*
1701 " tail = tail.cdr;" *newline*
1703 "return f.apply(this, args);" *newline*))))
1705 (define-builtin js-eval (string)
1706 (type-check (("string" "string" string))
1707 "eval.apply(window, [string])"))
1709 (define-builtin error (string)
1710 (js!selfcall "throw " string ";" *newline*))
1712 (define-builtin new () "{}")
1714 (define-builtin objectp (x)
1715 (js!bool (concat "(typeof (" x ") === 'object')")))
1717 (define-builtin oget (object key)
1719 "var tmp = " "(" object ")[" key "];" *newline*
1720 "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1722 (define-builtin oset (object key value)
1723 (concat "((" object ")[" key "] = " value ")"))
1725 (define-builtin in (key object)
1726 (js!bool (concat "((" key ") in (" object "))")))
1728 (define-builtin functionp (x)
1729 (js!bool (concat "(typeof " x " == 'function')")))
1731 (define-builtin write-string (x)
1732 (type-check (("x" "string" x))
1737 (let ((b (lookup-in-lexenv x *environment* 'function)))
1738 (and (eq (binding-type b) 'macro)
1741 (defun ls-macroexpand-1 (form)
1742 (let ((macro-binding (macro (car form))))
1744 (let ((expander (binding-value macro-binding)))
1745 (when (listp expander)
1746 (let ((compiled (eval expander)))
1747 ;; The list representation are useful while
1748 ;; bootstrapping, as we can dump the definition of the
1749 ;; macros easily, but they are slow because we have to
1750 ;; evaluate them and compile them now and again. So, let
1751 ;; us replace the list representation version of the
1752 ;; function with the compiled one.
1754 #+ecmalisp (set-binding-value macro-binding compiled)
1755 (setq expander compiled)))
1756 (apply expander (cdr form)))
1759 (defun compile-funcall (function args)
1760 (if (and (symbolp function)
1761 (claimp function 'function 'non-overridable))
1762 (concat (ls-compile `',function) ".function("
1763 (join (mapcar #'ls-compile args)
1766 (concat (ls-compile `#',function) "("
1767 (join (mapcar #'ls-compile args)
1771 (defun ls-compile-block (sexps &optional return-last-p)
1773 (concat (ls-compile-block (butlast sexps))
1774 "return " (ls-compile (car (last sexps))) ";")
1776 (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
1777 (concat ";" *newline*))))
1779 (defun ls-compile (sexp)
1782 (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1784 ((and b (not (member 'special (binding-declarations b))))
1786 ((or (keywordp sexp)
1787 (member 'constant (binding-declarations b)))
1788 (concat (ls-compile `',sexp) ".value"))
1790 (ls-compile `(symbol-value ',sexp))))))
1791 ((integerp sexp) (integer-to-string sexp))
1792 ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1794 (let ((name (car sexp))
1798 ((assoc name *compilations*)
1799 (let ((comp (second (assoc name *compilations*))))
1801 ;; Built-in functions
1802 ((and (assoc name *builtins*)
1803 (not (claimp name 'function 'notinline)))
1804 (let ((comp (second (assoc name *builtins*))))
1808 (ls-compile (ls-macroexpand-1 sexp))
1809 (compile-funcall name args))))))))
1811 (defun ls-compile-toplevel (sexp)
1812 (let ((*toplevel-compilations* nil))
1814 ((and (consp sexp) (eq (car sexp) 'progn))
1815 (let ((subs (mapcar #'ls-compile-toplevel (cdr sexp))))
1816 (join (remove-if #'null-or-empty-p subs))))
1818 (let ((code (ls-compile sexp)))
1819 (concat (join-trailing (get-toplevel-compilations)
1820 (concat ";" *newline*))
1822 (concat code ";" *newline*)
1826 ;;; Once we have the compiler, we define the runtime environment and
1827 ;;; interactive development (eval), which works calling the compiler
1828 ;;; and evaluating the Javascript result globally.
1832 (defmacro with-compilation-unit (&body body)
1835 (setq *compilation-unit-checks* nil)
1837 (dolist (check *compilation-unit-checks*)
1842 (with-compilation-unit
1843 (ls-compile-toplevel x))))
1846 (export '(&rest &optional &body * *gensym-counter* *package* + - / 1+ 1- < <= =
1847 = > >= and append apply assoc atom block boundp boundp butlast caar
1848 cadddr caddr cadr car car case catch cdar cdddr cddr cdr cdr char
1849 char-code char= code-char cond cons consp copy-list decf declaim
1850 defparameter defun defvar digit-char-p disassemble documentation
1851 dolist dotimes ecase eq eql equal error eval every export fdefinition
1852 find-package find-symbol first fourth fset funcall function functionp
1853 gensym go identity if in-package incf integerp integerp intern
1854 keywordp lambda last length let let* list-all-packages list listp
1855 make-package make-symbol mapcar member minusp mod nil not nth nthcdr
1856 null numberp or package-name package-use-list packagep plusp
1857 prin1-to-string print proclaim prog1 prog2 pron push quote remove
1858 remove-if remove-if-not return return-from revappend reverse second
1859 set setq some string-upcase string string= stringp subseq
1860 symbol-function symbol-name symbol-package symbol-plist symbol-value
1861 symbolp t tagbody third throw truncate unless unwind-protect variable
1862 warn when write-line write-string zerop))
1864 (setq *package* *user-package*)
1866 (js-eval "var lisp")
1867 (js-vset "lisp" (new))
1868 (js-vset "lisp.read" #'ls-read-from-string)
1869 (js-vset "lisp.print" #'prin1-to-string)
1870 (js-vset "lisp.eval" #'eval)
1871 (js-vset "lisp.compile" #'ls-compile-toplevel)
1872 (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
1873 (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str))))
1875 ;; Set the initial global environment to be equal to the host global
1876 ;; environment at this point of the compilation.
1878 (toplevel-compilation
1881 ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
1883 (setq *literal-symbols* ',*literal-symbols*)
1884 (setq *environment* ',*environment*)
1885 (setq *variable-counter* ,*variable-counter*)
1886 (setq *gensym-counter* ,*gensym-counter*)
1887 (setq *block-counter* ,*block-counter*)))))
1890 (toplevel-compilation
1892 `(setq *literal-counter* ,*literal-counter*)))))
1895 ;;; Finally, we provide a couple of functions to easily bootstrap
1896 ;;; this. It just calls the compiler with this file as input.
1900 (defun read-whole-file (filename)
1901 (with-open-file (in filename)
1902 (let ((seq (make-array (file-length in) :element-type 'character)))
1903 (read-sequence seq in)
1906 (defun ls-compile-file (filename output)
1907 (setq *compilation-unit-checks* nil)
1908 (with-open-file (out output :direction :output :if-exists :supersede)
1909 (let* ((source (read-whole-file filename))
1910 (in (make-string-stream source)))
1912 for x = (ls-read in)
1914 for compilation = (ls-compile-toplevel x)
1915 when (plusp (length compilation))
1916 do (write-string compilation out))
1917 (dolist (check *compilation-unit-checks*)
1919 (setq *compilation-unit-checks* nil))))
1922 (setq *environment* (make-lexenv))
1923 (setq *literal-symbols* nil)
1924 (setq *variable-counter* 0
1928 (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))