Artifact Content
Not logged in

Artifact bedecb22284cfae99f749134b33261f03f7ca92b


module polemy.eval;
import polemy._common;
/*
 * Author:  k.inaba
 * License: NYSL 0.9982 (http://www.kmonos.net/nysl/
 *   Evaluator for the polemy programming language
 */
import polemy.ast;
import polemy.runtime;

Context eval(Program prog)
{
	return eval(prog, new Context);
}

Context eval(Program prog, Context ctx)
{
	foreach(s; prog)
		ctx = eval(s, ctx);
	return ctx;
}

Context eval(Statement _s, Context ctx)
{
	if( auto s = cast(DeclStatement)_s )
	{
		auto v = eval(s.expr, ctx);
		ctx.add(s.var, v);
		return ctx;
	}
	else
	if( auto s = cast(ExprStatement)_s )
	{
		eval(s.expr, ctx);
		return ctx;
	}
	throw new PolemyRuntimeException(sprintf!"Unknown Kind of Statement %s at [%s]"(typeid(_s), _s.pos));
}

Value eval(Expression _e, Context ctx)
{
	if( auto e = cast(StrLiteralExpression)_e )
	{
		return new StrValue(e.data);
	}
	else
	if( auto e = cast(IntLiteralExpression)_e )
	{
		return new IntValue(e.data);
	}
	else
	if( auto e = cast(VarExpression)_e )
	{
		return ctx[e.var];
	}
	else
	if( auto e = cast(BinOpExpression)_e )
	{
		if( e.op == "=" )
		{
			if( auto ev = cast(VarExpression)e.lhs )
			{
				Value r = eval(e.rhs, ctx);
				ctx[ev.var] = r;
				return r;
			}
			throw new PolemyRuntimeException(sprintf!"Lhs of assignment must be a variable: %s"(e.pos));
		}

		Value l = eval(e.lhs, ctx);
		Value r = eval(e.rhs, ctx);
		if( auto lv = cast(IntValue)l )
			if( auto rv = cast(IntValue)r )
				final switch(e.op)
				{
				case "+": return new IntValue(lv.data+rv.data);
				case "-": return new IntValue(lv.data-rv.data);
				case "*": return new IntValue(lv.data*rv.data);
				case "/": return new IntValue(lv.data/rv.data);
				}
			else
				throw new PolemyRuntimeException(sprintf!"rhs of %s must be an integer but was %s at [%s]"(e.op, typeid(r), e.rhs.pos));
		else
			throw new PolemyRuntimeException(sprintf!"lhs of %s must be an integer but was %s at [%s]"(e.op, typeid(l), e.lhs.pos));
	}
	throw new PolemyRuntimeException(sprintf!"Unknown Kind of Expression %s at [%s]"(typeid(_e), _e.pos));
}


version(unittest) import polemy.parse;
version(unittest) import std.stdio;
version(unittest) import std.exception;
unittest
{
	auto parser = parserFromString(`var x = 21; x = x + x*x;`);
	auto prog = parser.parseProgram();
	auto ctx = eval(prog);
	assert( ctx["x"] == new IntValue(BigInt(21+21*21)) );
	assert( !collectException(ctx["x"]) );
	assert( collectException(ctx["y"]) );
}
unittest
{
	auto parser = parserFromString(`var x = 21; x = x + x*y;`);
	auto prog = parser.parseProgram();
	assert( collectException(eval(prog)) );
}
unittest
{
	auto parser = parserFromString(`var x = 21; y = x + x*x;`);
	auto prog = parser.parseProgram();
	assert( collectException(eval(prog)) );
}