/*
 * This file is part of the Cforall project
 *
 * $Id: Unify.h,v 1.4 2005/08/29 20:14:16 rcbilson Exp $
 *
 */

#ifndef UNIFY_H
#define UNIFY_H

#include <map>
#include <list>
#include "SynTree/SynTree.h"
#include "SynTree/Type.h"
#include "SynTree/Declaration.h"
#include "SymTab/Indexer.h"
#include "TypeEnvironment.h"
#include "utility.h"

namespace ResolvExpr {

bool unify( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, OpenVarSet &openVars, const SymTab::Indexer &indexer );
bool unify( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, OpenVarSet &openVars, const SymTab::Indexer &indexer, Type *&commonType );
bool unifyExact( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, OpenVarSet &openVars, const SymTab::Indexer &indexer );

template< typename Iterator1, typename Iterator2 >
bool
unifyList( Iterator1 list1Begin, Iterator1 list1End, Iterator2 list2Begin, Iterator2 list2End, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, OpenVarSet &openVars, const SymTab::Indexer &indexer, std::list< Type* > &commonTypes ) {
  for( ; list1Begin != list1End && list2Begin != list2End; ++list1Begin, ++list2Begin ) {
    Type *commonType = 0;
    if( !unify( *list1Begin, *list2Begin, env, needAssertions, haveAssertions, openVars, indexer, commonType ) ) {
      return false;
    }
    commonTypes.push_back( commonType );
  }
  if( list1Begin != list1End || list2Begin != list2End ) {
    return false;
  } else {
    return true;
  }
}

template< typename Iterator1, typename Iterator2 >
bool
unifyList( Iterator1 list1Begin, Iterator1 list1End, Iterator2 list2Begin, Iterator2 list2End, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, OpenVarSet &openVars, const SymTab::Indexer &indexer ) {
  std::list< Type* > commonTypes;
  if( unifyList( list1Begin, list1End, list2Begin, list2End, env, needAssertions, haveAssertions, openVars, indexer, commonTypes ) ) {
    deleteAll( commonTypes );
    return true;
  } else {
    return false;
  }
}

} // namespace ResolvExpr

#endif /* #ifndef UNIFY_H */
