Artifact Content
Not logged in

Artifact 62b3543f769fc9c997f7d8825040e9b312009566


/**
 * Authors: k.inaba
 * License: NYSL 0.9982 http://www.kmonos.net/nysl/
 *
 * Evaluator for Polemy programming language.
 */
module polemy.eval;
import polemy._common;
import polemy.lex : LexPosition;
import polemy.ast;
import polemy.parse;
import polemy.value;
import std.typecons;
import std.stdio;

Table createGlobalContext()
{
	auto ctx = new Table;
	// [TODO] autogenerate these typechecks
	ctx.set("+", "@val", new FunValue(delegate Value(immutable LexPosition pos, Value[] args){
		if( args.length != 2 )
			throw new RuntimeException(pos, "+ takes two arguments!!");
		if( auto x = cast(IntValue)args[0] )
			if( auto y = cast(IntValue)args[1] )
				return new IntValue(x.data+y.data);
		throw new RuntimeException(pos, "cannot add non-integers");
	}));
	ctx.set("-", "@val", new FunValue(delegate Value(immutable LexPosition pos, Value[] args){
		if( args.length != 2 )
			throw new RuntimeException(pos, "- takes two arguments!!");
		if( auto x = cast(IntValue)args[0] )
			if( auto y = cast(IntValue)args[1] )
				return new IntValue(x.data-y.data);
		throw new RuntimeException(pos, "cannot subtract non-integers");
	}));
	ctx.set("*", "@val", new FunValue(delegate Value(immutable LexPosition pos, Value[] args){
		if( args.length != 2 )
			throw new RuntimeException(pos, "* takes two arguments!!");
		if( auto x = cast(IntValue)args[0] )
			if( auto y = cast(IntValue)args[1] )
				return new IntValue(x.data*y.data);
		throw new RuntimeException(pos, "cannot multiply non-integers");
	}));
	ctx.set("/", "@val", new FunValue(delegate Value(immutable LexPosition pos, Value[] args){
		if( args.length != 2 )
			throw new RuntimeException(pos, "/ takes two arguments!!");
		if( auto x = cast(IntValue)args[0] )
			if( auto y = cast(IntValue)args[1] )
				return new IntValue(x.data/y.data);
		throw new RuntimeException(pos, "cannot divide non-integers");
	}));
	ctx.set("<", "@val", new FunValue(delegate Value(immutable LexPosition pos, Value[] args){
		if( args.length != 2 )
			throw new RuntimeException(pos, "< takes two arguments!!");
		if( auto x = cast(IntValue)args[0] )
			if( auto y = cast(IntValue)args[1] )
				return new IntValue(BigInt(to!int(x.data < y.data)));
		throw new RuntimeException(pos, "cannot compare non-integers");
	}));
	ctx.set(">", "@val", new FunValue(delegate Value(immutable LexPosition pos, Value[] args){
		if( args.length != 2 )
			throw new RuntimeException(pos, "> takes two arguments!!");
		if( auto x = cast(IntValue)args[0] )
			if( auto y = cast(IntValue)args[1] )
				return new IntValue(BigInt(to!int(x.data>y.data)));
		throw new RuntimeException(pos, "cannot compare non-integers");
	}));
	ctx.set("print", "@val", new FunValue(delegate Value(immutable LexPosition pos, Value[] args){
		foreach(a; args)
			write(a);
		writeln("");
		return new IntValue(BigInt(178));
	}));
	ctx.set("if", "@val", new FunValue(delegate Value(immutable LexPosition pos, Value[] args){
		if( args.length != 3 )
			throw new RuntimeException(pos, "if takes three arguments!!");
		if( auto x = cast(IntValue)args[0] )
		if( auto ft = cast(FunValue)args[1] )
		if( auto fe = cast(FunValue)args[2] )
			return (x.data == 0 ? fe : ft).call(pos,[]);
		throw new RuntimeException(pos, "type mismatch in if");
	}));
	return ctx;
}

/// Entry point of this module

Tuple!(Value,"val",Table,"ctx") evalString(S,T...)(S str, T fn_ln_cn)
{
	return eval( polemy.parse.parseString(str, fn_ln_cn) );
}

Tuple!(Value,"val",Table,"ctx") evalFile(S, T...)(S filename, T ln_cn)
{
	return eval( polemy.parse.parseFile(filename, ln_cn) );
}

Tuple!(Value,"val",Table,"ctx") eval(AST e)
{
	Table ctx = createGlobalContext();
	return typeof(return)(eval(e, ctx), ctx);
}

Value eval(AST _e, Table ctx, bool splitCtx = false, Layer lay="@val")
{
	if( auto e = cast(StrLiteral)_e )
	{
		return new StrValue(e.data);
	}
	else
	if( auto e = cast(IntLiteral)_e )
	{
		return new IntValue(e.data);
	}
	else
	if( auto e = cast(VarExpression)_e )
	{
		return ctx.get(e.var, lay, e.pos);
	}
	else
	if( auto e = cast(LayeredExpression)_e )
	{
		return eval(e.expr, ctx, false, e.lay);
	}
	else
	if( auto e = cast(LetExpression)_e )
	{
		// for letrec, we need this, but should avoid overwriting????
		// ctx.set(e.var, "@val", new UndefinedValue, e.pos);
		Value v = eval(e.init, ctx, true);
		if(splitCtx)
			ctx = new Table(ctx, Table.Kind.NotPropagateSet);
		ctx.set(e.var, (e.layer.length ? e.layer : lay), v, e.pos);
		return eval(e.expr, ctx);
	}
	else
	if( auto e = cast(FuncallExpression)_e )
	{
		Value _f = eval(e.fun, ctx);
		if( auto f = cast(FunValue)_f ) {
			Value[] args;
			foreach(a; e.args)
				args ~= eval(a, ctx);
			return f.call(e.pos, args);
		} else
			throw new RuntimeException(e.pos, "Non-funcion is applied");
	}
	else
	if( auto e = cast(FunLiteral)_e )
	{
		return new FunValue(delegate Value(immutable LexPosition pos, Value[] args){
			if( e.params.length != args.length )
				throw new RuntimeException(e.pos, sprintf!"Argument Number Mismatch (%d required but %d given)"
					(e.params.length, args.length));
			Table ctxNeo = new Table(ctx, Table.Kind.NotPropagateSet);
			foreach(i,p; e.params)
				ctxNeo.set(p, "@val", args[i]);
			return eval(e.funbody, ctxNeo);
		});
	}
	throw new RuntimeException(_e.pos, sprintf!"Unknown Kind of Expression %s"(typeid(_e)));
}

unittest
{
	auto r = assert_nothrow( evalString(`var x = 21; x + x*x;`) );
	assert_eq( r.val, new IntValue(BigInt(21+21*21)) );
	assert_eq( r.ctx.get("x","@val"), new IntValue(BigInt(21)) );
	assert_nothrow( r.ctx.get("x","@val") );
	assert_throw!RuntimeException( r.ctx.get("y","@val") );
}
unittest
{
	auto r = assert_nothrow( evalString(`var x = 21; var x = x + x*x;`) );
	assert_eq( r.val, new IntValue(BigInt(21+21*21)) );
	assert_eq( r.ctx.get("x","@val"), new IntValue(BigInt(21+21*21)) );
	assert_nothrow( r.ctx.get("x","@val") );
	assert_throw!RuntimeException( r.ctx.get("y","@val") );
}
unittest
{
	assert_eq( evalString(`let x=1; let y=(let x=2); x`).val, new IntValue(BigInt(1)) ); 
	assert_eq( evalString(`let x=1; let y=(let x=2;fun(){x}); y()`).val, new IntValue(BigInt(2)) ); 
}
unittest
{
	assert_eq( evalString(`@a x=1; @b x=2; @a(x)`).val, new IntValue(BigInt(1)) );
	assert_eq( evalString(`@a x=1; @b x=2; @b(x)`).val, new IntValue(BigInt(2)) );
	assert_eq( evalString(`let x=1; let _ = (@a x=2;2); x`).val, new IntValue(BigInt(1)) );
	assert_throw!Error( evalString(`let x=1; let _ = (@a x=2;2); @a(x)`) );
}

unittest
{
	assert_eq( evalString(`var fac = fun(x){
		if(x)
			{ x*fac(x-1); }
		else
			{ 1; };
	};
	fac(10);`).val, new IntValue(BigInt(10*9*8*5040)));
	assert_eq( evalString(`var fib = fun(x){
		if(x<2)
			{ 1; }
		else
			{ fib(x-1) + fib(x-2); };
	};
	fib(10);`).val, new IntValue(BigInt(89)));
}