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