首页 > 解决方案 > 获取所有调用的函数(即使被另一个函数调用)libclang python

问题描述

我正在尝试使用 libclang/python 3.7 通过将程序解析为翻译单元来收集程序中调用的每个函数。我解析 main.cpp 文件以收集数据。

测试头.cpp

#include <testhead.h>
void a()
{
   std::cout<<5;
   b();
}
void b()
{
    std::cout<<6;
} 

主要.cpp

#include "testhead.h"

//classtest ct;

int main()
{
  a();
  return 0;
}

OutPut我正在尝试获取所有函数调用,由 CALL_EXPR 指出,它仅在函数 a() 调用函数 b() 时为函数 a() 提供

用于获取输出的示例 python/libclang

for i in node.get_children():
        if i.kind == clang.cindex.CursorKind.CALL_EXPR:
            print(str(i.kind)+","+i.spelling)
            #print(str(i.extent.start))
            tempSet.add(i.spelling)
        elif i.kind == clang.cindex.CursorKind.FUNCTION_DECL:
            print(str(i.kind)+","+i.spelling)
            #print(str(i.extent.start.file))
            for item in i.get_children():
                if item.kind == clang.cindex.CursorKind.CALL_EXPR:
                    tempSet.add(item.kind)
                    for n in item.get_children():
                        print(str(n.kind) +","+ n.spelling)
                        for z in n.get_children():
                            print(str(z.kind) +","+ z.spelling)
                elif item.kind == clang.cindex.CursorKind.COMPOUND_STMT:
                    print(' ' + str(item.kind) + ', ' + item.spelling)
                    #print(' ' + str(item.extent.start.file))
                    for c in item.get_children():
                        if c.kind == clang.cindex.CursorKind.CALL_EXPR:
                            print(' '*2 + str(c.kind) + ', ' + c.spelling+" , " + c.displayname)
                            #print(' '*2 + str(c.extent.start))
                            a = c.get_definition()
                            print(' '*10 + str(a))
                            tempSet.add(c.spelling)
                            for z in c.get_children():
                                print(' '*3 + str(z.kind) + ", "+ z.spelling)
                                a = z.get_definition()
                                print(' '*10 + str(a))
                                for x in z.get_children():
                                    print(' '*4 + str(x.kind) +","+ x.spelling)
                                    a = x.get_definition()
                                    print(' '*10 + str(a))
                                    for b in x.get_children():
                                        a = b.get_definition()
                                        print(' '*10 + str(a))
                                        print(' '*5 + str(b.kind) +","+ b.spelling)

通过反复试验,我发现我只能在 main.cpp 中定义的函数定义中找到嵌套函数调用。

到目前为止,我发现的唯一解决方案是我需要包含 .h 和 .cpp 的包含声明,例如:

#include <test.h>
#include <test.cpp>
main.cpp
..............

但是我将无法访问 .cpp,我将使用 dll

标签: pythonc++libclang

解决方案


推荐阅读