gpt4 book ai didi

antlr - 遍历节点

转载 作者:行者123 更新时间:2023-12-01 23:50:49 25 4
gpt4 key购买 nike

我有以下语法(简化):

filter   : eq | and;

eq : 'eq' '(' property ',' value ')';

and : 'and' '(' filter ',' filter (',' filter)* ')';

...

我正在解析简单的前缀结构,例如:

and(eq(name,john),eq(location,usa))

遍历 and 节点的 filter 节点的最佳方法是什么?生成的类 AndContext 有一个函数 filter(int index),但仅此而已。我想做类似的事情:

AndContext c = ...;

for (int i = 0; i < c.numberOfFilters(); ++i) {
FilterContext f = c.filter(i);
}

有函数getChildCount(),但是返回的是所有节点的个数(包括代表(, )的终端节点,等),而不仅仅是有趣的 filter 节点。

最佳答案

假设您的语法如下所示:

grammar F;

eq : 'eq' '(' property ',' value ')';
and : 'and' '(' filter ',' filter (',' filter)* ')';
filter : eq | and;
property : 'name' | 'location';
value : 'john' | 'usa';

然后您可以扩展生成的 FBaseListener 并覆盖其 enterAnd 以获取 FilterContext:

public class Main {

public static void main(String[] args) throws Exception {
FLexer lexer = new FLexer(new ANTLRInputStream("and(eq(name,john),eq(location,usa))"));
FParser parser = new FParser(new CommonTokenStream(lexer));
ParseTreeWalker.DEFAULT.walk(new AndListener(), parser.and());
}
}

class AndListener extends FBaseListener {

@Override
public void enterAnd(@NotNull FParser.AndContext ctx) {
for (FParser.FilterContext filterContext : ctx.filter()) {
System.out.println("filterContext=" + filterContext.getText());
}
}
}

将打印:

filterContext=eq(name,john)
filterContext=eq(location,usa)

关于antlr - 遍历节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26677264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com