Libclang Python绑定生成的AST无法解析C++源代码中的某些标记

1 投票
1 回答
1228 浏览
提问于 2025-04-18 13:42

我正在使用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');

如果有人能提供一个解决办法就太好了。也许有一个标志可以设置,避免这个问题?

1 个回答

1

你需要在调用解析的时候加上以下参数

-x c++ -std=c++11

否则它会默认把.h文件当作C语言代码来解析。你也可以把头文件的名字改成.hpp

这是我写的辅助脚本的样子。

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');
}

撰写回答