获取lib clang cursor / type

时间:2016-05-16 00:24:43

标签: python c++ clang libclang

我编写了一个脚本来检测我的C ++代码中的格式错误。 (例如,确保所有成员变量都以m_为前缀)。我想做的一件事是确保指针类型的asterix附加到类型(int* num,而不是int *num)。

所以我需要获取源代码中的类型文本。但是,获取光标或类型的拼写会返回一个漂亮的打印版本,它将始终返回int *,即使源有int*

为了解决这个问题,我得到了游标的范围并从源文件中获取子字符串并检查它。但是似乎没有办法获得类型的范围,所以我无法得到它的实际拼写?有办法做到这一点吗?也许通过获得该类型的令牌然后获得那些的范围?

(我使用python绑定,但如果需要可以切换到C API)

2 个答案:

答案 0 :(得分:0)

你可以尝试这样的事情。得到拼写:

std::string symbol = clang_getCString(clang_getCursorSpelling(Cursor));

寻找指针声明符:

case CXType_Pointer:
{
  // ...
}

使用clang_tokenize,然后使用它来查找*的展示位置。

// Tokens retrieved with clang_tokenize
// symbol declared earlier
auto finder = std::find(tokens.begin(), tokens.end(), symbol);
if (*(finder) == "*")
{
  if (*(finder + 1)) == " ") { /* ... */ } // int* asdf
} else if (*(finder) == " ") {
  if (*(finder + 1)) == "*") { /* ... */ } // int *asdf 
}

当然这是伪代码。编译器没有触及代码。

答案 1 :(得分:0)

Libclang是一个很好的工具,可以找到匹配(或不匹配模式)的成员变量,但是有一种更简单的方法来解决代码库中漂亮的打印指针和引用的问题。 #39; s使用clang-format 一种工具来格式化C / C ++ / Java / JavaScript / Objective-C / Protobuf代码

Clang-format有很多options,但可能最感兴趣的是PointerAlignment,它可以有以下值之一:Left,Right或Middle,它适当地重新格式化指针(和引用)。

您可以从其中一个在线工具或内置样式生成clang格式的新配置文件:

clang-format -style=llvm -dump-config > .clang-format

编辑该文件以将PointerAlignment设置为左并运行:

clang-format main.cpp 

在"糟糕的"格式化的代码片段如:

// main.cpp
int main()
{
    int a;
    int* b;
    int *c;
    int& d;
    int &d;
    int * e;
    const int * f;
    const int * const g;
    return 0;
}

我明白了:

// main.cpp
int main() {
  int a;
  int* b;
  int* c;
  int& d;
  int& d;
  int* e;
  const int* f;
  const int* const g;
  return 0;
}

其他设置的结果相似。

如果你确实需要从代码中执行此操作,可以使用libformat,支持clang格式的库,或者你可以使用invoke clang-format from a subprocess,这是其他工具的用法clang代码库就是这样做的。