如何使用 Clang AST 查找 VarDecl 类型定义的 SourceLocation?

sru*_*jzs 6 c++ clang abstract-syntax-tree

我试图确定类型是否在文件中定义或包含在另一个文件(系统头或其他文件)中,但我似乎找不到一种简单的方法来查找变量类型的位置。我能得到的最接近的是使用 TypeLoc 的方法,但这些方法仅提供变量声明的位置(很奇怪)。ASTContext 和 SourceManager 类似乎也没有提供太多帮助。关于如何做到这一点有什么想法吗(我确信一定办法)?

sru*_*jzs 2

getAs()这可以通过类型转换或使用方法将Type类转换为引用类型声明的内容来完成。

例如,

// Get Type of variable declaration
const clang::Type* type = var_decl->getTypeSourceInfo()->getTypeLoc().getTypePtr();

// Cast it as its appropriate subtype and then obtain its declaration
// For example, if the type was a record, you can cast it as a 
// RecordType and then obtain its definition.
const clang::RecordType* record_type = type->getAs<clang::RecordType>();
if (record_type != nullptr) {
  const clang::RecordDecl* type_decl = record_type->getDecl();

  clang::SourceLocation end_of_type_decl = type_decl->getLocEnd();
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!