![](/img/trans.png)
[英]I want to extract all method names and variable names from a java source file using ANTLR4
[英]How to save a method name and names of all methods called inside that method when parsing a java file with ANTLR4?
我正在開發一個程序,該程序使用來自 ANTLRs github 的 Java9 詞法分析器和語法來解析 Java 文件。 解析文件時,我想在HashMap<String, Set<String>>
保存每個方法名稱和該方法內部調用的所有方法的名稱。
我使用偵聽器模式,其中使用方法exitMethodDeclaration獲取方法名稱,使用exitMethodInvocation獲取方法調用。 問題是這兩個方法是在解析樹的不同節點上調用的,因此它們采用不同的上下文作為參數。 因此,據我所知,我無法調用該方法來獲取exitMethodDeclaration 中的調用。 我嘗試構建自己的遞歸,這樣我就可以通過將 methodDeclarationContext 作為參數傳遞給exitMethodInvocation來解決類型問題。 不過這會非常復雜,我想使用 ANTLRs 功能。
對於下面的代碼,每個方法的 hashSet 包含整個文件的所有方法調用,而不僅僅是特定方法的調用。
private HashMap<String, HashSet<String>> methodCalls = new HashMap<>();
private HashSet<String> methodCallNames = new HashSet<>();
public void exitMethodDeclaration(Java9Parser.MethodDeclarationContext ctx) {
String methodName = ctx.methodHeader().methodDeclarator().identifier().getText();
methodCalls.put(methodName, methodCallNames);
}
public void exitMethodInvocation(Java9Parser.MethodInvocationContext ctx) {
try {
String m = ctx.methodName().identifier().getText();
methodCallNames.add(m);
} catch (Exception e) {
}
}
關於如何在同一方法中收集不同上下文類型的節點、訪問偵聽器/訪問者方法中的子樹或其他想法的任何想法都非常受歡迎!
您可以創建一個 ArrayList 堆棧。
每次enterMethodDeclaration
,都會將一個新的Empty ArrayList 推送到您的堆棧中。
每次enterMethodInvocation
(或exit...
如果您願意),您都可以將methodName 添加到您在stack.peek() 上的ArrayList 中。
每當您exitMethodDeclartation
stack.pop() ArrayList 時,它都會列出您在該方法調用中直接遇到的所有方法名稱。 而且,方法名稱就在exitMethodDeclaration
的 Context 參數中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.