Chr*_*ton 11 python abstract-syntax-tree myhdl
以下是使用ast和symtable 包的Python代码段.我试图解析代码并检查类型.但我不明白如何遍历对象以获取被引用的实际变量.
下面的代码实现了一个NodeVisitor,并且一个函数被呈现给编译器并由编译器和ast走了.正在分析的函数(eval_types)传递了几个对象.
下面是构成示例的代码块.我为每个块添加了一些注释.要运行代码,需要重新组装"块".
导入和用于解压缩代码块的函数.
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)
Run Code Online (Sandbox Code Playgroud)
以下是节点访问者,它具有通用的未处理和名称访问者重载.
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)))
Run Code Online (Sandbox Code Playgroud)
以下是将在将使用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()
Run Code Online (Sandbox Code Playgroud)
以下是测试函数,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
Run Code Online (Sandbox Code Playgroud)
执行示例的代码,编译函数并进行分析.
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)
Run Code Online (Sandbox Code Playgroud)
以下是第一次访问名称的示例输出.
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']
Run Code Online (Sandbox Code Playgroud)
创建节点访问者似乎并不坏,但我无法弄清楚如何遍历对象层次结构.在一般情况下,被访问的变量可以深埋在对象中.如何获取从访问者访问的实际变量?我只看到一个对象在节点,但没有其他信息,结果变量访问是什么.
我不知道你是否还在寻找这个,但看起来你只需要添加 avisit_Attribute并向后遍历即可。如果您将其添加到您的示例中:
def visit_Attribute(self, node):
print(' attribute %s' % node.attr)
self._visit_children(node)
Run Code Online (Sandbox Code Playgroud)
那么输出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
Run Code Online (Sandbox Code Playgroud)
根据您想要执行的操作,您只需将属性存储在列表中,直到Name遇到 a,然后反转它们。
| 归档时间: |
|
| 查看次数: |
2687 次 |
| 最近记录: |