//
// 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 : Sat Feb 17 11:19:40 2018
// Update Count     : 213
//

#include <stddef.h>                      // for NULL
#include <cassert>                       // for strict_dynamic_cast, assert
#include <memory>                        // for allocator, allocator_traits<...
#include <tuple>                         // for get
#include <vector>

#include "Alternative.h"                 // for Alternative, AltList
#include "AlternativeFinder.h"           // for AlternativeFinder, resolveIn...
#include "Common/PassVisitor.h"          // for PassVisitor
#include "Common/SemanticError.h"        // for SemanticError
#include "Common/utility.h"              // for ValueGuard, group_iterate
#include "CurrentObject.h"               // for CurrentObject
#include "InitTweak/GenInit.h"
#include "InitTweak/InitTweak.h"         // for isIntrinsicSingleArgCallStmt
#include "RenameVars.h"                  // for RenameVars, global_renamer
#include "ResolvExpr/TypeEnvironment.h"  // for TypeEnvironment
#include "ResolveTypeof.h"               // for resolveTypeof
#include "Resolver.h"
#include "SymTab/Autogen.h"              // for SizeType
#include "SymTab/Indexer.h"              // for Indexer
#include "SynTree/Declaration.h"         // for ObjectDecl, TypeDecl, Declar...
#include "SynTree/Expression.h"          // for Expression, CastExpr, InitExpr
#include "SynTree/Initializer.h"         // for ConstructorInit, SingleInit
#include "SynTree/Statement.h"           // for ForStmt, Statement, BranchStmt
#include "SynTree/Type.h"                // for Type, BasicType, PointerType
#include "SynTree/TypeSubstitution.h"    // for TypeSubstitution
#include "SynTree/Visitor.h"             // for acceptAll, maybeAccept
#include "Tuples/Tuples.h"
#include "typeops.h"                     // for extractResultType
#include "Unify.h"                       // for unify

using namespace std;

namespace ResolvExpr {
	struct Resolver final : public WithIndexer, public WithGuards, public WithVisitorRef<Resolver>, public WithShortCircuiting, public WithStmtsToAdd {
		Resolver() {}
		Resolver( const SymTab::Indexer & other ) {
			indexer = other;
		}

		void previsit( FunctionDecl *functionDecl );
		void postvisit( FunctionDecl *functionDecl );
		void previsit( ObjectDecl *objectDecll );
		void previsit( TypeDecl *typeDecl );
		void previsit( EnumDecl * enumDecl );
		void previsit( StaticAssertDecl * assertDecl );

		void previsit( ArrayType * at );
		void previsit( PointerType * at );

		void previsit( ExprStmt *exprStmt );
		void previsit( AsmExpr *asmExpr );
		void previsit( AsmStmt *asmStmt );
		void previsit( IfStmt *ifStmt );
		void previsit( WhileStmt *whileStmt );
		void previsit( ForStmt *forStmt );
		void previsit( SwitchStmt *switchStmt );
		void previsit( CaseStmt *caseStmt );
		void previsit( BranchStmt *branchStmt );
		void previsit( ReturnStmt *returnStmt );
		void previsit( ThrowStmt *throwStmt );
		void previsit( CatchStmt *catchStmt );
		void previsit( WaitForStmt * stmt );
		void previsit( WithStmt * withStmt );

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

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

		void resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts );
		void fallbackInit( ConstructorInit * ctorInit );

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

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

	void resolveDecl( Declaration * decl, const SymTab::Indexer &indexer ) {
		PassVisitor<Resolver> resolver( indexer );
		maybeAccept( decl, resolver );
	}

	namespace {
		struct DeleteFinder : public WithShortCircuiting	{
			DeletedExpr * delExpr = nullptr;
			void previsit( DeletedExpr * expr ) {
				if ( delExpr ) visit_children = false;
				else delExpr = expr;
			}

			void previsit( Expression * ) {
				if ( delExpr ) visit_children = false;
			}
		};
	}

	DeletedExpr * findDeletedExpr( Expression * expr ) {
		PassVisitor<DeleteFinder> finder;
		expr->accept( finder );
		return finder.pass.delExpr;
	}

	namespace {
		struct StripCasts {
			Expression * postmutate( CastExpr * castExpr ) {
				if ( castExpr->isGenerated && ResolvExpr::typesCompatible( castExpr->arg->result, castExpr->result, SymTab::Indexer() ) ) {
					// generated cast is to the same type as its argument, so it's unnecessary -- remove it
					Expression * expr = castExpr->arg;
					castExpr->arg = nullptr;
					std::swap( expr->env, castExpr->env );
					return expr;
				}
				return castExpr;
			}

			static void strip( Expression *& expr ) {
				PassVisitor<StripCasts> stripper;
				expr = expr->acceptMutator( stripper );
			}
		};

		void finishExpr( Expression *&expr, const TypeEnvironment &env, TypeSubstitution * oldenv = nullptr ) {
			expr->env = oldenv ? oldenv->clone() : new TypeSubstitution;
			env.makeSubstitution( *expr->env );
			StripCasts::strip( expr ); // remove unnecessary casts that may be buried in an expression
		}

		void removeExtraneousCast( Expression *& expr, const SymTab::Indexer & indexer ) {
			if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
				if ( ResolvExpr::typesCompatible( castExpr->arg->result, castExpr->result, indexer ) ) {
					// cast is to the same type as its argument, so it's unnecessary -- remove it
					expr = castExpr->arg;
					castExpr->arg = nullptr;
					std::swap( expr->env, castExpr->env );
					delete castExpr;
				}
			}
		}
	} // namespace

	namespace {
		void findUnfinishedKindExpression(Expression * untyped, Alternative & alt, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, bool adjust = false, bool prune = true, bool failFast = true) {
			assertf( untyped, "expected a non-null expression." );
			TypeEnvironment env;
			AlternativeFinder finder( indexer, env );
			finder.find( untyped, adjust, prune, failFast );

			#if 0
			if ( finder.get_alternatives().size() != 1 ) {
				std::cerr << "untyped expr is ";
				untyped->print( std::cerr );
				std::cerr << std::endl << "alternatives are:";
				for ( const Alternative & alt : finder.get_alternatives() ) {
					alt.print( std::cerr );
				} // for
			} // if
			#endif

			AltList candidates;
			for ( Alternative & alt : finder.get_alternatives() ) {
				if ( pred( alt ) ) {
					candidates.push_back( std::move( alt ) );
				}
			}

			// xxx - if > 1 alternative with same cost, ignore deleted and pick from remaining
			// choose the lowest cost expression among the candidates
			AltList winners;
			findMinCost( candidates.begin(), candidates.end(), back_inserter( winners ) );
			if ( winners.size() == 0 ) {
				SemanticError( untyped, toString( "No reasonable alternatives for ", kindStr, (kindStr != "" ? " " : ""), "expression: ") );
			} else if ( winners.size() != 1 ) {
				std::ostringstream stream;
				stream << "Cannot choose between " << winners.size() << " alternatives for " << kindStr << (kindStr != "" ? " " : "") << "expression\n";
				untyped->print( stream );
				stream << " Alternatives are:\n";
				printAlts( winners, stream, 1 );
				SemanticError( untyped->location, stream.str() );
			}

			// there is one unambiguous interpretation - move the expression into the with statement
			Alternative & choice = winners.front();
			if ( findDeletedExpr( choice.expr ) ) {
				SemanticError( untyped->location, choice.expr, "Unique best alternative includes deleted identifier in " );
			}
			alt = std::move( choice );
		}

		/// resolve `untyped` to the expression whose alternative satisfies `pred` with the lowest cost; kindStr is used for providing better error messages
		void findKindExpression(Expression *& untyped, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, bool adjust = false, bool prune = true, bool failFast = true) {
			if ( ! untyped ) return;
			Alternative choice;
			findUnfinishedKindExpression( untyped, choice, indexer, kindStr, pred, adjust, prune, failFast );
			finishExpr( choice.expr, choice.env, untyped->env );
			delete untyped;
			untyped = choice.expr;
			choice.expr = nullptr;
		}

		bool standardAlternativeFilter( const Alternative & ) {
			// currently don't need to filter, under normal circumstances.
			// in the future, this may be useful for removing deleted expressions
			return true;
		}
	} // namespace

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

	Expression * resolveInVoidContext( Expression *expr, const SymTab::Indexer &indexer, TypeEnvironment &env ) {
		// it's a property of the language that a cast expression has either 1 or 0 interpretations; if it has 0
		// interpretations, an exception has already been thrown.
		assertf( expr, "expected a non-null expression." );

		static CastExpr untyped( nullptr ); // cast to void
		untyped.location = expr->location;

		// set up and resolve expression cast to void
		untyped.arg = expr;
		Alternative choice;
		findUnfinishedKindExpression( &untyped, choice, indexer, "", standardAlternativeFilter, true );
		CastExpr * castExpr = strict_dynamic_cast< CastExpr * >( choice.expr );
		env = std::move( choice.env );

		// clean up resolved expression
		Expression * ret = castExpr->arg;
		castExpr->arg = nullptr;

		// unlink the arg so that it isn't deleted twice at the end of the program
		untyped.arg = nullptr;
		return ret;
	}

	void findVoidExpression( Expression *& untyped, const SymTab::Indexer &indexer ) {
		resetTyVarRenaming();
		TypeEnvironment env;
		Expression * newExpr = resolveInVoidContext( untyped, indexer, env );
		finishExpr( newExpr, env, untyped->env );
		delete untyped;
		untyped = newExpr;
	}

	void findSingleExpression( Expression *&untyped, const SymTab::Indexer &indexer ) {
		findKindExpression( untyped, indexer, "", standardAlternativeFilter );
	}

	void findSingleExpression( Expression *& untyped, Type * type, const SymTab::Indexer & indexer ) {
		assert( untyped && type );
		// transfer location to generated cast for error purposes
		CodeLocation location = untyped->location;
		untyped = new CastExpr( untyped, type );
		untyped->location = location;
		findSingleExpression( untyped, indexer );
		removeExtraneousCast( untyped, indexer );
	}

	namespace {
		bool isIntegralType( const Alternative & alt ) {
			Type * type = alt.expr->result;
			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
		}

		void findIntegralExpression( Expression *& untyped, const SymTab::Indexer &indexer ) {
			findKindExpression( untyped, indexer, "condition", isIntegralType );
		}
	}

	void Resolver::previsit( ObjectDecl *objectDecl ) {
		Type *new_type = resolveTypeof( objectDecl->get_type(), indexer );
		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.
		GuardValue( 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 ) );
		}
	}

	template< typename PtrType >
	void Resolver::handlePtrType( PtrType * type ) {
		if ( type->get_dimension() ) {
			findSingleExpression( type->dimension, SymTab::SizeType->clone(), indexer );
		}
	}

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

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

	void Resolver::previsit( TypeDecl *typeDecl ) {
		if ( typeDecl->get_base() ) {
			Type *new_type = resolveTypeof( typeDecl->get_base(), indexer );
			typeDecl->set_base( new_type );
		} // if
	}

	void Resolver::previsit( FunctionDecl *functionDecl ) {
#if 0
		std::cerr << "resolver visiting functiondecl ";
		functionDecl->print( std::cerr );
		std::cerr << std::endl;
#endif
		Type *new_type = resolveTypeof( functionDecl->type, indexer );
		functionDecl->set_type( new_type );
		GuardValue( functionReturn );
		functionReturn = ResolvExpr::extractResultType( functionDecl->type );

		{
			// resolve with-exprs with parameters in scope and add any newly generated declarations to the
			// front of the function body.
			auto guard = makeFuncGuard( [this]() { indexer.enterScope(); }, [this](){ indexer.leaveScope(); } );
			indexer.addFunctionType( functionDecl->type );
			std::list< Statement * > newStmts;
			resolveWithExprs( functionDecl->withExprs, newStmts );
			if ( functionDecl->statements ) {
				functionDecl->statements->kids.splice( functionDecl->statements->kids.begin(), newStmts );
			} else {
				assertf( functionDecl->withExprs.empty() && newStmts.empty(), "Function %s without a body has with-clause and/or generated with declarations.", functionDecl->name.c_str() );
			}
		}
	}

	void Resolver::postvisit( FunctionDecl *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->type->parameters ) {
			if ( ObjectDecl * obj = dynamic_cast< ObjectDecl * >( d ) ) {
				if ( SingleInit * init = dynamic_cast< SingleInit * >( obj->init ) ) {
					delete init->value->env;
					init->value->env = nullptr;
				}
			}
		}
	}

	void Resolver::previsit( EnumDecl * ) {
		// in case we decide to allow nested enums
		GuardValue( inEnumDecl );
		inEnumDecl = true;
	}

	void Resolver::previsit( StaticAssertDecl * assertDecl ) {
		findIntegralExpression( assertDecl->condition, indexer );
	}

	void Resolver::previsit( ExprStmt *exprStmt ) {
		visit_children = false;
		assertf( exprStmt->expr, "ExprStmt has null Expression in resolver" );
		findVoidExpression( exprStmt->expr, indexer );
	}

	void Resolver::previsit( AsmExpr *asmExpr ) {
		visit_children = false;
		findVoidExpression( asmExpr->operand, indexer );
		if ( asmExpr->get_inout() ) {
			findVoidExpression( asmExpr->inout, indexer );
		} // if
	}

	void Resolver::previsit( AsmStmt *asmStmt ) {
		visit_children = false;
		acceptAll( asmStmt->get_input(), *visitor );
		acceptAll( asmStmt->get_output(), *visitor );
	}

	void Resolver::previsit( IfStmt *ifStmt ) {
		findIntegralExpression( ifStmt->condition, indexer );
	}

	void Resolver::previsit( WhileStmt *whileStmt ) {
		findIntegralExpression( whileStmt->condition, indexer );
	}

	void Resolver::previsit( ForStmt *forStmt ) {
		if ( forStmt->condition ) {
			findIntegralExpression( forStmt->condition, indexer );
		} // if

		if ( forStmt->increment ) {
			findVoidExpression( forStmt->increment, indexer );
		} // if
	}

	void Resolver::previsit( SwitchStmt *switchStmt ) {
		GuardValue( currentObject );
		findIntegralExpression( switchStmt->condition, indexer );

		currentObject = CurrentObject( switchStmt->condition->result );
	}

	void Resolver::previsit( CaseStmt *caseStmt ) {
		if ( caseStmt->condition ) {
			std::list< InitAlternative > initAlts = currentObject.getOptions();
			assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral expression." );
			// must remove cast from case statement because RangeExpr cannot be cast.
			Expression * newExpr = new CastExpr( caseStmt->condition, initAlts.front().type->clone() );
			findSingleExpression( newExpr, indexer );
			// case condition cannot have a cast in C, so it must be removed, regardless of whether it performs a conversion.
			// Ideally we would perform the conversion internally here.
			if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( newExpr ) ) {
				newExpr = castExpr->arg;
				castExpr->arg = nullptr;
				std::swap( newExpr->env, castExpr->env );
				delete castExpr;
			}
			caseStmt->condition = newExpr;
		}
	}

	void Resolver::previsit( BranchStmt *branchStmt ) {
		visit_children = false;
		// must resolve the argument for a computed goto
		if ( branchStmt->get_type() == BranchStmt::Goto ) { // check for computed goto statement
			if ( branchStmt->computedTarget ) {
				// computed goto argument is void *
				findSingleExpression( branchStmt->computedTarget, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), indexer );
			} // if
		} // if
	}

	void Resolver::previsit( ReturnStmt *returnStmt ) {
		visit_children = false;
		if ( returnStmt->expr ) {
			findSingleExpression( returnStmt->expr, functionReturn->clone(), indexer );
		} // if
	}

	void Resolver::previsit( ThrowStmt *throwStmt ) {
		visit_children = false;
		// TODO: Replace *exception type with &exception type.
		if ( throwStmt->get_expr() ) {
			StructDecl * exception_decl =
				indexer.lookupStruct( "__cfaabi_ehm__base_exception_t" );
			assert( exception_decl );
			Type * exceptType = new PointerType( noQualifiers, new StructInstType( noQualifiers, exception_decl ) );
			findSingleExpression( throwStmt->expr, exceptType, indexer );
		}
	}

	void Resolver::previsit( CatchStmt *catchStmt ) {
		if ( catchStmt->cond ) {
			findSingleExpression( catchStmt->cond, new BasicType( noQualifiers, BasicType::Bool ), indexer );
		}
	}

	template< typename iterator_t >
	inline bool advance_to_mutex( iterator_t & it, const iterator_t & end ) {
		while( it != end && !(*it)->get_type()->get_mutex() ) {
			it++;
		}

		return it != end;
	}

	void Resolver::previsit( WaitForStmt * stmt ) {
		visit_children = false;

		// Resolve all clauses first
		for( auto& clause : stmt->clauses ) {

			TypeEnvironment env;
			AlternativeFinder funcFinder( indexer, env );

			// Find all alternatives for a function in canonical form
			funcFinder.findWithAdjustment( clause.target.function );

			if ( funcFinder.get_alternatives().empty() ) {
				stringstream ss;
				ss << "Use of undeclared indentifier '";
				ss << strict_dynamic_cast<NameExpr*>( clause.target.function )->name;
				ss << "' in call to waitfor";
				SemanticError( stmt->location, ss.str() );
			}

			if(clause.target.arguments.empty()) {
				SemanticError( stmt->location, "Waitfor clause must have at least one mutex parameter");
			}

			// Find all alternatives for all arguments in canonical form
			std::vector< AlternativeFinder > argAlternatives;
			funcFinder.findSubExprs( clause.target.arguments.begin(), clause.target.arguments.end(), back_inserter( argAlternatives ) );

			// List all combinations of arguments
			std::vector< AltList > possibilities;
			combos( argAlternatives.begin(), argAlternatives.end(), back_inserter( possibilities ) );

			AltList                func_candidates;
			std::vector< AltList > args_candidates;

			// For every possible function :
			// 	try matching the arguments to the parameters
			// 	not the other way around because we have more arguments than parameters
			SemanticErrorException errors;
			for ( Alternative & func : funcFinder.get_alternatives() ) {
				try {
					PointerType * pointer = dynamic_cast< PointerType* >( func.expr->get_result()->stripReferences() );
					if( !pointer ) {
						SemanticError( func.expr->get_result(), "candidate not viable: not a pointer type\n" );
					}

					FunctionType * function = dynamic_cast< FunctionType* >( pointer->get_base() );
					if( !function ) {
						SemanticError( pointer->get_base(), "candidate not viable: not a function type\n" );
					}


					{
						auto param     = function->parameters.begin();
						auto param_end = function->parameters.end();

						if( !advance_to_mutex( param, param_end ) ) {
							SemanticError(function, "candidate function not viable: no mutex parameters\n");
						}
					}

					Alternative newFunc( func );
					// Strip reference from function
					referenceToRvalueConversion( newFunc.expr, newFunc.cost );

					// For all the set of arguments we have try to match it with the parameter of the current function alternative
					for ( auto & argsList : possibilities ) {

						try {
							// Declare data structures need for resolution
							OpenVarSet openVars;
							AssertionSet resultNeed, resultHave;
							TypeEnvironment resultEnv( func.env );
							makeUnifiableVars( function, openVars, resultNeed );
							// add all type variables as open variables now so that those not used in the parameter
							// list are still considered open.
							resultEnv.add( function->forall );

							// Load type variables from arguemnts into one shared space
							simpleCombineEnvironments( argsList.begin(), argsList.end(), resultEnv );

							// Make sure we don't widen any existing bindings
							resultEnv.forbidWidening();

							// Find any unbound type variables
							resultEnv.extractOpenVars( openVars );

							auto param     = function->parameters.begin();
							auto param_end = function->parameters.end();

							int n_mutex_param = 0;

							// For every arguments of its set, check if it matches one of the parameter
							// The order is important
							for( auto & arg : argsList ) {

								// Ignore non-mutex arguments
								if( !advance_to_mutex( param, param_end ) ) {
									// We ran out of parameters but still have arguments
									// this function doesn't match
									SemanticError( function, toString("candidate function not viable: too many mutex arguments, expected ", n_mutex_param, "\n" ));
								}

								n_mutex_param++;

								// Check if the argument matches the parameter type in the current scope
								if( ! unify( arg.expr->get_result(), (*param)->get_type(), resultEnv, resultNeed, resultHave, openVars, this->indexer ) ) {
									// Type doesn't match
									stringstream ss;
									ss << "candidate function not viable: no known convertion from '";
									(*param)->get_type()->print( ss );
									ss << "' to '";
									arg.expr->get_result()->print( ss );
									ss << "' with env '";
									resultEnv.print(ss);
									ss << "'\n";
									SemanticError( function, ss.str() );
								}

								param++;
							}

							// All arguments match !

							// Check if parameters are missing
							if( advance_to_mutex( param, param_end ) ) {
								do {
									n_mutex_param++;
									param++;
								} while( advance_to_mutex( param, param_end ) );

								// We ran out of arguments but still have parameters left
								// this function doesn't match
								SemanticError( function, toString("candidate function not viable: too few mutex arguments, expected ", n_mutex_param, "\n" ));
							}

							// All parameters match !

							// Finish the expressions to tie in the proper environments
							finishExpr( newFunc.expr, resultEnv );
							for( Alternative & alt : argsList ) {
								finishExpr( alt.expr, resultEnv );
							}

							// This is a match store it and save it for later
							func_candidates.push_back( newFunc );
							args_candidates.push_back( argsList );

						}
						catch( SemanticErrorException &e ) {
							errors.append( e );
						}
					}
				}
				catch( SemanticErrorException &e ) {
					errors.append( e );
				}
			}

			// Make sure we got the right number of arguments
			if( func_candidates.empty() )    { SemanticErrorException top( stmt->location, "No alternatives for function in call to waitfor"  ); top.append( errors ); throw top; }
			if( args_candidates.empty() )    { SemanticErrorException top( stmt->location, "No alternatives for arguments in call to waitfor" ); top.append( errors ); throw top; }
			if( func_candidates.size() > 1 ) { SemanticErrorException top( stmt->location, "Ambiguous function in call to waitfor"            ); top.append( errors ); throw top; }
			if( args_candidates.size() > 1 ) { SemanticErrorException top( stmt->location, "Ambiguous arguments in call to waitfor"           ); top.append( errors ); throw top; }
			// TODO: need to use findDeletedExpr to ensure no deleted identifiers are used.

			// Swap the results from the alternative with the unresolved values.
			// Alternatives will handle deletion on destruction
			std::swap( clause.target.function, func_candidates.front().expr );
			for( auto arg_pair : group_iterate( clause.target.arguments, args_candidates.front() ) ) {
				std::swap ( std::get<0>( arg_pair), std::get<1>( arg_pair).expr );
			}

			// Resolve the conditions as if it were an IfStmt
			// Resolve the statments normally
			findSingleExpression( clause.condition, this->indexer );
			clause.statement->accept( *visitor );
		}


		if( stmt->timeout.statement ) {
			// Resolve the timeout as an size_t for now
			// Resolve the conditions as if it were an IfStmt
			// Resolve the statments normally
			findSingleExpression( stmt->timeout.time, new BasicType( noQualifiers, BasicType::LongLongUnsignedInt ), this->indexer );
			findSingleExpression( stmt->timeout.condition, this->indexer );
			stmt->timeout.statement->accept( *visitor );
		}

		if( stmt->orelse.statement ) {
			// Resolve the conditions as if it were an IfStmt
			// Resolve the statments normally
			findSingleExpression( stmt->orelse.condition, this->indexer );
			stmt->orelse.statement->accept( *visitor );
		}
	}

	bool isStructOrUnion( const Alternative & alt ) {
		Type * t = alt.expr->result->stripReferences();
		return dynamic_cast< StructInstType * >( t ) || dynamic_cast< UnionInstType * >( t );
	}

	void Resolver::resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts ) {
		for ( Expression *& expr : withExprs )  {
			// only struct- and union-typed expressions are viable candidates
			findKindExpression( expr, indexer, "with statement", isStructOrUnion );

			// if with expression might be impure, create a temporary so that it is evaluated once
			if ( Tuples::maybeImpure( expr ) ) {
				static UniqueName tmpNamer( "_with_tmp_" );
				ObjectDecl * tmp = ObjectDecl::newObject( tmpNamer.newName(), expr->result->clone(), new SingleInit( expr ) );
				expr = new VariableExpr( tmp );
				newStmts.push_back( new DeclStmt( tmp ) );
				if ( InitTweak::isConstructable( tmp->type ) ) {
					// generate ctor/dtor and resolve them
					tmp->init = InitTweak::genCtorInit( tmp );
					tmp->accept( *visitor );
				}
			}
		}
	}

	void Resolver::previsit( WithStmt * withStmt ) {
		resolveWithExprs( withStmt->exprs, stmtsToAddBefore );
	}

	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::previsit( SingleInit *singleInit ) {
		visit_children = false;
		// resolve initialization using the possibilities as determined by the currentObject cursor
		Expression * newExpr = new UntypedInitExpr( singleInit->value, currentObject.getOptions() );
		findSingleExpression( newExpr, indexer );
		InitExpr * initExpr = strict_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->expr;
		initExpr->expr = nullptr;
		std::swap( initExpr->env, newExpr->env );
		// InitExpr may have inferParams in the case where the expression specializes a function pointer,
		// and newExpr may already have inferParams of its own, so a simple swap is not sufficient.
		newExpr->spliceInferParams( initExpr );
		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();

		removeExtraneousCast( newExpr, indexer );

		// 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() ) ) {
						if ( CastExpr *ce = dynamic_cast< CastExpr * >( newExpr ) ) {
							// strip cast if we're initializing a char[] with a char *, e.g.  char x[] = "hello";
							newExpr = ce->get_arg();
							ce->set_arg( nullptr );
							std::swap( ce->env, newExpr->env );
							delete ce;
						}
					}
				}
			}
		}

		// set initializer expr to resolved express
		singleInit->value = newExpr;

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

	void Resolver::previsit( ListInit * listInit ) {
		visit_children = false;
		// 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( *visitor );
		}
		// 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(), *visitor );
	}

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

	void resolveStmtExpr( StmtExpr * stmtExpr, const SymTab::Indexer & indexer ) {
		assert( stmtExpr );
		PassVisitor<Resolver> resolver( indexer );
		stmtExpr->accept( resolver );
		stmtExpr->computeResult();
		// xxx - aggregate the environments from all statements? Possibly in AlternativeFinder instead?
	}

	void Resolver::previsit( ConstructorInit *ctorInit ) {
		visit_children = false;
		// xxx - fallback init has been removed => remove fallbackInit function and remove complexity from FixInit and remove C-init from ConstructorInit
		maybeAccept( ctorInit->ctor, *visitor );
		maybeAccept( ctorInit->dtor, *visitor );

		// found a constructor - can get rid of C-style initializer
		delete ctorInit->init;
		ctorInit->init = nullptr;

		// 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->ctor ) ) {
			delete ctorInit->ctor;
			ctorInit->ctor = nullptr;
		}

		if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->dtor ) ) {
			delete ctorInit->dtor;
			ctorInit->dtor = nullptr;
		}

		// 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: //
