plpgsql: IO using stream table. Add keywords.
[jackhill/mal.git] / python / step6_file.py
1 import sys, traceback
2 import mal_readline
3 import mal_types as types
4 import reader, printer
5 from env import Env
6 import core
7
8 # read
9 def READ(str):
10 return reader.read_str(str)
11
12 # eval
13 def eval_ast(ast, env):
14 if types._symbol_Q(ast):
15 return env.get(ast)
16 elif types._list_Q(ast):
17 return types._list(*map(lambda a: EVAL(a, env), ast))
18 elif types._vector_Q(ast):
19 return types._vector(*map(lambda a: EVAL(a, env), ast))
20 elif types._hash_map_Q(ast):
21 keyvals = []
22 for k in ast.keys():
23 keyvals.append(EVAL(k, env))
24 keyvals.append(EVAL(ast[k], env))
25 return types._hash_map(*keyvals)
26 else:
27 return ast # primitive value, return unchanged
28
29 def EVAL(ast, env):
30 while True:
31 #print("EVAL %s" % printer._pr_str(ast))
32 if not types._list_Q(ast):
33 return eval_ast(ast, env)
34
35 # apply list
36 if len(ast) == 0: return ast
37 a0 = ast[0]
38
39 if "def!" == a0:
40 a1, a2 = ast[1], ast[2]
41 res = EVAL(a2, env)
42 return env.set(a1, res)
43 elif "let*" == a0:
44 a1, a2 = ast[1], ast[2]
45 let_env = Env(env)
46 for i in range(0, len(a1), 2):
47 let_env.set(a1[i], EVAL(a1[i+1], let_env))
48 ast = a2
49 env = let_env
50 # Continue loop (TCO)
51 elif "do" == a0:
52 eval_ast(ast[1:-1], env)
53 ast = ast[-1]
54 # Continue loop (TCO)
55 elif "if" == a0:
56 a1, a2 = ast[1], ast[2]
57 cond = EVAL(a1, env)
58 if cond is None or cond is False:
59 if len(ast) > 3: ast = ast[3]
60 else: ast = None
61 else:
62 ast = a2
63 # Continue loop (TCO)
64 elif "fn*" == a0:
65 a1, a2 = ast[1], ast[2]
66 return types._function(EVAL, Env, a2, env, a1)
67 else:
68 el = eval_ast(ast, env)
69 f = el[0]
70 if hasattr(f, '__ast__'):
71 ast = f.__ast__
72 env = f.__gen_env__(el[1:])
73 else:
74 return f(*el[1:])
75
76 # print
77 def PRINT(exp):
78 return printer._pr_str(exp)
79
80 # repl
81 repl_env = Env()
82 def REP(str):
83 return PRINT(EVAL(READ(str), repl_env))
84
85 # core.py: defined using python
86 for k, v in core.ns.items(): repl_env.set(types._symbol(k), v)
87 repl_env.set(types._symbol('eval'), lambda ast: EVAL(ast, repl_env))
88 repl_env.set(types._symbol('*ARGV*'), types._list(*sys.argv[2:]))
89
90 # core.mal: defined using the language itself
91 REP("(def! not (fn* (a) (if a false true)))")
92 REP("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))")
93
94 if len(sys.argv) >= 2:
95 REP('(load-file "' + sys.argv[1] + '")')
96 sys.exit(0)
97
98 # repl loop
99 while True:
100 try:
101 line = mal_readline.readline("user> ")
102 if line == None: break
103 if line == "": continue
104 print(REP(line))
105 except reader.Blank: continue
106 except Exception as e:
107 print("".join(traceback.format_exception(*sys.exc_info())))