ANTLR解析树中的Python-AST?

2024-09-30 22:11:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

像这样的东西存在吗?在

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

编辑2:所说的“AST”是指http://docs.python.org/2/library/ast.html#abstract-grammar,而“parse tree”是指http://docs.python.org/2/reference/grammar.html。在


Tags: 文件项目orghttp编辑docs节点html
3条回答

以下是一个开始:

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();
    }
}

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

^{pr2}$

会打印:

'- file_input
   |- stmt
   |  |- small_stmt
   |  |  |- atom
   |  |  |  '- TOKEN[type: 35, text: f]
   |  |  '- trailer
   |  |     |- TOKEN[type: 47, text: (]
   |  |     |- arglist
   |  |     |  |- test
   |  |     |  |  '- TOKEN[type: 35, text: arg1]
   |  |     |  |- TOKEN[type: 53, text: =]
   |  |     |  '- test
   |  |     |     '- TOKEN[type: 36, text: '1']
   |  |     '- TOKEN[type: 48, text: )]
   |  '- TOKEN[type: 34, text: \n]
   '- TOKEN[type: -1, text: ]

我知道它仍然包含您可能不想要的节点,但是您甚至可以添加一组您想要排除的令牌类型。请随意砍掉!在

Here is a Gist包含上面代码的一个版本,带有正确的import语句和一些javadoc和内联注释。在

eclipsedltk项目Python子项目在Java中实现了custom Python AST model。它是从AntlrV3 ast构建的,但是从AntlrV4解析树重新构建应该不会太困难。在

EclipsePyDev project大概还实现了一个基于Java的AST for python源代码。注意,两个项目中的源树布局应该非常相似。在

当然,您应该在使用这些源代码之前检查许可证,只是为了确定。在

我找到了一个解决办法:

使用Jythonast(谢谢@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());

输出是

^{pr2}$

这并没有严格回答问题,也可能不适用于所有用户,所以我不选择这个答案。在

相关问题 更多 >