我正在尝试使用 Clang Lexer 库来查找标记的位置(特别是命名空间声明的左大括号)。我的想法(因为 NamespaceDecl 没有它的方法)是在命名空间声明开始后找到第一个左大括号的位置。然而,看着 Lexer API ,在访问 AST 时,我似乎找不到一种简短的方法来执行此操作。有任何建议/替代方案而不必做一些像重新解析代码这样的激烈事情吗?
最佳答案
这是一种找到支架的方法。在我的测试中,它适用于命名和匿名命名空间。
// Assuming ns_decl is pointer to the NamespaceDecl
// sm is reference to the SourceManager
... in addition to the usual headers:
#include "clang/Basic/TokenKinds.h" // for clang::tok
#include "clang/Lex/Lexer.h" // for Lexer
...
clang::LangOptions lopt;
bool skipNewLines = false;
SourceLocation locToUse = ns_decl->isAnonymousNamespace() ?
ns_decl->getLocStart() : ns_decl->getLocation();
SourceLocation next_loc(
clang::Lexer::findLocationAfterToken(
locToUse,clang::tok::l_brace, sm,lopt,skipNewLines));
在这样的声明中
namespace NOPQ {
void f(int){}
}
namespace
ABCD
{
void g(float){}
}
namespace {
void h(int){}
}
next_loc 将对应于第 1 行,NOPQ 的第 18 列;第 7 行,ABCD 的第 7 列;和第 11 行,第 12 列用于匿名 ns。
关于c++ - 如何在 Clang AST 中的 SourceLocation 之后找到字符的 SourceLocation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45046194/