#include "builtins/builtins.h"

using namespace empathy;
using namespace empathy::builtins;

namespace empathy::builtins
{
    void SetupRuntimeArrayType( Env& e )
    {
        RegisterBuiltinFunc< Value ( Value, uint64_t ) >( e, "RTArray"_sid,
            []( const Value& containedType, uint64_t count )
            {
                assert( containedType.isType() );
                return ToValue( RTArray( ValueToIRExpr( containedType ), count ) );
            } );
    }
}

namespace empathy::ir
{
    Value Bridge< RTArray >::ToValue( const RTArray& a )
    {
        return Value( Type(), TVEC( TSID( rt_type ), TSID( rt_array ), TERM( a.m_count ), a.m_containedType ) );
    }

    optional< RTArray > Bridge< RTArray >::FromValue( const Value& v )
    {
        auto result = Decompose( v.val(),
            Vec(
                Lit( "rt_type"_sid ),
                Lit( "rt_array"_sid ),
                Val< uint64_t >(),
                SubTerm()
            )
        );

        if( !result )
            return nullopt;

        auto&& [count, containedType] = *result;
        return RTArray( containedType, count );
    }
}
