4

我找到了一个ANTLRv4 Python3 grammer,但它生成了一个解析树,它通常有很多无用的节点。

我正在寻找一个已知的包来从该解析树中获取 Python AST。

这样的事情存在吗?

编辑:关于使用 Pythonast包的说明:我的项目是用 Java 编写的,我需要解析 Python 文件。

编辑 2: 'AST' 我的意思是http://docs.python.org/2/library/ast.html#abstract-grammar,而'解析树' 我的意思是http://docs.python.org/2 /reference/grammar.html

4

4 回答 4

7

以下可能是一个开始:

public class AST {

    private final Object payload;

    private final List<AST> children;

    public AST(ParseTree tree) {
        this(null, tree);
    }

    private AST(AST ast, ParseTree tree) {
        this(ast, tree, new ArrayList<AST>());
    }

    private AST(AST parent, ParseTree tree, List<AST> children) {

        this.payload = getPayload(tree);
        this.children = children;

        if (parent == null) {
            walk(tree, this);
        }
        else {
            parent.children.add(this);
        }
    }

    public Object getPayload() {
        return payload;
    }

    public List<AST> getChildren() {
        return new ArrayList<>(children);
    }

    private Object getPayload(ParseTree tree) {
        if (tree.getChildCount() == 0) {
            return tree.getPayload();
        }
        else {
            String ruleName = tree.getClass().getSimpleName().replace("Context", "");
            return Character.toLowerCase(ruleName.charAt(0)) + ruleName.substring(1);
        }
    }

    private static void walk(ParseTree tree, AST ast) {

        if (tree.getChildCount() == 0) {
            new AST(ast, tree);
        }
        else if (tree.getChildCount() == 1) {
            walk(tree.getChild(0), ast);
        }
        else if (tree.getChildCount() > 1) {

            for (int i = 0; i < tree.getChildCount(); i++) {

                AST temp = new AST(ast, tree.getChild(i));

                if (!(temp.payload instanceof Token)) {
                    walk(tree.getChild(i), temp);
                }
            }
        }
    }

    @Override
    public String toString() {

        StringBuilder builder = new StringBuilder();

        AST ast = this;
        List<AST> firstStack = new ArrayList<>();
        firstStack.add(ast);

        List<List<AST>> childListStack = new ArrayList<>();
        childListStack.add(firstStack);

        while (!childListStack.isEmpty()) {

            List<AST> childStack = childListStack.get(childListStack.size() - 1);

            if (childStack.isEmpty()) {
                childListStack.remove(childListStack.size() - 1);
            }
            else {
                ast = childStack.remove(0);
                String caption;

                if (ast.payload instanceof Token) {
                    Token token = (Token) ast.payload;
                    caption = String.format("TOKEN[type: %s, text: %s]",
                            token.getType(), token.getText().replace("\n", "\\n"));
                }
                else {
                    caption = String.valueOf(ast.payload);
                }

                String indent = "";

                for (int i = 0; i < childListStack.size() - 1; i++) {
                    indent += (childListStack.get(i).size() > 0) ? "|  " : "   ";
                }

                builder.append(indent)
                        .append(childStack.isEmpty() ? "'- " : "|- ")
                        .append(caption)
                        .append("\n");

                if (ast.children.size() > 0) {
                    List<AST> children = new ArrayList<>();
                    for (int i = 0; i < ast.children.size(); i++) {
                        children.add(ast.children.get(i));
                    }
                    childListStack.add(children);
                }
            }
        }

        return builder.toString();
    }
}

并可用于为输入创建 AST,"f(arg1='1')\n"如下所示:

public static void main(String[] args) {

    Python3Lexer lexer = new Python3Lexer(new ANTLRInputStream("f(arg1='1')\n"));
    Python3Parser parser = new Python3Parser(new CommonTokenStream(lexer));

    ParseTree tree = parser.file_input();
    AST ast = new AST(tree);

    System.out.println(ast);
}

这将打印:

'- 文件输入
   |- stmt
   | |- small_stmt
   | | |- 原子
   | | | '- TOKEN[类型:35,文本:f]
   | | '- 预告片
   | | |- TOKEN[类型:47,文本:(]
   | | |- 参数列表
   | | | |- 测试
   | | | | '- 令牌 [类型:35,文本:arg1]
   | | | |- 代币[类型:53,文本:=]
   | | | '- 测试
   | | | '- TOKEN [类型:36,文本:'1']
   | | '- 令牌[类型:48,文本:)]
   | '- 令牌[类型:34,文本:\n]
   '- 令牌[类型:-1,文本:]

我意识到这仍然包含您可能不想要的节点,但您甚至可以添加一组您想要排除的令牌类型。随意破解!

这是一个 Gist,其中包含上述代码的一个版本,其中包含正确的 import 语句和一些 JavaDocs 和内联注释。

于 2014-07-16T19:27:48.620 回答
0

Eclipse DLTK 项目 Python 子项目在 Java 中实现了一个自定义 Python AST 模型。它是从AntlrV3 ast构建的,但从 AntlrV4 解析树构建起来应该不会太难。

Eclipse PyDev 项目大概也为 python 源代码实现了一个基于 Java 的 AST。请注意,两个项目中源代码树的布局应该非常相似。

当然,您应该在使用这些来源的代码之前检查许可证,以确保安全。

于 2014-07-15T22:31:43.103 回答
0

我找到了解决方法:

使用Jythonand ast(感谢@delnan 带我去那里)。或者,直接在 Python 代码中完成您需要的所有操作,然后将结果返回给 Java。

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import ast");
PyObject o = interpreter.eval(
    "ast.dump(ast.parse('f(arg1=\\'1\\')', 'filename', 'eval'))" + "\n");
System.out.print(o.toString());

输出是

Expression(body=Call(func=Name(id='f', ctx=Load()), args=[], keywords=[keyword(arg='arg1', value=Str(s='1'))], starargs=None, kwargs=None))

这并未严格回答问题,并且可能不适用于所有用户,因此我未选择此答案。

于 2014-07-16T03:46:00.543 回答
0

ANTLR4 可以生成一个访问者,您可以使用它来遍历解析树并构造一个 AST。Python 有一个ast包,所以这应该不是问题(如果您使用的是 Python)。

我使用 ANTLR4在 Python 3 中编写了一个玩具 Python 解释器(作为我学习的一部分)。访客代码位于 中/tinypy/AST/builder/,因此您可以了解它是如何完成的。

于 2015-12-25T19:42:40.773 回答