Changes in / [bead1cf:c018b85]


Ignore:
Location:
src
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • src/ResolvExpr/ResolveAssertions.cc

    rbead1cf rc018b85  
    2020#include <list>                     // for list
    2121#include <memory>                   // for unique_ptr
     22#include <string>
    2223#include <unordered_map>            // for unordered_map, unordered_multimap
    2324#include <utility>                  // for move
     
    5556        using CandidateList = std::vector<AssnCandidate>;
    5657
     58        /// Unique identifier for a yet-to-be-resolved assertion
     59        struct AssnId {
     60                DeclarationWithType* decl;  ///< Declaration of assertion
     61                AssertionSetValue info;     ///< Information about assertion
     62
     63                AssnId(DeclarationWithType* decl, const AssertionSetValue& info) : decl(decl), info(info) {}
     64        };
     65
     66        /// Cached assertion items
     67        struct AssnCacheItem {
     68                CandidateList matches;         ///< Possible matches for this assertion
     69                std::vector<AssnId> deferIds;  ///< Deferred assertions which resolve to this item
     70
     71                AssnCacheItem( CandidateList&& m ) : matches(std::move(m)), deferIds() {}
     72        };
     73
     74        /// Cache of resolved assertions
     75        using AssnCache = std::unordered_map<std::string, AssnCacheItem>;
     76
    5777        /// Reference to single deferred item
    5878        struct DeferRef {
    59                 const DeclarationWithType* decl;
    60                 const AssertionSetValue& info;
     79                const AssnCacheItem& item;
    6180                const AssnCandidate& match;
    6281        };
     
    6584        /// Acts like indexed list of DeferRef
    6685        struct DeferItem {
    67                 DeclarationWithType* decl;
    68                 AssertionSetValue info;
    69                 CandidateList matches;
    70 
    71                 DeferItem( DeclarationWithType* decl, const AssertionSetValue& info,
    72                         CandidateList&& matches )
    73                 : decl(decl), info(info), matches(std::move(matches)) {}
    74 
    75                 bool empty() const { return matches.empty(); }
    76 
    77                 CandidateList::size_type size() const { return matches.size(); }
    78 
    79                 DeferRef operator[] ( unsigned i ) const { return { decl, info, matches[i] }; }
     86                const AssnCache* cache;     ///< Cache storing assertion item
     87                std::string key;            ///< Key into cache
     88               
     89                DeferItem( const AssnCache& cache, const std::string& key ) : cache(&cache), key(key) {}
     90
     91                bool empty() const { return cache->at(key).matches.empty(); }
     92
     93                CandidateList::size_type size() const { return cache->at(key).matches.size(); }
     94
     95                DeferRef operator[] ( unsigned i ) const {
     96                        const AssnCacheItem& item = cache->at(key);
     97                        return { item, item.matches[i] };
     98                }
     99
     100                // sortable by key
     101                // TODO look into optimizing combination process with other sort orders (e.g. by number
     102                // of matches in candidate)
     103                bool operator< ( const DeferItem& o ) const { return key < o.key; }
     104                bool operator== ( const DeferItem& o ) const { return key == o.key; }
    80105        };
    81106
     
    152177                                for ( const auto& assn : x.assns ) {
    153178                                        k += computeConversionCost(
    154                                                 assn.match.adjType, assn.decl->get_type(), indexer, x.env );
     179                                                assn.match.adjType, assn.item.deferIds[0].decl->get_type(), indexer,
     180                                                x.env );
    155181                                }
    156182                                it = cache.emplace_hint( it, &x, k );
     
    208234                                candidate->get_uniqueId(), match.adjType->clone(), decl->get_type()->clone(),
    209235                                varExpr };
    210 
    211                 // // follow the current assertion's ID chain to find the correct set of inferred parameters
    212                 // // to add the candidate o (i.e. the set of inferred parameters belonging to the entity
    213                 // // which requested the assertion parameter)
    214                 // InferredParams* inferParams = &alt.expr->inferParams;
    215                 // for ( UniqueId id : info.idChain ) {
    216                 //      inferParams = (*inferParams)[ id ].inferParams.get();
    217                 // }
    218 
    219                 // (*inferParams)[ decl->get_uniqueId() ] = ParamEntry{
    220                 //              candidate->get_uniqueId(), match.adjType, decl->get_type()->clone(), varExpr };
    221236        }
    222237
    223238        /// Adds a captured assertion to the symbol table
    224239        void addToIndexer( AssertionSet &assertSet, SymTab::Indexer &indexer ) {
    225                 for ( AssertionSet::iterator i = assertSet.begin(); i != assertSet.end(); ++i ) {
    226                         if ( i->second.isUsed ) {
    227                                 indexer.addId( i->first );
     240                for ( auto&  i : assertSet ) {
     241                        if ( i.second.isUsed ) {
     242                                indexer.addId( i.first );
    228243                        }
    229244                }
     
    234249
    235250        /// Resolve a single assertion, in context
    236         bool resolveAssertion( AssertionItem& assn, ResnState& resn ) {
     251        bool resolveAssertion( AssertionItem& assn, ResnState& resn, AssnCache& cache ) {
    237252                // skip unused assertions
    238253                if ( ! assn.info.isUsed ) return true;
    239254
    240                 // lookup candidates for this assertion
    241                 std::list< SymTab::Indexer::IdData > candidates;
    242                 resn.indexer.lookupId( assn.decl->name, candidates );
    243 
    244                 // find the candidates that unify with the desired type
    245                 CandidateList matches;
    246                 for ( const auto& cdata : candidates ) {
    247                         DeclarationWithType* candidate = cdata.id;
    248 
    249                         // build independent unification context for candidate
    250                         AssertionSet have, newNeed;
    251                         TypeEnvironment newEnv{ resn.alt.env };
    252                         OpenVarSet newOpenVars{ resn.alt.openVars };
    253                         Type* adjType = candidate->get_type()->clone();
    254                         adjustExprType( adjType, newEnv, resn.indexer );
    255                         renameTyVars( adjType );
    256 
    257                         // keep unifying candidates
    258                         if ( unify( assn.decl->get_type(), adjType, newEnv, newNeed, have, newOpenVars,
    259                                         resn.indexer ) ) {
    260                                 // set up binding slot for recursive assertions
    261                                 UniqueId crntResnSlot = 0;
    262                                 if ( ! newNeed.empty() ) {
    263                                         crntResnSlot = ++globalResnSlot;
    264                                         for ( auto& a : newNeed ) {
    265                                                 a.second.resnSlot = crntResnSlot;
     255                // check cache for this assertion
     256                std::string assnKey = SymTab::Mangler::mangleAssnKey( assn.decl, resn.alt.env );
     257                auto it = cache.find( assnKey );
     258
     259                // attempt to resolve assertion if this is the first time seen
     260                if ( it == cache.end() ) {
     261                        // lookup candidates for this assertion
     262                        std::list< SymTab::Indexer::IdData > candidates;
     263                        resn.indexer.lookupId( assn.decl->name, candidates );
     264
     265                        // find the candidates that unify with the desired type
     266                        CandidateList matches;
     267                        for ( const auto& cdata : candidates ) {
     268                                DeclarationWithType* candidate = cdata.id;
     269
     270                                // build independent unification context for candidate
     271                                AssertionSet have, newNeed;
     272                                TypeEnvironment newEnv{ resn.alt.env };
     273                                OpenVarSet newOpenVars{ resn.alt.openVars };
     274                                Type* adjType = candidate->get_type()->clone();
     275                                adjustExprType( adjType, newEnv, resn.indexer );
     276                                renameTyVars( adjType );
     277
     278                                // keep unifying candidates
     279                                if ( unify( assn.decl->get_type(), adjType, newEnv, newNeed, have, newOpenVars,
     280                                                resn.indexer ) ) {
     281                                        // set up binding slot for recursive assertions
     282                                        UniqueId crntResnSlot = 0;
     283                                        if ( ! newNeed.empty() ) {
     284                                                crntResnSlot = ++globalResnSlot;
     285                                                for ( auto& a : newNeed ) {
     286                                                        a.second.resnSlot = crntResnSlot;
     287                                                }
    266288                                        }
    267                                 }
    268                                 // // set up idChain on new assertions
    269                                 // for ( auto& a : newNeed ) {
    270                                 //      a.second.idChain = assn.info.idChain;
    271                                 //      a.second.idChain.push_back( assn.decl->get_uniqueId() );
    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;
     289
     290                                        matches.emplace_back( cdata, adjType, std::move(newEnv), std::move(have),
     291                                                std::move(newNeed), std::move(newOpenVars), crntResnSlot );
     292                                } else {
     293                                        delete adjType;
     294                                }
    278295                        }
    279                 }
     296
     297                        it = cache.emplace_hint( it, assnKey, AssnCacheItem{ std::move(matches) } );
     298                }
     299
     300                CandidateList& matches = it->second.matches;
    280301
    281302                // break if no suitable assertion
     
    284305                // defer if too many suitable assertions
    285306                if ( matches.size() > 1 ) {
    286                         resn.deferred.emplace_back( assn.decl, assn.info, std::move(matches) );
     307                        it->second.deferIds.emplace_back( assn.decl, assn.info );
     308                        resn.deferred.emplace_back( cache, assnKey );
    287309                        return true;
    288310                }
     
    292314                addToIndexer( match.have, resn.indexer );
    293315                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);
     316                resn.alt.env = match.env;
     317                resn.alt.openVars = match.openVars;
    296318
    297319                bindAssertion( assn.decl, assn.info, resn.alt, match, resn.inferred );
     
    354376                ResnList resns{ ResnState{ alt, root_indexer } };
    355377                ResnList new_resns{};
     378                AssnCache assnCache;
    356379
    357380                // resolve assertions in breadth-first-order up to a limited number of levels deep
     
    362385                                for ( auto& assn : resn.need ) {
    363386                                        // fail early if any assertion is not resolvable
    364                                         if ( ! resolveAssertion( assn, resn ) ) goto nextResn;
     387                                        if ( ! resolveAssertion( assn, resn, assnCache ) ) goto nextResn;
    365388                                }
    366389
     
    373396                                        }
    374397                                } else {
     398                                        // only resolve each deferred assertion once
     399                                        std::sort( resn.deferred.begin(), resn.deferred.end() );
     400                                        auto last = std::unique( resn.deferred.begin(), resn.deferred.end() );
     401                                        resn.deferred.erase( last, resn.deferred.end() );
    375402                                        // resolve deferred assertions by mutual compatibility
    376403                                        std::vector<CandidateEnvMerger::OutType> compatible = filterCombos(
     
    380407                                        CandidateCost coster{ resn.indexer };
    381408                                        std::sort( compatible.begin(), compatible.end(), coster );
    382                                         // // sort by cost if pruning
    383                                         // if ( pruneAssertions ) {
    384                                         //      auto lmin = sort_mins( compatible.begin(), compatible.end(),
    385                                         //              CandidateCost{resn.indexer} );
    386                                         //      compatible.erase( lmin, compatible.end() );
    387                                         // }
    388409
    389410                                        // keep map of detected options
     
    408429                                                        new_resn.newNeed.insert( match.need.begin(), match.need.end() );
    409430
    410                                                         bindAssertion( r.decl, r.info, new_resn.alt, match, new_resn.inferred );
     431                                                        // for each deferred assertion with the same form
     432                                                        for ( AssnId id : r.item.deferIds ) {
     433                                                                bindAssertion(
     434                                                                        id.decl, id.info, new_resn.alt, match, new_resn.inferred );
     435                                                        }
    411436                                                }
    412437
  • src/SymTab/Mangler.cc

    rbead1cf rc018b85  
    1515#include "Mangler.h"
    1616
    17 #include <algorithm>                // for copy, transform
    18 #include <cassert>                  // for assert, assertf
    19 #include <functional>               // for const_mem_fun_t, mem_fun
    20 #include <iterator>                 // for ostream_iterator, back_insert_ite...
    21 #include <list>                     // for _List_iterator, list, _List_const...
    22 #include <string>                   // for string, char_traits, operator<<
    23 
    24 #include "CodeGen/OperatorTable.h"  // for OperatorInfo, operatorLookup
     17#include <algorithm>                     // for copy, transform
     18#include <cassert>                       // for assert, assertf
     19#include <functional>                    // for const_mem_fun_t, mem_fun
     20#include <iterator>                      // for ostream_iterator, back_insert_ite...
     21#include <list>                          // for _List_iterator, list, _List_const...
     22#include <string>                        // for string, char_traits, operator<<
     23
     24#include "CodeGen/OperatorTable.h"       // for OperatorInfo, operatorLookup
    2525#include "Common/PassVisitor.h"
    26 #include "Common/SemanticError.h"   // for SemanticError
    27 #include "Common/utility.h"         // for toString
    28 #include "Parser/LinkageSpec.h"     // for Spec, isOverridable, AutoGen, Int...
    29 #include "SynTree/Declaration.h"    // for TypeDecl, DeclarationWithType
    30 #include "SynTree/Expression.h"     // for TypeExpr, Expression, operator<<
    31 #include "SynTree/Type.h"           // for Type, ReferenceToType, Type::Fora...
     26#include "Common/SemanticError.h"        // for SemanticError
     27#include "Common/utility.h"              // for toString
     28#include "Parser/LinkageSpec.h"          // for Spec, isOverridable, AutoGen, Int...
     29#include "ResolvExpr/TypeEnvironment.h"  // for TypeEnvironment
     30#include "SynTree/Declaration.h"         // for TypeDecl, DeclarationWithType
     31#include "SynTree/Expression.h"          // for TypeExpr, Expression, operator<<
     32#include "SynTree/Type.h"                // for Type, ReferenceToType, Type::Fora...
    3233
    3334namespace SymTab {
     
    3738                        struct Mangler : public WithShortCircuiting, public WithVisitorRef<Mangler>, public WithGuards {
    3839                                Mangler( bool mangleOverridable, bool typeMode, bool mangleGenericParams );
     40                                Mangler( const ResolvExpr::TypeEnvironment& env );
    3941                                Mangler( const Mangler & ) = delete;
    4042
     
    6567                          private:
    6668                                std::ostringstream mangleName;  ///< Mangled name being constructed
    67                                 typedef std::map< std::string, std::pair< int, int > > VarMapType;
     69                                typedef std::map< std::string, std::pair< std::string, int > > VarMapType;
    6870                                VarMapType varNums;             ///< Map of type variables to indices
    6971                                int nextVarNum;                 ///< Next type variable index
     72                                const ResolvExpr::TypeEnvironment* env;  ///< optional environment for substitutions
    7073                                bool isTopLevel;                ///< Is the Mangler at the top level
    7174                                bool mangleOverridable;         ///< Specially mangle overridable built-in methods
     
    7578                                bool inQualifiedType = false;   ///< Add start/end delimiters around qualified type
    7679
     80                          public:
     81                                Mangler( bool mangleOverridable, bool typeMode, bool mangleGenericParams,
     82                                        int nextVarNum, const ResolvExpr::TypeEnvironment* env,
     83                                        const VarMapType& varNums );
     84
     85                          private:
    7786                                void mangleDecl( DeclarationWithType *declaration );
    7887                                void mangleRef( ReferenceToType *refType, std::string prefix );
     
    100109                }
    101110
     111                std::string mangleAssnKey( DeclarationWithType* decl,
     112                                const ResolvExpr::TypeEnvironment& env ) {
     113                        PassVisitor<Mangler> mangler( env );
     114                        maybeAccept( decl, mangler );
     115                        return mangler.pass.get_mangleName();
     116                }
     117
    102118                namespace {
    103119                        Mangler::Mangler( bool mangleOverridable, bool typeMode, bool mangleGenericParams )
    104                                 : nextVarNum( 0 ), isTopLevel( true ), mangleOverridable( mangleOverridable ), typeMode( typeMode ), mangleGenericParams( mangleGenericParams ) {}
     120                                : nextVarNum( 0 ), env(nullptr), isTopLevel( true ),
     121                                mangleOverridable( mangleOverridable ), typeMode( typeMode ),
     122                                mangleGenericParams( mangleGenericParams ) {}
     123                       
     124                        Mangler::Mangler( const ResolvExpr::TypeEnvironment& env )
     125                                : nextVarNum( 0 ), env( &env ), isTopLevel( true ), mangleOverridable( false ),
     126                                typeMode( false ), mangleGenericParams( true ) {}
     127                       
     128                        Mangler::Mangler( bool mangleOverridable, bool typeMode, bool mangleGenericParams,
     129                                int nextVarNum, const ResolvExpr::TypeEnvironment* env,
     130                                const VarMapType& varNums )
     131                                : varNums( varNums ), nextVarNum( nextVarNum ), env( env ), isTopLevel( false ),
     132                                mangleOverridable( mangleOverridable ), typeMode( typeMode ),
     133                                mangleGenericParams( mangleGenericParams ) {}
    105134
    106135                        void Mangler::mangleDecl( DeclarationWithType * declaration ) {
     
    329358                                                        assert( false );
    330359                                                } // switch
    331                                                 varNums[ (*i)->name ] = std::pair< int, int >( nextVarNum++, (int)(*i)->get_kind() );
     360                                                std::string varName;
     361                                                // replace type with substitution name if environment is available and bound
     362                                                if ( env ) {
     363                                                        const ResolvExpr::EqvClass* varClass = env->lookup( (*i)->name );
     364                                                        if ( varClass && varClass->type ) {
     365                                                                PassVisitor<Mangler> sub_mangler(
     366                                                                        mangleOverridable, typeMode, mangleGenericParams, nextVarNum,
     367                                                                        env, varNums );
     368                                                                varClass->type->accept( sub_mangler );
     369                                                                varName = std::string{"%"} + sub_mangler.pass.get_mangleName();
     370                                                        }
     371                                                }
     372                                                // otherwise just give type numeric name
     373                                                if ( varName.empty() ) {
     374                                                        varName = std::to_string( nextVarNum++ );
     375                                                }
     376                                                varNums[ (*i)->name ] = std::make_pair( varName, (int)(*i)->get_kind() );
    332377                                                for ( std::list< DeclarationWithType* >::iterator assert = (*i)->assertions.begin(); assert != (*i)->assertions.end(); ++assert ) {
    333                                                         PassVisitor<Mangler> sub_mangler( mangleOverridable, typeMode, mangleGenericParams );
    334                                                         sub_mangler.pass.nextVarNum = nextVarNum;
    335                                                         sub_mangler.pass.isTopLevel = false;
    336                                                         sub_mangler.pass.varNums = varNums;
     378                                                        PassVisitor<Mangler> sub_mangler(
     379                                                                mangleOverridable, typeMode, mangleGenericParams, nextVarNum, env,
     380                                                                varNums );
    337381                                                        (*assert)->accept( sub_mangler );
    338                                                         assertionNames.push_back( sub_mangler.pass.mangleName.str() );
     382                                                        assertionNames.push_back( sub_mangler.pass.get_mangleName() );
    339383                                                        acount++;
    340384                                                } // for
  • src/SymTab/Mangler.h

    rbead1cf rc018b85  
    3131// * Currently name compression is not implemented.
    3232
     33namespace ResolvExpr {
     34        class TypeEnvironment;
     35}
     36
    3337namespace SymTab {
    3438        namespace Mangler {
     
    4044                /// Mangle ignoring generic type parameters
    4145                std::string mangleConcrete( Type* ty );
     46                /// Mangle for assertion key
     47                std::string mangleAssnKey( DeclarationWithType* decl,
     48                        const ResolvExpr::TypeEnvironment& env );
    4249
    4350                namespace Encoding {
Note: See TracChangeset for help on using the changeset viewer.