//
// 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.
//
// GenPoly.cc -- 
//
// Author           : Richard C. Bilson
// Created On       : Mon May 18 07:44:20 2015
// Last Modified By : Peter A. Buhr
// Last Modified On : Tue May 19 07:37:46 2015
// Update Count     : 1
//

#include "GenPoly.h"
#include "SynTree/Type.h"

#include <iostream>
using namespace std;

namespace GenPoly {
	// interface functions
	bool isPolyVal( Type *type, const TyVarMap &tyVars ) {
		return isPolyVal( type, tyVars, false );
	}

	bool needsAdapter( FunctionType *adaptee, const TyVarMap &tyVars ) {  
		return needsAdapter( adaptee, tyVars, false );
	}

	bool isPolyVal( Type *type, const TyVarMap &tyVars, bool considerAllTyVars ) {
		if ( TypeInstType *typeInst = dynamic_cast< TypeInstType* >( type ) ) {
			if ( tyVars.find( typeInst->get_name() ) != tyVars.end() ) {
				return true;
			} // if
			return considerAllTyVars;
		} // if
		return false;
	}

	// A function needs an adapter if it returns a polymorphic value or if any of its
	// parameters have polymorphic type
	bool needsAdapter( FunctionType *adaptee, const TyVarMap &tyVars, bool considerAllTyVars ) {
		bool needsAdapter = false;
		if ( ! adaptee->get_returnVals().empty() && isPolyVal( adaptee->get_returnVals().front()->get_type(), tyVars, considerAllTyVars ) ) {
			needsAdapter = true;
		} // if
		for ( std::list< DeclarationWithType* >::const_iterator innerArg = adaptee->get_parameters().begin(); ! needsAdapter && innerArg != adaptee->get_parameters().end(); ++innerArg ) {
			if ( isPolyVal( (*innerArg)->get_type(), tyVars, considerAllTyVars ) ) {
				needsAdapter = true;
			} // if
		} // for
		return needsAdapter;
	}

	void printTyVarMap( std::ostream &os, const TyVarMap &tyVarMap ) {
		for ( TyVarMap::const_iterator i = tyVarMap.begin(); i != tyVarMap.end(); ++i ) {
			os << i->first << " (" << i->second << ") ";
		} // for
		os << std::endl;
	}
} // namespace GenPoly

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