Goose  Artifact [0fbdd5edb3]

Artifact 0fbdd5edb3fff6def10a294e8b545294393dc638e35acb00d2f994690fc6b961:

  • File bs/sema/substitute.cpp — part of check-in [dd70f4c696] at 2019-03-17 15:54:13 on branch trunk — Sema: terms can now be wrapped along with a callback to be invoked by Substitute(). (user: achavasse size: 1476)

#include "sema.h"

namespace empathy::sema
{
    optional< Term > Substitute( const Term& src, const UnificationContext& context )
    {
        if( !holds_alternative< pvec >( src.content() ) )
            return src;

        if( auto optHole = HoleFromIRExpr( src ) )
        {
            const auto& hole = *optHole;

            // We only substitute indexed holes. If we encounter a named hole,
            // output it as is.
            if( !holds_alternative< uint32_t >( hole ) )
                return src;

            const auto& optVal = context.getValue( get< uint32_t >( hole ) );
            if( !optVal )
                return src;

            return Substitute( *optVal, context );
        }

        if( auto optCB = UnwrapCallback( src ) )
        {
            auto val = Substitute( optCB->first, context );
            if( !val )
                return nullopt;

            return ( *optCB->second )( *val );
        }

        const auto& vec = *get< pvec >( src.content() );
        immer::vector< Term > outputTerms;
        auto vt = outputTerms.transient();
        bool faulty = false;

        for( auto&& t : vec.terms() )
        {
            auto newT = Substitute( t, context );
            if( !newT )
                return nullopt;

            faulty = faulty || newT->isFaulty();
            vt.push_back( move( *newT ) );
        }

        return Term( src.location(), make_shared< Vector >( vt.persistent(), faulty ) );
    }
}