source: src/ResolvExpr/ResolveAssertions.cc@ 83ab931

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr no_list persistent-indexer pthread-emulation qualifiedEnum stuck-waitfor-destruct
Last change on this file since 83ab931 was 83ab931, checked in by Aaron Moss <a3moss@…>, 7 years ago

Fix type renaming issue with deferred resolution

  • Property mode set to 100644
File size: 14.6 KB
Line 
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
11// Last Modified By : Aaron B. Moss
12// Last Modified On : Fri Oct 05 13:46:00 2018
13// Update Count : 1
14//
15
16#include "ResolveAssertions.h"
17
18#include <cassert> // for assertf
19#include <list> // for list
20#include <unordered_map> // for unordered_map, unordered_multimap
21#include <utility> // for move
22#include <vector> // for vector
23
24#include "Alternative.h" // for Alternative, AssertionItem, AssertionList
25#include "Common/FilterCombos.h" // for filterCombos
26#include "Common/utility.h" // for sort_mins
27#include "ResolvExpr/RenameVars.h" // for renameTyVars
28#include "SymTab/Indexer.h" // for Indexer
29#include "SynTree/Expression.h" // for InferredParams
30#include "TypeEnvironment.h" // for TypeEnvironment, etc.
31#include "typeops.h" // for adjustExprType
32#include "Unify.h" // for unify
33
34namespace ResolvExpr {
35 /// Unified assertion candidate
36 struct AssnCandidate {
37 SymTab::Indexer::IdData cdata; ///< Satisfying declaration
38 Type* adjType; ///< Satisfying type
39 TypeEnvironment env; ///< Post-unification environment
40 AssertionSet have; ///< Post-unification have-set
41 AssertionSet need; ///< Post-unification need-set
42 OpenVarSet openVars; ///< Post-unification open-var set
43 UniqueId resnSlot; ///< Slot for any recursive assertion IDs
44
45 AssnCandidate( const SymTab::Indexer::IdData& cdata, Type* adjType, TypeEnvironment&& env,
46 AssertionSet&& have, AssertionSet&& need, OpenVarSet&& openVars, UniqueId resnSlot )
47 : cdata(cdata), adjType(adjType), env(std::move(env)), have(std::move(have)),
48 need(std::move(need)), openVars(std::move(openVars)), resnSlot(resnSlot) {}
49 };
50
51 /// List of candidate assertion resolutions
52 using CandidateList = std::vector<AssnCandidate>;
53
54 /// Reference to single deferred item
55 struct DeferRef {
56 const DeclarationWithType* decl;
57 const AssertionSetValue& info;
58 const AssnCandidate& match;
59 };
60
61 /// Wrapper for the deferred items from a single assertion resolution.
62 /// Acts like indexed list of DeferRef
63 struct DeferItem {
64 DeclarationWithType* decl;
65 AssertionSetValue info;
66 CandidateList matches;
67
68 DeferItem( DeclarationWithType* decl, const AssertionSetValue& info,
69 CandidateList&& matches )
70 : decl(decl), info(info), matches(std::move(matches)) {}
71
72 bool empty() const { return matches.empty(); }
73
74 CandidateList::size_type size() const { return matches.size(); }
75
76 DeferRef operator[] ( unsigned i ) const { return { decl, info, matches[i] }; }
77 };
78
79 /// List of deferred resolution items
80 using DeferList = std::vector<DeferItem>;
81
82 /// Combo iterator that combines candidates into an output list, merging their environments.
83 /// Rejects an appended candidate if the environments cannot be merged.
84 class CandidateEnvMerger {
85 /// Current list of merged candidates
86 std::vector<DeferRef> crnt;
87 /// Stack of environments to support backtracking
88 std::vector<TypeEnvironment> envs;
89 /// Stack of open variables to support backtracking
90 std::vector<OpenVarSet> varSets;
91 /// Indexer to use for merges
92 const SymTab::Indexer& indexer;
93
94 public:
95 /// The merged environment/open variables and the list of candidates
96 struct OutType {
97 TypeEnvironment env;
98 OpenVarSet openVars;
99 std::vector<DeferRef> assns;
100
101 OutType( const TypeEnvironment& env, const OpenVarSet& openVars,
102 const std::vector<DeferRef>& assns )
103 : env(env), openVars(openVars), assns(assns) {}
104 };
105
106 CandidateEnvMerger( const TypeEnvironment& env, const OpenVarSet& openVars,
107 const SymTab::Indexer& indexer )
108 : crnt(), envs{ env }, varSets{ openVars }, indexer(indexer) {}
109
110 bool append( DeferRef i ) {
111 TypeEnvironment env = envs.back();
112 OpenVarSet openVars = varSets.back();
113 mergeOpenVars( openVars, i.match.openVars );
114
115 if ( ! env.combine( i.match.env, openVars, indexer ) ) return false;
116
117 crnt.emplace_back( i );
118 envs.emplace_back( env );
119 varSets.emplace_back( openVars );
120 return true;
121 }
122
123 void backtrack() {
124 crnt.pop_back();
125 envs.pop_back();
126 varSets.pop_back();
127 }
128
129 OutType finalize() { return { envs.back(), varSets.back(), crnt }; }
130 };
131
132 /// Comparator for CandidateEnvMerger outputs that sums their costs and caches the stored
133 /// sums
134 struct CandidateCost {
135 using Element = CandidateEnvMerger::OutType;
136 private:
137 using Memo = std::unordered_map<const Element*, Cost>;
138 mutable Memo cache; ///< cache of element costs
139 const SymTab::Indexer& indexer; ///< Indexer for costing
140
141 public:
142 CandidateCost( const SymTab::Indexer& indexer ) : indexer(indexer) {}
143
144 /// reports the cost of an element
145 Cost get( const Element& x ) const {
146 Memo::const_iterator it = cache.find( &x );
147 if ( it == cache.end() ) {
148 Cost k = Cost::zero;
149 for ( const auto& assn : x.assns ) {
150 k += computeConversionCost(
151 assn.match.adjType, assn.decl->get_type(), indexer, x.env );
152 }
153 it = cache.emplace_hint( it, &x, k );
154 }
155 return it->second;
156 }
157
158 /// compares elements by cost
159 bool operator() ( const Element& a, const Element& b ) const {
160 return get( a ) < get( b );
161 }
162 };
163
164 /// Set of assertion resolutions, grouped by resolution ID
165 using InferCache = std::unordered_map< UniqueId, InferredParams >;
166
167 /// Flag for state iteration
168 enum IterateFlag { IterateState };
169
170 /// State needed to resolve a set of assertions
171 struct ResnState {
172 Alternative alt; ///< Alternative assertion is rooted on
173 AssertionList need; ///< Assertions to find
174 AssertionSet newNeed; ///< New assertions for current resolutions
175 DeferList deferred; ///< Deferred matches
176 InferCache inferred; ///< Cache of already-inferred parameters
177 SymTab::Indexer& indexer; ///< Name lookup (depends on previous assertions)
178
179 /// Initial resolution state for an alternative
180 ResnState( Alternative& a, SymTab::Indexer& indexer )
181 : alt(a), need(), newNeed(), deferred(), inferred(), indexer(indexer) {
182 need.swap( a.need );
183 }
184
185 /// Updated resolution state with new need-list
186 ResnState( ResnState&& o, IterateFlag )
187 : alt(std::move(o.alt)), need(o.newNeed.begin(), o.newNeed.end()), newNeed(), deferred(),
188 inferred(std::move(o.inferred)), indexer(o.indexer) {}
189 };
190
191 /// Binds a single assertion, updating resolution state
192 void bindAssertion( const DeclarationWithType* decl, AssertionSetValue info, Alternative& alt,
193 AssnCandidate& match, InferCache& inferred ) {
194
195 DeclarationWithType* candidate = match.cdata.id;
196 assertf( candidate->get_uniqueId(), "Assertion candidate does not have a unique ID: %s", toString( candidate ).c_str() );
197
198 Expression* varExpr = match.cdata.combine( alt.cvtCost );
199 delete varExpr->result;
200 varExpr->result = match.adjType->clone();
201 if ( match.resnSlot ) { varExpr->resnSlots.push_back( match.resnSlot ); }
202
203 // place newly-inferred assertion in proper place in cache
204 inferred[ info.resnSlot ][ decl->get_uniqueId() ] = ParamEntry{
205 candidate->get_uniqueId(), match.adjType, decl->get_type()->clone(), varExpr };
206
207 // // follow the current assertion's ID chain to find the correct set of inferred parameters
208 // // to add the candidate o (i.e. the set of inferred parameters belonging to the entity
209 // // which requested the assertion parameter)
210 // InferredParams* inferParams = &alt.expr->inferParams;
211 // for ( UniqueId id : info.idChain ) {
212 // inferParams = (*inferParams)[ id ].inferParams.get();
213 // }
214
215 // (*inferParams)[ decl->get_uniqueId() ] = ParamEntry{
216 // candidate->get_uniqueId(), match.adjType, decl->get_type()->clone(), varExpr };
217 }
218
219 /// Adds a captured assertion to the symbol table
220 void addToIndexer( AssertionSet &assertSet, SymTab::Indexer &indexer ) {
221 for ( AssertionSet::iterator i = assertSet.begin(); i != assertSet.end(); ++i ) {
222 if ( i->second.isUsed ) {
223 indexer.addId( i->first );
224 }
225 }
226 }
227
228 // in AlternativeFinder.cc; unique ID for assertion resolutions
229 extern UniqueId globalResnSlot;
230
231 /// Resolve a single assertion, in context
232 bool resolveAssertion( AssertionItem& assn, ResnState& resn ) {
233 // skip unused assertions
234 if ( ! assn.info.isUsed ) return true;
235
236 // lookup candidates for this assertion
237 std::list< SymTab::Indexer::IdData > candidates;
238 resn.indexer.lookupId( assn.decl->name, candidates );
239
240 // find the candidates that unify with the desired type
241 CandidateList matches;
242 for ( const auto& cdata : candidates ) {
243 DeclarationWithType* candidate = cdata.id;
244
245 // build independent unification context for candidate
246 AssertionSet have, newNeed;
247 TypeEnvironment newEnv{ resn.alt.env };
248 OpenVarSet newOpenVars{ resn.alt.openVars };
249 Type* adjType = candidate->get_type()->clone();
250 adjustExprType( adjType, newEnv, resn.indexer );
251 renameTyVars( adjType );
252
253 // keep unifying candidates
254 if ( unify( assn.decl->get_type(), adjType, newEnv, newNeed, have, newOpenVars,
255 resn.indexer ) ) {
256 // set up binding slot for recursive assertions
257 UniqueId crntResnSlot = 0;
258 if ( ! newNeed.empty() ) {
259 crntResnSlot = ++globalResnSlot;
260 for ( auto& a : newNeed ) {
261 a.second.resnSlot = crntResnSlot;
262 }
263 }
264 // // set up idChain on new assertions
265 // for ( auto& a : newNeed ) {
266 // a.second.idChain = assn.info.idChain;
267 // a.second.idChain.push_back( assn.decl->get_uniqueId() );
268 // }
269
270 matches.emplace_back( cdata, adjType, std::move(newEnv), std::move(have),
271 std::move(newNeed), std::move(newOpenVars), crntResnSlot );
272 } else {
273 delete adjType;
274 }
275 }
276
277 // break if no suitable assertion
278 if ( matches.empty() ) return false;
279
280 // defer if too many suitable assertions
281 if ( matches.size() > 1 ) {
282 resn.deferred.emplace_back( assn.decl, assn.info, std::move(matches) );
283 return true;
284 }
285
286 // otherwise bind current match in ongoing scope
287 AssnCandidate& match = matches.front();
288 addToIndexer( match.have, resn.indexer );
289 resn.newNeed.insert( match.need.begin(), match.need.end() );
290 resn.alt.env = std::move(match.env);
291 resn.alt.openVars = std::move(match.openVars);
292
293 bindAssertion( assn.decl, assn.info, resn.alt, match, resn.inferred );
294 return true;
295 }
296
297 /// Associates inferred parameters with an expression
298 struct InferMatcher {
299 InferCache& inferred;
300
301 InferMatcher( InferCache& inferred ) : inferred( inferred ) {}
302
303 Expression* postmutate( Expression* expr ) {
304 // defer missing inferred parameters until they are hopefully found later
305 std::vector<UniqueId> missingSlots;
306 // place inferred parameters into resolution slots
307 for ( UniqueId slot : expr->resnSlots ) {
308 // fail if no matching parameters found
309 auto it = inferred.find( slot );
310 if ( it == inferred.end() ) {
311 missingSlots.push_back( slot );
312 continue;
313 }
314 InferredParams& inferParams = it->second;
315
316 // place inferred parameters into proper place in expression
317 for ( auto& entry : inferParams ) {
318 // recurse on inferParams of resolved expressions
319 entry.second.expr = postmutate( entry.second.expr );
320 // xxx - look at entry.second.inferParams?
321 expr->inferParams[ entry.first ] = entry.second;
322 }
323 }
324
325 // clear resolution slots and return
326 expr->resnSlots.swap( missingSlots );
327 return expr;
328 }
329 };
330
331 void finalizeAssertions( Alternative& alt, InferCache& inferred, AltList& out ) {
332 PassVisitor<InferMatcher> matcher{ inferred };
333 alt.expr = alt.expr->acceptMutator( matcher );
334 out.emplace_back( alt );
335 }
336
337 /// Limit to depth of recursion of assertion satisfaction
338 static const int recursionLimit = /* 10 */ 4;
339
340 void resolveAssertions( Alternative& alt, const SymTab::Indexer& indexer, AltList& out ) {
341 // finish early if no assertions to resolve
342 if ( alt.need.empty() ) {
343 out.emplace_back( alt );
344 return;
345 }
346
347 // build list of possible resolutions
348 using ResnList = std::vector<ResnState>;
349 SymTab::Indexer root_indexer{ indexer };
350 ResnList resns{ ResnState{ alt, root_indexer } };
351 ResnList new_resns{};
352
353 // resolve assertions in breadth-first-order up to a limited number of levels deep
354 for ( unsigned level = 0; level < recursionLimit; ++level ) {
355 // scan over all mutually-compatible resolutions
356 for ( auto& resn : resns ) {
357 // make initial pass at matching assertions
358 for ( auto& assn : resn.need ) {
359 // fail early if any assertion is not resolvable
360 if ( ! resolveAssertion( assn, resn ) ) goto nextResn;
361 }
362
363 if ( resn.deferred.empty() ) {
364 // either add successful match or push back next state
365 if ( resn.newNeed.empty() ) {
366 finalizeAssertions( resn.alt, resn.inferred, out );
367 } else {
368 new_resns.emplace_back( std::move(resn), IterateState );
369 }
370 } else {
371 // resolve deferred assertions by mutual compatibility and sort by cost
372 std::vector<CandidateEnvMerger::OutType> compatible = filterCombos(
373 resn.deferred,
374 CandidateEnvMerger{ resn.alt.env, resn.alt.openVars, resn.indexer } );
375 auto lmin = sort_mins( compatible.begin(), compatible.end(),
376 CandidateCost{resn.indexer} );
377
378 for ( auto it = compatible.begin(); it != lmin ; ++it ) {
379 auto& compat = *it;
380 ResnState new_resn = resn;
381
382 // add compatible assertions to new resolution state
383 for ( DeferRef r : compat.assns ) {
384 AssnCandidate match = r.match;
385 addToIndexer( match.have, new_resn.indexer );
386 new_resn.newNeed.insert( match.need.begin(), match.need.end() );
387
388 bindAssertion( r.decl, r.info, new_resn.alt, match, new_resn.inferred );
389 }
390
391 // set mutual environment into resolution state
392 new_resn.alt.env = std::move(compat.env);
393 new_resn.alt.openVars = std::move(compat.openVars);
394
395 // either add sucessful match or push back next state
396 if ( new_resn.newNeed.empty() ) {
397 finalizeAssertions( new_resn.alt, new_resn.inferred, out );
398 } else {
399 new_resns.emplace_back( std::move(new_resn), IterateState );
400 }
401 }
402 }
403 nextResn:; }
404
405 // finish or reset for next round
406 if ( new_resns.empty() ) return;
407 resns.swap( new_resns );
408 new_resns.clear();
409 }
410
411 // exceeded recursion limit if reaches here
412 if ( out.empty() ) {
413 SemanticError( alt.expr->location, "Too many recursive assertions" );
414 }
415 }
416} // namespace ResolvExpr
417
418// Local Variables: //
419// tab-width: 4 //
420// mode: c++ //
421// compile-command: "make install" //
422// End: //
Note: See TracBrowser for help on using the repository browser.