由Libclang的python绑定生成的AST无法解析c++源代码中的某些令牌

AST generated by Libclang’s python binding unable to parse certain tokens in C++ source codes

本文关键字:源代码 c++ 令牌 绑定 python Libclang AST      更新时间:2023-10-16

我正在使用Libclang的python绑定。我基本上有两个查询:

  1. 我想知道我们如何解析既不是由用户定义也不是包含库的库函数。例如,当我有以下源代码-

     char* a=(char *)malloc(4);
    
    • Libclang无法解析malloc(),因为此代码中既没有包含stdlib,也没有为malloc提供用户定义。
  2. 未使用构造函数定义的对象不会被Libclang的AST识别,例如在源代码中-

    vector<int> color;
    color.push_back(1);
    color.push_back(2);
    

push_back()语句将不会被解析,但是当这样写时:

        vector<int> color=new vector<int>();
        color.push_back(1);
        color.push_back(2);

可以正确解析

  • 这种行为的另一个令人惊讶的表现是当这些对象作为函数参数传递给用户定义的函数时。例如。

    bool check(int **grid, vector<char> color){
    color.push_back('a');
    }
    

push_back()仍然没有被识别,但是当编写它时,事情被正确解析

    bool check(int **grid, vector<char> color, int anc, int cur){
    vector<char> color = new vector<int>()
    color.push_back('a');

如果有人能提出一个解决办法,那就太好了。也许有一个标志可以避免这种情况?

您需要添加以下参数

- c++ -std=c++11

调用parse时,否则默认为解析.h文件的C代码。您可以将头文件重命名为.hpp

下面是我的helper脚本。

from cindex import *
def get_cursor_from_file(filename,my_args=[]):
    index = Index.create()
    options = TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD
    file_obj = index.parse(filename,args=my_args,options=options)
    for i in file_obj.diagnostics:
        print i
    return file_obj.cursor

x = get_cursor_from_file('test.cpp')
for c in x.get_children():
    print c.spelling

我测试的源文件看起来像这样

#include <vector>
using namespace std;
int main(){
 char* a=(char *)malloc(4);
 vector<int> color;
 vector<int> *color2=new vector<int>();
 color.push_back(1);
 color.push_back(2);
}
bool check(int **grid, vector<char> color){
    color.push_back('a');
}