source: src/ResolvExpr/ResolveAssertions.cc @ 9aaacc27

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resnenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprno_listpersistent-indexerpthread-emulationqualifiedEnum
Last change on this file since 9aaacc27 was 9aaacc27, checked in by Aaron Moss <a3moss@…>, 5 years ago

Fix segfault in some tests

  • 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->clone(), decl->get_type()->clone(), 
206                                varExpr };
207
208                // // follow the current assertion's ID chain to find the correct set of inferred parameters
209                // // to add the candidate o (i.e. the set of inferred parameters belonging to the entity
210                // // which requested the assertion parameter)
211                // InferredParams* inferParams = &alt.expr->inferParams;
212                // for ( UniqueId id : info.idChain ) {
213                //      inferParams = (*inferParams)[ id ].inferParams.get();
214                // }
215
216                // (*inferParams)[ decl->get_uniqueId() ] = ParamEntry{
217                //              candidate->get_uniqueId(), match.adjType, decl->get_type()->clone(), varExpr };
218        }
219
220        /// Adds a captured assertion to the symbol table
221        void addToIndexer( AssertionSet &assertSet, SymTab::Indexer &indexer ) {
222                for ( AssertionSet::iterator i = assertSet.begin(); i != assertSet.end(); ++i ) {
223                        if ( i->second.isUsed ) {
224                                indexer.addId( i->first );
225                        }
226                }
227        }
228
229        // in AlternativeFinder.cc; unique ID for assertion resolutions
230        extern UniqueId globalResnSlot;
231
232        /// Resolve a single assertion, in context
233        bool resolveAssertion( AssertionItem& assn, ResnState& resn ) {
234                // skip unused assertions
235                if ( ! assn.info.isUsed ) return true;
236
237                // lookup candidates for this assertion
238                std::list< SymTab::Indexer::IdData > candidates;
239                resn.indexer.lookupId( assn.decl->name, candidates );
240
241                // find the candidates that unify with the desired type
242                CandidateList matches;
243                for ( const auto& cdata : candidates ) {
244                        DeclarationWithType* candidate = cdata.id;
245
246                        // build independent unification context for candidate
247                        AssertionSet have, newNeed;
248                        TypeEnvironment newEnv{ resn.alt.env };
249                        OpenVarSet newOpenVars{ resn.alt.openVars };
250                        Type* adjType = candidate->get_type()->clone();
251                        adjustExprType( adjType, newEnv, resn.indexer );
252                        renameTyVars( adjType );
253
254                        // keep unifying candidates
255                        if ( unify( assn.decl->get_type(), adjType, newEnv, newNeed, have, newOpenVars, 
256                                        resn.indexer ) ) {
257                                // set up binding slot for recursive assertions
258                                UniqueId crntResnSlot = 0;
259                                if ( ! newNeed.empty() ) {
260                                        crntResnSlot = ++globalResnSlot;
261                                        for ( auto& a : newNeed ) {
262                                                a.second.resnSlot = crntResnSlot;
263                                        }
264                                }
265                                // // set up idChain on new assertions
266                                // for ( auto& a : newNeed ) {
267                                //      a.second.idChain = assn.info.idChain;
268                                //      a.second.idChain.push_back( assn.decl->get_uniqueId() );
269                                // }
270
271                                matches.emplace_back( cdata, adjType, std::move(newEnv), std::move(have), 
272                                        std::move(newNeed), std::move(newOpenVars), crntResnSlot );
273                        } else {
274                                //delete adjType;
275                        }
276                }
277
278                // break if no suitable assertion
279                if ( matches.empty() ) return false;
280
281                // defer if too many suitable assertions
282                if ( matches.size() > 1 ) {
283                        resn.deferred.emplace_back( assn.decl, assn.info, std::move(matches) );
284                        return true;
285                }
286
287                // otherwise bind current match in ongoing scope
288                AssnCandidate& match = matches.front();
289                addToIndexer( match.have, resn.indexer );
290                resn.newNeed.insert( match.need.begin(), match.need.end() );
291                resn.alt.env = std::move(match.env);
292                resn.alt.openVars = std::move(match.openVars);
293
294                bindAssertion( assn.decl, assn.info, resn.alt, match, resn.inferred );
295                return true;
296        }
297
298        /// Associates inferred parameters with an expression
299        struct InferMatcher {
300                InferCache& inferred;
301
302                InferMatcher( InferCache& inferred ) : inferred( inferred ) {}
303
304                Expression* postmutate( Expression* expr ) {
305                        // defer missing inferred parameters until they are hopefully found later
306                        std::vector<UniqueId> missingSlots;
307                        // place inferred parameters into resolution slots
308                        for ( UniqueId slot : expr->resnSlots ) {
309                                // fail if no matching parameters found
310                                auto it = inferred.find( slot );
311                                if ( it == inferred.end() ) {
312                                        missingSlots.push_back( slot );
313                                        continue;
314                                }
315                                InferredParams& inferParams = it->second;
316                               
317                                // place inferred parameters into proper place in expression
318                                for ( auto& entry : inferParams ) {
319                                        // recurse on inferParams of resolved expressions
320                                        entry.second.expr = postmutate( entry.second.expr );
321                                        // xxx - look at entry.second.inferParams?
322                                        expr->inferParams[ entry.first ] = entry.second;
323                                }
324                        }
325
326                        // clear resolution slots and return
327                        expr->resnSlots.swap( missingSlots );
328                        return expr;
329                }
330        };
331
332        void finalizeAssertions( Alternative& alt, InferCache& inferred, AltList& out ) {
333                PassVisitor<InferMatcher> matcher{ inferred };
334                alt.expr = alt.expr->acceptMutator( matcher );
335                out.emplace_back( alt );
336        }
337
338        /// Limit to depth of recursion of assertion satisfaction
339        static const int recursionLimit = /* 10 */ 4;
340
341        void resolveAssertions( Alternative& alt, const SymTab::Indexer& indexer, AltList& out ) {
342                // finish early if no assertions to resolve
343                if ( alt.need.empty() ) {
344                        out.emplace_back( alt );
345                        return;
346                }
347
348                // build list of possible resolutions
349                using ResnList = std::vector<ResnState>;
350                SymTab::Indexer root_indexer{ indexer };
351                ResnList resns{ ResnState{ alt, root_indexer } };
352                ResnList new_resns{};
353
354                // resolve assertions in breadth-first-order up to a limited number of levels deep
355                for ( unsigned level = 0; level < recursionLimit; ++level ) {
356                        // scan over all mutually-compatible resolutions
357                        for ( auto& resn : resns ) {
358                                // make initial pass at matching assertions
359                                for ( auto& assn : resn.need ) {
360                                        // fail early if any assertion is not resolvable
361                                        if ( ! resolveAssertion( assn, resn ) ) goto nextResn;
362                                }
363
364                                if ( resn.deferred.empty() ) {
365                                        // either add successful match or push back next state
366                                        if ( resn.newNeed.empty() ) {
367                                                finalizeAssertions( resn.alt, resn.inferred, out );
368                                        } else {
369                                                new_resns.emplace_back( std::move(resn), IterateState );
370                                        }
371                                } else {
372                                        // resolve deferred assertions by mutual compatibility and sort by cost
373                                        std::vector<CandidateEnvMerger::OutType> compatible = filterCombos(
374                                                resn.deferred, 
375                                                CandidateEnvMerger{ resn.alt.env, resn.alt.openVars, resn.indexer } );
376                                        auto lmin = sort_mins( compatible.begin(), compatible.end(), 
377                                                CandidateCost{resn.indexer} );
378                                       
379                                        for ( auto it = compatible.begin(); it != lmin ; ++it ) {
380                                                auto& compat = *it;
381                                                ResnState new_resn = resn;
382
383                                                // add compatible assertions to new resolution state
384                                                for ( DeferRef r : compat.assns ) {
385                                                        AssnCandidate match = r.match;
386                                                        addToIndexer( match.have, new_resn.indexer );
387                                                        new_resn.newNeed.insert( match.need.begin(), match.need.end() );
388
389                                                        bindAssertion( r.decl, r.info, new_resn.alt, match, new_resn.inferred );
390                                                }
391
392                                                // set mutual environment into resolution state
393                                                new_resn.alt.env = std::move(compat.env);
394                                                new_resn.alt.openVars = std::move(compat.openVars);
395
396                                                // either add sucessful match or push back next state
397                                                if ( new_resn.newNeed.empty() ) {
398                                                        finalizeAssertions( new_resn.alt, new_resn.inferred, out );
399                                                } else {
400                                                        new_resns.emplace_back( std::move(new_resn), IterateState );
401                                                }
402                                        }
403                                }
404                        nextResn:; }
405
406                        // finish or reset for next round
407                        if ( new_resns.empty() ) return;
408                        resns.swap( new_resns );
409                        new_resns.clear();
410                }
411               
412                // exceeded recursion limit if reaches here
413                if ( out.empty() ) {
414                        SemanticError( alt.expr->location, "Too many recursive assertions" );
415                }
416        }
417} // namespace ResolvExpr
418
419// Local Variables: //
420// tab-width: 4 //
421// mode: c++ //
422// compile-command: "make install" //
423// End: //
Note: See TracBrowser for help on using the repository browser.