/**
 * 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 = true)
{
	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, "@val", e.pos);
	}
	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);
		ctx.set(e.var, "@val", 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_nothrow( evalString(`print("Hello, world!");`) );
	assert_nothrow( evalString(`print(fun(){});`) );
}
unittest
{
	assert_nothrow( evalString(`var fac = fun(x){
		1;
	};
	print(fac(3));`));
	assert_nothrow( evalString(`var fac = fun(x){
		if(x)
			{ x*fac(x-1); }
		else
			{ 1; };
	};
	print(fac(10));`));
	assert_nothrow( evalString(`var fib = fun(x){
		if(x<2)
			{ 1; }
		else
			{ fib(x-1) + fib(x-2); };
	};
	print(fib(10));`));
}
