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

using namespace empathy;
using namespace empathy::ir;
using namespace empathy::parse;

namespace empathy::builtins
{
    void SetupIfStmt( Env& e )
    {
        auto handleIf = []( Parser& p, const Term& t, uint32_t prec )
        {
            auto pPrecBB = p.currentBB();

            auto np = p.makeNestedParser();
            if( !np.parseExpression( precedence::IfStmt ) )
            {
                cout << "expected an expression following the if statement.\n";
                return false;
            }

            auto condVal = np.popValue();
            if( !condVal )
            {
                cout << "expected an expression following the if statement.\n";
                return false;
            }

            const auto& context = p.resolver()->context();
            auto converted = ConvertValueToType( context, *condVal, GetValueType< bool >() );
            if( holds_alternative< ValUnifyError >( converted ) )
            {
                switch( get< ValUnifyError >( converted ) )
                {
                    case ValUnifyError::NoSolution:
                        cout << "if condition is not of bool type.\n";
                        break;

                    case ValUnifyError::Ambiguous:
                        cout << "ambiguous if condition bool conversion.\n";
                        break;
                }

                return false;
            }

            auto pThenBB = ParseSubStatement( p, precedence::IfStmt );
            if( !pThenBB )
            {
                cout << "expected a statement after the if condition.\n";
                return false;
            }

            // Retrieve the successor block of the then branch, if any
            auto pThenSuccBB = p.currentBB();

            ptr< llr::BasicBlock > pElseBB, pElseSuccBB;

            auto next = p.resolver()->lookAheadUnresolved();
            if( next )
            {
                const auto* nextSid = get_if< StringId >( &next->content() );
                if( nextSid && *nextSid == "else"_sid )
                {
                    p.resolver()->consumeUnresolved();
                    pElseBB = ParseSubStatement( p, precedence::IfStmt );
                    if( !pElseBB )
                    {
                        cout << "expected a statement after 'else'.\n";
                        return false;
                    }

                    // Retrieve the successor block of the else branch, if any
                    pElseSuccBB = p.currentBB();
                }
            }

            ptr< llr::BasicBlock > pSuccBB;

            // If both the then and the else blocks successors exist and are terminated,
            // we don't need a successor block.
            if( !pElseBB || ( pThenSuccBB && !pThenSuccBB->terminator() )
                || ( pElseSuccBB && !pElseSuccBB->terminator() ) )
                pSuccBB = p.cfg()->createBB();

            pPrecBB->setTerminator( llr::CondBranch(
                get< Value >( converted ),
                pThenBB,
                pElseBB ? pElseBB : pSuccBB ) );

            if( pThenSuccBB && !pThenSuccBB->terminator() )
                pThenSuccBB->setTerminator( llr::Branch( pSuccBB ) );

            if( pElseSuccBB && !pElseSuccBB->terminator() )
                pElseSuccBB->setTerminator( llr::Branch( pSuccBB ) );

            // Intentionally set the current BB to null if no
            // successor block was created: it means all our code paths
            // are already terminated and there is no point in emitting any more
            // instructions.
            p.setCurrentBB( pSuccBB );
            return true;
        };

        Rule r( handleIf );
        auto ruleVal = ToValue( move( r ) );
        auto ruleTerm = ValueToIRExpr( ruleVal );
        e.storeValue( AppendToVectorTerm( RootIdentity(), TSID( if ) ), ANYTERM( _ ), ruleTerm );
    }
}
