/**
 * Authors: k.inaba
 * License: NYSL 0.9982 http://www.kmonos.net/nysl/
 *
 * Convert values between Polemy and D
 */
module polemy.valueconv;
import polemy._common;
import polemy.failure;
import polemy.ast;
import polemy.layer;
import polemy.value;
import std.string;

LexPosition extractPos( Table t )
{
	Layer theLayer = ValueLayer;
	if(auto tt = t.access!Table(theLayer, "pos"))
	{
		auto fn = tt.access!StrValue(theLayer, "filename");
		auto ln = tt.access!IntValue(theLayer, "lineno");
		auto cl = tt.access!IntValue(theLayer, "column");
		if(fn !is null && ln !is null && cl !is null)
			return new LexPosition(fn.data,cast(int)ln.data.toInt,cast(int)cl.data.toInt);
	}
	return null;
}

Value[] tableAsConsList( Layer theLayer, Table t )
{
	Value[] result;
	while(t)
		if(auto v  = t.access!Value(theLayer, "car"))
		{
			result ~= v;
			t = t.access!Table(theLayer, "cdr");
		}
		else
			break;
	return result;
}

AST[] tableToASTList( Layer theLayer, Table t )
{
	AST[] result;
	foreach(v; tableAsConsList(theLayer, t))
		if(auto t = cast(Table)v)
			result ~= tableToAST(theLayer,t);
		else
			throw genex!RuntimeException(cast(LexPosition)null, "Invalid AST (non-table in cons-list)");
	return result;
}

AST tableToAST( Layer theLayer, Value vvvv )
{
	Table t = cast(Table)vvvv;
	if( t is null )
		throw genex!RuntimeException(cast(LexPosition)null, "Invalid AST (not a table)");

	auto nodeType = t.access!StrValue(theLayer, "is");
	if( nodeType is null )
		throw genex!RuntimeException(cast(LexPosition)null, "Invalid AST {is:(not string)}");
	auto pos = extractPos(t);
	switch(nodeType.data)
	{
	case "int":
		if(auto v = t.access!IntValue(theLayer, "data"))
			return new Int(pos, v.data);
		throw genex!RuntimeException(cast(LexPosition)null, `Invalid AST {is:"int", data:(not int)}`);
	case "str":
		if(auto v = t.access!StrValue(theLayer, "data"))
			return new Str(pos, v.data);
		throw genex!RuntimeException(cast(LexPosition)null, `Invalid AST {is:"str", data:(not string)}`);
	case "var":
		if(auto v = t.access!StrValue(theLayer, "name"))
			return new Var(pos, v.data);
		throw genex!RuntimeException(cast(LexPosition)null, `Invalid AST {is:"var", name:(not string)}`);
	case "lay":
		if(auto v = t.access!StrValue(theLayer, "layer"))
			if(auto e = t.access!Table(theLayer, "expr"))
				return new Lay(pos, v.data, tableToAST(theLayer,e));
			else
				throw genex!RuntimeException(cast(LexPosition)null, `Invalid AST {is:"lay", expr:(not table)}`);
		throw genex!RuntimeException(cast(LexPosition)null, `Invalid AST {is:"lay", layer:(not string)}`);
	case "let":
		if(auto n = t.access!StrValue(theLayer, "name"))
		if(auto e = t.access!Table(theLayer, "init"))
		if(auto b = t.access!Table(theLayer, "expr"))
		{
			string nn = n.data;
			auto ee = tableToAST(theLayer, e);
			auto bb = tableToAST(theLayer, b);
			Layer lay="";
			if(auto l = t.access!StrValue(theLayer, "layer"))
				lay = l.data;
			return new Let(pos, nn, lay, ee, bb);
		}
		throw genex!RuntimeException(cast(LexPosition)null, `Invalid AST {is:"let", name:"???", init:"???", expr:"???"}`);
	case "app":
		if(auto f = t.access!Table(theLayer, "fun"))
		if(auto a = t.access!Table(theLayer, "args"))
			return new App(pos, tableToAST(theLayer,f), tableToASTList(theLayer,a));
		throw genex!RuntimeException(cast(LexPosition)null, `Invalid AST {is:"app", fun:???, args:???}`);
	case "fun":
		if(auto p = t.access!Table(theLayer, "params"))
		if(auto b = t.access!Table(theLayer, "funbody"))
		{
			Parameter[] ps;
			foreach(v; tableAsConsList(theLayer, p))
			{
				if(auto tt = cast(Table)v)
				if(auto ss = tt.access!StrValue(theLayer, "name"))
				if(auto ll = tt.access!Table(theLayer, "layers"))
				{
					Layer[] ls;
					foreach(lll; tableAsConsList(theLayer, ll))
						if(auto l = cast(StrValue)lll)
							ls ~= l.data;
						else
							throw genex!RuntimeException(cast(LexPosition)null, sprintf!`Invalid AST {bad fun params %s}`(lll));
					ps ~= new Parameter(ss.data, ls);
					continue;
				}
				else
				{
					Layer[] emp;
					ps ~= new Parameter(ss.data, emp);
					continue;
				}
				throw genex!RuntimeException(cast(LexPosition)null, sprintf!`Invalid AST {bad fun params %s}`(v));
			}
			auto bb = tableToAST(theLayer, b);
			return new Fun(pos,ps,bb);
		}
		throw genex!RuntimeException(cast(LexPosition)null, `Invalid AST {is:"fun", param:???, body:???}`);
	default:
		throw genex!RuntimeException(cast(LexPosition)null, sprintf!`Invalid AST {is: "%s"} unknown`(nodeType.data));
	}
}

/// Cons of two pairs

Table makeCons(Value a, Value d)
{
	Table t = new Table;
	t.set("car", ValueLayer, a);
	t.set("cdr", ValueLayer, d);
	return t;
}

/// Experimental!!! Convert D value (except AST) to  Polemy Value

Value d2polemy(T)(T e)
{
	return ast2table(e, delegate Value(AST){ assert(false); });
}

/// Convert AST to Table so that it can be used in Polemy

Value ast2table(T)(T e, Value delegate(AST) rec)
{
	static if(is(T==BigInt) || isIntegral!(T))
		return new IntValue(e);
	else
	static if(is(Unqual!(T)==string))
		return new StrValue(e);
	else
	static if(is(T S : S[]))
	{
		Table lst = new Table;
		foreach_reverse(a; e)
			static if(is(S : AST))
				lst = makeCons(rec(a), lst);
			else
				lst = makeCons(ast2table(a,rec), lst);
		return lst;
	}
	else
	static if(is(T : AST))
	{
		assert( typeid(e) == typeid(T), text("abstracted: ", typeid(e), " vs ", typeid(T)) );
		auto t = new Table;
		t.set("pos", ValueLayer, ast2table(e.pos,rec));
		t.set("is" , ValueLayer, new StrValue(typeid(e).name.split(".")[$-1].tolower()));
		foreach(i,m; e.tupleof)
			static if(is(typeof(m) : AST))
				t.set(e.tupleof[i].stringof[2..$], ValueLayer, rec(m));
			else
				t.set(e.tupleof[i].stringof[2..$], ValueLayer, ast2table(m,rec));
		return t;
	}
	else
	static if(is(T == class))
	{
		auto t = new Table;
		foreach(i,m; e.tupleof)
			static if(is(typeof(m) : AST))
				t.set(e.tupleof[i].stringof[2..$], ValueLayer, rec(m));
			else
				t.set(e.tupleof[i].stringof[2..$], ValueLayer, ast2table(m,rec));
		return t;
	}
	else
		static assert(false, "unknown type <"~T.stringof~"> during AST encoding");
}
