[英]Read a ANTLR grammar
Due a grammar, Antlr generates a parser. 由于存在语法,Antlr会生成解析器。
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? 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
. 从语法文件或字符串中,您可以创建一个
Grammar
对象 ,该对象具有许多您可能感兴趣的方法,例如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
. 您也可以通过
getImportedGrammars
获得这些getImportedGrammars
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.