git @ Cat's Eye Technologies Strelnokoff / 9d11f6f
It works! And still under 500 lines of code. Chris Pressey 1 year, 6 months ago
1 changed file(s) with 29 addition(s) and 10 deletion(s). Raw diff Collapse all Expand all
366366 local evaluate
367367 evaluate = function(ast)
368368 assert(ast ~= nil, "ast is nil")
369 debug("eval", ast.tag)
370 AST.case(ast, {
369 debug("eval", render(ast))
370 local result = AST.case(ast, {
371371 program = function(assignments)
372 local index = math.random(1, #assignments)
373 debug("eval", "program: chose " .. tostring(index))
374 return evaluate(assignments[index])
372 local index, result
373 local done = false
374 while not done do
375 index = math.random(1, #assignments)
376 debug("eval", "program: chose " .. tostring(index))
377 result = evaluate(assignments[index])
378 -- TODO: how do we tell when we're done?
379 end
375380 end,
376381 assignment = function(varname, varindex, expr)
377382 debug("eval", "assignment: " .. varname .. " = " .. render(expr))
393398 elseif op == "*" then
394399 lval = evaluate(lhs)
395400 -- short-circuiting multiplication
396 if not lval then
401 if lval == 0 then
397402 return 0
398403 else
399404 rval = evaluate(rhs)
402407 elseif op == "/" then
403408 lval = evaluate(lhs)
404409 rval = evaluate(rhs)
405 if not rval then
410 if rval == 0 then
406411 return 0
407412 else
408413 return lval // rval
415420 else
416421 return 0
417422 end
423 elseif op == ">" then
424 lval = evaluate(lhs)
425 rval = evaluate(rhs)
426 if lval > rval then
427 return 1
428 else
429 return 0
430 end
418431 else
419432 error("Not implemented BinOp: " .. op)
420433 end
423436 debug("eval", "action: " .. action .. " " .. mode .. " " .. render(expr))
424437 local r
425438 local val = evaluate(expr)
426 if mode == "char" then r = chr(val) else r = tostring(val) end
427 io:write(r)
439 if mode == "char" then r = string.char(val) else r = tostring(val) end
440 io.stdout:write(r)
441 io.stdout:flush()
442 return val
428443 end,
429444 literal = function(val)
430445 return val
431446 end,
432447 varaccess = function(varname, varindex)
433 debug("eval", "varaccess: " .. varname)
448 debug("eval", "varaccess: " .. varname .. " is " .. tostring(store[varname]))
434449 if not store[varname] then
435450 store[varname] = 0
436451 end
452 debug("eval", "varaccess: " .. varname .. " is " .. tostring(store[varname]))
437453 return store[varname]
438454 end,
439455 })
456 assert(result ~= nil, "result of evaluating " .. render(ast) .. " was nil")
457 return result
440458 end
441459
442460 --
455473 --
456474
457475 function main(arg)
476 math.randomseed(os.time())
458477 local filename
459478 while #arg > 0 do
460479 if arg[1] == "--debug" then