//
// 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 : Wed Jun 29 21:45:53 2016
// Update Count     : 14
//

#include "GenPoly.h"

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

#include <iostream>
using namespace std;

namespace GenPoly {
	namespace {
		/// Checks a parameter list for polymorphic parameters; will substitute according to env if present
		bool hasPolyParams( std::list< Expression* >& params, const TypeSubstitution *env ) {
			for ( std::list< Expression* >::iterator param = params.begin(); param != params.end(); ++param ) {
				TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
				assertf(paramType, "Aggregate parameters should be type expressions");
				if ( isPolyType( paramType->get_type(), env ) ) return true;
			}
			return false;
		}

		/// Checks a parameter list for polymorphic parameters from tyVars; will substitute according to env if present
		bool hasPolyParams( std::list< Expression* >& params, const TyVarMap &tyVars, const TypeSubstitution *env ) {
			for ( std::list< Expression* >::iterator param = params.begin(); param != params.end(); ++param ) {
				TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
				assert(paramType && "Aggregate parameters should be type expressions");
				if ( isPolyType( paramType->get_type(), tyVars, env ) ) return true;
			}
			return false;
		}

		/// Checks a parameter list for dynamic-layout parameters from tyVars; will substitute according to env if present
		bool hasDynParams( std::list< Expression* >& params, const TyVarMap &tyVars, const TypeSubstitution *env ) {
			for ( std::list< Expression* >::iterator param = params.begin(); param != params.end(); ++param ) {
				TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
				assert(paramType && "Aggregate parameters should be type expressions");
				if ( isDynType( paramType->get_type(), tyVars, env ) ) return true;
			}
			return false;
		}
	}

	Type* replaceTypeInst( Type* type, const TypeSubstitution* env ) {
		if ( ! env ) return type;
		if ( TypeInstType *typeInst = dynamic_cast< TypeInstType* >( type ) ) {
			Type *newType = env->lookup( typeInst->get_name() );
			if ( newType ) return newType;
		}
		return type;
	}

	Type *isPolyType( Type *type, const TypeSubstitution *env ) {
		type = replaceTypeInst( type, env );

		if ( dynamic_cast< TypeInstType * >( type ) ) {
			return type;
		} else if ( StructInstType *structType = dynamic_cast< StructInstType* >( type ) ) {
			if ( hasPolyParams( structType->get_parameters(), env ) ) return type;
		} else if ( UnionInstType *unionType = dynamic_cast< UnionInstType* >( type ) ) {
			if ( hasPolyParams( unionType->get_parameters(), env ) ) return type;
		}
		return 0;
	}

	Type *isPolyType( Type *type, const TyVarMap &tyVars, const TypeSubstitution *env ) {
		type = replaceTypeInst( type, env );

		if ( TypeInstType *typeInst = dynamic_cast< TypeInstType * >( type ) ) {
			if ( tyVars.find( typeInst->get_name() ) != tyVars.end() ) {
				return type;
			}
		} else if ( StructInstType *structType = dynamic_cast< StructInstType* >( type ) ) {
			if ( hasPolyParams( structType->get_parameters(), tyVars, env ) ) return type;
		} else if ( UnionInstType *unionType = dynamic_cast< UnionInstType* >( type ) ) {
			if ( hasPolyParams( unionType->get_parameters(), tyVars, env ) ) return type;
		}
		return 0;
	}

	ReferenceToType *isDynType( Type *type, const TyVarMap &tyVars, const TypeSubstitution *env ) {
		type = replaceTypeInst( type, env );

		if ( TypeInstType *typeInst = dynamic_cast< TypeInstType * >( type ) ) {
			auto var = tyVars.find( typeInst->get_name() );
			if ( var != tyVars.end() && var->second.isComplete ) {
				return typeInst;
			}
		} else if ( StructInstType *structType = dynamic_cast< StructInstType* >( type ) ) {
			if ( hasDynParams( structType->get_parameters(), tyVars, env ) ) return structType;
		} else if ( UnionInstType *unionType = dynamic_cast< UnionInstType* >( type ) ) {
			if ( hasDynParams( unionType->get_parameters(), tyVars, env ) ) return unionType;
		}
		return 0;
	}

	ReferenceToType *isDynRet( FunctionType *function, const TyVarMap &forallTypes ) {
		if ( function->get_returnVals().empty() ) return 0;

		return (ReferenceToType*)isDynType( function->get_returnVals().front()->get_type(), forallTypes );
	}

	ReferenceToType *isDynRet( FunctionType *function ) {
		if ( function->get_returnVals().empty() ) return 0;

		TyVarMap forallTypes( TypeDecl::Data{} );
		makeTyVarMap( function, forallTypes );
		return (ReferenceToType*)isDynType( function->get_returnVals().front()->get_type(), forallTypes );
	}

	bool needsAdapter( FunctionType *adaptee, const TyVarMap &tyVars ) {
// 		if ( ! adaptee->get_returnVals().empty() && isPolyType( adaptee->get_returnVals().front()->get_type(), tyVars ) ) {
// 			return true;
// 		} // if
		if ( isDynRet( adaptee, tyVars ) ) return true;

		for ( std::list< DeclarationWithType* >::const_iterator innerArg = adaptee->get_parameters().begin(); innerArg != adaptee->get_parameters().end(); ++innerArg ) {
// 			if ( isPolyType( (*innerArg)->get_type(), tyVars ) ) {
			if ( isDynType( (*innerArg)->get_type(), tyVars ) ) {
				return true;
			} // if
		} // for
		return false;
	}

	Type *isPolyPtr( Type *type, const TypeSubstitution *env ) {
		type = replaceTypeInst( type, env );

		if ( PointerType *ptr = dynamic_cast< PointerType *>( type ) ) {
			return isPolyType( ptr->get_base(), env );
		}
		return 0;
	}

	Type *isPolyPtr( Type *type, const TyVarMap &tyVars, const TypeSubstitution *env ) {
		type = replaceTypeInst( type, env );

		if ( PointerType *ptr = dynamic_cast< PointerType *>( type ) ) {
			return isPolyType( ptr->get_base(), tyVars, env );
		}
		return 0;
	}

	Type * hasPolyBase( Type *type, int *levels, const TypeSubstitution *env ) {
		int dummy;
		if ( ! levels ) { levels = &dummy; }
		*levels = 0;

		while ( true ) {
			type = replaceTypeInst( type, env );

			if ( PointerType *ptr = dynamic_cast< PointerType *>( type ) ) {
				type = ptr->get_base();
				++(*levels);
			} else break;
		}

		return isPolyType( type, env );
	}

	Type * hasPolyBase( Type *type, const TyVarMap &tyVars, int *levels, const TypeSubstitution *env ) {
		int dummy;
		if ( ! levels ) { levels = &dummy; }
		*levels = 0;

		while ( true ) {
			type = replaceTypeInst( type, env );

			if ( PointerType *ptr = dynamic_cast< PointerType *>( type ) ) {
				type = ptr->get_base();
				++(*levels);
			} else break;
		}

		return isPolyType( type, tyVars, env );
	}

	FunctionType * getFunctionType( Type *ty ) {
		PointerType *ptrType;
		if ( ( ptrType = dynamic_cast< PointerType* >( ty ) ) ) {
			return dynamic_cast< FunctionType* >( ptrType->get_base() ); // pointer if FunctionType, NULL otherwise
		} else {
			return dynamic_cast< FunctionType* >( ty ); // pointer if FunctionType, NULL otherwise
		}
	}

	VariableExpr * getBaseVar( Expression *expr, int *levels ) {
		int dummy;
		if ( ! levels ) { levels = &dummy; }
		*levels = 0;

		while ( true ) {
			if ( VariableExpr *varExpr = dynamic_cast< VariableExpr* >( expr ) ) {
				return varExpr;
			} else if ( MemberExpr *memberExpr = dynamic_cast< MemberExpr* >( expr ) ) {
				expr = memberExpr->get_aggregate();
			} else if ( AddressExpr *addressExpr = dynamic_cast< AddressExpr* >( expr ) ) {
				expr = addressExpr->get_arg();
			} else if ( UntypedExpr *untypedExpr = dynamic_cast< UntypedExpr* >( expr ) ) {
				// look for compiler-inserted dereference operator
				NameExpr *fn = dynamic_cast< NameExpr* >( untypedExpr->get_function() );
				if ( ! fn || fn->get_name() != std::string("*?") ) return 0;
				expr = *untypedExpr->begin_args();
			} else if ( CommaExpr *commaExpr = dynamic_cast< CommaExpr* >( expr ) ) {
				// copy constructors insert comma exprs, look at second argument which contains the variable
				expr = commaExpr->get_arg2();
				continue;
			} else if ( ConditionalExpr * condExpr = dynamic_cast< ConditionalExpr * >( expr ) ) {
				int lvl1;
				int lvl2;
				VariableExpr * var1 = getBaseVar( condExpr->get_arg2(), &lvl1 );
				VariableExpr * var2 = getBaseVar( condExpr->get_arg3(), &lvl2 );
				if ( lvl1 == lvl2 && var1 && var2 && var1->get_var() == var2->get_var() ) {
					*levels = lvl1;
					return var1;
				}
				break;
			} else break;

			++(*levels);
		}

		return 0;
	}

	void addToTyVarMap( TypeDecl * tyVar, TyVarMap &tyVarMap ) {
		tyVarMap[ tyVar->get_name() ] = TypeDecl::Data{ tyVar };
	}

	void makeTyVarMap( Type *type, TyVarMap &tyVarMap ) {
		for ( Type::ForallList::const_iterator tyVar = type->get_forall().begin(); tyVar != type->get_forall().end(); ++tyVar ) {
			assert( *tyVar );
			addToTyVarMap( *tyVar, tyVarMap );
		}
		if ( PointerType *pointer = dynamic_cast< PointerType* >( type ) ) {
			makeTyVarMap( pointer->get_base(), tyVarMap );
		}
	}

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