解析时是否可以统计某个元素出现的次数?
我试图找到一种方法来跟踪构建解析树时元素出现的次数。假设我的语法如下所示:
grammar sample;
@members {
private int xCount= 0;
private int yCount= 0;
private int zCount= 0;
}
// rules
fileData : part1 part2 EOF;
part1 : x+ y+ z+;
part2 : z+ y+ x+;
// I want to count these:
x : a+ b+ c+ {xCount++;};
y : c+ b+ a+ {yCount++;};
z : a+ c+ b+ {zCount++;};
// lexer rules
a : '1';
b : '2';
c : '3';
我如何利用计数的变量并说出类似 {System.out.println("found 4 x's, 5 y's, and 6 z's");}
解析何时完成?
I am trying to find a way to keep track of the number of times an element appears when building a parse tree. Let's say my grammar looks something like this:
grammar sample;
@members {
private int xCount= 0;
private int yCount= 0;
private int zCount= 0;
}
// rules
fileData : part1 part2 EOF;
part1 : x+ y+ z+;
part2 : z+ y+ x+;
// I want to count these:
x : a+ b+ c+ {xCount++;};
y : c+ b+ a+ {yCount++;};
z : a+ c+ b+ {zCount++;};
// lexer rules
a : '1';
b : '2';
c : '3';
How can I make use of the variables counted and say something like {System.out.println("found 4 x's, 5 y's, and 6 z's");}
when the parsing is complete?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以简单地在启动规则 (
fileData
) 的末尾打印它:或者将一个方法添加到您的
@members
部分:然后像这样使用它:
这将打印:
但 IMO 更好的选择是将(Java)代码与语法分开,并将其移至侦听器中。因此,从语法中删除嵌入的代码:
并创建一个监听器:
并像这样使用它:
导致:
请参阅: https://github.com/antlr/antlr4/blob/master/doc/listeners.md
请注意:中的注释“//词法分析器规则”
不是非常正确:它们是解析器规则,而不是词法分析器规则。 ANTLR 对上面的代码片段进行如下解释:
其中
T_0
、T_1
和T_2
是词法分析器规则。You can simply print it at the end of your start rule (
fileData
):or add a method to your
@members
section:and then use it like this:
which will print:
But an IMO better option is to separate the (Java) code from your grammar, and move this into a listener. So remove the embedded code from the grammar:
and create a listener:
and use it like this:
resulting in:
See: https://github.com/antlr/antlr4/blob/master/doc/listeners.md
Note that the comment "// lexer rules" in:
is not really correct: they're parser rules, not lexer rules. The snippet above is interpreted by ANTLR like this:
where
T_0
,T_1
andT_2
are the lexer rules.