gpt4 book ai didi

java - 从 ANTLR AST 识别 Java 变量

转载 作者:行者123 更新时间:2023-11-30 03:51:58 26 4
gpt4 key购买 nike

我想列出使用 ANTLR4 的 Java 源代码中使用的所有变量。对于以下源,结果应为 a,b,i

class Item {}
class First {
public static void main(String[] args) {
int a = 3;
int b;
b = a + 1;
Item i = new Item();
i = new Item();
System.out.println(b);
}
}

使用the official grammar我可以这样提取 AST: ( view larger ) AST grammar

问题是我不知道如何区分变量和例如系统,因为它们都被标记为表达式 -> 主要

我想这是一个常见问题,但我找不到任何合适的答案。谁能帮我?

最佳答案

只需重写 JavaBaseListener 中的 enterVariableDeclarator(...) 方法即可获取文本 variableDeclaratorId 匹配项:

public class Main {

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

final String source = "class Item {}\n" +
"class First {\n" +
" public static void main(String[] args) {\n" +
" int a = 3;\n" +
" int b;\n" +
" b = a + 1;\n" +
" Item i = new Item();\n" +
" i = new Item();\n" +
" System.out.println(b);\n" +
" }\n" +
"}";

final JavaLexer lexer = new JavaLexer(new ANTLRInputStream(source));
final JavaParser parser = new JavaParser(new CommonTokenStream(lexer));
final List<String> variables = new ArrayList<>();

ParseTreeWalker.DEFAULT.walk(new JavaBaseListener() {
// variableDeclarator
// : variableDeclaratorId ('=' variableInitializer)?
// ;
@Override
public void enterVariableDeclarator(@NotNull JavaParser.VariableDeclaratorContext ctx) {
variables.add(ctx.variableDeclaratorId().getText());
}
}, parser.compilationUnit());

System.out.printf("variable=%s", variables);
}
}

将打印:

variable=[a, b, i]

关于java - 从 ANTLR AST 识别 Java 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24208450/

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