/* $Id$ 
 * 
 * SimplifyExpressions: simplify nested expressions to simple expressions.
 *
 * Copyright (C) 2009 FAUmachine Team <info@faumachine.org>.
 * This program is free software. You can redistribute it and/or modify it
 * under the terms of the GNU General Public License, either version 2 of
 * the License, or (at your option) any later version. See COPYING.
 */

#include "frontend/visitor/SimplifyExpressions.hpp"
#include "frontend/ast/Process.hpp"
#include "frontend/ast/VarAssignStat.hpp"
#include "frontend/ast/FunctionCall.hpp"

namespace ast {

void
SimplifyExpressions::visit(Process &node)
{
	this->simpleSeqs.clear();

	assert(node.seqStats != NULL);
	this->listTraverse(*node.seqStats, this->simpleSeqs);

	/* TODO: pickup new declarations.
	node.declarations->push_back(FIXME);
	*/
}

void
SimplifyExpressions::visit(VarAssignStat &node)
{
	assert(node.source != NULL);
	assert(node.target != NULL);

	node.source->accept(*this);
	this->setNode(node.source);
}

void
SimplifyExpressions::visit(SigAssignStat &node)
{
	// FIXME
}

void
SimplifyExpressions::visit(CondalSigAssign &node)
{
	// must have been replaced already.
	assert(false);
}

void
SimplifyExpressions::visit(FunctionCall &node)
{
	// TODO 
}

void
SimplifyExpressions::setNode(Expression *&e)
{
	if (this->repexp != NULL) {
		e = this->repexp;
		this->repexp = NULL;
	}
}

SimpleName *
SimplifyExpressions::genTemporary(
	SubtypeIndication *type,
	std::string name, 
	const char *suffix
)
{
	if (name == "") {
		name = "tmp";
	}
	if (suffix == NULL) {
		suffix = "";
	}

	name = "__" + name + suffix;
	std::string *namep = new std::string(name);

	VarDeclaration *vd = 
		new VarDeclaration(
			ValDeclaration::MODE_INOUT,
			namep,
			NULL,
			type,
			Location("simplified"));


	std::list<Symbol*> cands = std::list<Symbol*>();
	Symbol *sym = new Symbol(namep, SYMBOL_VARIABLE, NULL, *vd);
	cands.push_back(sym);

	SimpleName *ret = new SimpleName(
				new std::string(name), 
				cands, 
				Location("simplified"));
	return ret;
}


} /* namespace ast */
