/* Tuplr: A programming language
 * Copyright (C) 2008-2009 David Robillard <dave@drobilla.net>
 *
 * Tuplr is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 *
 * Tuplr is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General
 * Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Tuplr.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @file
 * @brief Compile all code (compilation pass 2)
 */

#include "tuplr.hpp"

using namespace std;

#define COMPILE_LITERAL(CT) \
template<> CVal ALiteral<CT>::compile(CEnv& cenv) { \
	return cenv.engine()->compileLiteral(cenv, this); \
}
COMPILE_LITERAL(int32_t);
COMPILE_LITERAL(float);
COMPILE_LITERAL(bool);

CVal
ASymbol::compile(CEnv& cenv)
{
	return *cenv.vals.ref(this);
}

CVal
AFn::compile(CEnv& cenv)
{
	return impls.find(cenv.type(this));
}

CVal
ACall::compile(CEnv& cenv)
{
	AFn* c = cenv.tenv.resolve(at(0))->to<AFn*>();

	if (!c) return NULL; // Primitive

	AType protT(loc);
	for (size_t i = 1; i < size(); ++i)
		protT.push_back(cenv.type(at(i)));

	TEnv::GenericTypes::const_iterator gt = cenv.tenv.genericTypes.find(c);
	assert(gt != cenv.tenv.genericTypes.end());
	AType fnT(loc);
	fnT.push_back(cenv.penv.sym("Fn"));
	fnT.push_back(&protT);
	fnT.push_back(cenv.type(this));

	CFunc f = c->impls.find(&fnT);
	THROW_IF(!f, loc, (format("callee failed to compile for type %1%") % fnT.str()).str());

	vector<CVal> args(size() - 1);
	for (size_t i = 0; i < args.size(); ++i)
		args[i] = at(i + 1)->compile(cenv);

	return cenv.engine()->compileCall(cenv, f, args);
}

CVal
ADef::compile(CEnv& cenv)
{
	// Define stub first for recursion
	cenv.def(sym(), at(2), cenv.type(at(2)), NULL);
	CVal val = at(size() - 1)->compile(cenv);
	cenv.vals.def(sym(), val);
	return val;
}

CVal
AIf::compile(CEnv& cenv)
{
	return cenv.engine()->compileIf(cenv, this);
}

CVal
APrimitive::compile(CEnv& cenv)
{
	return cenv.engine()->compilePrimitive(cenv, this);
}