source: src/ResolvExpr/ResolveAssertions.cc@ b10c39a0

ADT arm-eh ast-experimental cleanup-dtors enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since b10c39a0 was 052cd71, checked in by Aaron Moss <a3moss@…>, 7 years ago

revert unfruitful assertion caching attempt

  • Property mode set to 100644
File size: 15.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 <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
40namespace 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 it = cache.emplace_hint( it, &x, k );
159 }
160 return it->second;
161 }
162
163 /// compares elements by cost
164 bool operator() ( const Element& a, const Element& b ) const {
165 return get( a ) < get( b );
166 }
167 };
168
169 /// Set of assertion resolutions, grouped by resolution ID
170 using InferCache = std::unordered_map< UniqueId, InferredParams >;
171
172 /// Flag for state iteration
173 enum IterateFlag { IterateState };
174
175 /// State needed to resolve a set of assertions
176 struct ResnState {
177 Alternative alt; ///< Alternative assertion is rooted on
178 AssertionList need; ///< Assertions to find
179 AssertionSet newNeed; ///< New assertions for current resolutions
180 DeferList deferred; ///< Deferred matches
181 InferCache inferred; ///< Cache of already-inferred parameters
182 SymTab::Indexer& indexer; ///< Name lookup (depends on previous assertions)
183
184 /// Initial resolution state for an alternative
185 ResnState( Alternative& a, SymTab::Indexer& indexer )
186 : alt(a), need(), newNeed(), deferred(), inferred(), indexer(indexer) {
187 need.swap( a.need );
188 }
189
190 /// Updated resolution state with new need-list
191 ResnState( ResnState&& o, IterateFlag )
192 : alt(std::move(o.alt)), need(o.newNeed.begin(), o.newNeed.end()), newNeed(), deferred(),
193 inferred(std::move(o.inferred)), indexer(o.indexer) {}
194 };
195
196 /// Binds a single assertion, updating resolution state
197 void bindAssertion( const DeclarationWithType* decl, AssertionSetValue info, Alternative& alt,
198 AssnCandidate& match, InferCache& inferred ) {
199
200 DeclarationWithType* candidate = match.cdata.id;
201 assertf( candidate->get_uniqueId(), "Assertion candidate does not have a unique ID: %s", toString( candidate ).c_str() );
202
203 Expression* varExpr = match.cdata.combine( alt.cvtCost );
204 delete varExpr->result;
205 varExpr->result = match.adjType->clone();
206 if ( match.resnSlot ) { varExpr->resnSlots.push_back( match.resnSlot ); }
207
208 // place newly-inferred assertion in proper place in cache
209 inferred[ info.resnSlot ][ decl->get_uniqueId() ] = ParamEntry{
210 candidate->get_uniqueId(), match.adjType->clone(), decl->get_type()->clone(),
211 varExpr };
212 }
213
214 /// Adds a captured assertion to the symbol table
215 void addToIndexer( AssertionSet &assertSet, SymTab::Indexer &indexer ) {
216 for ( auto& i : assertSet ) {
217 if ( i.second.isUsed ) {
218 indexer.addId( i.first );
219 }
220 }
221 }
222
223 // in AlternativeFinder.cc; unique ID for assertion resolutions
224 extern UniqueId globalResnSlot;
225
226 /// Resolve a single assertion, in context
227 bool resolveAssertion( AssertionItem& assn, ResnState& resn ) {
228 // skip unused assertions
229 if ( ! assn.info.isUsed ) return true;
230
231 // lookup candidates for this assertion
232 std::list< SymTab::Indexer::IdData > candidates;
233 resn.indexer.lookupId( assn.decl->name, candidates );
234
235 // find the candidates that unify with the desired type
236 CandidateList matches;
237 for ( const auto& cdata : candidates ) {
238 DeclarationWithType* candidate = cdata.id;
239
240 // build independent unification context for candidate
241 AssertionSet have, newNeed;
242 TypeEnvironment newEnv{ resn.alt.env };
243 OpenVarSet newOpenVars{ resn.alt.openVars };
244 Type* adjType = candidate->get_type()->clone();
245 adjustExprType( adjType, newEnv, resn.indexer );
246 renameTyVars( adjType );
247
248 // keep unifying candidates
249 if ( unify( assn.decl->get_type(), adjType, newEnv, newNeed, have, newOpenVars,
250 resn.indexer ) ) {
251 // set up binding slot for recursive assertions
252 UniqueId crntResnSlot = 0;
253 if ( ! newNeed.empty() ) {
254 crntResnSlot = ++globalResnSlot;
255 for ( auto& a : newNeed ) {
256 a.second.resnSlot = crntResnSlot;
257 }
258 }
259
260 matches.emplace_back( cdata, adjType, std::move(newEnv), std::move(have),
261 std::move(newNeed), std::move(newOpenVars), crntResnSlot );
262 } else {
263 delete adjType;
264 }
265 }
266
267 // break if no suitable assertion
268 if ( matches.empty() ) return false;
269
270 // defer if too many suitable assertions
271 if ( matches.size() > 1 ) {
272 resn.deferred.emplace_back( assn.decl, assn.info, std::move(matches) );
273 return true;
274 }
275
276 // otherwise bind current match in ongoing scope
277 AssnCandidate& match = matches.front();
278 addToIndexer( match.have, resn.indexer );
279 resn.newNeed.insert( match.need.begin(), match.need.end() );
280 resn.alt.env = std::move(match.env);
281 resn.alt.openVars = std::move(match.openVars);
282
283 bindAssertion( assn.decl, assn.info, resn.alt, match, resn.inferred );
284 return true;
285 }
286
287 /// Associates inferred parameters with an expression
288 struct InferMatcher {
289 InferCache& inferred;
290
291 InferMatcher( InferCache& inferred ) : inferred( inferred ) {}
292
293 Expression* postmutate( Expression* expr ) {
294 // defer missing inferred parameters until they are hopefully found later
295 std::vector<UniqueId> missingSlots;
296 // place inferred parameters into resolution slots
297 for ( UniqueId slot : expr->resnSlots ) {
298 // fail if no matching parameters found
299 auto it = inferred.find( slot );
300 if ( it == inferred.end() ) {
301 missingSlots.push_back( slot );
302 continue;
303 }
304 InferredParams& inferParams = it->second;
305
306 // place inferred parameters into proper place in expression
307 for ( auto& entry : inferParams ) {
308 // recurse on inferParams of resolved expressions
309 entry.second.expr = postmutate( entry.second.expr );
310 // xxx - look at entry.second.inferParams?
311 expr->inferParams[ entry.first ] = entry.second;
312 }
313 }
314
315 // clear resolution slots and return
316 expr->resnSlots.swap( missingSlots );
317 return expr;
318 }
319 };
320
321 void finalizeAssertions( Alternative& alt, InferCache& inferred, AltList& out ) {
322 PassVisitor<InferMatcher> matcher{ inferred };
323 alt.expr = alt.expr->acceptMutator( matcher );
324 out.emplace_back( alt );
325 }
326
327 /// Limit to depth of recursion of assertion satisfaction
328 static const int recursionLimit = /* 10 */ 4;
329
330 void resolveAssertions( Alternative& alt, const SymTab::Indexer& indexer, AltList& out, std::list<std::string>& errors ) {
331 // finish early if no assertions to resolve
332 if ( alt.need.empty() ) {
333 out.emplace_back( alt );
334 return;
335 }
336
337 // build list of possible resolutions
338 using ResnList = std::vector<ResnState>;
339 SymTab::Indexer root_indexer{ indexer };
340 ResnList resns{ ResnState{ alt, root_indexer } };
341 ResnList new_resns{};
342
343 // resolve assertions in breadth-first-order up to a limited number of levels deep
344 for ( unsigned level = 0; level < recursionLimit; ++level ) {
345 // scan over all mutually-compatible resolutions
346 for ( auto& resn : resns ) {
347 // make initial pass at matching assertions
348 for ( auto& assn : resn.need ) {
349 // fail early if any assertion is not resolvable
350 if ( ! resolveAssertion( assn, resn ) ) {
351 Indenter tabs{ Indenter::tabsize, 3 };
352 std::ostringstream ss;
353 ss << tabs << "Unsatisfiable alternative:\n";
354 resn.alt.print( ss, ++tabs );
355 ss << --tabs << "Could not satisfy assertion:\n";
356 assn.decl->print( ss, ++tabs );
357
358 errors.emplace_back( ss.str() );
359 goto nextResn;
360 }
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
372 std::vector<CandidateEnvMerger::OutType> compatible = filterCombos(
373 resn.deferred,
374 CandidateEnvMerger{ resn.alt.env, resn.alt.openVars, resn.indexer } );
375 // fail early if no mutually-compatible assertion satisfaction
376 if ( compatible.empty() ) {
377 Indenter tabs{ Indenter::tabsize, 3 };
378 std::ostringstream ss;
379 ss << tabs << "Unsatisfiable alternative:\n";
380 resn.alt.print( ss, ++tabs );
381 ss << --tabs << "No mutually-compatible satisfaction for assertions:\n";
382 ++tabs;
383 for ( const auto& d : resn.deferred ) {
384 d.decl->print( ss, tabs );
385 }
386
387 errors.emplace_back( ss.str() );
388 goto nextResn;
389 }
390 // sort by cost
391 CandidateCost coster{ resn.indexer };
392 std::sort( compatible.begin(), compatible.end(), coster );
393
394 // keep map of detected options
395 std::unordered_map<std::string, Cost> found;
396 for ( auto& compat : compatible ) {
397 // filter by environment-adjusted result type, keep only cheapest option
398 Type* resType = alt.expr->result->clone();
399 compat.env.apply( resType );
400 // skip if cheaper alternative already processed with same result type
401 Cost resCost = coster.get( compat );
402 auto it = found.emplace( SymTab::Mangler::mangleType( resType ), resCost );
403 delete resType;
404 if ( it.second == false && it.first->second < resCost ) continue;
405
406 // proceed with resolution step
407 ResnState new_resn = resn;
408
409 // add compatible assertions to new resolution state
410 for ( DeferRef r : compat.assns ) {
411 AssnCandidate match = r.match;
412 addToIndexer( match.have, new_resn.indexer );
413 new_resn.newNeed.insert( match.need.begin(), match.need.end() );
414
415 bindAssertion( r.decl, r.info, new_resn.alt, match, new_resn.inferred );
416 }
417
418 // set mutual environment into resolution state
419 new_resn.alt.env = std::move(compat.env);
420 new_resn.alt.openVars = std::move(compat.openVars);
421
422 // either add sucessful match or push back next state
423 if ( new_resn.newNeed.empty() ) {
424 finalizeAssertions( new_resn.alt, new_resn.inferred, out );
425 } else {
426 new_resns.emplace_back( std::move(new_resn), IterateState );
427 }
428 }
429 }
430 nextResn:; }
431
432 // finish or reset for next round
433 if ( new_resns.empty() ) return;
434 resns.swap( new_resns );
435 new_resns.clear();
436 }
437
438 // exceeded recursion limit if reaches here
439 if ( out.empty() ) {
440 SemanticError( alt.expr->location, "Too many recursive assertions" );
441 }
442 }
443} // namespace ResolvExpr
444
445// Local Variables: //
446// tab-width: 4 //
447// mode: c++ //
448// compile-command: "make install" //
449// End: //
Note: See TracBrowser for help on using the repository browser.