如何在 ANTLR 中找到 children 的 children 上下文?
How to find children of children's context in ANTLR?
如标题所说,在ANTLR中监听或访问节点时,有没有办法找到children节点的children
例如:(使用 grammars-v4-java 词法分析器和解析规则)
首先,我取一个java文件到语法树。
grun Java compilationUnit -gui Example.java
// Example.java
public class Example {
String name = "test";
void call(){
String name1 = "test";
}
}
语法树是
然后我尝试使用java扩展baseListerner来监听enterClassDeclaration
节点。所以我可以获得 ClassDeclarationContext
节点。我想找到 child 类型为 LocalDeclarationContext
.
的 children 的 ClassDeclarationContext
节点的 children
在这个例子中:
public class MyListener extends JavaParserBaseListener {
@Override
public void enterClassDeclaration(JavaParser.ClassDeclarationContext ctx) {
// find the children of children by ctx
List<ParserRuleContext> contexts = findChildContextBy(ctx, LocalVariableDeclarationContext.class);
super.enterClassDeclaration(ctx);
}
}
变量contexts
应该有两个元素。 name
和 name1
不想children一层一层的找。 emmm,请问有什么方便的方法吗?
对于给定的解析树,使用 ANTLR4's XPath implementation.
可以很容易地查找特定的子节点(在任何嵌套级别)
您可以通过调用的解析器规则从完整的解析树 return 或在特定子树的 listener/visitor 方法中触发该搜索,例如:
List<ParseTreeMatch> matches = XPath.findAll(ctx, "//localVariableDeclaration", parser);
return 个匹配项是 LocalVariableDeclarationContext
的实例(如果有匹配的话)。
注意:链接页面描述了两个搜索实用程序,解析树匹配和 XPath,可以单独使用或一起使用。
如标题所说,在ANTLR中监听或访问节点时,有没有办法找到children节点的children
例如:(使用 grammars-v4-java 词法分析器和解析规则)
首先,我取一个java文件到语法树。
grun Java compilationUnit -gui Example.java
// Example.java
public class Example {
String name = "test";
void call(){
String name1 = "test";
}
}
语法树是
然后我尝试使用java扩展baseListerner来监听enterClassDeclaration
节点。所以我可以获得 ClassDeclarationContext
节点。我想找到 child 类型为 LocalDeclarationContext
.
ClassDeclarationContext
节点的 children
在这个例子中:
public class MyListener extends JavaParserBaseListener {
@Override
public void enterClassDeclaration(JavaParser.ClassDeclarationContext ctx) {
// find the children of children by ctx
List<ParserRuleContext> contexts = findChildContextBy(ctx, LocalVariableDeclarationContext.class);
super.enterClassDeclaration(ctx);
}
}
变量contexts
应该有两个元素。 name
和 name1
不想children一层一层的找。 emmm,请问有什么方便的方法吗?
对于给定的解析树,使用 ANTLR4's XPath implementation.
可以很容易地查找特定的子节点(在任何嵌套级别)您可以通过调用的解析器规则从完整的解析树 return 或在特定子树的 listener/visitor 方法中触发该搜索,例如:
List<ParseTreeMatch> matches = XPath.findAll(ctx, "//localVariableDeclaration", parser);
return 个匹配项是 LocalVariableDeclarationContext
的实例(如果有匹配的话)。
注意:链接页面描述了两个搜索实用程序,解析树匹配和 XPath,可以单独使用或一起使用。