//
// 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 : Tue Jul 12 17:21:02 2016
// Update Count     : 133
//

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

#include "ParseNode.h"
#include "SynTree/Statement.h"
#include "SynTree/Expression.h"
#include "parseutility.h"
#include "Common/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( const 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 );
			} // if
		} else {
			if ( decl->get_link() ) {
				next = new StatementNode( dynamic_cast< DeclarationNode* >( decl->get_link() ) );
				decl->set_next( 0 );
			} // if
			this->decl = decl;
		} // if
	} // if
}

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

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 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;
	} // if
	newnode->decl = maybeClone( decl );
	return newnode;
}

StatementNode *StatementNode::add_label( const std::string *l ) {
	if ( l != 0 ) {
		labels.push_front( *l );
		delete l;
	} // if
	return this;
}

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 );
	} // if
	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 );
	} // if
	return this;
}

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

		os << string( indent, ' ' );
		for ( i = labels.begin(); i != labels.end(); i++ )
			os << *i << ":";
		os << endl;
	} // if

	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 << string( indent, ' ' ) << StatementNode::StType[type] << endl;
		if ( type == Catch ) {
			if ( decl ) {
				os << string( indent + ParseNode::indent_by, ' ' ) << "Declaration: " << endl;
				decl->print( os, indent + 2 * ParseNode::indent_by );
			} else if ( isCatchRest ) {
				os << string( indent + ParseNode::indent_by, ' ' ) << "Catches the rest " << endl;
			} else {
				; // should never reach here
			} // if
		} // if
		if ( control ) {
			os << string( indent + ParseNode::indent_by, ' ' ) << "Control: " << endl;
			control->printList( os, indent + 2 * ParseNode::indent_by );
		} // if
		if ( block ) {
			os << string( indent + ParseNode::indent_by, ' ' ) << "Branches of execution: " << endl;
			block->printList( os, indent + 2 * ParseNode::indent_by );
		} // if
		if ( target ) {
			os << string( indent + ParseNode::indent_by, ' ' ) << "Target: " << get_target() << endl;
		} // if
		break;
	} // switch
}

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

	if ( ! labels.empty() ) {
		std::back_insert_iterator< std::list<Label> > lab_it( labs );
		copy( labels.begin(), labels.end(), lab_it );
	} // if

	// 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();
			} // if
			return new IfStmt( labs, notZeroExpr( maybeBuild<Expression>(get_control()) ), thenb, elseb );
		}
	  case While:
		assert( branches.size() == 1 );
		return new WhileStmt( labs, notZeroExpr( maybeBuild<Expression>(get_control()) ), branches.front() );
	  case Do:
		assert( branches.size() == 1 );
		return new WhileStmt( labs, notZeroExpr( maybeBuild<Expression>(get_control()) ), branches.front(), true );
	  case For:
		{
			assert( branches.size() == 1 );

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

			std::list<Statement *> init;
			if ( ctl->get_init() != 0 ) {
				buildList( ctl->get_init(), init );
			} // if

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

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

			return new ForStmt( labs, init, cond, incr, branches.front() );
		}
	  case Switch:
		return new SwitchStmt( labs, maybeBuild<Expression>(get_control()), branches );
	  case Case:
		return new CaseStmt( labs, maybeBuild<Expression>(get_control()), 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, maybeBuild<Expression>(get_control()), BranchStmt::Goto );
			} // if

			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();
			} // if
			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 );
		}
	  case Asm:
		assert( false );
	  default:
		// shouldn't be here
		return 0;
	} // switch
}


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

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

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

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

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

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

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

	if ( ! labels.empty() ) {
		std::back_insert_iterator< std::list<Label> > lab_it( labs );
		copy( labels.begin(), labels.end(), lab_it );
	} // if

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


AsmStmtNode::AsmStmtNode( Type t, bool voltile, ConstantNode *instruction, ExpressionNode *output, ExpressionNode *input, ConstantNode *clobber, LabelNode *gotolabels ) :
	StatementNode( t ), voltile( voltile ), instruction( instruction ), output( output ), input( input ), clobber( clobber ) {
	if ( gotolabels ) {
		this->gotolabels = gotolabels->get_labels();
		delete gotolabels;
	} // if
}

AsmStmtNode::~AsmStmtNode() {
	delete instruction; delete output; delete input; delete clobber;
}

void AsmStmtNode::print( std::ostream &os, int indent ) const {
	StatementNode::print( os, indent );					// print statement labels
	os << string( indent + ParseNode::indent_by, ' ' ) << "volatile:" << voltile << endl;
	if ( instruction ) {
		os << string( indent + ParseNode::indent_by, ' ' ) << "Instruction:" << endl;
		instruction->printList( os, indent + 2 * ParseNode::indent_by );
	} // if
	if ( output ) {
		os << string( indent + ParseNode::indent_by, ' ' ) << "Output:" << endl;
		output->printList( os, indent + 2 * ParseNode::indent_by );
	} // if
	if ( input ) {
		os << string( indent + ParseNode::indent_by, ' ' ) << "Input:" << endl;
		input->printList( os, indent + 2 * ParseNode::indent_by );
	} // if
	if ( clobber ) {
		os << string( indent + ParseNode::indent_by, ' ' ) << "Clobber:" << endl;
		clobber->printList( os, indent + 2 * ParseNode::indent_by );
	} // if
	if ( ! gotolabels.empty() ) {
		os << string( indent + ParseNode::indent_by, ' ' ) << "Goto Labels:" << endl;
		os << string( indent + 2 * ParseNode::indent_by, ' ' );
		for ( std::list<Label>::const_iterator i = gotolabels.begin();; ) {
			os << *i;
			i++;
		  if ( i == gotolabels.end() ) break;
			os << ", ";
		}
		os << endl;
	} // if
}

Statement *AsmStmtNode::build() const {
	std::list<Label> labs;

	if ( ! get_labels().empty() ) {
		std::back_insert_iterator< std::list<Label> > lab_it( labs );
		copy( get_labels().begin(), get_labels().end(), lab_it );
	} // if

	std::list< Expression * > out, in;
	std::list< ConstantExpr * > clob;
	buildList( output, out );
	buildList( input, in );
	buildList( clobber, clob );
	std::list< Label > gotolabs = gotolabels;
	return new AsmStmt( labs, voltile, (ConstantExpr *)maybeBuild< Expression >( instruction ), out, in, clob, gotolabs );
}


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

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

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