quote for integers, strings and lists. no symbols
[jscl.git] / lispstrack.lisp
1 ;;; Utils
2
3 ;;; simplify me, please
4 (defun concat (&rest strs)
5   (reduce (lambda (s1 s2) (concatenate 'string s1 s2))
6           strs
7           :initial-value ""))
8
9
10 (let ((counter 0))
11   (defun make-binding (symbol)
12     (cons symbol (format nil "V_~d" (incf counter)))))
13
14 ;;; Compiler
15
16 (defvar *compilations* nil)
17
18 (defun extend-env (args env)
19   (append (mapcar #'make-binding args) env))
20
21 (defun ls-lookup (symbol env)
22   (let ((binding (assoc symbol env)))
23     (if binding
24         (format nil "~a" (cdr binding))
25         (error "Undefined variable `~a'"  symbol))))
26
27 (defmacro define-compilation (name args &body body)
28   "creates a new primitive `name' with parameters args and @body. The
29 body can access to the local environment through the variable env"
30   `(push (list ',name (lambda (env ,@args) ,@body))
31          *compilations*))
32
33 (define-compilation if (condition true false)
34   (format nil "((~a)? (~a) : (~a))"
35           (ls-compile condition env)
36           (ls-compile true env)
37           (ls-compile false env)))
38
39 (define-compilation lambda (args &rest body)
40   (let ((new-env (extend-env args env)))
41     (concat "(function ("
42             (format nil "~{~a~^, ~}" (mapcar
43                                       (lambda (x) (ls-lookup x new-env))
44                                       args))
45             "){ "
46             (ls-compile-block body new-env)
47             "})
48 ")))
49
50 (define-compilation setq (var val)
51   (format nil "~a = ~a" (ls-lookup var env) (ls-compile val env)))
52
53 (define-compilation quote (sexp)
54   (cond
55     ((integerp sexp) (format nil "~a" sexp))
56     ((stringp sexp) (format nil "\"~a\"" sexp))
57     ((listp sexp)   (format nil "[~{~a~^, ~}]" sexp))))
58
59 (defparameter *env* '())
60 (defparameter *env-fun* '())
61
62 (defun ls-compile (sexp &optional env)
63   (cond
64     ((symbolp sexp) (ls-lookup sexp env))
65     ((integerp sexp) (format nil "~a" sexp))
66     ((stringp sexp) (format nil " \"~a\" " sexp))
67                                         ; list
68     ((listp sexp)
69      (let ((compiler-func (second (assoc (car sexp) *compilations*))))
70        (if compiler-func
71            (apply compiler-func env (cdr sexp))
72            ;; funcall
73            )))))
74
75 (defun ls-compile-block (sexps env)
76   (format nil
77     "~{~#[~; return ~a;~:;~a;~%~]~}"
78     (mapcar #'(lambda (x)
79                       (ls-compile x env))
80                   sexps)))