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 1+ (x) (+ x 1))
104 (defun 1- (x) (- x 1))
105 (defun zerop (x) (= x 0))
106 (defun truncate (x y) (floor (/ x y)))
108 (defun eql (x y) (eq x y))
110 (defun not (x) (if x nil t))
112 (defun cons (x y ) (cons x y))
113 (defun consp (x) (consp x))
116 "Return the CAR part of a cons, or NIL if X is null."
119 (defun cdr (x) (cdr x))
120 (defun caar (x) (car (car x)))
121 (defun cadr (x) (car (cdr x)))
122 (defun cdar (x) (cdr (car x)))
123 (defun cddr (x) (cdr (cdr x)))
124 (defun caddr (x) (car (cdr (cdr x))))
125 (defun cdddr (x) (cdr (cdr (cdr x))))
126 (defun cadddr (x) (car (cdr (cdr (cdr x)))))
127 (defun first (x) (car x))
128 (defun second (x) (cadr x))
129 (defun third (x) (caddr x))
130 (defun fourth (x) (cadddr x))
132 (defun list (&rest args) args)
138 (defmacro incf (x &optional (delta 1))
139 `(setq ,x (+ ,x ,delta)))
141 (defmacro decf (x &optional (delta 1))
142 `(setq ,x (- ,x ,delta)))
144 (defmacro push (x place)
145 `(setq ,place (cons ,x ,place)))
147 (defmacro dolist (iter &body body)
148 (let ((var (first iter))
151 (let ((,g!list ,(second iter))
154 (setq ,var (car ,g!list))
156 (setq ,g!list (cdr ,g!list)))
159 (defmacro dotimes (iter &body body)
160 (let ((g!to (gensym))
163 (result (third iter)))
167 (%while (< ,var ,g!to)
172 (defmacro cond (&rest clausules)
175 (if (eq (caar clausules) t)
176 `(progn ,@(cdar clausules))
177 `(if ,(caar clausules)
178 (progn ,@(cdar clausules))
179 (cond ,@(cdr clausules))))))
181 (defmacro case (form &rest clausules)
182 (let ((!form (gensym)))
183 `(let ((,!form ,form))
185 ,@(mapcar (lambda (clausule)
186 (if (eq (car clausule) t)
188 `((eql ,!form ',(car clausule))
192 (defmacro ecase (form &rest clausules)
197 (error "ECASE expression failed."))))))
199 (defmacro and (&rest forms)
210 (defmacro or (&rest forms)
218 `(let ((,g ,(car forms)))
219 (if ,g ,g (or ,@(cdr forms))))))))
221 (defmacro prog1 (form &body body)
222 (let ((value (gensym)))
223 `(let ((,value ,form))
227 (defmacro prog2 (form1 result &body body)
228 `(prog1 (progn ,form1 ,result) ,@body)))
231 ;;; This couple of helper functions will be defined in both Common
232 ;;; Lisp and in Ecmalisp.
233 (defun ensure-list (x)
238 (defun !reduce (func list initial)
243 (funcall func initial (car list)))))
245 ;;; Go on growing the Lisp language in Ecmalisp, with more high
246 ;;; level utilities as well as correct versions of other
250 (defun + (&rest args)
255 (defun - (x &rest others)
262 (defun append-two (list1 list2)
266 (append (cdr list1) list2))))
268 (defun append (&rest lists)
269 (!reduce #'append-two lists '()))
271 (defun revappend (list1 list2)
273 (push (car list1) list2)
274 (setq list1 (cdr list1)))
277 (defun reverse (list)
278 (revappend list '()))
280 (defun list-length (list)
282 (while (not (null list))
284 (setq list (cdr list)))
296 (defun concat-two (s1 s2)
299 (defun mapcar (func list)
302 (cons (funcall func (car list))
303 (mapcar func (cdr list)))))
305 (defun identity (x) x)
308 (mapcar #'identity x))
310 (defun code-char (x) x)
311 (defun char-code (x) x)
312 (defun char= (x y) (= x y))
315 (and (numberp x) (= (floor x) x)))
317 (defun plusp (x) (< 0 x))
318 (defun minusp (x) (< x 0))
321 (or (consp x) (null x)))
323 (defun nthcdr (n list)
324 (while (and (plusp n) list)
326 (setq list (cdr list)))
330 (car (nthcdr n list)))
333 (while (consp (cdr x))
339 (cons (car x) (butlast (cdr x)))))
341 (defun member (x list)
343 (when (eql x (car list))
345 (setq list (cdr list))))
347 (defun remove (x list)
352 (remove x (cdr list)))
354 (cons (car list) (remove x (cdr list))))))
356 (defun remove-if (func list)
360 ((funcall func (car list))
361 (remove-if func (cdr list)))
363 (cons (car list) (remove-if func (cdr list))))))
365 (defun remove-if-not (func list)
369 ((funcall func (car list))
370 (cons (car list) (remove-if-not func (cdr list))))
372 (remove-if-not func (cdr list)))))
374 (defun digit-char-p (x)
375 (if (and (<= #\0 x) (<= x #\9))
379 (defun subseq (seq a &optional b)
386 (error "Unsupported argument."))))
388 (defun parse-integer (string)
391 (size (length string)))
392 (while (< index size)
393 (setq value (+ (* value 10) (digit-char-p (char string index))))
397 (defun some (function seq)
402 (while (< index size)
403 (when (funcall function (char seq index))
404 (return-from some t))
409 (when (funcall function x)
412 (error "Unknown sequence."))))
414 (defun every (function seq)
419 (while (< index size)
420 (unless (funcall function (char seq index))
421 (return-from every nil))
426 (unless (funcall function x)
429 (error "Unknown sequence."))))
431 (defun assoc (x alist)
433 (if (eql x (caar alist))
435 (setq alist (cdr alist))))
439 (cond ((stringp x) x)
440 ((symbolp x) (symbol-name x))
441 (t (char-to-string x))))
443 (defun string= (s1 s2)
446 (defun fdefinition (x)
453 (error "Invalid function"))))
455 (defun disassemble (function)
456 (write-line (lambda-code (fdefinition function)))
459 (defun documentation (x type)
460 "Return the documentation of X. TYPE must be the symbol VARIABLE or FUNCTION."
463 (let ((func (fdefinition x)))
464 (oget func "docstring")))
467 (error "Wrong argument type! it should be a symbol"))
472 (defvar *package-list* nil)
474 (defun list-all-packages ()
477 (defun make-package (name &optional use)
478 (let ((package (new))
479 (use (mapcar #'find-package-or-fail use)))
480 (oset package "packageName" name)
481 (oset package "symbols" (new))
482 (oset package "exports" (new))
483 (oset package "use" use)
484 (push package *package-list*)
488 (and (objectp x) (in "symbols" x)))
490 (defun find-package (package-designator)
491 (when (packagep package-designator)
492 (return-from find-package package-designator))
493 (let ((name (string package-designator)))
494 (dolist (package *package-list*)
495 (when (string= (package-name package) name)
498 (defun find-package-or-fail (package-designator)
499 (or (find-package package-designator)
500 (error "Package unknown.")))
502 (defun package-name (package-designator)
503 (let ((package (find-package-or-fail package-designator)))
504 (oget package "packageName")))
506 (defun %package-symbols (package-designator)
507 (let ((package (find-package-or-fail package-designator)))
508 (oget package "symbols")))
510 (defun package-use-list (package-designator)
511 (let ((package (find-package-or-fail package-designator)))
512 (oget package "use")))
514 (defun %package-external-symbols (package-designator)
515 (let ((package (find-package-or-fail package-designator)))
516 (oget package "exports")))
518 (defvar *common-lisp-package*
521 (defvar *user-package*
522 (make-package "CL-USER" (list *common-lisp-package*)))
524 (defvar *keyword-package*
525 (make-package "KEYWORD"))
528 (and (symbolp x) (eq (symbol-package x) *keyword-package*)))
530 (defvar *package* *common-lisp-package*)
532 (defmacro in-package (package-designator)
534 (setq *package* (find-package-or-fail ,package-designator))))
536 ;; This function is used internally to initialize the CL package
537 ;; with the symbols built during bootstrap.
538 (defun %intern-symbol (symbol)
539 (let ((symbols (%package-symbols *common-lisp-package*)))
540 (oset symbol "package" *common-lisp-package*)
541 (oset symbols (symbol-name symbol) symbol)))
543 (defun %find-symbol (name package)
544 (let ((package (find-package-or-fail package)))
545 (let ((symbols (%package-symbols package)))
546 (if (in name symbols)
547 (cons (oget symbols name) t)
548 (dolist (used (package-use-list package) (cons nil nil))
549 (let ((exports (%package-external-symbols used)))
550 (when (in name exports)
551 (return-from %find-symbol
552 (cons (oget exports name) t)))))))))
554 (defun find-symbol (name &optional (package *package*))
555 (car (%find-symbol name package)))
557 (defun intern (name &optional (package *package*))
558 (let ((package (find-package-or-fail package)))
559 (let ((result (%find-symbol name package)))
562 (let ((symbols (%package-symbols package)))
564 (let ((symbol (make-symbol name)))
565 (oset symbol "package" package)
566 (when (eq package *keyword-package*)
567 (oset symbol "value" symbol)
568 (export (list symbol) package))
569 (oset symbols name symbol)))))))
571 (defun symbol-package (symbol)
572 (unless (symbolp symbol)
573 (error "it is not a symbol"))
574 (oget symbol "package"))
576 (defun export (symbols &optional (package *package*))
577 (let ((exports (%package-external-symbols package)))
578 (dolist (symb symbols t)
579 (oset exports (symbol-name symb) symb)))))
582 ;;; The compiler offers some primitives and special forms which are
583 ;;; not found in Common Lisp, for instance, while. So, we grow Common
584 ;;; Lisp a bit to it can execute the rest of the file.
587 (defmacro while (condition &body body)
592 (defmacro eval-when-compile (&body body)
593 `(eval-when (:compile-toplevel :load-toplevel :execute)
596 (defun concat-two (s1 s2)
597 (concatenate 'string s1 s2))
599 (defun setcar (cons new)
600 (setf (car cons) new))
601 (defun setcdr (cons new)
602 (setf (cdr cons) new))
604 (defun aset (array idx value)
605 (setf (aref array idx) value)))
607 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
608 ;;; from here, this code will compile on both. We define some helper
609 ;;; functions now for string manipulation and so on. They will be
610 ;;; useful in the compiler, mostly.
612 (defvar *newline* (string (code-char 10)))
614 (defun concat (&rest strs)
615 (!reduce #'concat-two strs ""))
617 (defmacro concatf (variable &body form)
618 `(setq ,variable (concat ,variable (progn ,@form))))
620 ;;; Concatenate a list of strings, with a separator
621 (defun join (list &optional (separator ""))
630 (join (cdr list) separator)))))
632 (defun join-trailing (list &optional (separator ""))
635 (concat (car list) separator (join-trailing (cdr list) separator))))
637 (defun mapconcat (func list)
638 (join (mapcar func list)))
640 (defun vector-to-list (vector)
642 (size (length vector)))
643 (dotimes (i size (reverse list))
644 (push (aref vector i) list))))
646 (defun list-to-vector (list)
647 (let ((v (make-array (length list)))
653 ;;; Like CONCAT, but prefix each line with four spaces. Two versions
654 ;;; of this function are available, because the Ecmalisp version is
655 ;;; very slow and bootstraping was annoying.
658 (defun indent (&rest string)
659 (let ((input (join string)))
662 (size (length input)))
663 (when (plusp (length input)) (concatf output " "))
664 (while (< index size)
666 (if (and (char= (char input index) #\newline)
668 (not (char= (char input (1+ index)) #\newline)))
669 (concat (string #\newline) " ")
670 (string (char input index)))))
671 (concatf output str))
676 (defun indent (&rest string)
677 (with-output-to-string (*standard-output*)
678 (with-input-from-string (input (join string))
680 for line = (read-line input nil)
682 do (write-string " ")
683 do (write-line line)))))
686 (defun integer-to-string (x)
691 (concat "-" (integer-to-string (- 0 x))))
694 (while (not (zerop x))
695 (push (mod x 10) digits)
696 (setq x (truncate x 10)))
697 (join (mapcar (lambda (d) (string (char "0123456789" d)))
701 ;;; Wrap X with a Javascript code to convert the result from
702 ;;; Javascript generalized booleans to T or NIL.
704 (concat "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
706 ;;; Concatenate the arguments and wrap them with a self-calling
707 ;;; Javascript anonymous function. It is used to make some Javascript
708 ;;; statements valid expressions and provide a private scope as well.
709 ;;; It could be defined as function, but we could do some
710 ;;; preprocessing in the future.
711 (defmacro js!selfcall (&body body)
712 `(concat "(function(){" *newline* (indent ,@body) "})()"))
719 (defun prin1-to-string (form)
722 (if (cdr (%find-symbol (symbol-name form) *package*))
724 (let ((package (symbol-package form))
725 (name (symbol-name form)))
726 (concat (if (eq package (find-package "KEYWORD"))
728 (package-name package))
730 ((integerp form) (integer-to-string form))
731 ((stringp form) (concat "\"" (escape-string form) "\""))
733 (let ((name (oget form "fname")))
735 (concat "#<FUNCTION " name ">")
736 (concat "#<FUNCTION>"))))
739 (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
740 (let ((last (last form)))
741 (if (null (cdr last))
742 (prin1-to-string (car last))
743 (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
746 (concat "#" (prin1-to-string (vector-to-list form))))
748 (concat "#<PACKAGE " (package-name form) ">"))))
750 (defun write-line (x)
752 (write-string *newline*)
756 (write-string "WARNING: ")
760 (write-line (prin1-to-string x))
766 ;;; The Lisp reader, parse strings and return Lisp objects. The main
767 ;;; entry points are `ls-read' and `ls-read-from-string'.
769 (defun make-string-stream (string)
772 (defun %peek-char (stream)
773 (and (< (cdr stream) (length (car stream)))
774 (char (car stream) (cdr stream))))
776 (defun %read-char (stream)
777 (and (< (cdr stream) (length (car stream)))
778 (prog1 (char (car stream) (cdr stream))
779 (setcdr stream (1+ (cdr stream))))))
781 (defun whitespacep (ch)
782 (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
784 (defun skip-whitespaces (stream)
786 (setq ch (%peek-char stream))
787 (while (and ch (whitespacep ch))
789 (setq ch (%peek-char stream)))))
791 (defun terminalp (ch)
792 (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
794 (defun read-until (stream func)
797 (setq ch (%peek-char stream))
798 (while (and ch (not (funcall func ch)))
799 (setq string (concat string (string ch)))
801 (setq ch (%peek-char stream)))
804 (defun skip-whitespaces-and-comments (stream)
806 (skip-whitespaces stream)
807 (setq ch (%peek-char stream))
808 (while (and ch (char= ch #\;))
809 (read-until stream (lambda (x) (char= x #\newline)))
810 (skip-whitespaces stream)
811 (setq ch (%peek-char stream)))))
813 (defun %read-list (stream)
814 (skip-whitespaces-and-comments stream)
815 (let ((ch (%peek-char stream)))
818 (error "Unspected EOF"))
824 (prog1 (ls-read stream)
825 (skip-whitespaces-and-comments stream)
826 (unless (char= (%read-char stream) #\))
827 (error "')' was expected."))))
829 (cons (ls-read stream) (%read-list stream))))))
831 (defun read-string (stream)
834 (setq ch (%read-char stream))
835 (while (not (eql ch #\"))
837 (error "Unexpected EOF"))
839 (setq ch (%read-char stream)))
840 (setq string (concat string (string ch)))
841 (setq ch (%read-char stream)))
844 (defun read-sharp (stream)
846 (ecase (%read-char stream)
848 (list 'function (ls-read stream)))
849 (#\( (list-to-vector (%read-list stream)))
852 (concat (string (%read-char stream))
853 (read-until stream #'terminalp))))
855 ((string= cname "space") (char-code #\space))
856 ((string= cname "tab") (char-code #\tab))
857 ((string= cname "newline") (char-code #\newline))
858 (t (char-code (char cname 0))))))
860 (let ((feature (read-until stream #'terminalp)))
862 ((string= feature "common-lisp")
863 (ls-read stream) ;ignore
865 ((string= feature "ecmalisp")
868 (error "Unknown reader form.")))))))
870 ;;; Parse a string of the form NAME, PACKAGE:NAME or
871 ;;; PACKAGE::NAME and return the name. If the string is of the
872 ;;; form 1) or 3), but the symbol does not exist, it will be created
873 ;;; and interned in that package.
874 (defun read-symbol (string)
875 (let ((size (length string))
876 package name internalp index)
878 (while (and (< index size)
879 (not (char= (char string index) #\:)))
885 (setq package *package*)
890 (setq package "KEYWORD")
891 (setq package (string-upcase (subseq string 0 index))))
893 (when (char= (char string index) #\:)
896 (setq name (subseq string index))))
897 ;; Canonalize symbol name and package
898 (setq name (string-upcase name))
899 (setq package (find-package package))
900 ;; TODO: PACKAGE:SYMBOL should signal error if SYMBOL is not an
901 ;; external symbol from PACKAGE.
902 (if (or internalp (eq package (find-package "KEYWORD")))
903 (intern name package)
904 (find-symbol name package))))
906 (defvar *eof* (gensym))
907 (defun ls-read (stream)
908 (skip-whitespaces-and-comments stream)
909 (let ((ch (%peek-char stream)))
911 ((or (null ch) (char= ch #\)))
918 (list 'quote (ls-read stream)))
921 (list 'backquote (ls-read stream)))
924 (read-string stream))
927 (if (eql (%peek-char stream) #\@)
928 (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
929 (list 'unquote (ls-read stream))))
933 (let ((string (read-until stream #'terminalp)))
934 (if (every #'digit-char-p string)
935 (parse-integer string)
936 (read-symbol string)))))))
938 (defun ls-read-from-string (string)
939 (ls-read (make-string-stream string)))
944 ;;; Translate the Lisp code to Javascript. It will compile the special
945 ;;; forms. Some primitive functions are compiled as special forms
946 ;;; too. The respective real functions are defined in the target (see
947 ;;; the beginning of this file) as well as some primitive functions.
949 (defvar *compilation-unit-checks* '())
951 (defun make-binding (name type value &optional declarations)
952 (list name type value declarations))
954 (defun binding-name (b) (first b))
955 (defun binding-type (b) (second b))
956 (defun binding-value (b) (third b))
957 (defun binding-declarations (b) (fourth b))
959 (defun set-binding-value (b value)
960 (setcar (cddr b) value))
962 (defun set-binding-declarations (b value)
963 (setcar (cdddr b) value))
965 (defun push-binding-declaration (decl b)
966 (set-binding-declarations b (cons decl (binding-declarations b))))
969 (defun make-lexenv ()
970 (list nil nil nil nil))
972 (defun copy-lexenv (lexenv)
975 (defun push-to-lexenv (binding lexenv namespace)
977 (variable (setcar lexenv (cons binding (car lexenv))))
978 (function (setcar (cdr lexenv) (cons binding (cadr lexenv))))
979 (block (setcar (cddr lexenv) (cons binding (caddr lexenv))))
980 (gotag (setcar (cdddr lexenv) (cons binding (cadddr lexenv))))))
982 (defun extend-lexenv (bindings lexenv namespace)
983 (let ((env (copy-lexenv lexenv)))
984 (dolist (binding (reverse bindings) env)
985 (push-to-lexenv binding env namespace))))
987 (defun lookup-in-lexenv (name lexenv namespace)
988 (assoc name (ecase namespace
989 (variable (first lexenv))
990 (function (second lexenv))
991 (block (third lexenv))
992 (gotag (fourth lexenv)))))
994 (defvar *environment* (make-lexenv))
996 (defvar *variable-counter* 0)
997 (defun gvarname (symbol)
998 (concat "v" (integer-to-string (incf *variable-counter*))))
1000 (defun translate-variable (symbol)
1001 (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
1003 (defun extend-local-env (args)
1004 (let ((new (copy-lexenv *environment*)))
1005 (dolist (symbol args new)
1006 (let ((b (make-binding symbol 'lexical-variable (gvarname symbol))))
1007 (push-to-lexenv b new 'variable)))))
1009 ;;; Toplevel compilations
1010 (defvar *toplevel-compilations* nil)
1012 (defun toplevel-compilation (string)
1013 (push string *toplevel-compilations*))
1015 (defun null-or-empty-p (x)
1018 (defun get-toplevel-compilations ()
1019 (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
1021 (defun %compile-defmacro (name lambda)
1022 (toplevel-compilation (ls-compile `',name))
1023 (push-to-lexenv (make-binding name 'macro lambda) *environment* 'function))
1025 (defun global-binding (name type namespace)
1026 (or (lookup-in-lexenv name *environment* namespace)
1027 (let ((b (make-binding name type nil)))
1028 (push-to-lexenv b *environment* namespace)
1031 (defun claimp (symbol namespace claim)
1032 (let ((b (lookup-in-lexenv symbol *environment* namespace)))
1033 (and b (member claim (binding-declarations b)))))
1035 (defun !proclaim (decl)
1038 (dolist (name (cdr decl))
1039 (let ((b (global-binding name 'variable 'variable)))
1040 (push-binding-declaration 'special b))))
1042 (dolist (name (cdr decl))
1043 (let ((b (global-binding name 'function 'function)))
1044 (push-binding-declaration 'notinline b))))
1046 (dolist (name (cdr decl))
1047 (let ((b (global-binding name 'variable 'variable)))
1048 (push-binding-declaration 'constant b))))
1050 (dolist (name (cdr decl))
1051 (let ((b (global-binding name 'function 'function)))
1052 (push-binding-declaration 'non-overridable b))))))
1055 (fset 'proclaim #'!proclaim)
1059 (defvar *compilations* nil)
1061 (defmacro define-compilation (name args &body body)
1062 ;; Creates a new primitive `name' with parameters args and
1063 ;; @body. The body can access to the local environment through the
1064 ;; variable *ENVIRONMENT*.
1065 `(push (list ',name (lambda ,args (block ,name ,@body)))
1068 (define-compilation if (condition true false)
1069 (concat "(" (ls-compile condition) " !== " (ls-compile nil)
1070 " ? " (ls-compile true)
1071 " : " (ls-compile false)
1074 (defvar *lambda-list-keywords* '(&optional &rest))
1076 (defun list-until-keyword (list)
1077 (if (or (null list) (member (car list) *lambda-list-keywords*))
1079 (cons (car list) (list-until-keyword (cdr list)))))
1081 (defun lambda-list-required-arguments (lambda-list)
1082 (list-until-keyword lambda-list))
1084 (defun lambda-list-optional-arguments-with-default (lambda-list)
1085 (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
1087 (defun lambda-list-optional-arguments (lambda-list)
1088 (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
1090 (defun lambda-list-rest-argument (lambda-list)
1091 (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
1093 (error "Bad lambda-list"))
1097 (defun lambda-docstring-wrapper (docstring &rest strs)
1100 "var func = " (join strs) ";" *newline*
1101 "func.docstring = '" docstring "';" *newline*
1102 "return func;" *newline*)
1105 (define-compilation lambda (lambda-list &rest body)
1106 (let ((required-arguments (lambda-list-required-arguments lambda-list))
1107 (optional-arguments (lambda-list-optional-arguments lambda-list))
1108 (rest-argument (lambda-list-rest-argument lambda-list))
1110 ;; Get the documentation string for the lambda function
1111 (when (and (stringp (car body))
1112 (not (null (cdr body))))
1113 (setq documentation (car body))
1114 (setq body (cdr body)))
1115 (let ((n-required-arguments (length required-arguments))
1116 (n-optional-arguments (length optional-arguments))
1117 (*environment* (extend-local-env
1118 (append (ensure-list rest-argument)
1120 optional-arguments))))
1121 (lambda-docstring-wrapper
1124 (join (mapcar #'translate-variable
1125 (append required-arguments optional-arguments))
1128 ;; Check number of arguments
1130 (if required-arguments
1131 (concat "if (arguments.length < " (integer-to-string n-required-arguments)
1132 ") throw 'too few arguments';" *newline*)
1134 (if (not rest-argument)
1135 (concat "if (arguments.length > "
1136 (integer-to-string (+ n-required-arguments n-optional-arguments))
1137 ") throw 'too many arguments';" *newline*)
1139 ;; Optional arguments
1140 (if optional-arguments
1141 (concat "switch(arguments.length){" *newline*
1142 (let ((optional-and-defaults
1143 (lambda-list-optional-arguments-with-default lambda-list))
1147 (while (< idx n-optional-arguments)
1148 (let ((arg (nth idx optional-and-defaults)))
1149 (push (concat "case "
1150 (integer-to-string (+ idx n-required-arguments)) ":" *newline*
1151 (translate-variable (car arg))
1153 (ls-compile (cadr arg))
1157 (push (concat "default: break;" *newline*) cases)
1158 (join (reverse cases))))
1161 ;; &rest/&body argument
1163 (let ((js!rest (translate-variable rest-argument)))
1164 (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
1165 "for (var i = arguments.length-1; i>="
1166 (integer-to-string (+ n-required-arguments n-optional-arguments))
1168 (indent js!rest " = "
1169 "{car: arguments[i], cdr: ") js!rest "};"
1173 (ls-compile-block body t)) *newline*
1176 (define-compilation setq (var val)
1177 (let ((b (lookup-in-lexenv var *environment* 'variable)))
1178 (if (eq (binding-type b) 'lexical-variable)
1179 (concat (binding-value b) " = " (ls-compile val))
1180 (ls-compile `(set ',var ,val)))))
1182 ;;; FFI Variable accessors
1183 (define-compilation js-vref (var)
1186 (define-compilation js-vset (var val)
1187 (concat "(" var " = " (ls-compile val) ")"))
1191 (defun escape-string (string)
1194 (size (length string)))
1195 (while (< index size)
1196 (let ((ch (char string index)))
1197 (when (or (char= ch #\") (char= ch #\\))
1198 (setq output (concat output "\\")))
1199 (when (or (char= ch #\newline))
1200 (setq output (concat output "\\"))
1202 (setq output (concat output (string ch))))
1207 (defvar *literal-symbols* nil)
1208 (defvar *literal-counter* 0)
1211 (concat "l" (integer-to-string (incf *literal-counter*))))
1213 (defun literal (sexp &optional recursive)
1215 ((integerp sexp) (integer-to-string sexp))
1216 ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1218 (or (cdr (assoc sexp *literal-symbols*))
1220 (s #+common-lisp (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1221 #+ecmalisp (ls-compile
1222 `(intern ,(symbol-name sexp)
1223 ,(package-name (symbol-package sexp))))))
1224 (push (cons sexp v) *literal-symbols*)
1225 (toplevel-compilation (concat "var " v " = " s))
1228 (let ((c (concat "{car: " (literal (car sexp) t) ", "
1229 "cdr: " (literal (cdr sexp) t) "}")))
1233 (toplevel-compilation (concat "var " v " = " c))
1236 (let ((elements (vector-to-list sexp)))
1237 (let ((c (concat "[" (join (mapcar #'literal elements) ", ") "]")))
1241 (toplevel-compilation (concat "var " v " = " c))
1244 (define-compilation quote (sexp)
1247 (define-compilation %while (pred &rest body)
1249 "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1250 (indent (ls-compile-block body))
1252 "return " (ls-compile nil) ";" *newline*))
1254 (define-compilation function (x)
1256 ((and (listp x) (eq (car x) 'lambda))
1259 (ls-compile `(symbol-function ',x)))))
1261 (define-compilation eval-when-compile (&rest body)
1262 (eval (cons 'progn body))
1265 (defmacro define-transformation (name args form)
1266 `(define-compilation ,name ,args
1267 (ls-compile ,form)))
1269 (define-compilation progn (&rest body)
1270 (js!selfcall (ls-compile-block body t)))
1272 (defun special-variable-p (x)
1273 (claimp x 'variable 'special))
1275 ;;; Wrap CODE to restore the symbol values of the dynamic
1276 ;;; bindings. BINDINGS is a list of pairs of the form
1277 ;;; (SYMBOL . PLACE), where PLACE is a Javascript variable
1278 ;;; name to initialize the symbol value and where to stored
1280 (defun let-binding-wrapper (bindings body)
1281 (when (null bindings)
1282 (return-from let-binding-wrapper body))
1285 (indent "var tmp;" *newline*
1288 (let ((s (ls-compile `(quote ,(car b)))))
1289 (concat "tmp = " s ".value;" *newline*
1290 s ".value = " (cdr b) ";" *newline*
1291 (cdr b) " = tmp;" *newline*)))
1295 "finally {" *newline*
1297 (mapconcat (lambda (b)
1298 (let ((s (ls-compile `(quote ,(car b)))))
1299 (concat s ".value" " = " (cdr b) ";" *newline*)))
1303 (define-compilation let (bindings &rest body)
1304 (let ((bindings (mapcar #'ensure-list bindings)))
1305 (let ((variables (mapcar #'first bindings)))
1306 (let ((cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
1307 (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
1309 (concat "(function("
1310 (join (mapcar (lambda (x)
1311 (if (special-variable-p x)
1312 (let ((v (gvarname x)))
1313 (push (cons x v) dynamic-bindings)
1315 (translate-variable x)))
1319 (let ((body (ls-compile-block body t)))
1320 (indent (let-binding-wrapper dynamic-bindings body)))
1321 "})(" (join cvalues ",") ")")))))
1324 ;;; Return the code to initialize BINDING, and push it extending the
1325 ;;; current lexical environment if the variable is special.
1326 (defun let*-initialize-value (binding)
1327 (let ((var (first binding))
1328 (value (second binding)))
1329 (if (special-variable-p var)
1330 (concat (ls-compile `(setq ,var ,value)) ";" *newline*)
1331 (let ((v (gvarname var)))
1332 (let ((b (make-binding var 'variable v)))
1333 (prog1 (concat "var " v " = " (ls-compile value) ";" *newline*)
1334 (push-to-lexenv b *environment* 'variable)))))))
1336 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
1337 ;;; DOES NOT generate code to initialize the value of the symbols,
1338 ;;; unlike let-binding-wrapper.
1339 (defun let*-binding-wrapper (symbols body)
1340 (when (null symbols)
1341 (return-from let*-binding-wrapper body))
1342 (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
1343 (remove-if-not #'special-variable-p symbols))))
1347 (mapconcat (lambda (b)
1348 (let ((s (ls-compile `(quote ,(car b)))))
1349 (concat "var " (cdr b) " = " s ".value;" *newline*)))
1353 "finally {" *newline*
1355 (mapconcat (lambda (b)
1356 (let ((s (ls-compile `(quote ,(car b)))))
1357 (concat s ".value" " = " (cdr b) ";" *newline*)))
1362 (define-compilation let* (bindings &rest body)
1363 (let ((bindings (mapcar #'ensure-list bindings))
1364 (*environment* (copy-lexenv *environment*)))
1366 (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
1367 (body (concat (mapconcat #'let*-initialize-value bindings)
1368 (ls-compile-block body t))))
1369 (let*-binding-wrapper specials body)))))
1372 (defvar *block-counter* 0)
1374 (define-compilation block (name &rest body)
1375 (let ((tr (integer-to-string (incf *block-counter*))))
1376 (let ((b (make-binding name 'block tr)))
1379 (let ((*environment* (extend-lexenv (list b) *environment* 'block)))
1380 (indent "return " (ls-compile `(progn ,@body)) ";" *newline*))
1382 "catch (cf){" *newline*
1383 " if (cf.type == 'block' && cf.id == " tr ")" *newline*
1384 " return cf.value;" *newline*
1386 " throw cf;" *newline*
1389 (define-compilation return-from (name &optional value)
1390 (let ((b (lookup-in-lexenv name *environment* 'block)))
1395 "id: " (binding-value b) ", "
1396 "value: " (ls-compile value) ", "
1397 "message: 'Return from unknown block " (symbol-name name) ".'"
1399 (error (concat "Unknown block `" (symbol-name name) "'.")))))
1402 (define-compilation catch (id &rest body)
1404 "var id = " (ls-compile id) ";" *newline*
1406 (indent "return " (ls-compile `(progn ,@body))
1409 "catch (cf){" *newline*
1410 " if (cf.type == 'catch' && cf.id == id)" *newline*
1411 " return cf.value;" *newline*
1413 " throw cf;" *newline*
1416 (define-compilation throw (id value)
1420 "id: " (ls-compile id) ", "
1421 "value: " (ls-compile value) ", "
1422 "message: 'Throw uncatched.'"
1426 (defvar *tagbody-counter* 0)
1427 (defvar *go-tag-counter* 0)
1430 (or (integerp x) (symbolp x)))
1432 (defun declare-tagbody-tags (tbidx body)
1434 (mapcar (lambda (label)
1435 (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1436 (make-binding label 'gotag (list tbidx tagidx))))
1437 (remove-if-not #'go-tag-p body))))
1438 (extend-lexenv bindings *environment* 'gotag)))
1440 (define-compilation tagbody (&rest body)
1441 ;; Ignore the tagbody if it does not contain any go-tag. We do this
1442 ;; because 1) it is easy and 2) many built-in forms expand to a
1443 ;; implicit tagbody, so we save some space.
1444 (unless (some #'go-tag-p body)
1445 (return-from tagbody (ls-compile `(progn ,@body nil))))
1446 ;; The translation assumes the first form in BODY is a label
1447 (unless (go-tag-p (car body))
1448 (push (gensym "START") body))
1449 ;; Tagbody compilation
1450 (let ((tbidx (integer-to-string *tagbody-counter*)))
1451 (let ((*environment* (declare-tagbody-tags tbidx body))
1453 (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1454 (setq initag (second (binding-value b))))
1456 "var tagbody_" tbidx " = " initag ";" *newline*
1458 "while (true) {" *newline*
1459 (indent "try {" *newline*
1460 (indent (let ((content ""))
1461 (concat "switch(tagbody_" tbidx "){" *newline*
1462 "case " initag ":" *newline*
1463 (dolist (form (cdr body) content)
1465 (if (not (go-tag-p form))
1466 (indent (ls-compile form) ";" *newline*)
1467 (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1468 (concat "case " (second (binding-value b)) ":" *newline*)))))
1469 "default:" *newline*
1470 " break tbloop;" *newline*
1473 "catch (jump) {" *newline*
1474 " if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1475 " tagbody_" tbidx " = jump.label;" *newline*
1477 " throw(jump);" *newline*
1480 "return " (ls-compile nil) ";" *newline*))))
1482 (define-compilation go (label)
1483 (let ((b (lookup-in-lexenv label *environment* 'gotag))
1485 ((symbolp label) (symbol-name label))
1486 ((integerp label) (integer-to-string label)))))
1491 "id: " (first (binding-value b)) ", "
1492 "label: " (second (binding-value b)) ", "
1493 "message: 'Attempt to GO to non-existing tag " n "'"
1495 (error (concat "Unknown tag `" n "'.")))))
1498 (define-compilation unwind-protect (form &rest clean-up)
1500 "var ret = " (ls-compile nil) ";" *newline*
1502 (indent "ret = " (ls-compile form) ";" *newline*)
1503 "} finally {" *newline*
1504 (indent (ls-compile-block clean-up))
1506 "return ret;" *newline*))
1509 ;;; A little backquote implementation without optimizations of any
1510 ;;; kind for ecmalisp.
1511 (defun backquote-expand-1 (form)
1517 ((eq (car form) 'unquote)
1519 ((eq (car form) 'backquote)
1520 (backquote-expand-1 (backquote-expand-1 (cadr form))))
1525 ((and (listp s) (eq (car s) 'unquote))
1526 (list 'list (cadr s)))
1527 ((and (listp s) (eq (car s) 'unquote-splicing))
1530 (list 'list (backquote-expand-1 s)))))
1533 (defun backquote-expand (form)
1534 (if (and (listp form) (eq (car form) 'backquote))
1535 (backquote-expand-1 (cadr form))
1538 (defmacro backquote (form)
1539 (backquote-expand-1 form))
1541 (define-transformation backquote (form)
1542 (backquote-expand-1 form))
1546 (defvar *builtins* nil)
1548 (defmacro define-raw-builtin (name args &body body)
1549 ;; Creates a new primitive function `name' with parameters args and
1550 ;; @body. The body can access to the local environment through the
1551 ;; variable *ENVIRONMENT*.
1552 `(push (list ',name (lambda ,args (block ,name ,@body)))
1555 (defmacro define-builtin (name args &body body)
1557 (define-raw-builtin ,name ,args
1558 (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1561 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1562 (defmacro type-check (decls &body body)
1564 ,@(mapcar (lambda (decl)
1565 `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1567 ,@(mapcar (lambda (decl)
1568 `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1569 (indent "throw 'The value ' + "
1571 " + ' is not a type "
1576 (concat "return " (progn ,@body) ";" *newline*)))
1578 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
1579 ;;; a variable which holds a list of forms. It will compile them and
1580 ;;; store the result in some Javascript variables. BODY is evaluated
1581 ;;; with ARGS bound to the list of these variables to generate the
1582 ;;; code which performs the transformation on these variables.
1584 (defun variable-arity-call (args function)
1585 (unless (consp args)
1586 (error "ARGS must be a non-empty list"))
1591 (let ((v (concat "x" (integer-to-string (incf counter)))))
1594 (concat "var " v " = " (ls-compile x) ";" *newline*
1595 "if (typeof " v " !== 'number') throw 'Not a number!';"
1597 (js!selfcall prelude (funcall function (reverse variables)))))
1600 (defmacro variable-arity (args &body body)
1601 (unless (symbolp args)
1602 (error "Bad usage of VARIABLE-ARITY, yo must pass a symbol"))
1603 `(variable-arity-call ,args
1605 (concat "return " ,@body ";" *newline*))))
1608 (defun num-op-num (x op y)
1609 (type-check (("x" "number" x) ("y" "number" y))
1610 (concat "x" op "y")))
1612 (define-raw-builtin + (&rest numbers)
1615 (variable-arity numbers
1616 (join numbers "+"))))
1618 (define-raw-builtin - (x &rest others)
1619 (let ((args (cons x others)))
1620 (variable-arity args
1622 (concat "-" (car args))
1626 (define-builtin * (x y) (num-op-num x "*" y))
1627 (define-builtin / (x y) (num-op-num x "/" y))
1629 (define-builtin mod (x y) (num-op-num x "%" y))
1631 (define-builtin < (x y) (js!bool (num-op-num x "<" y)))
1632 (define-builtin > (x y) (js!bool (num-op-num x ">" y)))
1633 (define-builtin = (x y) (js!bool (num-op-num x "==" y)))
1634 (define-builtin <= (x y) (js!bool (num-op-num x "<=" y)))
1635 (define-builtin >= (x y) (js!bool (num-op-num x ">=" y)))
1637 (define-builtin numberp (x)
1638 (js!bool (concat "(typeof (" x ") == \"number\")")))
1640 (define-builtin floor (x)
1641 (type-check (("x" "number" x))
1644 (define-builtin cons (x y)
1645 (concat "({car: " x ", cdr: " y "})"))
1647 (define-builtin consp (x)
1650 "var tmp = " x ";" *newline*
1651 "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1653 (define-builtin car (x)
1655 "var tmp = " x ";" *newline*
1656 "return tmp === " (ls-compile nil)
1657 "? " (ls-compile nil)
1658 ": tmp.car;" *newline*))
1660 (define-builtin cdr (x)
1662 "var tmp = " x ";" *newline*
1663 "return tmp === " (ls-compile nil) "? "
1665 ": tmp.cdr;" *newline*))
1667 (define-builtin setcar (x new)
1668 (type-check (("x" "object" x))
1669 (concat "(x.car = " new ")")))
1671 (define-builtin setcdr (x new)
1672 (type-check (("x" "object" x))
1673 (concat "(x.cdr = " new ")")))
1675 (define-builtin symbolp (x)
1678 "var tmp = " x ";" *newline*
1679 "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1681 (define-builtin make-symbol (name)
1682 (type-check (("name" "string" name))
1685 (define-builtin symbol-name (x)
1686 (concat "(" x ").name"))
1688 (define-builtin set (symbol value)
1689 (concat "(" symbol ").value = " value))
1691 (define-builtin fset (symbol value)
1692 (concat "(" symbol ").function = " value))
1694 (define-builtin boundp (x)
1695 (js!bool (concat "(" x ".value !== undefined)")))
1697 (define-builtin symbol-value (x)
1699 "var symbol = " x ";" *newline*
1700 "var value = symbol.value;" *newline*
1701 "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1702 "return value;" *newline*))
1704 (define-builtin symbol-function (x)
1706 "var symbol = " x ";" *newline*
1707 "var func = symbol.function;" *newline*
1708 "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1709 "return func;" *newline*))
1711 (define-builtin symbol-plist (x)
1712 (concat "((" x ").plist || " (ls-compile nil) ")"))
1714 (define-builtin lambda-code (x)
1715 (concat "(" x ").toString()"))
1718 (define-builtin eq (x y) (js!bool (concat "(" x " === " y ")")))
1719 (define-builtin equal (x y) (js!bool (concat "(" x " == " y ")")))
1721 (define-builtin char-to-string (x)
1722 (type-check (("x" "number" x))
1723 "String.fromCharCode(x)"))
1725 (define-builtin stringp (x)
1726 (js!bool (concat "(typeof(" x ") == \"string\")")))
1728 (define-builtin string-upcase (x)
1729 (type-check (("x" "string" x))
1732 (define-builtin string-length (x)
1733 (type-check (("x" "string" x))
1736 (define-raw-builtin slice (string a &optional b)
1738 "var str = " (ls-compile string) ";" *newline*
1739 "var a = " (ls-compile a) ";" *newline*
1742 (concat "b = " (ls-compile b) ";" *newline*)
1744 "return str.slice(a,b);" *newline*))
1746 (define-builtin char (string index)
1747 (type-check (("string" "string" string)
1748 ("index" "number" index))
1749 "string.charCodeAt(index)"))
1751 (define-builtin concat-two (string1 string2)
1752 (type-check (("string1" "string" string1)
1753 ("string2" "string" string2))
1754 "string1.concat(string2)"))
1756 (define-raw-builtin funcall (func &rest args)
1757 (concat "(" (ls-compile func) ")("
1758 (join (mapcar #'ls-compile args)
1762 (define-raw-builtin apply (func &rest args)
1764 (concat "(" (ls-compile func) ")()")
1765 (let ((args (butlast args))
1766 (last (car (last args))))
1768 "var f = " (ls-compile func) ";" *newline*
1769 "var args = [" (join (mapcar #'ls-compile args)
1772 "var tail = (" (ls-compile last) ");" *newline*
1773 "while (tail != " (ls-compile nil) "){" *newline*
1774 " args.push(tail.car);" *newline*
1775 " tail = tail.cdr;" *newline*
1777 "return f.apply(this, args);" *newline*))))
1779 (define-builtin js-eval (string)
1780 (type-check (("string" "string" string))
1781 "eval.apply(window, [string])"))
1783 (define-builtin error (string)
1784 (js!selfcall "throw " string ";" *newline*))
1786 (define-builtin new () "{}")
1788 (define-builtin objectp (x)
1789 (js!bool (concat "(typeof (" x ") === 'object')")))
1791 (define-builtin oget (object key)
1793 "var tmp = " "(" object ")[" key "];" *newline*
1794 "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1796 (define-builtin oset (object key value)
1797 (concat "((" object ")[" key "] = " value ")"))
1799 (define-builtin in (key object)
1800 (js!bool (concat "((" key ") in (" object "))")))
1802 (define-builtin functionp (x)
1803 (js!bool (concat "(typeof " x " == 'function')")))
1805 (define-builtin write-string (x)
1806 (type-check (("x" "string" x))
1809 (define-builtin make-array (n)
1811 "var r = [];" *newline*
1812 "for (var i = 0; i < " n "; i++)" *newline*
1813 (indent "r.push(" (ls-compile nil) ");" *newline*)
1814 "return r;" *newline*))
1816 (define-builtin arrayp (x)
1819 "var x = " x ";" *newline*
1820 "return typeof x === 'object' && 'length' in x;")))
1822 (define-builtin aref (array n)
1824 "var x = " "(" array ")[" n "];" *newline*
1825 "if (x === undefined) throw 'Out of range';" *newline*
1826 "return x;" *newline*))
1828 (define-builtin aset (array n value)
1830 "var x = " array ";" *newline*
1831 "var i = " n ";" *newline*
1832 "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
1833 "return x[i] = " value ";" *newline*))
1838 (let ((b (lookup-in-lexenv x *environment* 'function)))
1839 (and (eq (binding-type b) 'macro)
1842 (defun ls-macroexpand-1 (form)
1843 (let ((macro-binding (macro (car form))))
1845 (let ((expander (binding-value macro-binding)))
1846 (when (listp expander)
1847 (let ((compiled (eval expander)))
1848 ;; The list representation are useful while
1849 ;; bootstrapping, as we can dump the definition of the
1850 ;; macros easily, but they are slow because we have to
1851 ;; evaluate them and compile them now and again. So, let
1852 ;; us replace the list representation version of the
1853 ;; function with the compiled one.
1855 #+ecmalisp (set-binding-value macro-binding compiled)
1856 (setq expander compiled)))
1857 (apply expander (cdr form)))
1860 (defun compile-funcall (function args)
1861 (if (and (symbolp function)
1862 (claimp function 'function 'non-overridable))
1863 (concat (ls-compile `',function) ".function("
1864 (join (mapcar #'ls-compile args)
1867 (concat (ls-compile `#',function) "("
1868 (join (mapcar #'ls-compile args)
1872 (defun ls-compile-block (sexps &optional return-last-p)
1874 (concat (ls-compile-block (butlast sexps))
1875 "return " (ls-compile (car (last sexps))) ";")
1877 (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
1878 (concat ";" *newline*))))
1880 (defun ls-compile (sexp)
1883 (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1885 ((and b (not (member 'special (binding-declarations b))))
1887 ((or (keywordp sexp)
1888 (member 'constant (binding-declarations b)))
1889 (concat (ls-compile `',sexp) ".value"))
1891 (ls-compile `(symbol-value ',sexp))))))
1892 ((integerp sexp) (integer-to-string sexp))
1893 ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1894 ((arrayp sexp) (literal sexp))
1896 (let ((name (car sexp))
1900 ((assoc name *compilations*)
1901 (let ((comp (second (assoc name *compilations*))))
1903 ;; Built-in functions
1904 ((and (assoc name *builtins*)
1905 (not (claimp name 'function 'notinline)))
1906 (let ((comp (second (assoc name *builtins*))))
1910 (ls-compile (ls-macroexpand-1 sexp))
1911 (compile-funcall name args))))))
1913 (error "How should I compile this?"))))
1915 (defun ls-compile-toplevel (sexp)
1916 (let ((*toplevel-compilations* nil))
1918 ((and (consp sexp) (eq (car sexp) 'progn))
1919 (let ((subs (mapcar #'ls-compile-toplevel (cdr sexp))))
1920 (join (remove-if #'null-or-empty-p subs))))
1922 (let ((code (ls-compile sexp)))
1923 (concat (join-trailing (get-toplevel-compilations)
1924 (concat ";" *newline*))
1926 (concat code ";" *newline*)
1930 ;;; Once we have the compiler, we define the runtime environment and
1931 ;;; interactive development (eval), which works calling the compiler
1932 ;;; and evaluating the Javascript result globally.
1936 (defmacro with-compilation-unit (&body body)
1939 (setq *compilation-unit-checks* nil)
1941 (dolist (check *compilation-unit-checks*)
1946 (with-compilation-unit
1947 (ls-compile-toplevel x))))
1950 (export '(&rest &optional &body * *gensym-counter* *package* + - / 1+ 1- < <= =
1951 = > >= and append apply aref arrayp aset assoc atom block boundp
1952 boundp butlast caar cadddr caddr cadr car car case catch cdar cdddr
1953 cddr cdr cdr char char-code char= code-char cond cons consp copy-list
1954 decf declaim defparameter defun defvar digit-char-p disassemble
1955 documentation dolist dotimes ecase eq eql equal error eval every
1956 export fdefinition find-package find-symbol first fourth fset funcall
1957 function functionp gensym go identity if in-package incf integerp
1958 integerp intern keywordp lambda last length let let* list-all-packages
1959 list listp make-array make-package make-symbol mapcar member minusp
1960 mod nil not nth nthcdr null numberp or package-name package-use-list
1961 packagep plusp prin1-to-string print proclaim prog1 prog2 pron push
1962 quote remove remove-if remove-if-not return return-from revappend
1963 reverse second set setq some string-upcase string string= stringp
1964 subseq symbol-function symbol-name symbol-package symbol-plist
1965 symbol-value symbolp t tagbody third throw truncate unless
1966 unwind-protect variable warn when write-line write-string zerop))
1968 (setq *package* *user-package*)
1970 (js-eval "var lisp")
1971 (js-vset "lisp" (new))
1972 (js-vset "lisp.read" #'ls-read-from-string)
1973 (js-vset "lisp.print" #'prin1-to-string)
1974 (js-vset "lisp.eval" #'eval)
1975 (js-vset "lisp.compile" #'ls-compile-toplevel)
1976 (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
1977 (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str))))
1979 ;; Set the initial global environment to be equal to the host global
1980 ;; environment at this point of the compilation.
1982 (toplevel-compilation
1985 ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
1987 (setq *literal-symbols* ',*literal-symbols*)
1988 (setq *environment* ',*environment*)
1989 (setq *variable-counter* ,*variable-counter*)
1990 (setq *gensym-counter* ,*gensym-counter*)
1991 (setq *block-counter* ,*block-counter*)))))
1994 (toplevel-compilation
1996 `(setq *literal-counter* ,*literal-counter*)))))
1999 ;;; Finally, we provide a couple of functions to easily bootstrap
2000 ;;; this. It just calls the compiler with this file as input.
2004 (defun read-whole-file (filename)
2005 (with-open-file (in filename)
2006 (let ((seq (make-array (file-length in) :element-type 'character)))
2007 (read-sequence seq in)
2010 (defun ls-compile-file (filename output)
2011 (setq *compilation-unit-checks* nil)
2012 (with-open-file (out output :direction :output :if-exists :supersede)
2013 (let* ((source (read-whole-file filename))
2014 (in (make-string-stream source)))
2016 for x = (ls-read in)
2018 for compilation = (ls-compile-toplevel x)
2019 when (plusp (length compilation))
2020 do (write-string compilation out))
2021 (dolist (check *compilation-unit-checks*)
2023 (setq *compilation-unit-checks* nil))))
2026 (setq *environment* (make-lexenv))
2027 (setq *literal-symbols* nil)
2028 (setq *variable-counter* 0
2032 (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))