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))
136 (defun rest (x) (cdr x))
138 (defun list (&rest args) args)
144 (defmacro incf (x &optional (delta 1))
145 `(setq ,x (+ ,x ,delta)))
147 (defmacro decf (x &optional (delta 1))
148 `(setq ,x (- ,x ,delta)))
150 (defmacro push (x place)
151 `(setq ,place (cons ,x ,place)))
153 (defmacro dolist (iter &body body)
154 (let ((var (first iter))
157 (let ((,g!list ,(second iter))
160 (setq ,var (car ,g!list))
162 (setq ,g!list (cdr ,g!list)))
165 (defmacro dotimes (iter &body body)
166 (let ((g!to (gensym))
169 (result (third iter)))
173 (%while (< ,var ,g!to)
178 (defmacro cond (&rest clausules)
181 (if (eq (caar clausules) t)
182 `(progn ,@(cdar clausules))
183 `(if ,(caar clausules)
184 (progn ,@(cdar clausules))
185 (cond ,@(cdr clausules))))))
187 (defmacro case (form &rest clausules)
188 (let ((!form (gensym)))
189 `(let ((,!form ,form))
191 ,@(mapcar (lambda (clausule)
192 (if (eq (car clausule) t)
194 `((eql ,!form ',(car clausule))
198 (defmacro ecase (form &rest clausules)
203 (error "ECASE expression failed."))))))
205 (defmacro and (&rest forms)
216 (defmacro or (&rest forms)
224 `(let ((,g ,(car forms)))
225 (if ,g ,g (or ,@(cdr forms))))))))
227 (defmacro prog1 (form &body body)
228 (let ((value (gensym)))
229 `(let ((,value ,form))
233 (defmacro prog2 (form1 result &body body)
234 `(prog1 (progn ,form1 ,result) ,@body)))
237 ;;; This couple of helper functions will be defined in both Common
238 ;;; Lisp and in Ecmalisp.
239 (defun ensure-list (x)
244 (defun !reduce (func list initial)
249 (funcall func initial (car list)))))
251 ;;; Go on growing the Lisp language in Ecmalisp, with more high
252 ;;; level utilities as well as correct versions of other
256 (defun + (&rest args)
261 (defun - (x &rest others)
268 (defun append-two (list1 list2)
272 (append (cdr list1) list2))))
274 (defun append (&rest lists)
275 (!reduce #'append-two lists '()))
277 (defun revappend (list1 list2)
279 (push (car list1) list2)
280 (setq list1 (cdr list1)))
283 (defun reverse (list)
284 (revappend list '()))
286 (defmacro psetq (&rest pairs)
287 (let ( ;; For each pair, we store here a list of the form
288 ;; (VARIABLE GENSYM VALUE).
292 ((null pairs) (return))
294 (error "Odd paris in PSETQ"))
296 (let ((variable (car pairs))
297 (value (cadr pairs)))
298 (push `(,variable ,(gensym) ,value) assignments)
299 (setq pairs (cddr pairs))))))
300 (setq assignments (reverse assignments))
302 `(let ,(mapcar #'cdr assignments)
303 (setq ,@(!reduce #'append (mapcar #'butlast assignments) '())))))
305 (defmacro do (varlist endlist &body body)
307 (let ,(mapcar (lambda (x) (list (first x) (second x))) varlist)
310 (return (progn ,(cdr endlist))))
315 (and (consp (cddr v))
316 (list (first v) (third v))))
319 (defmacro do* (varlist endlist &body body)
321 (let* ,(mapcar (lambda (x) (list (first x) (second x))) varlist)
324 (return (progn ,(cdr endlist))))
329 (and (consp (cddr v))
330 (list (first v) (third v))))
333 (defun list-length (list)
335 (while (not (null list))
337 (setq list (cdr list)))
349 (defun concat-two (s1 s2)
352 (defun mapcar (func list)
355 (cons (funcall func (car list))
356 (mapcar func (cdr list)))))
358 (defun identity (x) x)
361 (mapcar #'identity x))
363 (defun code-char (x) x)
364 (defun char-code (x) x)
365 (defun char= (x y) (= x y))
368 (and (numberp x) (= (floor x) x)))
370 (defun plusp (x) (< 0 x))
371 (defun minusp (x) (< x 0))
374 (or (consp x) (null x)))
376 (defun nthcdr (n list)
377 (while (and (plusp n) list)
379 (setq list (cdr list)))
383 (car (nthcdr n list)))
386 (while (consp (cdr x))
392 (cons (car x) (butlast (cdr x)))))
394 (defun member (x list)
396 (when (eql x (car list))
398 (setq list (cdr list))))
400 (defun remove (x list)
405 (remove x (cdr list)))
407 (cons (car list) (remove x (cdr list))))))
409 (defun remove-if (func list)
413 ((funcall func (car list))
414 (remove-if func (cdr list)))
416 (cons (car list) (remove-if func (cdr list))))))
418 (defun remove-if-not (func list)
422 ((funcall func (car list))
423 (cons (car list) (remove-if-not func (cdr list))))
425 (remove-if-not func (cdr list)))))
427 (defun digit-char-p (x)
428 (if (and (<= #\0 x) (<= x #\9))
432 (defun subseq (seq a &optional b)
439 (error "Unsupported argument."))))
441 (defun some (function seq)
446 (while (< index size)
447 (when (funcall function (char seq index))
448 (return-from some t))
453 (when (funcall function x)
456 (error "Unknown sequence."))))
458 (defun every (function seq)
463 (while (< index size)
464 (unless (funcall function (char seq index))
465 (return-from every nil))
470 (unless (funcall function x)
473 (error "Unknown sequence."))))
475 (defun assoc (x alist)
477 (if (eql x (caar alist))
479 (setq alist (cdr alist))))
483 (cond ((stringp x) x)
484 ((symbolp x) (symbol-name x))
485 (t (char-to-string x))))
487 (defun string= (s1 s2)
490 (defun fdefinition (x)
497 (error "Invalid function"))))
499 (defun disassemble (function)
500 (write-line (lambda-code (fdefinition function)))
503 (defun documentation (x type)
504 "Return the documentation of X. TYPE must be the symbol VARIABLE or FUNCTION."
507 (let ((func (fdefinition x)))
508 (oget func "docstring")))
511 (error "Wrong argument type! it should be a symbol"))
514 (defmacro multiple-value-bind (variables value-from &body body)
515 `(multiple-value-call (lambda (&optional ,@variables &rest ,(gensym))
519 (defmacro multiple-value-list (value-from)
520 `(multiple-value-call #'list ,value-from))
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)
592 (if (in "package" symbol)
593 (find-package-or-fail (oget symbol "package"))
594 *common-lisp-package*))
595 (symbols (%package-symbols package)))
596 (oset symbol "package" package)
597 (when (eq package *keyword-package*)
598 (oset symbol "value" symbol))
599 (oset symbols (symbol-name symbol) symbol)))
601 (defun find-symbol (name &optional (package *package*))
602 (let* ((package (find-package-or-fail package))
603 (externals (%package-external-symbols package))
604 (symbols (%package-symbols package)))
607 (values (oget externals name) :external))
609 (values (oget symbols name) :internal))
611 (dolist (used (package-use-list package) (values nil nil))
612 (let ((exports (%package-external-symbols used)))
613 (when (in name exports)
614 (return (values (oget exports name) :inherit)))))))))
616 (defun intern (name &optional (package *package*))
617 (let ((package (find-package-or-fail package)))
618 (multiple-value-bind (symbol foundp)
619 (find-symbol name package)
621 (values symbol foundp)
622 (let ((symbols (%package-symbols package)))
624 (let ((symbol (make-symbol name)))
625 (oset symbol "package" package)
626 (when (eq package *keyword-package*)
627 (oset symbol "value" symbol)
628 (export (list symbol) package))
629 (oset symbols name symbol)
630 (values symbol nil)))))))
632 (defun symbol-package (symbol)
633 (unless (symbolp symbol)
634 (error "it is not a symbol"))
635 (oget symbol "package"))
637 (defun export (symbols &optional (package *package*))
638 (let ((exports (%package-external-symbols package)))
639 (dolist (symb symbols t)
640 (oset exports (symbol-name symb) symb))))
642 (defun get-universal-time ()
643 (+ (get-unix-time) 2208988800)))
646 ;;; The compiler offers some primitives and special forms which are
647 ;;; not found in Common Lisp, for instance, while. So, we grow Common
648 ;;; Lisp a bit to it can execute the rest of the file.
651 (defmacro while (condition &body body)
656 (defmacro eval-when-compile (&body body)
657 `(eval-when (:compile-toplevel :load-toplevel :execute)
660 (defun concat-two (s1 s2)
661 (concatenate 'string s1 s2))
663 (defun aset (array idx value)
664 (setf (aref array idx) value)))
666 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
667 ;;; from here, this code will compile on both. We define some helper
668 ;;; functions now for string manipulation and so on. They will be
669 ;;; useful in the compiler, mostly.
671 (defvar *newline* (string (code-char 10)))
673 (defun concat (&rest strs)
674 (!reduce #'concat-two strs ""))
676 (defmacro concatf (variable &body form)
677 `(setq ,variable (concat ,variable (progn ,@form))))
679 ;;; Concatenate a list of strings, with a separator
680 (defun join (list &optional (separator ""))
689 (join (cdr list) separator)))))
691 (defun join-trailing (list &optional (separator ""))
694 (concat (car list) separator (join-trailing (cdr list) separator))))
696 (defun mapconcat (func list)
697 (join (mapcar func list)))
699 (defun vector-to-list (vector)
701 (size (length vector)))
702 (dotimes (i size (reverse list))
703 (push (aref vector i) list))))
705 (defun list-to-vector (list)
706 (let ((v (make-array (length list)))
714 (defun values-list (list)
715 (values-array (list-to-vector list)))
717 (defun values (&rest args)
721 ;;; Like CONCAT, but prefix each line with four spaces. Two versions
722 ;;; of this function are available, because the Ecmalisp version is
723 ;;; very slow and bootstraping was annoying.
726 (defun indent (&rest string)
727 (let ((input (join string)))
730 (size (length input)))
731 (when (plusp (length input)) (concatf output " "))
732 (while (< index size)
734 (if (and (char= (char input index) #\newline)
736 (not (char= (char input (1+ index)) #\newline)))
737 (concat (string #\newline) " ")
738 (string (char input index)))))
739 (concatf output str))
744 (defun indent (&rest string)
745 (with-output-to-string (*standard-output*)
746 (with-input-from-string (input (join string))
748 for line = (read-line input nil)
750 do (write-string " ")
751 do (write-line line)))))
754 (defun integer-to-string (x)
759 (concat "-" (integer-to-string (- 0 x))))
762 (while (not (zerop x))
763 (push (mod x 10) digits)
764 (setq x (truncate x 10)))
765 (join (mapcar (lambda (d) (string (char "0123456789" d)))
769 ;;; Wrap X with a Javascript code to convert the result from
770 ;;; Javascript generalized booleans to T or NIL.
772 (concat "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
774 ;;; Concatenate the arguments and wrap them with a self-calling
775 ;;; Javascript anonymous function. It is used to make some Javascript
776 ;;; statements valid expressions and provide a private scope as well.
777 ;;; It could be defined as function, but we could do some
778 ;;; preprocessing in the future.
779 (defmacro js!selfcall (&body body)
780 `(concat "(function(){" *newline* (indent ,@body) "})()"))
787 (defun prin1-to-string (form)
790 (multiple-value-bind (symbol foundp)
791 (find-symbol (symbol-name form) *package*)
792 (if (and foundp (eq symbol form))
794 (let ((package (symbol-package form))
795 (name (symbol-name form)))
798 ((eq package (find-package "KEYWORD")) "")
799 (t (package-name package)))
801 ((integerp form) (integer-to-string form))
802 ((stringp form) (concat "\"" (escape-string form) "\""))
804 (let ((name (oget form "fname")))
806 (concat "#<FUNCTION " name ">")
807 (concat "#<FUNCTION>"))))
810 (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
811 (let ((last (last form)))
812 (if (null (cdr last))
813 (prin1-to-string (car last))
814 (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
817 (concat "#" (prin1-to-string (vector-to-list form))))
819 (concat "#<PACKAGE " (package-name form) ">"))))
821 (defun write-line (x)
823 (write-string *newline*)
827 (write-string "WARNING: ")
831 (write-line (prin1-to-string x))
837 ;;; The Lisp reader, parse strings and return Lisp objects. The main
838 ;;; entry points are `ls-read' and `ls-read-from-string'.
840 (defun make-string-stream (string)
843 (defun %peek-char (stream)
844 (and (< (cdr stream) (length (car stream)))
845 (char (car stream) (cdr stream))))
847 (defun %read-char (stream)
848 (and (< (cdr stream) (length (car stream)))
849 (prog1 (char (car stream) (cdr stream))
850 (rplacd stream (1+ (cdr stream))))))
852 (defun whitespacep (ch)
853 (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
855 (defun skip-whitespaces (stream)
857 (setq ch (%peek-char stream))
858 (while (and ch (whitespacep ch))
860 (setq ch (%peek-char stream)))))
862 (defun terminalp (ch)
863 (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
865 (defun read-until (stream func)
868 (setq ch (%peek-char stream))
869 (while (and ch (not (funcall func ch)))
870 (setq string (concat string (string ch)))
872 (setq ch (%peek-char stream)))
875 (defun skip-whitespaces-and-comments (stream)
877 (skip-whitespaces stream)
878 (setq ch (%peek-char stream))
879 (while (and ch (char= ch #\;))
880 (read-until stream (lambda (x) (char= x #\newline)))
881 (skip-whitespaces stream)
882 (setq ch (%peek-char stream)))))
884 (defun %read-list (stream)
885 (skip-whitespaces-and-comments stream)
886 (let ((ch (%peek-char stream)))
889 (error "Unspected EOF"))
895 (prog1 (ls-read stream)
896 (skip-whitespaces-and-comments stream)
897 (unless (char= (%read-char stream) #\))
898 (error "')' was expected."))))
900 (cons (ls-read stream) (%read-list stream))))))
902 (defun read-string (stream)
905 (setq ch (%read-char stream))
906 (while (not (eql ch #\"))
908 (error "Unexpected EOF"))
910 (setq ch (%read-char stream)))
911 (setq string (concat string (string ch)))
912 (setq ch (%read-char stream)))
915 (defun read-sharp (stream)
917 (ecase (%read-char stream)
919 (list 'function (ls-read stream)))
920 (#\( (list-to-vector (%read-list stream)))
921 (#\: (make-symbol (string-upcase (read-until stream #'terminalp))))
924 (concat (string (%read-char stream))
925 (read-until stream #'terminalp))))
927 ((string= cname "space") (char-code #\space))
928 ((string= cname "tab") (char-code #\tab))
929 ((string= cname "newline") (char-code #\newline))
930 (t (char-code (char cname 0))))))
932 (let ((feature (read-until stream #'terminalp)))
934 ((string= feature "common-lisp")
935 (ls-read stream) ;ignore
937 ((string= feature "ecmalisp")
940 (error "Unknown reader form.")))))))
942 ;;; Parse a string of the form NAME, PACKAGE:NAME or
943 ;;; PACKAGE::NAME and return the name. If the string is of the
944 ;;; form 1) or 3), but the symbol does not exist, it will be created
945 ;;; and interned in that package.
946 (defun read-symbol (string)
947 (let ((size (length string))
948 package name internalp index)
950 (while (and (< index size)
951 (not (char= (char string index) #\:)))
957 (setq package *package*)
962 (setq package "KEYWORD")
963 (setq package (string-upcase (subseq string 0 index))))
965 (when (char= (char string index) #\:)
968 (setq name (subseq string index))))
969 ;; Canonalize symbol name and package
970 (setq name (string-upcase name))
971 (setq package (find-package package))
972 ;; TODO: PACKAGE:SYMBOL should signal error if SYMBOL is not an
973 ;; external symbol from PACKAGE.
974 (if (or internalp (eq package (find-package "KEYWORD")))
975 (intern name package)
976 (find-symbol name package))))
979 (defun !parse-integer (string junk-allow)
983 (size (length string))
985 (when (zerop size) (return (values nil 0)))
987 (case (char string 0)
992 (unless (and (< index size)
993 (setq value (digit-char-p (char string index))))
994 (return (values nil index)))
997 (while (< index size)
998 (let ((digit (digit-char-p (char string index))))
999 (unless digit (return))
1000 (setq value (+ (* value 10) digit))
1004 (char= (char string index) #\space))
1005 (values (* sign value) index)
1006 (values nil index)))))
1009 (defun parse-integer (string)
1010 (!parse-integer string nil))
1012 (defvar *eof* (gensym))
1013 (defun ls-read (stream)
1014 (skip-whitespaces-and-comments stream)
1015 (let ((ch (%peek-char stream)))
1017 ((or (null ch) (char= ch #\)))
1021 (%read-list stream))
1024 (list 'quote (ls-read stream)))
1027 (list 'backquote (ls-read stream)))
1030 (read-string stream))
1033 (if (eql (%peek-char stream) #\@)
1034 (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
1035 (list 'unquote (ls-read stream))))
1037 (read-sharp stream))
1039 (let ((string (read-until stream #'terminalp)))
1040 (or (values (!parse-integer string nil))
1041 (read-symbol string)))))))
1043 (defun ls-read-from-string (string)
1044 (ls-read (make-string-stream string)))
1049 ;;; Translate the Lisp code to Javascript. It will compile the special
1050 ;;; forms. Some primitive functions are compiled as special forms
1051 ;;; too. The respective real functions are defined in the target (see
1052 ;;; the beginning of this file) as well as some primitive functions.
1054 ;;; A Form can return a multiple values object calling VALUES, like
1055 ;;; values(arg1, arg2, ...). It will work in any context, as well as
1056 ;;; returning an individual object. However, if the special variable
1057 ;;; `*multiple-value-p*' is NIL, is granted that only the primary
1058 ;;; value will be used, so we can optimize to avoid the VALUES
1060 (defvar *multiple-value-p* nil)
1063 (defun make-binding (name type value &optional declarations)
1064 (list name type value declarations))
1066 (defun binding-name (b) (first b))
1067 (defun binding-type (b) (second b))
1068 (defun binding-value (b) (third b))
1069 (defun binding-declarations (b) (fourth b))
1071 (defun set-binding-value (b value)
1072 (rplaca (cddr b) value))
1074 (defun set-binding-declarations (b value)
1075 (rplaca (cdddr b) value))
1077 (defun push-binding-declaration (decl b)
1078 (set-binding-declarations b (cons decl (binding-declarations b))))
1081 (defun make-lexenv ()
1082 (list nil nil nil nil))
1084 (defun copy-lexenv (lexenv)
1087 (defun push-to-lexenv (binding lexenv namespace)
1089 (variable (rplaca lexenv (cons binding (car lexenv))))
1090 (function (rplaca (cdr lexenv) (cons binding (cadr lexenv))))
1091 (block (rplaca (cddr lexenv) (cons binding (caddr lexenv))))
1092 (gotag (rplaca (cdddr lexenv) (cons binding (cadddr lexenv))))))
1094 (defun extend-lexenv (bindings lexenv namespace)
1095 (let ((env (copy-lexenv lexenv)))
1096 (dolist (binding (reverse bindings) env)
1097 (push-to-lexenv binding env namespace))))
1099 (defun lookup-in-lexenv (name lexenv namespace)
1100 (assoc name (ecase namespace
1101 (variable (first lexenv))
1102 (function (second lexenv))
1103 (block (third lexenv))
1104 (gotag (fourth lexenv)))))
1106 (defvar *environment* (make-lexenv))
1108 (defvar *variable-counter* 0)
1109 (defun gvarname (symbol)
1110 (concat "v" (integer-to-string (incf *variable-counter*))))
1112 (defun translate-variable (symbol)
1113 (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
1115 (defun extend-local-env (args)
1116 (let ((new (copy-lexenv *environment*)))
1117 (dolist (symbol args new)
1118 (let ((b (make-binding symbol 'variable (gvarname symbol))))
1119 (push-to-lexenv b new 'variable)))))
1121 ;;; Toplevel compilations
1122 (defvar *toplevel-compilations* nil)
1124 (defun toplevel-compilation (string)
1125 (push string *toplevel-compilations*))
1127 (defun null-or-empty-p (x)
1130 (defun get-toplevel-compilations ()
1131 (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
1133 (defun %compile-defmacro (name lambda)
1134 (toplevel-compilation (ls-compile `',name))
1135 (push-to-lexenv (make-binding name 'macro lambda) *environment* 'function)
1138 (defun global-binding (name type namespace)
1139 (or (lookup-in-lexenv name *environment* namespace)
1140 (let ((b (make-binding name type nil)))
1141 (push-to-lexenv b *environment* namespace)
1144 (defun claimp (symbol namespace claim)
1145 (let ((b (lookup-in-lexenv symbol *environment* namespace)))
1146 (and b (member claim (binding-declarations b)))))
1148 (defun !proclaim (decl)
1151 (dolist (name (cdr decl))
1152 (let ((b (global-binding name 'variable 'variable)))
1153 (push-binding-declaration 'special b))))
1155 (dolist (name (cdr decl))
1156 (let ((b (global-binding name 'function 'function)))
1157 (push-binding-declaration 'notinline b))))
1159 (dolist (name (cdr decl))
1160 (let ((b (global-binding name 'variable 'variable)))
1161 (push-binding-declaration 'constant b))))))
1164 (fset 'proclaim #'!proclaim)
1168 (defvar *compilations* nil)
1170 (defmacro define-compilation (name args &body body)
1171 ;; Creates a new primitive `name' with parameters args and
1172 ;; @body. The body can access to the local environment through the
1173 ;; variable *ENVIRONMENT*.
1174 `(push (list ',name (lambda ,args (block ,name ,@body)))
1177 (define-compilation if (condition true false)
1178 (concat "(" (ls-compile condition) " !== " (ls-compile nil)
1179 " ? " (ls-compile true *multiple-value-p*)
1180 " : " (ls-compile false *multiple-value-p*)
1183 (defvar *lambda-list-keywords* '(&optional &rest))
1185 (defun list-until-keyword (list)
1186 (if (or (null list) (member (car list) *lambda-list-keywords*))
1188 (cons (car list) (list-until-keyword (cdr list)))))
1190 (defun lambda-list-required-arguments (lambda-list)
1191 (list-until-keyword lambda-list))
1193 (defun lambda-list-optional-arguments-with-default (lambda-list)
1194 (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
1196 (defun lambda-list-optional-arguments (lambda-list)
1197 (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
1199 (defun lambda-list-rest-argument (lambda-list)
1200 (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
1202 (error "Bad lambda-list"))
1205 (defun lambda-docstring-wrapper (docstring &rest strs)
1208 "var func = " (join strs) ";" *newline*
1209 "func.docstring = '" docstring "';" *newline*
1210 "return func;" *newline*)
1213 (defun lambda-check-argument-count
1214 (n-required-arguments n-optional-arguments rest-p)
1215 ;; Note: Remember that we assume that the number of arguments of a
1216 ;; call is at least 1 (the values argument).
1217 (let ((min (1+ n-required-arguments))
1218 (max (if rest-p 'n/a (+ 1 n-required-arguments n-optional-arguments))))
1220 ;; Special case: a positive exact number of arguments.
1221 (when (and (< 1 min) (eql min max))
1222 (return (concat "checkArgs(arguments, " (integer-to-string min) ");" *newline*)))
1226 (concat "checkArgsAtLeast(arguments, " (integer-to-string min) ");" *newline*)
1229 (concat "checkArgsAtMost(arguments, " (integer-to-string max) ");" *newline*)
1232 (defun compile-lambda (lambda-list body)
1233 (let ((required-arguments (lambda-list-required-arguments lambda-list))
1234 (optional-arguments (lambda-list-optional-arguments lambda-list))
1235 (rest-argument (lambda-list-rest-argument lambda-list))
1237 ;; Get the documentation string for the lambda function
1238 (when (and (stringp (car body))
1239 (not (null (cdr body))))
1240 (setq documentation (car body))
1241 (setq body (cdr body)))
1242 (let ((n-required-arguments (length required-arguments))
1243 (n-optional-arguments (length optional-arguments))
1244 (*environment* (extend-local-env
1245 (append (ensure-list rest-argument)
1247 optional-arguments))))
1248 (lambda-docstring-wrapper
1251 (join (cons "values"
1252 (mapcar #'translate-variable
1253 (append required-arguments optional-arguments)))
1257 ;; Check number of arguments
1258 (lambda-check-argument-count n-required-arguments
1259 n-optional-arguments
1261 ;; Optional arguments
1262 (if optional-arguments
1263 (concat "switch(arguments.length-1){" *newline*
1264 (let ((optional-and-defaults
1265 (lambda-list-optional-arguments-with-default lambda-list))
1269 (while (< idx n-optional-arguments)
1270 (let ((arg (nth idx optional-and-defaults)))
1271 (push (concat "case "
1272 (integer-to-string (+ idx n-required-arguments)) ":" *newline*
1273 (translate-variable (car arg))
1275 (ls-compile (cadr arg))
1279 (push (concat "default: break;" *newline*) cases)
1280 (join (reverse cases))))
1283 ;; &rest/&body argument
1285 (let ((js!rest (translate-variable rest-argument)))
1286 (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
1287 "for (var i = arguments.length-1; i>="
1288 (integer-to-string (+ 1 n-required-arguments n-optional-arguments))
1290 (indent js!rest " = "
1291 "{car: arguments[i], cdr: ") js!rest "};"
1295 (let ((*multiple-value-p* t)) (ls-compile-block body t)))
1299 (defun setq-pair (var val)
1300 (let ((b (lookup-in-lexenv var *environment* 'variable)))
1301 (if (and (eq (binding-type b) 'variable)
1302 (not (member 'special (binding-declarations b)))
1303 (not (member 'constant (binding-declarations b))))
1304 (concat (binding-value b) " = " (ls-compile val))
1305 (ls-compile `(set ',var ,val)))))
1307 (define-compilation setq (&rest pairs)
1311 ((null pairs) (return))
1313 (error "Odd paris in SETQ"))
1316 (concat (setq-pair (car pairs) (cadr pairs))
1317 (if (null (cddr pairs)) "" ", ")))
1318 (setq pairs (cddr pairs)))))
1319 (concat "(" result ")")))
1321 ;;; FFI Variable accessors
1322 (define-compilation js-vref (var)
1325 (define-compilation js-vset (var val)
1326 (concat "(" var " = " (ls-compile val) ")"))
1331 (defun escape-string (string)
1334 (size (length string)))
1335 (while (< index size)
1336 (let ((ch (char string index)))
1337 (when (or (char= ch #\") (char= ch #\\))
1338 (setq output (concat output "\\")))
1339 (when (or (char= ch #\newline))
1340 (setq output (concat output "\\"))
1342 (setq output (concat output (string ch))))
1347 (defvar *literal-symbols* nil)
1348 (defvar *literal-counter* 0)
1351 (concat "l" (integer-to-string (incf *literal-counter*))))
1353 (defun literal (sexp &optional recursive)
1355 ((integerp sexp) (integer-to-string sexp))
1356 ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1358 (or (cdr (assoc sexp *literal-symbols*))
1361 (let ((package (symbol-package sexp)))
1362 (if (eq package (find-package "KEYWORD"))
1363 (concat "{name: \"" (escape-string (symbol-name sexp))
1364 "\", 'package': '" (package-name package) "'}")
1365 (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")))
1367 (let ((package (symbol-package sexp)))
1369 (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1370 (ls-compile `(intern ,(symbol-name sexp) ,(package-name package)))))))
1371 (push (cons sexp v) *literal-symbols*)
1372 (toplevel-compilation (concat "var " v " = " s))
1375 (let* ((head (butlast sexp))
1377 (c (concat "QIList("
1378 (join-trailing (mapcar (lambda (x) (literal x t)) head) ",")
1379 (literal (car tail) t)
1381 (literal (cdr tail) t)
1386 (toplevel-compilation (concat "var " v " = " c))
1389 (let ((elements (vector-to-list sexp)))
1390 (let ((c (concat "[" (join (mapcar #'literal elements) ", ") "]")))
1394 (toplevel-compilation (concat "var " v " = " c))
1397 (define-compilation quote (sexp)
1400 (define-compilation %while (pred &rest body)
1402 "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1403 (indent (ls-compile-block body))
1405 "return " (ls-compile nil) ";" *newline*))
1407 (define-compilation function (x)
1409 ((and (listp x) (eq (car x) 'lambda))
1410 (compile-lambda (cadr x) (cddr x)))
1412 (let ((b (lookup-in-lexenv x *environment* 'function)))
1415 (ls-compile `(symbol-function ',x)))))))
1418 (defun make-function-binding (fname)
1419 (make-binding fname 'function (gvarname fname)))
1421 (defun compile-function-definition (list)
1422 (compile-lambda (car list) (cdr list)))
1424 (defun translate-function (name)
1425 (let ((b (lookup-in-lexenv name *environment* 'function)))
1428 (define-compilation flet (definitions &rest body)
1429 (let* ((fnames (mapcar #'car definitions))
1430 (fbody (mapcar #'cdr definitions))
1431 (cfuncs (mapcar #'compile-function-definition fbody))
1433 (extend-lexenv (mapcar #'make-function-binding fnames)
1436 (concat "(function("
1437 (join (mapcar #'translate-function fnames) ",")
1439 (let ((body (ls-compile-block body t)))
1441 "})(" (join cfuncs ",") ")")))
1443 (define-compilation labels (definitions &rest body)
1444 (let* ((fnames (mapcar #'car definitions))
1446 (extend-lexenv (mapcar #'make-function-binding fnames)
1450 (mapconcat (lambda (func)
1451 (concat "var " (translate-function (car func))
1452 " = " (compile-lambda (cadr func) (cddr func))
1455 (ls-compile-block body t))))
1459 (defvar *compiling-file* nil)
1460 (define-compilation eval-when-compile (&rest body)
1461 (if *compiling-file*
1463 (eval (cons 'progn body))
1465 (ls-compile `(progn ,@body))))
1467 (defmacro define-transformation (name args form)
1468 `(define-compilation ,name ,args
1469 (ls-compile ,form)))
1471 (define-compilation progn (&rest body)
1472 (if (null (cdr body))
1473 (ls-compile (car body) *multiple-value-p*)
1474 (js!selfcall (ls-compile-block body t))))
1476 (defun special-variable-p (x)
1477 (and (claimp x 'variable 'special) t))
1479 ;;; Wrap CODE to restore the symbol values of the dynamic
1480 ;;; bindings. BINDINGS is a list of pairs of the form
1481 ;;; (SYMBOL . PLACE), where PLACE is a Javascript variable
1482 ;;; name to initialize the symbol value and where to stored
1484 (defun let-binding-wrapper (bindings body)
1485 (when (null bindings)
1486 (return-from let-binding-wrapper body))
1489 (indent "var tmp;" *newline*
1492 (let ((s (ls-compile `(quote ,(car b)))))
1493 (concat "tmp = " s ".value;" *newline*
1494 s ".value = " (cdr b) ";" *newline*
1495 (cdr b) " = tmp;" *newline*)))
1499 "finally {" *newline*
1501 (mapconcat (lambda (b)
1502 (let ((s (ls-compile `(quote ,(car b)))))
1503 (concat s ".value" " = " (cdr b) ";" *newline*)))
1507 (define-compilation let (bindings &rest body)
1508 (let* ((bindings (mapcar #'ensure-list bindings))
1509 (variables (mapcar #'first bindings))
1510 (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
1511 (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
1513 (concat "(function("
1514 (join (mapcar (lambda (x)
1515 (if (special-variable-p x)
1516 (let ((v (gvarname x)))
1517 (push (cons x v) dynamic-bindings)
1519 (translate-variable x)))
1523 (let ((body (ls-compile-block body t)))
1524 (indent (let-binding-wrapper dynamic-bindings body)))
1525 "})(" (join cvalues ",") ")")))
1528 ;;; Return the code to initialize BINDING, and push it extending the
1529 ;;; current lexical environment if the variable is not special.
1530 (defun let*-initialize-value (binding)
1531 (let ((var (first binding))
1532 (value (second binding)))
1533 (if (special-variable-p var)
1534 (concat (ls-compile `(setq ,var ,value)) ";" *newline*)
1535 (let* ((v (gvarname var))
1536 (b (make-binding var 'variable v)))
1537 (prog1 (concat "var " v " = " (ls-compile value) ";" *newline*)
1538 (push-to-lexenv b *environment* 'variable))))))
1540 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
1541 ;;; DOES NOT generate code to initialize the value of the symbols,
1542 ;;; unlike let-binding-wrapper.
1543 (defun let*-binding-wrapper (symbols body)
1544 (when (null symbols)
1545 (return-from let*-binding-wrapper body))
1546 (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
1547 (remove-if-not #'special-variable-p symbols))))
1551 (mapconcat (lambda (b)
1552 (let ((s (ls-compile `(quote ,(car b)))))
1553 (concat "var " (cdr b) " = " s ".value;" *newline*)))
1557 "finally {" *newline*
1559 (mapconcat (lambda (b)
1560 (let ((s (ls-compile `(quote ,(car b)))))
1561 (concat s ".value" " = " (cdr b) ";" *newline*)))
1565 (define-compilation let* (bindings &rest body)
1566 (let ((bindings (mapcar #'ensure-list bindings))
1567 (*environment* (copy-lexenv *environment*)))
1569 (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
1570 (body (concat (mapconcat #'let*-initialize-value bindings)
1571 (ls-compile-block body t))))
1572 (let*-binding-wrapper specials body)))))
1575 (defvar *block-counter* 0)
1577 (define-compilation block (name &rest body)
1578 (let* ((tr (integer-to-string (incf *block-counter*)))
1579 (b (make-binding name 'block tr)))
1580 (when *multiple-value-p*
1581 (push-binding-declaration 'multiple-value b))
1582 (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
1583 (cbody (ls-compile-block body t)))
1584 (if (member 'used (binding-declarations b))
1589 "catch (cf){" *newline*
1590 " if (cf.type == 'block' && cf.id == " tr ")" *newline*
1591 (if *multiple-value-p*
1592 " return values.apply(this, forcemv(cf.values));"
1593 " return cf.values;")
1596 " throw cf;" *newline*
1598 (js!selfcall cbody)))))
1600 (define-compilation return-from (name &optional value)
1601 (let* ((b (lookup-in-lexenv name *environment* 'block))
1602 (multiple-value-p (member 'multiple-value (binding-declarations b))))
1604 (error (concat "Unknown block `" (symbol-name name) "'.")))
1605 (push-binding-declaration 'used b)
1607 (if multiple-value-p
1608 (concat "var values = mv;" *newline*)
1612 "id: " (binding-value b) ", "
1613 "values: " (ls-compile value multiple-value-p) ", "
1614 "message: 'Return from unknown block " (symbol-name name) ".'"
1617 (define-compilation catch (id &rest body)
1619 "var id = " (ls-compile id) ";" *newline*
1621 (indent (ls-compile-block body t)) *newline*
1623 "catch (cf){" *newline*
1624 " if (cf.type == 'catch' && cf.id == id)" *newline*
1625 (if *multiple-value-p*
1626 " return values.apply(this, forcemv(cf.values));"
1627 " return pv.apply(this, forcemv(cf.values));")
1630 " throw cf;" *newline*
1633 (define-compilation throw (id value)
1635 "var values = mv;" *newline*
1638 "id: " (ls-compile id) ", "
1639 "values: " (ls-compile value t) ", "
1640 "message: 'Throw uncatched.'"
1644 (defvar *tagbody-counter* 0)
1645 (defvar *go-tag-counter* 0)
1648 (or (integerp x) (symbolp x)))
1650 (defun declare-tagbody-tags (tbidx body)
1652 (mapcar (lambda (label)
1653 (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1654 (make-binding label 'gotag (list tbidx tagidx))))
1655 (remove-if-not #'go-tag-p body))))
1656 (extend-lexenv bindings *environment* 'gotag)))
1658 (define-compilation tagbody (&rest body)
1659 ;; Ignore the tagbody if it does not contain any go-tag. We do this
1660 ;; because 1) it is easy and 2) many built-in forms expand to a
1661 ;; implicit tagbody, so we save some space.
1662 (unless (some #'go-tag-p body)
1663 (return-from tagbody (ls-compile `(progn ,@body nil))))
1664 ;; The translation assumes the first form in BODY is a label
1665 (unless (go-tag-p (car body))
1666 (push (gensym "START") body))
1667 ;; Tagbody compilation
1668 (let ((tbidx (integer-to-string *tagbody-counter*)))
1669 (let ((*environment* (declare-tagbody-tags tbidx body))
1671 (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1672 (setq initag (second (binding-value b))))
1674 "var tagbody_" tbidx " = " initag ";" *newline*
1676 "while (true) {" *newline*
1677 (indent "try {" *newline*
1678 (indent (let ((content ""))
1679 (concat "switch(tagbody_" tbidx "){" *newline*
1680 "case " initag ":" *newline*
1681 (dolist (form (cdr body) content)
1683 (if (not (go-tag-p form))
1684 (indent (ls-compile form) ";" *newline*)
1685 (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1686 (concat "case " (second (binding-value b)) ":" *newline*)))))
1687 "default:" *newline*
1688 " break tbloop;" *newline*
1691 "catch (jump) {" *newline*
1692 " if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1693 " tagbody_" tbidx " = jump.label;" *newline*
1695 " throw(jump);" *newline*
1698 "return " (ls-compile nil) ";" *newline*))))
1700 (define-compilation go (label)
1701 (let ((b (lookup-in-lexenv label *environment* 'gotag))
1703 ((symbolp label) (symbol-name label))
1704 ((integerp label) (integer-to-string label)))))
1709 "id: " (first (binding-value b)) ", "
1710 "label: " (second (binding-value b)) ", "
1711 "message: 'Attempt to GO to non-existing tag " n "'"
1713 (error (concat "Unknown tag `" n "'.")))))
1715 (define-compilation unwind-protect (form &rest clean-up)
1717 "var ret = " (ls-compile nil) ";" *newline*
1719 (indent "ret = " (ls-compile form) ";" *newline*)
1720 "} finally {" *newline*
1721 (indent (ls-compile-block clean-up))
1723 "return ret;" *newline*))
1725 (define-compilation multiple-value-call (func-form &rest forms)
1727 "var func = " (ls-compile func-form) ";" *newline*
1728 "var args = [" (if *multiple-value-p* "values" "pv") "];" *newline*
1731 "var values = mv;" *newline*
1733 (mapconcat (lambda (form)
1734 (concat "vs = " (ls-compile form t) ";" *newline*
1735 "if (typeof vs === 'object' && 'multiple-value' in vs)" *newline*
1736 (indent "args = args.concat(vs);" *newline*)
1738 (indent "args.push(vs);" *newline*)))
1740 "return func.apply(window, args);" *newline*) ";" *newline*))
1742 (define-compilation multiple-value-prog1 (first-form &rest forms)
1744 "var args = " (ls-compile first-form *multiple-value-p*) ";" *newline*
1745 (ls-compile-block forms)
1746 "return args;" *newline*))
1750 ;;; A little backquote implementation without optimizations of any
1751 ;;; kind for ecmalisp.
1752 (defun backquote-expand-1 (form)
1758 ((eq (car form) 'unquote)
1760 ((eq (car form) 'backquote)
1761 (backquote-expand-1 (backquote-expand-1 (cadr form))))
1766 ((and (listp s) (eq (car s) 'unquote))
1767 (list 'list (cadr s)))
1768 ((and (listp s) (eq (car s) 'unquote-splicing))
1771 (list 'list (backquote-expand-1 s)))))
1774 (defun backquote-expand (form)
1775 (if (and (listp form) (eq (car form) 'backquote))
1776 (backquote-expand-1 (cadr form))
1779 (defmacro backquote (form)
1780 (backquote-expand-1 form))
1782 (define-transformation backquote (form)
1783 (backquote-expand-1 form))
1787 (defvar *builtins* nil)
1789 (defmacro define-raw-builtin (name args &body body)
1790 ;; Creates a new primitive function `name' with parameters args and
1791 ;; @body. The body can access to the local environment through the
1792 ;; variable *ENVIRONMENT*.
1793 `(push (list ',name (lambda ,args (block ,name ,@body)))
1796 (defmacro define-builtin (name args &body body)
1798 (define-raw-builtin ,name ,args
1799 (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1802 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1803 (defmacro type-check (decls &body body)
1805 ,@(mapcar (lambda (decl)
1806 `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1808 ,@(mapcar (lambda (decl)
1809 `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1810 (indent "throw 'The value ' + "
1812 " + ' is not a type "
1817 (concat "return " (progn ,@body) ";" *newline*)))
1819 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
1820 ;;; a variable which holds a list of forms. It will compile them and
1821 ;;; store the result in some Javascript variables. BODY is evaluated
1822 ;;; with ARGS bound to the list of these variables to generate the
1823 ;;; code which performs the transformation on these variables.
1825 (defun variable-arity-call (args function)
1826 (unless (consp args)
1827 (error "ARGS must be a non-empty list"))
1832 (let ((v (concat "x" (integer-to-string (incf counter)))))
1835 (concat "var " v " = " (ls-compile x) ";" *newline*
1836 "if (typeof " v " !== 'number') throw 'Not a number!';"
1838 (js!selfcall prelude (funcall function (reverse variables)))))
1841 (defmacro variable-arity (args &body body)
1842 (unless (symbolp args)
1843 (error "Bad usage of VARIABLE-ARITY, you must pass a symbol"))
1844 `(variable-arity-call ,args
1846 (concat "return " ,@body ";" *newline*))))
1848 (defun num-op-num (x op y)
1849 (type-check (("x" "number" x) ("y" "number" y))
1850 (concat "x" op "y")))
1852 (define-raw-builtin + (&rest numbers)
1855 (variable-arity numbers
1856 (join numbers "+"))))
1858 (define-raw-builtin - (x &rest others)
1859 (let ((args (cons x others)))
1860 (variable-arity args
1862 (concat "-" (car args))
1865 (define-raw-builtin * (&rest numbers)
1868 (variable-arity numbers
1869 (join numbers "*"))))
1871 (define-raw-builtin / (x &rest others)
1872 (let ((args (cons x others)))
1873 (variable-arity args
1875 (concat "1 /" (car args))
1878 (define-builtin mod (x y) (num-op-num x "%" y))
1881 (defun comparison-conjuntion (vars op)
1886 (concat (car vars) op (cadr vars)))
1888 (concat (car vars) op (cadr vars)
1890 (comparison-conjuntion (cdr vars) op)))))
1892 (defmacro define-builtin-comparison (op sym)
1893 `(define-raw-builtin ,op (x &rest args)
1894 (let ((args (cons x args)))
1895 (variable-arity args
1896 (js!bool (comparison-conjuntion args ,sym))))))
1898 (define-builtin-comparison > ">")
1899 (define-builtin-comparison < "<")
1900 (define-builtin-comparison >= ">=")
1901 (define-builtin-comparison <= "<=")
1902 (define-builtin-comparison = "==")
1904 (define-builtin numberp (x)
1905 (js!bool (concat "(typeof (" x ") == \"number\")")))
1907 (define-builtin floor (x)
1908 (type-check (("x" "number" x))
1911 (define-builtin cons (x y)
1912 (concat "({car: " x ", cdr: " y "})"))
1914 (define-builtin consp (x)
1917 "var tmp = " x ";" *newline*
1918 "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1920 (define-builtin car (x)
1922 "var tmp = " x ";" *newline*
1923 "return tmp === " (ls-compile nil)
1924 "? " (ls-compile nil)
1925 ": tmp.car;" *newline*))
1927 (define-builtin cdr (x)
1929 "var tmp = " x ";" *newline*
1930 "return tmp === " (ls-compile nil) "? "
1932 ": tmp.cdr;" *newline*))
1934 (define-builtin rplaca (x new)
1935 (type-check (("x" "object" x))
1936 (concat "(x.car = " new ", x)")))
1938 (define-builtin rplacd (x new)
1939 (type-check (("x" "object" x))
1940 (concat "(x.cdr = " new ", x)")))
1942 (define-builtin symbolp (x)
1945 "var tmp = " x ";" *newline*
1946 "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1948 (define-builtin make-symbol (name)
1949 (type-check (("name" "string" name))
1952 (define-builtin symbol-name (x)
1953 (concat "(" x ").name"))
1955 (define-builtin set (symbol value)
1956 (concat "(" symbol ").value = " value))
1958 (define-builtin fset (symbol value)
1959 (concat "(" symbol ").fvalue = " value))
1961 (define-builtin boundp (x)
1962 (js!bool (concat "(" x ".value !== undefined)")))
1964 (define-builtin symbol-value (x)
1966 "var symbol = " x ";" *newline*
1967 "var value = symbol.value;" *newline*
1968 "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1969 "return value;" *newline*))
1971 (define-builtin symbol-function (x)
1973 "var symbol = " x ";" *newline*
1974 "var func = symbol.fvalue;" *newline*
1975 "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1976 "return func;" *newline*))
1978 (define-builtin symbol-plist (x)
1979 (concat "((" x ").plist || " (ls-compile nil) ")"))
1981 (define-builtin lambda-code (x)
1982 (concat "(" x ").toString()"))
1984 (define-builtin eq (x y) (js!bool (concat "(" x " === " y ")")))
1985 (define-builtin equal (x y) (js!bool (concat "(" x " == " y ")")))
1987 (define-builtin char-to-string (x)
1988 (type-check (("x" "number" x))
1989 "String.fromCharCode(x)"))
1991 (define-builtin stringp (x)
1992 (js!bool (concat "(typeof(" x ") == \"string\")")))
1994 (define-builtin string-upcase (x)
1995 (type-check (("x" "string" x))
1998 (define-builtin string-length (x)
1999 (type-check (("x" "string" x))
2002 (define-raw-builtin slice (string a &optional b)
2004 "var str = " (ls-compile string) ";" *newline*
2005 "var a = " (ls-compile a) ";" *newline*
2008 (concat "b = " (ls-compile b) ";" *newline*)
2010 "return str.slice(a,b);" *newline*))
2012 (define-builtin char (string index)
2013 (type-check (("string" "string" string)
2014 ("index" "number" index))
2015 "string.charCodeAt(index)"))
2017 (define-builtin concat-two (string1 string2)
2018 (type-check (("string1" "string" string1)
2019 ("string2" "string" string2))
2020 "string1.concat(string2)"))
2022 (define-raw-builtin funcall (func &rest args)
2023 (concat "(" (ls-compile func) ")("
2024 (join (cons (if *multiple-value-p* "values" "pv")
2025 (mapcar #'ls-compile args))
2029 (define-raw-builtin apply (func &rest args)
2031 (concat "(" (ls-compile func) ")()")
2032 (let ((args (butlast args))
2033 (last (car (last args))))
2035 "var f = " (ls-compile func) ";" *newline*
2036 "var args = [" (join (cons (if *multiple-value-p* "values" "pv")
2037 (mapcar #'ls-compile args))
2040 "var tail = (" (ls-compile last) ");" *newline*
2041 "while (tail != " (ls-compile nil) "){" *newline*
2042 " args.push(tail.car);" *newline*
2043 " tail = tail.cdr;" *newline*
2045 "return f.apply(this, args);" *newline*))))
2047 (define-builtin js-eval (string)
2048 (type-check (("string" "string" string))
2049 (if *multiple-value-p*
2051 "var v = eval.apply(window, [string]);" *newline*
2052 "if (typeof v !== 'object' || !('multiple-value' in v)){" *newline*
2053 (indent "v = [v];" *newline*
2054 "v['multiple-value'] = true;" *newline*)
2056 "return values.apply(this, v);" *newline*)
2057 "eval.apply(window, [string])")))
2059 (define-builtin error (string)
2060 (js!selfcall "throw " string ";" *newline*))
2062 (define-builtin new () "{}")
2064 (define-builtin objectp (x)
2065 (js!bool (concat "(typeof (" x ") === 'object')")))
2067 (define-builtin oget (object key)
2069 "var tmp = " "(" object ")[" key "];" *newline*
2070 "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
2072 (define-builtin oset (object key value)
2073 (concat "((" object ")[" key "] = " value ")"))
2075 (define-builtin in (key object)
2076 (js!bool (concat "((" key ") in (" object "))")))
2078 (define-builtin functionp (x)
2079 (js!bool (concat "(typeof " x " == 'function')")))
2081 (define-builtin write-string (x)
2082 (type-check (("x" "string" x))
2085 (define-builtin make-array (n)
2087 "var r = [];" *newline*
2088 "for (var i = 0; i < " n "; i++)" *newline*
2089 (indent "r.push(" (ls-compile nil) ");" *newline*)
2090 "return r;" *newline*))
2092 (define-builtin arrayp (x)
2095 "var x = " x ";" *newline*
2096 "return typeof x === 'object' && 'length' in x;")))
2098 (define-builtin aref (array n)
2100 "var x = " "(" array ")[" n "];" *newline*
2101 "if (x === undefined) throw 'Out of range';" *newline*
2102 "return x;" *newline*))
2104 (define-builtin aset (array n value)
2106 "var x = " array ";" *newline*
2107 "var i = " n ";" *newline*
2108 "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
2109 "return x[i] = " value ";" *newline*))
2111 (define-builtin get-unix-time ()
2112 (concat "(Math.round(new Date() / 1000))"))
2114 (define-builtin values-array (array)
2115 (if *multiple-value-p*
2116 (concat "values.apply(this, " array ")")
2117 (concat "pv.apply(this, " array ")")))
2119 (define-raw-builtin values (&rest args)
2120 (if *multiple-value-p*
2121 (concat "values(" (join (mapcar #'ls-compile args) ", ") ")")
2122 (concat "pv(" (join (mapcar #'ls-compile args) ", ") ")")))
2126 (let ((b (lookup-in-lexenv x *environment* 'function)))
2127 (and (eq (binding-type b) 'macro)
2130 (defun ls-macroexpand-1 (form)
2131 (let ((macro-binding (macro (car form))))
2133 (let ((expander (binding-value macro-binding)))
2134 (when (listp expander)
2135 (let ((compiled (eval expander)))
2136 ;; The list representation are useful while
2137 ;; bootstrapping, as we can dump the definition of the
2138 ;; macros easily, but they are slow because we have to
2139 ;; evaluate them and compile them now and again. So, let
2140 ;; us replace the list representation version of the
2141 ;; function with the compiled one.
2143 #+ecmalisp (set-binding-value macro-binding compiled)
2144 (setq expander compiled)))
2145 (apply expander (cdr form)))
2148 (defun compile-funcall (function args)
2149 (let* ((values-funcs (if *multiple-value-p* "values" "pv"))
2150 (arglist (concat "(" (join (cons values-funcs (mapcar #'ls-compile args)) ", ") ")")))
2152 ((translate-function function)
2153 (concat (translate-function function) arglist))
2154 ((and (symbolp function)
2155 #+ecmalisp (eq (symbol-package function) (find-package "COMMON-LISP"))
2157 (concat (ls-compile `',function) ".fvalue" arglist))
2159 (concat (ls-compile `#',function) arglist)))))
2161 (defun ls-compile-block (sexps &optional return-last-p)
2163 (concat (ls-compile-block (butlast sexps))
2164 "return " (ls-compile (car (last sexps)) *multiple-value-p*) ";")
2166 (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
2167 (concat ";" *newline*))))
2169 (defun ls-compile (sexp &optional multiple-value-p)
2170 (let ((*multiple-value-p* multiple-value-p))
2173 (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
2175 ((and b (not (member 'special (binding-declarations b))))
2177 ((or (keywordp sexp)
2178 (member 'constant (binding-declarations b)))
2179 (concat (ls-compile `',sexp) ".value"))
2181 (ls-compile `(symbol-value ',sexp))))))
2182 ((integerp sexp) (integer-to-string sexp))
2183 ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
2184 ((arrayp sexp) (literal sexp))
2186 (let ((name (car sexp))
2190 ((assoc name *compilations*)
2191 (let ((comp (second (assoc name *compilations*))))
2193 ;; Built-in functions
2194 ((and (assoc name *builtins*)
2195 (not (claimp name 'function 'notinline)))
2196 (let ((comp (second (assoc name *builtins*))))
2200 (ls-compile (ls-macroexpand-1 sexp) multiple-value-p)
2201 (compile-funcall name args))))))
2203 (error "How should I compile this?")))))
2205 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
2206 (let ((*toplevel-compilations* nil))
2208 ((and (consp sexp) (eq (car sexp) 'progn))
2209 (let ((subs (mapcar (lambda (s)
2210 (ls-compile-toplevel s t))
2212 (join (remove-if #'null-or-empty-p subs))))
2214 (let ((code (ls-compile sexp multiple-value-p)))
2215 (concat (join-trailing (get-toplevel-compilations)
2216 (concat ";" *newline*))
2218 (concat code ";" *newline*)
2222 ;;; Once we have the compiler, we define the runtime environment and
2223 ;;; interactive development (eval), which works calling the compiler
2224 ;;; and evaluating the Javascript result globally.
2229 (js-eval (ls-compile-toplevel x t)))
2231 (export '(&rest &optional &body * *gensym-counter* *package* + - / 1+ 1- < <= =
2232 = > >= and append apply aref arrayp aset assoc atom block boundp
2233 boundp butlast caar cadddr caddr cadr car car case catch cdar cdddr
2234 cddr cdr cdr char char-code char= code-char cond cons consp copy-list
2235 decf declaim defparameter defun defmacro defvar digit-char-p
2236 disassemble do do* documentation dolist dotimes ecase eq eql equal
2237 error eval every export fdefinition find-package find-symbol first
2238 flet fourth fset funcall function functionp gensym get-universal-time
2239 go identity if in-package incf integerp integerp intern keywordp labels
2240 lambda last length let let* list-all-packages list listp make-array
2241 make-package make-symbol mapcar member minusp mod multiple-value-bind
2242 multiple-value-call multiple-value-list multiple-value-prog1 nil not
2243 nth nthcdr null numberp or package-name package-use-list packagep
2244 parse-integer plusp prin1-to-string print proclaim prog1 prog2 progn
2245 psetq push quote remove remove-if remove-if-not return return-from
2246 revappend reverse rplaca rplacd second set setq some string-upcase
2247 string string= stringp subseq symbol-function symbol-name symbol-package
2248 symbol-plist symbol-value symbolp t tagbody third throw truncate
2249 unless unwind-protect values values-list variable warn when write-line
2250 write-string zerop))
2252 (setq *package* *user-package*)
2254 (js-eval "var lisp")
2255 (js-vset "lisp" (new))
2256 (js-vset "lisp.read" #'ls-read-from-string)
2257 (js-vset "lisp.print" #'prin1-to-string)
2258 (js-vset "lisp.eval" #'eval)
2259 (js-vset "lisp.compile" (lambda (s) (ls-compile-toplevel s t)))
2260 (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
2261 (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str) t)))
2263 ;; Set the initial global environment to be equal to the host global
2264 ;; environment at this point of the compilation.
2266 (toplevel-compilation
2269 ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
2271 (setq *literal-symbols* ',*literal-symbols*)
2272 (setq *environment* ',*environment*)
2273 (setq *variable-counter* ,*variable-counter*)
2274 (setq *gensym-counter* ,*gensym-counter*)
2275 (setq *block-counter* ,*block-counter*)))))
2278 (toplevel-compilation
2280 `(setq *literal-counter* ,*literal-counter*)))))
2283 ;;; Finally, we provide a couple of functions to easily bootstrap
2284 ;;; this. It just calls the compiler with this file as input.
2288 (defun read-whole-file (filename)
2289 (with-open-file (in filename)
2290 (let ((seq (make-array (file-length in) :element-type 'character)))
2291 (read-sequence seq in)
2294 (defun ls-compile-file (filename output)
2295 (let ((*compiling-file* t))
2296 (with-open-file (out output :direction :output :if-exists :supersede)
2297 (write-string (read-whole-file "prelude.js") out)
2298 (let* ((source (read-whole-file filename))
2299 (in (make-string-stream source)))
2301 for x = (ls-read in)
2303 for compilation = (ls-compile-toplevel x)
2304 when (plusp (length compilation))
2305 do (write-string compilation out))))))
2308 (setq *environment* (make-lexenv))
2309 (setq *literal-symbols* nil)
2310 (setq *variable-counter* 0
2314 (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))