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)
353 (let* ((head (cons 'sentinel nil))
355 (while (not (null list))
356 (let ((new (cons (funcall func (car list)) nil)))
362 (defun identity (x) x)
364 (defun constantly (x)
369 (mapcar #'identity x))
371 (defun code-char (x) x)
372 (defun char-code (x) x)
373 (defun char= (x y) (= x y))
376 (and (numberp x) (= (floor x) x)))
378 (defun plusp (x) (< 0 x))
379 (defun minusp (x) (< x 0))
382 (or (consp x) (null x)))
384 (defun nthcdr (n list)
385 (while (and (plusp n) list)
387 (setq list (cdr list)))
391 (car (nthcdr n list)))
394 (while (consp (cdr x))
400 (cons (car x) (butlast (cdr x)))))
402 (defun member (x list)
404 (when (eql x (car list))
406 (setq list (cdr list))))
408 (defun remove (x list)
413 (remove x (cdr list)))
415 (cons (car list) (remove x (cdr list))))))
417 (defun remove-if (func list)
421 ((funcall func (car list))
422 (remove-if func (cdr list)))
424 (cons (car list) (remove-if func (cdr list))))))
426 (defun remove-if-not (func list)
430 ((funcall func (car list))
431 (cons (car list) (remove-if-not func (cdr list))))
433 (remove-if-not func (cdr list)))))
435 (defun digit-char-p (x)
436 (if (and (<= #\0 x) (<= x #\9))
440 (defun digit-char (weight)
442 (char "0123456789" weight)))
444 (defun subseq (seq a &optional b)
451 (error "Unsupported argument."))))
453 (defun some (function seq)
458 (while (< index size)
459 (when (funcall function (char seq index))
460 (return-from some t))
465 (when (funcall function x)
468 (error "Unknown sequence."))))
470 (defun every (function seq)
475 (while (< index size)
476 (unless (funcall function (char seq index))
477 (return-from every nil))
482 (unless (funcall function x)
485 (error "Unknown sequence."))))
487 (defun assoc (x alist)
489 (if (eql x (caar alist))
491 (setq alist (cdr alist))))
495 (cond ((stringp x) x)
496 ((symbolp x) (symbol-name x))
497 (t (char-to-string x))))
499 (defun string= (s1 s2)
502 (defun fdefinition (x)
509 (error "Invalid function"))))
511 (defun disassemble (function)
512 (write-line (lambda-code (fdefinition function)))
515 (defun documentation (x type)
516 "Return the documentation of X. TYPE must be the symbol VARIABLE or FUNCTION."
519 (let ((func (fdefinition x)))
520 (oget func "docstring")))
523 (error "Wrong argument type! it should be a symbol"))
526 (defmacro multiple-value-bind (variables value-from &body body)
527 `(multiple-value-call (lambda (&optional ,@variables &rest ,(gensym))
531 (defmacro multiple-value-list (value-from)
532 `(multiple-value-call #'list ,value-from))
536 (defvar *package-list* nil)
538 (defun list-all-packages ()
541 (defun make-package (name &optional use)
542 (let ((package (new))
543 (use (mapcar #'find-package-or-fail use)))
544 (oset package "packageName" name)
545 (oset package "symbols" (new))
546 (oset package "exports" (new))
547 (oset package "use" use)
548 (push package *package-list*)
552 (and (objectp x) (in "symbols" x)))
554 (defun find-package (package-designator)
555 (when (packagep package-designator)
556 (return-from find-package package-designator))
557 (let ((name (string package-designator)))
558 (dolist (package *package-list*)
559 (when (string= (package-name package) name)
562 (defun find-package-or-fail (package-designator)
563 (or (find-package package-designator)
564 (error "Package unknown.")))
566 (defun package-name (package-designator)
567 (let ((package (find-package-or-fail package-designator)))
568 (oget package "packageName")))
570 (defun %package-symbols (package-designator)
571 (let ((package (find-package-or-fail package-designator)))
572 (oget package "symbols")))
574 (defun package-use-list (package-designator)
575 (let ((package (find-package-or-fail package-designator)))
576 (oget package "use")))
578 (defun %package-external-symbols (package-designator)
579 (let ((package (find-package-or-fail package-designator)))
580 (oget package "exports")))
582 (defvar *common-lisp-package*
585 (defvar *user-package*
586 (make-package "CL-USER" (list *common-lisp-package*)))
588 (defvar *keyword-package*
589 (make-package "KEYWORD"))
592 (and (symbolp x) (eq (symbol-package x) *keyword-package*)))
594 (defvar *package* *common-lisp-package*)
596 (defmacro in-package (package-designator)
598 (setq *package* (find-package-or-fail ,package-designator))))
600 ;; This function is used internally to initialize the CL package
601 ;; with the symbols built during bootstrap.
602 (defun %intern-symbol (symbol)
604 (if (in "package" symbol)
605 (find-package-or-fail (oget symbol "package"))
606 *common-lisp-package*))
607 (symbols (%package-symbols package)))
608 (oset symbol "package" package)
609 (when (eq package *keyword-package*)
610 (oset symbol "value" symbol))
611 (oset symbols (symbol-name symbol) symbol)))
613 (defun find-symbol (name &optional (package *package*))
614 (let* ((package (find-package-or-fail package))
615 (externals (%package-external-symbols package))
616 (symbols (%package-symbols package)))
619 (values (oget externals name) :external))
621 (values (oget symbols name) :internal))
623 (dolist (used (package-use-list package) (values nil nil))
624 (let ((exports (%package-external-symbols used)))
625 (when (in name exports)
626 (return (values (oget exports name) :inherit)))))))))
628 (defun intern (name &optional (package *package*))
629 (let ((package (find-package-or-fail package)))
630 (multiple-value-bind (symbol foundp)
631 (find-symbol name package)
633 (values symbol foundp)
634 (let ((symbols (%package-symbols package)))
636 (let ((symbol (make-symbol name)))
637 (oset symbol "package" package)
638 (when (eq package *keyword-package*)
639 (oset symbol "value" symbol)
640 (export (list symbol) package))
641 (oset symbols name symbol)
642 (values symbol nil)))))))
644 (defun symbol-package (symbol)
645 (unless (symbolp symbol)
646 (error "it is not a symbol"))
647 (oget symbol "package"))
649 (defun export (symbols &optional (package *package*))
650 (let ((exports (%package-external-symbols package)))
651 (dolist (symb symbols t)
652 (oset exports (symbol-name symb) symb))))
654 (defun get-universal-time ()
655 (+ (get-unix-time) 2208988800)))
658 ;;; The compiler offers some primitives and special forms which are
659 ;;; not found in Common Lisp, for instance, while. So, we grow Common
660 ;;; Lisp a bit to it can execute the rest of the file.
663 (defmacro while (condition &body body)
668 (defmacro eval-when-compile (&body body)
669 `(eval-when (:compile-toplevel :load-toplevel :execute)
672 (defun concat-two (s1 s2)
673 (concatenate 'string s1 s2))
675 (defun aset (array idx value)
676 (setf (aref array idx) value)))
678 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
679 ;;; from here, this code will compile on both. We define some helper
680 ;;; functions now for string manipulation and so on. They will be
681 ;;; useful in the compiler, mostly.
683 (defvar *newline* (string (code-char 10)))
685 (defun concat (&rest strs)
686 (!reduce #'concat-two strs ""))
688 (defmacro concatf (variable &body form)
689 `(setq ,variable (concat ,variable (progn ,@form))))
691 ;;; Concatenate a list of strings, with a separator
692 (defun join (list &optional (separator ""))
701 (join (cdr list) separator)))))
703 (defun join-trailing (list &optional (separator ""))
706 (concat (car list) separator (join-trailing (cdr list) separator))))
708 (defun mapconcat (func list)
709 (join (mapcar func list)))
711 (defun vector-to-list (vector)
713 (size (length vector)))
714 (dotimes (i size (reverse list))
715 (push (aref vector i) list))))
717 (defun list-to-vector (list)
718 (let ((v (make-array (length list)))
726 (defun values-list (list)
727 (values-array (list-to-vector list)))
729 (defun values (&rest args)
733 ;;; Like CONCAT, but prefix each line with four spaces. Two versions
734 ;;; of this function are available, because the Ecmalisp version is
735 ;;; very slow and bootstraping was annoying.
738 (defun indent (&rest string)
739 (let ((input (join string)))
742 (size (length input)))
743 (when (plusp (length input)) (concatf output " "))
744 (while (< index size)
746 (if (and (char= (char input index) #\newline)
748 (not (char= (char input (1+ index)) #\newline)))
749 (concat (string #\newline) " ")
750 (string (char input index)))))
751 (concatf output str))
756 (defun indent (&rest string)
757 (with-output-to-string (*standard-output*)
758 (with-input-from-string (input (join string))
760 for line = (read-line input nil)
762 do (write-string " ")
763 do (write-line line)))))
765 (defun integer-to-string (x)
770 (concat "-" (integer-to-string (- 0 x))))
773 (while (not (zerop x))
774 (push (mod x 10) digits)
775 (setq x (truncate x 10)))
776 (mapconcat (lambda (x) (string (digit-char x)))
780 ;;; Wrap X with a Javascript code to convert the result from
781 ;;; Javascript generalized booleans to T or NIL.
783 (concat "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
785 ;;; Concatenate the arguments and wrap them with a self-calling
786 ;;; Javascript anonymous function. It is used to make some Javascript
787 ;;; statements valid expressions and provide a private scope as well.
788 ;;; It could be defined as function, but we could do some
789 ;;; preprocessing in the future.
790 (defmacro js!selfcall (&body body)
791 `(concat "(function(){" *newline* (indent ,@body) "})()"))
798 (defun prin1-to-string (form)
801 (multiple-value-bind (symbol foundp)
802 (find-symbol (symbol-name form) *package*)
803 (if (and foundp (eq symbol form))
805 (let ((package (symbol-package form))
806 (name (symbol-name form)))
809 ((eq package (find-package "KEYWORD")) "")
810 (t (package-name package)))
812 ((integerp form) (integer-to-string form))
813 ((stringp form) (concat "\"" (escape-string form) "\""))
815 (let ((name (oget form "fname")))
817 (concat "#<FUNCTION " name ">")
818 (concat "#<FUNCTION>"))))
821 (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
822 (let ((last (last form)))
823 (if (null (cdr last))
824 (prin1-to-string (car last))
825 (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
828 (concat "#" (prin1-to-string (vector-to-list form))))
830 (concat "#<PACKAGE " (package-name form) ">"))))
832 (defun write-line (x)
834 (write-string *newline*)
838 (write-string "WARNING: ")
842 (write-line (prin1-to-string x))
848 ;;; The Lisp reader, parse strings and return Lisp objects. The main
849 ;;; entry points are `ls-read' and `ls-read-from-string'.
851 (defun make-string-stream (string)
854 (defun %peek-char (stream)
855 (and (< (cdr stream) (length (car stream)))
856 (char (car stream) (cdr stream))))
858 (defun %read-char (stream)
859 (and (< (cdr stream) (length (car stream)))
860 (prog1 (char (car stream) (cdr stream))
861 (rplacd stream (1+ (cdr stream))))))
863 (defun whitespacep (ch)
864 (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
866 (defun skip-whitespaces (stream)
868 (setq ch (%peek-char stream))
869 (while (and ch (whitespacep ch))
871 (setq ch (%peek-char stream)))))
873 (defun terminalp (ch)
874 (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
876 (defun read-until (stream func)
879 (setq ch (%peek-char stream))
880 (while (and ch (not (funcall func ch)))
881 (setq string (concat string (string ch)))
883 (setq ch (%peek-char stream)))
886 (defun skip-whitespaces-and-comments (stream)
888 (skip-whitespaces stream)
889 (setq ch (%peek-char stream))
890 (while (and ch (char= ch #\;))
891 (read-until stream (lambda (x) (char= x #\newline)))
892 (skip-whitespaces stream)
893 (setq ch (%peek-char stream)))))
895 (defun %read-list (stream)
896 (skip-whitespaces-and-comments stream)
897 (let ((ch (%peek-char stream)))
900 (error "Unspected EOF"))
906 (prog1 (ls-read stream)
907 (skip-whitespaces-and-comments stream)
908 (unless (char= (%read-char stream) #\))
909 (error "')' was expected."))))
911 (cons (ls-read stream) (%read-list stream))))))
913 (defun read-string (stream)
916 (setq ch (%read-char stream))
917 (while (not (eql ch #\"))
919 (error "Unexpected EOF"))
921 (setq ch (%read-char stream)))
922 (setq string (concat string (string ch)))
923 (setq ch (%read-char stream)))
926 (defun read-sharp (stream)
928 (ecase (%read-char stream)
930 (list 'function (ls-read stream)))
931 (#\( (list-to-vector (%read-list stream)))
932 (#\: (make-symbol (string-upcase (read-until stream #'terminalp))))
935 (concat (string (%read-char stream))
936 (read-until stream #'terminalp))))
938 ((string= cname "space") (char-code #\space))
939 ((string= cname "tab") (char-code #\tab))
940 ((string= cname "newline") (char-code #\newline))
941 (t (char-code (char cname 0))))))
943 (let ((feature (read-until stream #'terminalp)))
945 ((string= feature "common-lisp")
946 (ls-read stream) ;ignore
948 ((string= feature "ecmalisp")
951 (error "Unknown reader form.")))))))
953 ;;; Parse a string of the form NAME, PACKAGE:NAME or
954 ;;; PACKAGE::NAME and return the name. If the string is of the
955 ;;; form 1) or 3), but the symbol does not exist, it will be created
956 ;;; and interned in that package.
957 (defun read-symbol (string)
958 (let ((size (length string))
959 package name internalp index)
961 (while (and (< index size)
962 (not (char= (char string index) #\:)))
968 (setq package *package*)
973 (setq package "KEYWORD")
974 (setq package (string-upcase (subseq string 0 index))))
976 (when (char= (char string index) #\:)
979 (setq name (subseq string index))))
980 ;; Canonalize symbol name and package
981 (setq name (string-upcase name))
982 (setq package (find-package package))
983 ;; TODO: PACKAGE:SYMBOL should signal error if SYMBOL is not an
984 ;; external symbol from PACKAGE.
985 (if (or internalp (eq package (find-package "KEYWORD")))
986 (intern name package)
987 (find-symbol name package))))
990 (defun !parse-integer (string junk-allow)
994 (size (length string))
996 (when (zerop size) (return (values nil 0)))
998 (case (char string 0)
1003 (unless (and (< index size)
1004 (setq value (digit-char-p (char string index))))
1005 (return (values nil index)))
1008 (while (< index size)
1009 (let ((digit (digit-char-p (char string index))))
1010 (unless digit (return))
1011 (setq value (+ (* value 10) digit))
1015 (char= (char string index) #\space))
1016 (values (* sign value) index)
1017 (values nil index)))))
1020 (defun parse-integer (string)
1021 (!parse-integer string nil))
1023 (defvar *eof* (gensym))
1024 (defun ls-read (stream)
1025 (skip-whitespaces-and-comments stream)
1026 (let ((ch (%peek-char stream)))
1028 ((or (null ch) (char= ch #\)))
1032 (%read-list stream))
1035 (list 'quote (ls-read stream)))
1038 (list 'backquote (ls-read stream)))
1041 (read-string stream))
1044 (if (eql (%peek-char stream) #\@)
1045 (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
1046 (list 'unquote (ls-read stream))))
1048 (read-sharp stream))
1050 (let ((string (read-until stream #'terminalp)))
1051 (or (values (!parse-integer string nil))
1052 (read-symbol string)))))))
1054 (defun ls-read-from-string (string)
1055 (ls-read (make-string-stream string)))
1060 ;;; Translate the Lisp code to Javascript. It will compile the special
1061 ;;; forms. Some primitive functions are compiled as special forms
1062 ;;; too. The respective real functions are defined in the target (see
1063 ;;; the beginning of this file) as well as some primitive functions.
1065 ;;; A Form can return a multiple values object calling VALUES, like
1066 ;;; values(arg1, arg2, ...). It will work in any context, as well as
1067 ;;; returning an individual object. However, if the special variable
1068 ;;; `*multiple-value-p*' is NIL, is granted that only the primary
1069 ;;; value will be used, so we can optimize to avoid the VALUES
1071 (defvar *multiple-value-p* nil)
1074 (defun make-binding (name type value &optional declarations)
1075 (list name type value declarations))
1077 (defun binding-name (b) (first b))
1078 (defun binding-type (b) (second b))
1079 (defun binding-value (b) (third b))
1080 (defun binding-declarations (b) (fourth b))
1082 (defun set-binding-value (b value)
1083 (rplaca (cddr b) value))
1085 (defun set-binding-declarations (b value)
1086 (rplaca (cdddr b) value))
1088 (defun push-binding-declaration (decl b)
1089 (set-binding-declarations b (cons decl (binding-declarations b))))
1092 (defun make-lexenv ()
1093 (list nil nil nil nil))
1095 (defun copy-lexenv (lexenv)
1098 (defun push-to-lexenv (binding lexenv namespace)
1100 (variable (rplaca lexenv (cons binding (car lexenv))))
1101 (function (rplaca (cdr lexenv) (cons binding (cadr lexenv))))
1102 (block (rplaca (cddr lexenv) (cons binding (caddr lexenv))))
1103 (gotag (rplaca (cdddr lexenv) (cons binding (cadddr lexenv))))))
1105 (defun extend-lexenv (bindings lexenv namespace)
1106 (let ((env (copy-lexenv lexenv)))
1107 (dolist (binding (reverse bindings) env)
1108 (push-to-lexenv binding env namespace))))
1110 (defun lookup-in-lexenv (name lexenv namespace)
1111 (assoc name (ecase namespace
1112 (variable (first lexenv))
1113 (function (second lexenv))
1114 (block (third lexenv))
1115 (gotag (fourth lexenv)))))
1117 (defvar *environment* (make-lexenv))
1119 (defvar *variable-counter* 0)
1120 (defun gvarname (symbol)
1121 (concat "v" (integer-to-string (incf *variable-counter*))))
1123 (defun translate-variable (symbol)
1124 (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
1126 (defun extend-local-env (args)
1127 (let ((new (copy-lexenv *environment*)))
1128 (dolist (symbol args new)
1129 (let ((b (make-binding symbol 'variable (gvarname symbol))))
1130 (push-to-lexenv b new 'variable)))))
1132 ;;; Toplevel compilations
1133 (defvar *toplevel-compilations* nil)
1135 (defun toplevel-compilation (string)
1136 (push string *toplevel-compilations*))
1138 (defun null-or-empty-p (x)
1141 (defun get-toplevel-compilations ()
1142 (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
1144 (defun %compile-defmacro (name lambda)
1145 (toplevel-compilation (ls-compile `',name))
1146 (push-to-lexenv (make-binding name 'macro lambda) *environment* 'function)
1149 (defun global-binding (name type namespace)
1150 (or (lookup-in-lexenv name *environment* namespace)
1151 (let ((b (make-binding name type nil)))
1152 (push-to-lexenv b *environment* namespace)
1155 (defun claimp (symbol namespace claim)
1156 (let ((b (lookup-in-lexenv symbol *environment* namespace)))
1157 (and b (member claim (binding-declarations b)))))
1159 (defun !proclaim (decl)
1162 (dolist (name (cdr decl))
1163 (let ((b (global-binding name 'variable 'variable)))
1164 (push-binding-declaration 'special b))))
1166 (dolist (name (cdr decl))
1167 (let ((b (global-binding name 'function 'function)))
1168 (push-binding-declaration 'notinline b))))
1170 (dolist (name (cdr decl))
1171 (let ((b (global-binding name 'variable 'variable)))
1172 (push-binding-declaration 'constant b))))))
1175 (fset 'proclaim #'!proclaim)
1179 (defvar *compilations* nil)
1181 (defmacro define-compilation (name args &body body)
1182 ;; Creates a new primitive `name' with parameters args and
1183 ;; @body. The body can access to the local environment through the
1184 ;; variable *ENVIRONMENT*.
1185 `(push (list ',name (lambda ,args (block ,name ,@body)))
1188 (define-compilation if (condition true false)
1189 (concat "(" (ls-compile condition) " !== " (ls-compile nil)
1190 " ? " (ls-compile true *multiple-value-p*)
1191 " : " (ls-compile false *multiple-value-p*)
1194 (defvar *lambda-list-keywords* '(&optional &rest))
1196 (defun list-until-keyword (list)
1197 (if (or (null list) (member (car list) *lambda-list-keywords*))
1199 (cons (car list) (list-until-keyword (cdr list)))))
1201 (defun lambda-list-required-arguments (lambda-list)
1202 (list-until-keyword lambda-list))
1204 (defun lambda-list-optional-arguments-with-default (lambda-list)
1205 (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
1207 (defun lambda-list-optional-arguments (lambda-list)
1208 (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
1210 (defun lambda-list-rest-argument (lambda-list)
1211 (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
1213 (error "Bad lambda-list"))
1216 (defun lambda-docstring-wrapper (docstring &rest strs)
1219 "var func = " (join strs) ";" *newline*
1220 "func.docstring = '" docstring "';" *newline*
1221 "return func;" *newline*)
1224 (defun lambda-check-argument-count
1225 (n-required-arguments n-optional-arguments rest-p)
1226 ;; Note: Remember that we assume that the number of arguments of a
1227 ;; call is at least 1 (the values argument).
1228 (let ((min (1+ n-required-arguments))
1229 (max (if rest-p 'n/a (+ 1 n-required-arguments n-optional-arguments))))
1231 ;; Special case: a positive exact number of arguments.
1232 (when (and (< 1 min) (eql min max))
1233 (return (concat "checkArgs(arguments, " (integer-to-string min) ");" *newline*)))
1237 (concat "checkArgsAtLeast(arguments, " (integer-to-string min) ");" *newline*)
1240 (concat "checkArgsAtMost(arguments, " (integer-to-string max) ");" *newline*)
1243 (defun compile-lambda (lambda-list body)
1244 (let ((required-arguments (lambda-list-required-arguments lambda-list))
1245 (optional-arguments (lambda-list-optional-arguments lambda-list))
1246 (rest-argument (lambda-list-rest-argument lambda-list))
1248 ;; Get the documentation string for the lambda function
1249 (when (and (stringp (car body))
1250 (not (null (cdr body))))
1251 (setq documentation (car body))
1252 (setq body (cdr body)))
1253 (let ((n-required-arguments (length required-arguments))
1254 (n-optional-arguments (length optional-arguments))
1255 (*environment* (extend-local-env
1256 (append (ensure-list rest-argument)
1258 optional-arguments))))
1259 (lambda-docstring-wrapper
1262 (join (cons "values"
1263 (mapcar #'translate-variable
1264 (append required-arguments optional-arguments)))
1268 ;; Check number of arguments
1269 (lambda-check-argument-count n-required-arguments
1270 n-optional-arguments
1272 ;; Optional arguments
1273 (if optional-arguments
1274 (concat "switch(arguments.length-1){" *newline*
1275 (let ((optional-and-defaults
1276 (lambda-list-optional-arguments-with-default lambda-list))
1280 (while (< idx n-optional-arguments)
1281 (let ((arg (nth idx optional-and-defaults)))
1282 (push (concat "case "
1283 (integer-to-string (+ idx n-required-arguments)) ":" *newline*
1284 (translate-variable (car arg))
1286 (ls-compile (cadr arg))
1290 (push (concat "default: break;" *newline*) cases)
1291 (join (reverse cases))))
1294 ;; &rest/&body argument
1296 (let ((js!rest (translate-variable rest-argument)))
1297 (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
1298 "for (var i = arguments.length-1; i>="
1299 (integer-to-string (+ 1 n-required-arguments n-optional-arguments))
1301 (indent js!rest " = "
1302 "{car: arguments[i], cdr: ") js!rest "};"
1306 (let ((*multiple-value-p* t)) (ls-compile-block body t)))
1310 (defun setq-pair (var val)
1311 (let ((b (lookup-in-lexenv var *environment* 'variable)))
1312 (if (and (eq (binding-type b) 'variable)
1313 (not (member 'special (binding-declarations b)))
1314 (not (member 'constant (binding-declarations b))))
1315 (concat (binding-value b) " = " (ls-compile val))
1316 (ls-compile `(set ',var ,val)))))
1318 (define-compilation setq (&rest pairs)
1322 ((null pairs) (return))
1324 (error "Odd paris in SETQ"))
1327 (concat (setq-pair (car pairs) (cadr pairs))
1328 (if (null (cddr pairs)) "" ", ")))
1329 (setq pairs (cddr pairs)))))
1330 (concat "(" result ")")))
1332 ;;; FFI Variable accessors
1333 (define-compilation js-vref (var)
1336 (define-compilation js-vset (var val)
1337 (concat "(" var " = " (ls-compile val) ")"))
1342 (defun escape-string (string)
1345 (size (length string)))
1346 (while (< index size)
1347 (let ((ch (char string index)))
1348 (when (or (char= ch #\") (char= ch #\\))
1349 (setq output (concat output "\\")))
1350 (when (or (char= ch #\newline))
1351 (setq output (concat output "\\"))
1353 (setq output (concat output (string ch))))
1358 (defvar *literal-symbols* nil)
1359 (defvar *literal-counter* 0)
1362 (concat "l" (integer-to-string (incf *literal-counter*))))
1364 (defun literal (sexp &optional recursive)
1366 ((integerp sexp) (integer-to-string sexp))
1367 ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1369 (or (cdr (assoc sexp *literal-symbols*))
1372 (let ((package (symbol-package sexp)))
1373 (if (eq package (find-package "KEYWORD"))
1374 (concat "{name: \"" (escape-string (symbol-name sexp))
1375 "\", 'package': '" (package-name package) "'}")
1376 (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")))
1378 (let ((package (symbol-package sexp)))
1380 (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1381 (ls-compile `(intern ,(symbol-name sexp) ,(package-name package)))))))
1382 (push (cons sexp v) *literal-symbols*)
1383 (toplevel-compilation (concat "var " v " = " s))
1386 (let* ((head (butlast sexp))
1388 (c (concat "QIList("
1389 (join-trailing (mapcar (lambda (x) (literal x t)) head) ",")
1390 (literal (car tail) t)
1392 (literal (cdr tail) t)
1397 (toplevel-compilation (concat "var " v " = " c))
1400 (let ((elements (vector-to-list sexp)))
1401 (let ((c (concat "[" (join (mapcar #'literal elements) ", ") "]")))
1405 (toplevel-compilation (concat "var " v " = " c))
1408 (define-compilation quote (sexp)
1411 (define-compilation %while (pred &rest body)
1413 "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1414 (indent (ls-compile-block body))
1416 "return " (ls-compile nil) ";" *newline*))
1418 (define-compilation function (x)
1420 ((and (listp x) (eq (car x) 'lambda))
1421 (compile-lambda (cadr x) (cddr x)))
1423 (let ((b (lookup-in-lexenv x *environment* 'function)))
1426 (ls-compile `(symbol-function ',x)))))))
1429 (defun make-function-binding (fname)
1430 (make-binding fname 'function (gvarname fname)))
1432 (defun compile-function-definition (list)
1433 (compile-lambda (car list) (cdr list)))
1435 (defun translate-function (name)
1436 (let ((b (lookup-in-lexenv name *environment* 'function)))
1439 (define-compilation flet (definitions &rest body)
1440 (let* ((fnames (mapcar #'car definitions))
1441 (fbody (mapcar #'cdr definitions))
1442 (cfuncs (mapcar #'compile-function-definition fbody))
1444 (extend-lexenv (mapcar #'make-function-binding fnames)
1447 (concat "(function("
1448 (join (mapcar #'translate-function fnames) ",")
1450 (let ((body (ls-compile-block body t)))
1452 "})(" (join cfuncs ",") ")")))
1454 (define-compilation labels (definitions &rest body)
1455 (let* ((fnames (mapcar #'car definitions))
1457 (extend-lexenv (mapcar #'make-function-binding fnames)
1461 (mapconcat (lambda (func)
1462 (concat "var " (translate-function (car func))
1463 " = " (compile-lambda (cadr func) (cddr func))
1466 (ls-compile-block body t))))
1470 (defvar *compiling-file* nil)
1471 (define-compilation eval-when-compile (&rest body)
1472 (if *compiling-file*
1474 (eval (cons 'progn body))
1476 (ls-compile `(progn ,@body))))
1478 (defmacro define-transformation (name args form)
1479 `(define-compilation ,name ,args
1480 (ls-compile ,form)))
1482 (define-compilation progn (&rest body)
1483 (if (null (cdr body))
1484 (ls-compile (car body) *multiple-value-p*)
1485 (js!selfcall (ls-compile-block body t))))
1487 (defun special-variable-p (x)
1488 (and (claimp x 'variable 'special) t))
1490 ;;; Wrap CODE to restore the symbol values of the dynamic
1491 ;;; bindings. BINDINGS is a list of pairs of the form
1492 ;;; (SYMBOL . PLACE), where PLACE is a Javascript variable
1493 ;;; name to initialize the symbol value and where to stored
1495 (defun let-binding-wrapper (bindings body)
1496 (when (null bindings)
1497 (return-from let-binding-wrapper body))
1500 (indent "var tmp;" *newline*
1503 (let ((s (ls-compile `(quote ,(car b)))))
1504 (concat "tmp = " s ".value;" *newline*
1505 s ".value = " (cdr b) ";" *newline*
1506 (cdr b) " = tmp;" *newline*)))
1510 "finally {" *newline*
1512 (mapconcat (lambda (b)
1513 (let ((s (ls-compile `(quote ,(car b)))))
1514 (concat s ".value" " = " (cdr b) ";" *newline*)))
1518 (define-compilation let (bindings &rest body)
1519 (let* ((bindings (mapcar #'ensure-list bindings))
1520 (variables (mapcar #'first bindings))
1521 (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
1522 (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
1524 (concat "(function("
1525 (join (mapcar (lambda (x)
1526 (if (special-variable-p x)
1527 (let ((v (gvarname x)))
1528 (push (cons x v) dynamic-bindings)
1530 (translate-variable x)))
1534 (let ((body (ls-compile-block body t)))
1535 (indent (let-binding-wrapper dynamic-bindings body)))
1536 "})(" (join cvalues ",") ")")))
1539 ;;; Return the code to initialize BINDING, and push it extending the
1540 ;;; current lexical environment if the variable is not special.
1541 (defun let*-initialize-value (binding)
1542 (let ((var (first binding))
1543 (value (second binding)))
1544 (if (special-variable-p var)
1545 (concat (ls-compile `(setq ,var ,value)) ";" *newline*)
1546 (let* ((v (gvarname var))
1547 (b (make-binding var 'variable v)))
1548 (prog1 (concat "var " v " = " (ls-compile value) ";" *newline*)
1549 (push-to-lexenv b *environment* 'variable))))))
1551 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
1552 ;;; DOES NOT generate code to initialize the value of the symbols,
1553 ;;; unlike let-binding-wrapper.
1554 (defun let*-binding-wrapper (symbols body)
1555 (when (null symbols)
1556 (return-from let*-binding-wrapper body))
1557 (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
1558 (remove-if-not #'special-variable-p symbols))))
1562 (mapconcat (lambda (b)
1563 (let ((s (ls-compile `(quote ,(car b)))))
1564 (concat "var " (cdr b) " = " s ".value;" *newline*)))
1568 "finally {" *newline*
1570 (mapconcat (lambda (b)
1571 (let ((s (ls-compile `(quote ,(car b)))))
1572 (concat s ".value" " = " (cdr b) ";" *newline*)))
1576 (define-compilation let* (bindings &rest body)
1577 (let ((bindings (mapcar #'ensure-list bindings))
1578 (*environment* (copy-lexenv *environment*)))
1580 (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
1581 (body (concat (mapconcat #'let*-initialize-value bindings)
1582 (ls-compile-block body t))))
1583 (let*-binding-wrapper specials body)))))
1586 (defvar *block-counter* 0)
1588 (define-compilation block (name &rest body)
1589 (let* ((tr (integer-to-string (incf *block-counter*)))
1590 (b (make-binding name 'block tr)))
1591 (when *multiple-value-p*
1592 (push-binding-declaration 'multiple-value b))
1593 (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
1594 (cbody (ls-compile-block body t)))
1595 (if (member 'used (binding-declarations b))
1600 "catch (cf){" *newline*
1601 " if (cf.type == 'block' && cf.id == " tr ")" *newline*
1602 (if *multiple-value-p*
1603 " return values.apply(this, forcemv(cf.values));"
1604 " return cf.values;")
1607 " throw cf;" *newline*
1609 (js!selfcall cbody)))))
1611 (define-compilation return-from (name &optional value)
1612 (let* ((b (lookup-in-lexenv name *environment* 'block))
1613 (multiple-value-p (member 'multiple-value (binding-declarations b))))
1615 (error (concat "Unknown block `" (symbol-name name) "'.")))
1616 (push-binding-declaration 'used b)
1618 (if multiple-value-p
1619 (concat "var values = mv;" *newline*)
1623 "id: " (binding-value b) ", "
1624 "values: " (ls-compile value multiple-value-p) ", "
1625 "message: 'Return from unknown block " (symbol-name name) ".'"
1628 (define-compilation catch (id &rest body)
1630 "var id = " (ls-compile id) ";" *newline*
1632 (indent (ls-compile-block body t)) *newline*
1634 "catch (cf){" *newline*
1635 " if (cf.type == 'catch' && cf.id == id)" *newline*
1636 (if *multiple-value-p*
1637 " return values.apply(this, forcemv(cf.values));"
1638 " return pv.apply(this, forcemv(cf.values));")
1641 " throw cf;" *newline*
1644 (define-compilation throw (id value)
1646 "var values = mv;" *newline*
1649 "id: " (ls-compile id) ", "
1650 "values: " (ls-compile value t) ", "
1651 "message: 'Throw uncatched.'"
1655 (defvar *tagbody-counter* 0)
1656 (defvar *go-tag-counter* 0)
1659 (or (integerp x) (symbolp x)))
1661 (defun declare-tagbody-tags (tbidx body)
1663 (mapcar (lambda (label)
1664 (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1665 (make-binding label 'gotag (list tbidx tagidx))))
1666 (remove-if-not #'go-tag-p body))))
1667 (extend-lexenv bindings *environment* 'gotag)))
1669 (define-compilation tagbody (&rest body)
1670 ;; Ignore the tagbody if it does not contain any go-tag. We do this
1671 ;; because 1) it is easy and 2) many built-in forms expand to a
1672 ;; implicit tagbody, so we save some space.
1673 (unless (some #'go-tag-p body)
1674 (return-from tagbody (ls-compile `(progn ,@body nil))))
1675 ;; The translation assumes the first form in BODY is a label
1676 (unless (go-tag-p (car body))
1677 (push (gensym "START") body))
1678 ;; Tagbody compilation
1679 (let ((tbidx (integer-to-string *tagbody-counter*)))
1680 (let ((*environment* (declare-tagbody-tags tbidx body))
1682 (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1683 (setq initag (second (binding-value b))))
1685 "var tagbody_" tbidx " = " initag ";" *newline*
1687 "while (true) {" *newline*
1688 (indent "try {" *newline*
1689 (indent (let ((content ""))
1690 (concat "switch(tagbody_" tbidx "){" *newline*
1691 "case " initag ":" *newline*
1692 (dolist (form (cdr body) content)
1694 (if (not (go-tag-p form))
1695 (indent (ls-compile form) ";" *newline*)
1696 (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1697 (concat "case " (second (binding-value b)) ":" *newline*)))))
1698 "default:" *newline*
1699 " break tbloop;" *newline*
1702 "catch (jump) {" *newline*
1703 " if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1704 " tagbody_" tbidx " = jump.label;" *newline*
1706 " throw(jump);" *newline*
1709 "return " (ls-compile nil) ";" *newline*))))
1711 (define-compilation go (label)
1712 (let ((b (lookup-in-lexenv label *environment* 'gotag))
1714 ((symbolp label) (symbol-name label))
1715 ((integerp label) (integer-to-string label)))))
1720 "id: " (first (binding-value b)) ", "
1721 "label: " (second (binding-value b)) ", "
1722 "message: 'Attempt to GO to non-existing tag " n "'"
1724 (error (concat "Unknown tag `" n "'.")))))
1726 (define-compilation unwind-protect (form &rest clean-up)
1728 "var ret = " (ls-compile nil) ";" *newline*
1730 (indent "ret = " (ls-compile form) ";" *newline*)
1731 "} finally {" *newline*
1732 (indent (ls-compile-block clean-up))
1734 "return ret;" *newline*))
1736 (define-compilation multiple-value-call (func-form &rest forms)
1738 "var func = " (ls-compile func-form) ";" *newline*
1739 "var args = [" (if *multiple-value-p* "values" "pv") "];" *newline*
1742 "var values = mv;" *newline*
1744 (mapconcat (lambda (form)
1745 (concat "vs = " (ls-compile form t) ";" *newline*
1746 "if (typeof vs === 'object' && 'multiple-value' in vs)" *newline*
1747 (indent "args = args.concat(vs);" *newline*)
1749 (indent "args.push(vs);" *newline*)))
1751 "return func.apply(window, args);" *newline*) ";" *newline*))
1753 (define-compilation multiple-value-prog1 (first-form &rest forms)
1755 "var args = " (ls-compile first-form *multiple-value-p*) ";" *newline*
1756 (ls-compile-block forms)
1757 "return args;" *newline*))
1761 ;;; A little backquote implementation without optimizations of any
1762 ;;; kind for ecmalisp.
1763 (defun backquote-expand-1 (form)
1769 ((eq (car form) 'unquote)
1771 ((eq (car form) 'backquote)
1772 (backquote-expand-1 (backquote-expand-1 (cadr form))))
1777 ((and (listp s) (eq (car s) 'unquote))
1778 (list 'list (cadr s)))
1779 ((and (listp s) (eq (car s) 'unquote-splicing))
1782 (list 'list (backquote-expand-1 s)))))
1785 (defun backquote-expand (form)
1786 (if (and (listp form) (eq (car form) 'backquote))
1787 (backquote-expand-1 (cadr form))
1790 (defmacro backquote (form)
1791 (backquote-expand-1 form))
1793 (define-transformation backquote (form)
1794 (backquote-expand-1 form))
1798 (defvar *builtins* nil)
1800 (defmacro define-raw-builtin (name args &body body)
1801 ;; Creates a new primitive function `name' with parameters args and
1802 ;; @body. The body can access to the local environment through the
1803 ;; variable *ENVIRONMENT*.
1804 `(push (list ',name (lambda ,args (block ,name ,@body)))
1807 (defmacro define-builtin (name args &body body)
1809 (define-raw-builtin ,name ,args
1810 (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1813 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1814 (defmacro type-check (decls &body body)
1816 ,@(mapcar (lambda (decl)
1817 `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1819 ,@(mapcar (lambda (decl)
1820 `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1821 (indent "throw 'The value ' + "
1823 " + ' is not a type "
1828 (concat "return " (progn ,@body) ";" *newline*)))
1830 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
1831 ;;; a variable which holds a list of forms. It will compile them and
1832 ;;; store the result in some Javascript variables. BODY is evaluated
1833 ;;; with ARGS bound to the list of these variables to generate the
1834 ;;; code which performs the transformation on these variables.
1836 (defun variable-arity-call (args function)
1837 (unless (consp args)
1838 (error "ARGS must be a non-empty list"))
1843 (let ((v (concat "x" (integer-to-string (incf counter)))))
1846 (concat "var " v " = " (ls-compile x) ";" *newline*
1847 "if (typeof " v " !== 'number') throw 'Not a number!';"
1849 (js!selfcall prelude (funcall function (reverse variables)))))
1852 (defmacro variable-arity (args &body body)
1853 (unless (symbolp args)
1854 (error "Bad usage of VARIABLE-ARITY, you must pass a symbol"))
1855 `(variable-arity-call ,args
1857 (concat "return " ,@body ";" *newline*))))
1859 (defun num-op-num (x op y)
1860 (type-check (("x" "number" x) ("y" "number" y))
1861 (concat "x" op "y")))
1863 (define-raw-builtin + (&rest numbers)
1866 (variable-arity numbers
1867 (join numbers "+"))))
1869 (define-raw-builtin - (x &rest others)
1870 (let ((args (cons x others)))
1871 (variable-arity args
1873 (concat "-" (car args))
1876 (define-raw-builtin * (&rest numbers)
1879 (variable-arity numbers
1880 (join numbers "*"))))
1882 (define-raw-builtin / (x &rest others)
1883 (let ((args (cons x others)))
1884 (variable-arity args
1886 (concat "1 /" (car args))
1889 (define-builtin mod (x y) (num-op-num x "%" y))
1892 (defun comparison-conjuntion (vars op)
1897 (concat (car vars) op (cadr vars)))
1899 (concat (car vars) op (cadr vars)
1901 (comparison-conjuntion (cdr vars) op)))))
1903 (defmacro define-builtin-comparison (op sym)
1904 `(define-raw-builtin ,op (x &rest args)
1905 (let ((args (cons x args)))
1906 (variable-arity args
1907 (js!bool (comparison-conjuntion args ,sym))))))
1909 (define-builtin-comparison > ">")
1910 (define-builtin-comparison < "<")
1911 (define-builtin-comparison >= ">=")
1912 (define-builtin-comparison <= "<=")
1913 (define-builtin-comparison = "==")
1915 (define-builtin numberp (x)
1916 (js!bool (concat "(typeof (" x ") == \"number\")")))
1918 (define-builtin floor (x)
1919 (type-check (("x" "number" x))
1922 (define-builtin cons (x y)
1923 (concat "({car: " x ", cdr: " y "})"))
1925 (define-builtin consp (x)
1928 "var tmp = " x ";" *newline*
1929 "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1931 (define-builtin car (x)
1933 "var tmp = " x ";" *newline*
1934 "return tmp === " (ls-compile nil)
1935 "? " (ls-compile nil)
1936 ": tmp.car;" *newline*))
1938 (define-builtin cdr (x)
1940 "var tmp = " x ";" *newline*
1941 "return tmp === " (ls-compile nil) "? "
1943 ": tmp.cdr;" *newline*))
1945 (define-builtin rplaca (x new)
1946 (type-check (("x" "object" x))
1947 (concat "(x.car = " new ", x)")))
1949 (define-builtin rplacd (x new)
1950 (type-check (("x" "object" x))
1951 (concat "(x.cdr = " new ", x)")))
1953 (define-builtin symbolp (x)
1956 "var tmp = " x ";" *newline*
1957 "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1959 (define-builtin make-symbol (name)
1960 (type-check (("name" "string" name))
1963 (define-builtin symbol-name (x)
1964 (concat "(" x ").name"))
1966 (define-builtin set (symbol value)
1967 (concat "(" symbol ").value = " value))
1969 (define-builtin fset (symbol value)
1970 (concat "(" symbol ").fvalue = " value))
1972 (define-builtin boundp (x)
1973 (js!bool (concat "(" x ".value !== undefined)")))
1975 (define-builtin symbol-value (x)
1977 "var symbol = " x ";" *newline*
1978 "var value = symbol.value;" *newline*
1979 "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1980 "return value;" *newline*))
1982 (define-builtin symbol-function (x)
1984 "var symbol = " x ";" *newline*
1985 "var func = symbol.fvalue;" *newline*
1986 "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1987 "return func;" *newline*))
1989 (define-builtin symbol-plist (x)
1990 (concat "((" x ").plist || " (ls-compile nil) ")"))
1992 (define-builtin lambda-code (x)
1993 (concat "(" x ").toString()"))
1995 (define-builtin eq (x y) (js!bool (concat "(" x " === " y ")")))
1996 (define-builtin equal (x y) (js!bool (concat "(" x " == " y ")")))
1998 (define-builtin char-to-string (x)
1999 (type-check (("x" "number" x))
2000 "String.fromCharCode(x)"))
2002 (define-builtin stringp (x)
2003 (js!bool (concat "(typeof(" x ") == \"string\")")))
2005 (define-builtin string-upcase (x)
2006 (type-check (("x" "string" x))
2009 (define-builtin string-length (x)
2010 (type-check (("x" "string" x))
2013 (define-raw-builtin slice (string a &optional b)
2015 "var str = " (ls-compile string) ";" *newline*
2016 "var a = " (ls-compile a) ";" *newline*
2019 (concat "b = " (ls-compile b) ";" *newline*)
2021 "return str.slice(a,b);" *newline*))
2023 (define-builtin char (string index)
2024 (type-check (("string" "string" string)
2025 ("index" "number" index))
2026 "string.charCodeAt(index)"))
2028 (define-builtin concat-two (string1 string2)
2029 (type-check (("string1" "string" string1)
2030 ("string2" "string" string2))
2031 "string1.concat(string2)"))
2033 (define-raw-builtin funcall (func &rest args)
2034 (concat "(" (ls-compile func) ")("
2035 (join (cons (if *multiple-value-p* "values" "pv")
2036 (mapcar #'ls-compile args))
2040 (define-raw-builtin apply (func &rest args)
2042 (concat "(" (ls-compile func) ")()")
2043 (let ((args (butlast args))
2044 (last (car (last args))))
2046 "var f = " (ls-compile func) ";" *newline*
2047 "var args = [" (join (cons (if *multiple-value-p* "values" "pv")
2048 (mapcar #'ls-compile args))
2051 "var tail = (" (ls-compile last) ");" *newline*
2052 "while (tail != " (ls-compile nil) "){" *newline*
2053 " args.push(tail.car);" *newline*
2054 " tail = tail.cdr;" *newline*
2056 "return f.apply(this, args);" *newline*))))
2058 (define-builtin js-eval (string)
2059 (type-check (("string" "string" string))
2060 (if *multiple-value-p*
2062 "var v = eval.apply(window, [string]);" *newline*
2063 "if (typeof v !== 'object' || !('multiple-value' in v)){" *newline*
2064 (indent "v = [v];" *newline*
2065 "v['multiple-value'] = true;" *newline*)
2067 "return values.apply(this, v);" *newline*)
2068 "eval.apply(window, [string])")))
2070 (define-builtin error (string)
2071 (js!selfcall "throw " string ";" *newline*))
2073 (define-builtin new () "{}")
2075 (define-builtin objectp (x)
2076 (js!bool (concat "(typeof (" x ") === 'object')")))
2078 (define-builtin oget (object key)
2080 "var tmp = " "(" object ")[" key "];" *newline*
2081 "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
2083 (define-builtin oset (object key value)
2084 (concat "((" object ")[" key "] = " value ")"))
2086 (define-builtin in (key object)
2087 (js!bool (concat "((" key ") in (" object "))")))
2089 (define-builtin functionp (x)
2090 (js!bool (concat "(typeof " x " == 'function')")))
2092 (define-builtin write-string (x)
2093 (type-check (("x" "string" x))
2096 (define-builtin make-array (n)
2098 "var r = [];" *newline*
2099 "for (var i = 0; i < " n "; i++)" *newline*
2100 (indent "r.push(" (ls-compile nil) ");" *newline*)
2101 "return r;" *newline*))
2103 (define-builtin arrayp (x)
2106 "var x = " x ";" *newline*
2107 "return typeof x === 'object' && 'length' in x;")))
2109 (define-builtin aref (array n)
2111 "var x = " "(" array ")[" n "];" *newline*
2112 "if (x === undefined) throw 'Out of range';" *newline*
2113 "return x;" *newline*))
2115 (define-builtin aset (array n value)
2117 "var x = " array ";" *newline*
2118 "var i = " n ";" *newline*
2119 "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
2120 "return x[i] = " value ";" *newline*))
2122 (define-builtin get-unix-time ()
2123 (concat "(Math.round(new Date() / 1000))"))
2125 (define-builtin values-array (array)
2126 (if *multiple-value-p*
2127 (concat "values.apply(this, " array ")")
2128 (concat "pv.apply(this, " array ")")))
2130 (define-raw-builtin values (&rest args)
2131 (if *multiple-value-p*
2132 (concat "values(" (join (mapcar #'ls-compile args) ", ") ")")
2133 (concat "pv(" (join (mapcar #'ls-compile args) ", ") ")")))
2137 (let ((b (lookup-in-lexenv x *environment* 'function)))
2138 (and (eq (binding-type b) 'macro)
2141 (defun ls-macroexpand-1 (form)
2142 (let ((macro-binding (macro (car form))))
2144 (let ((expander (binding-value macro-binding)))
2145 (when (listp expander)
2146 (let ((compiled (eval expander)))
2147 ;; The list representation are useful while
2148 ;; bootstrapping, as we can dump the definition of the
2149 ;; macros easily, but they are slow because we have to
2150 ;; evaluate them and compile them now and again. So, let
2151 ;; us replace the list representation version of the
2152 ;; function with the compiled one.
2154 #+ecmalisp (set-binding-value macro-binding compiled)
2155 (setq expander compiled)))
2156 (apply expander (cdr form)))
2159 (defun compile-funcall (function args)
2160 (let* ((values-funcs (if *multiple-value-p* "values" "pv"))
2161 (arglist (concat "(" (join (cons values-funcs (mapcar #'ls-compile args)) ", ") ")")))
2163 ((translate-function function)
2164 (concat (translate-function function) arglist))
2165 ((and (symbolp function)
2166 #+ecmalisp (eq (symbol-package function) (find-package "COMMON-LISP"))
2168 (concat (ls-compile `',function) ".fvalue" arglist))
2170 (concat (ls-compile `#',function) arglist)))))
2172 (defun ls-compile-block (sexps &optional return-last-p)
2174 (concat (ls-compile-block (butlast sexps))
2175 "return " (ls-compile (car (last sexps)) *multiple-value-p*) ";")
2177 (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
2178 (concat ";" *newline*))))
2180 (defun ls-compile (sexp &optional multiple-value-p)
2181 (let ((*multiple-value-p* multiple-value-p))
2184 (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
2186 ((and b (not (member 'special (binding-declarations b))))
2188 ((or (keywordp sexp)
2189 (member 'constant (binding-declarations b)))
2190 (concat (ls-compile `',sexp) ".value"))
2192 (ls-compile `(symbol-value ',sexp))))))
2193 ((integerp sexp) (integer-to-string sexp))
2194 ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
2195 ((arrayp sexp) (literal sexp))
2197 (let ((name (car sexp))
2201 ((assoc name *compilations*)
2202 (let ((comp (second (assoc name *compilations*))))
2204 ;; Built-in functions
2205 ((and (assoc name *builtins*)
2206 (not (claimp name 'function 'notinline)))
2207 (let ((comp (second (assoc name *builtins*))))
2211 (ls-compile (ls-macroexpand-1 sexp) multiple-value-p)
2212 (compile-funcall name args))))))
2214 (error "How should I compile this?")))))
2216 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
2217 (let ((*toplevel-compilations* nil))
2219 ((and (consp sexp) (eq (car sexp) 'progn))
2220 (let ((subs (mapcar (lambda (s)
2221 (ls-compile-toplevel s t))
2223 (join (remove-if #'null-or-empty-p subs))))
2225 (let ((code (ls-compile sexp multiple-value-p)))
2226 (concat (join-trailing (get-toplevel-compilations)
2227 (concat ";" *newline*))
2229 (concat code ";" *newline*)
2233 ;;; Once we have the compiler, we define the runtime environment and
2234 ;;; interactive development (eval), which works calling the compiler
2235 ;;; and evaluating the Javascript result globally.
2240 (js-eval (ls-compile-toplevel x t)))
2242 (export '(&rest &optional &body * *gensym-counter* *package* + - /
2243 1+ 1- < <= = = > >= and append apply aref arrayp aset
2244 assoc atom block boundp boundp butlast caar cadddr caddr
2245 cadr car car case catch cdar cdddr cddr cdr cdr char
2246 char-code char= code-char cond cons consp constantly
2247 copy-list decf declaim defparameter defun defmacro defvar
2248 digit-char digit-char-p disassemble do do* documentation
2249 dolist dotimes ecase eq eql equal error eval every export
2250 fdefinition find-package find-symbol first flet fourth
2251 fset funcall function functionp gensym get-universal-time
2252 go identity if in-package incf integerp integerp intern
2253 keywordp labels lambda last length let let*
2254 list-all-packages list listp make-array make-package
2255 make-symbol mapcar member minusp mod multiple-value-bind
2256 multiple-value-call multiple-value-list
2257 multiple-value-prog1 nil not nth nthcdr null numberp or
2258 package-name package-use-list packagep parse-integer plusp
2259 prin1-to-string print proclaim prog1 prog2 progn psetq
2260 push quote remove remove-if remove-if-not return
2261 return-from revappend reverse rplaca rplacd second set
2262 setq some string-upcase string string= stringp subseq
2263 symbol-function symbol-name symbol-package symbol-plist
2264 symbol-value symbolp t tagbody third throw truncate unless
2265 unwind-protect values values-list variable warn when
2266 write-line write-string zerop))
2268 (setq *package* *user-package*)
2270 (js-eval "var lisp")
2271 (js-vset "lisp" (new))
2272 (js-vset "lisp.read" #'ls-read-from-string)
2273 (js-vset "lisp.print" #'prin1-to-string)
2274 (js-vset "lisp.eval" #'eval)
2275 (js-vset "lisp.compile" (lambda (s) (ls-compile-toplevel s t)))
2276 (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
2277 (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str) t)))
2279 ;; Set the initial global environment to be equal to the host global
2280 ;; environment at this point of the compilation.
2282 (toplevel-compilation
2285 ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
2287 (setq *literal-symbols* ',*literal-symbols*)
2288 (setq *environment* ',*environment*)
2289 (setq *variable-counter* ,*variable-counter*)
2290 (setq *gensym-counter* ,*gensym-counter*)
2291 (setq *block-counter* ,*block-counter*)))))
2294 (toplevel-compilation
2296 `(setq *literal-counter* ,*literal-counter*)))))
2299 ;;; Finally, we provide a couple of functions to easily bootstrap
2300 ;;; this. It just calls the compiler with this file as input.
2304 (defun read-whole-file (filename)
2305 (with-open-file (in filename)
2306 (let ((seq (make-array (file-length in) :element-type 'character)))
2307 (read-sequence seq in)
2310 (defun ls-compile-file (filename output)
2311 (let ((*compiling-file* t))
2312 (with-open-file (out output :direction :output :if-exists :supersede)
2313 (write-string (read-whole-file "prelude.js") out)
2314 (let* ((source (read-whole-file filename))
2315 (in (make-string-stream source)))
2317 for x = (ls-read in)
2319 for compilation = (ls-compile-toplevel x)
2320 when (plusp (length compilation))
2321 do (write-string compilation out))))))
2324 (setq *environment* (make-lexenv))
2325 (setq *literal-symbols* nil)
2326 (setq *variable-counter* 0
2330 (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))