//
// 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.
//
// TypeEnvironment.cc --
//
// Author           : Richard C. Bilson
// Created On       : Sun May 17 12:19:47 2015
// Last Modified By : Peter A. Buhr
// Last Modified On : Sun May 17 12:23:36 2015
// Update Count     : 3
//

#include <algorithm>
#include <iterator>

#include "TypeEnvironment.h"
#include "SynTree/Type.h"
#include "SynTree/TypeSubstitution.h"
#include "Common/utility.h"

namespace ResolvExpr {
	// adding this comparison operator significantly improves assertion resolution run time for
	// some cases. The current resolution algorithm's speed partially depends on the order of
	// assertions. Assertions which have fewer possible matches should appear before
	// assertions which have more possible matches. This seems to imply that this could
	// be further improved by providing an indexer as an additional argument and ordering based
	// on the number of matches of the same kind (object, function) for the names of the
	// declarations.
	//
	// I've seen a TU go from 54 minutes to 1 minute 34 seconds with the addition of this comparator.
	bool AssertCompare::operator()( DeclarationWithType * d1, DeclarationWithType * d2 ) const {
			// Objects are always less than functions
			if ( ObjectDecl * objectDecl1 = dynamic_cast< ObjectDecl * >( d1 ) ) {
				if ( ObjectDecl * objectDecl2 = dynamic_cast< ObjectDecl * >( d2 ) ) {
					// objects are ordered by name then type pointer, in that order
					int cmp = objectDecl1->get_name().compare( objectDecl2->get_name() );
					return cmp < 0 ||
						( cmp == 0 && objectDecl1->get_type() < objectDecl2->get_type() );
				} else {
					return true;
				}
			} else if ( FunctionDecl * funcDecl1 = dynamic_cast< FunctionDecl * >( d1 ) ) {
				if ( FunctionDecl * funcDecl2 = dynamic_cast< FunctionDecl * >( d2 ) ) {
					// functions are ordered by name, # parameters, # returnVals, type pointer in that order
					FunctionType * ftype1 = funcDecl1->get_functionType();
					FunctionType * ftype2 = funcDecl2->get_functionType();
					int numThings1 = ftype1->get_parameters().size() + ftype1->get_returnVals().size();
					int numThings2 = ftype2->get_parameters().size() + ftype2->get_returnVals().size();
					if ( numThings1 < numThings2 ) return true;
					if ( numThings1 > numThings2 ) return false;

					// if ( ftype1->get_parameters().size() < ftype2->get_parameters().size() ) return true;
					// else if ( ftype1->get_parameters().size() > ftype2->get_parameters().size() ) return false;
					// // same number of parameters
					// if ( ftype1->get_returnVals().size() < ftype2->get_returnVals().size() ) return true;
					// else if ( ftype1->get_returnVals().size() > ftype2->get_returnVals().size() ) return false;
					// same number of return vals
					// int cmp = funcDecl1->get_name().compare( funcDecl2->get_name() );
					// if ( cmp < 0 ) return true;
					// else if ( cmp > 0 ) return false;
					// // same name
					return ftype1 < ftype2;
				} else {
					return false;
				}
			} else {
				assert( false );
			}
		}

	void printAssertionSet( const AssertionSet &assertions, std::ostream &os, int indent ) {
		for ( AssertionSet::const_iterator i = assertions.begin(); i != assertions.end(); ++i ) {
			i->first->print( os, indent );
			if ( i->second.isUsed ) {
				os << "(used)";
			} else {
				os << "(not used)";
			} // if
		} // for
	}

	void printOpenVarSet( const OpenVarSet &openVars, std::ostream &os, int indent ) {
		os << std::string( indent, ' ' );
		for ( OpenVarSet::const_iterator i = openVars.begin(); i != openVars.end(); ++i ) {
			os << i->first << "(" << i->second << ") ";
		} // for
	}

	void EqvClass::initialize( const EqvClass &src, EqvClass &dest ) {
		dest.vars = src.vars;
		dest.type = maybeClone( src.type );
		dest.allowWidening = src.allowWidening;
		dest.data = src.data;
	}

	EqvClass::EqvClass() : type( 0 ), allowWidening( true ) {
	}

	EqvClass::EqvClass( const EqvClass &other ) {
		initialize( other, *this );
	}

	EqvClass &EqvClass::operator=( const EqvClass &other ) {
		if ( this == &other ) return *this;
		delete type;
		initialize( other, *this );
		return *this;
	}

	EqvClass::~EqvClass() {
		delete type;
	}

	void EqvClass::print( std::ostream &os, int indent ) const {
		os << std::string( indent, ' ' ) << "( ";
		std::copy( vars.begin(), vars.end(), std::ostream_iterator< std::string >( os, " " ) );
		os << ")";
		if ( type ) {
			os << " -> ";
			type->print( os, indent );
		} // if
		if ( ! allowWidening ) {
			os << " (no widening)";
		} // if
		os << std::endl;
	}

	bool TypeEnvironment::lookup( const std::string &var, EqvClass &eqvClass ) const {
		for ( std::list< EqvClass >::const_iterator i = env.begin(); i != env.end(); ++i ) {
			if ( i->vars.find( var ) != i->vars.end() ) {
///       std::cout << var << " is in class ";
///       i->print( std::cout );
				eqvClass = *i;
				return true;
			}
///     std::cout << var << " is not in class ";
///     i->print( std::cout );
		} // for
		return false;
	}

	void TypeEnvironment::add( const EqvClass &eqvClass ) {
		std::list< EqvClass >::iterator i = env.begin();
		while ( i != env.end() ) {
			std::list< EqvClass >::iterator next = i;
			next++;
			std::set< std::string > intersection;
			std::set_intersection( i->vars.begin(), i->vars.end(), eqvClass.vars.begin(), eqvClass.vars.end(), std::inserter( intersection, intersection.begin() ) );
			if ( ! intersection.empty() ) {
				env.erase( i );
			} // if
			i = next;
		} // while
		env.insert( env.end(), eqvClass );
	}

	void TypeEnvironment::add( const Type::ForallList &tyDecls ) {
		for ( Type::ForallList::const_iterator i = tyDecls.begin(); i != tyDecls.end(); ++i ) {
			EqvClass newClass;
			newClass.vars.insert( (*i)->get_name() );
			newClass.data = TypeDecl::Data{ (*i) };
			env.push_back( newClass );
		} // for
	}

	void TypeEnvironment::makeSubstitution( TypeSubstitution &sub ) const {
		for ( std::list< EqvClass >::const_iterator theClass = env.begin(); theClass != env.end(); ++theClass ) {
			for ( std::set< std::string >::const_iterator theVar = theClass->vars.begin(); theVar != theClass->vars.end(); ++theVar ) {
///       std::cout << "adding " << *theVar;
				if ( theClass->type ) {
///         std::cout << " bound to ";
///         theClass->type->print( std::cout );
///         std::cout << std::endl;
					sub.add( *theVar, theClass->type );
				} else if ( theVar != theClass->vars.begin() ) {
					TypeInstType *newTypeInst = new TypeInstType( Type::Qualifiers(), *theClass->vars.begin(), theClass->data.kind == TypeDecl::Ftype );
///         std::cout << " bound to variable " << *theClass->vars.begin() << std::endl;
					sub.add( *theVar, newTypeInst );
					delete newTypeInst;
				} // if
			} // for
		} // for
///   std::cerr << "input env is:" << std::endl;
///   print( std::cerr, 8 );
///   std::cerr << "sub is:" << std::endl;
///   sub.print( std::cerr, 8 );
		sub.normalize();
	}

	void TypeEnvironment::print( std::ostream &os, int indent ) const {
		for ( std::list< EqvClass >::const_iterator i = env.begin(); i != env.end(); ++i ) {
			i->print( os, indent );
		} // for
	}

	std::list< EqvClass >::iterator TypeEnvironment::internal_lookup( const std::string &var ) {
		for ( std::list< EqvClass >::iterator i = env.begin(); i != env.end(); ++i ) {
			if ( i->vars.find( var ) == i->vars.end() ) {
				return i;
			} // if
		} // for
		return env.end();
	}

	void TypeEnvironment::simpleCombine( const TypeEnvironment &second ) {
		env.insert( env.end(), second.env.begin(), second.env.end() );
	}

	void TypeEnvironment::combine( const TypeEnvironment &second, Type *(*combineFunc)( Type*, Type* ) ) {
		TypeEnvironment secondCopy( second );
		for ( std::list< EqvClass >::iterator firstClass = env.begin(); firstClass != env.end(); ++firstClass ) {
			EqvClass &newClass = *firstClass;
			std::set< std::string > newVars;
			for ( std::set< std::string >::const_iterator var = firstClass->vars.begin(); var != firstClass->vars.end(); ++var ) {
				std::list< EqvClass >::iterator secondClass = secondCopy.internal_lookup( *var );
				if ( secondClass != secondCopy.env.end() ) {
					newVars.insert( secondClass->vars.begin(), secondClass->vars.end() );
					if ( secondClass->type ) {
						if ( newClass.type ) {
							Type *newType = combineFunc( newClass.type, secondClass->type );
							delete newClass.type;
							newClass.type = newType;
							newClass.allowWidening = newClass.allowWidening && secondClass->allowWidening;
						} else {
							newClass.type = secondClass->type->clone();
							newClass.allowWidening = secondClass->allowWidening;
						} // if
					} // if
					secondCopy.env.erase( secondClass );
				} // if
			} // for
			newClass.vars.insert( newVars.begin(), newVars.end() );
		} // for
		for ( std::list< EqvClass >::iterator secondClass = secondCopy.env.begin(); secondClass != secondCopy.env.end(); ++secondClass ) {
			env.push_back( *secondClass );
		} // for
	}

	void TypeEnvironment::extractOpenVars( OpenVarSet &openVars ) const {
		for ( std::list< EqvClass >::const_iterator eqvClass = env.begin(); eqvClass != env.end(); ++eqvClass ) {
			for ( std::set< std::string >::const_iterator var = eqvClass->vars.begin(); var != eqvClass->vars.end(); ++var ) {
				openVars[ *var ] = eqvClass->data;
			} // for
		} // for
	}

} // namespace ResolvExpr

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