//
// 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 : Thu Aug  4 11:21:32 2016
// Update Count     : 202
//

// 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 <ext/alloc_traits.h>              // for __alloc_traits<>::value_type
#include <algorithm>                       // for find, find_if
#include <cassert>                         // for assert, assertf
#include <memory>                          // for allocator_traits<>::value_...

#include "Common/utility.h"                // for toString, operator+
#include "ControlStruct/LabelGenerator.h"  // for LabelGenerator
#include "MLEMutator.h"
#include "SynTree/Attribute.h"             // for Attribute
#include "SynTree/Expression.h"            // for Expression
#include "SynTree/Statement.h"             // for BranchStmt, CompoundStmt

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", cmpndStmt);
			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", loopStmt);
		Label contLabel = generator->newLabel("loopContinue", loopStmt);
		enclosingControlStructures.push_back( Entry( loopStmt, brkLabel, contLabel ) );
		loopStmt->set_body ( loopStmt->get_body()->acceptMutator( *this ) );

		assert( ! enclosingControlStructures.empty() );
		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", ifStmt);
			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", switchStmt);
		enclosingControlStructures.push_back( Entry(switchStmt, brkLabel) );
		mutateAll( switchStmt->get_statements(), *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 * > &statements = switchStmt->get_statements();
			if ( statements.empty() ) {
				statements.push_back( CaseStmt::makeDefault() );
			} // if

			if ( CaseStmt * c = dynamic_cast< CaseStmt * >( statements.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 statements of a switch are still CaseStmts
		} // if

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

	void addUnused( Statement * stmt, const Label & originalTarget ) {
		// break/continue without a label doesn't need unused attribute
		if ( originalTarget == "" ) return;
		// add unused attribute to the originalTarget of a labelled break/continue
		for ( Label & l : stmt->get_labels() ) {
			// find the label to add unused attribute to
			if ( l == originalTarget ) {
				for ( Attribute * attr : l.get_attributes() ) {
					// ensure attribute isn't added twice
					if ( attr->get_name() == "unused" ) return;
				}
				l.get_attributes().push_back( new Attribute( "unused" ) );
				return;
			}
		}
		assertf( false, "Could not find label '%s' on statement %s", originalTarget.get_name().c_str(), toString( stmt ).c_str() );
	}


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

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

		// 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

		// add unused attribute to label to silence warnings
		addUnused( targetEntry->get_controlStructure(), branchStmt->get_originalTarget() );

		// transform break/continue statements into goto to simplify later handling of branches
		delete branchStmt;
		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

		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: //
