首页 > 解决方案 > CLang AST 如何获得宏连接的 CharRange?

问题描述

与此解决方案相关: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, SM, 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

如果有人对此有经验,我会很高兴提供任何相关信息或片段。现在我将编译..

标签: clang

解决方案


推荐阅读