与此解决方案相关的:https://stackoverflow.com/a/56513459/15116235
上述例子是
#define STR_MAX 2049
#define BAR(X) X
int main() {
char inStrDef[STR_MAX];
char inStrFunc[BAR(2049)];
char inStrFuncnested[BAR(BAR(STR_MAX))];
}
解决方案代码是
// clang::VarDecl *VD;
// clang::ASTContext *Context;
auto &SM = Context->getsourceManager();
auto &LO = Context->getLangOpts();
auto DeclarationType = VD->getTypeSourceInfo()->getTypeloc();
if (auto ArrayType = DeclarationType.getas<ConstantArrayTypeloc>()) {
auto *Size = ArrayType.getSizeExpr();
auto CharRange = Lexer::getasCharRange(Size->getsourceRange(),SM,LO);
// Lexer gets text for [start,end) and we want him to grab the end as well
CharRange.setEnd(CharRange.getEnd().getLocWithOffset(1));
auto StringRep = Lexer::getsourceText(CharRange,LO);
llvm::errs() << StringRep << "\n";
}
输出是
STR_MAX
BAR(2049)
BAR(BAR(STR_MAX))
如何获取宏连接的 CharRange?
示例的改编:
#define BAR(X) A##X
int main() {
char inStrFunc[BAR(2049)];
}
预期输出为 2049
目前我得到 BAR
编辑:
我将在 git 版本的 clang 中研究最近的 MacroExpansionRangeRecorder 东西。 见https://github.com/llvm/llvm-project/blob/main/clang/lib/Analysis/MacroExpansionContext.cpp
如果有人对此有经验,我很乐意提供任何相关信息或片段。 现在我会编译..