2017-09-21 05:21:41 +03:00
|
|
|
#!/usr/bin/env hy
|
|
|
|
|
2017-09-22 06:35:00 +03:00
|
|
|
(import [hy.models [HySymbol :as Sym]])
|
2017-09-21 05:21:41 +03:00
|
|
|
(import sys traceback)
|
|
|
|
(import [reader [read-str Blank]])
|
|
|
|
(import [printer [pr-str]])
|
|
|
|
(import [env [env-new env-get env-set]])
|
|
|
|
|
|
|
|
;; read
|
|
|
|
(defn READ [str]
|
|
|
|
(read-str str))
|
|
|
|
|
|
|
|
;; eval
|
|
|
|
(defn eval-ast [ast env]
|
|
|
|
;;(print "eval-ast:" ast (type ast))
|
|
|
|
(if
|
|
|
|
(symbol? ast) (env-get env ast)
|
2017-09-22 06:35:00 +03:00
|
|
|
(instance? dict ast) (dict (map (fn [k]
|
|
|
|
[(EVAL k env) (EVAL (get ast k) env)])
|
|
|
|
ast))
|
2017-09-21 05:21:41 +03:00
|
|
|
(instance? tuple ast) (tuple (map (fn [x] (EVAL x env)) ast))
|
|
|
|
(instance? list ast) (list (map (fn [x] (EVAL x env)) ast))
|
|
|
|
True ast))
|
|
|
|
|
|
|
|
(defn EVAL [ast env]
|
2017-09-22 07:58:14 +03:00
|
|
|
;;(print "EVAL:" ast (type ast))
|
|
|
|
;; indented to match later steps
|
|
|
|
(if (not (instance? tuple ast))
|
|
|
|
(eval-ast ast env)
|
2017-09-21 05:21:41 +03:00
|
|
|
|
2017-09-22 07:58:14 +03:00
|
|
|
;; apply list
|
|
|
|
(do
|
|
|
|
(setv [a0 a1 a2] [(nth ast 0) (nth ast 1) (nth ast 2)])
|
|
|
|
(if
|
|
|
|
(none? a0)
|
|
|
|
ast
|
2017-09-21 05:21:41 +03:00
|
|
|
|
2017-09-22 07:58:14 +03:00
|
|
|
(= (Sym "def!") a0)
|
|
|
|
(env-set env a1 (EVAL a2 env))
|
2017-09-21 05:21:41 +03:00
|
|
|
|
2017-09-22 07:58:14 +03:00
|
|
|
(= (Sym "let*") a0)
|
|
|
|
(do
|
|
|
|
(setv env (env-new env))
|
|
|
|
(for [[b e] (partition a1 2)]
|
|
|
|
(env-set env b (EVAL e env)))
|
|
|
|
(EVAL a2 env))
|
2017-09-21 05:21:41 +03:00
|
|
|
|
2017-09-22 07:58:14 +03:00
|
|
|
;; apply
|
|
|
|
(do
|
|
|
|
(setv el (eval-ast ast env)
|
|
|
|
f (first el)
|
|
|
|
args (list (rest el)))
|
|
|
|
(apply f args))))))
|
2017-09-21 05:21:41 +03:00
|
|
|
|
|
|
|
;; print
|
|
|
|
(defn PRINT [exp]
|
|
|
|
(pr-str exp True))
|
|
|
|
|
|
|
|
;; repl
|
|
|
|
(def repl-env {'+ +
|
|
|
|
'- -
|
|
|
|
'* *
|
|
|
|
'/ (fn [a b] (int (/ a b)))})
|
|
|
|
|
|
|
|
(defn REP [str]
|
|
|
|
(PRINT (EVAL (READ str) repl-env)))
|
|
|
|
|
2017-09-22 07:32:15 +03:00
|
|
|
(defmain [&rest args]
|
|
|
|
;; indented to match later steps
|
|
|
|
(while True
|
|
|
|
(try
|
|
|
|
(do (setv line (raw_input "user> "))
|
|
|
|
(if (= "" line) (continue))
|
|
|
|
(print (REP line)))
|
|
|
|
(except [EOFError] (break))
|
|
|
|
(except [Blank])
|
|
|
|
(except []
|
|
|
|
(print (.join "" (apply traceback.format_exception
|
|
|
|
(.exc_info sys))))))))
|