我正在使用libclang的Python API。我有一个小测试程序打印解析文件的AST(节点类型,名称,类型):
public static int occur(int n, int i, int[] a)
{
if(i == a.size())
{
return 0;
}
return a[i] == n ? 1 + occur(n, i+1, a) : occur(n, i+1, a);
}
文件" map.hpp"包含以下代码:
from clang import cindex
def print_ast(node, depth):
line = " " * depth + "Node: %s" % node.kind
if node.spelling:
line += ", '%s'" % node.spelling
if node.type.spelling:
line += " (type: '%s')" % node.type.spelling
print(line)
for child in node.get_children():
print_ast(child, depth + 1)
if __name__ == "__main__":
lib_path = "/usr/lib/llvm-3.8/lib/"
cindex.Config.set_library_path(lib_path)
#cindex.Config.set_library_file(lib_path + "libclang-3.8.so")
index = cindex.Index.create()
options = (cindex.TranslationUnit.PARSE_INCOMPLETE |
cindex.TranslationUnit.PARSE_SKIP_FUNCTION_BODIES)
filename = "map.hpp"
with open(filename, "r") as infile:
content = infile.read()
translation_unit = index.parse(
filename, unsaved_files=[(filename, content)], options=options)
cursor = translation_unit.cursor
print_ast(cursor, 0)
我使用libclang-3.5获得以下输出(和3.6,在Ubuntu 14.04 / 16.04上安装了sudo pip install libclang-3.5-dev python-clang-3.5):
#include <string>
#include <map>
int lookup(std::map<std::string, int>& m)
{
return m["test"];
}
...以及libclang-3.8(和3.7):
...
Node: CursorKind.FUNCTION_DECL, 'lookup' (type: 'int std::map<std::string, int> &)')
Node: CursorKind.PARM_DECL, 'm' (type: 'std::map<std::string, int> &')
Node: CursorKind.NAMESPACE_REF, 'std'
Node: CursorKind.TEMPLATE_REF, 'map'
Node: CursorKind.NAMESPACE_REF, 'std'
Node: CursorKind.TYPE_REF, 'string' (type: 'string')
所以似乎可以确定正确类型的&#39; m&#39;但是在libclang 3.7中API已经改变,或者它被破坏或者其他错误。解析器似乎没有字符串或地图的任何问题,但当我包括两个标题时,我遇到了这个问题。