//
// 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.
//
// Unify.cc --
//
// Author           : Richard C. Bilson
// Created On       : Sun May 17 12:27:10 2015
// Last Modified By : Peter A. Buhr
// Last Modified On : Thu Mar 16 16:22:54 2017
// Update Count     : 42
//

#include <cassert>                // for assertf, assert
#include <iterator>               // for back_insert_iterator, back_inserter
#include <map>                    // for _Rb_tree_const_iterator, _Rb_tree_i...
#include <memory>                 // for unique_ptr
#include <set>                    // for set
#include <string>                 // for string, operator==, operator!=, bas...
#include <utility>                // for pair

#include "Common/PassVisitor.h"   // for PassVisitor
#include "FindOpenVars.h"         // for findOpenVars
#include "Parser/LinkageSpec.h"   // for C
#include "SynTree/Constant.h"     // for Constant
#include "SynTree/Declaration.h"  // for TypeDecl, TypeDecl::Data, Declarati...
#include "SynTree/Expression.h"   // for TypeExpr, Expression, ConstantExpr
#include "SynTree/Mutator.h"      // for Mutator
#include "SynTree/Type.h"         // for Type, TypeInstType, FunctionType
#include "SynTree/Visitor.h"      // for Visitor
#include "Tuples/Tuples.h"        // for isTtype
#include "TypeEnvironment.h"      // for EqvClass, AssertionSet, OpenVarSet
#include "Unify.h"
#include "typeops.h"              // for flatten, occurs, commonType

namespace SymTab {
class Indexer;
}  // namespace SymTab

// #define DEBUG

namespace ResolvExpr {

	struct Unify : public WithShortCircuiting {
		Unify( Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer );

		bool get_result() const { return result; }

		void previsit( BaseSyntaxNode * ) { visit_children = false; }

		void postvisit( VoidType * voidType );
		void postvisit( BasicType * basicType );
		void postvisit( PointerType * pointerType );
		void postvisit( ArrayType * arrayType );
		void postvisit( ReferenceType * refType );
		void postvisit( FunctionType * functionType );
		void postvisit( StructInstType * aggregateUseType );
		void postvisit( UnionInstType * aggregateUseType );
		void postvisit( EnumInstType * aggregateUseType );
		void postvisit( TraitInstType * aggregateUseType );
		void postvisit( TypeInstType * aggregateUseType );
		void postvisit( TupleType * tupleType );
		void postvisit( VarArgsType * varArgsType );
		void postvisit( ZeroType * zeroType );
		void postvisit( OneType * oneType );

	  private:
		template< typename RefType > void handleRefType( RefType *inst, Type *other );
		template< typename RefType > void handleGenericRefType( RefType *inst, Type *other );

		bool result;
		Type *type2;				// inherited
		TypeEnvironment &env;
		AssertionSet &needAssertions;
		AssertionSet &haveAssertions;
		const OpenVarSet &openVars;
		WidenMode widenMode;
		const SymTab::Indexer &indexer;
	};

	/// Attempts an inexact unification of type1 and type2.
	/// Returns false if no such unification; if the types can be unified, sets common (unless they unify exactly and have identical type qualifiers)
	bool unifyInexact( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer, Type *&common );
	bool unifyExact( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer );

	bool typesCompatible( Type *first, Type *second, const SymTab::Indexer &indexer, const TypeEnvironment &env ) {
		TypeEnvironment newEnv;
		OpenVarSet openVars, closedVars; // added closedVars
		AssertionSet needAssertions, haveAssertions;
		Type *newFirst = first->clone(), *newSecond = second->clone();
		env.apply( newFirst );
		env.apply( newSecond );

		// do we need to do this? Seems like we do, types should be able to be compatible if they
		// have free variables that can unify
		findOpenVars( newFirst, openVars, closedVars, needAssertions, haveAssertions, false );
		findOpenVars( newSecond, openVars, closedVars, needAssertions, haveAssertions, true );

		bool result = unifyExact( newFirst, newSecond, newEnv, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
		delete newFirst;
		delete newSecond;
		return result;
	}

	bool typesCompatibleIgnoreQualifiers( Type *first, Type *second, const SymTab::Indexer &indexer, const TypeEnvironment &env ) {
		TypeEnvironment newEnv;
		OpenVarSet openVars;
		AssertionSet needAssertions, haveAssertions;
		Type *newFirst = first->clone(), *newSecond = second->clone();
		env.apply( newFirst );
		env.apply( newSecond );
		newFirst->get_qualifiers() = Type::Qualifiers();
		newSecond->get_qualifiers() = Type::Qualifiers();
///   std::cerr << "first is ";
///   first->print( std::cerr );
///   std::cerr << std::endl << "second is ";
///   second->print( std::cerr );
///   std::cerr << std::endl << "newFirst is ";
///   newFirst->print( std::cerr );
///   std::cerr << std::endl << "newSecond is ";
///   newSecond->print( std::cerr );
///   std::cerr << std::endl;
		bool result = unifyExact( newFirst, newSecond, newEnv, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
		delete newFirst;
		delete newSecond;
		return result;
	}

	bool isFtype( Type *type ) {
		if ( dynamic_cast< FunctionType* >( type ) ) {
			return true;
		} else if ( TypeInstType *typeInst = dynamic_cast< TypeInstType* >( type ) ) {
			return typeInst->get_isFtype();
		} // if
		return false;
	}

	bool tyVarCompatible( const TypeDecl::Data & data, Type *type ) {
		switch ( data.kind ) {
		  case TypeDecl::Dtype:
			// to bind to an object type variable, the type must not be a function type.
			// if the type variable is specified to be a complete type then the incoming
			// type must also be complete
			// xxx - should this also check that type is not a tuple type and that it's not a ttype?
			return ! isFtype( type ) && (! data.isComplete || type->isComplete() );
		  case TypeDecl::Ftype:
			return isFtype( type );
		  case TypeDecl::Ttype:
			// ttype unifies with any tuple type
			return dynamic_cast< TupleType * >( type ) || Tuples::isTtype( type );
		} // switch
		return false;
	}

	bool bindVar( TypeInstType *typeInst, Type *other, const TypeDecl::Data & data, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer ) {
		// remove references from other, so that type variables can only bind to value types
		other = other->stripReferences();
		OpenVarSet::const_iterator tyvar = openVars.find( typeInst->get_name() );
		assert( tyvar != openVars.end() );
		if ( ! tyVarCompatible( tyvar->second, other ) ) {
			return false;
		} // if
		if ( occurs( other, typeInst->get_name(), env ) ) {
			return false;
		} // if
		EqvClass curClass;
		if ( env.lookup( typeInst->get_name(), curClass ) ) {
			if ( curClass.type ) {
				Type *common = 0;
				// attempt to unify equivalence class type (which has qualifiers stripped, so they must be restored) with the type to bind to
				std::unique_ptr< Type > newType( curClass.type->clone() );
				newType->get_qualifiers() = typeInst->get_qualifiers();
				if ( unifyInexact( newType.get(), other, env, needAssertions, haveAssertions, openVars, widenMode & WidenMode( curClass.allowWidening, true ), indexer, common ) ) {
					if ( common ) {
						common->get_qualifiers() = Type::Qualifiers();
						delete curClass.type;
						curClass.type = common;
						env.add( curClass );
					} // if
					return true;
				} else {
					return false;
				} // if
			} else {
				curClass.type = other->clone();
				curClass.type->get_qualifiers() = Type::Qualifiers();
				curClass.allowWidening = widenMode.widenFirst && widenMode.widenSecond;
				env.add( curClass );
			} // if
		} else {
			EqvClass newClass;
			newClass.vars.insert( typeInst->get_name() );
			newClass.type = other->clone();
			newClass.type->get_qualifiers() = Type::Qualifiers();
			newClass.allowWidening = widenMode.widenFirst && widenMode.widenSecond;
			newClass.data = data;
			env.add( newClass );
		} // if
		return true;
	}

	bool bindVarToVar( TypeInstType *var1, TypeInstType *var2, const TypeDecl::Data & data, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer ) {
		bool result = true;
		EqvClass class1, class2;
		bool hasClass1 = false, hasClass2 = false;
		bool widen1 = false, widen2 = false;
		Type *type1 = 0, *type2 = 0;

		if ( env.lookup( var1->get_name(), class1 ) ) {
			hasClass1 = true;
			if ( class1.type ) {
				if ( occurs( class1.type, var2->get_name(), env ) ) {
					return false;
				} // if
				type1 = class1.type->clone();
			} // if
			widen1 = widenMode.widenFirst && class1.allowWidening;
		} // if
		if ( env.lookup( var2->get_name(), class2 ) ) {
			hasClass2 = true;
			if ( class2.type ) {
				if ( occurs( class2.type, var1->get_name(), env ) ) {
					return false;
				} // if
				type2 = class2.type->clone();
			} // if
			widen2 = widenMode.widenSecond && class2.allowWidening;
		} // if

		if ( type1 && type2 ) {
//    std::cerr << "has type1 && type2" << std::endl;
			WidenMode newWidenMode ( widen1, widen2 );
			Type *common = 0;
			if ( unifyInexact( type1, type2, env, needAssertions, haveAssertions, openVars, newWidenMode, indexer, common ) ) {
				class1.vars.insert( class2.vars.begin(), class2.vars.end() );
				class1.allowWidening = widen1 && widen2;
				if ( common ) {
					common->get_qualifiers() = Type::Qualifiers();
					delete class1.type;
					class1.type = common;
				} // if
				env.add( class1 );
			} else {
				result = false;
			} // if
		} else if ( hasClass1 && hasClass2 ) {
			if ( type1 ) {
				class1.vars.insert( class2.vars.begin(), class2.vars.end() );
				class1.allowWidening = widen1;
				env.add( class1 );
			} else {
				class2.vars.insert( class1.vars.begin(), class1.vars.end() );
				class2.allowWidening = widen2;
				env.add( class2 );
			} // if
		} else if ( hasClass1 ) {
			class1.vars.insert( var2->get_name() );
			class1.allowWidening = widen1;
			env.add( class1 );
		} else if ( hasClass2 ) {
			class2.vars.insert( var1->get_name() );
			class2.allowWidening = widen2;
			env.add( class2 );
		} else {
			EqvClass newClass;
			newClass.vars.insert( var1->get_name() );
			newClass.vars.insert( var2->get_name() );
			newClass.allowWidening = widen1 && widen2;
			newClass.data = data;
			env.add( newClass );
		} // if
		delete type1;
		delete type2;
		return result;
	}

	bool unify( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, OpenVarSet &openVars, const SymTab::Indexer &indexer ) {
		OpenVarSet closedVars;
		findOpenVars( type1, openVars, closedVars, needAssertions, haveAssertions, false );
		findOpenVars( type2, openVars, closedVars, needAssertions, haveAssertions, true );
		Type *commonType = 0;
		if ( unifyInexact( type1, type2, env, needAssertions, haveAssertions, openVars, WidenMode( true, true ), indexer, commonType ) ) {
			if ( commonType ) {
				delete commonType;
			} // if
			return true;
		} else {
			return false;
		} // if
	}

	bool unify( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, OpenVarSet &openVars, const SymTab::Indexer &indexer, Type *&commonType ) {
		OpenVarSet closedVars;
		findOpenVars( type1, openVars, closedVars, needAssertions, haveAssertions, false );
		findOpenVars( type2, openVars, closedVars, needAssertions, haveAssertions, true );
		return unifyInexact( type1, type2, env, needAssertions, haveAssertions, openVars, WidenMode( true, true ), indexer, commonType );
	}

	bool unifyExact( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer ) {
#ifdef DEBUG
		TypeEnvironment debugEnv( env );
#endif
		if ( type1->get_qualifiers() != type2->get_qualifiers() ) {
			return false;
		}

		bool result;
		TypeInstType *var1 = dynamic_cast< TypeInstType* >( type1 );
		TypeInstType *var2 = dynamic_cast< TypeInstType* >( type2 );
		OpenVarSet::const_iterator entry1, entry2;
		if ( var1 ) {
			entry1 = openVars.find( var1->get_name() );
		} // if
		if ( var2 ) {
			entry2 = openVars.find( var2->get_name() );
		} // if
		bool isopen1 = var1 && ( entry1 != openVars.end() );
		bool isopen2 = var2 && ( entry2 != openVars.end() );

		if ( isopen1 && isopen2 && entry1->second == entry2->second ) {
			result = bindVarToVar( var1, var2, entry1->second, env, needAssertions, haveAssertions, openVars, widenMode, indexer );
		} else if ( isopen1 ) {
			result = bindVar( var1, type2, entry1->second, env, needAssertions, haveAssertions, openVars, widenMode, indexer );
		} else if ( isopen2 ) {
			result = bindVar( var2, type1, entry2->second, env, needAssertions, haveAssertions, openVars, widenMode, indexer );
		} else {
			PassVisitor<Unify> comparator( type2, env, needAssertions, haveAssertions, openVars, widenMode, indexer );
			type1->accept( comparator );
			result = comparator.pass.get_result();
		} // if
#ifdef DEBUG
		std::cerr << "============ unifyExact" << std::endl;
		std::cerr << "type1 is ";
		type1->print( std::cerr );
		std::cerr << std::endl << "type2 is ";
		type2->print( std::cerr );
		std::cerr << std::endl << "openVars are ";
		printOpenVarSet( openVars, std::cerr, 8 );
		std::cerr << std::endl << "input env is " << std::endl;
		debugEnv.print( std::cerr, 8 );
		std::cerr << std::endl << "result env is " << std::endl;
		env.print( std::cerr, 8 );
		std::cerr << "result is " << result << std::endl;
#endif
		return result;
	}

	bool unifyExact( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, OpenVarSet &openVars, const SymTab::Indexer &indexer ) {
		return unifyExact( type1, type2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
	}

	bool unifyInexact( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer, Type *&common ) {
		Type::Qualifiers tq1 = type1->get_qualifiers(), tq2 = type2->get_qualifiers();
		type1->get_qualifiers() = Type::Qualifiers();
		type2->get_qualifiers() = Type::Qualifiers();
		bool result;
#ifdef DEBUG
		std::cerr << "unifyInexact type 1 is ";
		type1->print( std::cerr );
		std::cerr << " type 2 is ";
		type2->print( std::cerr );
		std::cerr << std::endl;
#endif
		if ( ! unifyExact( type1, type2, env, needAssertions, haveAssertions, openVars, widenMode, indexer ) ) {
#ifdef DEBUG
			std::cerr << "unifyInexact: no exact unification found" << std::endl;
#endif
			if ( ( common = commonType( type1, type2, widenMode.widenFirst, widenMode.widenSecond, indexer, env, openVars ) ) ) {
				common->get_qualifiers() = tq1 | tq2;
#ifdef DEBUG
				std::cerr << "unifyInexact: common type is ";
				common->print( std::cerr );
				std::cerr << std::endl;
#endif
				result = true;
			} else {
#ifdef DEBUG
				std::cerr << "unifyInexact: no common type found" << std::endl;
#endif
				result = false;
			} // if
		} else {
			if ( tq1 != tq2 ) {
				if ( ( tq1 > tq2 || widenMode.widenFirst ) && ( tq2 > tq1 || widenMode.widenSecond ) ) {
					common = type1->clone();
					common->get_qualifiers() = tq1 | tq2;
					result = true;
				} else {
					result = false;
				} // if
			} else {
				common = type1->clone();
				common->get_qualifiers() = tq1 | tq2;
				result = true;
			} // if
		} // if
		type1->get_qualifiers() = tq1;
		type2->get_qualifiers() = tq2;
		return result;
	}

	Unify::Unify( Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer )
		: result( false ), type2( type2 ), env( env ), needAssertions( needAssertions ), haveAssertions( haveAssertions ), openVars( openVars ), widenMode( widenMode ), indexer( indexer ) {
	}

	void Unify::postvisit( __attribute__((unused)) VoidType *voidType) {
		result = dynamic_cast< VoidType* >( type2 );
	}

	void Unify::postvisit(BasicType *basicType) {
		if ( BasicType *otherBasic = dynamic_cast< BasicType* >( type2 ) ) {
			result = basicType->get_kind() == otherBasic->get_kind();
		} // if
	}

	void markAssertionSet( AssertionSet &assertions, DeclarationWithType *assert ) {
///   std::cerr << "assertion set is" << std::endl;
///   printAssertionSet( assertions, std::cerr, 8 );
///   std::cerr << "looking for ";
///   assert->print( std::cerr );
///   std::cerr << std::endl;
		AssertionSet::iterator i = assertions.find( assert );
		if ( i != assertions.end() ) {
///     std::cerr << "found it!" << std::endl;
			i->second.isUsed = true;
		} // if
	}

	void markAssertions( AssertionSet &assertion1, AssertionSet &assertion2, Type *type ) {
		for ( std::list< TypeDecl* >::const_iterator tyvar = type->get_forall().begin(); tyvar != type->get_forall().end(); ++tyvar ) {
			for ( std::list< DeclarationWithType* >::const_iterator assert = (*tyvar)->get_assertions().begin(); assert != (*tyvar)->get_assertions().end(); ++assert ) {
				markAssertionSet( assertion1, *assert );
				markAssertionSet( assertion2, *assert );
			} // for
		} // for
	}

	void Unify::postvisit(PointerType *pointerType) {
		if ( PointerType *otherPointer = dynamic_cast< PointerType* >( type2 ) ) {
			result = unifyExact( pointerType->get_base(), otherPointer->get_base(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
			markAssertions( haveAssertions, needAssertions, pointerType );
			markAssertions( haveAssertions, needAssertions, otherPointer );
		} // if
	}

	void Unify::postvisit(ReferenceType *refType) {
		if ( ReferenceType *otherRef = dynamic_cast< ReferenceType* >( type2 ) ) {
			result = unifyExact( refType->get_base(), otherRef->get_base(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
			markAssertions( haveAssertions, needAssertions, refType );
			markAssertions( haveAssertions, needAssertions, otherRef );
		} // if
	}

	void Unify::postvisit(ArrayType *arrayType) {
		ArrayType *otherArray = dynamic_cast< ArrayType* >( type2 );
		// to unify, array types must both be VLA or both not VLA
		// and must both have a dimension expression or not have a dimension
		if ( otherArray && arrayType->get_isVarLen() == otherArray->get_isVarLen() ) {

			if ( ! arrayType->get_isVarLen() && ! otherArray->get_isVarLen() &&
				arrayType->get_dimension() != 0 && otherArray->get_dimension() != 0 ) {
				ConstantExpr * ce1 = dynamic_cast< ConstantExpr * >( arrayType->get_dimension() );
				ConstantExpr * ce2 = dynamic_cast< ConstantExpr * >( otherArray->get_dimension() );
				// see C11 Reference Manual 6.7.6.2.6
				// two array types with size specifiers that are integer constant expressions are
				// compatible if both size specifiers have the same constant value
				if ( ce1 && ce2 ) {
					Constant * c1 = ce1->get_constant();
					Constant * c2 = ce2->get_constant();

					if ( c1->get_value() != c2->get_value() ) {
						// does not unify if the dimension is different
						return;
					}
				}
			}

			result = unifyExact( arrayType->get_base(), otherArray->get_base(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
		} // if
	}

	template< typename Iterator, typename Func >
	std::unique_ptr<Type> combineTypes( Iterator begin, Iterator end, Func & toType ) {
		std::list< Type * > types;
		for ( ; begin != end; ++begin ) {
			// it's guaranteed that a ttype variable will be bound to a flat tuple, so ensure that this results in a flat tuple
			flatten( toType( *begin ), back_inserter( types ) );
		}
		return std::unique_ptr<Type>( new TupleType( Type::Qualifiers(), types ) );
	}

	template< typename Iterator1, typename Iterator2 >
	bool unifyDeclList( Iterator1 list1Begin, Iterator1 list1End, Iterator2 list2Begin, Iterator2 list2End, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, const SymTab::Indexer &indexer ) {
		auto get_type = [](DeclarationWithType * dwt){ return dwt->get_type(); };
		for ( ; list1Begin != list1End && list2Begin != list2End; ++list1Begin, ++list2Begin ) {
			Type * t1 = (*list1Begin)->get_type();
			Type * t2 = (*list2Begin)->get_type();
			bool isTtype1 = Tuples::isTtype( t1 );
			bool isTtype2 = Tuples::isTtype( t2 );
			// xxx - assumes ttype must be last parameter
			// xxx - there may be a nice way to refactor this, but be careful because the argument positioning might matter in some cases.
			if ( isTtype1 && ! isTtype2 ) {
				// combine all of the things in list2, then unify
				return unifyExact( t1, combineTypes( list2Begin, list2End, get_type ).get(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
			} else if ( isTtype2 && ! isTtype1 ) {
				// combine all of the things in list1, then unify
				return unifyExact( combineTypes( list1Begin, list1End, get_type ).get(), t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
			} else if ( ! unifyExact( t1, t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer ) ) {
				return false;
			} // if
		} // for
		// may get to the end of one argument list before the end of the other. This is only okay when the other is a ttype
		if ( list1Begin != list1End ) {
			// try unifying empty tuple type with ttype
			Type * t1 = (*list1Begin)->get_type();
			if ( Tuples::isTtype( t1 ) ) {
				return unifyExact( t1, combineTypes( list2Begin, list2End, get_type ).get(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
			} else return false;
		} else if ( list2Begin != list2End ) {
			// try unifying empty tuple type with ttype
			Type * t2 = (*list2Begin)->get_type();
			if ( Tuples::isTtype( t2 ) ) {
				return unifyExact( combineTypes( list1Begin, list1End, get_type ).get(), t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
			} else return false;
		} else {
			return true;
		} // if
	}

	/// Finds ttypes and replaces them with their expansion, if known.
	/// This needs to be done so that satisfying ttype assertions is easier.
	/// If this isn't done then argument lists can have wildly different
	/// size and structure, when they should be compatible.
	struct TtypeExpander : public WithShortCircuiting {
		TypeEnvironment & tenv;
		TtypeExpander( TypeEnvironment & tenv ) : tenv( tenv ) {}
		void premutate( TypeInstType * ) { visit_children = false; }
		Type * postmutate( TypeInstType * typeInst ) {
			EqvClass eqvClass;
			if ( tenv.lookup( typeInst->get_name(), eqvClass ) ) {
				if ( eqvClass.data.kind == TypeDecl::Ttype ) {
					// expand ttype parameter into its actual type
					if ( eqvClass.type ) {
						delete typeInst;
						return eqvClass.type->clone();
					}
				}
			}
			return typeInst;
		}
	};

	/// flattens a list of declarations, so that each tuple type has a single declaration.
	/// makes use of TtypeExpander to ensure ttypes are flat as well.
	void flattenList( std::list< DeclarationWithType * > src, std::list< DeclarationWithType * > & dst, TypeEnvironment & env ) {
		dst.clear();
		for ( DeclarationWithType * dcl : src ) {
			PassVisitor<TtypeExpander> expander( env );
			dcl->acceptMutator( expander );
			std::list< Type * > types;
			flatten( dcl->get_type(), back_inserter( types ) );
			for ( Type * t : types ) {
				// outermost const, volatile, _Atomic qualifiers in parameters should not play a role in the unification of function types, since they do not determine whether a function is callable.
				// Note: MUST consider at least mutex qualifier, since functions can be overloaded on outermost mutex and a mutex function has different requirements than a non-mutex function.
				t->get_qualifiers() -= Type::Qualifiers(Type::Const | Type::Volatile | Type::Atomic);

				dst.push_back( new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::C, nullptr, t, nullptr ) );
			}
			delete dcl;
		}
	}

	void Unify::postvisit(FunctionType *functionType) {
		FunctionType *otherFunction = dynamic_cast< FunctionType* >( type2 );
		if ( otherFunction && functionType->get_isVarArgs() == otherFunction->get_isVarArgs() ) {
			// flatten the parameter lists for both functions so that tuple structure
			// doesn't affect unification. Must be a clone so that the types don't change.
			std::unique_ptr<FunctionType> flatFunc( functionType->clone() );
			std::unique_ptr<FunctionType> flatOther( otherFunction->clone() );
			flattenList( flatFunc->get_parameters(), flatFunc->get_parameters(), env );
			flattenList( flatOther->get_parameters(), flatOther->get_parameters(), env );

			// sizes don't have to match if ttypes are involved; need to be more precise wrt where the ttype is to prevent errors
			if ( (flatFunc->parameters.size() == flatOther->parameters.size() && flatFunc->returnVals.size() == flatOther->returnVals.size()) || flatFunc->isTtype() || flatOther->isTtype() ) {
				if ( unifyDeclList( flatFunc->parameters.begin(), flatFunc->parameters.end(), flatOther->parameters.begin(), flatOther->parameters.end(), env, needAssertions, haveAssertions, openVars, indexer ) ) {
					if ( unifyDeclList( flatFunc->returnVals.begin(), flatFunc->returnVals.end(), flatOther->returnVals.begin(), flatOther->returnVals.end(), env, needAssertions, haveAssertions, openVars, indexer ) ) {

						// the original types must be used in mark assertions, since pointer comparisons are used
						markAssertions( haveAssertions, needAssertions, functionType );
						markAssertions( haveAssertions, needAssertions, otherFunction );

						result = true;
					} // if
				} // if
			} // if
		} // if
	}

	template< typename RefType >
	void Unify::handleRefType( RefType *inst, Type *other ) {
		// check that other type is compatible and named the same
		RefType *otherStruct = dynamic_cast< RefType* >( other );
		result = otherStruct && inst->name == otherStruct->name;
	}

	template< typename RefType >
	void Unify::handleGenericRefType( RefType *inst, Type *other ) {
		// Check that other type is compatible and named the same
		handleRefType( inst, other );
		if ( ! result ) return;
		// Check that parameters of types unify, if any
		std::list< Expression* > params = inst->parameters;
		std::list< Expression* > otherParams = ((RefType*)other)->parameters;

		std::list< Expression* >::const_iterator it = params.begin(), jt = otherParams.begin();
		for ( ; it != params.end() && jt != otherParams.end(); ++it, ++jt ) {
			TypeExpr *param = dynamic_cast< TypeExpr* >(*it);
			assertf(param, "Aggregate parameters should be type expressions");
			TypeExpr *otherParam = dynamic_cast< TypeExpr* >(*jt);
			assertf(otherParam, "Aggregate parameters should be type expressions");

			Type* paramTy = param->get_type();
			Type* otherParamTy = otherParam->get_type();

			bool tupleParam = Tuples::isTtype( paramTy );
			bool otherTupleParam = Tuples::isTtype( otherParamTy );

			if ( tupleParam && otherTupleParam ) {
				++it; ++jt;  // skip ttype parameters for break
			} else if ( tupleParam ) {
				// bundle other parameters into tuple to match
				std::list< Type * > binderTypes;

				do {
					binderTypes.push_back( otherParam->get_type()->clone() );
					++jt;

					if ( jt == otherParams.end() ) break;

					otherParam = dynamic_cast< TypeExpr* >(*jt);
					assertf(otherParam, "Aggregate parameters should be type expressions");
				} while (true);

				otherParamTy = new TupleType{ paramTy->get_qualifiers(), binderTypes };
				++it;  // skip ttype parameter for break
			} else if ( otherTupleParam ) {
				// bundle parameters into tuple to match other
				std::list< Type * > binderTypes;

				do {
					binderTypes.push_back( param->get_type()->clone() );
					++it;

					if ( it == params.end() ) break;

					param = dynamic_cast< TypeExpr* >(*it);
					assertf(param, "Aggregate parameters should be type expressions");
				} while (true);

				paramTy = new TupleType{ otherParamTy->get_qualifiers(), binderTypes };
				++jt;  // skip ttype parameter for break
			}

			if ( ! unifyExact( paramTy, otherParamTy, env, needAssertions, haveAssertions, openVars, WidenMode(false, false), indexer ) ) {
				result = false;
				return;
			}

			// ttype parameter should be last
			if ( tupleParam || otherTupleParam ) break;
		}
		result = ( it == params.end() && jt == otherParams.end() );
	}

	void Unify::postvisit(StructInstType *structInst) {
		handleGenericRefType( structInst, type2 );
	}

	void Unify::postvisit(UnionInstType *unionInst) {
		handleGenericRefType( unionInst, type2 );
	}

	void Unify::postvisit(EnumInstType *enumInst) {
		handleRefType( enumInst, type2 );
	}

	void Unify::postvisit(TraitInstType *contextInst) {
		handleRefType( contextInst, type2 );
	}

	void Unify::postvisit(TypeInstType *typeInst) {
		assert( openVars.find( typeInst->get_name() ) == openVars.end() );
		TypeInstType *otherInst = dynamic_cast< TypeInstType* >( type2 );
		if ( otherInst && typeInst->get_name() == otherInst->get_name() ) {
			result = true;
///   } else {
///     NamedTypeDecl *nt = indexer.lookupType( typeInst->get_name() );
///     if ( nt ) {
///       TypeDecl *type = dynamic_cast< TypeDecl* >( nt );
///       assert( type );
///       if ( type->get_base() ) {
///         result = unifyExact( type->get_base(), typeInst, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
///       }
///     }
		} // if
	}

	template< typename Iterator1, typename Iterator2 >
	bool unifyList( Iterator1 list1Begin, Iterator1 list1End, Iterator2 list2Begin, Iterator2 list2End, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, const SymTab::Indexer &indexer ) {
		auto get_type = [](Type * t) { return t; };
		for ( ; list1Begin != list1End && list2Begin != list2End; ++list1Begin, ++list2Begin ) {
			Type * t1 = *list1Begin;
			Type * t2 = *list2Begin;
			bool isTtype1 = Tuples::isTtype( t1 );
			bool isTtype2 = Tuples::isTtype( t2 );
			// xxx - assumes ttype must be last parameter
			// xxx - there may be a nice way to refactor this, but be careful because the argument positioning might matter in some cases.
			if ( isTtype1 && ! isTtype2 ) {
				// combine all of the things in list2, then unify
				return unifyExact( t1, combineTypes( list2Begin, list2End, get_type ).get(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
			} else if ( isTtype2 && ! isTtype1 ) {
				// combine all of the things in list1, then unify
				return unifyExact( combineTypes( list1Begin, list1End, get_type ).get(), t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
			} else if ( ! unifyExact( t1, t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer ) ) {
				return false;
			} // if

		} // for
		if ( list1Begin != list1End ) {
			// try unifying empty tuple type with ttype
			Type * t1 = *list1Begin;
			if ( Tuples::isTtype( t1 ) ) {
				return unifyExact( t1, combineTypes( list2Begin, list2End, get_type ).get(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
			} else return false;
		} else if ( list2Begin != list2End ) {
			// try unifying empty tuple type with ttype
			Type * t2 = *list2Begin;
			if ( Tuples::isTtype( t2 ) ) {
				return unifyExact( combineTypes( list1Begin, list1End, get_type ).get(), t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
			} else return false;
		} else {
			return true;
		} // if
	}

	void Unify::postvisit(TupleType *tupleType) {
		if ( TupleType *otherTuple = dynamic_cast< TupleType* >( type2 ) ) {
			std::unique_ptr<TupleType> flat1( tupleType->clone() );
			std::unique_ptr<TupleType> flat2( otherTuple->clone() );
			std::list<Type *> types1, types2;

			PassVisitor<TtypeExpander> expander( env );
			flat1->acceptMutator( expander );
			flat2->acceptMutator( expander );

			flatten( flat1.get(), back_inserter( types1 ) );
			flatten( flat2.get(), back_inserter( types2 ) );

			result = unifyList( types1.begin(), types1.end(), types2.begin(), types2.end(), env, needAssertions, haveAssertions, openVars, indexer );
		} // if
	}

	void Unify::postvisit( __attribute__((unused)) VarArgsType *varArgsType ) {
		result = dynamic_cast< VarArgsType* >( type2 );
	}

	void Unify::postvisit( __attribute__((unused)) ZeroType *zeroType ) {
		result = dynamic_cast< ZeroType* >( type2 );
	}

	void Unify::postvisit( __attribute__((unused)) OneType *oneType ) {
		result = dynamic_cast< OneType* >( type2 );
	}

	// xxx - compute once and store in the FunctionType?
	Type * extractResultType( FunctionType * function ) {
		if ( function->get_returnVals().size() == 0 ) {
			return new VoidType( Type::Qualifiers() );
		} else if ( function->get_returnVals().size() == 1 ) {
			return function->get_returnVals().front()->get_type()->clone();
		} else {
			std::list< Type * > types;
			for ( DeclarationWithType * decl : function->get_returnVals() ) {
				types.push_back( decl->get_type()->clone() );
			} // for
			return new TupleType( Type::Qualifiers(), types );
		}
	}
} // namespace ResolvExpr

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