#include "sema.h"

namespace goose::sema
{
    Term Substitute( const Term& src, const TypeCheckingContext& context )
    {
        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( !hole.name.isNumerical() )
                return src;

            const auto& optVal = context.getValue( hole.name.id() );
            if( !optVal )
                return HOLE( "_"_sid );

            return Substitute( *optVal, context );
        }

        if( !holds_alternative< pvec >( src ) )
            return src;

        const auto& vec = *get< pvec >( src );

        auto outputTerms = make_shared< Vector >();
        outputTerms->reserve( vec.terms().size() );

        for( auto&& t : vec.terms() )
            outputTerms->append( Substitute( t, context ) );

        return outputTerms;
    }
}
