简体   繁体   English

Antlr v3:在解析树中打印给定节点的子树

[英]Antlr v3: Printing the subtree of a given node in a parse tree

I'm current working on a project and I came to the point where I need to extract all methods from a given Java source code. 我目前在一个项目上工作,我到了需要从给定Java源代码中提取所有方法的地步。 I need to implement it in antlr v3 but I came to a dead-end since the api documentation doesn't clarify how can one do that. 我需要在antlr v3中实现它,但是由于api文档没有阐明如何做到这一点,我走到了死胡同。 I've also searched through the official book but still with no success. 我也搜索过正式书,但仍然没有成功。 Any ideas? 有任何想法吗?

EDIT: I found that in antlr v4 this can be done as: 编辑:我发现在antlr v4中可以这样做:

import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
import java.io.*;


public class Main {
    public static void main(String[] args) throws IOException {
        ANTLRInputStream input = new ANTLRInputStream(System.in);
        JavaLexer lexer = new JavaLexer(input);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        JavaParser parser = new JavaParser(tokens);

        ParseTree tree = parser.compilationUnit();
        ParseTreeWalker walker = new ParseTreeWalker();
        MethodPrinter printer = new MethodPrinter();
        walker.walk(printer, tree);
        for (String method : printer.methods)
            System.out.println(method);
    }
}

where Method printer is implemented as: Method printer的实现方式为:

import org.antlr.v4.runtime.tree.TerminalNode;
import java.util.ArrayList;

public class MethodPrinter extends JavaBaseListener {
    boolean inMethod;
    String currentMethod;
    ArrayList<String> methods;

    public MethodPrinter() {
        inMethod = false;
        methods = new ArrayList<String>();
    }

    public void enterMethodDeclaration(JavaParser.MethodDeclarationContext ctx) {
        inMethod = true;
        currentMethod = "";
    }

    public void exitMethodDeclaration(JavaParser.MethodDeclarationContext ctx) {
        inMethod = false;
        methods.add(currentMethod);
    }

    public void visitTerminal(TerminalNode node) {
        if (inMethod)
            currentMethod += node.getText() + " ";
    }
}

How this can be implemented in antlr v3 ? 如何在antlr v3中实现呢?

Java source code has to be encapsulated in a class. Java源代码必须封装在一个类中。
You can use reflection to get all the methods in a given class. 您可以使用反射来获取给定类中的所有方法。

...
Class cl = Class.forName("com.example.test.MyClass");
// or cl = someObject.getClass();
List<Method> methods = cl.getDeclaredMethods(cl);
methods.addAll(cl.getMethods());
...

then you can use it a normal java list 那么你可以使用它一个普通的Java列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM