使用libclang检查通用属性

Tam*_*lei 7 c++ clang abstract-syntax-tree libclang

我想在下面的例子中解析类成员函数的通用属性:

class Foo
{
public:
    void foo [[interesting]] ();
    void bar ();
};
Run Code Online (Sandbox Code Playgroud)

使用libclang C API,我想在源代码中区分foobar(并知道它foo具有interesting属性).这可能吗?我很难找到解释API中使用的概念的示例或文档(我找到了一个参考,但是当没有解释这些概念时,这很难使用).

Tam*_*lei 8

虽然我无法在 AST 中找到通用属性(似乎它们在构建 AST 时或之前被删除,而不是在它之后),但我确实找到了一个解决方法。

annotate以下形式的clang 属性:

__attribute__((annotate("something")))
Run Code Online (Sandbox Code Playgroud)

使用宏,我可以获得合理的语法和在 AST 中可见的注释:

#define INTERESTING __attribute__((annotate("interesting")))

class Foo
{
public:
    INTERESTING void foo();
    void bar();
};
Run Code Online (Sandbox Code Playgroud)

该属性将是方法节点的子节点,其 display_name 是注释字符串。一个可能的 AST 转储:

 <CursorKind.TRANSLATION_UNIT>
  "test.h"
{
  __builtin_va_list <CursorKind.TYPEDEF_DECL>
    "__builtin_va_list"
  type_info <CursorKind.CLASS_DECL>
    "type_info"
  Foo <CursorKind.CLASS_DECL>
    "Foo"
  {
     <CursorKind.CXX_ACCESS_SPEC_DECL>
      ""
    foo <CursorKind.CXX_METHOD>
      "foo()"
    {
       <CursorKind.ANNOTATE_ATTR>
        "interesting"
    }
    bar <CursorKind.CXX_METHOD>
      "bar()"
  }
}
Run Code Online (Sandbox Code Playgroud)

它也产生相同的输出void foo INTERESTING ();