Artifact Content
Not logged in

Artifact a16d8d322739557e45d8afeb380a9932890d88c3


/**
 * 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("+", "@v", new FunValue(delegate Value(immutable LexPosition pos, Layer lay, Value[] args){
		if( args.length != 2 )
			throw genex!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 genex!RuntimeException(pos, "cannot add non-integers");
	}));
	ctx.set("-", "@v", new FunValue(delegate Value(immutable LexPosition pos, Layer lay, Value[] args){
		if( args.length != 2 )
			throw genex!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 genex!RuntimeException(pos, "cannot subtract non-integers");
	}));
	ctx.set("*", "@v", new FunValue(delegate Value(immutable LexPosition pos, Layer lay, Value[] args){
		if( args.length != 2 )
			throw genex!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 genex!RuntimeException(pos, "cannot multiply non-integers");
	}));
	ctx.set("/", "@v", new FunValue(delegate Value(immutable LexPosition pos, Layer lay, Value[] args){
		if( args.length != 2 )
			throw genex!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 genex!RuntimeException(pos, "cannot divide non-integers");
	}));
	ctx.set("<", "@v", new FunValue(delegate Value(immutable LexPosition pos, Layer lay, Value[] args){
		if( args.length != 2 )
			throw genex!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 genex!RuntimeException(pos, "cannot compare non-integers");
	}));
	ctx.set(">", "@v", new FunValue(delegate Value(immutable LexPosition pos, Layer lay, Value[] args){
		if( args.length != 2 )
			throw genex!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 genex!RuntimeException(pos, "cannot compare non-integers");
	}));
	ctx.set("print", "@v", new FunValue(delegate Value(immutable LexPosition pos, Layer lay, Value[] args){
		foreach(a; args)
			write(a);
		writeln("");
		return new IntValue(BigInt(178));
	}));
	ctx.set("if", "@v", new FunValue(delegate Value(immutable LexPosition pos, Layer lay, Value[] args){
		if( args.length != 3 )
			throw genex!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,lay,[]);
		throw genex!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) );
}

/// Entry point of this module

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

/// Entry point of this module

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

/// Entry point of this module
/// If splitCtx = true, then inner variable declaration do not overwrite ctx.
/// lay is the layer ID for evaluation (standard value semantics uses "@v").
import std.typetuple;
Value eval(AST e, Table ctx, bool splitCtx, Layer lay)
{
	return e.match(
		(StrLiteral e)
		{
			return new StrValue(e.data);
		},
		(IntLiteral e)
		{
			return new IntValue(e.data);
		},
		(VarExpression e)
		{
			return ctx.get(e.var, lay, e.pos);
		},
		(LayeredExpression e)
		{
			return eval(e.expr, ctx, false, e.lay);
		},
		(LetExpression e)
		{
			// for letrec, we need this, but should avoid overwriting????
			// ctx.set(e.var, "@v", new UndefinedValue, e.pos);
			Value v = eval(e.init, ctx, true, lay);
			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, false, lay);
		},
		(FuncallExpression e)
		{
			Value _f = eval(e.fun, ctx, true, lay);
			if( auto f = cast(FunValue)_f ) {
				Value[] args;
				foreach(a; e.args)
					args ~= eval(a, ctx, true, lay);
				return f.call(e.pos, lay, args);
			}
			throw genex!RuntimeException(e.pos, "Non-funcion is applied");
		},
		(FunLiteral e)
		{
			return new FunValue(delegate Value(immutable LexPosition pos, string lay, Value[] args){
				if( e.params.length != args.length )
					throw genex!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.name, lay, args[i]);
				return eval(e.funbody, ctxNeo, true, lay);
			});
		},
		delegate Value (AST e)
		{
			throw genex!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","@v"), new IntValue(BigInt(21)) );
	assert_nothrow( r.ctx.get("x","@v") );
	assert_throw!RuntimeException( r.ctx.get("y","@v") );
}
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","@v"), new IntValue(BigInt(21+21*21)) );
	assert_nothrow( r.ctx.get("x","@v") );
	assert_throw!RuntimeException( r.ctx.get("y","@v") );
}
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)));
}

unittest
{
	assert_throw!Throwable( evalString(`@s "+"=fun(x,y){x-y};@s(1+2)`) );
	assert_eq( evalString(`@s "+"=fun(x,y){x-y};1+2`).val, new IntValue(BigInt(3)) );
	assert_eq( evalString(`@s "+"=fun(x,y){@v(@s(x)-@s(y))};1+2`).val, new IntValue(BigInt(3)) );
	assert_eq( evalString(`@s "+"=fun(x,y){@v(@s(x)-@s(y))};@s(1+2)`).val, new IntValue(BigInt(-1)) );
}