source: src/ResolvExpr/ResolveAssertions.cc@ 07e3652

ADT ast-experimental
Last change on this file since 07e3652 was 5bf3976, checked in by Andrew Beach <ajbeach@…>, 3 years ago

Header Clean-Up: Created new headers for new AST typeops and moved declarations.

  • Property mode set to 100644
File size: 18.4 KB
RevLine 
[6d6e829]1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// ResolveAssertions.cc --
8//
9// Author : Aaron B. Moss
10// Created On : Fri Oct 05 13:46:00 2018
[7d01cf44]11// Last Modified By : Andrew Beach
12// Last Modified On : Thu Aug 8 16:47:00 2019
13// Update Count : 3
[6d6e829]14//
15
16#include "ResolveAssertions.h"
17
[b3bd772]18#include <algorithm> // for sort
[83ab931]19#include <cassert> // for assertf
20#include <list> // for list
[b3bd772]21#include <memory> // for unique_ptr
[4d2d45f9]22#include <sstream> // for ostringstream
23#include <string> // for string
[83ab931]24#include <unordered_map> // for unordered_map, unordered_multimap
25#include <utility> // for move
26#include <vector> // for vector
27
[5bf3976]28#include "AdjustExprType.hpp" // for adjustExprType
[83ab931]29#include "Alternative.h" // for Alternative, AssertionItem, AssertionList
30#include "Common/FilterCombos.h" // for filterCombos
[4d2d45f9]31#include "Common/Indenter.h" // for Indenter
[83ab931]32#include "Common/utility.h" // for sort_mins
[d76c588]33#include "GenPoly/GenPoly.h" // for getFunctionType
[fed6a0f]34#include "ResolvExpr/AlternativeFinder.h" // for computeConversionCost
[83ab931]35#include "ResolvExpr/RenameVars.h" // for renameTyVars
[5bf3976]36#include "SpecCost.hpp" // for specCost
[83ab931]37#include "SymTab/Indexer.h" // for Indexer
[b3bd772]38#include "SymTab/Mangler.h" // for Mangler
[83ab931]39#include "SynTree/Expression.h" // for InferredParams
40#include "TypeEnvironment.h" // for TypeEnvironment, etc.
41#include "Unify.h" // for unify
[6d6e829]42
43namespace ResolvExpr {
44 /// Unified assertion candidate
45 struct AssnCandidate {
46 SymTab::Indexer::IdData cdata; ///< Satisfying declaration
47 Type* adjType; ///< Satisfying type
48 TypeEnvironment env; ///< Post-unification environment
49 AssertionSet have; ///< Post-unification have-set
50 AssertionSet need; ///< Post-unification need-set
51 OpenVarSet openVars; ///< Post-unification open-var set
[0b00df0]52 UniqueId resnSlot; ///< Slot for any recursive assertion IDs
[6d6e829]53
[aaeacf4]54 AssnCandidate( const SymTab::Indexer::IdData& cdata, Type* adjType, TypeEnvironment&& env,
55 AssertionSet&& have, AssertionSet&& need, OpenVarSet&& openVars, UniqueId resnSlot )
56 : cdata(cdata), adjType(adjType), env(std::move(env)), have(std::move(have)),
[0b00df0]57 need(std::move(need)), openVars(std::move(openVars)), resnSlot(resnSlot) {}
[6d6e829]58 };
59
60 /// List of candidate assertion resolutions
61 using CandidateList = std::vector<AssnCandidate>;
62
63 /// Reference to single deferred item
64 struct DeferRef {
[052cd71]65 const DeclarationWithType* decl;
66 const AssertionSetValue& info;
[6d6e829]67 const AssnCandidate& match;
68 };
69
70 /// Wrapper for the deferred items from a single assertion resolution.
71 /// Acts like indexed list of DeferRef
72 struct DeferItem {
[052cd71]73 const DeclarationWithType* decl;
74 const AssertionSetValue& info;
75 CandidateList matches;
[6d6e829]76
[85dac33]77 DeferItem( const DeclarationWithType* decl, const AssertionSetValue& info, CandidateList&& matches )
[052cd71]78 : decl(decl), info(info), matches(std::move(matches)) {}
[6d6e829]79
[052cd71]80 bool empty() const { return matches.empty(); }
[6d6e829]81
[052cd71]82 CandidateList::size_type size() const { return matches.size(); }
[4d2d45f9]83
[052cd71]84 DeferRef operator[] ( unsigned i ) const { return { decl, info, matches[i] }; }
[6d6e829]85 };
86
87 /// List of deferred resolution items
88 using DeferList = std::vector<DeferItem>;
89
[aaeacf4]90 /// Combo iterator that combines candidates into an output list, merging their environments.
[6d6e829]91 /// Rejects an appended candidate if the environments cannot be merged.
92 class CandidateEnvMerger {
93 /// Current list of merged candidates
94 std::vector<DeferRef> crnt;
95 /// Stack of environments to support backtracking
96 std::vector<TypeEnvironment> envs;
97 /// Stack of open variables to support backtracking
98 std::vector<OpenVarSet> varSets;
99 /// Indexer to use for merges
100 const SymTab::Indexer& indexer;
[aaeacf4]101
[6d6e829]102 public:
103 /// The merged environment/open variables and the list of candidates
104 struct OutType {
105 TypeEnvironment env;
106 OpenVarSet openVars;
107 std::vector<DeferRef> assns;
[c519942]108 Cost cost;
[6d6e829]109
[aaeacf4]110 OutType( const TypeEnvironment& env, const OpenVarSet& openVars,
[6d6e829]111 const std::vector<DeferRef>& assns )
[c519942]112 : env(env), openVars(openVars), assns(assns), cost(Cost::infinity) {}
[6d6e829]113 };
114
[aaeacf4]115 CandidateEnvMerger( const TypeEnvironment& env, const OpenVarSet& openVars,
[6d6e829]116 const SymTab::Indexer& indexer )
117 : crnt(), envs{ env }, varSets{ openVars }, indexer(indexer) {}
118
119 bool append( DeferRef i ) {
120 TypeEnvironment env = envs.back();
121 OpenVarSet openVars = varSets.back();
122 mergeOpenVars( openVars, i.match.openVars );
123
124 if ( ! env.combine( i.match.env, openVars, indexer ) ) return false;
125
126 crnt.emplace_back( i );
127 envs.emplace_back( env );
128 varSets.emplace_back( openVars );
129 return true;
130 }
131
132 void backtrack() {
133 crnt.pop_back();
134 envs.pop_back();
135 varSets.pop_back();
136 }
137
138 OutType finalize() { return { envs.back(), varSets.back(), crnt }; }
139 };
140
[aaeacf4]141 /// Comparator for CandidateEnvMerger outputs that sums their costs and caches the stored
[fbecee5]142 /// sums
143 struct CandidateCost {
144 using Element = CandidateEnvMerger::OutType;
145 private:
146 const SymTab::Indexer& indexer; ///< Indexer for costing
147
148 public:
149 CandidateCost( const SymTab::Indexer& indexer ) : indexer(indexer) {}
150
151 /// reports the cost of an element
[c519942]152 Cost get( Element& x ) const {
153 // check cached cost
154 if ( x.cost != Cost::infinity ) return x.cost;
155
156 // generate cost
157 Cost k = Cost::zero;
158 for ( const auto& assn : x.assns ) {
[d76c588]159 // compute conversion cost from satisfying decl to assertion
[aaeacf4]160 k += computeConversionCost(
[7d01cf44]161 assn.match.adjType, assn.decl->get_type(), false, indexer, x.env );
[aaeacf4]162
[c519942]163 // mark vars+specialization cost on function-type assertions
[d76c588]164 FunctionType* func = GenPoly::getFunctionType( assn.match.cdata.id->get_type() );
[c519942]165 if ( ! func ) continue;
[aaeacf4]166
[c519942]167 for ( DeclarationWithType* formal : func->parameters ) {
168 k.decSpec( specCost( formal->get_type() ) );
169 }
170 k.incVar( func->forall.size() );
171 for ( TypeDecl* td : func->forall ) {
172 k.decSpec( td->assertions.size() );
[fbecee5]173 }
174 }
[c519942]175
176 // cache and return
177 x.cost = k;
178 return k;
[fbecee5]179 }
[aaeacf4]180
[fbecee5]181 /// compares elements by cost
[c519942]182 bool operator() ( Element& a, Element& b ) const {
[fbecee5]183 return get( a ) < get( b );
184 }
185 };
186
[0b00df0]187 /// Set of assertion resolutions, grouped by resolution ID
188 using InferCache = std::unordered_map< UniqueId, InferredParams >;
189
[b408364]190 /// Lexicographically-ordered vector of costs
191 using CostVec = std::vector< Cost >;
192
193 int compare( const CostVec & a, const CostVec & b ) {
194 unsigned i = 0;
195 do {
196 // lex-compare where shorter one is less
197 if ( i == a.size() ) {
198 return i == b.size() ? 0 : -1;
199 }
200 if ( i == b.size() /* && i < a.size() */ ) return 1;
[6f096d2]201
[b408364]202 int c = a[i].compare( b[i] );
203 if ( c != 0 ) return c;
204 } while ( ++i );
205 assert(!"unreachable");
206 }
207
208 bool operator< ( const CostVec & a, const CostVec & b ) { return compare( a, b ) < 0; }
209
[6d6e829]210 /// Flag for state iteration
211 enum IterateFlag { IterateState };
212
213 /// State needed to resolve a set of assertions
214 struct ResnState {
[0b00df0]215 Alternative alt; ///< Alternative assertion is rooted on
216 AssertionList need; ///< Assertions to find
217 AssertionSet newNeed; ///< New assertions for current resolutions
218 DeferList deferred; ///< Deferred matches
219 InferCache inferred; ///< Cache of already-inferred parameters
[b408364]220 CostVec costs; ///< Costs of recursive assertion satisfaction for disambiguation
[0b00df0]221 SymTab::Indexer& indexer; ///< Name lookup (depends on previous assertions)
[6d6e829]222
223 /// Initial resolution state for an alternative
[6f096d2]224 ResnState( Alternative & a, SymTab::Indexer & indexer )
[b408364]225 : alt(a), need(), newNeed(), deferred(), inferred(), costs{ Cost::zero }, indexer(indexer) {
[6d6e829]226 need.swap( a.need );
227 }
228
229 /// Updated resolution state with new need-list
[6f096d2]230 ResnState( ResnState && o, IterateFlag )
[aaeacf4]231 : alt(std::move(o.alt)), need(o.newNeed.begin(), o.newNeed.end()), newNeed(), deferred(),
[b408364]232 inferred(std::move(o.inferred)), costs(o.costs), indexer(o.indexer) {
233 costs.emplace_back( Cost::zero );
234 }
[6d6e829]235 };
236
237 /// Binds a single assertion, updating resolution state
[6f096d2]238 void bindAssertion( const DeclarationWithType * decl, AssertionSetValue info, Alternative & alt,
239 AssnCandidate & match, InferCache & inferred ) {
[aaeacf4]240
[6f096d2]241 const DeclarationWithType * candidate = match.cdata.id;
242 assertf( candidate->uniqueId, "Assertion candidate does not have a unique ID: %s", toString( candidate ).c_str() );
[6d6e829]243
[6f096d2]244 Expression * varExpr = match.cdata.combine( alt.cvtCost );
[2c187378]245 delete varExpr->result;
246 varExpr->result = match.adjType->clone();
[0b00df0]247 if ( match.resnSlot ) { varExpr->resnSlots.push_back( match.resnSlot ); }
[6d6e829]248
[0b00df0]249 // place newly-inferred assertion in proper place in cache
250 inferred[ info.resnSlot ][ decl->get_uniqueId() ] = ParamEntry{
[6f096d2]251 candidate->uniqueId, candidate->clone(), match.adjType->clone(), decl->get_type()->clone(),
[9aaacc27]252 varExpr };
[6d6e829]253 }
254
255 /// Adds a captured assertion to the symbol table
[6f096d2]256 void addToIndexer( AssertionSet & assertSet, SymTab::Indexer & indexer ) {
[e1f7eef]257 for ( auto& i : assertSet ) {
258 if ( i.second.isUsed ) {
259 indexer.addId( i.first );
[6d6e829]260 }
261 }
262 }
263
[0b00df0]264 // in AlternativeFinder.cc; unique ID for assertion resolutions
265 extern UniqueId globalResnSlot;
266
[6d6e829]267 /// Resolve a single assertion, in context
[6f096d2]268 bool resolveAssertion( AssertionItem & assn, ResnState & resn ) {
[6d6e829]269 // skip unused assertions
270 if ( ! assn.info.isUsed ) return true;
271
[052cd71]272 // lookup candidates for this assertion
273 std::list< SymTab::Indexer::IdData > candidates;
274 resn.indexer.lookupId( assn.decl->name, candidates );
275
276 // find the candidates that unify with the desired type
277 CandidateList matches;
[6f096d2]278 for ( const auto & cdata : candidates ) {
279 const DeclarationWithType * candidate = cdata.id;
[052cd71]280
[2fb35df]281 // ignore deleted candidates.
282 // NOTE: this behavior is different from main resolver.
283 // further investigations might be needed to determine
284 // if we should implement the same rule here
285 // (i.e. error if unique best match is deleted)
286 if (candidate->isDeleted) continue;
287
288 // build independent unification context. for candidate
[052cd71]289 AssertionSet have, newNeed;
290 TypeEnvironment newEnv{ resn.alt.env };
291 OpenVarSet newOpenVars{ resn.alt.openVars };
[6f096d2]292 Type * adjType = candidate->get_type()->clone();
[052cd71]293 adjustExprType( adjType, newEnv, resn.indexer );
294 renameTyVars( adjType );
295
296 // keep unifying candidates
[aaeacf4]297 if ( unify( assn.decl->get_type(), adjType, newEnv, newNeed, have, newOpenVars,
[052cd71]298 resn.indexer ) ) {
299 // set up binding slot for recursive assertions
300 UniqueId crntResnSlot = 0;
301 if ( ! newNeed.empty() ) {
302 crntResnSlot = ++globalResnSlot;
303 for ( auto& a : newNeed ) {
304 a.second.resnSlot = crntResnSlot;
[0b00df0]305 }
[2fd9f24]306 }
[e1f7eef]307
[aaeacf4]308 matches.emplace_back( cdata, adjType, std::move(newEnv), std::move(have),
[052cd71]309 std::move(newNeed), std::move(newOpenVars), crntResnSlot );
310 } else {
311 delete adjType;
312 }
[6d6e829]313 }
314
315 // break if no suitable assertion
316 if ( matches.empty() ) return false;
317
318 // defer if too many suitable assertions
319 if ( matches.size() > 1 ) {
[052cd71]320 resn.deferred.emplace_back( assn.decl, assn.info, std::move(matches) );
[6d6e829]321 return true;
322 }
323
324 // otherwise bind current match in ongoing scope
325 AssnCandidate& match = matches.front();
326 addToIndexer( match.have, resn.indexer );
327 resn.newNeed.insert( match.need.begin(), match.need.end() );
[052cd71]328 resn.alt.env = std::move(match.env);
329 resn.alt.openVars = std::move(match.openVars);
[6d6e829]330
[0b00df0]331 bindAssertion( assn.decl, assn.info, resn.alt, match, resn.inferred );
[6d6e829]332 return true;
333 }
334
[0b00df0]335 /// Associates inferred parameters with an expression
336 struct InferMatcher {
337 InferCache& inferred;
338
339 InferMatcher( InferCache& inferred ) : inferred( inferred ) {}
340
341 Expression* postmutate( Expression* expr ) {
[40290497]342 // defer missing inferred parameters until they are hopefully found later
343 std::vector<UniqueId> missingSlots;
[0b00df0]344 // place inferred parameters into resolution slots
345 for ( UniqueId slot : expr->resnSlots ) {
346 // fail if no matching parameters found
[40290497]347 auto it = inferred.find( slot );
348 if ( it == inferred.end() ) {
349 missingSlots.push_back( slot );
350 continue;
351 }
352 InferredParams& inferParams = it->second;
[aaeacf4]353
[0b00df0]354 // place inferred parameters into proper place in expression
355 for ( auto& entry : inferParams ) {
356 // recurse on inferParams of resolved expressions
357 entry.second.expr = postmutate( entry.second.expr );
358 // xxx - look at entry.second.inferParams?
[462a7c7]359 auto res = expr->inferParams.emplace( entry.first, entry.second );
360 assert(res.second);
[0b00df0]361 }
362 }
363
364 // clear resolution slots and return
[40290497]365 expr->resnSlots.swap( missingSlots );
[0b00df0]366 return expr;
367 }
368 };
369
[b408364]370 /// Map of alternative return types to recursive assertion satisfaction costs
371 using PruneMap = std::unordered_map<std::string, CostVec>;
372
373 /// Gets the pruning key for an alternative
374 std::string pruneKey( const Alternative & alt ) {
375 Type* resType = alt.expr->result->clone();
376 alt.env.apply( resType );
377 std::string resKey = SymTab::Mangler::mangleType( resType );
378 delete resType;
[1d760934]379 return resKey;
[b408364]380 }
[6f096d2]381
382 /// Replace resnSlots with inferParams and add alternative to output list, if meets pruning
[b408364]383 /// threshold.
384 void finalizeAssertions( ResnState& resn, PruneMap & pruneThresholds, AltList& out ) {
385 // prune if cheaper alternative for same key has already been generated
386 std::string resKey = pruneKey( resn.alt );
387 auto it = pruneThresholds.find( resKey );
388 if ( it != pruneThresholds.end() ) {
389 if ( it->second < resn.costs ) return;
390 } else {
391 pruneThresholds.emplace_hint( it, resKey, resn.costs );
392 }
393
394 // replace resolution slots with inferred params, add to output
395 PassVisitor<InferMatcher> matcher{ resn.inferred };
396 resn.alt.expr = resn.alt.expr->acceptMutator( matcher );
397 out.emplace_back( resn.alt );
[0b00df0]398 }
399
400 /// Limit to depth of recursion of assertion satisfaction
[aca6a54c]401 static const int recursionLimit = 7;
[d3b2c32a]402 /// Maximum number of simultaneously-deferred assertions to attempt concurrent satisfaction of
403 static const int deferLimit = 10;
[6d6e829]404
[4d2d45f9]405 void resolveAssertions( Alternative& alt, const SymTab::Indexer& indexer, AltList& out, std::list<std::string>& errors ) {
[6d6e829]406 // finish early if no assertions to resolve
407 if ( alt.need.empty() ) {
408 out.emplace_back( alt );
409 return;
410 }
411
412 // build list of possible resolutions
413 using ResnList = std::vector<ResnState>;
414 SymTab::Indexer root_indexer{ indexer };
415 ResnList resns{ ResnState{ alt, root_indexer } };
416 ResnList new_resns{};
[6f096d2]417
[b408364]418 // Pruning thresholds by result type of the output alternatives.
419 // Alternatives *should* be generated in sorted order, so no need to retroactively prune
420 PruneMap thresholds;
[6d6e829]421
422 // resolve assertions in breadth-first-order up to a limited number of levels deep
423 for ( unsigned level = 0; level < recursionLimit; ++level ) {
424 // scan over all mutually-compatible resolutions
425 for ( auto& resn : resns ) {
[b408364]426 // stop this branch if already found a better option
427 auto it = thresholds.find( pruneKey( resn.alt ) );
428 if ( it != thresholds.end() && it->second < resn.costs ) goto nextResn;
429
[6d6e829]430 // make initial pass at matching assertions
431 for ( auto& assn : resn.need ) {
432 // fail early if any assertion is not resolvable
[052cd71]433 if ( ! resolveAssertion( assn, resn ) ) {
[99d4584]434 Indenter tabs{ 3 };
[4d2d45f9]435 std::ostringstream ss;
436 ss << tabs << "Unsatisfiable alternative:\n";
437 resn.alt.print( ss, ++tabs );
[d3b2c32a]438 ss << (tabs-1) << "Could not satisfy assertion:\n";
439 assn.decl->print( ss, tabs );
[aaeacf4]440
[4d2d45f9]441 errors.emplace_back( ss.str() );
442 goto nextResn;
443 }
[6d6e829]444 }
445
446 if ( resn.deferred.empty() ) {
447 // either add successful match or push back next state
448 if ( resn.newNeed.empty() ) {
[b408364]449 finalizeAssertions( resn, thresholds, out );
[6d6e829]450 } else {
451 new_resns.emplace_back( std::move(resn), IterateState );
452 }
[d3b2c32a]453 } else if ( resn.deferred.size() > deferLimit ) {
454 // too many deferred assertions to attempt mutual compatibility
455 Indenter tabs{ 3 };
456 std::ostringstream ss;
457 ss << tabs << "Unsatisfiable alternative:\n";
458 resn.alt.print( ss, ++tabs );
459 ss << (tabs-1) << "Too many non-unique satisfying assignments for "
460 "assertions:\n";
461 for ( const auto& d : resn.deferred ) {
462 d.decl->print( ss, tabs );
463 }
464
465 errors.emplace_back( ss.str() );
466 goto nextResn;
[6d6e829]467 } else {
[b3bd772]468 // resolve deferred assertions by mutual compatibility
[6d6e829]469 std::vector<CandidateEnvMerger::OutType> compatible = filterCombos(
[aaeacf4]470 resn.deferred,
[6d6e829]471 CandidateEnvMerger{ resn.alt.env, resn.alt.openVars, resn.indexer } );
[4d2d45f9]472 // fail early if no mutually-compatible assertion satisfaction
473 if ( compatible.empty() ) {
[99d4584]474 Indenter tabs{ 3 };
[4d2d45f9]475 std::ostringstream ss;
476 ss << tabs << "Unsatisfiable alternative:\n";
477 resn.alt.print( ss, ++tabs );
[d3b2c32a]478 ss << (tabs-1) << "No mutually-compatible satisfaction for assertions:\n";
[4d2d45f9]479 for ( const auto& d : resn.deferred ) {
[052cd71]480 d.decl->print( ss, tabs );
[4d2d45f9]481 }
482
483 errors.emplace_back( ss.str() );
484 goto nextResn;
485 }
[b408364]486 // sort by cost for overall pruning
[b3bd772]487 CandidateCost coster{ resn.indexer };
488 std::sort( compatible.begin(), compatible.end(), coster );
489
490 for ( auto& compat : compatible ) {
[6d6e829]491 ResnState new_resn = resn;
492
493 // add compatible assertions to new resolution state
494 for ( DeferRef r : compat.assns ) {
495 AssnCandidate match = r.match;
496 addToIndexer( match.have, new_resn.indexer );
497 new_resn.newNeed.insert( match.need.begin(), match.need.end() );
498
[052cd71]499 bindAssertion( r.decl, r.info, new_resn.alt, match, new_resn.inferred );
[6d6e829]500 }
501
502 // set mutual environment into resolution state
503 new_resn.alt.env = std::move(compat.env);
504 new_resn.alt.openVars = std::move(compat.openVars);
505
[b408364]506 // mark cost of this path
507 new_resn.costs.back() += compat.cost;
508
[6d6e829]509 // either add sucessful match or push back next state
510 if ( new_resn.newNeed.empty() ) {
[b408364]511 finalizeAssertions( new_resn, thresholds, out );
[6d6e829]512 } else {
513 new_resns.emplace_back( std::move(new_resn), IterateState );
514 }
515 }
516 }
517 nextResn:; }
518
519 // finish or reset for next round
520 if ( new_resns.empty() ) return;
521 resns.swap( new_resns );
522 new_resns.clear();
523 }
[aaeacf4]524
[6d6e829]525 // exceeded recursion limit if reaches here
526 if ( out.empty() ) {
527 SemanticError( alt.expr->location, "Too many recursive assertions" );
528 }
529 }
530} // namespace ResolvExpr
531
532// Local Variables: //
533// tab-width: 4 //
534// mode: c++ //
535// compile-command: "make install" //
536// End: //
Note: See TracBrowser for help on using the repository browser.