Example usage for org.antlr.v4 Tool createGrammar

List of usage examples for org.antlr.v4 Tool createGrammar

Introduction

In this page you can find the example usage for org.antlr.v4 Tool createGrammar.

Prototype

public Grammar createGrammar(GrammarRootAST ast) 

Source Link

Document

Given the raw AST of a grammar, create a grammar object associated with the AST.

Usage

From source file:org.opencypher.tools.grammar.Antlr4TestUtils.java

License:Apache License

private static Grammar createGrammar(String resource, org.opencypher.grammar.Grammar.ParserOption... options) {
    // We need to do some custom post-processing to get the lexer rules right
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    String grammarString = null;/*from   ww w . j av a 2s. com*/
    try {
        Antlr4.write(Fixture.grammarResource(Antlr4.class, resource, options), out);
        grammarString = out.toString(UTF_8.name());
        System.out.println(grammarString);
    } catch (Throwable t) {
        t.printStackTrace();
        fail("Unexpected error while writing antlr grammar");
    }

    org.antlr.v4.Tool tool = new org.antlr.v4.Tool();

    GrammarRootAST ast = tool.parseGrammarFromString(grammarString);
    Grammar grammar = tool.createGrammar(ast);
    tool.process(grammar, false);
    return grammar;
}

From source file:org.opencypher.tools.grammar.Antlr4ToolFacade.java

License:Apache License

public static void assertGeneratesValidParser(String resource) throws Exception {
    Output.Readable buffer = stringBuilder();
    Tool antlr = new Tool();
    Antlr4ToolFacade facade = new Antlr4ToolFacade(antlr, buffer);
    try {/*www . ja  va  2  s. c o m*/
        Antlr4.write(Fixture.grammarResource(Antlr4.class, resource), buffer);
    } catch (Throwable e) {
        try {
            facade.reportFailureIn("generating grammar");
        } catch (AssertionError x) {
            throw e;
        }
    }
    antlr.addListener(facade);
    GrammarRootAST ast = antlr.parse(resource, new ANTLRReaderStream(buffer.reader()));
    if (ast.hasErrors) {
        RuleAST lastGood = lastGoodRule(ast);
        if (lastGood == null) {
            facade.reportFailureIn("parsing grammar");
        } else {
            facade.reportFailureIn(
                    "parsing grammar, after " + lastGood.getRuleName() + " on line " + lastGood.getLine());
        }
    }
    antlr.process(antlr.createGrammar(ast), false);
    if (facade.hasErrors()) {
        facade.reportFailureIn("processing grammar");
    }
}