Example usage for org.antlr.v4.runtime CommonTokenStream seek

List of usage examples for org.antlr.v4.runtime CommonTokenStream seek

Introduction

In this page you can find the example usage for org.antlr.v4.runtime CommonTokenStream seek.

Prototype

@Override
    public void seek(int index) 

Source Link

Usage

From source file:edu.clemson.cs.rsrg.init.Controller.java

License:Open Source License

/**
 * <p>This method uses the {@link ResolveFile} provided
 * to construct a parser and create an ANTLR4 module AST.</p>
 *
 * @param file The RESOLVE file that we are going to compile.
 *
 * @return The inner representation for a module. See {@link ModuleDec}.
 *
 * @throws MiscErrorException Some how we couldn't instantiate an {@link CharStream}.
 * @throws SourceErrorException There are errors in the source file.
 *//*w w w.  ja va  2 s . com*/
private ModuleDec createModuleAST(ResolveFile file) {
    CharStream input = file.getInputStream();
    if (input == null) {
        throw new MiscErrorException("CharStream null", new IllegalArgumentException());
    }

    // Create a RESOLVE language lexer
    ResolveLexer lexer = new ResolveLexer(input);
    ResolveTokenFactory factory = new ResolveTokenFactory(file);
    lexer.removeErrorListeners();
    lexer.addErrorListener(myAntlrLexerErrorListener);
    lexer.setTokenFactory(factory);

    // Create a RESOLVE language parser
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    ResolveParser parser = new ResolveParser(tokens);
    parser.removeErrorListeners();
    parser.addErrorListener(myAntlrParserErrorListener);
    parser.setTokenFactory(factory);

    // Two-Stage Parsing
    // Reason: We might not need the full power of LL.
    // The solution proposed by the ANTLR folks (found here:
    // https://github.com/antlr/antlr4/blob/master/doc/faq/general.md)
    // is to use SLL prediction mode first and switch to LL if it fails.
    ParserRuleContext rootModuleCtx;
    parser.getInterpreter().setPredictionMode(PredictionMode.SLL);
    try {
        rootModuleCtx = parser.module();
    } catch (Exception ex) {
        tokens.seek(0);
        parser.reset();
        parser.getInterpreter().setPredictionMode(PredictionMode.LL);
        rootModuleCtx = parser.module();
    }

    // Check for any parsing errors
    int numParserErrors = parser.getNumberOfSyntaxErrors();
    if (numParserErrors != 0) {
        throw new MiscErrorException("Found " + numParserErrors + " errors while parsing " + file.toString(),
                new IllegalStateException());
    }

    // Build the intermediate representation
    TreeBuildingListener v = new TreeBuildingListener(file, myCompileEnvironment.getTypeGraph());
    ParseTreeWalker.DEFAULT.walk(v, rootModuleCtx);

    return v.getModule();
}