【发布时间】:2016-11-20 10:55:54
【问题描述】:
我正在尝试使用 libclang python 绑定来解析我的 c++ 源文件。我无法获取宏的值或扩展宏。
这是我的示例 C++ 代码
#define FOO 6001
#define EXPAND_MACR \
int \
foo = 61
int main()
{
EXPAND_MACR;
cout << foo;
return 0;
}
这是我的python脚本
import sys
import clang.cindex
def visit(node):
if node.kind in (clang.cindex.CursorKind.MACRO_INSTANTIATION, clang.cindex.CursorKind.MACRO_DEFINITION):
print 'Found %s Type %s DATA %s Extent %s [line=%s, col=%s]' % (node.displayname, node.kind, node.data, node.extent, node.location.line, node.location.column)
for c in node.get_children():
visit(c)
if __name__ == '__main__':
index = clang.cindex.Index.create()
tu = index.parse(sys.argv[1], options=clang.cindex.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD)
print 'Translation unit:', tu.spelling
visit(tu.cursor)
这是我从 clang 那里得到的信息:
Found FOO Type CursorKind.MACRO_DEFINITION DATA <clang.cindex.c_void_p_Array_3 object at 0x10b86d950> Extent <SourceRange start <SourceLocation file 'sample.cpp', line 4, column 9>, end <SourceLocation file 'sample.cpp', line 4, column 17>> [line=4, col=9]
Found EXPAND_MACR Type CursorKind.MACRO_DEFINITION DATA <clang.cindex.c_void_p_Array_3 object at 0x10b86d950> Extent <SourceRange start <SourceLocation file 'sample.cpp', line 6, column 9>, end <SourceLocation file 'sample.cpp', line 8, column 11>> [line=6, col=9]
Found EXPAND_MACR Type CursorKind.MACRO_INSTANTIATION DATA <clang.cindex.c_void_p_Array_3 object at 0x10b86d950> Extent <SourceRange start <SourceLocation file 'sample.cpp', line 12, column 2>, end <SourceLocation file 'sample.cpp', line 12, column 13>> [line=12, col=2]
如果你观察我的 python 脚本,node.data 会给出
DATA <clang.cindex.c_void_p_Array_3 object at 0x10b86d950>
我可以读取 clang 返回的 Extent 数据,然后从 start 到 end 位置解析文件以获取值。我想知道是否有更好的方法来获取宏值?
我想直接(不使用Extent)获取宏(示例中的6001)的值。我怎么能得到那个?
另外对于EXPAND_MACR 想得到int foo = 61
【问题讨论】: