//
// 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.
//
// CaseRangeMutator.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:35:13 2016
// Update Count     : 9
//

#include <list>
#include <cassert>
#include <cstdlib>
#include <iterator>

#include "Common/utility.h"

#include "SynTree/Statement.h"
#include "SynTree/Expression.h"
#include "SynTree/Constant.h"
#include "SynTree/Type.h"
#include "CaseRangeMutator.h"

namespace ControlStruct {
	Statement *CaseRangeMutator::mutate( SwitchStmt *switchStmt ) {
		std::list< Statement * > &cases = switchStmt->get_branches();

		// a `for' would be more natural... all this contortions are because `replace' invalidates the iterator
		std::list< Statement * >::iterator i = cases.begin();
		while ( i != cases.end() ) {
			(*i )->acceptMutator( *this );

			if ( ! newCaseLabels.empty() ) {
				std::list< Statement * > newCases;

				// transform( newCaseLabels.begin(), newCaseLabels.end(), bnd1st( ptr_fun( ctor< CaseStmt, Label, Expression * > ) ) );

				for ( std::list< Expression * >::iterator j = newCaseLabels.begin();
					  j != newCaseLabels.end(); j++ ) {
					std::list<Label> emptyLabels;
					std::list< Statement *> emptyStmts;
					newCases.push_back( new CaseStmt( emptyLabels, *j, emptyStmts ) );
				} // for

				if ( CaseStmt *currentCase = dynamic_cast< CaseStmt * > ( *i ) )
					if ( ! currentCase->get_statements().empty() ) {
						CaseStmt *lastCase = dynamic_cast< CaseStmt * > ( newCases.back() );
						if ( lastCase == 0 ) { throw ( 0 ); /* FIXME */ } // something is very wrong, as I just made these, and they were all cases
						// transfer the statement block ( if any ) to the new list:
						lastCase->set_statements( currentCase->get_statements() );
					} // if
				std::list< Statement * >::iterator j = i; advance( j, 1 );
				replace ( cases, i, newCases );
				i = j;
				newCaseLabels.clear();
			} else
				i++;
		} // while

		return switchStmt;
	}

	Statement *CaseRangeMutator::mutate( CaseStmt *caseStmt ) {
		UntypedExpr *cond;
		if ( ( cond = dynamic_cast< UntypedExpr * >( caseStmt->get_condition() )) != 0 ) {
			NameExpr *nmfunc;
			if ( ( nmfunc = dynamic_cast< NameExpr *>( cond->get_function() )) != 0 ) {
				if ( nmfunc->get_name() == std::string("Range") ) {
					assert( cond->get_args().size() == 2 );
					std::list<Expression *>::iterator i = cond->get_args().begin();
					Expression *lo = *i, *hi = *(++i ); // "unnecessary" temporaries
					fillRange( lo, hi );
				} // if
			} // if
		} else if ( TupleExpr *tcond = dynamic_cast< TupleExpr * >( caseStmt->get_condition() ) ) {
			// case list
			assert( ! tcond->get_exprs().empty() );
			for ( std::list< Expression * >::iterator i = tcond->get_exprs().begin(); i != tcond->get_exprs().end(); i++ )
				newCaseLabels.push_back( *i ); // do I need to clone them?
		} // if

		std::list< Statement * > &stmts = caseStmt->get_statements();
		mutateAll ( stmts, *this );

		return caseStmt;
	}

	void CaseRangeMutator::fillRange( Expression *lo, Expression *hi ) {
		// generate the actual range ( and check for consistency )
		Constant *c_lo, *c_hi;
		ConstantExpr *ce_lo, *ce_hi;
		ce_lo = dynamic_cast< ConstantExpr * >( lo );
		ce_hi = dynamic_cast< ConstantExpr * >( hi );

		if ( ce_lo && ce_hi ) {
			c_lo = ce_lo->get_constant(); c_hi = ce_hi->get_constant();
		} /* else {
			 if ( ! ce_lo ) ;
			 if ( ! ce_hi ) ;
			 } */
		BasicType *ty_lo = dynamic_cast< BasicType * >( c_lo->get_type() ),
			*ty_hi = dynamic_cast< BasicType * >( c_hi->get_type() );
	
		if ( ! ty_lo || ! ty_hi )
			return; // one of them is not a constant

		switch ( ty_lo->get_kind() ) {
		  case BasicType::Char:
		  case BasicType::UnsignedChar:
			switch ( ty_hi->get_kind() ) {
			  case BasicType::Char:
			  case BasicType::UnsignedChar:
				// first case, they are both printable ASCII characters represented as 'x'
				if ( c_lo->get_value().size() == 3 && c_hi->get_value().size() == 3 ) {
					char ch_lo = ( c_lo->get_value())[1], ch_hi = ( c_hi->get_value())[1];

					if ( ch_lo > ch_hi ) { char t=ch_lo; ch_lo=ch_hi; ch_hi=t; }

					for ( char c = ch_lo; c <=  ch_hi; c++ ) {
						Type::Qualifiers q;
						Constant cnst( new BasicType( q, BasicType::Char ),
									   std::string("'") + c + std::string("'") );
						newCaseLabels.push_back( new ConstantExpr( cnst ) );
					} // for

					return;
				} // if
				break;
			  default:
				// error: incompatible constants
				break;
			} // switch
			break;
		  case BasicType::ShortSignedInt:
		  case BasicType::ShortUnsignedInt:
		  case BasicType::SignedInt:
		  case BasicType::UnsignedInt:
		  case BasicType::LongSignedInt:
		  case BasicType::LongUnsignedInt:
		  case BasicType::LongLongSignedInt:
		  case BasicType::LongLongUnsignedInt:
			switch ( ty_hi->get_kind() ) {
			  case BasicType::ShortSignedInt:
			  case BasicType::ShortUnsignedInt:
			  case BasicType::SignedInt:
			  case BasicType::UnsignedInt:
			  case BasicType::LongSignedInt:
			  case BasicType::LongUnsignedInt:
			  case BasicType::LongLongSignedInt:
			  case BasicType::LongLongUnsignedInt: {
				  int i_lo = atoi( c_lo->get_value().c_str()),
					  i_hi = atoi( c_hi->get_value().c_str());

				  if ( i_lo > i_hi ) { int t=i_lo; i_lo=i_hi; i_hi=t; }

				  for ( int c = i_lo; c <=  i_hi; c++ ) {
					  Type::Qualifiers q;
					  Constant cnst( new BasicType( q, ty_hi->get_kind()), // figure can't hurt (used to think in positives)
									 toString< int >( c ) );
					  newCaseLabels.push_back( new ConstantExpr( cnst ) );
				  }

				  return;
			  }
			  default:
				// error: incompatible constants
				break;
			}
			break;
		  default:
			break;
		} // switch

		/* End: */{ 
			// invalid range, signal a warning (it still generates the two case labels)
			newCaseLabels.push_back( lo );
			newCaseLabels.push_back( hi );
			return;
		}
	}
} // namespace ControlStruct

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