简体   繁体   中英

Read a ANTLR grammar

Due a grammar, Antlr generates a parser.

However, I would need to issue the grammar itself.

For example, I would need to know how many rules are there, how many optional sub-rules are there, and so on.

For example,

Grammar grammar = read_stream ('grammar_file.g4).
for (Rule rule : grammar.getRules())
{
  //....
}

Does it exists something like this out of the box with ANTLR4?

Sure. See the documentation on interpreted grammars . From a grammar file or string, you can create a Grammar object , which has lots of methods you might be interested in, such as getRule .

Here's a quick example based on the documentation on that page (I haven't actually tested this!):

LexerGrammar lg = new LexerGrammar(
    "lexer grammar L;\n" +
    "A : 'a' ;\n" +
    "B : 'b' ;\n" +
    "C : 'c' ;\n");
Grammar g = new Grammar(
    "parser grammar T;\n" +
    "s : (A|B)* C ;\n",
    lg);

for (String ruleName : g.getRuleNames()) {
    Rule rule = g.getRule(null, ruleName);
    // ...
}

Note that the above does not include rules from imported grammars. You can also get those via getImportedGrammars .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM