有没有办法使用 libclang 检测匿名枚举而不依赖拼写名称中的文本?
与libclang的 python 绑定包括使用clang.cindex.Cursor.is_anonymous检测 C/C++ 结构或联合是否匿名的功能,最终调用clang_Cursor_isAnonymous。
以下示例演示了该问题。
import sys
from clang.cindex import *
def nodeinfo(n):
return (n.kind, n.is_anonymous(), n.spelling, n.type.spelling)
idx = Index.create()
# translation unit parsed correctly
tu = idx.parse(sys.argv[1], ['-std=c++11'])
assert(len(tu.diagnostics) == 0)
for n in tu.cursor.walk_preorder():
if n.kind == CursorKind.STRUCT_DECL and n.is_anonymous():
print nodeinfo(n)
if n.kind == CursorKind.UNION_DECL and n.is_anonymous():
print nodeinfo(n)
if n.kind == CursorKind.ENUM_DECL:
if n.is_anonymous():
print nodeinfo(n)
else:
print 'INCORRECT', nodeinfo(n)
在 sample.cpp 上运行时
enum
{
VAL = 1
};
struct s
{
struct {};
union
{
int x;
float y;
};
};
给出:
INCORRECT (CursorKind.ENUM_DECL, False, '', '(anonymous enum at sample1.cpp:1:1)')
(CursorKind.STRUCT_DECL, True, '', 's::(anonymous struct at sample1.cpp:8:5)')
(CursorKind.UNION_DECL, True, '', 's::(anonymous union at sample1.cpp:9:5)')