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
30 (lambda (name args &rest body)
32 (%compile-defmacro ',name
34 (lambda ,(mapcar #'(lambda (x)
41 (defmacro declaim (&rest decls)
43 ,@(mapcar (lambda (decl) `(!proclaim ',decl)) decls)))
45 (declaim (constant nil t) (special t nil))
50 (defmacro lambda (args &body body)
51 `(function (lambda ,args ,@body)))
53 (defmacro when (condition &body body)
54 `(if ,condition (progn ,@body) nil))
56 (defmacro unless (condition &body body)
57 `(if ,condition nil (progn ,@body)))
59 (defmacro defvar (name value &optional docstring)
61 (declaim (special ,name))
62 (unless (boundp ',name) (setq ,name ,value))
63 ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
66 (defmacro defparameter (name value &optional docstring)
69 ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
72 (defmacro named-lambda (name args &rest body)
73 (let ((x (gensym "FN")))
74 `(let ((,x (lambda ,args ,@body)))
75 (oset ,x "fname" ,name)
78 (defmacro defun (name args &rest body)
81 (named-lambda ,(symbol-name name) ,args
82 ,@(if (and (stringp (car body)) (not (null (cdr body))))
83 `(,(car body) (block ,name ,@(cdr body)))
84 `((block ,name ,@body)))))
90 (defmacro return (&optional value)
91 `(return-from nil ,value))
93 (defmacro while (condition &body body)
94 `(block nil (%while ,condition ,@body)))
96 (defvar *gensym-counter* 0)
97 (defun gensym (&optional (prefix "G"))
98 (setq *gensym-counter* (+ *gensym-counter* 1))
99 (make-symbol (concat-two prefix (integer-to-string *gensym-counter*))))
105 (defun = (x y) (= x y))
106 (defun * (x y) (* x y))
107 (defun / (x y) (/ x y))
108 (defun 1+ (x) (+ x 1))
109 (defun 1- (x) (- x 1))
110 (defun zerop (x) (= x 0))
111 (defun truncate (x y) (floor (/ x y)))
113 (defun eql (x y) (eq x y))
115 (defun not (x) (if x nil t))
117 (defun cons (x y ) (cons x y))
118 (defun consp (x) (consp x))
121 "Return the CAR part of a cons, or NIL if X is null."
124 (defun cdr (x) (cdr x))
125 (defun caar (x) (car (car x)))
126 (defun cadr (x) (car (cdr x)))
127 (defun cdar (x) (cdr (car x)))
128 (defun cddr (x) (cdr (cdr x)))
129 (defun caddr (x) (car (cdr (cdr x))))
130 (defun cdddr (x) (cdr (cdr (cdr x))))
131 (defun cadddr (x) (car (cdr (cdr (cdr x)))))
132 (defun first (x) (car x))
133 (defun second (x) (cadr x))
134 (defun third (x) (caddr x))
135 (defun fourth (x) (cadddr x))
137 (defun list (&rest args) args)
143 (defmacro incf (x &optional (delta 1))
144 `(setq ,x (+ ,x ,delta)))
146 (defmacro decf (x &optional (delta 1))
147 `(setq ,x (- ,x ,delta)))
149 (defmacro push (x place)
150 `(setq ,place (cons ,x ,place)))
152 (defmacro dolist (iter &body body)
153 (let ((var (first iter))
156 (let ((,g!list ,(second iter))
159 (setq ,var (car ,g!list))
161 (setq ,g!list (cdr ,g!list)))
164 (defmacro dotimes (iter &body body)
165 (let ((g!to (gensym))
168 (result (third iter)))
172 (%while (< ,var ,g!to)
177 (defmacro cond (&rest clausules)
180 (if (eq (caar clausules) t)
181 `(progn ,@(cdar clausules))
182 `(if ,(caar clausules)
183 (progn ,@(cdar clausules))
184 (cond ,@(cdr clausules))))))
186 (defmacro case (form &rest clausules)
187 (let ((!form (gensym)))
188 `(let ((,!form ,form))
190 ,@(mapcar (lambda (clausule)
191 (if (eq (car clausule) t)
193 `((eql ,!form ',(car clausule))
197 (defmacro ecase (form &rest clausules)
202 (error "ECASE expression failed."))))))
204 (defmacro and (&rest forms)
215 (defmacro or (&rest forms)
223 `(let ((,g ,(car forms)))
224 (if ,g ,g (or ,@(cdr forms))))))))
226 (defmacro prog1 (form &body body)
227 (let ((value (gensym)))
228 `(let ((,value ,form))
232 (defmacro prog2 (form1 result &body body)
233 `(prog1 (progn ,form1 ,result) ,@body)))
236 ;;; This couple of helper functions will be defined in both Common
237 ;;; Lisp and in Ecmalisp.
238 (defun ensure-list (x)
243 (defun !reduce (func list initial)
248 (funcall func initial (car list)))))
250 ;;; Go on growing the Lisp language in Ecmalisp, with more high
251 ;;; level utilities as well as correct versions of other
255 (defun + (&rest args)
260 (defun - (x &rest others)
267 (defun append-two (list1 list2)
271 (append (cdr list1) list2))))
273 (defun append (&rest lists)
274 (!reduce #'append-two lists '()))
276 (defun revappend (list1 list2)
278 (push (car list1) list2)
279 (setq list1 (cdr list1)))
282 (defun reverse (list)
283 (revappend list '()))
285 (defmacro psetq (&rest pairs)
286 (let ( ;; For each pair, we store here a list of the form
287 ;; (VARIABLE GENSYM VALUE).
291 ((null pairs) (return))
293 (error "Odd paris in PSETQ"))
295 (let ((variable (car pairs))
296 (value (cadr pairs)))
297 (push `(,variable ,(gensym) ,value) assignments)
298 (setq pairs (cddr pairs))))))
299 (setq assignments (reverse assignments))
301 `(let ,(mapcar #'cdr assignments)
302 (setq ,@(!reduce #'append (mapcar #'butlast assignments) '())))))
304 (defmacro do (varlist endlist &body body)
306 (let ,(mapcar (lambda (x) (list (first x) (second x))) varlist)
309 (return (progn ,(cdr endlist))))
314 (and (consp (cddr v))
315 (list (first v) (third v))))
318 (defmacro do* (varlist endlist &body body)
320 (let* ,(mapcar (lambda (x) (list (first x) (second x))) varlist)
323 (return (progn ,(cdr endlist))))
328 (and (consp (cddr v))
329 (list (first v) (third v))))
332 (defun list-length (list)
334 (while (not (null list))
336 (setq list (cdr list)))
348 (defun concat-two (s1 s2)
351 (defun mapcar (func list)
354 (cons (funcall func (car list))
355 (mapcar func (cdr list)))))
357 (defun identity (x) x)
360 (mapcar #'identity x))
362 (defun code-char (x) x)
363 (defun char-code (x) x)
364 (defun char= (x y) (= x y))
367 (and (numberp x) (= (floor x) x)))
369 (defun plusp (x) (< 0 x))
370 (defun minusp (x) (< x 0))
373 (or (consp x) (null x)))
375 (defun nthcdr (n list)
376 (while (and (plusp n) list)
378 (setq list (cdr list)))
382 (car (nthcdr n list)))
385 (while (consp (cdr x))
391 (cons (car x) (butlast (cdr x)))))
393 (defun member (x list)
395 (when (eql x (car list))
397 (setq list (cdr list))))
399 (defun remove (x list)
404 (remove x (cdr list)))
406 (cons (car list) (remove x (cdr list))))))
408 (defun remove-if (func list)
412 ((funcall func (car list))
413 (remove-if func (cdr list)))
415 (cons (car list) (remove-if func (cdr list))))))
417 (defun remove-if-not (func list)
421 ((funcall func (car list))
422 (cons (car list) (remove-if-not func (cdr list))))
424 (remove-if-not func (cdr list)))))
426 (defun digit-char-p (x)
427 (if (and (<= #\0 x) (<= x #\9))
431 (defun subseq (seq a &optional b)
438 (error "Unsupported argument."))))
440 (defun parse-integer (string)
443 (size (length string)))
444 (while (< index size)
445 (setq value (+ (* value 10) (digit-char-p (char string index))))
449 (defun some (function seq)
454 (while (< index size)
455 (when (funcall function (char seq index))
456 (return-from some t))
461 (when (funcall function x)
464 (error "Unknown sequence."))))
466 (defun every (function seq)
471 (while (< index size)
472 (unless (funcall function (char seq index))
473 (return-from every nil))
478 (unless (funcall function x)
481 (error "Unknown sequence."))))
483 (defun assoc (x alist)
485 (if (eql x (caar alist))
487 (setq alist (cdr alist))))
491 (cond ((stringp x) x)
492 ((symbolp x) (symbol-name x))
493 (t (char-to-string x))))
495 (defun string= (s1 s2)
498 (defun fdefinition (x)
505 (error "Invalid function"))))
507 (defun disassemble (function)
508 (write-line (lambda-code (fdefinition function)))
511 (defun documentation (x type)
512 "Return the documentation of X. TYPE must be the symbol VARIABLE or FUNCTION."
515 (let ((func (fdefinition x)))
516 (oget func "docstring")))
519 (error "Wrong argument type! it should be a symbol"))
524 (defvar *package-list* nil)
526 (defun list-all-packages ()
529 (defun make-package (name &optional use)
530 (let ((package (new))
531 (use (mapcar #'find-package-or-fail use)))
532 (oset package "packageName" name)
533 (oset package "symbols" (new))
534 (oset package "exports" (new))
535 (oset package "use" use)
536 (push package *package-list*)
540 (and (objectp x) (in "symbols" x)))
542 (defun find-package (package-designator)
543 (when (packagep package-designator)
544 (return-from find-package package-designator))
545 (let ((name (string package-designator)))
546 (dolist (package *package-list*)
547 (when (string= (package-name package) name)
550 (defun find-package-or-fail (package-designator)
551 (or (find-package package-designator)
552 (error "Package unknown.")))
554 (defun package-name (package-designator)
555 (let ((package (find-package-or-fail package-designator)))
556 (oget package "packageName")))
558 (defun %package-symbols (package-designator)
559 (let ((package (find-package-or-fail package-designator)))
560 (oget package "symbols")))
562 (defun package-use-list (package-designator)
563 (let ((package (find-package-or-fail package-designator)))
564 (oget package "use")))
566 (defun %package-external-symbols (package-designator)
567 (let ((package (find-package-or-fail package-designator)))
568 (oget package "exports")))
570 (defvar *common-lisp-package*
573 (defvar *user-package*
574 (make-package "CL-USER" (list *common-lisp-package*)))
576 (defvar *keyword-package*
577 (make-package "KEYWORD"))
580 (and (symbolp x) (eq (symbol-package x) *keyword-package*)))
582 (defvar *package* *common-lisp-package*)
584 (defmacro in-package (package-designator)
586 (setq *package* (find-package-or-fail ,package-designator))))
588 ;; This function is used internally to initialize the CL package
589 ;; with the symbols built during bootstrap.
590 (defun %intern-symbol (symbol)
591 (let ((symbols (%package-symbols *common-lisp-package*)))
592 (oset symbol "package" *common-lisp-package*)
593 (oset symbols (symbol-name symbol) symbol)))
595 (defun %find-symbol (name package)
596 (let ((package (find-package-or-fail package)))
597 (let ((symbols (%package-symbols package)))
598 (if (in name symbols)
599 (cons (oget symbols name) t)
600 (dolist (used (package-use-list package) (cons nil nil))
601 (let ((exports (%package-external-symbols used)))
602 (when (in name exports)
603 (return-from %find-symbol
604 (cons (oget exports name) t)))))))))
606 (defun find-symbol (name &optional (package *package*))
607 (car (%find-symbol name package)))
609 (defun intern (name &optional (package *package*))
610 (let ((package (find-package-or-fail package)))
611 (let ((result (%find-symbol name package)))
614 (let ((symbols (%package-symbols package)))
616 (let ((symbol (make-symbol name)))
617 (oset symbol "package" package)
618 (when (eq package *keyword-package*)
619 (oset symbol "value" symbol)
620 (export (list symbol) package))
621 (oset symbols name symbol)))))))
623 (defun symbol-package (symbol)
624 (unless (symbolp symbol)
625 (error "it is not a symbol"))
626 (oget symbol "package"))
628 (defun export (symbols &optional (package *package*))
629 (let ((exports (%package-external-symbols package)))
630 (dolist (symb symbols t)
631 (oset exports (symbol-name symb) symb))))
633 (defun get-universal-time ()
634 (+ (get-unix-time) 2208988800)))
637 ;;; The compiler offers some primitives and special forms which are
638 ;;; not found in Common Lisp, for instance, while. So, we grow Common
639 ;;; Lisp a bit to it can execute the rest of the file.
642 (defmacro while (condition &body body)
647 (defmacro eval-when-compile (&body body)
648 `(eval-when (:compile-toplevel :load-toplevel :execute)
651 (defun concat-two (s1 s2)
652 (concatenate 'string s1 s2))
654 (defun aset (array idx value)
655 (setf (aref array idx) value)))
657 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
658 ;;; from here, this code will compile on both. We define some helper
659 ;;; functions now for string manipulation and so on. They will be
660 ;;; useful in the compiler, mostly.
662 (defvar *newline* (string (code-char 10)))
664 (defun concat (&rest strs)
665 (!reduce #'concat-two strs ""))
667 (defmacro concatf (variable &body form)
668 `(setq ,variable (concat ,variable (progn ,@form))))
670 ;;; Concatenate a list of strings, with a separator
671 (defun join (list &optional (separator ""))
680 (join (cdr list) separator)))))
682 (defun join-trailing (list &optional (separator ""))
685 (concat (car list) separator (join-trailing (cdr list) separator))))
687 (defun mapconcat (func list)
688 (join (mapcar func list)))
690 (defun vector-to-list (vector)
692 (size (length vector)))
693 (dotimes (i size (reverse list))
694 (push (aref vector i) list))))
696 (defun list-to-vector (list)
697 (let ((v (make-array (length list)))
705 (defun values-list (list)
706 (values-array (list-to-vector list)))
708 (defun values (&rest args)
711 (defmacro multiple-value-bind (variables value-from &body body)
712 `(multiple-value-call (lambda (&optional ,@variables &rest ,(gensym))
716 (defmacro multiple-value-list (value-from)
717 `(multiple-value-call #'list ,value-from)))
720 ;;; Like CONCAT, but prefix each line with four spaces. Two versions
721 ;;; of this function are available, because the Ecmalisp version is
722 ;;; very slow and bootstraping was annoying.
725 (defun indent (&rest string)
726 (let ((input (join string)))
729 (size (length input)))
730 (when (plusp (length input)) (concatf output " "))
731 (while (< index size)
733 (if (and (char= (char input index) #\newline)
735 (not (char= (char input (1+ index)) #\newline)))
736 (concat (string #\newline) " ")
737 (string (char input index)))))
738 (concatf output str))
743 (defun indent (&rest string)
744 (with-output-to-string (*standard-output*)
745 (with-input-from-string (input (join string))
747 for line = (read-line input nil)
749 do (write-string " ")
750 do (write-line line)))))
753 (defun integer-to-string (x)
758 (concat "-" (integer-to-string (- 0 x))))
761 (while (not (zerop x))
762 (push (mod x 10) digits)
763 (setq x (truncate x 10)))
764 (join (mapcar (lambda (d) (string (char "0123456789" d)))
768 ;;; Wrap X with a Javascript code to convert the result from
769 ;;; Javascript generalized booleans to T or NIL.
771 (concat "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
773 ;;; Concatenate the arguments and wrap them with a self-calling
774 ;;; Javascript anonymous function. It is used to make some Javascript
775 ;;; statements valid expressions and provide a private scope as well.
776 ;;; It could be defined as function, but we could do some
777 ;;; preprocessing in the future.
778 (defmacro js!selfcall (&body body)
779 `(concat "(function(){" *newline* (indent ,@body) "})()"))
786 (defun prin1-to-string (form)
789 (if (cdr (%find-symbol (symbol-name form) *package*))
791 (let ((package (symbol-package form))
792 (name (symbol-name form)))
795 ((eq package (find-package "KEYWORD")) "")
796 (t (package-name package)))
798 ((integerp form) (integer-to-string form))
799 ((stringp form) (concat "\"" (escape-string form) "\""))
801 (let ((name (oget form "fname")))
803 (concat "#<FUNCTION " name ">")
804 (concat "#<FUNCTION>"))))
807 (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
808 (let ((last (last form)))
809 (if (null (cdr last))
810 (prin1-to-string (car last))
811 (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
814 (concat "#" (prin1-to-string (vector-to-list form))))
816 (concat "#<PACKAGE " (package-name form) ">"))))
818 (defun write-line (x)
820 (write-string *newline*)
824 (write-string "WARNING: ")
828 (write-line (prin1-to-string x))
834 ;;; The Lisp reader, parse strings and return Lisp objects. The main
835 ;;; entry points are `ls-read' and `ls-read-from-string'.
837 (defun make-string-stream (string)
840 (defun %peek-char (stream)
841 (and (< (cdr stream) (length (car stream)))
842 (char (car stream) (cdr stream))))
844 (defun %read-char (stream)
845 (and (< (cdr stream) (length (car stream)))
846 (prog1 (char (car stream) (cdr stream))
847 (rplacd stream (1+ (cdr stream))))))
849 (defun whitespacep (ch)
850 (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
852 (defun skip-whitespaces (stream)
854 (setq ch (%peek-char stream))
855 (while (and ch (whitespacep ch))
857 (setq ch (%peek-char stream)))))
859 (defun terminalp (ch)
860 (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
862 (defun read-until (stream func)
865 (setq ch (%peek-char stream))
866 (while (and ch (not (funcall func ch)))
867 (setq string (concat string (string ch)))
869 (setq ch (%peek-char stream)))
872 (defun skip-whitespaces-and-comments (stream)
874 (skip-whitespaces stream)
875 (setq ch (%peek-char stream))
876 (while (and ch (char= ch #\;))
877 (read-until stream (lambda (x) (char= x #\newline)))
878 (skip-whitespaces stream)
879 (setq ch (%peek-char stream)))))
881 (defun %read-list (stream)
882 (skip-whitespaces-and-comments stream)
883 (let ((ch (%peek-char stream)))
886 (error "Unspected EOF"))
892 (prog1 (ls-read stream)
893 (skip-whitespaces-and-comments stream)
894 (unless (char= (%read-char stream) #\))
895 (error "')' was expected."))))
897 (cons (ls-read stream) (%read-list stream))))))
899 (defun read-string (stream)
902 (setq ch (%read-char stream))
903 (while (not (eql ch #\"))
905 (error "Unexpected EOF"))
907 (setq ch (%read-char stream)))
908 (setq string (concat string (string ch)))
909 (setq ch (%read-char stream)))
912 (defun read-sharp (stream)
914 (ecase (%read-char stream)
916 (list 'function (ls-read stream)))
917 (#\( (list-to-vector (%read-list stream)))
918 (#\: (make-symbol (string-upcase (read-until stream #'terminalp))))
921 (concat (string (%read-char stream))
922 (read-until stream #'terminalp))))
924 ((string= cname "space") (char-code #\space))
925 ((string= cname "tab") (char-code #\tab))
926 ((string= cname "newline") (char-code #\newline))
927 (t (char-code (char cname 0))))))
929 (let ((feature (read-until stream #'terminalp)))
931 ((string= feature "common-lisp")
932 (ls-read stream) ;ignore
934 ((string= feature "ecmalisp")
937 (error "Unknown reader form.")))))))
939 ;;; Parse a string of the form NAME, PACKAGE:NAME or
940 ;;; PACKAGE::NAME and return the name. If the string is of the
941 ;;; form 1) or 3), but the symbol does not exist, it will be created
942 ;;; and interned in that package.
943 (defun read-symbol (string)
944 (let ((size (length string))
945 package name internalp index)
947 (while (and (< index size)
948 (not (char= (char string index) #\:)))
954 (setq package *package*)
959 (setq package "KEYWORD")
960 (setq package (string-upcase (subseq string 0 index))))
962 (when (char= (char string index) #\:)
965 (setq name (subseq string index))))
966 ;; Canonalize symbol name and package
967 (setq name (string-upcase name))
968 (setq package (find-package package))
969 ;; TODO: PACKAGE:SYMBOL should signal error if SYMBOL is not an
970 ;; external symbol from PACKAGE.
971 (if (or internalp (eq package (find-package "KEYWORD")))
972 (intern name package)
973 (find-symbol name package))))
975 (defvar *eof* (gensym))
976 (defun ls-read (stream)
977 (skip-whitespaces-and-comments stream)
978 (let ((ch (%peek-char stream)))
980 ((or (null ch) (char= ch #\)))
987 (list 'quote (ls-read stream)))
990 (list 'backquote (ls-read stream)))
993 (read-string stream))
996 (if (eql (%peek-char stream) #\@)
997 (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
998 (list 'unquote (ls-read stream))))
1000 (read-sharp stream))
1002 (let ((string (read-until stream #'terminalp)))
1003 (if (every #'digit-char-p string)
1004 (parse-integer string)
1005 (read-symbol string)))))))
1007 (defun ls-read-from-string (string)
1008 (ls-read (make-string-stream string)))
1013 ;;; Translate the Lisp code to Javascript. It will compile the special
1014 ;;; forms. Some primitive functions are compiled as special forms
1015 ;;; too. The respective real functions are defined in the target (see
1016 ;;; the beginning of this file) as well as some primitive functions.
1018 ;;; A Form can return a multiple values object calling VALUES, like
1019 ;;; values(arg1, arg2, ...). It will work in any context, as well as
1020 ;;; returning an individual object. However, if the special variable
1021 ;;; `*multiple-value-p*' is NIL, is granted that only the primary
1022 ;;; value will be used, so we can optimize to avoid the VALUES
1024 (defvar *multiple-value-p* nil)
1027 (defun make-binding (name type value &optional declarations)
1028 (list name type value declarations))
1030 (defun binding-name (b) (first b))
1031 (defun binding-type (b) (second b))
1032 (defun binding-value (b) (third b))
1033 (defun binding-declarations (b) (fourth b))
1035 (defun set-binding-value (b value)
1036 (rplaca (cddr b) value))
1038 (defun set-binding-declarations (b value)
1039 (rplaca (cdddr b) value))
1041 (defun push-binding-declaration (decl b)
1042 (set-binding-declarations b (cons decl (binding-declarations b))))
1045 (defun make-lexenv ()
1046 (list nil nil nil nil))
1048 (defun copy-lexenv (lexenv)
1051 (defun push-to-lexenv (binding lexenv namespace)
1053 (variable (rplaca lexenv (cons binding (car lexenv))))
1054 (function (rplaca (cdr lexenv) (cons binding (cadr lexenv))))
1055 (block (rplaca (cddr lexenv) (cons binding (caddr lexenv))))
1056 (gotag (rplaca (cdddr lexenv) (cons binding (cadddr lexenv))))))
1058 (defun extend-lexenv (bindings lexenv namespace)
1059 (let ((env (copy-lexenv lexenv)))
1060 (dolist (binding (reverse bindings) env)
1061 (push-to-lexenv binding env namespace))))
1063 (defun lookup-in-lexenv (name lexenv namespace)
1064 (assoc name (ecase namespace
1065 (variable (first lexenv))
1066 (function (second lexenv))
1067 (block (third lexenv))
1068 (gotag (fourth lexenv)))))
1070 (defvar *environment* (make-lexenv))
1072 (defvar *variable-counter* 0)
1073 (defun gvarname (symbol)
1074 (concat "v" (integer-to-string (incf *variable-counter*))))
1076 (defun translate-variable (symbol)
1077 (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
1079 (defun extend-local-env (args)
1080 (let ((new (copy-lexenv *environment*)))
1081 (dolist (symbol args new)
1082 (let ((b (make-binding symbol 'variable (gvarname symbol))))
1083 (push-to-lexenv b new 'variable)))))
1085 ;;; Toplevel compilations
1086 (defvar *toplevel-compilations* nil)
1088 (defun toplevel-compilation (string)
1089 (push string *toplevel-compilations*))
1091 (defun null-or-empty-p (x)
1094 (defun get-toplevel-compilations ()
1095 (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
1097 (defun %compile-defmacro (name lambda)
1098 (toplevel-compilation (ls-compile `',name))
1099 (push-to-lexenv (make-binding name 'macro lambda) *environment* 'function)
1102 (defun global-binding (name type namespace)
1103 (or (lookup-in-lexenv name *environment* namespace)
1104 (let ((b (make-binding name type nil)))
1105 (push-to-lexenv b *environment* namespace)
1108 (defun claimp (symbol namespace claim)
1109 (let ((b (lookup-in-lexenv symbol *environment* namespace)))
1110 (and b (member claim (binding-declarations b)))))
1112 (defun !proclaim (decl)
1115 (dolist (name (cdr decl))
1116 (let ((b (global-binding name 'variable 'variable)))
1117 (push-binding-declaration 'special b))))
1119 (dolist (name (cdr decl))
1120 (let ((b (global-binding name 'function 'function)))
1121 (push-binding-declaration 'notinline b))))
1123 (dolist (name (cdr decl))
1124 (let ((b (global-binding name 'variable 'variable)))
1125 (push-binding-declaration 'constant b))))))
1128 (fset 'proclaim #'!proclaim)
1132 (defvar *compilations* nil)
1134 (defmacro define-compilation (name args &body body)
1135 ;; Creates a new primitive `name' with parameters args and
1136 ;; @body. The body can access to the local environment through the
1137 ;; variable *ENVIRONMENT*.
1138 `(push (list ',name (lambda ,args (block ,name ,@body)))
1141 (define-compilation if (condition true false)
1142 (concat "(" (ls-compile condition) " !== " (ls-compile nil)
1143 " ? " (ls-compile true *multiple-value-p*)
1144 " : " (ls-compile false *multiple-value-p*)
1147 (defvar *lambda-list-keywords* '(&optional &rest))
1149 (defun list-until-keyword (list)
1150 (if (or (null list) (member (car list) *lambda-list-keywords*))
1152 (cons (car list) (list-until-keyword (cdr list)))))
1154 (defun lambda-list-required-arguments (lambda-list)
1155 (list-until-keyword lambda-list))
1157 (defun lambda-list-optional-arguments-with-default (lambda-list)
1158 (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
1160 (defun lambda-list-optional-arguments (lambda-list)
1161 (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
1163 (defun lambda-list-rest-argument (lambda-list)
1164 (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
1166 (error "Bad lambda-list"))
1169 (defun lambda-docstring-wrapper (docstring &rest strs)
1172 "var func = " (join strs) ";" *newline*
1173 "func.docstring = '" docstring "';" *newline*
1174 "return func;" *newline*)
1177 (defun lambda-check-argument-count
1178 (n-required-arguments n-optional-arguments rest-p)
1179 ;; Note: Remember that we assume that the number of arguments of a
1180 ;; call is at least 1 (the values argument).
1181 (let ((min (1+ n-required-arguments))
1182 (max (if rest-p 'n/a (+ 1 n-required-arguments n-optional-arguments))))
1184 ;; Special case: a positive exact number of arguments.
1185 (when (and (< 1 min) (eql min max))
1186 (return (concat "checkArgs(arguments, " (integer-to-string min) ");" *newline*)))
1190 (concat "checkArgsAtLeast(arguments, " (integer-to-string min) ");" *newline*)
1193 (concat "checkArgsAtMost(arguments, " (integer-to-string max) ");" *newline*)
1196 (defun compile-lambda (lambda-list body)
1197 (let ((required-arguments (lambda-list-required-arguments lambda-list))
1198 (optional-arguments (lambda-list-optional-arguments lambda-list))
1199 (rest-argument (lambda-list-rest-argument lambda-list))
1201 ;; Get the documentation string for the lambda function
1202 (when (and (stringp (car body))
1203 (not (null (cdr body))))
1204 (setq documentation (car body))
1205 (setq body (cdr body)))
1206 (let ((n-required-arguments (length required-arguments))
1207 (n-optional-arguments (length optional-arguments))
1208 (*environment* (extend-local-env
1209 (append (ensure-list rest-argument)
1211 optional-arguments))))
1212 (lambda-docstring-wrapper
1215 (join (cons "values"
1216 (mapcar #'translate-variable
1217 (append required-arguments optional-arguments)))
1221 ;; Check number of arguments
1222 (lambda-check-argument-count n-required-arguments
1223 n-optional-arguments
1225 ;; Optional arguments
1226 (if optional-arguments
1227 (concat "switch(arguments.length-1){" *newline*
1228 (let ((optional-and-defaults
1229 (lambda-list-optional-arguments-with-default lambda-list))
1233 (while (< idx n-optional-arguments)
1234 (let ((arg (nth idx optional-and-defaults)))
1235 (push (concat "case "
1236 (integer-to-string (+ idx n-required-arguments)) ":" *newline*
1237 (translate-variable (car arg))
1239 (ls-compile (cadr arg))
1243 (push (concat "default: break;" *newline*) cases)
1244 (join (reverse cases))))
1247 ;; &rest/&body argument
1249 (let ((js!rest (translate-variable rest-argument)))
1250 (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
1251 "for (var i = arguments.length-1; i>="
1252 (integer-to-string (+ 1 n-required-arguments n-optional-arguments))
1254 (indent js!rest " = "
1255 "{car: arguments[i], cdr: ") js!rest "};"
1259 (let ((*multiple-value-p* t)) (ls-compile-block body t)))
1263 (defun setq-pair (var val)
1264 (let ((b (lookup-in-lexenv var *environment* 'variable)))
1265 (if (and (eq (binding-type b) 'variable)
1266 (not (member 'special (binding-declarations b)))
1267 (not (member 'constant (binding-declarations b))))
1268 (concat (binding-value b) " = " (ls-compile val))
1269 (ls-compile `(set ',var ,val)))))
1271 (define-compilation setq (&rest pairs)
1275 ((null pairs) (return))
1277 (error "Odd paris in SETQ"))
1280 (concat (setq-pair (car pairs) (cadr pairs))
1281 (if (null (cddr pairs)) "" ", ")))
1282 (setq pairs (cddr pairs)))))
1283 (concat "(" result ")")))
1285 ;;; FFI Variable accessors
1286 (define-compilation js-vref (var)
1289 (define-compilation js-vset (var val)
1290 (concat "(" var " = " (ls-compile val) ")"))
1295 (defun escape-string (string)
1298 (size (length string)))
1299 (while (< index size)
1300 (let ((ch (char string index)))
1301 (when (or (char= ch #\") (char= ch #\\))
1302 (setq output (concat output "\\")))
1303 (when (or (char= ch #\newline))
1304 (setq output (concat output "\\"))
1306 (setq output (concat output (string ch))))
1311 (defvar *literal-symbols* nil)
1312 (defvar *literal-counter* 0)
1315 (concat "l" (integer-to-string (incf *literal-counter*))))
1317 (defun literal (sexp &optional recursive)
1319 ((integerp sexp) (integer-to-string sexp))
1320 ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1322 (or (cdr (assoc sexp *literal-symbols*))
1324 (s #+common-lisp (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1326 (let ((package (symbol-package sexp)))
1328 (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1329 (ls-compile `(intern ,(symbol-name sexp) ,(package-name package)))))))
1330 (push (cons sexp v) *literal-symbols*)
1331 (toplevel-compilation (concat "var " v " = " s))
1334 (let* ((head (butlast sexp))
1336 (c (concat "QIList("
1337 (join-trailing (mapcar (lambda (x) (literal x t)) head) ",")
1338 (literal (car tail) t)
1340 (literal (cdr tail) t)
1345 (toplevel-compilation (concat "var " v " = " c))
1348 (let ((elements (vector-to-list sexp)))
1349 (let ((c (concat "[" (join (mapcar #'literal elements) ", ") "]")))
1353 (toplevel-compilation (concat "var " v " = " c))
1356 (define-compilation quote (sexp)
1359 (define-compilation %while (pred &rest body)
1361 "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1362 (indent (ls-compile-block body))
1364 "return " (ls-compile nil) ";" *newline*))
1366 (define-compilation function (x)
1368 ((and (listp x) (eq (car x) 'lambda))
1369 (compile-lambda (cadr x) (cddr x)))
1371 (ls-compile `(symbol-function ',x)))))
1373 (defvar *compiling-file* nil)
1374 (define-compilation eval-when-compile (&rest body)
1375 (if *compiling-file*
1377 (eval (cons 'progn body))
1379 (ls-compile `(progn ,@body))))
1381 (defmacro define-transformation (name args form)
1382 `(define-compilation ,name ,args
1383 (ls-compile ,form)))
1385 (define-compilation progn (&rest body)
1386 (if (null (cdr body))
1387 (ls-compile (car body) *multiple-value-p*)
1388 (js!selfcall (ls-compile-block body t))))
1390 (defun special-variable-p (x)
1391 (and (claimp x 'variable 'special) t))
1393 ;;; Wrap CODE to restore the symbol values of the dynamic
1394 ;;; bindings. BINDINGS is a list of pairs of the form
1395 ;;; (SYMBOL . PLACE), where PLACE is a Javascript variable
1396 ;;; name to initialize the symbol value and where to stored
1398 (defun let-binding-wrapper (bindings body)
1399 (when (null bindings)
1400 (return-from let-binding-wrapper body))
1403 (indent "var tmp;" *newline*
1406 (let ((s (ls-compile `(quote ,(car b)))))
1407 (concat "tmp = " s ".value;" *newline*
1408 s ".value = " (cdr b) ";" *newline*
1409 (cdr b) " = tmp;" *newline*)))
1413 "finally {" *newline*
1415 (mapconcat (lambda (b)
1416 (let ((s (ls-compile `(quote ,(car b)))))
1417 (concat s ".value" " = " (cdr b) ";" *newline*)))
1421 (define-compilation let (bindings &rest body)
1422 (let* ((bindings (mapcar #'ensure-list bindings))
1423 (variables (mapcar #'first bindings))
1424 (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
1425 (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
1427 (concat "(function("
1428 (join (mapcar (lambda (x)
1429 (if (special-variable-p x)
1430 (let ((v (gvarname x)))
1431 (push (cons x v) dynamic-bindings)
1433 (translate-variable x)))
1437 (let ((body (ls-compile-block body t)))
1438 (indent (let-binding-wrapper dynamic-bindings body)))
1439 "})(" (join cvalues ",") ")")))
1442 ;;; Return the code to initialize BINDING, and push it extending the
1443 ;;; current lexical environment if the variable is not special.
1444 (defun let*-initialize-value (binding)
1445 (let ((var (first binding))
1446 (value (second binding)))
1447 (if (special-variable-p var)
1448 (concat (ls-compile `(setq ,var ,value)) ";" *newline*)
1449 (let* ((v (gvarname var))
1450 (b (make-binding var 'variable v)))
1451 (prog1 (concat "var " v " = " (ls-compile value) ";" *newline*)
1452 (push-to-lexenv b *environment* 'variable))))))
1454 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
1455 ;;; DOES NOT generate code to initialize the value of the symbols,
1456 ;;; unlike let-binding-wrapper.
1457 (defun let*-binding-wrapper (symbols body)
1458 (when (null symbols)
1459 (return-from let*-binding-wrapper body))
1460 (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
1461 (remove-if-not #'special-variable-p symbols))))
1465 (mapconcat (lambda (b)
1466 (let ((s (ls-compile `(quote ,(car b)))))
1467 (concat "var " (cdr b) " = " s ".value;" *newline*)))
1471 "finally {" *newline*
1473 (mapconcat (lambda (b)
1474 (let ((s (ls-compile `(quote ,(car b)))))
1475 (concat s ".value" " = " (cdr b) ";" *newline*)))
1479 (define-compilation let* (bindings &rest body)
1480 (let ((bindings (mapcar #'ensure-list bindings))
1481 (*environment* (copy-lexenv *environment*)))
1483 (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
1484 (body (concat (mapconcat #'let*-initialize-value bindings)
1485 (ls-compile-block body t))))
1486 (let*-binding-wrapper specials body)))))
1489 (defvar *block-counter* 0)
1491 (define-compilation block (name &rest body)
1492 (let* ((tr (integer-to-string (incf *block-counter*)))
1493 (b (make-binding name 'block tr)))
1494 (when *multiple-value-p*
1495 (push-binding-declaration 'multiple-value b))
1496 (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
1497 (cbody (ls-compile-block body t)))
1498 (if (member 'used (binding-declarations b))
1503 "catch (cf){" *newline*
1504 " if (cf.type == 'block' && cf.id == " tr ")" *newline*
1505 (if *multiple-value-p*
1506 " return values.apply(this, forcemv(cf.values));"
1507 " return cf.values;")
1510 " throw cf;" *newline*
1512 (js!selfcall cbody)))))
1514 (define-compilation return-from (name &optional value)
1515 (let* ((b (lookup-in-lexenv name *environment* 'block))
1516 (multiple-value-p (member 'multiple-value (binding-declarations b))))
1518 (error (concat "Unknown block `" (symbol-name name) "'.")))
1519 (push-binding-declaration 'used b)
1521 (if multiple-value-p
1522 (concat "var values = mv;" *newline*)
1526 "id: " (binding-value b) ", "
1527 "values: " (ls-compile value multiple-value-p) ", "
1528 "message: 'Return from unknown block " (symbol-name name) ".'"
1531 (define-compilation catch (id &rest body)
1533 "var id = " (ls-compile id) ";" *newline*
1535 (indent (ls-compile-block body t)) *newline*
1537 "catch (cf){" *newline*
1538 " if (cf.type == 'catch' && cf.id == id)" *newline*
1539 (if *multiple-value-p*
1540 " return values.apply(this, forcemv(cf.values));"
1541 " return pv.apply(this, forcemv(cf.values));")
1544 " throw cf;" *newline*
1547 (define-compilation throw (id value)
1549 "var values = mv;" *newline*
1552 "id: " (ls-compile id) ", "
1553 "values: " (ls-compile value t) ", "
1554 "message: 'Throw uncatched.'"
1558 (defvar *tagbody-counter* 0)
1559 (defvar *go-tag-counter* 0)
1562 (or (integerp x) (symbolp x)))
1564 (defun declare-tagbody-tags (tbidx body)
1566 (mapcar (lambda (label)
1567 (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1568 (make-binding label 'gotag (list tbidx tagidx))))
1569 (remove-if-not #'go-tag-p body))))
1570 (extend-lexenv bindings *environment* 'gotag)))
1572 (define-compilation tagbody (&rest body)
1573 ;; Ignore the tagbody if it does not contain any go-tag. We do this
1574 ;; because 1) it is easy and 2) many built-in forms expand to a
1575 ;; implicit tagbody, so we save some space.
1576 (unless (some #'go-tag-p body)
1577 (return-from tagbody (ls-compile `(progn ,@body nil))))
1578 ;; The translation assumes the first form in BODY is a label
1579 (unless (go-tag-p (car body))
1580 (push (gensym "START") body))
1581 ;; Tagbody compilation
1582 (let ((tbidx (integer-to-string *tagbody-counter*)))
1583 (let ((*environment* (declare-tagbody-tags tbidx body))
1585 (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1586 (setq initag (second (binding-value b))))
1588 "var tagbody_" tbidx " = " initag ";" *newline*
1590 "while (true) {" *newline*
1591 (indent "try {" *newline*
1592 (indent (let ((content ""))
1593 (concat "switch(tagbody_" tbidx "){" *newline*
1594 "case " initag ":" *newline*
1595 (dolist (form (cdr body) content)
1597 (if (not (go-tag-p form))
1598 (indent (ls-compile form) ";" *newline*)
1599 (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1600 (concat "case " (second (binding-value b)) ":" *newline*)))))
1601 "default:" *newline*
1602 " break tbloop;" *newline*
1605 "catch (jump) {" *newline*
1606 " if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1607 " tagbody_" tbidx " = jump.label;" *newline*
1609 " throw(jump);" *newline*
1612 "return " (ls-compile nil) ";" *newline*))))
1614 (define-compilation go (label)
1615 (let ((b (lookup-in-lexenv label *environment* 'gotag))
1617 ((symbolp label) (symbol-name label))
1618 ((integerp label) (integer-to-string label)))))
1623 "id: " (first (binding-value b)) ", "
1624 "label: " (second (binding-value b)) ", "
1625 "message: 'Attempt to GO to non-existing tag " n "'"
1627 (error (concat "Unknown tag `" n "'.")))))
1629 (define-compilation unwind-protect (form &rest clean-up)
1631 "var ret = " (ls-compile nil) ";" *newline*
1633 (indent "ret = " (ls-compile form) ";" *newline*)
1634 "} finally {" *newline*
1635 (indent (ls-compile-block clean-up))
1637 "return ret;" *newline*))
1639 (define-compilation multiple-value-call (func-form &rest forms)
1641 "var func = " (ls-compile func-form) ";" *newline*
1642 "var args = [" (if *multiple-value-p* "values" "pv") "];" *newline*
1645 "var values = mv;" *newline*
1647 (mapconcat (lambda (form)
1648 (concat "vs = " (ls-compile form t) ";" *newline*
1649 "if (typeof vs === 'object' && 'multiple-value' in vs)" *newline*
1650 (indent "args = args.concat(vs);" *newline*)
1652 (indent "args.push(vs);" *newline*)))
1654 "return func.apply(window, args);" *newline*) ";" *newline*))
1656 (define-compilation multiple-value-prog1 (first-form &rest forms)
1658 "var args = " (ls-compile first-form *multiple-value-p*) ";" *newline*
1659 (ls-compile-block forms)
1660 "return args;" *newline*))
1664 ;;; A little backquote implementation without optimizations of any
1665 ;;; kind for ecmalisp.
1666 (defun backquote-expand-1 (form)
1672 ((eq (car form) 'unquote)
1674 ((eq (car form) 'backquote)
1675 (backquote-expand-1 (backquote-expand-1 (cadr form))))
1680 ((and (listp s) (eq (car s) 'unquote))
1681 (list 'list (cadr s)))
1682 ((and (listp s) (eq (car s) 'unquote-splicing))
1685 (list 'list (backquote-expand-1 s)))))
1688 (defun backquote-expand (form)
1689 (if (and (listp form) (eq (car form) 'backquote))
1690 (backquote-expand-1 (cadr form))
1693 (defmacro backquote (form)
1694 (backquote-expand-1 form))
1696 (define-transformation backquote (form)
1697 (backquote-expand-1 form))
1701 (defvar *builtins* nil)
1703 (defmacro define-raw-builtin (name args &body body)
1704 ;; Creates a new primitive function `name' with parameters args and
1705 ;; @body. The body can access to the local environment through the
1706 ;; variable *ENVIRONMENT*.
1707 `(push (list ',name (lambda ,args (block ,name ,@body)))
1710 (defmacro define-builtin (name args &body body)
1712 (define-raw-builtin ,name ,args
1713 (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1716 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1717 (defmacro type-check (decls &body body)
1719 ,@(mapcar (lambda (decl)
1720 `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1722 ,@(mapcar (lambda (decl)
1723 `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1724 (indent "throw 'The value ' + "
1726 " + ' is not a type "
1731 (concat "return " (progn ,@body) ";" *newline*)))
1733 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
1734 ;;; a variable which holds a list of forms. It will compile them and
1735 ;;; store the result in some Javascript variables. BODY is evaluated
1736 ;;; with ARGS bound to the list of these variables to generate the
1737 ;;; code which performs the transformation on these variables.
1739 (defun variable-arity-call (args function)
1740 (unless (consp args)
1741 (error "ARGS must be a non-empty list"))
1746 (let ((v (concat "x" (integer-to-string (incf counter)))))
1749 (concat "var " v " = " (ls-compile x) ";" *newline*
1750 "if (typeof " v " !== 'number') throw 'Not a number!';"
1752 (js!selfcall prelude (funcall function (reverse variables)))))
1755 (defmacro variable-arity (args &body body)
1756 (unless (symbolp args)
1757 (error "Bad usage of VARIABLE-ARITY, you must pass a symbol"))
1758 `(variable-arity-call ,args
1760 (concat "return " ,@body ";" *newline*))))
1762 (defun num-op-num (x op y)
1763 (type-check (("x" "number" x) ("y" "number" y))
1764 (concat "x" op "y")))
1766 (define-raw-builtin + (&rest numbers)
1769 (variable-arity numbers
1770 (join numbers "+"))))
1772 (define-raw-builtin - (x &rest others)
1773 (let ((args (cons x others)))
1774 (variable-arity args
1776 (concat "-" (car args))
1779 (define-raw-builtin * (&rest numbers)
1782 (variable-arity numbers
1783 (join numbers "*"))))
1785 (define-raw-builtin / (x &rest others)
1786 (let ((args (cons x others)))
1787 (variable-arity args
1789 (concat "1 /" (car args))
1792 (define-builtin mod (x y) (num-op-num x "%" y))
1795 (defun comparison-conjuntion (vars op)
1800 (concat (car vars) op (cadr vars)))
1802 (concat (car vars) op (cadr vars)
1804 (comparison-conjuntion (cdr vars) op)))))
1806 (defmacro define-builtin-comparison (op sym)
1807 `(define-raw-builtin ,op (x &rest args)
1808 (let ((args (cons x args)))
1809 (variable-arity args
1810 (js!bool (comparison-conjuntion args ,sym))))))
1812 (define-builtin-comparison > ">")
1813 (define-builtin-comparison < "<")
1814 (define-builtin-comparison >= ">=")
1815 (define-builtin-comparison <= "<=")
1816 (define-builtin-comparison = "==")
1818 (define-builtin numberp (x)
1819 (js!bool (concat "(typeof (" x ") == \"number\")")))
1821 (define-builtin floor (x)
1822 (type-check (("x" "number" x))
1825 (define-builtin cons (x y)
1826 (concat "({car: " x ", cdr: " y "})"))
1828 (define-builtin consp (x)
1831 "var tmp = " x ";" *newline*
1832 "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1834 (define-builtin car (x)
1836 "var tmp = " x ";" *newline*
1837 "return tmp === " (ls-compile nil)
1838 "? " (ls-compile nil)
1839 ": tmp.car;" *newline*))
1841 (define-builtin cdr (x)
1843 "var tmp = " x ";" *newline*
1844 "return tmp === " (ls-compile nil) "? "
1846 ": tmp.cdr;" *newline*))
1848 (define-builtin rplaca (x new)
1849 (type-check (("x" "object" x))
1850 (concat "(x.car = " new ", x)")))
1852 (define-builtin rplacd (x new)
1853 (type-check (("x" "object" x))
1854 (concat "(x.cdr = " new ", x)")))
1856 (define-builtin symbolp (x)
1859 "var tmp = " x ";" *newline*
1860 "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1862 (define-builtin make-symbol (name)
1863 (type-check (("name" "string" name))
1866 (define-builtin symbol-name (x)
1867 (concat "(" x ").name"))
1869 (define-builtin set (symbol value)
1870 (concat "(" symbol ").value = " value))
1872 (define-builtin fset (symbol value)
1873 (concat "(" symbol ").fvalue = " value))
1875 (define-builtin boundp (x)
1876 (js!bool (concat "(" x ".value !== undefined)")))
1878 (define-builtin symbol-value (x)
1880 "var symbol = " x ";" *newline*
1881 "var value = symbol.value;" *newline*
1882 "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1883 "return value;" *newline*))
1885 (define-builtin symbol-function (x)
1887 "var symbol = " x ";" *newline*
1888 "var func = symbol.fvalue;" *newline*
1889 "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1890 "return func;" *newline*))
1892 (define-builtin symbol-plist (x)
1893 (concat "((" x ").plist || " (ls-compile nil) ")"))
1895 (define-builtin lambda-code (x)
1896 (concat "(" x ").toString()"))
1898 (define-builtin eq (x y) (js!bool (concat "(" x " === " y ")")))
1899 (define-builtin equal (x y) (js!bool (concat "(" x " == " y ")")))
1901 (define-builtin char-to-string (x)
1902 (type-check (("x" "number" x))
1903 "String.fromCharCode(x)"))
1905 (define-builtin stringp (x)
1906 (js!bool (concat "(typeof(" x ") == \"string\")")))
1908 (define-builtin string-upcase (x)
1909 (type-check (("x" "string" x))
1912 (define-builtin string-length (x)
1913 (type-check (("x" "string" x))
1916 (define-raw-builtin slice (string a &optional b)
1918 "var str = " (ls-compile string) ";" *newline*
1919 "var a = " (ls-compile a) ";" *newline*
1922 (concat "b = " (ls-compile b) ";" *newline*)
1924 "return str.slice(a,b);" *newline*))
1926 (define-builtin char (string index)
1927 (type-check (("string" "string" string)
1928 ("index" "number" index))
1929 "string.charCodeAt(index)"))
1931 (define-builtin concat-two (string1 string2)
1932 (type-check (("string1" "string" string1)
1933 ("string2" "string" string2))
1934 "string1.concat(string2)"))
1936 (define-raw-builtin funcall (func &rest args)
1937 (concat "(" (ls-compile func) ")("
1938 (join (cons (if *multiple-value-p* "values" "pv")
1939 (mapcar #'ls-compile args))
1943 (define-raw-builtin apply (func &rest args)
1945 (concat "(" (ls-compile func) ")()")
1946 (let ((args (butlast args))
1947 (last (car (last args))))
1949 "var f = " (ls-compile func) ";" *newline*
1950 "var args = [" (join (cons (if *multiple-value-p* "values" "pv")
1951 (mapcar #'ls-compile args))
1954 "var tail = (" (ls-compile last) ");" *newline*
1955 "while (tail != " (ls-compile nil) "){" *newline*
1956 " args.push(tail.car);" *newline*
1957 " tail = tail.cdr;" *newline*
1959 "return f.apply(this, args);" *newline*))))
1961 (define-builtin js-eval (string)
1962 (type-check (("string" "string" string))
1963 (if *multiple-value-p*
1965 "var v = eval.apply(window, [string]);" *newline*
1966 "if (typeof v !== 'object' || !('multiple-value' in v)){" *newline*
1967 (indent "v = [v];" *newline*
1968 "v['multiple-value'] = true;" *newline*)
1970 "return values.apply(this, v);" *newline*)
1971 "eval.apply(window, [string])")))
1973 (define-builtin error (string)
1974 (js!selfcall "throw " string ";" *newline*))
1976 (define-builtin new () "{}")
1978 (define-builtin objectp (x)
1979 (js!bool (concat "(typeof (" x ") === 'object')")))
1981 (define-builtin oget (object key)
1983 "var tmp = " "(" object ")[" key "];" *newline*
1984 "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1986 (define-builtin oset (object key value)
1987 (concat "((" object ")[" key "] = " value ")"))
1989 (define-builtin in (key object)
1990 (js!bool (concat "((" key ") in (" object "))")))
1992 (define-builtin functionp (x)
1993 (js!bool (concat "(typeof " x " == 'function')")))
1995 (define-builtin write-string (x)
1996 (type-check (("x" "string" x))
1999 (define-builtin make-array (n)
2001 "var r = [];" *newline*
2002 "for (var i = 0; i < " n "; i++)" *newline*
2003 (indent "r.push(" (ls-compile nil) ");" *newline*)
2004 "return r;" *newline*))
2006 (define-builtin arrayp (x)
2009 "var x = " x ";" *newline*
2010 "return typeof x === 'object' && 'length' in x;")))
2012 (define-builtin aref (array n)
2014 "var x = " "(" array ")[" n "];" *newline*
2015 "if (x === undefined) throw 'Out of range';" *newline*
2016 "return x;" *newline*))
2018 (define-builtin aset (array n value)
2020 "var x = " array ";" *newline*
2021 "var i = " n ";" *newline*
2022 "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
2023 "return x[i] = " value ";" *newline*))
2025 (define-builtin get-unix-time ()
2026 (concat "(Math.round(new Date() / 1000))"))
2028 (define-builtin values-array (array)
2029 (if *multiple-value-p*
2030 (concat "values.apply(this, " array ")")
2031 (concat "pv.apply(this, " array ")")))
2033 (define-raw-builtin values (&rest args)
2034 (if *multiple-value-p*
2035 (concat "values(" (join (mapcar #'ls-compile args) ", ") ")")
2036 (concat "pv(" (join (mapcar #'ls-compile args) ", ") ")")))
2040 (let ((b (lookup-in-lexenv x *environment* 'function)))
2041 (and (eq (binding-type b) 'macro)
2044 (defun ls-macroexpand-1 (form)
2045 (let ((macro-binding (macro (car form))))
2047 (let ((expander (binding-value macro-binding)))
2048 (when (listp expander)
2049 (let ((compiled (eval expander)))
2050 ;; The list representation are useful while
2051 ;; bootstrapping, as we can dump the definition of the
2052 ;; macros easily, but they are slow because we have to
2053 ;; evaluate them and compile them now and again. So, let
2054 ;; us replace the list representation version of the
2055 ;; function with the compiled one.
2057 #+ecmalisp (set-binding-value macro-binding compiled)
2058 (setq expander compiled)))
2059 (apply expander (cdr form)))
2062 (defun compile-funcall (function args)
2063 (let ((values-funcs (if *multiple-value-p* "values" "pv")))
2064 (if (and (symbolp function)
2065 #+ecmalisp (eq (symbol-package function) (find-package "COMMON-LISP"))
2067 (concat (ls-compile `',function) ".fvalue("
2068 (join (cons values-funcs (mapcar #'ls-compile args))
2071 (concat (ls-compile `#',function) "("
2072 (join (cons values-funcs (mapcar #'ls-compile args))
2076 (defun ls-compile-block (sexps &optional return-last-p)
2078 (concat (ls-compile-block (butlast sexps))
2079 "return " (ls-compile (car (last sexps)) *multiple-value-p*) ";")
2081 (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
2082 (concat ";" *newline*))))
2084 (defun ls-compile (sexp &optional multiple-value-p)
2085 (let ((*multiple-value-p* multiple-value-p))
2088 (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
2090 ((and b (not (member 'special (binding-declarations b))))
2092 ((or (keywordp sexp)
2093 (member 'constant (binding-declarations b)))
2094 (concat (ls-compile `',sexp) ".value"))
2096 (ls-compile `(symbol-value ',sexp))))))
2097 ((integerp sexp) (integer-to-string sexp))
2098 ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
2099 ((arrayp sexp) (literal sexp))
2101 (let ((name (car sexp))
2105 ((assoc name *compilations*)
2106 (let ((comp (second (assoc name *compilations*))))
2108 ;; Built-in functions
2109 ((and (assoc name *builtins*)
2110 (not (claimp name 'function 'notinline)))
2111 (let ((comp (second (assoc name *builtins*))))
2115 (ls-compile (ls-macroexpand-1 sexp) multiple-value-p)
2116 (compile-funcall name args))))))
2118 (error "How should I compile this?")))))
2120 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
2121 (let ((*toplevel-compilations* nil))
2123 ((and (consp sexp) (eq (car sexp) 'progn))
2124 (let ((subs (mapcar (lambda (s)
2125 (ls-compile-toplevel s t))
2127 (join (remove-if #'null-or-empty-p subs))))
2129 (let ((code (ls-compile sexp multiple-value-p)))
2130 (concat (join-trailing (get-toplevel-compilations)
2131 (concat ";" *newline*))
2133 (concat code ";" *newline*)
2137 ;;; Once we have the compiler, we define the runtime environment and
2138 ;;; interactive development (eval), which works calling the compiler
2139 ;;; and evaluating the Javascript result globally.
2144 (js-eval (ls-compile-toplevel x t)))
2146 (export '(&rest &optional &body * *gensym-counter* *package* + - / 1+ 1- < <= =
2147 = > >= and append apply aref arrayp aset assoc atom block boundp
2148 boundp butlast caar cadddr caddr cadr car car case catch cdar cdddr
2149 cddr cdr cdr char char-code char= code-char cond cons consp copy-list
2150 decf declaim defparameter defun defmacro defvar digit-char-p
2151 disassemble do do* documentation dolist dotimes ecase eq eql equal
2152 error eval every export fdefinition find-package find-symbol first
2153 fourth fset funcall function functionp gensym get-universal-time go
2154 identity if in-package incf integerp integerp intern keywordp lambda
2155 last length let let* list-all-packages list listp make-array
2156 make-package make-symbol mapcar member minusp mod multiple-value-bind
2157 multiple-value-call multiple-value-list multiple-value-prog1 nil not
2158 nth nthcdr null numberp or package-name package-use-list packagep
2159 plusp prin1-to-string print proclaim prog1 prog2 progn psetq push
2160 quote remove remove-if remove-if-not return return-from revappend
2161 reverse rplaca rplacd second set setq some string-upcase string
2162 string= stringp subseq symbol-function symbol-name symbol-package
2163 symbol-plist symbol-value symbolp t tagbody third throw truncate
2164 unless unwind-protect values values-list variable warn when write-line
2165 write-string zerop))
2167 (setq *package* *user-package*)
2169 (js-eval "var lisp")
2170 (js-vset "lisp" (new))
2171 (js-vset "lisp.read" #'ls-read-from-string)
2172 (js-vset "lisp.print" #'prin1-to-string)
2173 (js-vset "lisp.eval" #'eval)
2174 (js-vset "lisp.compile" (lambda (s) (ls-compile-toplevel s t)))
2175 (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
2176 (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str) t)))
2178 ;; Set the initial global environment to be equal to the host global
2179 ;; environment at this point of the compilation.
2181 (toplevel-compilation
2184 ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
2186 (setq *literal-symbols* ',*literal-symbols*)
2187 (setq *environment* ',*environment*)
2188 (setq *variable-counter* ,*variable-counter*)
2189 (setq *gensym-counter* ,*gensym-counter*)
2190 (setq *block-counter* ,*block-counter*)))))
2193 (toplevel-compilation
2195 `(setq *literal-counter* ,*literal-counter*)))))
2198 ;;; Finally, we provide a couple of functions to easily bootstrap
2199 ;;; this. It just calls the compiler with this file as input.
2203 (defun read-whole-file (filename)
2204 (with-open-file (in filename)
2205 (let ((seq (make-array (file-length in) :element-type 'character)))
2206 (read-sequence seq in)
2209 (defun ls-compile-file (filename output)
2210 (let ((*compiling-file* t))
2211 (with-open-file (out output :direction :output :if-exists :supersede)
2212 (write-string (read-whole-file "prelude.js") out)
2213 (let* ((source (read-whole-file filename))
2214 (in (make-string-stream source)))
2216 for x = (ls-read in)
2218 for compilation = (ls-compile-toplevel x)
2219 when (plusp (length compilation))
2220 do (write-string compilation out))))))
2223 (setq *environment* (make-lexenv))
2224 (setq *literal-symbols* nil)
2225 (setq *variable-counter* 0
2229 (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))