【发布时间】:2021-02-03 08:41:55
【问题描述】:
我使用 clang.cindex 库来解析 C++ 源代码。
使用get_children() 函数,我尝试打印所有已解析的行。
这是我的 Python 代码。
import clang.cindex
def print_all(cursor, i):
print('\t' * i, cursor.kind, ':', cursor.spelling, '(', cursor.location, ')')
for child in cursor.get_children():
print_all(child, i+1)
if __name__=='__main__':
tu = clang.cindex.Index.create().parse(filename)
print_all(tu.cursor, 0)
这是目标 C++ 源代码。
void bad()
{
char * data;
data = NULL;
data = new char[50];
data[0] = '\0';
const int& baseObject = char_ncpy_81_bad();
baseObject.action(data);
}
但是,它不会打印所有行。 打印出来的线条如下。
Cursor.Kind.Function_DECL : bad ( <..., line 9, column 6> )
CursorKind.COMPOUND_STMT : ( <..., line 10, column 1> )
CursorKind.DECL_STMT : ( <..., line 11, column 5> )
CursorKind.VAR_DECL : data ( <..., line 11, column 12> )
CursorKind.BINARY_OPERATOR : ( <..., line 14, column 5> )
CursorKind.DECL_REF_EXPR : data ( <..., line 14, column 5> )
CursorKind.CXX_DELETE_EXPR : ( <..., line 14, column 12> )
CursorKind.UNEXPOSED_EXPR : ( <..., line 14, column 21> )
CursorKind.Integer_LITERAL : ( <..., line 14, column 21> )
CursorKind.BINARY_OPERATOR : ( <..., line 15, column 5> )
CursorKind.ARRAY_SUBSCRIPT_EXPR : ( <..., line 15, column 5> )
CursorKind.UNEXPOSED_EXPR : data ( <..., line 15, column 5> )
CursorKind.DECL_REF_EXPR : data ( <..., line 15, column 5> )
CursorKind.INTEGER_LITERAL : ( <..., line 15, column 5> )
CursorKind.CHARACTER_LITERAL : ( <..., line 15, column 5> )
CursorKind.DECL_STMT : ( <..., line 16, column 5> )
CursorKind.VAR_DECL : baseObject ( <..., line 16, column 16> )
如您所见,结果中没有出现某些行。
如何打印所有 C++ 代码行? 或者Python上有没有C++源码解析库?
【问题讨论】: