#include "compiler.h"
#include "builtins/builtins.h"
#include "builtins/helpers.h"
#include "sema/sema.h"
#include "execute/execute.h"
#include "diagnostics/diagnostics.h"

#include "llvm/Support/InitLLVM.h"
#include "llvm/Support/TargetSelect.h"

using namespace empathy;
using namespace empathy::util;
using namespace empathy::ir;
using namespace empathy::diagnostics;

Compiler::Compiler( int argc, char** argv ) :
    m_pEnv( make_shared< sema::Env >() )
{
    llvm::InitLLVM( argc, argv );

    string cmdArgs;
    for( size_t i = 1; i < static_cast< size_t >( argc ); ++i )
    {
        if( i > 1 )
            cmdArgs = cmdArgs + ' ';
        cmdArgs = cmdArgs + argv[i];
    }

    builtins::SetupBuiltins( *m_pEnv );

    builtins::RegisterBuiltinFunc< builtins::Eager< string > () >( *m_pEnv, "Args"_sid,
        [cmdArgs]()
        {
            return cmdArgs;
        } );

    builtins::RegisterBuiltinFunc< void ( string ) >( *m_pEnv, "Print"_sid,
        []( const string& str )
        {
            cout << str << endl;
        } );

    llvm::InitializeAllTargetInfos();
    llvm::InitializeAllTargets();
    llvm::InitializeAllTargetMCs();
    llvm::InitializeAllAsmParsers();
    llvm::InitializeAllAsmPrinters();
}

uint32_t Compiler::execute( istream& source, const string& filename )
{
    sema::Context c( m_pEnv, builtins::RootIdentity(), GetValueType< uint32_t >() );

    auto r = make_shared< parse::Resolver >( make_shared< lex::Lexer >( source, filename ), c );
    parse::Parser p( r );

    auto cfg = make_shared< llr::CFG >();
    p.setCFG( cfg );
    p.setCurrentBB( cfg->entryBB() );

    p.parseSequence();

    if( !r->eos() )
    {
        DiagnosticsManager::GetInstance().emitErrorMessage(
            r->getCurrentLocation(), "syntax error." );
        return 0;
    }

    if( !cfg->entryBB()->canBeExecuted() )
    {
        DiagnosticsManager::GetInstance().emitErrorMessage( 0,
            format( "{}: can not be executed.", filename ) );
        return 0;
    }

    execute::VM vm;
    auto result = vm.execute( cfg->entryBB() );
    if( !result )
        return 1;

    return *FromValue< uint32_t >( *result );
}
