source: src/ResolvExpr/ResolveAssertions.cc@ 40290497

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 40290497 was 40290497, checked in by Aaron Moss <a3moss@…>, 8 years ago

Fiddle with missing inferParams handling

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