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 (defun map1 (func list)
389 (collect (funcall func (car list)))
390 (setq list (cdr list)))))
392 (defmacro loop (&body body)
395 (defun mapcar (func list &rest lists)
396 (let ((lists (cons list lists)))
400 (let ((elems (map1 #'car lists)))
401 (do ((tail lists (cdr tail)))
403 (when (null (car tail)) (return-from loop))
404 (rplaca tail (cdar tail)))
405 (collect (apply func elems))))))))
407 (defun identity (x) x)
409 (defun constantly (x)
414 (mapcar #'identity x))
416 (defun list* (arg &rest others)
417 (cond ((null others) arg)
418 ((null (cdr others)) (cons arg (car others)))
419 (t (do ((x others (cdr x)))
420 ((null (cddr x)) (rplacd x (cadr x))))
423 (defun code-char (x) x)
424 (defun char-code (x) x)
425 (defun char= (x y) (= x y))
428 (and (numberp x) (= (floor x) x)))
430 (defun plusp (x) (< 0 x))
431 (defun minusp (x) (< x 0))
434 (or (consp x) (null x)))
436 (defun nthcdr (n list)
437 (while (and (plusp n) list)
439 (setq list (cdr list)))
443 (car (nthcdr n list)))
446 (while (consp (cdr x))
452 (cons (car x) (butlast (cdr x)))))
454 (defun member (x list)
456 (when (eql x (car list))
458 (setq list (cdr list))))
460 (defun remove (x list)
465 (remove x (cdr list)))
467 (cons (car list) (remove x (cdr list))))))
469 (defun remove-if (func list)
473 ((funcall func (car list))
474 (remove-if func (cdr list)))
477 (cons (car list) (remove-if func (cdr list))))))
479 (defun remove-if-not (func list)
483 ((funcall func (car list))
484 (cons (car list) (remove-if-not func (cdr list))))
486 (remove-if-not func (cdr list)))))
488 (defun digit-char-p (x)
489 (if (and (<= #\0 x) (<= x #\9))
493 (defun digit-char (weight)
495 (char "0123456789" weight)))
497 (defun subseq (seq a &optional b)
504 (error "Unsupported argument."))))
506 (defmacro do-sequence (iteration &body body)
509 `(let ((,seq ,(second iteration)))
514 (dotimes (,index (length ,seq))
515 (let ((,(first iteration)
520 (dolist (,(first iteration) ,seq)
523 (error "type-error!"))))))
525 (defun some (function seq)
526 (do-sequence (elt seq)
527 (when (funcall function elt)
528 (return-from some t))))
530 (defun every (function seq)
531 (do-sequence (elt seq)
532 (unless (funcall function elt)
533 (return-from every nil)))
536 (defun position (elt sequence)
544 (defun assoc (x alist)
546 (if (eql x (caar alist))
548 (setq alist (cdr alist))))
552 (cond ((stringp x) x)
553 ((symbolp x) (symbol-name x))
554 (t (char-to-string x))))
556 (defun string= (s1 s2)
559 (defun fdefinition (x)
566 (error "Invalid function"))))
568 (defun disassemble (function)
569 (write-line (lambda-code (fdefinition function)))
572 (defun documentation (x type)
573 "Return the documentation of X. TYPE must be the symbol VARIABLE or FUNCTION."
576 (let ((func (fdefinition x)))
577 (oget func "docstring")))
580 (error "Wrong argument type! it should be a symbol"))
583 (defmacro multiple-value-bind (variables value-from &body body)
584 `(multiple-value-call (lambda (&optional ,@variables &rest ,(gensym))
588 (defmacro multiple-value-list (value-from)
589 `(multiple-value-call #'list ,value-from))
592 ;;; Generalized references (SETF)
594 (defvar *setf-expanders* nil)
596 (defun get-setf-expansion (place)
598 (let ((value (gensym)))
602 `(setq ,place ,value)
604 (let ((place (ls-macroexpand-1 place)))
605 (let* ((access-fn (car place))
606 (expander (cdr (assoc access-fn *setf-expanders*))))
607 (when (null expander)
608 (error "Unknown generalized reference."))
609 (apply expander (cdr place))))))
611 (defmacro define-setf-expander (access-fn lambda-list &body body)
612 (unless (symbolp access-fn)
613 (error "ACCESS-FN must be a symbol."))
614 `(progn (push (cons ',access-fn (lambda ,lambda-list ,@body))
618 (defmacro setf (&rest pairs)
623 (error "Odd number of arguments to setf."))
625 (let ((place (first pairs))
626 (value (second pairs)))
627 (multiple-value-bind (vars vals store-vars writer-form reader-form)
628 (get-setf-expansion place)
629 ;; TODO: Optimize the expansion a little bit to avoid let*
630 ;; or multiple-value-bind when unnecesary.
631 `(let* ,(mapcar #'list vars vals)
632 (multiple-value-bind ,store-vars
637 ,@(do ((pairs pairs (cddr pairs))
638 (result '() (cons `(setf ,(car pairs) ,(cadr pairs)) result)))
640 (reverse result)))))))
642 (define-setf-expander car (x)
643 (let ((cons (gensym))
644 (new-value (gensym)))
648 `(progn (rplaca ,cons ,new-value) ,new-value)
651 (define-setf-expander cdr (x)
652 (let ((cons (gensym))
653 (new-value (gensym)))
657 `(progn (rplacd ,cons ,new-value) ,new-value)
660 ;; Incorrect typecase, but used in NCONC.
661 (defmacro typecase (x &rest clausules)
662 (let ((value (gensym)))
665 ,@(mapcar (lambda (c)
679 ;; The NCONC function is based on the SBCL's one.
680 (defun nconc (&rest lists)
681 (flet ((fail (object)
682 (error "type-error in nconc")))
683 (do ((top lists (cdr top)))
685 (let ((top-of-top (car top)))
688 (let* ((result top-of-top)
690 (do ((elements (cdr top) (cdr elements)))
692 (let ((ele (car elements)))
694 (cons (rplacd (last splice) ele)
696 (null (rplacd (last splice) nil))
697 (atom (if (cdr elements)
699 (rplacd (last splice) ele))))))
705 (return top-of-top))))))))
708 (do ((1st (cdr x) (if (endp 1st) 1st (cdr 1st)))
709 (2nd x 1st) ; 2nd follows first down the list.
710 (3rd y 2nd)) ;3rd follows 2nd down the list.
714 (defun notany (fn seq)
720 (defvar *package-list* nil)
722 (defun list-all-packages ()
725 (defun make-package (name &key use)
726 (let ((package (new))
727 (use (mapcar #'find-package-or-fail use)))
728 (oset package "packageName" name)
729 (oset package "symbols" (new))
730 (oset package "exports" (new))
731 (oset package "use" use)
732 (push package *package-list*)
736 (and (objectp x) (in "symbols" x)))
738 (defun find-package (package-designator)
739 (when (packagep package-designator)
740 (return-from find-package package-designator))
741 (let ((name (string package-designator)))
742 (dolist (package *package-list*)
743 (when (string= (package-name package) name)
746 (defun find-package-or-fail (package-designator)
747 (or (find-package package-designator)
748 (error "Package unknown.")))
750 (defun package-name (package-designator)
751 (let ((package (find-package-or-fail package-designator)))
752 (oget package "packageName")))
754 (defun %package-symbols (package-designator)
755 (let ((package (find-package-or-fail package-designator)))
756 (oget package "symbols")))
758 (defun package-use-list (package-designator)
759 (let ((package (find-package-or-fail package-designator)))
760 (oget package "use")))
762 (defun %package-external-symbols (package-designator)
763 (let ((package (find-package-or-fail package-designator)))
764 (oget package "exports")))
766 (defvar *common-lisp-package*
769 (defvar *user-package*
770 (make-package "CL-USER" :use (list *common-lisp-package*)))
772 (defvar *keyword-package*
773 (make-package "KEYWORD"))
776 (and (symbolp x) (eq (symbol-package x) *keyword-package*)))
778 (defvar *package* *common-lisp-package*)
780 (defmacro in-package (package-designator)
782 (setq *package* (find-package-or-fail ,package-designator))))
784 ;; This function is used internally to initialize the CL package
785 ;; with the symbols built during bootstrap.
786 (defun %intern-symbol (symbol)
788 (if (in "package" symbol)
789 (find-package-or-fail (oget symbol "package"))
790 *common-lisp-package*))
791 (symbols (%package-symbols package)))
792 (oset symbol "package" package)
793 (when (eq package *keyword-package*)
794 (oset symbol "value" symbol))
795 (oset symbols (symbol-name symbol) symbol)))
797 (defun find-symbol (name &optional (package *package*))
798 (let* ((package (find-package-or-fail package))
799 (externals (%package-external-symbols package))
800 (symbols (%package-symbols package)))
803 (values (oget externals name) :external))
805 (values (oget symbols name) :internal))
807 (dolist (used (package-use-list package) (values nil nil))
808 (let ((exports (%package-external-symbols used)))
809 (when (in name exports)
810 (return (values (oget exports name) :inherit)))))))))
812 (defun intern (name &optional (package *package*))
813 (let ((package (find-package-or-fail package)))
814 (multiple-value-bind (symbol foundp)
815 (find-symbol name package)
817 (values symbol foundp)
818 (let ((symbols (%package-symbols package)))
820 (let ((symbol (make-symbol name)))
821 (oset symbol "package" package)
822 (when (eq package *keyword-package*)
823 (oset symbol "value" symbol)
824 (export (list symbol) package))
825 (oset symbols name symbol)
826 (values symbol nil)))))))
828 (defun symbol-package (symbol)
829 (unless (symbolp symbol)
830 (error "it is not a symbol"))
831 (oget symbol "package"))
833 (defun export (symbols &optional (package *package*))
834 (let ((exports (%package-external-symbols package)))
835 (dolist (symb symbols t)
836 (oset exports (symbol-name symb) symb))))
838 (defun get-universal-time ()
839 (+ (get-unix-time) 2208988800)))
842 ;;; The compiler offers some primitives and special forms which are
843 ;;; not found in Common Lisp, for instance, while. So, we grow Common
844 ;;; Lisp a bit to it can execute the rest of the file.
847 (defmacro while (condition &body body)
852 (defmacro eval-when-compile (&body body)
853 `(eval-when (:compile-toplevel :load-toplevel :execute)
856 (defun concat-two (s1 s2)
857 (concatenate 'string s1 s2))
859 (defun aset (array idx value)
860 (setf (aref array idx) value)))
862 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
863 ;;; from here, this code will compile on both. We define some helper
864 ;;; functions now for string manipulation and so on. They will be
865 ;;; useful in the compiler, mostly.
867 (defvar *newline* (string (code-char 10)))
869 (defun concat (&rest strs)
870 (!reduce #'concat-two strs :initial-value ""))
872 (defmacro concatf (variable &body form)
873 `(setq ,variable (concat ,variable (progn ,@form))))
875 ;;; Concatenate a list of strings, with a separator
876 (defun join (list &optional (separator ""))
885 (join (cdr list) separator)))))
887 (defun join-trailing (list &optional (separator ""))
890 (concat (car list) separator (join-trailing (cdr list) separator))))
892 (defun mapconcat (func list)
893 (join (mapcar func list)))
895 (defun vector-to-list (vector)
897 (size (length vector)))
898 (dotimes (i size (reverse list))
899 (push (aref vector i) list))))
901 (defun list-to-vector (list)
902 (let ((v (make-array (length list)))
910 (defun values-list (list)
911 (values-array (list-to-vector list)))
913 (defun values (&rest args)
916 (defun integer-to-string (x)
921 (concat "-" (integer-to-string (- 0 x))))
924 (while (not (zerop x))
925 (push (mod x 10) digits)
926 (setq x (truncate x 10)))
927 (mapconcat (lambda (x) (string (digit-char x)))
935 (defun prin1-to-string (form)
938 (multiple-value-bind (symbol foundp)
939 (find-symbol (symbol-name form) *package*)
940 (if (and foundp (eq symbol form))
942 (let ((package (symbol-package form))
943 (name (symbol-name form)))
946 ((eq package (find-package "KEYWORD")) "")
947 (t (package-name package)))
949 ((integerp form) (integer-to-string form))
950 ((stringp form) (concat "\"" (escape-string form) "\""))
952 (let ((name (oget form "fname")))
954 (concat "#<FUNCTION " name ">")
955 (concat "#<FUNCTION>"))))
958 (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
959 (let ((last (last form)))
960 (if (null (cdr last))
961 (prin1-to-string (car last))
962 (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
965 (concat "#" (if (zerop (length form))
967 (prin1-to-string (vector-to-list form)))))
969 (concat "#<PACKAGE " (package-name form) ">"))
971 (concat "#<javascript object>"))))
973 (defun write-line (x)
975 (write-string *newline*)
979 (write-string "WARNING: ")
983 (write-line (prin1-to-string x))
990 ;;; The Lisp reader, parse strings and return Lisp objects. The main
991 ;;; entry points are `ls-read' and `ls-read-from-string'.
993 (defun make-string-stream (string)
996 (defun %peek-char (stream)
997 (and (< (cdr stream) (length (car stream)))
998 (char (car stream) (cdr stream))))
1000 (defun %read-char (stream)
1001 (and (< (cdr stream) (length (car stream)))
1002 (prog1 (char (car stream) (cdr stream))
1003 (rplacd stream (1+ (cdr stream))))))
1005 (defun whitespacep (ch)
1006 (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
1008 (defun skip-whitespaces (stream)
1010 (setq ch (%peek-char stream))
1011 (while (and ch (whitespacep ch))
1013 (setq ch (%peek-char stream)))))
1015 (defun terminalp (ch)
1016 (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
1018 (defun read-until (stream func)
1021 (setq ch (%peek-char stream))
1022 (while (and ch (not (funcall func ch)))
1023 (setq string (concat string (string ch)))
1025 (setq ch (%peek-char stream)))
1028 (defun skip-whitespaces-and-comments (stream)
1030 (skip-whitespaces stream)
1031 (setq ch (%peek-char stream))
1032 (while (and ch (char= ch #\;))
1033 (read-until stream (lambda (x) (char= x #\newline)))
1034 (skip-whitespaces stream)
1035 (setq ch (%peek-char stream)))))
1037 (defun %read-list (stream)
1038 (skip-whitespaces-and-comments stream)
1039 (let ((ch (%peek-char stream)))
1042 (error "Unspected EOF"))
1048 (prog1 (ls-read stream)
1049 (skip-whitespaces-and-comments stream)
1050 (unless (char= (%read-char stream) #\))
1051 (error "')' was expected."))))
1053 (cons (ls-read stream) (%read-list stream))))))
1055 (defun read-string (stream)
1058 (setq ch (%read-char stream))
1059 (while (not (eql ch #\"))
1061 (error "Unexpected EOF"))
1063 (setq ch (%read-char stream)))
1064 (setq string (concat string (string ch)))
1065 (setq ch (%read-char stream)))
1068 (defun read-sharp (stream)
1070 (ecase (%read-char stream)
1072 (list 'function (ls-read stream)))
1073 (#\( (list-to-vector (%read-list stream)))
1074 (#\: (make-symbol (string-upcase (read-until stream #'terminalp))))
1077 (concat (string (%read-char stream))
1078 (read-until stream #'terminalp))))
1080 ((string= cname "space") (char-code #\space))
1081 ((string= cname "tab") (char-code #\tab))
1082 ((string= cname "newline") (char-code #\newline))
1083 (t (char-code (char cname 0))))))
1085 (let ((feature (read-until stream #'terminalp)))
1087 ((string= feature "common-lisp")
1088 (ls-read stream) ;ignore
1090 ((string= feature "ecmalisp")
1093 (error "Unknown reader form.")))))))
1095 ;;; Parse a string of the form NAME, PACKAGE:NAME or
1096 ;;; PACKAGE::NAME and return the name. If the string is of the
1097 ;;; form 1) or 3), but the symbol does not exist, it will be created
1098 ;;; and interned in that package.
1099 (defun read-symbol (string)
1100 (let ((size (length string))
1101 package name internalp index)
1103 (while (and (< index size)
1104 (not (char= (char string index) #\:)))
1107 ;; No package prefix
1110 (setq package *package*)
1115 (setq package "KEYWORD")
1116 (setq package (string-upcase (subseq string 0 index))))
1118 (when (char= (char string index) #\:)
1121 (setq name (subseq string index))))
1122 ;; Canonalize symbol name and package
1123 (setq name (string-upcase name))
1124 (setq package (find-package package))
1125 ;; TODO: PACKAGE:SYMBOL should signal error if SYMBOL is not an
1126 ;; external symbol from PACKAGE.
1127 (if (or internalp (eq package (find-package "KEYWORD")))
1128 (intern name package)
1129 (find-symbol name package))))
1132 (defun !parse-integer (string junk-allow)
1136 (size (length string))
1138 (when (zerop size) (return (values nil 0)))
1140 (case (char string 0)
1145 (unless (and (< index size)
1146 (setq value (digit-char-p (char string index))))
1147 (return (values nil index)))
1150 (while (< index size)
1151 (let ((digit (digit-char-p (char string index))))
1152 (unless digit (return))
1153 (setq value (+ (* value 10) digit))
1155 ;; Trailing whitespace
1156 (do ((i index (1+ i)))
1157 ((or (= i size) (not (whitespacep (char string i))))
1158 (and (= i size) (setq index i))))
1161 (values (* sign value) index)
1162 (values nil index)))))
1165 (defun parse-integer (string)
1166 (!parse-integer string nil))
1168 (defvar *eof* (gensym))
1169 (defun ls-read (stream)
1170 (skip-whitespaces-and-comments stream)
1171 (let ((ch (%peek-char stream)))
1173 ((or (null ch) (char= ch #\)))
1177 (%read-list stream))
1180 (list 'quote (ls-read stream)))
1183 (list 'backquote (ls-read stream)))
1186 (read-string stream))
1189 (if (eql (%peek-char stream) #\@)
1190 (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
1191 (list 'unquote (ls-read stream))))
1193 (read-sharp stream))
1195 (let ((string (read-until stream #'terminalp)))
1196 (or (values (!parse-integer string nil))
1197 (read-symbol string)))))))
1199 (defun ls-read-from-string (string)
1200 (ls-read (make-string-stream string)))
1205 ;;; Translate the Lisp code to Javascript. It will compile the special
1206 ;;; forms. Some primitive functions are compiled as special forms
1207 ;;; too. The respective real functions are defined in the target (see
1208 ;;; the beginning of this file) as well as some primitive functions.
1210 (defun code (&rest args)
1211 (mapconcat (lambda (arg)
1214 ((integerp arg) (integer-to-string arg))
1216 (t (error "Unknown argument."))))
1219 ;;; Wrap X with a Javascript code to convert the result from
1220 ;;; Javascript generalized booleans to T or NIL.
1222 (code "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
1224 ;;; Concatenate the arguments and wrap them with a self-calling
1225 ;;; Javascript anonymous function. It is used to make some Javascript
1226 ;;; statements valid expressions and provide a private scope as well.
1227 ;;; It could be defined as function, but we could do some
1228 ;;; preprocessing in the future.
1229 (defmacro js!selfcall (&body body)
1230 `(code "(function(){" *newline* (indent ,@body) "})()"))
1232 ;;; Like CODE, but prefix each line with four spaces. Two versions
1233 ;;; of this function are available, because the Ecmalisp version is
1234 ;;; very slow and bootstraping was annoying.
1237 (defun indent (&rest string)
1238 (let ((input (apply #'code string)))
1241 (size (length input)))
1242 (when (plusp (length input)) (concatf output " "))
1243 (while (< index size)
1245 (if (and (char= (char input index) #\newline)
1247 (not (char= (char input (1+ index)) #\newline)))
1248 (concat (string #\newline) " ")
1249 (string (char input index)))))
1250 (concatf output str))
1255 (defun indent (&rest string)
1256 (with-output-to-string (*standard-output*)
1257 (with-input-from-string (input (apply #'code string))
1259 for line = (read-line input nil)
1261 do (write-string " ")
1262 do (write-line line)))))
1265 ;;; A Form can return a multiple values object calling VALUES, like
1266 ;;; values(arg1, arg2, ...). It will work in any context, as well as
1267 ;;; returning an individual object. However, if the special variable
1268 ;;; `*multiple-value-p*' is NIL, is granted that only the primary
1269 ;;; value will be used, so we can optimize to avoid the VALUES
1271 (defvar *multiple-value-p* nil)
1273 (defun make-binding (name type value &optional declarations)
1274 (list name type value declarations))
1276 (defun binding-name (b) (first b))
1277 (defun binding-type (b) (second b))
1278 (defun binding-value (b) (third b))
1279 (defun binding-declarations (b) (fourth b))
1281 (defun set-binding-value (b value)
1282 (rplaca (cddr b) value))
1284 (defun set-binding-declarations (b value)
1285 (rplaca (cdddr b) value))
1287 (defun push-binding-declaration (decl b)
1288 (set-binding-declarations b (cons decl (binding-declarations b))))
1291 (defun make-lexenv ()
1292 (list nil nil nil nil))
1294 (defun copy-lexenv (lexenv)
1297 (defun push-to-lexenv (binding lexenv namespace)
1299 (variable (rplaca lexenv (cons binding (car lexenv))))
1300 (function (rplaca (cdr lexenv) (cons binding (cadr lexenv))))
1301 (block (rplaca (cddr lexenv) (cons binding (caddr lexenv))))
1302 (gotag (rplaca (cdddr lexenv) (cons binding (cadddr lexenv))))))
1304 (defun extend-lexenv (bindings lexenv namespace)
1305 (let ((env (copy-lexenv lexenv)))
1306 (dolist (binding (reverse bindings) env)
1307 (push-to-lexenv binding env namespace))))
1309 (defun lookup-in-lexenv (name lexenv namespace)
1310 (assoc name (ecase namespace
1311 (variable (first lexenv))
1312 (function (second lexenv))
1313 (block (third lexenv))
1314 (gotag (fourth lexenv)))))
1316 (defvar *environment* (make-lexenv))
1318 (defvar *variable-counter* 0)
1319 (defun gvarname (symbol)
1320 (code "v" (incf *variable-counter*)))
1322 (defun translate-variable (symbol)
1323 (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
1325 (defun extend-local-env (args)
1326 (let ((new (copy-lexenv *environment*)))
1327 (dolist (symbol args new)
1328 (let ((b (make-binding symbol 'variable (gvarname symbol))))
1329 (push-to-lexenv b new 'variable)))))
1331 ;;; Toplevel compilations
1332 (defvar *toplevel-compilations* nil)
1334 (defun toplevel-compilation (string)
1335 (push string *toplevel-compilations*))
1337 (defun null-or-empty-p (x)
1340 (defun get-toplevel-compilations ()
1341 (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
1343 (defun %compile-defmacro (name lambda)
1344 (toplevel-compilation (ls-compile `',name))
1345 (push-to-lexenv (make-binding name 'macro lambda) *environment* 'function)
1348 (defun global-binding (name type namespace)
1349 (or (lookup-in-lexenv name *environment* namespace)
1350 (let ((b (make-binding name type nil)))
1351 (push-to-lexenv b *environment* namespace)
1354 (defun claimp (symbol namespace claim)
1355 (let ((b (lookup-in-lexenv symbol *environment* namespace)))
1356 (and b (member claim (binding-declarations b)))))
1358 (defun !proclaim (decl)
1361 (dolist (name (cdr decl))
1362 (let ((b (global-binding name 'variable 'variable)))
1363 (push-binding-declaration 'special b))))
1365 (dolist (name (cdr decl))
1366 (let ((b (global-binding name 'function 'function)))
1367 (push-binding-declaration 'notinline b))))
1369 (dolist (name (cdr decl))
1370 (let ((b (global-binding name 'variable 'variable)))
1371 (push-binding-declaration 'constant b))))))
1374 (fset 'proclaim #'!proclaim)
1378 (defvar *compilations* nil)
1380 (defmacro define-compilation (name args &body body)
1381 ;; Creates a new primitive `name' with parameters args and
1382 ;; @body. The body can access to the local environment through the
1383 ;; variable *ENVIRONMENT*.
1384 `(push (list ',name (lambda ,args (block ,name ,@body)))
1387 (define-compilation if (condition true false)
1388 (code "(" (ls-compile condition) " !== " (ls-compile nil)
1389 " ? " (ls-compile true *multiple-value-p*)
1390 " : " (ls-compile false *multiple-value-p*)
1393 (defvar *ll-keywords* '(&optional &rest &key))
1395 (defun list-until-keyword (list)
1396 (if (or (null list) (member (car list) *ll-keywords*))
1398 (cons (car list) (list-until-keyword (cdr list)))))
1400 (defun ll-section (keyword ll)
1401 (list-until-keyword (cdr (member keyword ll))))
1403 (defun ll-required-arguments (ll)
1404 (list-until-keyword ll))
1406 (defun ll-optional-arguments-canonical (ll)
1407 (mapcar #'ensure-list (ll-section '&optional ll)))
1409 (defun ll-optional-arguments (ll)
1410 (mapcar #'car (ll-optional-arguments-canonical ll)))
1412 (defun ll-rest-argument (ll)
1413 (let ((rest (ll-section '&rest ll)))
1415 (error "Bad lambda-list"))
1418 (defun ll-keyword-arguments-canonical (ll)
1419 (flet ((canonicalize (keyarg)
1420 ;; Build a canonical keyword argument descriptor, filling
1421 ;; the optional fields. The result is a list of the form
1422 ;; ((keyword-name var) init-form).
1423 (let ((arg (ensure-list keyarg)))
1424 (cons (if (listp (car arg))
1426 (list (intern (symbol-name (car arg)) "KEYWORD") (car arg)))
1428 (mapcar #'canonicalize (ll-section '&key ll))))
1430 (defun ll-keyword-arguments (ll)
1431 (mapcar (lambda (keyarg) (second (first keyarg)))
1432 (ll-keyword-arguments-canonical ll)))
1434 (defun ll-svars (lambda-list)
1437 (ll-keyword-arguments-canonical lambda-list)
1438 (ll-optional-arguments-canonical lambda-list))))
1439 (remove nil (mapcar #'third args))))
1441 (defun lambda-docstring-wrapper (docstring &rest strs)
1444 "var func = " (join strs) ";" *newline*
1445 "func.docstring = '" docstring "';" *newline*
1446 "return func;" *newline*)
1447 (apply #'code strs)))
1449 (defun lambda-check-argument-count
1450 (n-required-arguments n-optional-arguments rest-p)
1451 ;; Note: Remember that we assume that the number of arguments of a
1452 ;; call is at least 1 (the values argument).
1453 (let ((min (1+ n-required-arguments))
1454 (max (if rest-p 'n/a (+ 1 n-required-arguments n-optional-arguments))))
1456 ;; Special case: a positive exact number of arguments.
1457 (when (and (< 1 min) (eql min max))
1458 (return (code "checkArgs(arguments, " min ");" *newline*)))
1462 (code "checkArgsAtLeast(arguments, " min ");" *newline*))
1464 (code "checkArgsAtMost(arguments, " max ");" *newline*))))))
1466 (defun compile-lambda-optional (ll)
1467 (let* ((optional-arguments (ll-optional-arguments-canonical ll))
1468 (n-required-arguments (length (ll-required-arguments ll)))
1469 (n-optional-arguments (length optional-arguments)))
1470 (when optional-arguments
1471 (code (mapconcat (lambda (arg)
1472 (code "var " (translate-variable (first arg)) "; " *newline*
1474 (code "var " (translate-variable (third arg))
1475 " = " (ls-compile t)
1478 "switch(arguments.length-1){" *newline*
1482 (while (< idx n-optional-arguments)
1483 (let ((arg (nth idx optional-arguments)))
1484 (push (code "case " (+ idx n-required-arguments) ":" *newline*
1485 (indent (translate-variable (car arg))
1487 (ls-compile (cadr arg)) ";" *newline*)
1489 (indent (translate-variable (third arg))
1495 (push (code "default: break;" *newline*) cases)
1496 (join (reverse cases))))
1499 (defun compile-lambda-rest (ll)
1500 (let ((n-required-arguments (length (ll-required-arguments ll)))
1501 (n-optional-arguments (length (ll-optional-arguments ll)))
1502 (rest-argument (ll-rest-argument ll)))
1504 (let ((js!rest (translate-variable rest-argument)))
1505 (code "var " js!rest "= " (ls-compile nil) ";" *newline*
1506 "for (var i = arguments.length-1; i>="
1507 (+ 1 n-required-arguments n-optional-arguments)
1509 (indent js!rest " = {car: arguments[i], cdr: ") js!rest "};"
1512 (defun compile-lambda-parse-keywords (ll)
1513 (let ((n-required-arguments
1514 (length (ll-required-arguments ll)))
1515 (n-optional-arguments
1516 (length (ll-optional-arguments ll)))
1518 (ll-keyword-arguments-canonical ll)))
1520 ;; Declare variables
1521 (mapconcat (lambda (arg)
1522 (let ((var (second (car arg))))
1523 (code "var " (translate-variable var) "; " *newline*
1525 (code "var " (translate-variable (third arg))
1526 " = " (ls-compile nil)
1530 (flet ((parse-keyword (keyarg)
1531 ;; ((keyword-name var) init-form)
1532 (code "for (i=" (+ 1 n-required-arguments n-optional-arguments)
1533 "; i<arguments.length; i+=2){" *newline*
1535 "if (arguments[i] === " (ls-compile (caar keyarg)) "){" *newline*
1536 (indent (translate-variable (cadr (car keyarg)))
1537 " = arguments[i+1];"
1539 (let ((svar (third keyarg)))
1541 (code (translate-variable svar) " = " (ls-compile t) ";" *newline*)))
1546 "if (i == arguments.length){" *newline*
1547 (indent (translate-variable (cadr (car keyarg))) " = " (ls-compile (cadr keyarg)) ";" *newline*)
1549 (when keyword-arguments
1550 (code "var i;" *newline*
1551 (mapconcat #'parse-keyword keyword-arguments))))
1552 ;; Check for unknown keywords
1553 (when keyword-arguments
1554 (code "for (i=" (+ 1 n-required-arguments n-optional-arguments)
1555 "; i<arguments.length; i+=2){" *newline*
1557 (join (mapcar (lambda (x)
1558 (concat "arguments[i] !== " (ls-compile (caar x))))
1563 "throw 'Unknown keyword argument ' + arguments[i].name;" *newline*))
1566 (defun compile-lambda (ll body)
1567 (let ((required-arguments (ll-required-arguments ll))
1568 (optional-arguments (ll-optional-arguments ll))
1569 (keyword-arguments (ll-keyword-arguments ll))
1570 (rest-argument (ll-rest-argument ll))
1572 ;; Get the documentation string for the lambda function
1573 (when (and (stringp (car body))
1574 (not (null (cdr body))))
1575 (setq documentation (car body))
1576 (setq body (cdr body)))
1577 (let ((n-required-arguments (length required-arguments))
1578 (n-optional-arguments (length optional-arguments))
1579 (*environment* (extend-local-env
1580 (append (ensure-list rest-argument)
1585 (lambda-docstring-wrapper
1588 (join (cons "values"
1589 (mapcar #'translate-variable
1590 (append required-arguments optional-arguments)))
1594 ;; Check number of arguments
1595 (lambda-check-argument-count n-required-arguments
1596 n-optional-arguments
1597 (or rest-argument keyword-arguments))
1598 (compile-lambda-optional ll)
1599 (compile-lambda-rest ll)
1600 (compile-lambda-parse-keywords ll)
1601 (let ((*multiple-value-p* t))
1602 (ls-compile-block body t)))
1607 (defun setq-pair (var val)
1608 (let ((b (lookup-in-lexenv var *environment* 'variable)))
1609 (if (and (eq (binding-type b) 'variable)
1610 (not (member 'special (binding-declarations b)))
1611 (not (member 'constant (binding-declarations b))))
1612 (code (binding-value b) " = " (ls-compile val))
1613 (ls-compile `(set ',var ,val)))))
1615 (define-compilation setq (&rest pairs)
1619 ((null pairs) (return))
1621 (error "Odd paris in SETQ"))
1624 (concat (setq-pair (car pairs) (cadr pairs))
1625 (if (null (cddr pairs)) "" ", ")))
1626 (setq pairs (cddr pairs)))))
1627 (code "(" result ")")))
1629 ;;; FFI Variable accessors
1630 (define-compilation js-vref (var)
1633 (define-compilation js-vset (var val)
1634 (code "(" var " = " (ls-compile val) ")"))
1638 (defun escape-string (string)
1641 (size (length string)))
1642 (while (< index size)
1643 (let ((ch (char string index)))
1644 (when (or (char= ch #\") (char= ch #\\))
1645 (setq output (concat output "\\")))
1646 (when (or (char= ch #\newline))
1647 (setq output (concat output "\\"))
1649 (setq output (concat output (string ch))))
1654 (defvar *literal-symbols* nil)
1655 (defvar *literal-counter* 0)
1658 (code "l" (incf *literal-counter*)))
1660 (defun literal (sexp &optional recursive)
1662 ((integerp sexp) (integer-to-string sexp))
1663 ((stringp sexp) (code "\"" (escape-string sexp) "\""))
1665 (or (cdr (assoc sexp *literal-symbols*))
1668 (let ((package (symbol-package sexp)))
1669 (if (eq package (find-package "KEYWORD"))
1670 (code "{name: \"" (escape-string (symbol-name sexp))
1671 "\", 'package': '" (package-name package) "'}")
1672 (code "{name: \"" (escape-string (symbol-name sexp)) "\"}")))
1674 (let ((package (symbol-package sexp)))
1676 (code "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1677 (ls-compile `(intern ,(symbol-name sexp) ,(package-name package)))))))
1678 (push (cons sexp v) *literal-symbols*)
1679 (toplevel-compilation (code "var " v " = " s))
1682 (let* ((head (butlast sexp))
1685 (join-trailing (mapcar (lambda (x) (literal x t)) head) ",")
1686 (literal (car tail) t)
1688 (literal (cdr tail) t)
1693 (toplevel-compilation (code "var " v " = " c))
1696 (let ((elements (vector-to-list sexp)))
1697 (let ((c (concat "[" (join (mapcar #'literal elements) ", ") "]")))
1701 (toplevel-compilation (code "var " v " = " c))
1704 (define-compilation quote (sexp)
1707 (define-compilation %while (pred &rest body)
1709 "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1710 (indent (ls-compile-block body))
1712 "return " (ls-compile nil) ";" *newline*))
1714 (define-compilation function (x)
1716 ((and (listp x) (eq (car x) 'lambda))
1717 (compile-lambda (cadr x) (cddr x)))
1719 (let ((b (lookup-in-lexenv x *environment* 'function)))
1722 (ls-compile `(symbol-function ',x)))))))
1725 (defun make-function-binding (fname)
1726 (make-binding fname 'function (gvarname fname)))
1728 (defun compile-function-definition (list)
1729 (compile-lambda (car list) (cdr list)))
1731 (defun translate-function (name)
1732 (let ((b (lookup-in-lexenv name *environment* 'function)))
1735 (define-compilation flet (definitions &rest body)
1736 (let* ((fnames (mapcar #'car definitions))
1737 (fbody (mapcar #'cdr definitions))
1738 (cfuncs (mapcar #'compile-function-definition fbody))
1740 (extend-lexenv (mapcar #'make-function-binding fnames)
1744 (join (mapcar #'translate-function fnames) ",")
1746 (let ((body (ls-compile-block body t)))
1748 "})(" (join cfuncs ",") ")")))
1750 (define-compilation labels (definitions &rest body)
1751 (let* ((fnames (mapcar #'car definitions))
1753 (extend-lexenv (mapcar #'make-function-binding fnames)
1757 (mapconcat (lambda (func)
1758 (code "var " (translate-function (car func))
1759 " = " (compile-lambda (cadr func) (cddr func))
1762 (ls-compile-block body t))))
1765 (defvar *compiling-file* nil)
1766 (define-compilation eval-when-compile (&rest body)
1767 (if *compiling-file*
1769 (eval (cons 'progn body))
1771 (ls-compile `(progn ,@body))))
1773 (defmacro define-transformation (name args form)
1774 `(define-compilation ,name ,args
1775 (ls-compile ,form)))
1777 (define-compilation progn (&rest body)
1778 (if (null (cdr body))
1779 (ls-compile (car body) *multiple-value-p*)
1780 (js!selfcall (ls-compile-block body t))))
1782 (defun special-variable-p (x)
1783 (and (claimp x 'variable 'special) t))
1785 ;;; Wrap CODE to restore the symbol values of the dynamic
1786 ;;; bindings. BINDINGS is a list of pairs of the form
1787 ;;; (SYMBOL . PLACE), where PLACE is a Javascript variable
1788 ;;; name to initialize the symbol value and where to stored
1790 (defun let-binding-wrapper (bindings body)
1791 (when (null bindings)
1792 (return-from let-binding-wrapper body))
1795 (indent "var tmp;" *newline*
1798 (let ((s (ls-compile `(quote ,(car b)))))
1799 (code "tmp = " s ".value;" *newline*
1800 s ".value = " (cdr b) ";" *newline*
1801 (cdr b) " = tmp;" *newline*)))
1805 "finally {" *newline*
1807 (mapconcat (lambda (b)
1808 (let ((s (ls-compile `(quote ,(car b)))))
1809 (code s ".value" " = " (cdr b) ";" *newline*)))
1813 (define-compilation let (bindings &rest body)
1814 (let* ((bindings (mapcar #'ensure-list bindings))
1815 (variables (mapcar #'first bindings))
1816 (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
1817 (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
1820 (join (mapcar (lambda (x)
1821 (if (special-variable-p x)
1822 (let ((v (gvarname x)))
1823 (push (cons x v) dynamic-bindings)
1825 (translate-variable x)))
1829 (let ((body (ls-compile-block body t)))
1830 (indent (let-binding-wrapper dynamic-bindings body)))
1831 "})(" (join cvalues ",") ")")))
1834 ;;; Return the code to initialize BINDING, and push it extending the
1835 ;;; current lexical environment if the variable is not special.
1836 (defun let*-initialize-value (binding)
1837 (let ((var (first binding))
1838 (value (second binding)))
1839 (if (special-variable-p var)
1840 (code (ls-compile `(setq ,var ,value)) ";" *newline*)
1841 (let* ((v (gvarname var))
1842 (b (make-binding var 'variable v)))
1843 (prog1 (code "var " v " = " (ls-compile value) ";" *newline*)
1844 (push-to-lexenv b *environment* 'variable))))))
1846 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
1847 ;;; DOES NOT generate code to initialize the value of the symbols,
1848 ;;; unlike let-binding-wrapper.
1849 (defun let*-binding-wrapper (symbols body)
1850 (when (null symbols)
1851 (return-from let*-binding-wrapper body))
1852 (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
1853 (remove-if-not #'special-variable-p symbols))))
1857 (mapconcat (lambda (b)
1858 (let ((s (ls-compile `(quote ,(car b)))))
1859 (code "var " (cdr b) " = " s ".value;" *newline*)))
1863 "finally {" *newline*
1865 (mapconcat (lambda (b)
1866 (let ((s (ls-compile `(quote ,(car b)))))
1867 (code s ".value" " = " (cdr b) ";" *newline*)))
1871 (define-compilation let* (bindings &rest body)
1872 (let ((bindings (mapcar #'ensure-list bindings))
1873 (*environment* (copy-lexenv *environment*)))
1875 (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
1876 (body (concat (mapconcat #'let*-initialize-value bindings)
1877 (ls-compile-block body t))))
1878 (let*-binding-wrapper specials body)))))
1881 (defvar *block-counter* 0)
1883 (define-compilation block (name &rest body)
1884 (let* ((tr (incf *block-counter*))
1885 (b (make-binding name 'block tr)))
1886 (when *multiple-value-p*
1887 (push-binding-declaration 'multiple-value b))
1888 (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
1889 (cbody (ls-compile-block body t)))
1890 (if (member 'used (binding-declarations b))
1895 "catch (cf){" *newline*
1896 " if (cf.type == 'block' && cf.id == " tr ")" *newline*
1897 (if *multiple-value-p*
1898 " return values.apply(this, forcemv(cf.values));"
1899 " return cf.values;")
1902 " throw cf;" *newline*
1904 (js!selfcall cbody)))))
1906 (define-compilation return-from (name &optional value)
1907 (let* ((b (lookup-in-lexenv name *environment* 'block))
1908 (multiple-value-p (member 'multiple-value (binding-declarations b))))
1910 (error (concat "Unknown block `" (symbol-name name) "'.")))
1911 (push-binding-declaration 'used b)
1913 (when multiple-value-p (code "var values = mv;" *newline*))
1916 "id: " (binding-value b) ", "
1917 "values: " (ls-compile value multiple-value-p) ", "
1918 "message: 'Return from unknown block " (symbol-name name) ".'"
1921 (define-compilation catch (id &rest body)
1923 "var id = " (ls-compile id) ";" *newline*
1925 (indent (ls-compile-block body t)) *newline*
1927 "catch (cf){" *newline*
1928 " if (cf.type == 'catch' && cf.id == id)" *newline*
1929 (if *multiple-value-p*
1930 " return values.apply(this, forcemv(cf.values));"
1931 " return pv.apply(this, forcemv(cf.values));")
1934 " throw cf;" *newline*
1937 (define-compilation throw (id value)
1939 "var values = mv;" *newline*
1942 "id: " (ls-compile id) ", "
1943 "values: " (ls-compile value t) ", "
1944 "message: 'Throw uncatched.'"
1948 (defvar *tagbody-counter* 0)
1949 (defvar *go-tag-counter* 0)
1952 (or (integerp x) (symbolp x)))
1954 (defun declare-tagbody-tags (tbidx body)
1956 (mapcar (lambda (label)
1957 (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1958 (make-binding label 'gotag (list tbidx tagidx))))
1959 (remove-if-not #'go-tag-p body))))
1960 (extend-lexenv bindings *environment* 'gotag)))
1962 (define-compilation tagbody (&rest body)
1963 ;; Ignore the tagbody if it does not contain any go-tag. We do this
1964 ;; because 1) it is easy and 2) many built-in forms expand to a
1965 ;; implicit tagbody, so we save some space.
1966 (unless (some #'go-tag-p body)
1967 (return-from tagbody (ls-compile `(progn ,@body nil))))
1968 ;; The translation assumes the first form in BODY is a label
1969 (unless (go-tag-p (car body))
1970 (push (gensym "START") body))
1971 ;; Tagbody compilation
1972 (let ((tbidx *tagbody-counter*))
1973 (let ((*environment* (declare-tagbody-tags tbidx body))
1975 (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1976 (setq initag (second (binding-value b))))
1978 "var tagbody_" tbidx " = " initag ";" *newline*
1980 "while (true) {" *newline*
1981 (indent "try {" *newline*
1982 (indent (let ((content ""))
1983 (code "switch(tagbody_" tbidx "){" *newline*
1984 "case " initag ":" *newline*
1985 (dolist (form (cdr body) content)
1987 (if (not (go-tag-p form))
1988 (indent (ls-compile form) ";" *newline*)
1989 (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1990 (code "case " (second (binding-value b)) ":" *newline*)))))
1991 "default:" *newline*
1992 " break tbloop;" *newline*
1995 "catch (jump) {" *newline*
1996 " if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1997 " tagbody_" tbidx " = jump.label;" *newline*
1999 " throw(jump);" *newline*
2002 "return " (ls-compile nil) ";" *newline*))))
2004 (define-compilation go (label)
2005 (let ((b (lookup-in-lexenv label *environment* 'gotag))
2007 ((symbolp label) (symbol-name label))
2008 ((integerp label) (integer-to-string label)))))
2010 (error (concat "Unknown tag `" n "'.")))
2014 "id: " (first (binding-value b)) ", "
2015 "label: " (second (binding-value b)) ", "
2016 "message: 'Attempt to GO to non-existing tag " n "'"
2019 (define-compilation unwind-protect (form &rest clean-up)
2021 "var ret = " (ls-compile nil) ";" *newline*
2023 (indent "ret = " (ls-compile form) ";" *newline*)
2024 "} finally {" *newline*
2025 (indent (ls-compile-block clean-up))
2027 "return ret;" *newline*))
2029 (define-compilation multiple-value-call (func-form &rest forms)
2031 "var func = " (ls-compile func-form) ";" *newline*
2032 "var args = [" (if *multiple-value-p* "values" "pv") "];" *newline*
2035 "var values = mv;" *newline*
2037 (mapconcat (lambda (form)
2038 (code "vs = " (ls-compile form t) ";" *newline*
2039 "if (typeof vs === 'object' && 'multiple-value' in vs)" *newline*
2040 (indent "args = args.concat(vs);" *newline*)
2042 (indent "args.push(vs);" *newline*)))
2044 "return func.apply(window, args);" *newline*) ";" *newline*))
2046 (define-compilation multiple-value-prog1 (first-form &rest forms)
2048 "var args = " (ls-compile first-form *multiple-value-p*) ";" *newline*
2049 (ls-compile-block forms)
2050 "return args;" *newline*))
2053 ;;; Backquote implementation.
2055 ;;; Author: Guy L. Steele Jr. Date: 27 December 1985
2056 ;;; Tested under Symbolics Common Lisp and Lucid Common Lisp.
2057 ;;; This software is in the public domain.
2059 ;;; The following are unique tokens used during processing.
2060 ;;; They need not be symbols; they need not even be atoms.
2061 (defvar *comma* 'unquote)
2062 (defvar *comma-atsign* 'unquote-splicing)
2064 (defvar *bq-list* (make-symbol "BQ-LIST"))
2065 (defvar *bq-append* (make-symbol "BQ-APPEND"))
2066 (defvar *bq-list** (make-symbol "BQ-LIST*"))
2067 (defvar *bq-nconc* (make-symbol "BQ-NCONC"))
2068 (defvar *bq-clobberable* (make-symbol "BQ-CLOBBERABLE"))
2069 (defvar *bq-quote* (make-symbol "BQ-QUOTE"))
2070 (defvar *bq-quote-nil* (list *bq-quote* nil))
2072 ;;; BACKQUOTE is an ordinary macro (not a read-macro) that processes
2073 ;;; the expression foo, looking for occurrences of #:COMMA,
2074 ;;; #:COMMA-ATSIGN, and #:COMMA-DOT. It constructs code in strict
2075 ;;; accordance with the rules on pages 349-350 of the first edition
2076 ;;; (pages 528-529 of this second edition). It then optionally
2077 ;;; applies a code simplifier.
2079 ;;; If the value of *BQ-SIMPLIFY* is non-NIL, then BACKQUOTE
2080 ;;; processing applies the code simplifier. If the value is NIL,
2081 ;;; then the code resulting from BACKQUOTE is exactly that
2082 ;;; specified by the official rules.
2083 (defparameter *bq-simplify* t)
2085 (defmacro backquote (x)
2086 (bq-completely-process x))
2088 ;;; Backquote processing proceeds in three stages:
2090 ;;; (1) BQ-PROCESS applies the rules to remove occurrences of
2091 ;;; #:COMMA, #:COMMA-ATSIGN, and #:COMMA-DOT corresponding to
2092 ;;; this level of BACKQUOTE. (It also causes embedded calls to
2093 ;;; BACKQUOTE to be expanded so that nesting is properly handled.)
2094 ;;; Code is produced that is expressed in terms of functions
2095 ;;; #:BQ-LIST, #:BQ-APPEND, and #:BQ-CLOBBERABLE. This is done
2096 ;;; so that the simplifier will simplify only list construction
2097 ;;; functions actually generated by BACKQUOTE and will not involve
2098 ;;; any user code in the simplification. #:BQ-LIST means LIST,
2099 ;;; #:BQ-APPEND means APPEND, and #:BQ-CLOBBERABLE means IDENTITY
2100 ;;; but indicates places where "%." was used and where NCONC may
2101 ;;; therefore be introduced by the simplifier for efficiency.
2103 ;;; (2) BQ-SIMPLIFY, if used, rewrites the code produced by
2104 ;;; BQ-PROCESS to produce equivalent but faster code. The
2105 ;;; additional functions #:BQ-LIST* and #:BQ-NCONC may be
2106 ;;; introduced into the code.
2108 ;;; (3) BQ-REMOVE-TOKENS goes through the code and replaces
2109 ;;; #:BQ-LIST with LIST, #:BQ-APPEND with APPEND, and so on.
2110 ;;; #:BQ-CLOBBERABLE is simply eliminated (a call to it being
2111 ;;; replaced by its argument). #:BQ-LIST* is replaced by either
2112 ;;; LIST* or CONS (the latter is used in the two-argument case,
2113 ;;; purely to make the resulting code a tad more readable).
2115 (defun bq-completely-process (x)
2116 (let ((raw-result (bq-process x)))
2117 (bq-remove-tokens (if *bq-simplify*
2118 (bq-simplify raw-result)
2121 (defun bq-process (x)
2123 (list *bq-quote* x))
2124 ((eq (car x) 'backquote)
2125 (bq-process (bq-completely-process (cadr x))))
2126 ((eq (car x) *comma*) (cadr x))
2127 ((eq (car x) *comma-atsign*)
2128 ;; (error ",@~S after `" (cadr x))
2129 (error "ill-formed"))
2130 ;; ((eq (car x) *comma-dot*)
2131 ;; ;; (error ",.~S after `" (cadr x))
2132 ;; (error "ill-formed"))
2133 (t (do ((p x (cdr p))
2134 (q '() (cons (bracket (car p)) q)))
2137 (nreconc q (list (list *bq-quote* p)))))
2138 (when (eq (car p) *comma*)
2139 (unless (null (cddr p))
2140 ;; (error "Malformed ,~S" p)
2141 (error "Malformed"))
2142 (return (cons *bq-append*
2143 (nreconc q (list (cadr p))))))
2144 (when (eq (car p) *comma-atsign*)
2145 ;; (error "Dotted ,@~S" p)
2147 ;; (when (eq (car p) *comma-dot*)
2148 ;; ;; (error "Dotted ,.~S" p)
2149 ;; (error "Dotted"))
2152 ;;; This implements the bracket operator of the formal rules.
2155 (list *bq-list* (bq-process x)))
2156 ((eq (car x) *comma*)
2157 (list *bq-list* (cadr x)))
2158 ((eq (car x) *comma-atsign*)
2160 ;; ((eq (car x) *comma-dot*)
2161 ;; (list *bq-clobberable* (cadr x)))
2162 (t (list *bq-list* (bq-process x)))))
2164 ;;; This auxiliary function is like MAPCAR but has two extra
2165 ;;; purposes: (1) it handles dotted lists; (2) it tries to make
2166 ;;; the result share with the argument x as much as possible.
2167 (defun maptree (fn x)
2170 (let ((a (funcall fn (car x)))
2171 (d (maptree fn (cdr x))))
2172 (if (and (eql a (car x)) (eql d (cdr x)))
2176 ;;; This predicate is true of a form that when read looked
2177 ;;; like %@foo or %.foo.
2178 (defun bq-splicing-frob (x)
2180 (or (eq (car x) *comma-atsign*)
2181 ;; (eq (car x) *comma-dot*)
2184 ;;; This predicate is true of a form that when read
2185 ;;; looked like %@foo or %.foo or just plain %foo.
2188 (or (eq (car x) *comma*)
2189 (eq (car x) *comma-atsign*)
2190 ;; (eq (car x) *comma-dot*)
2193 ;;; The simplifier essentially looks for calls to #:BQ-APPEND and
2194 ;;; tries to simplify them. The arguments to #:BQ-APPEND are
2195 ;;; processed from right to left, building up a replacement form.
2196 ;;; At each step a number of special cases are handled that,
2197 ;;; loosely speaking, look like this:
2199 ;;; (APPEND (LIST a b c) foo) => (LIST* a b c foo)
2200 ;;; provided a, b, c are not splicing frobs
2201 ;;; (APPEND (LIST* a b c) foo) => (LIST* a b (APPEND c foo))
2202 ;;; provided a, b, c are not splicing frobs
2203 ;;; (APPEND (QUOTE (x)) foo) => (LIST* (QUOTE x) foo)
2204 ;;; (APPEND (CLOBBERABLE x) foo) => (NCONC x foo)
2205 (defun bq-simplify (x)
2208 (let ((x (if (eq (car x) *bq-quote*)
2210 (maptree #'bq-simplify x))))
2211 (if (not (eq (car x) *bq-append*))
2213 (bq-simplify-args x)))))
2215 (defun bq-simplify-args (x)
2216 (do ((args (reverse (cdr x)) (cdr args))
2219 (cond ((atom (car args))
2220 (bq-attach-append *bq-append* (car args) result))
2221 ((and (eq (caar args) *bq-list*)
2222 (notany #'bq-splicing-frob (cdar args)))
2223 (bq-attach-conses (cdar args) result))
2224 ((and (eq (caar args) *bq-list**)
2225 (notany #'bq-splicing-frob (cdar args)))
2227 (reverse (cdr (reverse (cdar args))))
2228 (bq-attach-append *bq-append*
2229 (car (last (car args)))
2231 ((and (eq (caar args) *bq-quote*)
2232 (consp (cadar args))
2233 (not (bq-frob (cadar args)))
2234 (null (cddar args)))
2235 (bq-attach-conses (list (list *bq-quote*
2238 ((eq (caar args) *bq-clobberable*)
2239 (bq-attach-append *bq-nconc* (cadar args) result))
2240 (t (bq-attach-append *bq-append*
2243 ((null args) result)))
2245 (defun null-or-quoted (x)
2246 (or (null x) (and (consp x) (eq (car x) *bq-quote*))))
2248 ;;; When BQ-ATTACH-APPEND is called, the OP should be #:BQ-APPEND
2249 ;;; or #:BQ-NCONC. This produces a form (op item result) but
2250 ;;; some simplifications are done on the fly:
2252 ;;; (op '(a b c) '(d e f g)) => '(a b c d e f g)
2253 ;;; (op item 'nil) => item, provided item is not a splicable frob
2254 ;;; (op item 'nil) => (op item), if item is a splicable frob
2255 ;;; (op item (op a b c)) => (op item a b c)
2256 (defun bq-attach-append (op item result)
2257 (cond ((and (null-or-quoted item) (null-or-quoted result))
2258 (list *bq-quote* (append (cadr item) (cadr result))))
2259 ((or (null result) (equal result *bq-quote-nil*))
2260 (if (bq-splicing-frob item) (list op item) item))
2261 ((and (consp result) (eq (car result) op))
2262 (list* (car result) item (cdr result)))
2263 (t (list op item result))))
2265 ;;; The effect of BQ-ATTACH-CONSES is to produce a form as if by
2266 ;;; `(LIST* ,@items ,result) but some simplifications are done
2269 ;;; (LIST* 'a 'b 'c 'd) => '(a b c . d)
2270 ;;; (LIST* a b c 'nil) => (LIST a b c)
2271 ;;; (LIST* a b c (LIST* d e f g)) => (LIST* a b c d e f g)
2272 ;;; (LIST* a b c (LIST d e f g)) => (LIST a b c d e f g)
2273 (defun bq-attach-conses (items result)
2274 (cond ((and (every #'null-or-quoted items)
2275 (null-or-quoted result))
2277 (append (mapcar #'cadr items) (cadr result))))
2278 ((or (null result) (equal result *bq-quote-nil*))
2279 (cons *bq-list* items))
2280 ((and (consp result)
2281 (or (eq (car result) *bq-list*)
2282 (eq (car result) *bq-list**)))
2283 (cons (car result) (append items (cdr result))))
2284 (t (cons *bq-list** (append items (list result))))))
2286 ;;; Removes funny tokens and changes (#:BQ-LIST* a b) into
2287 ;;; (CONS a b) instead of (LIST* a b), purely for readability.
2288 (defun bq-remove-tokens (x)
2289 (cond ((eq x *bq-list*) 'list)
2290 ((eq x *bq-append*) 'append)
2291 ((eq x *bq-nconc*) 'nconc)
2292 ((eq x *bq-list**) 'list*)
2293 ((eq x *bq-quote*) 'quote)
2295 ((eq (car x) *bq-clobberable*)
2296 (bq-remove-tokens (cadr x)))
2297 ((and (eq (car x) *bq-list**)
2300 (cons 'cons (maptree #'bq-remove-tokens (cdr x))))
2301 (t (maptree #'bq-remove-tokens x))))
2303 (define-transformation backquote (form)
2304 (bq-completely-process form))
2309 (defvar *builtins* nil)
2311 (defmacro define-raw-builtin (name args &body body)
2312 ;; Creates a new primitive function `name' with parameters args and
2313 ;; @body. The body can access to the local environment through the
2314 ;; variable *ENVIRONMENT*.
2315 `(push (list ',name (lambda ,args (block ,name ,@body)))
2318 (defmacro define-builtin (name args &body body)
2319 `(define-raw-builtin ,name ,args
2320 (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
2323 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
2324 (defmacro type-check (decls &body body)
2326 ,@(mapcar (lambda (decl)
2327 `(code "var " ,(first decl) " = " ,(third decl) ";" *newline*))
2329 ,@(mapcar (lambda (decl)
2330 `(code "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
2331 (indent "throw 'The value ' + "
2333 " + ' is not a type "
2338 (code "return " (progn ,@body) ";" *newline*)))
2340 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
2341 ;;; a variable which holds a list of forms. It will compile them and
2342 ;;; store the result in some Javascript variables. BODY is evaluated
2343 ;;; with ARGS bound to the list of these variables to generate the
2344 ;;; code which performs the transformation on these variables.
2346 (defun variable-arity-call (args function)
2347 (unless (consp args)
2348 (error "ARGS must be a non-empty list"))
2354 (push (integer-to-string x) fargs)
2355 (let ((v (code "x" (incf counter))))
2358 (code "var " v " = " (ls-compile x) ";" *newline*
2359 "if (typeof " v " !== 'number') throw 'Not a number!';"
2361 (js!selfcall prelude (funcall function (reverse fargs)))))
2364 (defmacro variable-arity (args &body body)
2365 (unless (symbolp args)
2366 (error "Bad usage of VARIABLE-ARITY, you must pass a symbol"))
2367 `(variable-arity-call ,args
2369 (code "return " ,@body ";" *newline*))))
2371 (defun num-op-num (x op y)
2372 (type-check (("x" "number" x) ("y" "number" y))
2375 (define-raw-builtin + (&rest numbers)
2378 (variable-arity numbers
2379 (join numbers "+"))))
2381 (define-raw-builtin - (x &rest others)
2382 (let ((args (cons x others)))
2383 (variable-arity args
2385 (concat "-" (car args))
2388 (define-raw-builtin * (&rest numbers)
2391 (variable-arity numbers
2392 (join numbers "*"))))
2394 (define-raw-builtin / (x &rest others)
2395 (let ((args (cons x others)))
2396 (variable-arity args
2398 (concat "1 /" (car args))
2401 (define-builtin mod (x y) (num-op-num x "%" y))
2404 (defun comparison-conjuntion (vars op)
2409 (concat (car vars) op (cadr vars)))
2411 (concat (car vars) op (cadr vars)
2413 (comparison-conjuntion (cdr vars) op)))))
2415 (defmacro define-builtin-comparison (op sym)
2416 `(define-raw-builtin ,op (x &rest args)
2417 (let ((args (cons x args)))
2418 (variable-arity args
2419 (js!bool (comparison-conjuntion args ,sym))))))
2421 (define-builtin-comparison > ">")
2422 (define-builtin-comparison < "<")
2423 (define-builtin-comparison >= ">=")
2424 (define-builtin-comparison <= "<=")
2425 (define-builtin-comparison = "==")
2427 (define-builtin numberp (x)
2428 (js!bool (code "(typeof (" x ") == \"number\")")))
2430 (define-builtin floor (x)
2431 (type-check (("x" "number" x))
2434 (define-builtin cons (x y)
2435 (code "({car: " x ", cdr: " y "})"))
2437 (define-builtin consp (x)
2440 "var tmp = " x ";" *newline*
2441 "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
2443 (define-builtin car (x)
2445 "var tmp = " x ";" *newline*
2446 "return tmp === " (ls-compile nil)
2447 "? " (ls-compile nil)
2448 ": tmp.car;" *newline*))
2450 (define-builtin cdr (x)
2452 "var tmp = " x ";" *newline*
2453 "return tmp === " (ls-compile nil) "? "
2455 ": tmp.cdr;" *newline*))
2457 (define-builtin rplaca (x new)
2458 (type-check (("x" "object" x))
2459 (code "(x.car = " new ", x)")))
2461 (define-builtin rplacd (x new)
2462 (type-check (("x" "object" x))
2463 (code "(x.cdr = " new ", x)")))
2465 (define-builtin symbolp (x)
2468 "var tmp = " x ";" *newline*
2469 "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
2471 (define-builtin make-symbol (name)
2472 (type-check (("name" "string" name))
2475 (define-builtin symbol-name (x)
2476 (code "(" x ").name"))
2478 (define-builtin set (symbol value)
2479 (code "(" symbol ").value = " value))
2481 (define-builtin fset (symbol value)
2482 (code "(" symbol ").fvalue = " value))
2484 (define-builtin boundp (x)
2485 (js!bool (code "(" x ".value !== undefined)")))
2487 (define-builtin symbol-value (x)
2489 "var symbol = " x ";" *newline*
2490 "var value = symbol.value;" *newline*
2491 "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
2492 "return value;" *newline*))
2494 (define-builtin symbol-function (x)
2496 "var symbol = " x ";" *newline*
2497 "var func = symbol.fvalue;" *newline*
2498 "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
2499 "return func;" *newline*))
2501 (define-builtin symbol-plist (x)
2502 (code "((" x ").plist || " (ls-compile nil) ")"))
2504 (define-builtin lambda-code (x)
2505 (code "(" x ").toString()"))
2507 (define-builtin eq (x y) (js!bool (code "(" x " === " y ")")))
2508 (define-builtin equal (x y) (js!bool (code "(" x " == " y ")")))
2510 (define-builtin char-to-string (x)
2511 (type-check (("x" "number" x))
2512 "String.fromCharCode(x)"))
2514 (define-builtin stringp (x)
2515 (js!bool (code "(typeof(" x ") == \"string\")")))
2517 (define-builtin string-upcase (x)
2518 (type-check (("x" "string" x))
2521 (define-builtin string-length (x)
2522 (type-check (("x" "string" x))
2525 (define-raw-builtin slice (string a &optional b)
2527 "var str = " (ls-compile string) ";" *newline*
2528 "var a = " (ls-compile a) ";" *newline*
2530 (when b (code "b = " (ls-compile b) ";" *newline*))
2531 "return str.slice(a,b);" *newline*))
2533 (define-builtin char (string index)
2534 (type-check (("string" "string" string)
2535 ("index" "number" index))
2536 "string.charCodeAt(index)"))
2538 (define-builtin concat-two (string1 string2)
2539 (type-check (("string1" "string" string1)
2540 ("string2" "string" string2))
2541 "string1.concat(string2)"))
2543 (define-raw-builtin funcall (func &rest args)
2545 "var f = " (ls-compile func) ";" *newline*
2546 "return (typeof f === 'function'? f: f.fvalue)("
2547 (join (cons (if *multiple-value-p* "values" "pv")
2548 (mapcar #'ls-compile args))
2552 (define-raw-builtin apply (func &rest args)
2554 (code "(" (ls-compile func) ")()")
2555 (let ((args (butlast args))
2556 (last (car (last args))))
2558 "var f = " (ls-compile func) ";" *newline*
2559 "var args = [" (join (cons (if *multiple-value-p* "values" "pv")
2560 (mapcar #'ls-compile args))
2563 "var tail = (" (ls-compile last) ");" *newline*
2564 "while (tail != " (ls-compile nil) "){" *newline*
2565 " args.push(tail.car);" *newline*
2566 " tail = tail.cdr;" *newline*
2568 "return (typeof f === 'function'? f : f.fvalue).apply(this, args);" *newline*))))
2570 (define-builtin js-eval (string)
2571 (type-check (("string" "string" string))
2572 (if *multiple-value-p*
2574 "var v = eval.apply(window, [string]);" *newline*
2575 "if (typeof v !== 'object' || !('multiple-value' in v)){" *newline*
2576 (indent "v = [v];" *newline*
2577 "v['multiple-value'] = true;" *newline*)
2579 "return values.apply(this, v);" *newline*)
2580 "eval.apply(window, [string])")))
2582 (define-builtin error (string)
2583 (js!selfcall "throw " string ";" *newline*))
2585 (define-builtin new () "{}")
2587 (define-builtin objectp (x)
2588 (js!bool (code "(typeof (" x ") === 'object')")))
2590 (define-builtin oget (object key)
2592 "var tmp = " "(" object ")[" key "];" *newline*
2593 "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
2595 (define-builtin oset (object key value)
2596 (code "((" object ")[" key "] = " value ")"))
2598 (define-builtin in (key object)
2599 (js!bool (code "((" key ") in (" object "))")))
2601 (define-builtin functionp (x)
2602 (js!bool (code "(typeof " x " == 'function')")))
2604 (define-builtin write-string (x)
2605 (type-check (("x" "string" x))
2608 (define-builtin make-array (n)
2610 "var r = [];" *newline*
2611 "for (var i = 0; i < " n "; i++)" *newline*
2612 (indent "r.push(" (ls-compile nil) ");" *newline*)
2613 "return r;" *newline*))
2615 (define-builtin arrayp (x)
2618 "var x = " x ";" *newline*
2619 "return typeof x === 'object' && 'length' in x;")))
2621 (define-builtin aref (array n)
2623 "var x = " "(" array ")[" n "];" *newline*
2624 "if (x === undefined) throw 'Out of range';" *newline*
2625 "return x;" *newline*))
2627 (define-builtin aset (array n value)
2629 "var x = " array ";" *newline*
2630 "var i = " n ";" *newline*
2631 "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
2632 "return x[i] = " value ";" *newline*))
2634 (define-builtin get-unix-time ()
2635 (code "(Math.round(new Date() / 1000))"))
2637 (define-builtin values-array (array)
2638 (if *multiple-value-p*
2639 (code "values.apply(this, " array ")")
2640 (code "pv.apply(this, " array ")")))
2642 (define-raw-builtin values (&rest args)
2643 (if *multiple-value-p*
2644 (code "values(" (join (mapcar #'ls-compile args) ", ") ")")
2645 (code "pv(" (join (mapcar #'ls-compile args) ", ") ")")))
2649 (let ((b (lookup-in-lexenv x *environment* 'function)))
2650 (and (eq (binding-type b) 'macro)
2653 (defun ls-macroexpand-1 (form)
2654 (let ((macro-binding (macro (car form))))
2656 (let ((expander (binding-value macro-binding)))
2657 (when (listp expander)
2658 (let ((compiled (eval expander)))
2659 ;; The list representation are useful while
2660 ;; bootstrapping, as we can dump the definition of the
2661 ;; macros easily, but they are slow because we have to
2662 ;; evaluate them and compile them now and again. So, let
2663 ;; us replace the list representation version of the
2664 ;; function with the compiled one.
2666 #+ecmalisp (set-binding-value macro-binding compiled)
2667 (setq expander compiled)))
2668 (apply expander (cdr form)))
2671 (defun compile-funcall (function args)
2672 (let* ((values-funcs (if *multiple-value-p* "values" "pv"))
2673 (arglist (concat "(" (join (cons values-funcs (mapcar #'ls-compile args)) ", ") ")")))
2675 ((translate-function function)
2676 (concat (translate-function function) arglist))
2677 ((and (symbolp function)
2678 #+ecmalisp (eq (symbol-package function) (find-package "COMMON-LISP"))
2680 (code (ls-compile `',function) ".fvalue" arglist))
2682 (code (ls-compile `#',function) arglist)))))
2684 (defun ls-compile-block (sexps &optional return-last-p)
2686 (code (ls-compile-block (butlast sexps))
2687 "return " (ls-compile (car (last sexps)) *multiple-value-p*) ";")
2689 (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
2690 (concat ";" *newline*))))
2692 (defun ls-compile (sexp &optional multiple-value-p)
2693 (let ((*multiple-value-p* multiple-value-p))
2696 (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
2698 ((and b (not (member 'special (binding-declarations b))))
2700 ((or (keywordp sexp)
2701 (member 'constant (binding-declarations b)))
2702 (code (ls-compile `',sexp) ".value"))
2704 (ls-compile `(symbol-value ',sexp))))))
2705 ((integerp sexp) (integer-to-string sexp))
2706 ((stringp sexp) (code "\"" (escape-string sexp) "\""))
2707 ((arrayp sexp) (literal sexp))
2709 (let ((name (car sexp))
2713 ((assoc name *compilations*)
2714 (let ((comp (second (assoc name *compilations*))))
2716 ;; Built-in functions
2717 ((and (assoc name *builtins*)
2718 (not (claimp name 'function 'notinline)))
2719 (let ((comp (second (assoc name *builtins*))))
2723 (ls-compile (ls-macroexpand-1 sexp) multiple-value-p)
2724 (compile-funcall name args))))))
2726 (error (concat "How should I compile " (prin1-to-string sexp) "?"))))))
2729 (defvar *compile-print-toplevels* nil)
2731 (defun truncate-string (string &optional (width 60))
2732 (let ((size (length string))
2733 (n (or (position #\newline string)
2734 (min width (length string)))))
2735 (subseq string 0 n)))
2737 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
2738 (let ((*toplevel-compilations* nil))
2740 ((and (consp sexp) (eq (car sexp) 'progn))
2741 (let ((subs (mapcar (lambda (s)
2742 (ls-compile-toplevel s t))
2744 (join (remove-if #'null-or-empty-p subs))))
2746 (when *compile-print-toplevels*
2747 (let ((form-string (prin1-to-string sexp)))
2748 (write-string "Compiling ")
2749 (write-string (truncate-string form-string))
2750 (write-line "...")))
2752 (let ((code (ls-compile sexp multiple-value-p)))
2753 (code (join-trailing (get-toplevel-compilations)
2754 (code ";" *newline*))
2756 (code code ";" *newline*))))))))
2759 ;;; Once we have the compiler, we define the runtime environment and
2760 ;;; interactive development (eval), which works calling the compiler
2761 ;;; and evaluating the Javascript result globally.
2766 (js-eval (ls-compile-toplevel x t)))
2768 (export '(&rest &key &optional &body * *gensym-counter* *package* + - / 1+ 1- <
2769 <= = = > >= and append apply aref arrayp assoc atom block boundp
2770 boundp butlast caar cadddr caddr cadr car car case catch cdar cdddr
2771 cddr cdr cdr char char-code fdefinition find-package find-symbol first
2772 flet fourth fset funcall function functionp gensym get-setf-expansion
2773 get-universal-time go identity if in-package incf integerp integerp
2774 intern keywordp labels lambda last length let let* char= code-char
2775 cond cons consp constantly copy-list decf declaim define-setf-expander
2776 defconstant defparameter defun defmacro defvar digit-char digit-char-p
2777 disassemble do do* documentation dolist dotimes ecase eq eql equal
2778 error eval every export list-all-packages list list* listp loop make-array
2779 make-package make-symbol mapcar member minusp mod multiple-value-bind
2780 multiple-value-call multiple-value-list multiple-value-prog1 nconc nil not
2781 nth nthcdr null numberp or package-name package-use-list packagep
2782 parse-integer plusp prin1-to-string print proclaim prog1 prog2 progn
2783 psetq push quote nreconc remove remove-if remove-if-not return return-from
2784 revappend reverse rplaca rplacd second set setf setq some
2785 string-upcase string string= stringp subseq symbol-function
2786 symbol-name symbol-package symbol-plist symbol-value symbolp t tagbody
2787 third throw truncate unless unwind-protect values values-list variable
2788 warn when write-line write-string zerop))
2790 (setq *package* *user-package*)
2792 (js-eval "var lisp")
2793 (js-vset "lisp" (new))
2794 (js-vset "lisp.read" #'ls-read-from-string)
2795 (js-vset "lisp.print" #'prin1-to-string)
2796 (js-vset "lisp.eval" #'eval)
2797 (js-vset "lisp.compile" (lambda (s) (ls-compile-toplevel s t)))
2798 (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
2799 (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str) t)))
2801 ;; Set the initial global environment to be equal to the host global
2802 ;; environment at this point of the compilation.
2804 (toplevel-compilation
2805 (ls-compile `(setq *environment* ',*environment*))))
2808 (toplevel-compilation
2811 ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
2813 (setq *literal-symbols* ',*literal-symbols*)
2814 (setq *variable-counter* ,*variable-counter*)
2815 (setq *gensym-counter* ,*gensym-counter*)
2816 (setq *block-counter* ,*block-counter*)))))
2819 (toplevel-compilation
2821 `(setq *literal-counter* ,*literal-counter*)))))
2824 ;;; Finally, we provide a couple of functions to easily bootstrap
2825 ;;; this. It just calls the compiler with this file as input.
2829 (defun read-whole-file (filename)
2830 (with-open-file (in filename)
2831 (let ((seq (make-array (file-length in) :element-type 'character)))
2832 (read-sequence seq in)
2835 (defun ls-compile-file (filename output &key print)
2836 (let ((*compiling-file* t)
2837 (*compile-print-toplevels* print))
2838 (with-open-file (out output :direction :output :if-exists :supersede)
2839 (write-string (read-whole-file "prelude.js") out)
2840 (let* ((source (read-whole-file filename))
2841 (in (make-string-stream source)))
2843 for x = (ls-read in)
2845 for compilation = (ls-compile-toplevel x)
2846 when (plusp (length compilation))
2847 do (write-string compilation out))))))
2850 (setq *environment* (make-lexenv))
2851 (setq *literal-symbols* nil)
2852 (setq *variable-counter* 0
2856 (ls-compile-file "ecmalisp.lisp" "ecmalisp.js" :print t)))