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 extend-env (args env)
36 (append (mapcar #'make-binding args) env))
38 (defun ls-lookup (symbol env)
39 (let ((binding (assoc symbol env)))
41 (format nil "~a" (cdr binding))
42 (error "Undefined variable `~a'" symbol))))
44 (defmacro define-compilation (name args &body body)
45 "creates a new primitive `name' with parameters args and @body. The
46 body can access to the local environment through the variable env"
47 `(push (list ',name (lambda (env ,@args) ,@body))
50 (define-compilation if (condition true false)
51 (format nil "((~a)? (~a) : (~a))"
52 (ls-compile condition env)
54 (ls-compile false env)))
56 (define-compilation lambda (args &rest body)
57 (let ((new-env (extend-env args env)))
59 (join (mapcar (lambda (x) (ls-lookup x new-env))
64 (ls-compile-block body new-env)
68 (define-compilation setq (var val)
69 (format nil "~a = ~a" (ls-lookup var env) (ls-compile val env)))
71 (defun lisp->js (sexp)
73 ((integerp sexp) (format nil "~a" sexp))
74 ((stringp sexp) (format nil "\"~a\"" sexp))
75 ((listp sexp) (concat "[" (join (mapcar 'lisp->js sexp) ",") "]"))))
77 (define-compilation quote (sexp)
80 (define-compilation while (pred &rest body)
81 (format nil "(function(){while(~a){~{~a~}}})()"
83 (mapcar (lambda (x) (ls-compile x env)) body)))
85 (defparameter *env* '())
86 (defparameter *env-fun* '())
88 (defun ls-compile (sexp &optional env)
90 ((symbolp sexp) (ls-lookup sexp env))
91 ((integerp sexp) (format nil "~a" sexp))
92 ((stringp sexp) (format nil " \"~a\" " sexp))
95 (let ((compiler-func (second (assoc (car sexp) *compilations*))))
97 (apply compiler-func env (cdr sexp))
101 (defun ls-compile-sexps (sexps env)
102 (concat (join (mapcar (lambda (x)
108 (defun ls-compile-block (sexps env)
109 (concat (ls-compile-sexps (butlast sexps env) env)
111 return " (ls-compile (car (last sexps)) env) ";"))