#include "compiler.h"
#include "builtins/builtins.h"
#include "parse/parse.h"
#include "execute/execute.h"

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

Compiler::Compiler( int argc, char** argv ) :
    m_pEnv( make_shared< sema::Env >() )
{
    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< string () >( *m_pEnv, "Args"_sid,
        [cmdArgs]()
        {
            return cmdArgs;
        } );

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

optional< Value > Compiler::execute( istream& source, const ptr< string >& filename )
{
    sema::Context c( m_pEnv, TVEC( TSID( e0 ) ) );

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

    if( !r->eos() )
    {
        cout << "syntax error.\n";
        return nullopt;
    }

   auto llr = p.result();
    if( !llr )
        return nullopt;

    execute::VM vm;
    return execute::Evaluate( *llr, vm );
}
