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

How do I find the SourceLocation of the type definition of a VarDecl using the Clang AST?

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

这可以通过类型转换或使用 getAs() 方法将 Type class 转换为引用类型声明的对象来实现。

例如,

// 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();
}

希望对您有所帮助!