Commit | Line | Data |
---|---|---|
cadde2db JM |
1 | #!/usr/bin/env hy |
2 | ||
cadde2db JM |
3 | (import sys traceback) |
4 | (import [reader [read-str Blank]]) | |
5 | (import [printer [pr-str]]) | |
6 | ||
7 | ;; read | |
8 | (defn READ [str] | |
9 | (read-str str)) | |
10 | ||
11 | ;; eval | |
12 | (defn eval-ast [ast env] | |
13 | (if | |
14 | (symbol? ast) (if (.has_key env ast) (get env ast) | |
15 | (raise (Exception (+ ast " not found")))) | |
081c3223 JM |
16 | (instance? dict ast) (dict (map (fn [k] |
17 | [(EVAL k env) (EVAL (get ast k) env)]) | |
18 | ast)) | |
cadde2db JM |
19 | (instance? tuple ast) (tuple (map (fn [x] (EVAL x env)) ast)) |
20 | (instance? list ast) (list (map (fn [x] (EVAL x env)) ast)) | |
21 | True ast)) | |
22 | ||
23 | (defn EVAL [ast env] | |
1872f735 JM |
24 | ;; indented to match later steps |
25 | (if (not (instance? tuple ast)) | |
26 | (eval-ast ast env) | |
cadde2db | 27 | |
1872f735 JM |
28 | ;; apply list |
29 | (if | |
30 | (empty? ast) | |
31 | ast | |
e8f52c24 | 32 | |
1872f735 JM |
33 | ;; apply |
34 | (do | |
35 | (setv el (eval-ast ast env) | |
36 | f (first el) | |
37 | args (list (rest el))) | |
38 | (apply f args))))) | |
cadde2db JM |
39 | |
40 | ||
41 | (defn PRINT [exp] | |
42 | (pr-str exp True)) | |
43 | ||
44 | ;; repl | |
cadde2db JM |
45 | (def repl-env {'+ + |
46 | '- - | |
47 | '* * | |
48 | '/ (fn [a b] (int (/ a b)))}) | |
49 | ||
50 | (defn REP [str] | |
51 | (PRINT (EVAL (READ str) repl-env))) | |
52 | ||
e8f52c24 JM |
53 | (defmain [&rest args] |
54 | ;; indented to match later steps | |
55 | (while True | |
56 | (try | |
57 | (do (setv line (raw_input "user> ")) | |
58 | (if (= "" line) (continue)) | |
59 | (print (REP line))) | |
60 | (except [EOFError] (break)) | |
61 | (except [Blank]) | |
62 | (except [] | |
63 | (print (.join "" (apply traceback.format_exception | |
64 | (.exc_info sys)))))))) |