#include "builtins/builtins.h"

using namespace empathy;
using namespace empathy::builtins;

namespace empathy::builtins
{
    void SetupRuntimeBasicTypes( Env& e )
    {
        e.storeValue( AppendToVectorTerm( RootIdentity(), TSID( rt_half ) ), ANYTERM( _ ), GetValueType< RTHalf >() );
        e.storeValue( AppendToVectorTerm( RootIdentity(), TSID( rt_float ) ), ANYTERM( _ ), GetValueType< RTFloat >() );
        e.storeValue( AppendToVectorTerm( RootIdentity(), TSID( rt_double ) ), ANYTERM( _ ), GetValueType< RTDouble >() );

        RegisterBuiltinFunc< Value ( uint64_t ) >( e, "RTInteger"_sid,
            []( uint64_t numBits )
            {
                return ToValue( RTInteger( numBits ) );
            } );
    }
}

namespace empathy::ir
{
    //// Half
    const Term& Bridge< RTHalf >::Type()
    {
        static auto type = ValueToIRExpr( Value( TypeType(), TSID( rt_half ) ) );
        return type;
    }

    const Value& Bridge< RTHalf >::TypeVal()
    {
        static auto type = Value( TypeType(), TSID( rt_half ) );
        return type;
    }

    //// Float
    const Term& Bridge< RTFloat >::Type()
    {
        static auto type = ValueToIRExpr( Value( TypeType(), TSID( rt_float ) ) );
        return type;
    }

    const Value& Bridge< RTFloat >::TypeVal()
    {
        static auto type = Value( TypeType(), TSID( rt_float ) );
        return type;
    }

    //// Double
    const Term& Bridge< RTDouble >::Type()
    {
        static auto type = ValueToIRExpr( Value( TypeType(), TSID( rt_double ) ) );
        return type;
    }

    const Value& Bridge< RTDouble >::TypeVal()
    {
        static auto type = Value( TypeType(), TSID( rt_double ) );
        return type;
    }

    //// Integer
    const Term& Bridge< RTInteger >::Type()
    {
        static auto type = ValueToIRExpr( Value( TypeType(), TSID( rt_integer ) ) );
        return type;
    }

    Value Bridge< RTInteger >::ToValue( const RTInteger& i )
    {
        return Value( Type(), TERM( i.m_numBits ) );
    }

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

        if( !result )
            return nullopt;

        auto&& [numBits] = *result;
        return RTInteger( numBits );
    }
}
