//
// 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.
//
// ChooseMutator.cc -- 
//
// Author           : Rodolfo G. Esteves
// Created On       : Mon May 18 07:44:20 2015
// Last Modified By : Rob Schluntz
// Last Modified On : Wed Jun 03 15:30:20 2015
// Update Count     : 5
//

#include <list>

#include "SynTree/Statement.h"
#include "ChooseMutator.h"

namespace ControlStruct {
	Statement *ChooseMutator::mutate( ChooseStmt *chooseStmt ) {
		bool enclosingChoose = insideChoose;
		insideChoose = true;
		mutateAll( chooseStmt->get_branches(), *this );
		insideChoose = enclosingChoose;
		return new SwitchStmt( chooseStmt->get_labels(),  chooseStmt->get_condition(), chooseStmt->get_branches() );
	}

	Statement *ChooseMutator::mutate( SwitchStmt *switchStmt ) {
		bool enclosingChoose = insideChoose;
		insideChoose = false;
		mutateAll( switchStmt->get_branches(), *this );
		insideChoose = enclosingChoose;
		return switchStmt;
	}

	Statement *ChooseMutator::mutate( FallthruStmt *fallthruStmt ) {
		delete fallthruStmt;
		return new NullStmt();
	}

	Statement* ChooseMutator::mutate( CaseStmt *caseStmt ) {
		std::list< Statement * > &stmts = caseStmt->get_statements();

		// the difference between switch and choose is that switch has an implicit fallthrough
		// to the next case, whereas choose has an implicit break at the end of the current case.
		// thus to transform a choose statement into a switch, we only need to insert breaks at the
		// end of any case that doesn't already end in a break and that doesn't end in a fallthru

		if ( insideChoose ) {
			BranchStmt *posBrk;
			if ( (( posBrk = dynamic_cast< BranchStmt * > ( stmts.back() ) ) && 
				  ( posBrk->get_type() == BranchStmt::Break ))  // last statement in the list is a (superfluous) 'break' 
				 || dynamic_cast< FallthruStmt * > ( stmts.back() ) )
				; 
			else {
				stmts.push_back( new BranchStmt( std::list< Label >(), "", BranchStmt::Break ) );
			} // if
		} // if

		mutateAll ( stmts, *this );
		return caseStmt;
	}
} // namespace ControlStruct

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