//
// 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.
//
// MLEMutator.cc --
//
// Author           : Rodolfo G. Esteves
// Created On       : Mon May 18 07:44:20 2015
// Last Modified By : Peter A. Buhr
// Last Modified On : Tue Jul 12 17:36:51 2016
// Update Count     : 197
//

// NOTE: There are two known subtle differences from the code that uC++ generates for the same input
//   -CFA puts the break label inside at the end of a switch, uC++ puts it after
//   -CFA puts the break label after a block, uC++ puts it inside at the end
// It is unclear if these differences are important, but if they are, then the fix would go in this file, since this is
// where these labels are generated.

#include <cassert>
#include <algorithm>

#include "MLEMutator.h"
#include "SynTree/Statement.h"
#include "SynTree/Expression.h"
#include "SynTree/Attribute.h"

namespace ControlStruct {
	MLEMutator::~MLEMutator() {
		delete targetTable;
		targetTable = 0;
	}
	namespace {
		Statement * isLoop( Statement * stmt ) { return dynamic_cast< WhileStmt * >( stmt ) ? stmt : dynamic_cast< ForStmt * >( stmt ) ? stmt : 0; }
	}

	// break labels have to come after the statement they break out of, so mutate a statement, then if they inform us
	// through the breakLabel field tha they need a place to jump to on a break statement, add the break label to the
	// body of statements
	void MLEMutator::fixBlock( std::list< Statement * > &kids ) {
		for ( std::list< Statement * >::iterator k = kids.begin(); k != kids.end(); k++ ) {
			*k = (*k)->acceptMutator(*this);

			if ( ! get_breakLabel().empty() ) {
				std::list< Statement * >::iterator next = k+1;
				std::list<Label> ls; ls.push_back( get_breakLabel() );
				kids.insert( next, new NullStmt( ls ) );
				set_breakLabel("");
			} // if
		} // for
	}

	CompoundStmt* MLEMutator::mutate( CompoundStmt *cmpndStmt ) {
		bool labeledBlock = !(cmpndStmt->get_labels().empty());
		if ( labeledBlock ) {
			Label brkLabel = generator->newLabel("blockBreak");
			enclosingControlStructures.push_back( Entry( cmpndStmt, brkLabel ) );
		} // if

		// a child statement may set the break label - if they do, attach it to the next statement
		std::list< Statement * > &kids = cmpndStmt->get_kids();
		fixBlock( kids );

		if ( labeledBlock ) {
			assert( ! enclosingControlStructures.empty() );
			if ( ! enclosingControlStructures.back().useBreakExit().empty() ) {
				set_breakLabel( enclosingControlStructures.back().useBreakExit() );
			} // if
			enclosingControlStructures.pop_back();
		} // if

		return cmpndStmt;
	}

	template< typename LoopClass >
	Statement *MLEMutator::handleLoopStmt( LoopClass *loopStmt ) {
		// remember this as the most recent enclosing loop, then mutate the body of the loop -- this will determine
		// whether brkLabel and contLabel are used with branch statements and will recursively do the same to nested
		// loops
		Label brkLabel = generator->newLabel("loopBreak");
		Label contLabel = generator->newLabel("loopContinue");
		enclosingControlStructures.push_back( Entry( loopStmt, brkLabel, contLabel ) );
		loopStmt->set_body ( loopStmt->get_body()->acceptMutator( *this ) );

		Entry &e = enclosingControlStructures.back();
		// sanity check that the enclosing loops have been popped correctly
		assert ( e == loopStmt );

		// this will take the necessary steps to add definitions of the previous two labels, if they are used.
		loopStmt->set_body( mutateLoop( loopStmt->get_body(), e ) );
		enclosingControlStructures.pop_back();

		return loopStmt;
	}

	Statement *MLEMutator::mutate( CaseStmt *caseStmt ) {
		caseStmt->set_condition( maybeMutate( caseStmt->get_condition(), *this ) );
		fixBlock( caseStmt->get_statements() );

		return caseStmt;
	}

	template< typename IfClass >
	Statement *MLEMutator::handleIfStmt( IfClass *ifStmt ) {
		// generate a label for breaking out of a labeled if
		bool labeledBlock = !(ifStmt->get_labels().empty());
		if ( labeledBlock ) {
			Label brkLabel = generator->newLabel("blockBreak");
			enclosingControlStructures.push_back( Entry( ifStmt, brkLabel ) );
		} // if

		Parent::mutate( ifStmt );
		
		if ( labeledBlock ) {
			if ( ! enclosingControlStructures.back().useBreakExit().empty() ) {
				set_breakLabel( enclosingControlStructures.back().useBreakExit() );
			} // if
			enclosingControlStructures.pop_back();
		} // if
		return ifStmt;
	}

	template< typename SwitchClass >
	Statement *MLEMutator::handleSwitchStmt( SwitchClass *switchStmt ) {
		// generate a label for breaking out of a labeled switch
		Label brkLabel = generator->newLabel("switchBreak");
		enclosingControlStructures.push_back( Entry(switchStmt, brkLabel) );
		mutateAll( switchStmt->get_branches(), *this );

		Entry &e = enclosingControlStructures.back();
		assert ( e == switchStmt );

		// only generate break label if labeled break is used
		if ( e.isBreakUsed() ) {
			// for the purposes of keeping switch statements uniform (i.e. all statements that are direct children of a
			// switch should be CastStmts), append the exit label + break to the last case statement; create a default
			// case if there are no cases
			std::list< Statement * > &branches = switchStmt->get_branches();
			if ( branches.empty() ) {
				branches.push_back( CaseStmt::makeDefault() );
			} // if

			if ( CaseStmt * c = dynamic_cast< CaseStmt * >( branches.back() ) ) {
				std::list<Label> temp; temp.push_back( brkLabel );
				c->get_statements().push_back( new BranchStmt( temp, Label("brkLabel"), BranchStmt::Break ) );
			} else assert(0); // as of this point, all branches of a switch are still CaseStmts
		} // if

		assert ( enclosingControlStructures.back() == switchStmt );
		enclosingControlStructures.pop_back();
		return switchStmt;
	}

	Statement *MLEMutator::mutate( BranchStmt *branchStmt ) throw ( SemanticError ) {
		std::string originalTarget = branchStmt->get_originalTarget();

		std::list< Entry >::reverse_iterator targetEntry;
		if ( branchStmt->get_type() == BranchStmt::Goto ) {
			return branchStmt;
		} else if ( branchStmt->get_type() == BranchStmt::Continue) {
			// continue target must be a loop
			if ( branchStmt->get_target() == "" ) {
				targetEntry = std::find_if( enclosingControlStructures.rbegin(), enclosingControlStructures.rend(), [](Entry &e) { return isLoop( e.get_controlStructure() ); } );
			} else {
				// labelled continue - lookup label in table ot find attached control structure
				targetEntry = std::find( enclosingControlStructures.rbegin(), enclosingControlStructures.rend(), (*targetTable)[branchStmt->get_target()] );
			} // if
			if ( targetEntry == enclosingControlStructures.rend() || ! isLoop( targetEntry->get_controlStructure() ) ) {
				throw SemanticError( "'continue' target must be an enclosing loop: " + originalTarget );
			} // if
		} else if ( branchStmt->get_type() == BranchStmt::Break ) {
			if ( enclosingControlStructures.empty() ) throw SemanticError( "'break' outside a loop, switch, or labelled block" );
			targetEntry = enclosingControlStructures.rbegin();
		} else {
			assert( false );
		} // if

		if ( branchStmt->get_target() != "" && targetTable->find( branchStmt->get_target() ) == targetTable->end() ) {
			throw SemanticError("The label defined in the exit loop statement does not exist: " + originalTarget );  // shouldn't happen (since that's already checked)
		} // if

		// branch error checks, get the appropriate label name and create a goto
		Label exitLabel;
		switch ( branchStmt->get_type() ) {
		  case BranchStmt::Break:
				assert( targetEntry->useBreakExit() != "");
				exitLabel = targetEntry->useBreakExit();
				break;
		  case BranchStmt::Continue:
				assert( targetEntry->useContExit() != "");
				exitLabel = targetEntry->useContExit();
				break;
		  default:
				assert(0);					// shouldn't be here
		} // switch

		if ( branchStmt->get_target() == "" && branchStmt->get_type() != BranchStmt::Continue ) {
			// unlabelled break/continue - can keep branch as break/continue for extra semantic information, but add
			// exitLabel as its destination so that label passes can easily determine where the break/continue goes to
			branchStmt->set_target( exitLabel );
			return branchStmt;
		} else {
			// labelled break/continue - can't easily emulate this with break and continue, so transform into a goto
			delete branchStmt;
			return new BranchStmt( std::list<Label>(), exitLabel, BranchStmt::Goto );
		} // if
	}

	Statement *MLEMutator::mutateLoop( Statement *bodyLoop, Entry &e ) {
		// ensure loop body is a block
		CompoundStmt *newBody;
		if ( ! (newBody = dynamic_cast<CompoundStmt *>( bodyLoop )) ) {
			newBody = new CompoundStmt( std::list< Label >() );
			newBody->get_kids().push_back( bodyLoop );
		} // if

		// only generate these when needed

		if ( e.isContUsed() ) {
			// continue label goes in the body as the last statement
			std::list< Label > labels; labels.push_back( e.useContExit() );
			newBody->get_kids().push_back( new NullStmt( labels ) );
		} // if

		if ( e.isBreakUsed() ) {
			// break label goes after the loop -- it'll get set by the outer mutator if we do this
			set_breakLabel( e.useBreakExit() );
		} // if

		return newBody;
	}

	Statement *MLEMutator::mutate( WhileStmt *whileStmt ) {
		return handleLoopStmt( whileStmt );
	}

	Statement *MLEMutator::mutate( ForStmt *forStmt ) {
		return handleLoopStmt( forStmt );
	}

	Statement *MLEMutator::mutate( IfStmt *ifStmt ) {
		return handleIfStmt( ifStmt );
	}

	Statement *MLEMutator::mutate( SwitchStmt *switchStmt ) {
		return handleSwitchStmt( switchStmt );
	}
} // namespace ControlStruct

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