c++ - 如何在 Clang AST 中的 SourceLocation 之后找到字符的 SourceLocation?

标签 c++ clang abstract-syntax-tree lexer

我正在尝试使用 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/

相关文章:

c++ - 在 rccp int 中保留前导零

llvm - 使用 libclang 作为编译器

c++ - clang 3.0 + libc++ 中的 std::async 不起作用?

java - 使用 Eclipse AST 进行参数使用

compiler-construction - 将抽象语法树转换为字节码

c++ - 为数组赋值时是否存在性能差异

c++ - mysqlpp::Query::store() 上的 MySQL++ malloc_error_break

c++ - 使用 libclang/libtooling

c++ - 多线程和多进程应用程序的锁定机制有什么区别?

c++ - 将 std::function 作为参数传递时出现问题