Clang的一个项目的AST [英] AST of a project by Clang

查看:218
本文介绍了Clang的一个项目的AST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Clang python绑定提取c/c ++文件的AST.它非常适合我编写的一个简单程序.问题是当我想将其用于像opensl这样的大项目时.我可以为项目的任何单个文件运行clang,但是clang似乎错过了该项目的某些标头,只是为我提供了文件中一些功能的AST信息,而不是全部功能的AST信息.我用-I设置了include文件夹,但仍然获得了部分功能.

I use the Clang python binding to extract the AST of c/c++ files. It works perfectly for a simple program I wrote. The problem is when I want to employ it for a big project like openssl. I can run clang for any single file of the project, but clang seems to miss some headers of the project, and just gives me the AST of a few functions of the file, not all of the functions. I set the include folder by -I, but still getting part of the functions.

这是我的代码:

import clang.cindex as cl    
cl.Config.set_library_path(clang_lib_dir)
index = cl.Index.create()
lib = 'Path to include folder'
args = ['-I{}'.format(lib)]
translation_unit = index.parse(source_file, args=args)
my_get_info(translation_unit.cursor)

我收到太多找不到的头文件错误.

I receive too many header files not found errors.

更新

我用Make通过clang编译openssl吗?我可以将-emit-ast选项传递给clang来转储每个文件的ast,但是现在我无法通过clang python绑定读取它.

I used Make to compile openssl by clang? I can pass -emit-ast option to clang to dump the ast of each file, but I cannot read it now by the clang python binding.

有什么线索可以保存翻译单元的序列化表示形式,以便可以通过index.read()读取它吗?

Any clues how I can save the the serialized representation of the translation units so that I will be able to read it by index.read()?

谢谢!

推荐答案

您将简单地"需要提供正确的args.但是请注意两个可能的问题.

You would "simply" need to provide the right args. But be aware of two possible issues.

不同的文件可能需要不同的参数来进行解析.最简单的解决方案是获取编译数据库,然后从中提取编译命令.如果您采用这种方式,请注意,您需要过滤掉一些参数并删除-c FooBar.cpp之类的内容(可能还会删除其他内容),否则您可能会看到类似ASTReadError的内容.

Different files may require different arguments for parsing. The easiest solution is to obtain compilation database and then extract compile commands from it. If you go this way be aware that you would need to filter out the arguments a bit and remove things like -c FooBar.cpp (potentially some others), otherwise you may get something like ASTReadError.

另一个问题是包含路径(-I ...)可能是相对于源目录的.即,如果文件main.cpp是从具有-I include/path参数的目录/opt/project/编译而成的,则在调用index.parse(source_file, args=args)之前,您需要先将(chdir)插入/opt/project,完成后您将可能需要返回到原始工作目录.因此代码可能看起来像这样(伪代码):

Another issue is that the include paths (-I ...) may be relative to the source directory. I.e., if a file main.cpp compiled from a directory /opt/project/ with -I include/path argument, then before calling index.parse(source_file, args=args) you need to step in (chdir) into the /opt/project, and when you are done you will probably need to go back to the original working directory. So the code may look like this (pseudocode):

cwd = getcwd()
chdir('/opt/project')
translation_unit = index.parse(source_file, args=args)
chdir(cwd)

希望对您有帮助.

这篇关于Clang的一个项目的AST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆