//
// 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 : Peter A. Buhr
// Last Modified On : Thu Mar 23 17:23:14 2017
// Update Count     : 211
//

#include <iostream>

#include "Alternative.h"
#include "AlternativeFinder.h"
#include "CurrentObject.h"
#include "RenameVars.h"
#include "Resolver.h"
#include "ResolveTypeof.h"
#include "typeops.h"

#include "SynTree/Expression.h"
#include "SynTree/Initializer.h"
#include "SynTree/Statement.h"
#include "SynTree/Type.h"

#include "SymTab/Autogen.h"
#include "SymTab/Indexer.h"

#include "Common/utility.h"

#include "InitTweak/InitTweak.h"

using namespace std;

namespace ResolvExpr {
	class Resolver final : public SymTab::Indexer {
	  public:
		Resolver() : SymTab::Indexer( false ) {}
		Resolver( const SymTab:: Indexer & other ) : SymTab::Indexer( other ) {
			if ( const Resolver * res = dynamic_cast< const Resolver * >( &other ) ) {
				functionReturn = res->functionReturn;
				currentObject = res->currentObject;
				inEnumDecl = res->inEnumDecl;
			}
		}

		typedef SymTab::Indexer Parent;
		using Parent::visit;
		virtual void visit( FunctionDecl *functionDecl ) override;
		virtual void visit( ObjectDecl *functionDecl ) override;
		virtual void visit( TypeDecl *typeDecl ) override;
		virtual void visit( EnumDecl * enumDecl ) override;

		virtual void visit( ArrayType * at ) override;
		virtual void visit( PointerType * at ) override;

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

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

		template< typename PtrType >
		void handlePtrType( PtrType * type );

	  void resolveAggrInit( ReferenceToType *, InitIterator &, InitIterator & );
	  void resolveSingleAggrInit( Declaration *, InitIterator &, InitIterator &, TypeSubstitution sub );
	  void fallbackInit( ConstructorInit * ctorInit );

		Type * functionReturn = nullptr;
		CurrentObject currentObject = nullptr;
		bool inEnumDecl = false;
	};

	void resolve( std::list< Declaration * > translationUnit ) {
		Resolver resolver;
		acceptAll( translationUnit, resolver );
	}

	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
			assertf( finder.get_alternatives().size() == 1, "findSingleExpression: must have exactly one alternative at the end." );
			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 if ( dynamic_cast< ZeroType* >( type ) != nullptr || dynamic_cast< OneType* >( type ) != nullptr ) {
				return true;
			} 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_result()->size() == 1 && isIntegralType( i->expr->get_result() ) ) {
					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.
		ValueGuard<CurrentObject> temp( currentObject );
		currentObject = CurrentObject( objectDecl->get_type() );
		if ( inEnumDecl && dynamic_cast< EnumInstType * >( objectDecl->get_type() ) ) {
			// enumerator initializers should not use the enum type to initialize, since
			// the enum type is still incomplete at this point. Use signed int instead.
			currentObject = CurrentObject( new BasicType( Type::Qualifiers(), BasicType::SignedInt ) );
		}
		Parent::visit( objectDecl );
		if ( inEnumDecl && dynamic_cast< EnumInstType * >( objectDecl->get_type() ) ) {
			// delete newly created signed int type
			// delete currentObject.getType();
		}
	}

	template< typename PtrType >
	void Resolver::handlePtrType( PtrType * type ) {
		if ( type->get_dimension() ) {
			CastExpr *castExpr = new CastExpr( type->get_dimension(), SymTab::SizeType->clone() );
			Expression *newExpr = findSingleExpression( castExpr, *this );
			delete type->get_dimension();
			type->set_dimension( newExpr );
		}
	}

	void Resolver::visit( ArrayType * at ) {
		handlePtrType( at );
		Parent::visit( at );
	}

	void Resolver::visit( PointerType * pt ) {
		handlePtrType( pt );
		Parent::visit( pt );
	}

	void Resolver::visit( TypeDecl *typeDecl ) {
		if ( typeDecl->get_base() ) {
			Type *new_type = resolveTypeof( typeDecl->get_base(), *this );
			typeDecl->set_base( new_type );
		} // if
		Parent::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 );
		ValueGuard< Type * > oldFunctionReturn( functionReturn );
		functionReturn = ResolvExpr::extractResultType( functionDecl->get_functionType() );
		Parent::visit( functionDecl );

		// default value expressions have an environment which shouldn't be there and trips up later passes.
		// xxx - it might be necessary to somehow keep the information from this environment, but I can't currently
		// see how it's useful.
		for ( Declaration * d : functionDecl->get_functionType()->get_parameters() ) {
			if ( ObjectDecl * obj = dynamic_cast< ObjectDecl * >( d ) ) {
				if ( SingleInit * init = dynamic_cast< SingleInit * >( obj->get_init() ) ) {
					delete init->get_value()->get_env();
					init->get_value()->set_env( nullptr );
				}
			}
		}
	}

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

	void Resolver::visit( ExprStmt *exprStmt ) {
		assertf( exprStmt->get_expr(), "ExprStmt has null Expression in resolver" );
		Expression *newExpr = findVoidExpression( exprStmt->get_expr(), *this );
		delete exprStmt->get_expr();
		exprStmt->set_expr( newExpr );
	}

	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 );
		Parent::visit( ifStmt );
	}

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

	void Resolver::visit( ForStmt *forStmt ) {
		Parent::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
	}

	void Resolver::visit( SwitchStmt *switchStmt ) {
		ValueGuard< CurrentObject > oldCurrentObject( currentObject );
		Expression *newExpr;
		newExpr = findIntegralExpression( switchStmt->get_condition(), *this );
		delete switchStmt->get_condition();
		switchStmt->set_condition( newExpr );

		currentObject = CurrentObject( newExpr->get_result() );
		Parent::visit( switchStmt );
	}

	void Resolver::visit( CaseStmt *caseStmt ) {
		if ( caseStmt->get_condition() ) {
			std::list< InitAlternative > initAlts = currentObject.getOptions();
			assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral expression." );
			CastExpr * castExpr = new CastExpr( caseStmt->get_condition(), initAlts.front().type->clone() );
			Expression * newExpr = findSingleExpression( castExpr, *this );
			castExpr = safe_dynamic_cast< CastExpr * >( newExpr );
			caseStmt->set_condition( castExpr->get_arg() );
			castExpr->set_arg( nullptr );
			delete castExpr;
		}
		Parent::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(), functionReturn->clone() );
			Expression *newExpr = findSingleExpression( castExpr, *this );
			delete castExpr;
			returnStmt->set_expr( newExpr );
		} // if
	}

	void Resolver::visit( ThrowStmt *throwStmt ) {
		if ( throwStmt->get_expr() ) {
			Expression * wrapped = new CastExpr( throwStmt->get_expr(), new BasicType( Type::Qualifiers(), BasicType::SignedInt ) );
			Expression * newExpr = findSingleExpression( wrapped, *this );
			throwStmt->set_expr( newExpr );
		}
	}

	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 ) {
		// resolve initialization using the possibilities as determined by the currentObject cursor
		UntypedInitExpr * untyped = new UntypedInitExpr( singleInit->get_value(), currentObject.getOptions() );
		Expression * newExpr = findSingleExpression( untyped, *this );
		InitExpr * initExpr = safe_dynamic_cast< InitExpr * >( newExpr );

		// move cursor to the object that is actually initialized
		currentObject.setNext( initExpr->get_designation() );

		// discard InitExpr wrapper and retain relevant pieces
		newExpr = initExpr->get_expr();
		newExpr->set_env( initExpr->get_env() );
		initExpr->set_expr( nullptr );
		initExpr->set_env( nullptr );
		delete initExpr;

		// get the actual object's type (may not exactly match what comes back from the resolver due to conversions)
		Type * initContext = currentObject.getCurrentType();

		// check if actual object's 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_result() ) ) {
					if ( isCharType( pt->get_base() ) ) {
						// strip cast if we're initializing a char[] with a char *, e.g.  char x[] = "hello";
						CastExpr *ce = safe_dynamic_cast< CastExpr * >( newExpr );
						newExpr = ce->get_arg();
						ce->set_arg( nullptr );
						delete ce;
					}
				}
			}
		}

		// set initializer expr to resolved express
		singleInit->set_value( newExpr );

		// move cursor to next object in preparation for next initializer
		currentObject.increment();
	}

	void Resolver::visit( ListInit * listInit ) {
		// move cursor into brace-enclosed initializer-list
		currentObject.enterListInit();
		// xxx - fix this so that the list isn't copied, iterator should be used to change current element
		std::list<Designation *> newDesignations;
		for ( auto p : group_iterate(listInit->get_designations(), listInit->get_initializers()) ) {
			// iterate designations and initializers in pairs, moving the cursor to the current designated object and resolving
			// the initializer against that object.
			Designation * des = std::get<0>(p);
			Initializer * init = std::get<1>(p);
			newDesignations.push_back( currentObject.findNext( des ) );
			init->accept( *this );
		}
		// set the set of 'resolved' designations and leave the brace-enclosed initializer-list
		listInit->get_designations() = newDesignations; // xxx - memory management
		currentObject.exitListInit();

		// xxx - this part has not be folded into CurrentObject yet
		// } else if ( TypeInstType * tt = dynamic_cast< TypeInstType * >( initContext ) ) {
		// 	Type * base = tt->get_baseType()->get_base();
		// 	if ( base ) {
		// 		// know the implementation type, so try using that as the initContext
		// 		ObjectDecl tmpObj( "", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, base->clone(), nullptr );
		// 		currentObject = &tmpObj;
		// 		visit( listInit );
		// 	} else {
		// 		// missing implementation type -- might be an unknown type variable, so try proceeding with the current init context
		// 		Parent::visit( listInit );
		// 	}
		// } else {
	}

	// 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 );
		delete ctorInit->get_dtor();
		ctorInit->set_dtor( NULL );
		maybeAccept( ctorInit->get_init(), *this );
	}

	// needs to be callable from outside the resolver, so this is a standalone function
	void resolveCtorInit( ConstructorInit * ctorInit, const SymTab::Indexer & indexer ) {
		assert( ctorInit );
		Resolver resolver( indexer );
		ctorInit->accept( resolver );
	}

	void resolveStmtExpr( StmtExpr * stmtExpr, const SymTab::Indexer & indexer ) {
		assert( stmtExpr );
		Resolver resolver( indexer );
		stmtExpr->accept( resolver );
	}

	void Resolver::visit( ConstructorInit *ctorInit ) {
		// xxx - fallback init has been removed => remove fallbackInit function and remove complexity from FixInit and remove C-init from ConstructorInit
		maybeAccept( ctorInit->get_ctor(), *this );
		maybeAccept( ctorInit->get_dtor(), *this );

		// 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::isIntrinsicSingleArgCallStmt( ctorInit->get_ctor() ) ) {
			delete ctorInit->get_ctor();
			ctorInit->set_ctor( NULL );
		}

		if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->get_dtor() ) ) {
			delete ctorInit->get_dtor();
			ctorInit->set_dtor( NULL );
		}

		// xxx - todo -- what about arrays?
		// if ( dtor == NULL && InitTweak::isIntrinsicCallStmt( ctorInit->get_ctor() ) ) {
		// 	// can reduce the constructor down to a SingleInit using the
		// 	// second argument from the ctor call, since
		// 	delete ctorInit->get_ctor();
		// 	ctorInit->set_ctor( NULL );

		// 	Expression * arg =
		// 	ctorInit->set_init( new SingleInit( arg ) );
		// }
	}
} // namespace ResolvExpr

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