Merge commit 'e47ddca2f8d80145386a377fc81a738d89c46cf0'
[jackhill/mal.git] / mal / step6_file.mal
1 (load-file "../mal/env.mal")
2 (load-file "../mal/core.mal")
3
4 ;; read
5 (def! READ (fn* [strng]
6 (read-string strng)))
7
8
9 ;; eval
10 (def! eval-ast (fn* [ast env] (do
11 ;;(do (prn "eval-ast" ast "/" (keys env)) )
12 (cond
13 (symbol? ast) (env-get env ast)
14
15 (list? ast) (map (fn* [exp] (EVAL exp env)) ast)
16
17 (vector? ast) (apply vector (map (fn* [exp] (EVAL exp env)) ast))
18
19 (map? ast) (apply hash-map
20 (apply concat
21 (map (fn* [k] [k (EVAL (get ast k) env)])
22 (keys ast))))
23
24 "else" ast))))
25
26 (def! LET (fn* [env args]
27 (if (> (count args) 0)
28 (do
29 (env-set env (nth args 0) (EVAL (nth args 1) env))
30 (LET env (rest (rest args)))))))
31
32 (def! EVAL (fn* [ast env] (do
33 ;;(do (prn "EVAL" ast "/" (keys @env)) )
34 (if (not (list? ast))
35 (eval-ast ast env)
36
37 ;; apply list
38 (let* [a0 (first ast)]
39 (cond
40 (= 'def! a0)
41 (env-set env (nth ast 1) (EVAL (nth ast 2) env))
42
43 (= 'let* a0)
44 (let* [let-env (new-env env)]
45 (do
46 (LET let-env (nth ast 1))
47 (EVAL (nth ast 2) let-env)))
48
49 (= 'do a0)
50 (let* [el (eval-ast (rest ast) env)]
51 (nth el (- (count el) 1)))
52
53 (= 'if a0)
54 (let* [cond (EVAL (nth ast 1) env)]
55 (if (or (= cond nil) (= cond false))
56 (if (> (count ast) 3)
57 (EVAL (nth ast 3) env)
58 nil)
59 (EVAL (nth ast 2) env)))
60
61 (= 'fn* a0)
62 (fn* [& args]
63 (EVAL (nth ast 2) (new-env env (nth ast 1) args)))
64
65 "else"
66 (let* [el (eval-ast ast env)
67 f (first el)
68 args (rest el)]
69 (apply f args))))))))
70
71
72 ;; print
73 (def! PRINT (fn* [exp] (pr-str exp)))
74
75 ;; repl
76 (def! repl-env (new-env))
77 (def! rep (fn* [strng]
78 (PRINT (EVAL (READ strng) repl-env))))
79
80 ;; core.mal: defined directly using mal
81 (map (fn* [data] (env-set repl-env (nth data 0) (nth data 1))) core_ns)
82 (env-set repl-env 'eval (fn* [ast] (EVAL ast repl-env)))
83 (env-set repl-env '*ARGV* (rest *ARGV*))
84
85 ;; core.mal: defined using the new language itself
86 (rep "(def! not (fn* [a] (if a false true)))")
87 (rep "(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))")
88
89 ;; repl loop
90 (def! repl-loop (fn* []
91 (let* [line (readline "mal-user> ")]
92 (if line
93 (do
94 (if (not (= "" line))
95 (try*
96 (println (rep line))
97 (catch* exc
98 (println "Uncaught exception:" exc))))
99 (repl-loop))))))
100
101 (def! -main (fn* [& args]
102 (if (> (count args) 0)
103 (rep (str "(load-file \"" (first args) "\")"))
104 (repl-loop))))
105 (apply -main *ARGV*)