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)))))
34 (defvar *compilations* nil)
36 (defun extend-env (args env)
37 (append (mapcar #'make-binding args) env))
39 (defun ls-lookup (symbol env)
40 (let ((binding (assoc symbol env)))
42 (format nil "~a" (cdr binding))
43 (error "Undefined variable `~a'" symbol))))
45 (defmacro define-compilation (name args &body body)
46 "creates a new primitive `name' with parameters args and @body. The
47 body can access to the local environment through the variable env"
48 `(push (list ',name (lambda (env ,@args) ,@body))
51 (define-compilation if (condition true false)
52 (format nil "((~a)? (~a) : (~a))"
53 (ls-compile condition env)
55 (ls-compile false env)))
57 (define-compilation lambda (args &rest body)
58 (let ((new-env (extend-env args env)))
60 (join (mapcar (lambda (x) (ls-lookup x new-env))
65 (ls-compile-block body new-env)
69 (define-compilation setq (var val)
70 (format nil "~a = ~a" (ls-lookup var env) (ls-compile val env)))
72 (defun lisp->js (sexp)
74 ((integerp sexp) (format nil "~a" sexp))
75 ((stringp sexp) (format nil "\"~a\"" sexp))
76 ((listp sexp) (concat "[" (join (mapcar 'lisp->js sexp) ",") "]"))))
78 (define-compilation quote (sexp)
81 (define-compilation debug (form)
82 (format nil "console.log(~a)" (ls-compile form env)))
84 (defparameter *env* '())
85 (defparameter *env-fun* '())
87 (defun ls-compile (sexp &optional env)
89 ((symbolp sexp) (ls-lookup sexp env))
90 ((integerp sexp) (format nil "~a" sexp))
91 ((stringp sexp) (format nil " \"~a\" " sexp))
93 (let ((compiler-func (second (assoc (car sexp) *compilations*))))
95 (apply compiler-func env (cdr sexp))
99 (defun ls-compile-block (sexps env)
100 (concat (join (mapcar (lambda (x)
101 (concat (ls-compile x env) ";"))
105 return " (ls-compile (car (last sexps)) env) ";"))
108 (defun compile-test ()
109 (with-open-file (in "test.lisp")
110 (with-open-file (out "test.js" :direction :output :if-exists :supersede)
112 for x = (read in nil) while x
113 do (format out "~a;~%" (ls-compile x))))))