//
// 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 : Rob Schluntz
// Last Modified On : Mon Jul 20 13:58:35 2015
// Update Count     : 176
//

// 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
// we don't yet know 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"

namespace ControlStruct {
	MLEMutator::~MLEMutator() {
		delete targetTable;
		targetTable = 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;
				if ( next == kids.end() ) {
					std::list<Label> ls; ls.push_back( get_breakLabel() );
					kids.push_back( new NullStmt( ls ) );
				} else {
					(*next)->get_labels().push_back( get_breakLabel() );
				}

				set_breakLabel("");
			} // if
		} // for
	}

	CompoundStmt* MLEMutator::mutate( CompoundStmt *cmpndStmt ) {
		bool labeledBlock = !(cmpndStmt->get_labels().empty());
		if ( labeledBlock ) {
			Label brkLabel = generator->newLabel("blockBreak");
			enclosingBlocks.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( ! enclosingBlocks.empty() );
			if ( ! enclosingBlocks.back().useBreakExit().empty() ) {
				set_breakLabel( enclosingBlocks.back().useBreakExit() );
			}
			enclosingBlocks.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");
		enclosingLoops.push_back( Entry( loopStmt, brkLabel, contLabel ) );
		loopStmt->set_body ( loopStmt->get_body()->acceptMutator( *this ) );

		// sanity check that the enclosing loops have been popped correctly
		Entry &e = enclosingLoops.back();
		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 ) );
		enclosingLoops.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 SwitchClass >
	Statement *MLEMutator::handleSwitchStmt( SwitchClass *switchStmt ) {
		// generate a label for breaking out of a labeled switch 
		Label brkLabel = generator->newLabel("switchBreak");
		enclosingSwitches.push_back( Entry(switchStmt, brkLabel) );
		mutateAll( switchStmt->get_branches(), *this ); 

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

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

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

		if ( branchStmt->get_type() == BranchStmt::Goto )
			return branchStmt;

		// test if continue target is a loop
		if ( branchStmt->get_type() == BranchStmt::Continue) {
			if ( enclosingLoops.empty() ) {
				throw SemanticError( "'continue' outside a loop" );
			} else if ( branchStmt->get_target() != "" && std::find( enclosingLoops.begin(), enclosingLoops.end(), (*targetTable)[branchStmt->get_target()] ) == enclosingLoops.end() ) {
				throw SemanticError( "'continue' target label must be an enclosing loop: " + originalTarget );
			}
		}

		if ( branchStmt->get_type() == BranchStmt::Break && (enclosingLoops.empty() && enclosingSwitches.empty() && enclosingBlocks.empty() ) )
			throw SemanticError( "'break' outside a loop or switch" );

		if ( branchStmt->get_target() == "" ) return branchStmt;

		if ( 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)

		std::list< Entry >::iterator check;
		if ( ( check = std::find( enclosingLoops.begin(), enclosingLoops.end(), (*targetTable)[branchStmt->get_target()] ) ) == enclosingLoops.end() )
			// not in loop, checking if in block
			if ( (check = std::find( enclosingBlocks.begin(), enclosingBlocks.end(), (*targetTable)[branchStmt->get_target()] )) == enclosingBlocks.end() )
				// neither in loop nor in block, checking if in switch/choose
				if ( (check = std::find( enclosingSwitches.begin(), enclosingSwitches.end(), (*targetTable)[branchStmt->get_target()] )) == enclosingSwitches.end() )
					throw SemanticError("The target specified in the exit loop statement does not correspond to an enclosing control structure: " + originalTarget );

		// what about exiting innermost block or switch???
		if ( enclosingLoops.back() == (*check) )
			return branchStmt;				// exit the innermost loop (labels unnecessary)

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

		return new BranchStmt( std::list<Label>(), exitLabel, BranchStmt::Goto );
	}

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

		return newBody;
	}

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

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

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

	Statement *MLEMutator::mutate( ChooseStmt *switchStmt ) {
		return handleSwitchStmt( switchStmt );		
	}

} // namespace ControlStruct

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