package bilab;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;

import antlr.ANTLRException;
import antlr.CharBuffer;
import antlr.TokenBuffer;
import antlr.collections.AST;

import scigol.CombinedSharedInputState;
import scigol.LexerSharedInputStateWrapper;
import scigol.ParserSharedInputStateWrapper;
import scigol.ScigolLexer;
import scigol.ScigolParser;
import scigol.ScigolTreeParser;
import scigol.Scope;


// Execute source by interpretation 
public class InterpretExecutor implements ISourceExecutor
{
  public InterpretExecutor(Scope globalScope)
  {
    this.globalScope = globalScope;
  }
  
  public Object executeSource(InputStream src, String name) throws ANTLRException
  {
    CombinedSharedInputState istate = new CombinedSharedInputState();
    LexerSharedInputStateWrapper listate = new LexerSharedInputStateWrapper(istate,src);
    ParserSharedInputStateWrapper pistate = new ParserSharedInputStateWrapper(istate);
    
    ScigolLexer lexer = new ScigolLexer(listate);
    lexer.setTokenObjectClass("scigol.CommonTokenWithLocation");
    lexer.setFilename(name);
    
    ScigolParser parser = new ScigolParser(pistate);
    parser.setTokenBuffer(new TokenBuffer(lexer));
    parser.setASTNodeClass("scigol.CommonASTWithLocation");
    parser.setFilename(name);
    
    // parse 
    parser.program();
    
    AST t = parser.getAST();
//    Debug.WL("AST:\n"+t.toStringTree());

    ScigolTreeParser treeParser = new ScigolTreeParser(globalScope, false);
    
    treeParser.setASTNodeClass("scigol.CommonASTWithLocation");
//    treeParser.setASTFactory
    
    return treeParser.program(t);
  }
  
  
  
  public Object executeSource(String src) throws ANTLRException
  {
    StringReader sin = new StringReader(src);
    CombinedSharedInputState istate = new CombinedSharedInputState();
    LexerSharedInputStateWrapper listate = new LexerSharedInputStateWrapper(istate, new CharBuffer(sin));
    ParserSharedInputStateWrapper pistate = new ParserSharedInputStateWrapper(istate);
    ScigolLexer lexer = new ScigolLexer(listate);
    lexer.setFilename("<interactive>");
    
    ScigolParser parser = new ScigolParser(pistate);
    parser.setTokenBuffer(new TokenBuffer(lexer));
    parser.setFilename("<interactive>");

    // parse 
    parser.program();
    
    AST t = parser.getAST();
//Console.Out.WriteLine("AST:\n"+t.ToStringTree());
    
    ScigolTreeParser treeParser = new ScigolTreeParser(globalScope, true);
    return treeParser.program(t);
  }


  
  private Scope globalScope;
}
