有没有办法使用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)
Run Code Online (Sandbox Code Playgroud)
哪个在sample.cpp上运行
enum
{
VAL = 1
};
struct s …Run Code Online (Sandbox Code Playgroud) 我正在编写一个简单的工具来帮助重构我们的应用程序的源代码.我想解析基于wxWidgets库的C++代码,它定义了GUI并生成.ui用于Qt的XML 文件.我需要获取所有函数调用和参数值.
目前我正在使用Python绑定到Clang,使用下面的示例代码我得到了令牌及其种类和位置,但光标种类总是如此CursorKind.INVALID_FILE.
import sys
import clang.cindex
def find_typerefs(node):
""" Find all references to the type named 'typename'
"""
for t in node.get_tokens():
if not node.location.file != sys.argv[1]:
continue
if t.kind.value != 0 and t.kind.value != 1 and t.kind.value != 4:
print t.spelling
print t.location
print t.cursor.kind
print t.kind
print "\n"
index = clang.cindex.Index.create()
tu = index.parse(sys.argv[1])
print 'Translation unit:', tu.spelling
find_typerefs(tu.cursor)
Run Code Online (Sandbox Code Playgroud)
确定光标种类的正确方法是什么?
除了很少的博客文章,我找不到任何文档,但它们已经过时或者没有涵盖这个主题.我无法从Clang附带的例子中解决这个问题.
我有一些代码(从这里和这里获取和改编),它使用libclang 解析Python(Widnows)中的C++ 源文件并获取其所有声明语句,如下所示:
import clang.cindex
def parse_decl(node):
reference_node = node.get_definition()
if node.kind.is_declaration():
print(node.kind, node.kind.name,
node.location.line, ',', node.location.column,
reference_node.displayname)
for ch in node.get_children():
parse_decl(ch)
# configure path
clang.cindex.Config.set_library_file('C:/Program Files (x86)/LLVM/bin/libclang.dll')
index = clang.cindex.Index.create()
trans_unit = index.parse(r'C:\path\to\sourcefile\test.cpp', args=['-std=c++11'])
parse_decl(trans_unit.cursor)
Run Code Online (Sandbox Code Playgroud)
对于以下 C++ 源文件 ( test_ok.cpp):
/* test_ok.cpp
*/
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <cmath>
#include <iomanip>
using namespace std;
int main (int argc, char *argv[]) {
int linecount …Run Code Online (Sandbox Code Playgroud)