//
// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
//
// The contents of this file are covered under the licence agreement in the
// file "LICENCE" distributed with Cforall.
//
// StatementNode.cc -- 
//
// Author           : Rodolfo G. Esteves
// Created On       : Sat May 16 14:59:41 2015
// Last Modified By : Peter A. Buhr
// Last Modified On : Sat May 16 15:10:45 2015
// Update Count     : 7
//

#include <list>
#include <algorithm>
#include <cassert>

#include "ParseNode.h"
#include "SynTree/Statement.h"
#include "SynTree/Expression.h"
#include "parseutility.h"
#include "utility.h"

using namespace std;

const char *StatementNode::StType[] = {
	"Exp",   "If",       "Switch", "Case",    "Default",  "Choose",   "Fallthru", 
	"While", "Do",       "For", 
	"Goto",  "Continue", "Break",  "Return",  "Throw",
	"Try",   "Catch",    "Finally", "Asm",
	"Decl"
};

StatementNode::StatementNode() : ParseNode(), control( 0 ), block( 0 ), labels( 0 ), target( 0 ), decl( 0 ), isCatchRest ( false ) {}

StatementNode::StatementNode( string name_) : ParseNode( name_), control( 0 ), block( 0 ), labels( 0 ), target( 0 ), decl( 0 ), isCatchRest ( false ) {}

StatementNode::StatementNode( DeclarationNode *decl ) : type( Decl ), control( 0 ), block( 0 ), labels( 0 ), target( 0 ), isCatchRest ( false ) {
	if ( decl ) {
		if ( DeclarationNode *agg = decl->extractAggregate() ) {
			this->decl = agg;
			StatementNode *nextStmt = new StatementNode;
			nextStmt->type = Decl;
			nextStmt->decl = decl;
			next = nextStmt;
			if ( decl->get_link() ) {
				next->set_next( new StatementNode( dynamic_cast< DeclarationNode* >( decl->get_link() ) ) );
				decl->set_next( 0 );
			}
		} else {
			if ( decl->get_link() ) {
				next = new StatementNode( dynamic_cast< DeclarationNode* >( decl->get_link() ) );
				decl->set_next( 0 );
			}
			this->decl = decl;
		}
	}
}

StatementNode::StatementNode( Type t, ExpressionNode *ctrl_label, StatementNode *block_ ) :
		type( t ), control( ctrl_label ), block( block_), labels( 0 ), target( 0 ), decl( 0 ), isCatchRest ( false ) {
	if ( t == Default )
		control = 0;
} 

StatementNode::StatementNode( Type t, string *_target ) :
		type( t ), control( 0 ), block( 0 ),   labels( 0 ), target(_target ), decl( 0 ), isCatchRest ( false ) {}

StatementNode::~StatementNode() {
	delete control;
	delete block;
	delete labels;
	delete target;
	delete decl;
}

StatementNode * StatementNode::newCatchStmt( DeclarationNode *d, StatementNode *s, bool catchRestP ) {
	StatementNode *ret = new StatementNode( StatementNode::Catch, 0, s ); 
	ret->addDeclaration( d );
	ret->setCatchRest( catchRestP );

	return ret;
}

std::string StatementNode::get_target() const{
	if ( target )
		return *target;

	return string("");
}

StatementNode * StatementNode::clone() const {
	StatementNode *newnode = new StatementNode( type, maybeClone( control ), maybeClone( block ) );
	if ( target ) {
		newnode->target = new string( *target );
	} else {
		newnode->target = 0;
	}
	newnode->decl = maybeClone( decl );
	return newnode;
}

void StatementNode::set_control( ExpressionNode *c ) {
	control = c;
}

StatementNode * StatementNode::set_block( StatementNode *b ) {
	block = b;

	return this;
}

ExpressionNode *StatementNode::get_control() const {
	return control;
}

StatementNode *StatementNode::get_block() const {
	return block;
}

StatementNode::Type StatementNode::get_type() const {
	return type;
}

StatementNode *StatementNode::add_label( std::string *l ) {
	if ( l != 0 ) {
		if ( labels == 0 )
			labels = new std::list<std::string>();

		labels->push_front(*l ); 
		delete l;
	}
	return this;
}

std::list<std::string> *StatementNode::get_labels() const { return labels; }

StatementNode *StatementNode::add_controlexp( ExpressionNode *e ) {
	if ( control && e )
		control->add_to_list( e ); // xxx - check this

	return this;
}

StatementNode *StatementNode::append_block( StatementNode *stmt ) {
	if ( stmt != 0 ) {
		if ( block == 0 )
			block = stmt;
		else
			block->set_link( stmt );
	}
	return this;
}

StatementNode *StatementNode::append_last_case( StatementNode *stmt ) {
	if ( stmt != 0 ) {
		StatementNode *next = ( StatementNode *)get_link();
		if ( next && ( next->get_type() == StatementNode::Case || next->get_type() == StatementNode::Default ) )
			next->append_last_case ( stmt );
		else
			if ( block == 0 )
				block = stmt;
			else
				block->set_link( stmt );
	}
	return this;
}

void StatementNode::print( std::ostream &os, int indent ) const {
	if ( labels != 0 )
		if ( ! labels->empty()) {
			std::list<std::string>::const_iterator i;

			os << '\r' << string( indent, ' ');
			for ( i = labels->begin(); i != labels->end(); i++ )
				os << *i << ":";
			os << endl;
		}

	switch ( type ) {
	  case Decl:
		decl->print( os, indent );
		break;
	  case Exp:
		if ( control ) {
			os << string( indent, ' ' );
			control->print( os, indent );
			os << endl;
		} else 
			os << string( indent, ' ' ) << "Null Statement" << endl;
		break;
	  default:
		os << '\r' << string( indent, ' ') << StatementNode::StType[type] << endl;
		if ( type == Catch ) {
			if ( decl ) {
				os << '\r' << string( indent + ParseNode::indent_by, ' ' ) << "Declaration: " << endl;
				decl->print( os, indent + 2*ParseNode::indent_by );
			} else if ( isCatchRest ) {
				os << '\r' << string( indent + ParseNode::indent_by, ' ' ) << "Catches the rest " << endl;
			} else {
				; // should never reach here
			}
		}
		if ( control ) {
			os << '\r' << string( indent + ParseNode::indent_by, ' ' ) << "Expression: " << endl;
			control->printList( os, indent + 2*ParseNode::indent_by );
		}
		if ( block ) {
			os << '\r' << string( indent + ParseNode::indent_by, ' ' ) << "Branches of execution: " << endl;
			block->printList( os, indent + 2*ParseNode::indent_by );  
		}
		if ( target ) {
			os << '\r' << string( indent + ParseNode::indent_by, ' ' ) << "Target: " << get_target() << endl;
		}
		break;
	}
}

Statement *StatementNode::build() const {
	std::list<Statement *> branches;
	std::list<Expression *> exps;
	std::list<Label> labs;

	if ( labels != 0 ) {
		std::back_insert_iterator< std::list<Label> > lab_it( labs );
		copy( labels->begin(), labels->end(), lab_it );
	}

	// try {
	buildList<Statement, StatementNode>( get_block(), branches );

	switch ( type ) {
	  case Decl:
		return new DeclStmt( labs, maybeBuild< Declaration >( decl ) );
	  case Exp:
		{
			Expression *e = maybeBuild< Expression >( get_control() );

			if ( e )
				return new ExprStmt( labs, e );
			else
				return new NullStmt( labs );
		}
	  case If:
		{
			Statement *thenb = 0, *elseb = 0;
			assert( branches.size() >= 1 );

			thenb = branches.front();
			branches.pop_front();
			if ( ! branches.empty() ) {
				elseb = branches.front();
				branches.pop_front();
			}
			return new IfStmt( labs, notZeroExpr( get_control()->build() ), thenb, elseb );
		}
	  case While:
		assert( branches.size() == 1 );
		return new WhileStmt( labs, notZeroExpr( get_control()->build() ), branches.front() );
	  case Do:
		assert( branches.size() == 1 );
		return new WhileStmt( labs, notZeroExpr( get_control()->build() ), branches.front(), true );
	  case For:
		{
			assert( branches.size() == 1 );

			ForCtlExprNode *ctl = dynamic_cast<ForCtlExprNode *>( get_control() );
			assert( ctl != 0 );

			Statement *stmt = 0;
			if ( ctl->get_init() != 0 )
				stmt = ctl->get_init()->build();

			Expression *cond = 0;
			if ( ctl->get_condition() != 0 )
				cond = notZeroExpr( ctl->get_condition()->build() );

			Expression *incr = 0;
			if ( ctl->get_change() != 0 )
				incr = ctl->get_change()->build();

			return new ForStmt( labs, stmt, cond, incr, branches.front() );
		}
	  case Switch:
		return new SwitchStmt( labs, get_control()->build(), branches );
	  case Choose:
		return new ChooseStmt( labs, get_control()->build(), branches );
	  case Fallthru:
		return new FallthruStmt( labs );
	  case Case: 
		return new CaseStmt( labs, get_control()->build(), branches );
	  case Default:
		return new CaseStmt( labs, 0, branches, true );
	  case Goto:
		{
			if ( get_target() == "" ) {					// computed goto
				assert( get_control() != 0 );
				return new BranchStmt( labs, get_control()->build(), BranchStmt::Goto );
			}

			return new BranchStmt( labs, get_target(), BranchStmt::Goto );
		}
	  case Break:
		return new BranchStmt( labs, get_target(), BranchStmt::Break );
	  case Continue:
		return new BranchStmt( labs, get_target(), BranchStmt::Continue );
	  case Return:
	  case Throw :
		buildList( get_control(), exps );
		if ( exps.size() ==0 )
			return new ReturnStmt( labs, 0, type == Throw );
		if ( exps.size() > 0 )
			return new ReturnStmt( labs, exps.back(), type == Throw );
	  case Try:
		{
			assert( branches.size() >= 0 );
			CompoundStmt *tryBlock = dynamic_cast<CompoundStmt *>( branches.front());
			branches.pop_front();
			FinallyStmt *finallyBlock = 0;
			if ( ( finallyBlock = dynamic_cast<FinallyStmt *>( branches.back())) ) {
				branches.pop_back();
			}
			return new TryStmt( labs, tryBlock, branches, finallyBlock );
		}
	  case Catch:
		{
			assert( branches.size() == 1 );

			return new CatchStmt( labs, maybeBuild< Declaration >( decl ), branches.front(), isCatchRest );
		}
	  case Finally:
		{
			assert( branches.size() == 1 );
			CompoundStmt *block = dynamic_cast<CompoundStmt *>( branches.front() );
			assert( block != 0 );

			return new FinallyStmt( labs, block );
		}
	  default:
		// shouldn't be here
		return 0;
	}
}

CompoundStmtNode::CompoundStmtNode() : first( 0 ), last( 0 ) {
}

CompoundStmtNode::CompoundStmtNode( string *name_) : StatementNode(*name_), first( 0 ), last( 0 ) {
}

CompoundStmtNode::CompoundStmtNode( StatementNode *stmt ): first( stmt ) {
	if ( first ) {
		last = ( StatementNode *)( stmt->get_last());
	} else {
		last = 0;
	}
}

CompoundStmtNode::~CompoundStmtNode() {
	delete first;
}

void CompoundStmtNode::add_statement( StatementNode *stmt ) {
	if ( stmt != 0 ) {
		last->set_link( stmt );
		last = ( StatementNode *)( stmt->get_link());
	}
}

void CompoundStmtNode::print( ostream &os, int indent ) const {
	if ( first ) {
		first->printList( os, indent+2 );
	}
}

Statement *CompoundStmtNode::build() const {
	std::list<Label> labs;
	std::list<std::string> *labels = get_labels();

	if ( labels != 0 ) {
		std::back_insert_iterator< std::list<Label> > lab_it( labs );
		copy( labels->begin(), labels->end(), lab_it );
	}

	CompoundStmt *cs = new CompoundStmt( labs );
	buildList( first, cs->get_kids() );
	return cs;
}

void NullStmtNode::print( ostream &os, int indent ) const {
	os << "\r" << string( indent, ' ') << "Null Statement:" << endl;
}

Statement *NullStmtNode::build() const { 
	return new NullStmt;
}

// Local Variables: //
// tab-width: 4 //
// mode: c++ //
// compile-command: "make install" //
// End: //
