// // 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. // // ResolveAssertions.cc -- // // Author : Aaron B. Moss // Created On : Fri Oct 05 13:46:00 2018 // Last Modified By : Aaron B. Moss // Last Modified On : Fri Oct 05 13:46:00 2018 // Update Count : 1 // #include "ResolveAssertions.h" #include // for assertf #include // for list #include // for move #include // for vector #include "Alternative.h" // for Alternative, AssertionItem #include "Common/FilterCombos.h" // for filterCombos #include "SymTab/Indexer.h" // for Indexer #include "TypeEnvironment.h" // for TypeEnvironment, etc. #include "typeops.h" // for adjustExprType #include "Unify.h" // for unify namespace ResolvExpr { /// Unified assertion candidate struct AssnCandidate { SymTab::Indexer::IdData cdata; ///< Satisfying declaration Type* adjType; ///< Satisfying type TypeEnvironment env; ///< Post-unification environment AssertionSet have; ///< Post-unification have-set AssertionSet need; ///< Post-unification need-set OpenVarSet openVars; ///< Post-unification open-var set AssnCandidate( const SymTab::Indexer::IdData& cdata, Type* adjType, TypeEnvironment&& env, AssertionSet&& have, AssertionSet&& need, OpenVarSet&& openVars ) : cdata(cdata), adjType(adjType), env(std::move(env)), have(std::move(have)), need(std::move(need)), openVars(std::move(openVars)) {} }; /// List of candidate assertion resolutions using CandidateList = std::vector; /// Reference to single deferred item struct DeferRef { const DeclarationWithType* decl; const AssertionSetValue& info; const AssnCandidate& match; }; /// Wrapper for the deferred items from a single assertion resolution. /// Acts like indexed list of DeferRef struct DeferItem { DeclarationWithType* decl; AssertionSetValue info; CandidateList matches; DeferItem( DeclarationWithType* decl, const AssertionSetValue& info, CandidateList&& matches ) : decl(decl), info(info), matches(std::move(matches)) {} bool empty() const { return matches.empty(); } CandidateList::size_type size() const { return matches.size(); } DeferRef operator[] ( unsigned i ) const { return { decl, info, matches[i] }; } }; /// List of deferred resolution items using DeferList = std::vector; /// Combo iterator that combines candidates into an output list, merging their environments. /// Rejects an appended candidate if the environments cannot be merged. class CandidateEnvMerger { /// Current list of merged candidates std::vector crnt; /// Stack of environments to support backtracking std::vector envs; /// Stack of open variables to support backtracking std::vector varSets; /// Indexer to use for merges const SymTab::Indexer& indexer; public: /// The merged environment/open variables and the list of candidates struct OutType { TypeEnvironment env; OpenVarSet openVars; std::vector assns; OutType( const TypeEnvironment& env, const OpenVarSet& openVars, const std::vector& assns ) : env(env), openVars(openVars), assns(assns) {} }; CandidateEnvMerger( const TypeEnvironment& env, const OpenVarSet& openVars, const SymTab::Indexer& indexer ) : crnt(), envs{ env }, varSets{ openVars }, indexer(indexer) {} bool append( DeferRef i ) { TypeEnvironment env = envs.back(); OpenVarSet openVars = varSets.back(); mergeOpenVars( openVars, i.match.openVars ); if ( ! env.combine( i.match.env, openVars, indexer ) ) return false; crnt.emplace_back( i ); envs.emplace_back( env ); varSets.emplace_back( openVars ); return true; } void backtrack() { crnt.pop_back(); envs.pop_back(); varSets.pop_back(); } OutType finalize() { return { envs.back(), varSets.back(), crnt }; } }; /// Flag for state iteration enum IterateFlag { IterateState }; /// State needed to resolve a set of assertions struct ResnState { Alternative alt; ///< Alternative assertion is rooted on std::vector need; ///< Assertions to find AssertionSet newNeed; ///< New assertions for current resolutions DeferList deferred; ///< Deferred matches SymTab::Indexer& indexer; ///< Name lookup (depends on previous assertions) /// Initial resolution state for an alternative ResnState( Alternative& a, SymTab::Indexer& indexer ) : alt(a), need(), newNeed(), deferred(), indexer(indexer) { need.swap( a.need ); } /// Updated resolution state with new need-list ResnState( ResnState&& o, IterateFlag ) : alt(std::move(o.alt)), need(o.newNeed.begin(), o.newNeed.end()), newNeed(), deferred(), indexer(o.indexer) {} }; /// Binds a single assertion, updating resolution state void bindAssertion( const DeclarationWithType* decl, AssertionSetValue info, Alternative& alt, AssnCandidate& match ) { DeclarationWithType* candidate = match.cdata.id; assertf( candidate->get_uniqueId(), "Assertion candidate does not have a unique ID: %s", toString( candidate ).c_str() ); // everything with an empty idChain was pulled in by the current assertion. // add current assertion's idChain + current assertion's ID so that the correct // inferParameters can be found. for ( auto& a : match.need ) { if ( a.second.idChain.empty() ) { a.second.idChain = info.idChain; a.second.idChain.push_back( decl->get_uniqueId() ); } } Expression* varExpr = match.cdata.combine( alt.cvtCost ); varExpr->result = match.adjType; // follow the current assertion's ID chain to find the correct set of inferred parameters // to add the candidate o (i.e. the set of inferred parameters belonging to the entity // which requested the assertion parameter) InferredParams* inferParams = &alt.expr->inferParams; for ( UniqueId id : info.idChain ) { inferParams = (*inferParams)[ id ].inferParams.get(); } (*inferParams)[ decl->get_uniqueId() ] = ParamEntry{ candidate->get_uniqueId(), match.adjType, decl->get_type(), varExpr }; } /// Adds a captured assertion to the symbol table void addToIndexer( AssertionSet &assertSet, SymTab::Indexer &indexer ) { for ( AssertionSet::iterator i = assertSet.begin(); i != assertSet.end(); ++i ) { if ( i->second.isUsed ) { indexer.addId( i->first ); } } } /// Resolve a single assertion, in context bool resolveAssertion( AssertionItem& assn, ResnState& resn ) { // skip unused assertions if ( ! assn.info.isUsed ) return true; // lookup candidates for this assertion std::list< SymTab::Indexer::IdData > candidates; resn.indexer.lookupId( assn.decl->name, candidates ); // find the candidates that unify with the desired type CandidateList matches; for ( const auto& cdata : candidates ) { DeclarationWithType* candidate = cdata.id; // build independent unification context for candidate AssertionSet have, newNeed; TypeEnvironment newEnv{ resn.alt.env }; OpenVarSet newOpenVars{ resn.alt.openVars }; Type* adjType = candidate->get_type()->clone(); adjustExprType( adjType, newEnv, resn.indexer ); // keep unifying candidates if ( unify( assn.decl->get_type(), adjType, newEnv, newNeed, have, newOpenVars, resn.indexer ) ) { matches.emplace_back( cdata, adjType, std::move(newEnv), std::move(have), std::move(newNeed), std::move(newOpenVars) ); } } // break if no suitable assertion if ( matches.empty() ) return false; // defer if too many suitable assertions if ( matches.size() > 1 ) { resn.deferred.emplace_back( assn.decl, assn.info, std::move(matches) ); return true; } // otherwise bind current match in ongoing scope AssnCandidate& match = matches.front(); addToIndexer( match.have, resn.indexer ); resn.newNeed.insert( match.need.begin(), match.need.end() ); resn.alt.env = std::move(match.env); resn.alt.openVars = std::move(match.openVars); bindAssertion( assn.decl, assn.info, resn.alt, match ); return true; } ///< Limit to depth of recursion of assertion satisfaction static const int recursionLimit = /* 10 */ 4; void resolveAssertions( Alternative& alt, const SymTab::Indexer& indexer, AltList& out ) { // finish early if no assertions to resolve if ( alt.need.empty() ) { out.emplace_back( alt ); return; } // build list of possible resolutions using ResnList = std::vector; SymTab::Indexer root_indexer{ indexer }; ResnList resns{ ResnState{ alt, root_indexer } }; ResnList new_resns{}; // resolve assertions in breadth-first-order up to a limited number of levels deep for ( unsigned level = 0; level < recursionLimit; ++level ) { // scan over all mutually-compatible resolutions for ( auto& resn : resns ) { // make initial pass at matching assertions for ( auto& assn : resn.need ) { // fail early if any assertion is not resolvable if ( ! resolveAssertion( assn, resn ) ) goto nextResn; } if ( resn.deferred.empty() ) { // either add successful match or push back next state if ( resn.newNeed.empty() ) { out.emplace_back( resn.alt ); } else { new_resns.emplace_back( std::move(resn), IterateState ); } } else { // resolve deferred assertions by mutual compatibility std::vector compatible = filterCombos( resn.deferred, CandidateEnvMerger{ resn.alt.env, resn.alt.openVars, resn.indexer } ); for ( auto& compat : compatible ) { ResnState new_resn = resn; // add compatible assertions to new resolution state for ( DeferRef r : compat.assns ) { AssnCandidate match = r.match; addToIndexer( match.have, new_resn.indexer ); new_resn.newNeed.insert( match.need.begin(), match.need.end() ); bindAssertion( r.decl, r.info, new_resn.alt, match ); } // set mutual environment into resolution state new_resn.alt.env = std::move(compat.env); new_resn.alt.openVars = std::move(compat.openVars); // either add sucessful match or push back next state if ( new_resn.newNeed.empty() ) { out.emplace_back( new_resn.alt ); } else { new_resns.emplace_back( std::move(new_resn), IterateState ); } } } nextResn:; } // finish or reset for next round if ( new_resns.empty() ) return; resns.swap( new_resns ); new_resns.clear(); } // exceeded recursion limit if reaches here if ( out.empty() ) { SemanticError( alt.expr->location, "Too many recursive assertions" ); } } } // namespace ResolvExpr // Local Variables: // // tab-width: 4 // // mode: c++ // // compile-command: "make install" // // End: //