//
// 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.
//
// Resolver.cc --
//
// Author           : Richard C. Bilson
// Created On       : Sun May 17 12:17:01 2015
// Last Modified By : Rob Schluntz
// Last Modified On : Fri May 13 11:36:40 2016
// Update Count     : 203
//

#include "Resolver.h"
#include "AlternativeFinder.h"
#include "Alternative.h"
#include "RenameVars.h"
#include "ResolveTypeof.h"
#include "SynTree/Statement.h"
#include "SynTree/Type.h"
#include "SynTree/Expression.h"
#include "SynTree/Initializer.h"
#include "SymTab/Indexer.h"
#include "Common/utility.h"
#include "InitTweak/InitTweak.h"

#include <iostream>
using namespace std;

namespace ResolvExpr {
	class Resolver : public SymTab::Indexer {
	  public:
		Resolver() : SymTab::Indexer( false ), switchType( 0 ) {}

		virtual void visit( FunctionDecl *functionDecl );
		virtual void visit( ObjectDecl *functionDecl );
		virtual void visit( TypeDecl *typeDecl );
		virtual void visit( EnumDecl * enumDecl );

		virtual void visit( ArrayType * at );

		virtual void visit( ExprStmt *exprStmt );
		virtual void visit( AsmExpr *asmExpr );
		virtual void visit( AsmStmt *asmStmt );
		virtual void visit( IfStmt *ifStmt );
		virtual void visit( WhileStmt *whileStmt );
		virtual void visit( ForStmt *forStmt );
		virtual void visit( SwitchStmt *switchStmt );
		virtual void visit( ChooseStmt *switchStmt );
		virtual void visit( CaseStmt *caseStmt );
		virtual void visit( BranchStmt *branchStmt );
		virtual void visit( ReturnStmt *returnStmt );
		virtual void visit( ImplicitCtorDtorStmt * impCtorDtorStmt );

		virtual void visit( SingleInit *singleInit );
		virtual void visit( ListInit *listInit );
		virtual void visit( ConstructorInit *ctorInit );
	  private:
  	typedef std::list< Initializer * >::iterator InitIterator;

	  void resolveAggrInit( AggregateDecl *, InitIterator &, InitIterator & );
	  void resolveSingleAggrInit( Declaration *, InitIterator &, InitIterator & );
	  void fallbackInit( ConstructorInit * ctorInit );
		std::list< Type * > functionReturn;
		Type *initContext;
		Type *switchType;
		bool inEnumDecl = false;
	};

	void resolve( std::list< Declaration * > translationUnit ) {
		Resolver resolver;
		acceptAll( translationUnit, resolver );
#if 0
		resolver.print( cerr );
		for ( std::list< Declaration * >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
			(*i)->print( std::cerr );
			(*i)->accept( resolver );
		} // for
#endif
	}

	Expression *resolveInVoidContext( Expression *expr, const SymTab::Indexer &indexer ) {
		TypeEnvironment env;
		return resolveInVoidContext( expr, indexer, env );
	}


	namespace {
		void finishExpr( Expression *expr, const TypeEnvironment &env ) {
			expr->set_env( new TypeSubstitution );
			env.makeSubstitution( *expr->get_env() );
		}
	} // namespace

	Expression *findVoidExpression( Expression *untyped, const SymTab::Indexer &indexer ) {
		global_renamer.reset();
		TypeEnvironment env;
		Expression *newExpr = resolveInVoidContext( untyped, indexer, env );
		finishExpr( newExpr, env );
		return newExpr;
	}

	namespace {
		Expression *findSingleExpression( Expression *untyped, const SymTab::Indexer &indexer ) {
			TypeEnvironment env;
			AlternativeFinder finder( indexer, env );
			finder.find( untyped );
#if 0
			if ( finder.get_alternatives().size() != 1 ) {
				std::cout << "untyped expr is ";
				untyped->print( std::cout );
				std::cout << std::endl << "alternatives are:";
				for ( std::list< Alternative >::const_iterator i = finder.get_alternatives().begin(); i != finder.get_alternatives().end(); ++i ) {
					i->print( std::cout );
				} // for
			} // if
#endif
			assert( finder.get_alternatives().size() == 1 );
			Alternative &choice = finder.get_alternatives().front();
			Expression *newExpr = choice.expr->clone();
			finishExpr( newExpr, choice.env );
			return newExpr;
		}

		bool isIntegralType( Type *type ) {
			if ( dynamic_cast< EnumInstType * >( type ) ) {
				return true;
			} else if ( BasicType *bt = dynamic_cast< BasicType * >( type ) ) {
				return bt->isInteger();
			} else {
				return false;
			} // if
		}

		Expression *findIntegralExpression( Expression *untyped, const SymTab::Indexer &indexer ) {
			TypeEnvironment env;
			AlternativeFinder finder( indexer, env );
			finder.find( untyped );
#if 0
			if ( finder.get_alternatives().size() != 1 ) {
				std::cout << "untyped expr is ";
				untyped->print( std::cout );
				std::cout << std::endl << "alternatives are:";
				for ( std::list< Alternative >::const_iterator i = finder.get_alternatives().begin(); i != finder.get_alternatives().end(); ++i ) {
					i->print( std::cout );
				} // for
			} // if
#endif
			Expression *newExpr = 0;
			const TypeEnvironment *newEnv = 0;
			for ( AltList::const_iterator i = finder.get_alternatives().begin(); i != finder.get_alternatives().end(); ++i ) {
				if ( i->expr->get_results().size() == 1 && isIntegralType( i->expr->get_results().front() ) ) {
					if ( newExpr ) {
						throw SemanticError( "Too many interpretations for case control expression", untyped );
					} else {
						newExpr = i->expr->clone();
						newEnv = &i->env;
					} // if
				} // if
			} // for
			if ( ! newExpr ) {
				throw SemanticError( "No interpretations for case control expression", untyped );
			} // if
			finishExpr( newExpr, *newEnv );
			return newExpr;
		}

	}

	void Resolver::visit( ObjectDecl *objectDecl ) {
		Type *new_type = resolveTypeof( objectDecl->get_type(), *this );
		objectDecl->set_type( new_type );
		// To handle initialization of routine pointers, e.g., int (*fp)(int) = foo(), means that class-variable
		// initContext is changed multiple time because the LHS is analysed twice. The second analysis changes
		// initContext because of a function type can contain object declarations in the return and parameter types. So
		// each value of initContext is retained, so the type on the first analysis is preserved and used for selecting
		// the RHS.
		Type *temp = initContext;
		initContext = new_type;
		if ( inEnumDecl && dynamic_cast< EnumInstType * >( initContext ) ) {
			// enumerator initializers should not use the enum type to initialize, since
			// the enum type is still incomplete at this point. Use signed int instead.
			initContext = new BasicType( Type::Qualifiers(), BasicType::SignedInt );
		}
		SymTab::Indexer::visit( objectDecl );
		if ( inEnumDecl && dynamic_cast< EnumInstType * >( initContext ) ) {
			// delete newly created signed int type
			delete initContext;
		}
		initContext = temp;
	}

	void Resolver::visit( ArrayType * at ) {
		if ( at->get_dimension() ) {
			BasicType arrayLenType = BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
			CastExpr *castExpr = new CastExpr( at->get_dimension(), arrayLenType.clone() );
			Expression *newExpr = findSingleExpression( castExpr, *this );
			delete at->get_dimension();
			at->set_dimension( newExpr );
		}
		Visitor::visit( at );
	}

	void Resolver::visit( TypeDecl *typeDecl ) {
		if ( typeDecl->get_base() ) {
			Type *new_type = resolveTypeof( typeDecl->get_base(), *this );
			typeDecl->set_base( new_type );
		} // if
		SymTab::Indexer::visit( typeDecl );
	}

	void Resolver::visit( FunctionDecl *functionDecl ) {
#if 0
		std::cout << "resolver visiting functiondecl ";
		functionDecl->print( std::cout );
		std::cout << std::endl;
#endif
		Type *new_type = resolveTypeof( functionDecl->get_type(), *this );
		functionDecl->set_type( new_type );
		std::list< Type * > oldFunctionReturn = functionReturn;
		functionReturn.clear();
		for ( std::list< DeclarationWithType * >::const_iterator i = functionDecl->get_functionType()->get_returnVals().begin(); i != functionDecl->get_functionType()->get_returnVals().end(); ++i ) {
			functionReturn.push_back( (*i)->get_type() );
		} // for
		SymTab::Indexer::visit( functionDecl );
		functionReturn = oldFunctionReturn;
	}

	void Resolver::visit( EnumDecl * enumDecl ) {
		// in case we decide to allow nested enums
		bool oldInEnumDecl = inEnumDecl;
		inEnumDecl = true;
		SymTab::Indexer::visit( enumDecl );
		inEnumDecl = oldInEnumDecl;
	}

	void Resolver::visit( ExprStmt *exprStmt ) {
		if ( exprStmt->get_expr() ) {
			Expression *newExpr = findVoidExpression( exprStmt->get_expr(), *this );
			delete exprStmt->get_expr();
			exprStmt->set_expr( newExpr );
		} // if
	}

	void Resolver::visit( AsmExpr *asmExpr ) {
		Expression *newExpr = findVoidExpression( asmExpr->get_operand(), *this );
		delete asmExpr->get_operand();
		asmExpr->set_operand( newExpr );
		if ( asmExpr->get_inout() ) {
			newExpr = findVoidExpression( asmExpr->get_inout(), *this );
			delete asmExpr->get_inout();
			asmExpr->set_inout( newExpr );
		} // if
	}

	void Resolver::visit( AsmStmt *asmStmt ) {
		acceptAll( asmStmt->get_input(), *this);
		acceptAll( asmStmt->get_output(), *this);
	}

	void Resolver::visit( IfStmt *ifStmt ) {
		Expression *newExpr = findSingleExpression( ifStmt->get_condition(), *this );
		delete ifStmt->get_condition();
		ifStmt->set_condition( newExpr );
		Visitor::visit( ifStmt );
	}

	void Resolver::visit( WhileStmt *whileStmt ) {
		Expression *newExpr = findSingleExpression( whileStmt->get_condition(), *this );
		delete whileStmt->get_condition();
		whileStmt->set_condition( newExpr );
		Visitor::visit( whileStmt );
	}

	void Resolver::visit( ForStmt *forStmt ) {
		SymTab::Indexer::visit( forStmt );

		if ( forStmt->get_condition() ) {
			Expression * newExpr = findSingleExpression( forStmt->get_condition(), *this );
			delete forStmt->get_condition();
			forStmt->set_condition( newExpr );
		} // if

		if ( forStmt->get_increment() ) {
			Expression * newExpr = findVoidExpression( forStmt->get_increment(), *this );
			delete forStmt->get_increment();
			forStmt->set_increment( newExpr );
		} // if
	}

	template< typename SwitchClass >
	void handleSwitchStmt( SwitchClass *switchStmt, SymTab::Indexer &visitor ) {
		Expression *newExpr;
		newExpr = findIntegralExpression( switchStmt->get_condition(), visitor );
		delete switchStmt->get_condition();
		switchStmt->set_condition( newExpr );

		visitor.Visitor::visit( switchStmt );
	}

	void Resolver::visit( SwitchStmt *switchStmt ) {
		handleSwitchStmt( switchStmt, *this );
	}

	void Resolver::visit( ChooseStmt *switchStmt ) {
		handleSwitchStmt( switchStmt, *this );
	}

	void Resolver::visit( CaseStmt *caseStmt ) {
		Visitor::visit( caseStmt );
	}

	void Resolver::visit( BranchStmt *branchStmt ) {
		// must resolve the argument for a computed goto
		if ( branchStmt->get_type() == BranchStmt::Goto ) { // check for computed goto statement
			if ( Expression * arg = branchStmt->get_computedTarget() ) {
				VoidType v = Type::Qualifiers();		// cast to void * for the alternative finder
				PointerType pt( Type::Qualifiers(), v.clone() );
				CastExpr * castExpr = new CastExpr( arg, pt.clone() );
				Expression * newExpr = findSingleExpression( castExpr, *this ); // find best expression
				branchStmt->set_target( newExpr );
			} // if
		} // if
	}

	void Resolver::visit( ReturnStmt *returnStmt ) {
		if ( returnStmt->get_expr() ) {
			CastExpr *castExpr = new CastExpr( returnStmt->get_expr() );
			cloneAll( functionReturn, castExpr->get_results() );
			Expression *newExpr = findSingleExpression( castExpr, *this );
			delete castExpr;
			returnStmt->set_expr( newExpr );
		} // if
	}

	template< typename T >
	bool isCharType( T t ) {
		if ( BasicType * bt = dynamic_cast< BasicType * >( t ) ) {
			return bt->get_kind() == BasicType::Char || bt->get_kind() == BasicType::SignedChar ||
				bt->get_kind() == BasicType::UnsignedChar;
		}
		return false;
	}

	void Resolver::visit( SingleInit *singleInit ) {
		if ( singleInit->get_value() ) {
#if 0
			if (NameExpr * ne = dynamic_cast<NameExpr*>(singleInit->get_value())) {
				string n = ne->get_name();
				if (n == "0") {
					initContext = new BasicType(Type::Qualifiers(),
												BasicType::SignedInt);
				} else {
					DeclarationWithType * decl = lookupId( n );
					initContext = decl->get_type();
				}
			} else if (ConstantExpr * e =
					   dynamic_cast<ConstantExpr*>(singleInit->get_value())) {
				Constant *c = e->get_constant();
				initContext = c->get_type();
			} else {
				assert(0);
			}
#endif
			CastExpr *castExpr = new CastExpr( singleInit->get_value(), initContext->clone() );
			Expression *newExpr = findSingleExpression( castExpr, *this );
			delete castExpr;
			singleInit->set_value( newExpr );

			// check if initializing type is char[]
			if ( ArrayType * at = dynamic_cast< ArrayType * >( initContext ) ) {
				if ( isCharType( at->get_base() ) ) {
					// check if the resolved type is char *
					if ( PointerType * pt = dynamic_cast< PointerType *>( newExpr->get_results().front() ) ) {
						if ( isCharType( pt->get_base() ) ) {
							// strip cast if we're initializing a char[] with a char *, e.g.  char x[] = "hello";
							CastExpr *ce = dynamic_cast< CastExpr * >( newExpr );
							singleInit->set_value( ce->get_arg() );
							ce->set_arg( NULL );
							delete ce;
						}
					}
				}
			}
		} // if
//	singleInit->get_value()->accept( *this );
	}

	void Resolver::resolveSingleAggrInit( Declaration * dcl, InitIterator & init, InitIterator & initEnd ) {
		DeclarationWithType * dt = dynamic_cast< DeclarationWithType * >( dcl );
		assert( dt );
		initContext = dt->get_type();
		try {
			if ( init == initEnd ) return; // stop when there are no more initializers
			(*init)->accept( *this );
			++init; // made it past an initializer
		} catch( SemanticError & ) {
			// need to delve deeper, if you can
			if ( StructInstType * sit = dynamic_cast< StructInstType * >( dt->get_type() ) ) {
				resolveAggrInit( sit->get_baseStruct(), init, initEnd );
			} else if ( UnionInstType * uit = dynamic_cast< UnionInstType * >( dt->get_type() ) ) {
				resolveAggrInit( uit->get_baseUnion(), init, initEnd );
			} else {
				// member is not an aggregate type, so can't go any deeper

				// might need to rethink what is being thrown
				throw;
			} // if
		}
	}

	void Resolver::resolveAggrInit( AggregateDecl * aggr, InitIterator & init, InitIterator & initEnd ) {
		if ( StructDecl * st = dynamic_cast< StructDecl * >( aggr ) ) {
			// want to resolve each initializer to the members of the struct,
			// but if there are more initializers than members we should stop
			list< Declaration * >::iterator it = st->get_members().begin();
			for ( ; it != st->get_members().end(); ++it) {
				resolveSingleAggrInit( *it, init, initEnd );
			}
		} else if ( UnionDecl * un = dynamic_cast< UnionDecl * >( aggr ) ) {
			// only resolve to the first member of a union
			resolveSingleAggrInit( *un->get_members().begin(), init, initEnd );
		} // if
	}

	void Resolver::visit( ListInit * listInit ) {
		InitIterator iter = listInit->begin_initializers();
		InitIterator end = listInit->end_initializers();

		if ( ArrayType * at = dynamic_cast< ArrayType * >( initContext ) ) {
			// resolve each member to the base type of the array
			for ( ; iter != end; ++iter ) {
				initContext = at->get_base();
				(*iter)->accept( *this );
			} // for
		} else if ( StructInstType * st = dynamic_cast< StructInstType * >( initContext ) ) {
			resolveAggrInit( st->get_baseStruct(), iter, end );
		} else if ( UnionInstType *st = dynamic_cast< UnionInstType * >( initContext ) ) {
			resolveAggrInit( st->get_baseUnion(), iter, end );
		} else {
			// basic types are handled here
			Visitor::visit( listInit );
		}

#if 0
		if ( ArrayType *at = dynamic_cast<ArrayType*>(initContext) ) {
			std::list<Initializer *>::iterator iter( listInit->begin_initializers() );
			for ( ; iter != listInit->end_initializers(); ++iter ) {
				initContext = at->get_base();
				(*iter)->accept( *this );
			} // for
		} else if ( StructInstType *st = dynamic_cast<StructInstType*>(initContext) ) {
			StructDecl *baseStruct = st->get_baseStruct();
			std::list<Declaration *>::iterator iter1( baseStruct->get_members().begin() );
			std::list<Initializer *>::iterator iter2( listInit->begin_initializers() );
			for ( ; iter1 != baseStruct->get_members().end() && iter2 != listInit->end_initializers(); ++iter2 ) {
				if ( (*iter2)->get_designators().empty() ) {
					DeclarationWithType *dt = dynamic_cast<DeclarationWithType *>( *iter1 );
					initContext = dt->get_type();
					(*iter2)->accept( *this );
					++iter1;
				} else {
					StructDecl *st = baseStruct;
					iter1 = st->get_members().begin();
					std::list<Expression *>::iterator iter3( (*iter2)->get_designators().begin() );
					for ( ; iter3 != (*iter2)->get_designators().end(); ++iter3 ) {
						NameExpr *key = dynamic_cast<NameExpr *>( *iter3 );
						assert( key );
						for ( ; iter1 != st->get_members().end(); ++iter1 ) {
							if ( key->get_name() == (*iter1)->get_name() ) {
								(*iter1)->print( cout );
								cout << key->get_name() << endl;
								ObjectDecl *fred = dynamic_cast<ObjectDecl *>( *iter1 );
								assert( fred );
								StructInstType *mary = dynamic_cast<StructInstType*>( fred->get_type() );
								assert( mary );
								st = mary->get_baseStruct();
								iter1 = st->get_members().begin();
								break;
							} // if
						}  // for
					} // for
					ObjectDecl *fred = dynamic_cast<ObjectDecl *>( *iter1 );
					assert( fred );
					initContext = fred->get_type();
					(*listInit->begin_initializers())->accept( *this );
				} // if
			} // for
		} else if ( UnionInstType *st = dynamic_cast<UnionInstType*>(initContext) ) {
			DeclarationWithType *dt = dynamic_cast<DeclarationWithType *>( *st->get_baseUnion()->get_members().begin() );
			initContext = dt->get_type();
			(*listInit->begin_initializers())->accept( *this );
		} // if
#endif
	}

	// ConstructorInit - fall back on C-style initializer
	void Resolver::fallbackInit( ConstructorInit * ctorInit ) {
		// could not find valid constructor, or found an intrinsic constructor
		// fall back on C-style initializer
		delete ctorInit->get_ctor();
		ctorInit->set_ctor( NULL );
		maybeAccept( ctorInit->get_init(), *this );
	}

	void Resolver::visit( ConstructorInit *ctorInit ) {
		try {
			maybeAccept( ctorInit->get_ctor(), *this );
			maybeAccept( ctorInit->get_dtor(), *this );
		} catch ( SemanticError ) {
			// no alternatives for the constructor initializer - fallback on C-style initializer
			// xxx - not sure if this makes a ton of sense - should maybe never be able to have this situation?
			fallbackInit( ctorInit );
			return;
		}

		// found a constructor - can get rid of C-style initializer
		delete ctorInit->get_init();
		ctorInit->set_init( NULL );

		// intrinsic single parameter constructors and destructors do nothing. Since this was
		// implicitly generated, there's no way for it to have side effects, so get rid of it
		// to clean up generated code.
		if ( InitTweak::isInstrinsicSingleArgCallStmt( ctorInit->get_ctor() ) ) {
			delete ctorInit->get_ctor();
			ctorInit->set_ctor( NULL );
		}
		if ( InitTweak::isInstrinsicSingleArgCallStmt( ctorInit->get_ctor() ) ) {
			delete ctorInit->get_dtor();
			ctorInit->set_dtor( NULL );
		}
	}

	void Resolver::visit( ImplicitCtorDtorStmt * impCtorDtorStmt ) {
		// before resolving ctor/dtor, need to remove type qualifiers from the first argument (the object being constructed).
		// Do this through a cast expression to greatly simplify the code.
		Expression * callExpr = InitTweak::getCtorDtorCall( impCtorDtorStmt );
		assert( callExpr );
		Expression *& constructee = InitTweak::getCallArg( callExpr, 0 );
		Type * type = 0;

		// need to find the type of the first argument, which is unfortunately not uniform since array construction
		// includes an untyped '+' expression.
		if ( UntypedExpr * plusExpr = dynamic_cast< UntypedExpr * >( constructee ) ) {
			// constructee is <array>+<index>
			// get Variable <array>, then get the base type of the VariableExpr - this is the type that needs to be fixed
			Expression * arr = InitTweak::getCallArg( plusExpr, 0 );
			assert( dynamic_cast< VariableExpr * >( arr ) );
			assert( arr && arr->get_results().size() == 1 );
			type = arr->get_results().front()->clone();
		} else {
			// otherwise, constructing a plain object, which means the object's address is being taken.
			// Need to get the type of the VariableExpr object, because the AddressExpr is rebuilt and uses the
			// type of the VariableExpr to do so.
			assert( constructee->get_results().size() == 1 );
			AddressExpr * addrExpr = dynamic_cast< AddressExpr * > ( constructee );
			assert( addrExpr && addrExpr->get_results().size() == 1);
			type = addrExpr->get_results().front()->clone();
		}
		// cast to T* with qualifiers removed.
		// unfortunately, lvalue is considered a qualifier. For AddressExpr to resolve, its argument
		// must have an lvalue qualified type, so remove all qualifiers except lvalue. If we ever
		// remove lvalue as a qualifier, this can change to
		//   type->get_qualifiers() = Type::Qualifiers();
		Type * base = InitTweak::getPointerBase( type );
		assert( base );
		base->get_qualifiers() -= Type::Qualifiers(true, true, true, false, true, true);
		// if pointer has lvalue qualifier, cast won't appear in output
		type->set_isLvalue( false );
		constructee = new CastExpr( constructee, type );

		// finally, resolve the ctor/dtor
		impCtorDtorStmt->get_callStmt()->accept( *this );
	}
} // namespace ResolvExpr

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