#include "builtins/builtins.h"

using namespace empathy::builtins;

namespace empathy::builtins
{
    bool IsDecl( const Value& d )
    {
        auto typeVal = ValueFromIRExpr( d.type() );
        auto result = Decompose( typeVal->val(),
            Vec(
                Lit( "decl"_sid ),
                SubTerm()
            )
        );

        return !!result;
    }

    const Term& Decl::PatternTypeT::GetPattern()
    {
        static auto pattern = ValueToIRExpr(
            Value( TypeType(), TVEC( TSID( decl ), MkHole( "T"_sid ) ) ) );

        return pattern;
    }
}

namespace empathy::ir
{
    Term Bridge< Decl >::Type( const Term& declType )
    {
        return ValueToIRExpr( Value( TypeType(), TVEC( TSID( decl ), declType ) ) );
    }

    Value Bridge< Decl >::ToValue( const Decl& d )
    {
        return Value( Type( d.type() ), TERM( d.name() ) );
    }

    optional< Decl > Bridge< Decl >::FromValue( const Value& v )
    {
        auto typeVal = ValueFromIRExpr( v.type() );
        auto result = Decompose( typeVal->val(),
            Vec(
                Lit( "decl"_sid ),
                SubTerm()
            )
        );

        if( !result )
            return nullopt;

        auto&& [type] = *result;

        const auto& name = get< StringId >( v.val() );
        return Decl( move( type ), name );
    }
}
