Skip to content

Instantly share code, notes, and snippets.

@track8
Last active June 6, 2018 11:08
Show Gist options
  • Save track8/731bac732ac096a8ac256f1258bae282 to your computer and use it in GitHub Desktop.
Save track8/731bac732ac096a8ac256f1258bae282 to your computer and use it in GitHub Desktop.
require './minruby'
def evaluate(tree, genv, lenv)
case tree[0]
when 'lit'
tree[1]
when '+'
lenv['plus_count'] ||= 0
lenv['plus_count'] += 1
left = evaluate(tree[1], genv, lenv)
right = evaluate(tree[2], genv, lenv)
left + right
when '-'
left = evaluate(tree[1], genv, lenv)
right = evaluate(tree[2], genv, lenv)
left - right
when '*'
left = evaluate(tree[1], genv, lenv)
right = evaluate(tree[2], genv, lenv)
left * right
when '/'
left = evaluate(tree[1], genv, lenv)
right = evaluate(tree[2], genv, lenv)
left / right
when '%'
left = evaluate(tree[1], genv, lenv)
right = evaluate(tree[2], genv, lenv)
left % right
when '**'
left = evaluate(tree[1], genv, lenv)
right = evaluate(tree[2], genv, lenv)
left ** right
when '=='
left = evaluate(tree[1], genv, lenv)
right = evaluate(tree[2], genv, lenv)
left == right
when '<'
left = evaluate(tree[1], genv, lenv)
right = evaluate(tree[2], genv, lenv)
left < right
when '>'
left = evaluate(tree[1], genv, lenv)
right = evaluate(tree[2], genv, lenv)
left > right
when '<='
left = evaluate(tree[1], genv, lenv)
right = evaluate(tree[2], genv, lenv)
left <= right
when '>='
left = evaluate(tree[1], genv, lenv)
right = evaluate(tree[2], genv, lenv)
left >= right
when 'func_def'
genv[tree[1]] = ['user_defined', tree[2], tree[3]]
when 'func_call'
args = []
i = 0
while tree[i + 2]
args[i] = evaluate(tree[i + 2], genv, lenv)
i = i + 1
end
mhd = genv[tree[1]]
if mhd[0] == "buildin"
minruby_call(mhd[1], args)
else
new_lenv = {}
params = mhd[1]
i = 0
while params[i]
new_lenv[params[i]] = args[i]
i = i + 1
end
evaluate(mhd[2], genv, new_lenv)
end
when 'stmts'
i = 1
last = nil
while tree[i]
last = evaluate(tree[i], genv, lenv)
i = i + 1
end
last
when 'var_assign'
lenv[tree[1]] = evaluate(tree[2], genv, lenv)
when 'var_ref'
lenv[tree[1]]
when "if"
if evaluate(tree[1], genv, lenv)
evaluate(tree[2], genv, lenv)
else
evaluate(tree[3], genv, lenv)
end
when "while"
while evaluate(tree[1], genv, lenv)
evaluate(tree[2], genv, lenv)
end
when "case"
evaluate(tree[1], genv, lenv)
else
pp tree
end
end
def max(tree)
case tree[0]
when 'lit'
tree[1]
else
left = max(tree[1])
right = max(tree[2])
#[left, right].max
left > right ? left : right
end
end
str = minruby_load
tree = minruby_parse(str)
#pp tree
genv = { "p" => ["buildin", "p"],
"pp" => ["buildin", "pp"] }
lenv = {}
answer = evaluate(tree, genv, lenv)
#p lenv
#p answer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment