#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 SetupBreakStmt( Env& e )
    {
        auto handleBreak = []( Parser& p, uint32_t locationId, uint32_t prec )
        {
            auto& dm = DiagnosticsManager::GetInstance();

            if( p.isInParenExpr() || !p.cfg() || !p.breakableScopeLevels() )
            {
                dm.emitSyntaxErrorMessage( locationId, "the break statement is not allowed here.", 0 );
                return false;
            }

            if( !p.cfg()->currentBB() || p.cfg()->currentBB()->terminator() )
            {
                DiagnosticsManager::GetInstance().emitSyntaxErrorMessage(
                    locationId, "unreachable code.", 0 );
                p.cfg()->poison();
                return true;
            }

            // Emit cleanups for all live variables in the scopes that we are breaking through.
            p.destroyAllLiveValuesFromBreakScope( p.breakableScopeLevels() );

            p.cfg()->currentBB()->setTerminator( llr::Break( p.breakableScopeLevels() ) );
            return true;
        };

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