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

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

optional< uint32_t > Parser::getInfixOverloadSetPrecedence()
{
    if( isInParenExpr() )
        return nullopt;

    auto next = m_resolver->lookAheadUnresolved( 1 );
    if( !next )
        return nullopt;

    auto decomp = Decompose( *next, Val< Delimiter >() );
    if( !decomp || *decomp != Delimiter::OpenParen )
        return nullopt;

    return precedence::Application;
}

bool Parser::parseInfixOverloadSet( const ptr< builtins::OverloadSet >& pOvlSet, uint32_t prec )
{
    auto rt = *pop();
    m_resolver->consume();

    auto params = parseParenBlock( Delimiter::OpenParen );
    if( !params )
        return false;

    optional< Value > func;

    if( rt.type() == TSID( type ) )
        func = parseFunctionDeclaration( pOvlSet->name(), rt, *params );
    else if( IsTExpr( rt ) )
        func = parseTemplateFunction( pOvlSet->name(), rt, *params );

    if( !func )
        return false;

    const auto& c = m_resolver->context();
    if( !pOvlSet->add( c, *func ) )
    {
        cout << "error: duplicate function overload\n";
        return false;
    }

    return true;
}
