#include "builtins/builtins.h"

using namespace goose::builtins;

namespace goose::builtins
{
    bool IsTExpr( const optional< Value >& te )
    {
        return te && IsTExpr( *te );
    }

    bool IsTExpr( const Value& te )
    {
        if( te.isConstant() )
        {
            const auto* ppVec = get_if< pvec >( &te.val() );
            if( ppVec && !( *ppVec )->empty()
                &&( **ppVec )[0] == TSID( texpr ) )
            {
                return true;
            }
        }

        auto typeVal = EIRToValue( te.type() );
        if( !typeVal )
            return false;

        const auto* ppVec = get_if< pvec >( &typeVal->val() );
        if( !ppVec )
            return false;

        if( ( *ppVec )->empty() )
            return false;

        return ( **ppVec )[0] == TSID( texpr );
    }

    bool IsTVar( const Value& tv )
    {
        return tv.type() == GetValueType< TVar >();
    }
}

namespace goose::eir
{
    const Term& Bridge< TVar >::Type()
    {
        static auto type = ValueToEIR( Value( TypeType(), VEC( TSID( texpr ), TSID( tvar ) ) ) );
        return type;
    }

    Value Bridge< TVar >::ToValue( TVar&& td )
    {
        return Value( Type(), TERM( td.name() ) );
    }

    optional< TVar > Bridge< TVar >::FromValue( const Value& v )
    {
        if( !IsTVar( v ) )
            return nullopt;

        auto result = Decompose( v.val(),
            Val< StringId >()
        );

        if( !result )
            return nullopt;

        return TVar( *result );
    }
}
