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 (defparameter *env* '())
82 (defparameter *env-fun* '())
84 (defun ls-compile (sexp &optional env)
86 ((symbolp sexp) (ls-lookup sexp env))
87 ((integerp sexp) (format nil "~a" sexp))
88 ((stringp sexp) (format nil " \"~a\" " sexp))
91 (let ((compiler-func (second (assoc (car sexp) *compilations*))))
93 (apply compiler-func env (cdr sexp))
97 (defun ls-compile-block (sexps env)
98 (concat (join (mapcar (lambda (x)
99 (concat (ls-compile x env) ";"))
103 return " (ls-compile (car (last sexps)) env) ";"))
106 (defun compile-test ()
107 (with-open-file (in "test.lisp")
108 (with-open-file (out "test.js" :direction :output :if-exists :supersede)
110 for x = (read in nil) while x
111 do (write-string (ls-compile x) out)))))