3 (defmacro while (condition &body body)
8 ;;; simplify me, please
9 (defun concat (&rest strs)
10 (reduce (lambda (s1 s2) (concatenate 'string s1 s2))
16 (defun make-binding (symbol)
17 (cons symbol (format nil "V_~d" (incf counter)))))
19 ;;; Concatenate a list of strings, with a separator
20 (defun join (list separator)
29 (join (cdr list) separator)))))
33 (defvar *compilations* nil)
35 (defun ls-compile-sexps (sexps env)
36 (concat (join (mapcar (lambda (x)
42 (defun ls-compile-block (sexps env)
43 (concat (ls-compile-sexps (butlast sexps env) env)
45 return " (ls-compile (car (last sexps)) env) ";"))
48 (defun extend-env (args env)
49 (append (mapcar #'make-binding args) env))
51 (defun ls-lookup (symbol env)
52 (let ((binding (assoc symbol env)))
54 (format nil "~a" (cdr binding))
55 (error "Undefined variable `~a'" symbol))))
57 (defmacro define-compilation (name args &body body)
58 "creates a new primitive `name' with parameters args and @body. The
59 body can access to the local environment through the variable env"
60 `(push (list ',name (lambda (env ,@args) ,@body))
63 (define-compilation if (condition true false)
64 (format nil "((~a)? (~a) : (~a))"
65 (ls-compile condition env)
67 (ls-compile false env)))
69 (define-compilation lambda (args &rest body)
70 (let ((new-env (extend-env args env)))
72 (join (mapcar (lambda (x) (ls-lookup x new-env))
77 (ls-compile-block body new-env)
81 (define-compilation setq (var val)
82 (format nil "~a = ~a" (ls-lookup var env) (ls-compile val env)))
84 (defun lisp->js (sexp)
86 ((integerp sexp) (format nil "~a" sexp))
87 ((stringp sexp) (format nil "\"~a\"" sexp))
88 ((listp sexp) (concat "[" (join (mapcar 'lisp->js sexp) ",") "]"))))
90 (define-compilation quote (sexp)
93 (define-compilation while (pred &rest body)
94 (format nil "(function(){while(~a){~a}})() "
96 (ls-compile-sexps body env)))
98 (defparameter *env* '())
99 (defparameter *env-fun* '())
101 (defun ls-compile (sexp &optional env)
103 ((symbolp sexp) (ls-lookup sexp env))
104 ((integerp sexp) (format nil "~a" sexp))
105 ((stringp sexp) (format nil " \"~a\" " sexp))
108 (let ((compiler-func (second (assoc (car sexp) *compilations*))))
110 (apply compiler-func env (cdr sexp))