| 1 | #!/usr/bin/env hy |
| 2 | |
| 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")))) |
| 16 | (instance? dict ast) (dict (map (fn [k] |
| 17 | [(EVAL k env) (EVAL (get ast k) env)]) |
| 18 | ast)) |
| 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] |
| 24 | ;; indented to match later steps |
| 25 | (if (not (instance? tuple ast)) |
| 26 | (eval-ast ast env) |
| 27 | |
| 28 | ;; apply list |
| 29 | (if |
| 30 | (empty? ast) |
| 31 | ast |
| 32 | |
| 33 | ;; apply |
| 34 | (do |
| 35 | (setv el (eval-ast ast env) |
| 36 | f (first el) |
| 37 | args (list (rest el))) |
| 38 | (apply f args))))) |
| 39 | |
| 40 | ;; print |
| 41 | (defn PRINT [exp] |
| 42 | (pr-str exp True)) |
| 43 | |
| 44 | ;; repl |
| 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 | |
| 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 [e Exception] |
| 63 | (print (.join "" (apply traceback.format_exception |
| 64 | (.exc_info sys)))))))) |