getFilename returns 一个空字符串

getFilename returns an empty string

我有一个SourceLocation that I wish to extract its filename from. Apparently, I should be able to do that by using SourceManager's getFilename。但是,当我处理一些头文件时,结果似乎总是一个空字符串。

我查看了源代码,发现问题出在 getFilename 函数中,它显示为:

/// Return the filename of the file containing a SourceLocation.
StringRef getFilename(SourceLocation SpellingLoc) const {
  if (const FileEntry *F = getFileEntryForID(getFileID(SpellingLoc)))
    return F->getName();
  return StringRef();
}

getFileID 的结果在某种意义上是无效的,从某种意义上说,从它构造的 SLocEntry 将具有 isFile returning false。这会导致 getFileEntryForID(在幕后构造 SLocEntry)到 return 一个空指针。

我有一个解决方法,即:

StringRef myGetFilename(SourceLocation SpellingLoc) const {
  std::pair<FileID, unsigned> locInfo = getDecomposedExpansionLoc(SpellingLoc);
  if (const FileEntry *F = srcManager.getFileEntryForID(locInfo.first))
    return F->getName();
  return StringRef();
}

也就是说,首先调用 getDecomposedExpansionLoc 以获得原始 FileID 并在 getFileEntryForID 中使用它。

从实验上看,这似乎运作良好,但这是我第一天使用 clang,所以我不确定它是否真的正确。所以我有两个问题:

  1. 这是 clang 中的错误吗?
  2. 我的解决方法真的正确吗?

谢谢!

啊,所以问题似乎是 getFilename 需要一种特定的 SourceLocation,即 "SpellingLoc"。所以,改变:

srcManager.getFilename(loc)

srcManager.getFilename(srcManager.getSpellingLoc(loc))

将解决问题。