Skip to content

Commit fd5e586

Browse files
committed
Check for invalid SLocEntry before getting spelling
1 parent 90c397f commit fd5e586

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

clang-tools-extra/clangd/SourceCode.cpp

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,12 @@ bool isSpelledInSource(SourceLocation Loc, const SourceManager &SM) {
232232
if (Loc.isFileID())
233233
return true;
234234
auto Spelling = SM.getDecomposedSpellingLoc(Loc);
235-
StringRef SpellingFile = SM.getSLocEntry(Spelling.first).getFile().getName();
235+
bool InvalidSLocEntry = false;
236+
const auto SLocEntry = SM.getSLocEntry(Spelling.first, &InvalidSLocEntry);
237+
if (InvalidSLocEntry) {
238+
return false;
239+
}
240+
const StringRef SpellingFile = SLocEntry.getFile().getName();
236241
if (SpellingFile == "<scratch space>")
237242
return false;
238243
if (SpellingFile == "<built-in>")

clang-tools-extra/clangd/unittests/SourceCodeTests.cpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -813,6 +813,21 @@ TEST(SourceCodeTests, isKeywords) {
813813
EXPECT_FALSE(isKeyword("override", LangOpts));
814814
}
815815

816+
TEST(SourceCodeTests, isSpelledInSource) {
817+
Annotations Test(R"cpp(
818+
int abc = 1;
819+
)cpp");
820+
821+
ParsedAST AST = TestTU::withCode(Test.code()).build();
822+
llvm::errs() << Test.code();
823+
const SourceManager &SM = AST.getSourceManager();
824+
825+
EXPECT_TRUE(
826+
isSpelledInSource(SM.getLocForStartOfFile(SM.getMainFileID()), SM));
827+
EXPECT_TRUE(isSpelledInSource(SourceLocation(), SM));
828+
EXPECT_FALSE(isSpelledInSource(SourceLocation::getFromRawEncoding(-1), SM));
829+
}
830+
816831
struct IncrementalTestStep {
817832
llvm::StringRef Src;
818833
llvm::StringRef Contents;

0 commit comments

Comments
 (0)