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 (defmacro defconstant (name value &optional docstring)
47 (declaim (special ,name))
48 (declaim (constant ,name))
50 ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
54 (defconstant nil 'nil)
57 (defmacro lambda (args &body body)
58 `(function (lambda ,args ,@body)))
60 (defmacro when (condition &body body)
61 `(if ,condition (progn ,@body) nil))
63 (defmacro unless (condition &body body)
64 `(if ,condition nil (progn ,@body)))
66 (defmacro defvar (name value &optional docstring)
68 (declaim (special ,name))
69 (unless (boundp ',name) (setq ,name ,value))
70 ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
73 (defmacro defparameter (name value &optional docstring)
76 ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
79 (defmacro named-lambda (name args &rest body)
80 (let ((x (gensym "FN")))
81 `(let ((,x (lambda ,args ,@body)))
82 (oset ,x "fname" ,name)
85 (defmacro defun (name args &rest body)
88 (named-lambda ,(symbol-name name) ,args
89 ,@(if (and (stringp (car body)) (not (null (cdr body))))
90 `(,(car body) (block ,name ,@(cdr body)))
91 `((block ,name ,@body)))))
102 (error "type-error"))))
104 (defmacro return (&optional value)
105 `(return-from nil ,value))
107 (defmacro while (condition &body body)
108 `(block nil (%while ,condition ,@body)))
110 (defvar *gensym-counter* 0)
111 (defun gensym (&optional (prefix "G"))
112 (setq *gensym-counter* (+ *gensym-counter* 1))
113 (make-symbol (concat-two prefix (integer-to-string *gensym-counter*))))
119 (defun = (x y) (= x y))
120 (defun * (x y) (* x y))
121 (defun / (x y) (/ x y))
122 (defun 1+ (x) (+ x 1))
123 (defun 1- (x) (- x 1))
124 (defun zerop (x) (= x 0))
125 (defun truncate (x y) (floor (/ x y)))
127 (defun eql (x y) (eq x y))
129 (defun not (x) (if x nil t))
131 (defun cons (x y ) (cons x y))
132 (defun consp (x) (consp x))
135 "Return the CAR part of a cons, or NIL if X is null."
138 (defun cdr (x) (cdr x))
139 (defun caar (x) (car (car x)))
140 (defun cadr (x) (car (cdr x)))
141 (defun cdar (x) (cdr (car x)))
142 (defun cddr (x) (cdr (cdr x)))
143 (defun cadar (x) (car (cdr (car x))))
144 (defun caddr (x) (car (cdr (cdr x))))
145 (defun cdddr (x) (cdr (cdr (cdr x))))
146 (defun cadddr (x) (car (cdr (cdr (cdr x)))))
147 (defun first (x) (car x))
148 (defun second (x) (cadr x))
149 (defun third (x) (caddr x))
150 (defun fourth (x) (cadddr x))
151 (defun rest (x) (cdr x))
153 (defun list (&rest args) args)
159 (defmacro incf (x &optional (delta 1))
160 `(setq ,x (+ ,x ,delta)))
162 (defmacro decf (x &optional (delta 1))
163 `(setq ,x (- ,x ,delta)))
165 (defmacro push (x place)
166 (multiple-value-bind (dummies vals newval setter getter)
167 (get-setf-expansion place)
170 ,@(mapcar #'list dummies vals)
171 (,(car newval) (cons ,g ,getter))
175 (defmacro dolist (iter &body body)
176 (let ((var (first iter))
179 (let ((,g!list ,(second iter))
182 (setq ,var (car ,g!list))
184 (setq ,g!list (cdr ,g!list)))
187 (defmacro dotimes (iter &body body)
188 (let ((g!to (gensym))
191 (result (third iter)))
195 (%while (< ,var ,g!to)
200 (defmacro cond (&rest clausules)
203 (if (eq (caar clausules) t)
204 `(progn ,@(cdar clausules))
205 `(if ,(caar clausules)
206 (progn ,@(cdar clausules))
207 (cond ,@(cdr clausules))))))
209 (defmacro case (form &rest clausules)
210 (let ((!form (gensym)))
211 `(let ((,!form ,form))
213 ,@(mapcar (lambda (clausule)
214 (if (eq (car clausule) t)
216 `((eql ,!form ',(car clausule))
220 (defmacro ecase (form &rest clausules)
225 (error "ECASE expression failed."))))))
227 (defmacro and (&rest forms)
238 (defmacro or (&rest forms)
246 `(let ((,g ,(car forms)))
247 (if ,g ,g (or ,@(cdr forms))))))))
249 (defmacro prog1 (form &body body)
250 (let ((value (gensym)))
251 `(let ((,value ,form))
255 (defmacro prog2 (form1 result &body body)
256 `(prog1 (progn ,form1 ,result) ,@body)))
259 ;;; This couple of helper functions will be defined in both Common
260 ;;; Lisp and in Ecmalisp.
261 (defun ensure-list (x)
266 (defun !reduce (func list &key initial-value)
271 :initial-value (funcall func initial-value (car list)))))
273 ;;; Go on growing the Lisp language in Ecmalisp, with more high
274 ;;; level utilities as well as correct versions of other
278 (defun + (&rest args)
283 (defun - (x &rest others)
290 (defun append-two (list1 list2)
294 (append (cdr list1) list2))))
296 (defun append (&rest lists)
297 (!reduce #'append-two lists))
299 (defun revappend (list1 list2)
301 (push (car list1) list2)
302 (setq list1 (cdr list1)))
305 (defun reverse (list)
306 (revappend list '()))
308 (defmacro psetq (&rest pairs)
309 (let ( ;; For each pair, we store here a list of the form
310 ;; (VARIABLE GENSYM VALUE).
314 ((null pairs) (return))
316 (error "Odd paris in PSETQ"))
318 (let ((variable (car pairs))
319 (value (cadr pairs)))
320 (push `(,variable ,(gensym) ,value) assignments)
321 (setq pairs (cddr pairs))))))
322 (setq assignments (reverse assignments))
324 `(let ,(mapcar #'cdr assignments)
325 (setq ,@(!reduce #'append (mapcar #'butlast assignments))))))
327 (defmacro do (varlist endlist &body body)
329 (let ,(mapcar (lambda (x) (list (first x) (second x))) varlist)
332 (return (progn ,@(cdr endlist))))
337 (and (consp (cddr v))
338 (list (first v) (third v))))
341 (defmacro do* (varlist endlist &body body)
343 (let* ,(mapcar (lambda (x) (list (first x) (second x))) varlist)
346 (return (progn ,@(cdr endlist))))
351 (and (consp (cddr v))
352 (list (first v) (third v))))
355 (defun list-length (list)
357 (while (not (null list))
359 (setq list (cdr list)))
371 (defun concat-two (s1 s2)
374 (defmacro with-collect (&body body)
375 (let ((head (gensym))
377 `(let* ((,head (cons 'sentinel nil))
380 (rplacd ,tail (cons x nil))
381 (setq ,tail (cdr ,tail))
386 ;; A very simple defstruct built on lists. It supports just slot with
387 ;; an optional default initform, and it will create a constructor,
388 ;; predicate and accessors for you.
389 (defmacro defstruct (name &rest slots)
390 (unless (symbolp name)
391 (error "It is not a full defstruct implementation."))
392 (let* ((name-string (symbol-name name))
398 ((and (listp sd) (car sd) (cddr sd))
401 (error "Bad slot accessor."))))
403 (predicate (intern (concat name-string "P"))))
406 (defun ,(intern (concat "MAKE-" name-string)) (&key ,@slot-descriptions)
407 (list ',name ,@(mapcar #'car slot-descriptions)))
409 (defun ,predicate (x)
410 (and (consp x) (eq (car x) ',name)))
412 (defun ,(intern (concat "COPY-" name-string)) (x)
417 (dolist (slot slot-descriptions)
418 (let* ((name (car slot))
419 (accessor-name (intern (concat name-string "-" (string name)))))
421 `(defun ,accessor-name (x)
422 (unless (,predicate x)
423 (error ,(concat "The object is not a type " name-string)))
425 ;; TODO: Implement this with a higher level
426 ;; abstraction like defsetf or (defun (setf ..))
428 `(define-setf-expander ,accessor-name (x)
429 (let ((object (gensym))
430 (new-value (gensym)))
431 (values (list object)
435 (rplaca (nthcdr ,',index ,object) ,new-value)
437 `(,',accessor-name ,object)))))
441 (defun map1 (func list)
444 (collect (funcall func (car list)))
445 (setq list (cdr list)))))
447 (defmacro loop (&body body)
450 (defun mapcar (func list &rest lists)
451 (let ((lists (cons list lists)))
455 (let ((elems (map1 #'car lists)))
456 (do ((tail lists (cdr tail)))
458 (when (null (car tail)) (return-from loop))
459 (rplaca tail (cdar tail)))
460 (collect (apply func elems))))))))
462 (defun identity (x) x)
464 (defun constantly (x)
469 (mapcar #'identity x))
471 (defun list* (arg &rest others)
472 (cond ((null others) arg)
473 ((null (cdr others)) (cons arg (car others)))
474 (t (do ((x others (cdr x)))
475 ((null (cddr x)) (rplacd x (cadr x))))
478 (defun code-char (x) x)
479 (defun char-code (x) x)
480 (defun char= (x y) (= x y))
483 (and (numberp x) (= (floor x) x)))
485 (defun plusp (x) (< 0 x))
486 (defun minusp (x) (< x 0))
489 (or (consp x) (null x)))
491 (defun nthcdr (n list)
492 (while (and (plusp n) list)
494 (setq list (cdr list)))
498 (car (nthcdr n list)))
501 (while (consp (cdr x))
507 (cons (car x) (butlast (cdr x)))))
509 (defun member (x list)
511 (when (eql x (car list))
513 (setq list (cdr list))))
515 (defun remove (x list)
520 (remove x (cdr list)))
522 (cons (car list) (remove x (cdr list))))))
524 (defun remove-if (func list)
528 ((funcall func (car list))
529 (remove-if func (cdr list)))
532 (cons (car list) (remove-if func (cdr list))))))
534 (defun remove-if-not (func list)
538 ((funcall func (car list))
539 (cons (car list) (remove-if-not func (cdr list))))
541 (remove-if-not func (cdr list)))))
543 (defun digit-char-p (x)
544 (if (and (<= #\0 x) (<= x #\9))
548 (defun digit-char (weight)
550 (char "0123456789" weight)))
552 (defun subseq (seq a &optional b)
559 (error "Unsupported argument."))))
561 (defmacro do-sequence (iteration &body body)
564 `(let ((,seq ,(second iteration)))
569 (dotimes (,index (length ,seq))
570 (let ((,(first iteration)
575 (dolist (,(first iteration) ,seq)
578 (error "type-error!"))))))
580 (defun some (function seq)
581 (do-sequence (elt seq)
582 (when (funcall function elt)
583 (return-from some t))))
585 (defun every (function seq)
586 (do-sequence (elt seq)
587 (unless (funcall function elt)
588 (return-from every nil)))
591 (defun position (elt sequence)
599 (defun assoc (x alist)
601 (if (eql x (caar alist))
603 (setq alist (cdr alist))))
607 (cond ((stringp x) x)
608 ((symbolp x) (symbol-name x))
609 (t (char-to-string x))))
611 (defun string= (s1 s2)
614 (defun fdefinition (x)
621 (error "Invalid function"))))
623 (defun disassemble (function)
624 (write-line (lambda-code (fdefinition function)))
627 (defun documentation (x type)
628 "Return the documentation of X. TYPE must be the symbol VARIABLE or FUNCTION."
631 (let ((func (fdefinition x)))
632 (oget func "docstring")))
635 (error "Wrong argument type! it should be a symbol"))
638 (defmacro multiple-value-bind (variables value-from &body body)
639 `(multiple-value-call (lambda (&optional ,@variables &rest ,(gensym))
643 (defmacro multiple-value-list (value-from)
644 `(multiple-value-call #'list ,value-from))
647 ;;; Generalized references (SETF)
649 (defvar *setf-expanders* nil)
651 (defun get-setf-expansion (place)
653 (let ((value (gensym)))
657 `(setq ,place ,value)
659 (let ((place (ls-macroexpand-1 place)))
660 (let* ((access-fn (car place))
661 (expander (cdr (assoc access-fn *setf-expanders*))))
662 (when (null expander)
663 (error "Unknown generalized reference."))
664 (apply expander (cdr place))))))
666 (defmacro define-setf-expander (access-fn lambda-list &body body)
667 (unless (symbolp access-fn)
668 (error "ACCESS-FN must be a symbol."))
669 `(progn (push (cons ',access-fn (lambda ,lambda-list ,@body))
673 (defmacro setf (&rest pairs)
678 (error "Odd number of arguments to setf."))
680 (let ((place (first pairs))
681 (value (second pairs)))
682 (multiple-value-bind (vars vals store-vars writer-form reader-form)
683 (get-setf-expansion place)
684 ;; TODO: Optimize the expansion a little bit to avoid let*
685 ;; or multiple-value-bind when unnecesary.
686 `(let* ,(mapcar #'list vars vals)
687 (multiple-value-bind ,store-vars
692 ,@(do ((pairs pairs (cddr pairs))
693 (result '() (cons `(setf ,(car pairs) ,(cadr pairs)) result)))
695 (reverse result)))))))
697 (define-setf-expander car (x)
698 (let ((cons (gensym))
699 (new-value (gensym)))
703 `(progn (rplaca ,cons ,new-value) ,new-value)
706 (define-setf-expander cdr (x)
707 (let ((cons (gensym))
708 (new-value (gensym)))
712 `(progn (rplacd ,cons ,new-value) ,new-value)
715 ;; Incorrect typecase, but used in NCONC.
716 (defmacro typecase (x &rest clausules)
717 (let ((value (gensym)))
720 ,@(mapcar (lambda (c)
734 ;; The NCONC function is based on the SBCL's one.
735 (defun nconc (&rest lists)
736 (flet ((fail (object)
737 (error "type-error in nconc")))
738 (do ((top lists (cdr top)))
740 (let ((top-of-top (car top)))
743 (let* ((result top-of-top)
745 (do ((elements (cdr top) (cdr elements)))
747 (let ((ele (car elements)))
749 (cons (rplacd (last splice) ele)
751 (null (rplacd (last splice) nil))
752 (atom (if (cdr elements)
754 (rplacd (last splice) ele))))))
760 (return top-of-top))))))))
763 (do ((1st (cdr x) (if (endp 1st) 1st (cdr 1st)))
764 (2nd x 1st) ; 2nd follows first down the list.
765 (3rd y 2nd)) ;3rd follows 2nd down the list.
769 (defun notany (fn seq)
775 (defvar *package-list* nil)
777 (defun list-all-packages ()
780 (defun make-package (name &key use)
781 (let ((package (new))
782 (use (mapcar #'find-package-or-fail use)))
783 (oset package "packageName" name)
784 (oset package "symbols" (new))
785 (oset package "exports" (new))
786 (oset package "use" use)
787 (push package *package-list*)
791 (and (objectp x) (in "symbols" x)))
793 (defun find-package (package-designator)
794 (when (packagep package-designator)
795 (return-from find-package package-designator))
796 (let ((name (string package-designator)))
797 (dolist (package *package-list*)
798 (when (string= (package-name package) name)
801 (defun find-package-or-fail (package-designator)
802 (or (find-package package-designator)
803 (error "Package unknown.")))
805 (defun package-name (package-designator)
806 (let ((package (find-package-or-fail package-designator)))
807 (oget package "packageName")))
809 (defun %package-symbols (package-designator)
810 (let ((package (find-package-or-fail package-designator)))
811 (oget package "symbols")))
813 (defun package-use-list (package-designator)
814 (let ((package (find-package-or-fail package-designator)))
815 (oget package "use")))
817 (defun %package-external-symbols (package-designator)
818 (let ((package (find-package-or-fail package-designator)))
819 (oget package "exports")))
821 (defvar *common-lisp-package*
824 (defvar *user-package*
825 (make-package "CL-USER" :use (list *common-lisp-package*)))
827 (defvar *keyword-package*
828 (make-package "KEYWORD"))
831 (and (symbolp x) (eq (symbol-package x) *keyword-package*)))
833 (defvar *package* *common-lisp-package*)
835 (defmacro in-package (package-designator)
837 (setq *package* (find-package-or-fail ,package-designator))))
839 ;; This function is used internally to initialize the CL package
840 ;; with the symbols built during bootstrap.
841 (defun %intern-symbol (symbol)
843 (if (in "package" symbol)
844 (find-package-or-fail (oget symbol "package"))
845 *common-lisp-package*))
846 (symbols (%package-symbols package)))
847 (oset symbol "package" package)
848 (when (eq package *keyword-package*)
849 (oset symbol "value" symbol))
850 (oset symbols (symbol-name symbol) symbol)))
852 (defun find-symbol (name &optional (package *package*))
853 (let* ((package (find-package-or-fail package))
854 (externals (%package-external-symbols package))
855 (symbols (%package-symbols package)))
858 (values (oget externals name) :external))
860 (values (oget symbols name) :internal))
862 (dolist (used (package-use-list package) (values nil nil))
863 (let ((exports (%package-external-symbols used)))
864 (when (in name exports)
865 (return (values (oget exports name) :inherit)))))))))
867 (defun intern (name &optional (package *package*))
868 (let ((package (find-package-or-fail package)))
869 (multiple-value-bind (symbol foundp)
870 (find-symbol name package)
872 (values symbol foundp)
873 (let ((symbols (%package-symbols package)))
875 (let ((symbol (make-symbol name)))
876 (oset symbol "package" package)
877 (when (eq package *keyword-package*)
878 (oset symbol "value" symbol)
879 (export (list symbol) package))
880 (oset symbols name symbol)
881 (values symbol nil)))))))
883 (defun symbol-package (symbol)
884 (unless (symbolp symbol)
885 (error "it is not a symbol"))
886 (oget symbol "package"))
888 (defun export (symbols &optional (package *package*))
889 (let ((exports (%package-external-symbols package)))
890 (dolist (symb symbols t)
891 (oset exports (symbol-name symb) symb))))
893 (defun get-universal-time ()
894 (+ (get-unix-time) 2208988800)))
897 ;;; The compiler offers some primitives and special forms which are
898 ;;; not found in Common Lisp, for instance, while. So, we grow Common
899 ;;; Lisp a bit to it can execute the rest of the file.
902 (defmacro while (condition &body body)
907 (defmacro eval-when-compile (&body body)
908 `(eval-when (:compile-toplevel :load-toplevel :execute)
911 (defun concat-two (s1 s2)
912 (concatenate 'string s1 s2))
914 (defun aset (array idx value)
915 (setf (aref array idx) value)))
917 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
918 ;;; from here, this code will compile on both. We define some helper
919 ;;; functions now for string manipulation and so on. They will be
920 ;;; useful in the compiler, mostly.
922 (defvar *newline* (string (code-char 10)))
924 (defun concat (&rest strs)
925 (!reduce #'concat-two strs :initial-value ""))
927 (defmacro concatf (variable &body form)
928 `(setq ,variable (concat ,variable (progn ,@form))))
930 ;;; Concatenate a list of strings, with a separator
931 (defun join (list &optional (separator ""))
940 (join (cdr list) separator)))))
942 (defun join-trailing (list &optional (separator ""))
945 (concat (car list) separator (join-trailing (cdr list) separator))))
947 (defun mapconcat (func list)
948 (join (mapcar func list)))
950 (defun vector-to-list (vector)
952 (size (length vector)))
953 (dotimes (i size (reverse list))
954 (push (aref vector i) list))))
956 (defun list-to-vector (list)
957 (let ((v (make-array (length list)))
965 (defun values-list (list)
966 (values-array (list-to-vector list)))
968 (defun values (&rest args)
971 (defun integer-to-string (x)
976 (concat "-" (integer-to-string (- 0 x))))
979 (while (not (zerop x))
980 (push (mod x 10) digits)
981 (setq x (truncate x 10)))
982 (mapconcat (lambda (x) (string (digit-char x)))
990 (defun prin1-to-string (form)
993 (multiple-value-bind (symbol foundp)
994 (find-symbol (symbol-name form) *package*)
995 (if (and foundp (eq symbol form))
997 (let ((package (symbol-package form))
998 (name (symbol-name form)))
1000 ((null package) "#")
1001 ((eq package (find-package "KEYWORD")) "")
1002 (t (package-name package)))
1004 ((integerp form) (integer-to-string form))
1005 ((stringp form) (concat "\"" (escape-string form) "\""))
1007 (let ((name (oget form "fname")))
1009 (concat "#<FUNCTION " name ">")
1010 (concat "#<FUNCTION>"))))
1013 (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
1014 (let ((last (last form)))
1015 (if (null (cdr last))
1016 (prin1-to-string (car last))
1017 (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
1020 (concat "#" (if (zerop (length form))
1022 (prin1-to-string (vector-to-list form)))))
1024 (concat "#<PACKAGE " (package-name form) ">"))
1026 (concat "#<javascript object>"))))
1028 (defun write-line (x)
1030 (write-string *newline*)
1033 (defun warn (string)
1034 (write-string "WARNING: ")
1035 (write-line string))
1038 (write-line (prin1-to-string x))
1045 ;;; The Lisp reader, parse strings and return Lisp objects. The main
1046 ;;; entry points are `ls-read' and `ls-read-from-string'.
1048 (defun make-string-stream (string)
1051 (defun %peek-char (stream)
1052 (and (< (cdr stream) (length (car stream)))
1053 (char (car stream) (cdr stream))))
1055 (defun %read-char (stream)
1056 (and (< (cdr stream) (length (car stream)))
1057 (prog1 (char (car stream) (cdr stream))
1058 (rplacd stream (1+ (cdr stream))))))
1060 (defun whitespacep (ch)
1061 (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
1063 (defun skip-whitespaces (stream)
1065 (setq ch (%peek-char stream))
1066 (while (and ch (whitespacep ch))
1068 (setq ch (%peek-char stream)))))
1070 (defun terminalp (ch)
1071 (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
1073 (defun read-until (stream func)
1076 (setq ch (%peek-char stream))
1077 (while (and ch (not (funcall func ch)))
1078 (setq string (concat string (string ch)))
1080 (setq ch (%peek-char stream)))
1083 (defun skip-whitespaces-and-comments (stream)
1085 (skip-whitespaces stream)
1086 (setq ch (%peek-char stream))
1087 (while (and ch (char= ch #\;))
1088 (read-until stream (lambda (x) (char= x #\newline)))
1089 (skip-whitespaces stream)
1090 (setq ch (%peek-char stream)))))
1092 (defun %read-list (stream)
1093 (skip-whitespaces-and-comments stream)
1094 (let ((ch (%peek-char stream)))
1097 (error "Unspected EOF"))
1103 (prog1 (ls-read stream)
1104 (skip-whitespaces-and-comments stream)
1105 (unless (char= (%read-char stream) #\))
1106 (error "')' was expected."))))
1108 (cons (ls-read stream) (%read-list stream))))))
1110 (defun read-string (stream)
1113 (setq ch (%read-char stream))
1114 (while (not (eql ch #\"))
1116 (error "Unexpected EOF"))
1118 (setq ch (%read-char stream)))
1119 (setq string (concat string (string ch)))
1120 (setq ch (%read-char stream)))
1123 (defun read-sharp (stream)
1125 (ecase (%read-char stream)
1127 (list 'function (ls-read stream)))
1128 (#\( (list-to-vector (%read-list stream)))
1129 (#\: (make-symbol (string-upcase (read-until stream #'terminalp))))
1132 (concat (string (%read-char stream))
1133 (read-until stream #'terminalp))))
1135 ((string= cname "space") (char-code #\space))
1136 ((string= cname "tab") (char-code #\tab))
1137 ((string= cname "newline") (char-code #\newline))
1138 (t (char-code (char cname 0))))))
1140 (let ((feature (read-until stream #'terminalp)))
1142 ((string= feature "common-lisp")
1143 (ls-read stream) ;ignore
1145 ((string= feature "ecmalisp")
1148 (error "Unknown reader form.")))))))
1150 ;;; Parse a string of the form NAME, PACKAGE:NAME or
1151 ;;; PACKAGE::NAME and return the name. If the string is of the
1152 ;;; form 1) or 3), but the symbol does not exist, it will be created
1153 ;;; and interned in that package.
1154 (defun read-symbol (string)
1155 (let ((size (length string))
1156 package name internalp index)
1158 (while (and (< index size)
1159 (not (char= (char string index) #\:)))
1162 ;; No package prefix
1165 (setq package *package*)
1170 (setq package "KEYWORD")
1171 (setq package (string-upcase (subseq string 0 index))))
1173 (when (char= (char string index) #\:)
1176 (setq name (subseq string index))))
1177 ;; Canonalize symbol name and package
1178 (setq name (string-upcase name))
1179 (setq package (find-package package))
1180 ;; TODO: PACKAGE:SYMBOL should signal error if SYMBOL is not an
1181 ;; external symbol from PACKAGE.
1182 (if (or internalp (eq package (find-package "KEYWORD")))
1183 (intern name package)
1184 (find-symbol name package))))
1187 (defun !parse-integer (string junk-allow)
1191 (size (length string))
1193 (when (zerop size) (return (values nil 0)))
1195 (case (char string 0)
1200 (unless (and (< index size)
1201 (setq value (digit-char-p (char string index))))
1202 (return (values nil index)))
1205 (while (< index size)
1206 (let ((digit (digit-char-p (char string index))))
1207 (unless digit (return))
1208 (setq value (+ (* value 10) digit))
1212 (char= (char string index) #\space))
1213 (values (* sign value) index)
1214 (values nil index)))))
1217 (defun parse-integer (string)
1218 (!parse-integer string nil))
1220 (defvar *eof* (gensym))
1221 (defun ls-read (stream)
1222 (skip-whitespaces-and-comments stream)
1223 (let ((ch (%peek-char stream)))
1225 ((or (null ch) (char= ch #\)))
1229 (%read-list stream))
1232 (list 'quote (ls-read stream)))
1235 (list 'backquote (ls-read stream)))
1238 (read-string stream))
1241 (if (eql (%peek-char stream) #\@)
1242 (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
1243 (list 'unquote (ls-read stream))))
1245 (read-sharp stream))
1247 (let ((string (read-until stream #'terminalp)))
1248 (or (values (!parse-integer string nil))
1249 (read-symbol string)))))))
1251 (defun ls-read-from-string (string)
1252 (ls-read (make-string-stream string)))
1257 ;;; Translate the Lisp code to Javascript. It will compile the special
1258 ;;; forms. Some primitive functions are compiled as special forms
1259 ;;; too. The respective real functions are defined in the target (see
1260 ;;; the beginning of this file) as well as some primitive functions.
1262 (defun code (&rest args)
1263 (mapconcat (lambda (arg)
1266 ((integerp arg) (integer-to-string arg))
1268 (t (error "Unknown argument."))))
1271 ;;; Wrap X with a Javascript code to convert the result from
1272 ;;; Javascript generalized booleans to T or NIL.
1274 (code "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
1276 ;;; Concatenate the arguments and wrap them with a self-calling
1277 ;;; Javascript anonymous function. It is used to make some Javascript
1278 ;;; statements valid expressions and provide a private scope as well.
1279 ;;; It could be defined as function, but we could do some
1280 ;;; preprocessing in the future.
1281 (defmacro js!selfcall (&body body)
1282 `(code "(function(){" *newline* (indent ,@body) "})()"))
1284 ;;; Like CODE, but prefix each line with four spaces. Two versions
1285 ;;; of this function are available, because the Ecmalisp version is
1286 ;;; very slow and bootstraping was annoying.
1289 (defun indent (&rest string)
1290 (let ((input (apply #'code string)))
1293 (size (length input)))
1294 (when (plusp (length input)) (concatf output " "))
1295 (while (< index size)
1297 (if (and (char= (char input index) #\newline)
1299 (not (char= (char input (1+ index)) #\newline)))
1300 (concat (string #\newline) " ")
1301 (string (char input index)))))
1302 (concatf output str))
1307 (defun indent (&rest string)
1308 (with-output-to-string (*standard-output*)
1309 (with-input-from-string (input (apply #'code string))
1311 for line = (read-line input nil)
1313 do (write-string " ")
1314 do (write-line line)))))
1317 ;;; A Form can return a multiple values object calling VALUES, like
1318 ;;; values(arg1, arg2, ...). It will work in any context, as well as
1319 ;;; returning an individual object. However, if the special variable
1320 ;;; `*multiple-value-p*' is NIL, is granted that only the primary
1321 ;;; value will be used, so we can optimize to avoid the VALUES
1323 (defvar *multiple-value-p* nil)
1325 (defun make-binding (name type value &optional declarations)
1326 (list name type value declarations))
1328 (defun binding-name (b) (first b))
1329 (defun binding-type (b) (second b))
1330 (defun binding-value (b) (third b))
1331 (defun binding-declarations (b) (fourth b))
1333 (defun set-binding-value (b value)
1334 (rplaca (cddr b) value))
1336 (defun set-binding-declarations (b value)
1337 (rplaca (cdddr b) value))
1339 (defun push-binding-declaration (decl b)
1340 (set-binding-declarations b (cons decl (binding-declarations b))))
1343 (defun make-lexenv ()
1344 (list nil nil nil nil))
1346 (defun copy-lexenv (lexenv)
1349 (defun push-to-lexenv (binding lexenv namespace)
1351 (variable (rplaca lexenv (cons binding (car lexenv))))
1352 (function (rplaca (cdr lexenv) (cons binding (cadr lexenv))))
1353 (block (rplaca (cddr lexenv) (cons binding (caddr lexenv))))
1354 (gotag (rplaca (cdddr lexenv) (cons binding (cadddr lexenv))))))
1356 (defun extend-lexenv (bindings lexenv namespace)
1357 (let ((env (copy-lexenv lexenv)))
1358 (dolist (binding (reverse bindings) env)
1359 (push-to-lexenv binding env namespace))))
1361 (defun lookup-in-lexenv (name lexenv namespace)
1362 (assoc name (ecase namespace
1363 (variable (first lexenv))
1364 (function (second lexenv))
1365 (block (third lexenv))
1366 (gotag (fourth lexenv)))))
1368 (defvar *environment* (make-lexenv))
1370 (defvar *variable-counter* 0)
1371 (defun gvarname (symbol)
1372 (code "v" (incf *variable-counter*)))
1374 (defun translate-variable (symbol)
1375 (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
1377 (defun extend-local-env (args)
1378 (let ((new (copy-lexenv *environment*)))
1379 (dolist (symbol args new)
1380 (let ((b (make-binding symbol 'variable (gvarname symbol))))
1381 (push-to-lexenv b new 'variable)))))
1383 ;;; Toplevel compilations
1384 (defvar *toplevel-compilations* nil)
1386 (defun toplevel-compilation (string)
1387 (push string *toplevel-compilations*))
1389 (defun null-or-empty-p (x)
1392 (defun get-toplevel-compilations ()
1393 (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
1395 (defun %compile-defmacro (name lambda)
1396 (toplevel-compilation (ls-compile `',name))
1397 (push-to-lexenv (make-binding name 'macro lambda) *environment* 'function)
1400 (defun global-binding (name type namespace)
1401 (or (lookup-in-lexenv name *environment* namespace)
1402 (let ((b (make-binding name type nil)))
1403 (push-to-lexenv b *environment* namespace)
1406 (defun claimp (symbol namespace claim)
1407 (let ((b (lookup-in-lexenv symbol *environment* namespace)))
1408 (and b (member claim (binding-declarations b)))))
1410 (defun !proclaim (decl)
1413 (dolist (name (cdr decl))
1414 (let ((b (global-binding name 'variable 'variable)))
1415 (push-binding-declaration 'special b))))
1417 (dolist (name (cdr decl))
1418 (let ((b (global-binding name 'function 'function)))
1419 (push-binding-declaration 'notinline b))))
1421 (dolist (name (cdr decl))
1422 (let ((b (global-binding name 'variable 'variable)))
1423 (push-binding-declaration 'constant b))))))
1426 (fset 'proclaim #'!proclaim)
1430 (defvar *compilations* nil)
1432 (defmacro define-compilation (name args &body body)
1433 ;; Creates a new primitive `name' with parameters args and
1434 ;; @body. The body can access to the local environment through the
1435 ;; variable *ENVIRONMENT*.
1436 `(push (list ',name (lambda ,args (block ,name ,@body)))
1439 (define-compilation if (condition true false)
1440 (code "(" (ls-compile condition) " !== " (ls-compile nil)
1441 " ? " (ls-compile true *multiple-value-p*)
1442 " : " (ls-compile false *multiple-value-p*)
1445 (defvar *ll-keywords* '(&optional &rest &key))
1447 (defun list-until-keyword (list)
1448 (if (or (null list) (member (car list) *ll-keywords*))
1450 (cons (car list) (list-until-keyword (cdr list)))))
1452 (defun ll-section (keyword ll)
1453 (list-until-keyword (cdr (member keyword ll))))
1455 (defun ll-required-arguments (ll)
1456 (list-until-keyword ll))
1458 (defun ll-optional-arguments-canonical (ll)
1459 (mapcar #'ensure-list (ll-section '&optional ll)))
1461 (defun ll-optional-arguments (ll)
1462 (mapcar #'car (ll-optional-arguments-canonical ll)))
1464 (defun ll-rest-argument (ll)
1465 (let ((rest (ll-section '&rest ll)))
1467 (error "Bad lambda-list"))
1470 (defun ll-keyword-arguments-canonical (ll)
1471 (flet ((canonicalize (keyarg)
1472 ;; Build a canonical keyword argument descriptor, filling
1473 ;; the optional fields. The result is a list of the form
1474 ;; ((keyword-name var) init-form).
1475 (let ((arg (ensure-list keyarg)))
1476 (cons (if (listp (car arg))
1478 (list (intern (symbol-name (car arg)) "KEYWORD") (car arg)))
1480 (mapcar #'canonicalize (ll-section '&key ll))))
1482 (defun ll-keyword-arguments (ll)
1483 (mapcar (lambda (keyarg) (second (first keyarg)))
1484 (ll-keyword-arguments-canonical ll)))
1486 (defun ll-svars (lambda-list)
1489 (ll-keyword-arguments-canonical lambda-list)
1490 (ll-optional-arguments-canonical lambda-list))))
1491 (remove nil (mapcar #'third args))))
1493 (defun lambda-docstring-wrapper (docstring &rest strs)
1496 "var func = " (join strs) ";" *newline*
1497 "func.docstring = '" docstring "';" *newline*
1498 "return func;" *newline*)
1499 (apply #'code strs)))
1501 (defun lambda-check-argument-count
1502 (n-required-arguments n-optional-arguments rest-p)
1503 ;; Note: Remember that we assume that the number of arguments of a
1504 ;; call is at least 1 (the values argument).
1505 (let ((min (1+ n-required-arguments))
1506 (max (if rest-p 'n/a (+ 1 n-required-arguments n-optional-arguments))))
1508 ;; Special case: a positive exact number of arguments.
1509 (when (and (< 1 min) (eql min max))
1510 (return (code "checkArgs(arguments, " min ");" *newline*)))
1514 (code "checkArgsAtLeast(arguments, " min ");" *newline*))
1516 (code "checkArgsAtMost(arguments, " max ");" *newline*))))))
1518 (defun compile-lambda-optional (ll)
1519 (let* ((optional-arguments (ll-optional-arguments-canonical ll))
1520 (n-required-arguments (length (ll-required-arguments ll)))
1521 (n-optional-arguments (length optional-arguments)))
1522 (when optional-arguments
1523 (code (mapconcat (lambda (arg)
1524 (code "var " (translate-variable (first arg)) "; " *newline*
1526 (code "var " (translate-variable (third arg))
1527 " = " (ls-compile t)
1530 "switch(arguments.length-1){" *newline*
1534 (while (< idx n-optional-arguments)
1535 (let ((arg (nth idx optional-arguments)))
1536 (push (code "case " (+ idx n-required-arguments) ":" *newline*
1537 (indent (translate-variable (car arg))
1539 (ls-compile (cadr arg)) ";" *newline*)
1541 (indent (translate-variable (third arg))
1547 (push (code "default: break;" *newline*) cases)
1548 (join (reverse cases))))
1551 (defun compile-lambda-rest (ll)
1552 (let ((n-required-arguments (length (ll-required-arguments ll)))
1553 (n-optional-arguments (length (ll-optional-arguments ll)))
1554 (rest-argument (ll-rest-argument ll)))
1556 (let ((js!rest (translate-variable rest-argument)))
1557 (code "var " js!rest "= " (ls-compile nil) ";" *newline*
1558 "for (var i = arguments.length-1; i>="
1559 (+ 1 n-required-arguments n-optional-arguments)
1561 (indent js!rest " = {car: arguments[i], cdr: ") js!rest "};"
1564 (defun compile-lambda-parse-keywords (ll)
1565 (let ((n-required-arguments
1566 (length (ll-required-arguments ll)))
1567 (n-optional-arguments
1568 (length (ll-optional-arguments ll)))
1570 (ll-keyword-arguments-canonical ll)))
1572 ;; Declare variables
1573 (mapconcat (lambda (arg)
1574 (let ((var (second (car arg))))
1575 (code "var " (translate-variable var) "; " *newline*
1577 (code "var " (translate-variable (third arg))
1578 " = " (ls-compile nil)
1582 (flet ((parse-keyword (keyarg)
1583 ;; ((keyword-name var) init-form)
1584 (code "for (i=" (+ 1 n-required-arguments n-optional-arguments)
1585 "; i<arguments.length; i+=2){" *newline*
1587 "if (arguments[i] === " (ls-compile (caar keyarg)) "){" *newline*
1588 (indent (translate-variable (cadr (car keyarg)))
1589 " = arguments[i+1];"
1591 (let ((svar (third keyarg)))
1593 (code (translate-variable svar) " = " (ls-compile t) ";" *newline*)))
1598 "if (i == arguments.length){" *newline*
1599 (indent (translate-variable (cadr (car keyarg))) " = " (ls-compile (cadr keyarg)) ";" *newline*)
1601 (when keyword-arguments
1602 (code "var i;" *newline*
1603 (mapconcat #'parse-keyword keyword-arguments))))
1604 ;; Check for unknown keywords
1605 (when keyword-arguments
1606 (code "for (i=" (+ 1 n-required-arguments n-optional-arguments)
1607 "; i<arguments.length; i+=2){" *newline*
1609 (join (mapcar (lambda (x)
1610 (concat "arguments[i] !== " (ls-compile (caar x))))
1615 "throw 'Unknown keyword argument ' + arguments[i].name;" *newline*))
1618 (defun compile-lambda (ll body)
1619 (let ((required-arguments (ll-required-arguments ll))
1620 (optional-arguments (ll-optional-arguments ll))
1621 (keyword-arguments (ll-keyword-arguments ll))
1622 (rest-argument (ll-rest-argument ll))
1624 ;; Get the documentation string for the lambda function
1625 (when (and (stringp (car body))
1626 (not (null (cdr body))))
1627 (setq documentation (car body))
1628 (setq body (cdr body)))
1629 (let ((n-required-arguments (length required-arguments))
1630 (n-optional-arguments (length optional-arguments))
1631 (*environment* (extend-local-env
1632 (append (ensure-list rest-argument)
1637 (lambda-docstring-wrapper
1640 (join (cons "values"
1641 (mapcar #'translate-variable
1642 (append required-arguments optional-arguments)))
1646 ;; Check number of arguments
1647 (lambda-check-argument-count n-required-arguments
1648 n-optional-arguments
1649 (or rest-argument keyword-arguments))
1650 (compile-lambda-optional ll)
1651 (compile-lambda-rest ll)
1652 (compile-lambda-parse-keywords ll)
1653 (let ((*multiple-value-p* t))
1654 (ls-compile-block body t)))
1659 (defun setq-pair (var val)
1660 (let ((b (lookup-in-lexenv var *environment* 'variable)))
1661 (if (and (eq (binding-type b) 'variable)
1662 (not (member 'special (binding-declarations b)))
1663 (not (member 'constant (binding-declarations b))))
1664 (code (binding-value b) " = " (ls-compile val))
1665 (ls-compile `(set ',var ,val)))))
1667 (define-compilation setq (&rest pairs)
1671 ((null pairs) (return))
1673 (error "Odd paris in SETQ"))
1676 (concat (setq-pair (car pairs) (cadr pairs))
1677 (if (null (cddr pairs)) "" ", ")))
1678 (setq pairs (cddr pairs)))))
1679 (code "(" result ")")))
1681 ;;; FFI Variable accessors
1682 (define-compilation js-vref (var)
1685 (define-compilation js-vset (var val)
1686 (code "(" var " = " (ls-compile val) ")"))
1690 (defun escape-string (string)
1693 (size (length string)))
1694 (while (< index size)
1695 (let ((ch (char string index)))
1696 (when (or (char= ch #\") (char= ch #\\))
1697 (setq output (concat output "\\")))
1698 (when (or (char= ch #\newline))
1699 (setq output (concat output "\\"))
1701 (setq output (concat output (string ch))))
1706 (defvar *literal-symbols* nil)
1707 (defvar *literal-counter* 0)
1710 (code "l" (incf *literal-counter*)))
1712 (defun literal (sexp &optional recursive)
1714 ((integerp sexp) (integer-to-string sexp))
1715 ((stringp sexp) (code "\"" (escape-string sexp) "\""))
1717 (or (cdr (assoc sexp *literal-symbols*))
1720 (let ((package (symbol-package sexp)))
1721 (if (eq package (find-package "KEYWORD"))
1722 (code "{name: \"" (escape-string (symbol-name sexp))
1723 "\", 'package': '" (package-name package) "'}")
1724 (code "{name: \"" (escape-string (symbol-name sexp)) "\"}")))
1726 (let ((package (symbol-package sexp)))
1728 (code "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1729 (ls-compile `(intern ,(symbol-name sexp) ,(package-name package)))))))
1730 (push (cons sexp v) *literal-symbols*)
1731 (toplevel-compilation (code "var " v " = " s))
1734 (let* ((head (butlast sexp))
1737 (join-trailing (mapcar (lambda (x) (literal x t)) head) ",")
1738 (literal (car tail) t)
1740 (literal (cdr tail) t)
1745 (toplevel-compilation (code "var " v " = " c))
1748 (let ((elements (vector-to-list sexp)))
1749 (let ((c (concat "[" (join (mapcar #'literal elements) ", ") "]")))
1753 (toplevel-compilation (code "var " v " = " c))
1756 (define-compilation quote (sexp)
1759 (define-compilation %while (pred &rest body)
1761 "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1762 (indent (ls-compile-block body))
1764 "return " (ls-compile nil) ";" *newline*))
1766 (define-compilation function (x)
1768 ((and (listp x) (eq (car x) 'lambda))
1769 (compile-lambda (cadr x) (cddr x)))
1771 (let ((b (lookup-in-lexenv x *environment* 'function)))
1774 (ls-compile `(symbol-function ',x)))))))
1777 (defun make-function-binding (fname)
1778 (make-binding fname 'function (gvarname fname)))
1780 (defun compile-function-definition (list)
1781 (compile-lambda (car list) (cdr list)))
1783 (defun translate-function (name)
1784 (let ((b (lookup-in-lexenv name *environment* 'function)))
1787 (define-compilation flet (definitions &rest body)
1788 (let* ((fnames (mapcar #'car definitions))
1789 (fbody (mapcar #'cdr definitions))
1790 (cfuncs (mapcar #'compile-function-definition fbody))
1792 (extend-lexenv (mapcar #'make-function-binding fnames)
1796 (join (mapcar #'translate-function fnames) ",")
1798 (let ((body (ls-compile-block body t)))
1800 "})(" (join cfuncs ",") ")")))
1802 (define-compilation labels (definitions &rest body)
1803 (let* ((fnames (mapcar #'car definitions))
1805 (extend-lexenv (mapcar #'make-function-binding fnames)
1809 (mapconcat (lambda (func)
1810 (code "var " (translate-function (car func))
1811 " = " (compile-lambda (cadr func) (cddr func))
1814 (ls-compile-block body t))))
1817 (defvar *compiling-file* nil)
1818 (define-compilation eval-when-compile (&rest body)
1819 (if *compiling-file*
1821 (eval (cons 'progn body))
1823 (ls-compile `(progn ,@body))))
1825 (defmacro define-transformation (name args form)
1826 `(define-compilation ,name ,args
1827 (ls-compile ,form)))
1829 (define-compilation progn (&rest body)
1830 (if (null (cdr body))
1831 (ls-compile (car body) *multiple-value-p*)
1832 (js!selfcall (ls-compile-block body t))))
1834 (defun special-variable-p (x)
1835 (and (claimp x 'variable 'special) t))
1837 ;;; Wrap CODE to restore the symbol values of the dynamic
1838 ;;; bindings. BINDINGS is a list of pairs of the form
1839 ;;; (SYMBOL . PLACE), where PLACE is a Javascript variable
1840 ;;; name to initialize the symbol value and where to stored
1842 (defun let-binding-wrapper (bindings body)
1843 (when (null bindings)
1844 (return-from let-binding-wrapper body))
1847 (indent "var tmp;" *newline*
1850 (let ((s (ls-compile `(quote ,(car b)))))
1851 (code "tmp = " s ".value;" *newline*
1852 s ".value = " (cdr b) ";" *newline*
1853 (cdr b) " = tmp;" *newline*)))
1857 "finally {" *newline*
1859 (mapconcat (lambda (b)
1860 (let ((s (ls-compile `(quote ,(car b)))))
1861 (code s ".value" " = " (cdr b) ";" *newline*)))
1865 (define-compilation let (bindings &rest body)
1866 (let* ((bindings (mapcar #'ensure-list bindings))
1867 (variables (mapcar #'first bindings))
1868 (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
1869 (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
1872 (join (mapcar (lambda (x)
1873 (if (special-variable-p x)
1874 (let ((v (gvarname x)))
1875 (push (cons x v) dynamic-bindings)
1877 (translate-variable x)))
1881 (let ((body (ls-compile-block body t)))
1882 (indent (let-binding-wrapper dynamic-bindings body)))
1883 "})(" (join cvalues ",") ")")))
1886 ;;; Return the code to initialize BINDING, and push it extending the
1887 ;;; current lexical environment if the variable is not special.
1888 (defun let*-initialize-value (binding)
1889 (let ((var (first binding))
1890 (value (second binding)))
1891 (if (special-variable-p var)
1892 (code (ls-compile `(setq ,var ,value)) ";" *newline*)
1893 (let* ((v (gvarname var))
1894 (b (make-binding var 'variable v)))
1895 (prog1 (code "var " v " = " (ls-compile value) ";" *newline*)
1896 (push-to-lexenv b *environment* 'variable))))))
1898 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
1899 ;;; DOES NOT generate code to initialize the value of the symbols,
1900 ;;; unlike let-binding-wrapper.
1901 (defun let*-binding-wrapper (symbols body)
1902 (when (null symbols)
1903 (return-from let*-binding-wrapper body))
1904 (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
1905 (remove-if-not #'special-variable-p symbols))))
1909 (mapconcat (lambda (b)
1910 (let ((s (ls-compile `(quote ,(car b)))))
1911 (code "var " (cdr b) " = " s ".value;" *newline*)))
1915 "finally {" *newline*
1917 (mapconcat (lambda (b)
1918 (let ((s (ls-compile `(quote ,(car b)))))
1919 (code s ".value" " = " (cdr b) ";" *newline*)))
1923 (define-compilation let* (bindings &rest body)
1924 (let ((bindings (mapcar #'ensure-list bindings))
1925 (*environment* (copy-lexenv *environment*)))
1927 (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
1928 (body (concat (mapconcat #'let*-initialize-value bindings)
1929 (ls-compile-block body t))))
1930 (let*-binding-wrapper specials body)))))
1933 (defvar *block-counter* 0)
1935 (define-compilation block (name &rest body)
1936 (let* ((tr (incf *block-counter*))
1937 (b (make-binding name 'block tr)))
1938 (when *multiple-value-p*
1939 (push-binding-declaration 'multiple-value b))
1940 (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
1941 (cbody (ls-compile-block body t)))
1942 (if (member 'used (binding-declarations b))
1947 "catch (cf){" *newline*
1948 " if (cf.type == 'block' && cf.id == " tr ")" *newline*
1949 (if *multiple-value-p*
1950 " return values.apply(this, forcemv(cf.values));"
1951 " return cf.values;")
1954 " throw cf;" *newline*
1956 (js!selfcall cbody)))))
1958 (define-compilation return-from (name &optional value)
1959 (let* ((b (lookup-in-lexenv name *environment* 'block))
1960 (multiple-value-p (member 'multiple-value (binding-declarations b))))
1962 (error (concat "Unknown block `" (symbol-name name) "'.")))
1963 (push-binding-declaration 'used b)
1965 (when multiple-value-p (code "var values = mv;" *newline*))
1968 "id: " (binding-value b) ", "
1969 "values: " (ls-compile value multiple-value-p) ", "
1970 "message: 'Return from unknown block " (symbol-name name) ".'"
1973 (define-compilation catch (id &rest body)
1975 "var id = " (ls-compile id) ";" *newline*
1977 (indent (ls-compile-block body t)) *newline*
1979 "catch (cf){" *newline*
1980 " if (cf.type == 'catch' && cf.id == id)" *newline*
1981 (if *multiple-value-p*
1982 " return values.apply(this, forcemv(cf.values));"
1983 " return pv.apply(this, forcemv(cf.values));")
1986 " throw cf;" *newline*
1989 (define-compilation throw (id value)
1991 "var values = mv;" *newline*
1994 "id: " (ls-compile id) ", "
1995 "values: " (ls-compile value t) ", "
1996 "message: 'Throw uncatched.'"
2000 (defvar *tagbody-counter* 0)
2001 (defvar *go-tag-counter* 0)
2004 (or (integerp x) (symbolp x)))
2006 (defun declare-tagbody-tags (tbidx body)
2008 (mapcar (lambda (label)
2009 (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
2010 (make-binding label 'gotag (list tbidx tagidx))))
2011 (remove-if-not #'go-tag-p body))))
2012 (extend-lexenv bindings *environment* 'gotag)))
2014 (define-compilation tagbody (&rest body)
2015 ;; Ignore the tagbody if it does not contain any go-tag. We do this
2016 ;; because 1) it is easy and 2) many built-in forms expand to a
2017 ;; implicit tagbody, so we save some space.
2018 (unless (some #'go-tag-p body)
2019 (return-from tagbody (ls-compile `(progn ,@body nil))))
2020 ;; The translation assumes the first form in BODY is a label
2021 (unless (go-tag-p (car body))
2022 (push (gensym "START") body))
2023 ;; Tagbody compilation
2024 (let ((tbidx *tagbody-counter*))
2025 (let ((*environment* (declare-tagbody-tags tbidx body))
2027 (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
2028 (setq initag (second (binding-value b))))
2030 "var tagbody_" tbidx " = " initag ";" *newline*
2032 "while (true) {" *newline*
2033 (indent "try {" *newline*
2034 (indent (let ((content ""))
2035 (code "switch(tagbody_" tbidx "){" *newline*
2036 "case " initag ":" *newline*
2037 (dolist (form (cdr body) content)
2039 (if (not (go-tag-p form))
2040 (indent (ls-compile form) ";" *newline*)
2041 (let ((b (lookup-in-lexenv form *environment* 'gotag)))
2042 (code "case " (second (binding-value b)) ":" *newline*)))))
2043 "default:" *newline*
2044 " break tbloop;" *newline*
2047 "catch (jump) {" *newline*
2048 " if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
2049 " tagbody_" tbidx " = jump.label;" *newline*
2051 " throw(jump);" *newline*
2054 "return " (ls-compile nil) ";" *newline*))))
2056 (define-compilation go (label)
2057 (let ((b (lookup-in-lexenv label *environment* 'gotag))
2059 ((symbolp label) (symbol-name label))
2060 ((integerp label) (integer-to-string label)))))
2062 (error (concat "Unknown tag `" n "'.")))
2066 "id: " (first (binding-value b)) ", "
2067 "label: " (second (binding-value b)) ", "
2068 "message: 'Attempt to GO to non-existing tag " n "'"
2071 (define-compilation unwind-protect (form &rest clean-up)
2073 "var ret = " (ls-compile nil) ";" *newline*
2075 (indent "ret = " (ls-compile form) ";" *newline*)
2076 "} finally {" *newline*
2077 (indent (ls-compile-block clean-up))
2079 "return ret;" *newline*))
2081 (define-compilation multiple-value-call (func-form &rest forms)
2083 "var func = " (ls-compile func-form) ";" *newline*
2084 "var args = [" (if *multiple-value-p* "values" "pv") "];" *newline*
2087 "var values = mv;" *newline*
2089 (mapconcat (lambda (form)
2090 (code "vs = " (ls-compile form t) ";" *newline*
2091 "if (typeof vs === 'object' && 'multiple-value' in vs)" *newline*
2092 (indent "args = args.concat(vs);" *newline*)
2094 (indent "args.push(vs);" *newline*)))
2096 "return func.apply(window, args);" *newline*) ";" *newline*))
2098 (define-compilation multiple-value-prog1 (first-form &rest forms)
2100 "var args = " (ls-compile first-form *multiple-value-p*) ";" *newline*
2101 (ls-compile-block forms)
2102 "return args;" *newline*))
2105 ;;; Backquote implementation.
2107 ;;; Author: Guy L. Steele Jr. Date: 27 December 1985
2108 ;;; Tested under Symbolics Common Lisp and Lucid Common Lisp.
2109 ;;; This software is in the public domain.
2111 ;;; The following are unique tokens used during processing.
2112 ;;; They need not be symbols; they need not even be atoms.
2113 (defvar *comma* 'unquote)
2114 (defvar *comma-atsign* 'unquote-splicing)
2116 (defvar *bq-list* (make-symbol "BQ-LIST"))
2117 (defvar *bq-append* (make-symbol "BQ-APPEND"))
2118 (defvar *bq-list** (make-symbol "BQ-LIST*"))
2119 (defvar *bq-nconc* (make-symbol "BQ-NCONC"))
2120 (defvar *bq-clobberable* (make-symbol "BQ-CLOBBERABLE"))
2121 (defvar *bq-quote* (make-symbol "BQ-QUOTE"))
2122 (defvar *bq-quote-nil* (list *bq-quote* nil))
2124 ;;; BACKQUOTE is an ordinary macro (not a read-macro) that processes
2125 ;;; the expression foo, looking for occurrences of #:COMMA,
2126 ;;; #:COMMA-ATSIGN, and #:COMMA-DOT. It constructs code in strict
2127 ;;; accordance with the rules on pages 349-350 of the first edition
2128 ;;; (pages 528-529 of this second edition). It then optionally
2129 ;;; applies a code simplifier.
2131 ;;; If the value of *BQ-SIMPLIFY* is non-NIL, then BACKQUOTE
2132 ;;; processing applies the code simplifier. If the value is NIL,
2133 ;;; then the code resulting from BACKQUOTE is exactly that
2134 ;;; specified by the official rules.
2135 (defparameter *bq-simplify* t)
2137 (defmacro backquote (x)
2138 (bq-completely-process x))
2140 ;;; Backquote processing proceeds in three stages:
2142 ;;; (1) BQ-PROCESS applies the rules to remove occurrences of
2143 ;;; #:COMMA, #:COMMA-ATSIGN, and #:COMMA-DOT corresponding to
2144 ;;; this level of BACKQUOTE. (It also causes embedded calls to
2145 ;;; BACKQUOTE to be expanded so that nesting is properly handled.)
2146 ;;; Code is produced that is expressed in terms of functions
2147 ;;; #:BQ-LIST, #:BQ-APPEND, and #:BQ-CLOBBERABLE. This is done
2148 ;;; so that the simplifier will simplify only list construction
2149 ;;; functions actually generated by BACKQUOTE and will not involve
2150 ;;; any user code in the simplification. #:BQ-LIST means LIST,
2151 ;;; #:BQ-APPEND means APPEND, and #:BQ-CLOBBERABLE means IDENTITY
2152 ;;; but indicates places where "%." was used and where NCONC may
2153 ;;; therefore be introduced by the simplifier for efficiency.
2155 ;;; (2) BQ-SIMPLIFY, if used, rewrites the code produced by
2156 ;;; BQ-PROCESS to produce equivalent but faster code. The
2157 ;;; additional functions #:BQ-LIST* and #:BQ-NCONC may be
2158 ;;; introduced into the code.
2160 ;;; (3) BQ-REMOVE-TOKENS goes through the code and replaces
2161 ;;; #:BQ-LIST with LIST, #:BQ-APPEND with APPEND, and so on.
2162 ;;; #:BQ-CLOBBERABLE is simply eliminated (a call to it being
2163 ;;; replaced by its argument). #:BQ-LIST* is replaced by either
2164 ;;; LIST* or CONS (the latter is used in the two-argument case,
2165 ;;; purely to make the resulting code a tad more readable).
2167 (defun bq-completely-process (x)
2168 (let ((raw-result (bq-process x)))
2169 (bq-remove-tokens (if *bq-simplify*
2170 (bq-simplify raw-result)
2173 (defun bq-process (x)
2175 (list *bq-quote* x))
2176 ((eq (car x) 'backquote)
2177 (bq-process (bq-completely-process (cadr x))))
2178 ((eq (car x) *comma*) (cadr x))
2179 ((eq (car x) *comma-atsign*)
2180 ;; (error ",@~S after `" (cadr x))
2181 (error "ill-formed"))
2182 ;; ((eq (car x) *comma-dot*)
2183 ;; ;; (error ",.~S after `" (cadr x))
2184 ;; (error "ill-formed"))
2185 (t (do ((p x (cdr p))
2186 (q '() (cons (bracket (car p)) q)))
2189 (nreconc q (list (list *bq-quote* p)))))
2190 (when (eq (car p) *comma*)
2191 (unless (null (cddr p))
2192 ;; (error "Malformed ,~S" p)
2193 (error "Malformed"))
2194 (return (cons *bq-append*
2195 (nreconc q (list (cadr p))))))
2196 (when (eq (car p) *comma-atsign*)
2197 ;; (error "Dotted ,@~S" p)
2199 ;; (when (eq (car p) *comma-dot*)
2200 ;; ;; (error "Dotted ,.~S" p)
2201 ;; (error "Dotted"))
2204 ;;; This implements the bracket operator of the formal rules.
2207 (list *bq-list* (bq-process x)))
2208 ((eq (car x) *comma*)
2209 (list *bq-list* (cadr x)))
2210 ((eq (car x) *comma-atsign*)
2212 ;; ((eq (car x) *comma-dot*)
2213 ;; (list *bq-clobberable* (cadr x)))
2214 (t (list *bq-list* (bq-process x)))))
2216 ;;; This auxiliary function is like MAPCAR but has two extra
2217 ;;; purposes: (1) it handles dotted lists; (2) it tries to make
2218 ;;; the result share with the argument x as much as possible.
2219 (defun maptree (fn x)
2222 (let ((a (funcall fn (car x)))
2223 (d (maptree fn (cdr x))))
2224 (if (and (eql a (car x)) (eql d (cdr x)))
2228 ;;; This predicate is true of a form that when read looked
2229 ;;; like %@foo or %.foo.
2230 (defun bq-splicing-frob (x)
2232 (or (eq (car x) *comma-atsign*)
2233 ;; (eq (car x) *comma-dot*)
2236 ;;; This predicate is true of a form that when read
2237 ;;; looked like %@foo or %.foo or just plain %foo.
2240 (or (eq (car x) *comma*)
2241 (eq (car x) *comma-atsign*)
2242 ;; (eq (car x) *comma-dot*)
2245 ;;; The simplifier essentially looks for calls to #:BQ-APPEND and
2246 ;;; tries to simplify them. The arguments to #:BQ-APPEND are
2247 ;;; processed from right to left, building up a replacement form.
2248 ;;; At each step a number of special cases are handled that,
2249 ;;; loosely speaking, look like this:
2251 ;;; (APPEND (LIST a b c) foo) => (LIST* a b c foo)
2252 ;;; provided a, b, c are not splicing frobs
2253 ;;; (APPEND (LIST* a b c) foo) => (LIST* a b (APPEND c foo))
2254 ;;; provided a, b, c are not splicing frobs
2255 ;;; (APPEND (QUOTE (x)) foo) => (LIST* (QUOTE x) foo)
2256 ;;; (APPEND (CLOBBERABLE x) foo) => (NCONC x foo)
2257 (defun bq-simplify (x)
2260 (let ((x (if (eq (car x) *bq-quote*)
2262 (maptree #'bq-simplify x))))
2263 (if (not (eq (car x) *bq-append*))
2265 (bq-simplify-args x)))))
2267 (defun bq-simplify-args (x)
2268 (do ((args (reverse (cdr x)) (cdr args))
2271 (cond ((atom (car args))
2272 (bq-attach-append *bq-append* (car args) result))
2273 ((and (eq (caar args) *bq-list*)
2274 (notany #'bq-splicing-frob (cdar args)))
2275 (bq-attach-conses (cdar args) result))
2276 ((and (eq (caar args) *bq-list**)
2277 (notany #'bq-splicing-frob (cdar args)))
2279 (reverse (cdr (reverse (cdar args))))
2280 (bq-attach-append *bq-append*
2281 (car (last (car args)))
2283 ((and (eq (caar args) *bq-quote*)
2284 (consp (cadar args))
2285 (not (bq-frob (cadar args)))
2286 (null (cddar args)))
2287 (bq-attach-conses (list (list *bq-quote*
2290 ((eq (caar args) *bq-clobberable*)
2291 (bq-attach-append *bq-nconc* (cadar args) result))
2292 (t (bq-attach-append *bq-append*
2295 ((null args) result)))
2297 (defun null-or-quoted (x)
2298 (or (null x) (and (consp x) (eq (car x) *bq-quote*))))
2300 ;;; When BQ-ATTACH-APPEND is called, the OP should be #:BQ-APPEND
2301 ;;; or #:BQ-NCONC. This produces a form (op item result) but
2302 ;;; some simplifications are done on the fly:
2304 ;;; (op '(a b c) '(d e f g)) => '(a b c d e f g)
2305 ;;; (op item 'nil) => item, provided item is not a splicable frob
2306 ;;; (op item 'nil) => (op item), if item is a splicable frob
2307 ;;; (op item (op a b c)) => (op item a b c)
2308 (defun bq-attach-append (op item result)
2309 (cond ((and (null-or-quoted item) (null-or-quoted result))
2310 (list *bq-quote* (append (cadr item) (cadr result))))
2311 ((or (null result) (equal result *bq-quote-nil*))
2312 (if (bq-splicing-frob item) (list op item) item))
2313 ((and (consp result) (eq (car result) op))
2314 (list* (car result) item (cdr result)))
2315 (t (list op item result))))
2317 ;;; The effect of BQ-ATTACH-CONSES is to produce a form as if by
2318 ;;; `(LIST* ,@items ,result) but some simplifications are done
2321 ;;; (LIST* 'a 'b 'c 'd) => '(a b c . d)
2322 ;;; (LIST* a b c 'nil) => (LIST a b c)
2323 ;;; (LIST* a b c (LIST* d e f g)) => (LIST* a b c d e f g)
2324 ;;; (LIST* a b c (LIST d e f g)) => (LIST a b c d e f g)
2325 (defun bq-attach-conses (items result)
2326 (cond ((and (every #'null-or-quoted items)
2327 (null-or-quoted result))
2329 (append (mapcar #'cadr items) (cadr result))))
2330 ((or (null result) (equal result *bq-quote-nil*))
2331 (cons *bq-list* items))
2332 ((and (consp result)
2333 (or (eq (car result) *bq-list*)
2334 (eq (car result) *bq-list**)))
2335 (cons (car result) (append items (cdr result))))
2336 (t (cons *bq-list** (append items (list result))))))
2338 ;;; Removes funny tokens and changes (#:BQ-LIST* a b) into
2339 ;;; (CONS a b) instead of (LIST* a b), purely for readability.
2340 (defun bq-remove-tokens (x)
2341 (cond ((eq x *bq-list*) 'list)
2342 ((eq x *bq-append*) 'append)
2343 ((eq x *bq-nconc*) 'nconc)
2344 ((eq x *bq-list**) 'list*)
2345 ((eq x *bq-quote*) 'quote)
2347 ((eq (car x) *bq-clobberable*)
2348 (bq-remove-tokens (cadr x)))
2349 ((and (eq (car x) *bq-list**)
2352 (cons 'cons (maptree #'bq-remove-tokens (cdr x))))
2353 (t (maptree #'bq-remove-tokens x))))
2355 (define-transformation backquote (form)
2356 (bq-completely-process form))
2361 (defvar *builtins* nil)
2363 (defmacro define-raw-builtin (name args &body body)
2364 ;; Creates a new primitive function `name' with parameters args and
2365 ;; @body. The body can access to the local environment through the
2366 ;; variable *ENVIRONMENT*.
2367 `(push (list ',name (lambda ,args (block ,name ,@body)))
2370 (defmacro define-builtin (name args &body body)
2371 `(define-raw-builtin ,name ,args
2372 (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
2375 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
2376 (defmacro type-check (decls &body body)
2378 ,@(mapcar (lambda (decl)
2379 `(code "var " ,(first decl) " = " ,(third decl) ";" *newline*))
2381 ,@(mapcar (lambda (decl)
2382 `(code "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
2383 (indent "throw 'The value ' + "
2385 " + ' is not a type "
2390 (code "return " (progn ,@body) ";" *newline*)))
2392 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
2393 ;;; a variable which holds a list of forms. It will compile them and
2394 ;;; store the result in some Javascript variables. BODY is evaluated
2395 ;;; with ARGS bound to the list of these variables to generate the
2396 ;;; code which performs the transformation on these variables.
2398 (defun variable-arity-call (args function)
2399 (unless (consp args)
2400 (error "ARGS must be a non-empty list"))
2406 (push (integer-to-string x) fargs)
2407 (let ((v (code "x" (incf counter))))
2410 (code "var " v " = " (ls-compile x) ";" *newline*
2411 "if (typeof " v " !== 'number') throw 'Not a number!';"
2413 (js!selfcall prelude (funcall function (reverse fargs)))))
2416 (defmacro variable-arity (args &body body)
2417 (unless (symbolp args)
2418 (error "Bad usage of VARIABLE-ARITY, you must pass a symbol"))
2419 `(variable-arity-call ,args
2421 (code "return " ,@body ";" *newline*))))
2423 (defun num-op-num (x op y)
2424 (type-check (("x" "number" x) ("y" "number" y))
2427 (define-raw-builtin + (&rest numbers)
2430 (variable-arity numbers
2431 (join numbers "+"))))
2433 (define-raw-builtin - (x &rest others)
2434 (let ((args (cons x others)))
2435 (variable-arity args
2437 (concat "-" (car args))
2440 (define-raw-builtin * (&rest numbers)
2443 (variable-arity numbers
2444 (join numbers "*"))))
2446 (define-raw-builtin / (x &rest others)
2447 (let ((args (cons x others)))
2448 (variable-arity args
2450 (concat "1 /" (car args))
2453 (define-builtin mod (x y) (num-op-num x "%" y))
2456 (defun comparison-conjuntion (vars op)
2461 (concat (car vars) op (cadr vars)))
2463 (concat (car vars) op (cadr vars)
2465 (comparison-conjuntion (cdr vars) op)))))
2467 (defmacro define-builtin-comparison (op sym)
2468 `(define-raw-builtin ,op (x &rest args)
2469 (let ((args (cons x args)))
2470 (variable-arity args
2471 (js!bool (comparison-conjuntion args ,sym))))))
2473 (define-builtin-comparison > ">")
2474 (define-builtin-comparison < "<")
2475 (define-builtin-comparison >= ">=")
2476 (define-builtin-comparison <= "<=")
2477 (define-builtin-comparison = "==")
2479 (define-builtin numberp (x)
2480 (js!bool (code "(typeof (" x ") == \"number\")")))
2482 (define-builtin floor (x)
2483 (type-check (("x" "number" x))
2486 (define-builtin cons (x y)
2487 (code "({car: " x ", cdr: " y "})"))
2489 (define-builtin consp (x)
2492 "var tmp = " x ";" *newline*
2493 "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
2495 (define-builtin car (x)
2497 "var tmp = " x ";" *newline*
2498 "return tmp === " (ls-compile nil)
2499 "? " (ls-compile nil)
2500 ": tmp.car;" *newline*))
2502 (define-builtin cdr (x)
2504 "var tmp = " x ";" *newline*
2505 "return tmp === " (ls-compile nil) "? "
2507 ": tmp.cdr;" *newline*))
2509 (define-builtin rplaca (x new)
2510 (type-check (("x" "object" x))
2511 (code "(x.car = " new ", x)")))
2513 (define-builtin rplacd (x new)
2514 (type-check (("x" "object" x))
2515 (code "(x.cdr = " new ", x)")))
2517 (define-builtin symbolp (x)
2520 "var tmp = " x ";" *newline*
2521 "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
2523 (define-builtin make-symbol (name)
2524 (type-check (("name" "string" name))
2527 (define-builtin symbol-name (x)
2528 (code "(" x ").name"))
2530 (define-builtin set (symbol value)
2531 (code "(" symbol ").value = " value))
2533 (define-builtin fset (symbol value)
2534 (code "(" symbol ").fvalue = " value))
2536 (define-builtin boundp (x)
2537 (js!bool (code "(" x ".value !== undefined)")))
2539 (define-builtin symbol-value (x)
2541 "var symbol = " x ";" *newline*
2542 "var value = symbol.value;" *newline*
2543 "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
2544 "return value;" *newline*))
2546 (define-builtin symbol-function (x)
2548 "var symbol = " x ";" *newline*
2549 "var func = symbol.fvalue;" *newline*
2550 "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
2551 "return func;" *newline*))
2553 (define-builtin symbol-plist (x)
2554 (code "((" x ").plist || " (ls-compile nil) ")"))
2556 (define-builtin lambda-code (x)
2557 (code "(" x ").toString()"))
2559 (define-builtin eq (x y) (js!bool (code "(" x " === " y ")")))
2560 (define-builtin equal (x y) (js!bool (code "(" x " == " y ")")))
2562 (define-builtin char-to-string (x)
2563 (type-check (("x" "number" x))
2564 "String.fromCharCode(x)"))
2566 (define-builtin stringp (x)
2567 (js!bool (code "(typeof(" x ") == \"string\")")))
2569 (define-builtin string-upcase (x)
2570 (type-check (("x" "string" x))
2573 (define-builtin string-length (x)
2574 (type-check (("x" "string" x))
2577 (define-raw-builtin slice (string a &optional b)
2579 "var str = " (ls-compile string) ";" *newline*
2580 "var a = " (ls-compile a) ";" *newline*
2582 (when b (code "b = " (ls-compile b) ";" *newline*))
2583 "return str.slice(a,b);" *newline*))
2585 (define-builtin char (string index)
2586 (type-check (("string" "string" string)
2587 ("index" "number" index))
2588 "string.charCodeAt(index)"))
2590 (define-builtin concat-two (string1 string2)
2591 (type-check (("string1" "string" string1)
2592 ("string2" "string" string2))
2593 "string1.concat(string2)"))
2595 (define-raw-builtin funcall (func &rest args)
2597 "var f = " (ls-compile func) ";" *newline*
2598 "return (typeof f === 'function'? f: f.fvalue)("
2599 (join (cons (if *multiple-value-p* "values" "pv")
2600 (mapcar #'ls-compile args))
2604 (define-raw-builtin apply (func &rest args)
2606 (code "(" (ls-compile func) ")()")
2607 (let ((args (butlast args))
2608 (last (car (last args))))
2610 "var f = " (ls-compile func) ";" *newline*
2611 "var args = [" (join (cons (if *multiple-value-p* "values" "pv")
2612 (mapcar #'ls-compile args))
2615 "var tail = (" (ls-compile last) ");" *newline*
2616 "while (tail != " (ls-compile nil) "){" *newline*
2617 " args.push(tail.car);" *newline*
2618 " tail = tail.cdr;" *newline*
2620 "return (typeof f === 'function'? f : f.fvalue).apply(this, args);" *newline*))))
2622 (define-builtin js-eval (string)
2623 (type-check (("string" "string" string))
2624 (if *multiple-value-p*
2626 "var v = eval.apply(window, [string]);" *newline*
2627 "if (typeof v !== 'object' || !('multiple-value' in v)){" *newline*
2628 (indent "v = [v];" *newline*
2629 "v['multiple-value'] = true;" *newline*)
2631 "return values.apply(this, v);" *newline*)
2632 "eval.apply(window, [string])")))
2634 (define-builtin error (string)
2635 (js!selfcall "throw " string ";" *newline*))
2637 (define-builtin new () "{}")
2639 (define-builtin objectp (x)
2640 (js!bool (code "(typeof (" x ") === 'object')")))
2642 (define-builtin oget (object key)
2644 "var tmp = " "(" object ")[" key "];" *newline*
2645 "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
2647 (define-builtin oset (object key value)
2648 (code "((" object ")[" key "] = " value ")"))
2650 (define-builtin in (key object)
2651 (js!bool (code "((" key ") in (" object "))")))
2653 (define-builtin functionp (x)
2654 (js!bool (code "(typeof " x " == 'function')")))
2656 (define-builtin write-string (x)
2657 (type-check (("x" "string" x))
2660 (define-builtin make-array (n)
2662 "var r = [];" *newline*
2663 "for (var i = 0; i < " n "; i++)" *newline*
2664 (indent "r.push(" (ls-compile nil) ");" *newline*)
2665 "return r;" *newline*))
2667 (define-builtin arrayp (x)
2670 "var x = " x ";" *newline*
2671 "return typeof x === 'object' && 'length' in x;")))
2673 (define-builtin aref (array n)
2675 "var x = " "(" array ")[" n "];" *newline*
2676 "if (x === undefined) throw 'Out of range';" *newline*
2677 "return x;" *newline*))
2679 (define-builtin aset (array n value)
2681 "var x = " array ";" *newline*
2682 "var i = " n ";" *newline*
2683 "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
2684 "return x[i] = " value ";" *newline*))
2686 (define-builtin get-unix-time ()
2687 (code "(Math.round(new Date() / 1000))"))
2689 (define-builtin values-array (array)
2690 (if *multiple-value-p*
2691 (code "values.apply(this, " array ")")
2692 (code "pv.apply(this, " array ")")))
2694 (define-raw-builtin values (&rest args)
2695 (if *multiple-value-p*
2696 (code "values(" (join (mapcar #'ls-compile args) ", ") ")")
2697 (code "pv(" (join (mapcar #'ls-compile args) ", ") ")")))
2701 (let ((b (lookup-in-lexenv x *environment* 'function)))
2702 (and (eq (binding-type b) 'macro)
2705 (defun ls-macroexpand-1 (form)
2706 (let ((macro-binding (macro (car form))))
2708 (let ((expander (binding-value macro-binding)))
2709 (when (listp expander)
2710 (let ((compiled (eval expander)))
2711 ;; The list representation are useful while
2712 ;; bootstrapping, as we can dump the definition of the
2713 ;; macros easily, but they are slow because we have to
2714 ;; evaluate them and compile them now and again. So, let
2715 ;; us replace the list representation version of the
2716 ;; function with the compiled one.
2718 #+ecmalisp (set-binding-value macro-binding compiled)
2719 (setq expander compiled)))
2720 (apply expander (cdr form)))
2723 (defun compile-funcall (function args)
2724 (let* ((values-funcs (if *multiple-value-p* "values" "pv"))
2725 (arglist (concat "(" (join (cons values-funcs (mapcar #'ls-compile args)) ", ") ")")))
2727 ((translate-function function)
2728 (concat (translate-function function) arglist))
2729 ((and (symbolp function)
2730 #+ecmalisp (eq (symbol-package function) (find-package "COMMON-LISP"))
2732 (code (ls-compile `',function) ".fvalue" arglist))
2734 (code (ls-compile `#',function) arglist)))))
2736 (defun ls-compile-block (sexps &optional return-last-p)
2738 (code (ls-compile-block (butlast sexps))
2739 "return " (ls-compile (car (last sexps)) *multiple-value-p*) ";")
2741 (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
2742 (concat ";" *newline*))))
2744 (defun ls-compile (sexp &optional multiple-value-p)
2745 (let ((*multiple-value-p* multiple-value-p))
2748 (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
2750 ((and b (not (member 'special (binding-declarations b))))
2752 ((or (keywordp sexp)
2753 (member 'constant (binding-declarations b)))
2754 (code (ls-compile `',sexp) ".value"))
2756 (ls-compile `(symbol-value ',sexp))))))
2757 ((integerp sexp) (integer-to-string sexp))
2758 ((stringp sexp) (code "\"" (escape-string sexp) "\""))
2759 ((arrayp sexp) (literal sexp))
2761 (let ((name (car sexp))
2765 ((assoc name *compilations*)
2766 (let ((comp (second (assoc name *compilations*))))
2768 ;; Built-in functions
2769 ((and (assoc name *builtins*)
2770 (not (claimp name 'function 'notinline)))
2771 (let ((comp (second (assoc name *builtins*))))
2775 (ls-compile (ls-macroexpand-1 sexp) multiple-value-p)
2776 (compile-funcall name args))))))
2778 (error (concat "How should I compile " (prin1-to-string sexp) "?"))))))
2781 (defvar *compile-print-toplevels* nil)
2783 (defun truncate-string (string &optional (width 60))
2784 (let ((n (or (position #\newline string)
2785 (min width (length string)))))
2786 (subseq string 0 n)))
2788 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
2789 (let ((*toplevel-compilations* nil))
2791 ((and (consp sexp) (eq (car sexp) 'progn))
2792 (let ((subs (mapcar (lambda (s)
2793 (ls-compile-toplevel s t))
2795 (join (remove-if #'null-or-empty-p subs))))
2797 (when *compile-print-toplevels*
2798 (let ((form-string (prin1-to-string sexp)))
2799 (write-string "Compiling ")
2800 (write-string (truncate-string form-string))
2801 (write-line "...")))
2803 (let ((code (ls-compile sexp multiple-value-p)))
2804 (code (join-trailing (get-toplevel-compilations)
2805 (code ";" *newline*))
2807 (code code ";" *newline*))))))))
2810 ;;; Once we have the compiler, we define the runtime environment and
2811 ;;; interactive development (eval), which works calling the compiler
2812 ;;; and evaluating the Javascript result globally.
2817 (js-eval (ls-compile-toplevel x t)))
2819 (export '(&rest &key &optional &body * *gensym-counter* *package* + - / 1+ 1- <
2820 <= = = > >= and append apply aref arrayp assoc atom block boundp
2821 boundp butlast caar cadddr caddr cadr car car case catch cdar cdddr
2822 cddr cdr cdr char char-code fdefinition find-package find-symbol first
2823 flet fourth fset funcall function functionp gensym get-setf-expansion
2824 get-universal-time go identity if in-package incf integerp integerp
2825 intern keywordp labels lambda last length let let* char= code-char
2826 cond cons consp constantly copy-list decf declaim define-setf-expander
2827 defconstant defparameter defun defmacro defvar digit-char digit-char-p
2828 disassemble do do* documentation dolist dotimes ecase eq eql equal
2829 error eval every export list-all-packages list list* listp loop make-array
2830 make-package make-symbol mapcar member minusp mod multiple-value-bind
2831 multiple-value-call multiple-value-list multiple-value-prog1 nconc nil not
2832 nth nthcdr null numberp or package-name package-use-list packagep
2833 parse-integer plusp prin1-to-string print proclaim prog1 prog2 progn
2834 psetq push quote nreconc remove remove-if remove-if-not return return-from
2835 revappend reverse rplaca rplacd second set setf setq some
2836 string-upcase string string= stringp subseq symbol-function
2837 symbol-name symbol-package symbol-plist symbol-value symbolp t tagbody
2838 third throw truncate unless unwind-protect values values-list variable
2839 warn when write-line write-string zerop))
2841 (setq *package* *user-package*)
2843 (js-eval "var lisp")
2844 (js-vset "lisp" (new))
2845 (js-vset "lisp.read" #'ls-read-from-string)
2846 (js-vset "lisp.print" #'prin1-to-string)
2847 (js-vset "lisp.eval" #'eval)
2848 (js-vset "lisp.compile" (lambda (s) (ls-compile-toplevel s t)))
2849 (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
2850 (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str) t)))
2852 ;; Set the initial global environment to be equal to the host global
2853 ;; environment at this point of the compilation.
2855 (toplevel-compilation
2856 (ls-compile `(setq *environment* ',*environment*))))
2859 (toplevel-compilation
2862 ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
2864 (setq *literal-symbols* ',*literal-symbols*)
2865 (setq *variable-counter* ,*variable-counter*)
2866 (setq *gensym-counter* ,*gensym-counter*)
2867 (setq *block-counter* ,*block-counter*)))))
2870 (toplevel-compilation
2872 `(setq *literal-counter* ,*literal-counter*)))))
2875 ;;; Finally, we provide a couple of functions to easily bootstrap
2876 ;;; this. It just calls the compiler with this file as input.
2880 (defun read-whole-file (filename)
2881 (with-open-file (in filename)
2882 (let ((seq (make-array (file-length in) :element-type 'character)))
2883 (read-sequence seq in)
2886 (defun ls-compile-file (filename output &key print)
2887 (let ((*compiling-file* t)
2888 (*compile-print-toplevels* print))
2889 (with-open-file (out output :direction :output :if-exists :supersede)
2890 (write-string (read-whole-file "prelude.js") out)
2891 (let* ((source (read-whole-file filename))
2892 (in (make-string-stream source)))
2894 for x = (ls-read in)
2896 for compilation = (ls-compile-toplevel x)
2897 when (plusp (length compilation))
2898 do (write-string compilation out))))))
2901 (setq *environment* (make-lexenv))
2902 (setq *literal-symbols* nil)
2903 (setq *variable-counter* 0
2907 (ls-compile-file "ecmalisp.lisp" "ecmalisp.js" :print t)))