//
// 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 : Tue Jul 12 17:45:42 2016
// Update Count     : 204
//

#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 "SymTab/Autogen.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( PointerType * 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( CaseStmt *caseStmt );
		virtual void visit( BranchStmt *branchStmt );
		virtual void visit( ReturnStmt *returnStmt );

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

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

	  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;
	}

	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 );
		Visitor::visit( at );
	}

	void Resolver::visit( PointerType * pt ) {
		handlePtrType( pt );
		Visitor::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
		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( 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();
		InitIterator end = listInit->end();

		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 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
				initContext = base;
				visit( listInit );
			} else {
				// missing implementation type -- might be an unknown type variable, so try proceeding with the current init context
				Visitor::visit( listInit );
			}
		} else {
			assert( dynamic_cast< BasicType * >( initContext ) || dynamic_cast< PointerType * >( initContext ) );
			// 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 );
		delete ctorInit->get_dtor();
		ctorInit->set_dtor( 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::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: //
