【问题标题】:How can I skip includes using libclang?如何跳过包括使用 libclang?
【发布时间】:2023-03-13 03:04:01
【问题描述】:

我正在使用 libclang 来解析一个目标 c 源代码文件。以下代码查找所有 Objective-C 实例方法声明,但它也查找包含中的声明:

 enum CXCursorKind curKind  = clang_getCursorKind(cursor);
 CXString curKindName  = clang_getCursorKindSpelling(curKind);

 const char *funcDecl="ObjCInstanceMethodDecl";

 if(strcmp(clang_getCString(curKindName),funcDecl)==0{


 }

我怎样才能跳过头文件包含的所有内容?我只对源文件中我自己的 Objective-C 实例方法声明感兴趣,而不是任何包含。

例如以下内容不应包括在内

...

Location: /System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:15:9:315
Type: 
TypeKind: Invalid
CursorKind: ObjCInstanceMethodDecl

...

【问题讨论】:

    标签: objective-c parsing libclang


    【解决方案1】:

    回答这个问题是因为我无法相信硬编码路径比较是唯一的解决方案,而且确实有一个 clang_Location_isFromMainFile 函数可以完全满足您的需求,这样您就可以过滤访问者中不需要的结果,例如这个:

    if (clang_Location_isFromMainFile (clang_getCursorLocation (cursor)) == 0) {
      return CXChildVisit_Continue;
    }
    

    【讨论】:

    • 你知道我如何在 ASTFrontendAction 中使用它吗?
    【解决方案2】:

    我知道的唯一方法是在 AST 访问期间跳过不需要的路径。例如,您可以在访问者函数中添加如下内容。返回CXChildVisit_Continue 避免访问整个文件。

    CXFile file;
    unsigned int line, column, offset;
    CXString fileName;
    char * canonicalPath = NULL;
    
    clang_getExpansionLocation (clang_getCursorLocation (cursor),
                                &file, &line, &column, &offset);
    
    fileName = clang_getFileName (file);
    if (clang_getCString (fileName)) {
      canonicalPath = realpath (clang_getCString (fileName), NULL);
    }
    clang_disposeString (fileName);
    
    if (strcmp(canonicalPath, "/canonical/path/to/your/source/file") != 0) {
      return CXChildVisit_Continue;
    }
    

    另外,为什么要直接比较CursorKindSpelling 而不是CursorKind

    【讨论】:

    • clang_getFileName(file) 丢失
    • 不幸的是,光标现在没有到达我的源文件的方法声明。
    • 是的,你说得对,我忘了一步。在做这种事情时,我经常在比较文件路径时遇到困难,因为在文件系统上引用同一个文件的各种现有方法。避免这种情况的一种方法是在比较所有路径之前对其进行规范化。请查看我的编辑示例(希望这次完整!)
    • 这部分: if (strcmp(clang_getCString(fileName), "/canonical/path/to/your/source/file") != 0) { return CXChildVisit_Continue; } 不起作用...它没有达到方法声明,没有它一切正常(但速度慢)
    • 是的,我又犯了一个错误。我编辑了代码以基于canonicalPath 进行路径比较(这是使用realpath 的重点。
    猜你喜欢
    • 2013-05-21
    • 2020-06-21
    • 1970-01-01
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多