mirror of
https://github.com/kanaka/mal.git
synced 2024-11-14 00:09:01 +03:00
87 lines
2.8 KiB
Plaintext
87 lines
2.8 KiB
Plaintext
--- step6_file ----------------------------------
|
|
import types, reader, printer, env, core
|
|
|
|
READ(str): return reader.read_str(str)
|
|
|
|
eval_ast(ast,env):
|
|
switch type(ast):
|
|
symbol: return env.get(ast)
|
|
list,vector: return ast.map((x) -> EVAL(x,env))
|
|
hash: return ast.map((k,v) -> list(k, EVAL(v,env)))
|
|
_default_: return ast
|
|
|
|
EVAL(ast,env):
|
|
while true:
|
|
if not list?(ast): return eval_ast(ast, env)
|
|
if empty?(ast): return ast
|
|
switch ast[0]:
|
|
'def!: return env.set(ast[1], EVAL(ast[2], env))
|
|
'let*: env = ...; ast = ast[2] // TCO
|
|
'do: ast = eval_ast(ast[1..-1], env)[-1] // TCO
|
|
'if: EVAL(ast[1], env) ? ast = ast[2] : ast = ast[3] // TCO
|
|
'fn*: return new MalFunc(...)
|
|
_default_: f, args = eval_ast(ast, env)
|
|
if malfunc?(f): ast = f.fn; env = ... // TCO
|
|
else: return apply(f, args)
|
|
|
|
PRINT(exp): return printer.pr_str(exp)
|
|
|
|
repl_env = new Env()
|
|
rep(str): return PRINT(EVAL(READ(str),repl_env))
|
|
|
|
;; core.EXT: defined using Racket
|
|
core.ns.map((k,v) -> (repl_env.set(k, v)))
|
|
repl_env.set('eval, (ast) -> EVAL(ast, repl-env))
|
|
repl_env.set('*ARGV*, cmdline_args[1..])
|
|
|
|
;; core.mal: defined using the language itself
|
|
rep("(def! not (fn* (a) (if a false true)))")
|
|
rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))")
|
|
|
|
if cmdline_args: rep("(load-file \"" + args[0] + "\")"); exit 0
|
|
|
|
main loop:
|
|
try: println(rep(readline("user> ")))
|
|
catch e: println("Error: ", e)
|
|
|
|
--- env module ----------------------------------
|
|
class Env (outer=null,binds=[],exprs=[])
|
|
data = hash_map()
|
|
foreach b, i in binds:
|
|
if binds[i] == '&: data[binds[i+1]] = exprs.drop(i); break
|
|
else: data[binds[i]] = exprs[i]
|
|
set(k,v): return data.set(k,v)
|
|
find(k): return data.has(k) ? this : (if outer ? find(outer) : null)
|
|
get(k): return data.find(k).get(k) OR raise "'" + k + "' not found"
|
|
|
|
--- core module ---------------------------------
|
|
ns = {'=: equal?,
|
|
|
|
'pr-str: (a) -> a.map(|s| pr_str(e,true)).join(" ")),
|
|
'str: (a) -> a.map(|s| pr_str(e,false)).join("")),
|
|
'prn: (a) -> println(a.map(|s| pr_str(e,true)).join(" ")),
|
|
'println: (a) -> println(a.map(|s| pr_str(e,false)).join(" ")),
|
|
'read-string: read_str,
|
|
'slurp read-file,
|
|
|
|
'<: lt,
|
|
'<=: lte,
|
|
'>: gt,
|
|
'>=: gte,
|
|
'+: add,
|
|
'-: sub,
|
|
'*: mult,
|
|
'/: div,
|
|
|
|
'list: list,
|
|
'list?: list?,
|
|
|
|
'empty?: empty?,
|
|
'count: count,
|
|
|
|
'atom: (a) -> new Atom(a[0]),
|
|
'atom?: (a) -> type(a[0]) == "atom",
|
|
'deref: (a) -> a[0].val,
|
|
'reset!: (a) -> a[0].val = a[1],
|
|
'swap!: swap!}
|