#include "builtins/builtins.h"
#include "lex/lex.h"
#include "parse/parse.h"

using namespace empathy::builtins;
using namespace empathy::parse;

namespace empathy::ir
{
    Term Bridge< TFunc >::Type( const builtins::TFunc& tf )
    {
        return ValueToIRExpr( ::ToValue( tf.type() ) );
    }

    Value Bridge< TFunc >::ToValue( const TFunc& tf )
    {
        return Value( Type( tf ), VEC( Quote( tf.signature() ), tf.identity(),
            TERM( tf.toks() ) ) );
    }

    optional< TFunc > Bridge< TFunc >::FromValue( const Value& v )
    {
        auto typeVal = ValueFromIRExpr( v.type() );
        auto type = ::FromValue< TFuncType >( *typeVal );
        if( !type )
            return nullopt;

        auto result = Decompose( v.val(),
            Vec(
                SubTerm(),              // signature
                SubTerm(),              // identity
                Val< ptr< void > >()    // toks
            )
        );

        if( !result )
            return nullopt;

        auto&& [signature, identity, toks] = *result;

        return TFunc( move( *type ), *Unquote( signature ),
            identity, toks );
    }
}
