gpt4 book ai didi

c++11 - 如何通过 clang 工具访问解析的 C++11 属性

转载 作者:行者123 更新时间:2023-12-04 19:07:50 24 4
gpt4 key购买 nike

This answer 建议 clang post revision 165082 应该保留 AST 中的所有解析属性。

我首先认为这意味着将保留所有属性,但情况似乎并非如此:

$ clang++ -v
Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn)
Target: x86_64-apple-darwin13.0.0
Thread model: posix

$ cat att.cpp
void f [[noreturn, foo]] () {}

$ clang++ att.cpp -Xclang -ast-dump -fsyntax-only -std=c++11
att.cpp:1:20: warning: unknown attribute 'foo' ignored [-Wattributes]
void f [[noreturn, foo]] () {}
^
att.cpp:1:30: warning: function declared 'noreturn' should not return [-Winvalid-noreturn]
void f [[noreturn, foo]] () {}
^
TranslationUnitDecl 0x102021cd0 <<invalid sloc>>
|-TypedefDecl 0x102022210 <<invalid sloc>> __int128_t '__int128'
|-TypedefDecl 0x102022270 <<invalid sloc>> __uint128_t 'unsigned __int128'
|-TypedefDecl 0x102022630 <<invalid sloc>> __builtin_va_list '__va_list_tag [1]'
`-FunctionDecl 0x1020226d0 <att.cpp:1:1, col:30> f 'void (void)'
|-CompoundStmt 0x1020227b0 <col:29, col:30>
`-CXX11NoReturnAttr 0x102022770 <col:10>
2 warnings generated.

在上面,请注意属性“foo”确实被忽略了,并且不存在于 AST 中,与属性“noreturn”相反。

属性 'foo' 会在某个时候保留在 AST 中,还是所有属性都必须是实际编译器的一部分(在 Attr.td 等中定义,如 Clang Internals Manual 中所述)才能保留在 AST 中?

最佳答案

仅当 Clang 已经知道这些属性时,这些属性才会保留在 AST 中,这些属性是大多数 GCC 属性和 clang 自己定义的属性。但是,您可以(某种程度上)使用来自 this link 的提示添加自己的属性。 .这使您能够定义任何新属性,然后按以下方式在 ast 中处理它:
例如,您从上面的链接中获取了代码行

__attribute__((annotate("async"))) uint c;

然后在您的 RecursiveASTVisitor 实例化中,您可以执行以下操作:
 bool MyRecursiveASTVisitor::VisitVarDecl(VarDecl* v)                                                                                                                                                    
{
v->dump();
if(v->hasAttrs()){
clang::AttrVec vec = v->getAttrs();
printf("%s\n",vec[0]->getSpelling());
printf("%s\n", Lexer::getSourceText(
CharSourceRange::getTokenRange(
vec[0]->getRange()),
compiler.getSourceManager(),
langOpts).str().c_str());
}
return true;
}

第一个 printf 只打印“注释”,因为这是原始属性,为了获得感兴趣的值,我们从词法分析器中获取实际标记作为字符串。

由于我们没有创建新属性,因此我们只能获得 append 属性类型,但我们可以进一步挖掘并区分我们新创建的属性。不像新创建的属性那么优雅(虽然可能需要更改 clang 代码本身)但仍然有效。

关于c++11 - 如何通过 clang 工具访问解析的 C++11 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20180917/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com