gpt4 book ai didi

java - 使用 antlr4 解析 java 代码时导航到不属于上下文的标记

转载 作者:行者123 更新时间:2023-11-30 09:05:54 35 4
gpt4 key购买 nike

我正在使用 ANTLR 4.2 解析 Java 源文件。

我的目标是在类中找到具有特定注释的方法。

我面临的问题是 Java.g4语法不包括annotation规则作为 methodDeclaration 的一部分规则(这是有道理的),这意味着当我覆盖 enterMethodDeclaration 时,它不能直接从上下文对象中使用的 JavaBaseListener :

@Override
public void enterMethodDeclaration(@NotNull JavaParser.MethodDeclarationContext ctx) {
// How do I access the annotation on the method in 'ctx'?
}

到目前为止,我唯一的想法是获取 token 流并尝试从方法声明上下文的位置向后遍历它。这样做的问题是它非常麻烦(方法上的注释可能出现在修饰符之前,修饰符之后,也就是说,如果修饰符确实存在)并且我觉得它缺少听众/访问者方法的要点。

是否有一种干净的方法来获取方法上的注释?

最佳答案

与其尝试遍历向上 解析树,不如考虑向下遍历。您可以从 classBodyDeclaration 生产开始,检查您是否可以进入 memberDeclaration 并从那里进入 methodDeclaration。如果是这样,您就知道您目前正处于一种方法中。然后只需遍历 classBodyDeclaration 中的 modifier 列表即可找到注释。

快速演示:

public class Main {

public static void main(String[] args) throws Exception {

String input = "@Annotation(\"class\")\n" +
"class Mu {\n" +
"\n" +
" @Annotation(\"field\")\n" +
" int x;\n" +
" \n" +
" @Annotation(\"method\")\n" +
" void withAnnotation(){}\n" +
" \n" +
" void withoutAnnotation(){}\n" +
"}";

JavaLexer lexer = new JavaLexer(new ANTLRInputStream(input));
JavaParser parser = new JavaParser(new CommonTokenStream(lexer));

// classBodyDeclaration
// : ...
// | modifier* memberDeclaration
// ;
//
// memberDeclaration
// : methodDeclaration
// | ...
// ;
//
// methodDeclaration
// : (type|'void') Identifier formalParameters ...
// ;
//
// modifier
// : classOrInterfaceModifier
// | ...
// ;
//
// classOrInterfaceModifier
// : annotation
// | ...
// ;
ParseTreeWalker.DEFAULT.walk(new JavaBaseListener(){
@Override
public void enterClassBodyDeclaration(@NotNull JavaParser.ClassBodyDeclarationContext ctx) {

if (!(ctx.memberDeclaration() != null && ctx.memberDeclaration().methodDeclaration() != null)) {
// No method declaration.
return;
}

String methodName = ctx.memberDeclaration().methodDeclaration().Identifier().getText();

for (JavaParser.ModifierContext mctx : ctx.modifier()) {
if (mctx.classOrInterfaceModifier() != null && mctx.classOrInterfaceModifier().annotation() != null) {
System.out.println(methodName + " -> " + mctx.classOrInterfaceModifier().annotation().getText());
}
}
}
}, parser.compilationUnit());
}
}

打印:

withAnnotation -> @Annotation("method")

关于java - 使用 antlr4 解析 java 代码时导航到不属于上下文的标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24677858/

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