Goose  Artifact [d3708e9ce2]

Artifact d3708e9ce28dbb64a0c2a45e2af18f3f31b7361a0815d9453f86b42657fab016:

  • File bs/ir/match.h — part of check-in [fc368bcd5c] at 2018-11-12 20:13:48 on branch trunk — Handle AnyTerm and VecOfLength in term/trie pattern matching. (user: achavasse size: 2018)

#ifndef EMPATHY_IR_MATCH_H
#define EMPATHY_IR_MATCH_H

namespace empathy::ir
{
    class MatchSolution
    {
        public:
            size_t complexity() const { return m_complexity; }
            size_t numVars() const;

            template< typename T >
            const T* getVar( const StringId& name ) const
            {
                if( !m_pVars )
                    return nullptr;

                auto it = m_pVars->find( name );
                if( it == m_pVars->end() )
                    return nullptr;

                return any_cast< T >( &it->second );
            }

            // Tries to set the variable. If it already exists but have a different
            // value, returns false.
            template< typename T >
            bool setVar( const StringId& name, T&& val )
            {
                if( m_pVars )
                {
                    auto it = m_pVars->find( name );
                    if( it != m_pVars->end() )
                    {
                        using TT = remove_constref_t< T >;
                        if( const auto* pExistingVal = any_cast< TT >( &it->second ) )
                            return *pExistingVal == val;

                        return false;
                    }
                }

                setupVars();
                m_pVars->emplace( name, forward< T >( val ) );
                return true;
            }

            void incComplexity() { ++m_complexity; }

        private:
            void setupVars();

            ptr< unordered_map< StringId, any > > m_pVars;
            size_t m_complexity = 0;    // The number of container terms in the matched pattern
    };

    extern optional< MatchSolution > Match( const Term& expression, const Term& pattern );

    template< typename U >
    static Generator< pair< MatchSolution, const U& > > Match( const Term& expression, const Trie< U >& patterns );
    extern Generator< MatchSolution > Match( const Term& expression, const Trie<>& patterns );
}

#endif