Python ast包:遍历对象层次结构

时间:2012-02-24 04:29:22

标签: python abstract-syntax-tree myhdl

以下是使用 ast symtable 的Python代码段 包。我试图解析代码并检查类型。但是我 不了解如何遍历对象以获取实际变量 被引用。

以下代码实现了一个NodeVisitor,并且一个函数被呈现给编译器并由编译器和ast走了。正在分析的函数(eval_types)传递了几个对象。

以下是构成示例的代码块。我为每个块添加了一些注释。要运行代码," chunks"需要重新组装。

import和一个用于解压缩代码块以进行解析的函数。

import inspect
import ast
import symtable
from tokenize import generate_tokens, untokenize, INDENT
from cStringIO import StringIO

# _dedent borrowed from the myhdl package (www.myhdl.org)
def _dedent(s):
    """Dedent python code string."""

    result = [t[:2] for t in generate_tokens(StringIO(s).readline)]
    # set initial indent to 0 if any
    if result[0][0] == INDENT:
        result[0] = (INDENT, '')
    return untokenize(result)

以下是节点访问者,它具有通用的未处理和名称访问者重载。

class NodeVisitor(ast.NodeVisitor):
    def __init__(self, SymbolTable):
        self.symtable = SymbolTable
        for child in SymbolTable.get_children():
            self.symtable = child
            print(child.get_symbols())

    def _visit_children(self, node):
        """Determine if the node has children and visit"""
        for _, value in ast.iter_fields(node):
            if isinstance(value, list):
                for item in value:
                    if isinstance(item, ast.AST):
                        print('  visit item %s' % (type(item).__name__))
                        self.visit(item)

            elif isinstance(value, ast.AST):
                print('  visit value %s' % (type(value).__name__))
                self.visit(value)

    def generic_visit(self, node):
        print(type(node).__name__)
        self._visit_children(node)

    def visit_Name(self, node):
        print('  variable %s type %s' % (node.id,
                                         self.symtable.lookup(node.id)))
        print(dir(self.symtable.lookup(node.id)))

以下是将在将使用AST解析和分析的函数中使用的一些简单类。

class MyObj(object):
    def __init__(self):
        self.val = None

class MyObjFloat(object):
    def __init__(self):
        self.x = 1.

class MyObjInt(object):
    def __init__(self):
        self.x = 1

class MyObjObj(object):
    def __init__(self):
        self.xi = MyObjInt()
        self.xf = MyObjFloat()

以下是测试函数,eval_types函数是将用AST分析的函数。

def testFunc(x,y,xo,z):

    def eval_types():
        z.val = x + y + xo.xi.x + xo.xf.x

    return eval_types

执行示例的代码,编译函数并进行分析。

if __name__ == '__main__':
    z = MyObj()
    print(z.val)
    f = testFunc(1, 2, MyObjObj(), z)
    f()
    print(z.val)
    s = inspect.getsource(f)
    s = _dedent(s)
    print(type(s))
    print(s)

    SymbolTable = symtable.symtable(s,'string','exec')
    tree = ast.parse(s)
    v = NodeVisitor(SymbolTable)
    v.visit(tree)

以下是第一次访问名称的示例输出。

Module
  visit item FunctionDef
FunctionDef
  visit value arguments
arguments
  visit item Assign
Assign
  visit item Attribute
Attribute
  visit value Name
  variable z type <symbol 'z'>
['_Symbol__flags', '_Symbol__name', '_Symbol__namespaces', 
 '_Symbol__scope', '__class__', '__delattr__', '__dict__', 
 '__doc__', '__format__', '__getattribute__', '__hash__', 
 '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', 
 '__repr__', '__setattr__', '__sizeof__', '__str__', 
 '__subclasshook__', '__weakref__', 'get_name', 'get_namespace', 
 'get_namespaces', 'is_assigned', 'is_declared_global', 
 'is_free', 'is_global', 'is_imported', 'is_local', 
 'is_namespace', 'is_parameter', 'is_referenced']

创建节点访问者似乎并不好,但我无法弄清楚 如何遍历对象层次结构。在一般情况下变量 被访问的内容可能深埋在一个对象中。如何获取从访问者访问的实际变量?我只看到对象在节点处,但没有其他信息,结果变量访问是什么。

1 个答案:

答案 0 :(得分:2)

我不知道你是否还在寻找这个,但看起来你只需要添加一个visit_Attribute并向后遍历。如果您将此添加到您的示例中:

def visit_Attribute(self, node):
    print('  attribute %s' % node.attr)
    self._visit_children(node)

然后xo.xf.x的输出是:

Add
  visit value Attribute
  attribute x
  visit value Attribute
  attribute xf
  visit value Name
  variable xo type <symbol 'xo'>
  visit value Load

根据您要对此进行的操作,您只需将属性存储在列表中,直到遇到Name,然后将其反转。