diff --git a/clang-tools-extra/clangd/index/SymbolCollector.cpp b/clang-tools-extra/clangd/index/SymbolCollector.cpp index 030539707dea..83927bdb6153 100644 --- a/clang-tools-extra/clangd/index/SymbolCollector.cpp +++ b/clang-tools-extra/clangd/index/SymbolCollector.cpp @@ -124,10 +124,15 @@ SymbolLocation GetSymbolLocation(const NamedDecl *D, SourceManager &SM, SourceLocation Loc = SM.getSpellingLoc(D->getLocation()); if (D->getLocation().isMacroID()) { - // The symbol is formed via macro concatenation, the spelling location will - // be "", which is not interesting to us, use the expansion - // location instead. - if (llvm::StringRef(Loc.printToString(SM)).startswith("" + // * symbols controlled and defined by a compile command-line option + // `-DName=foo`, the spelling location will be "". + std::string PrintLoc = Loc.printToString(SM); + if (llvm::StringRef(PrintLoc).startswith("")) { FilePathStorage = makeAbsolutePath( SM, SM.getFilename(SM.getExpansionLoc(D->getLocation())), FallbackDir); diff --git a/clang-tools-extra/unittests/clangd/SymbolCollectorTests.cpp b/clang-tools-extra/unittests/clangd/SymbolCollectorTests.cpp index 2172b4aeaef7..6340686cb5d4 100644 --- a/clang-tools-extra/unittests/clangd/SymbolCollectorTests.cpp +++ b/clang-tools-extra/unittests/clangd/SymbolCollectorTests.cpp @@ -82,7 +82,8 @@ public: class SymbolCollectorTest : public ::testing::Test { public: - bool runSymbolCollector(StringRef HeaderCode, StringRef MainCode) { + bool runSymbolCollector(StringRef HeaderCode, StringRef MainCode, + const std::vector &ExtraArgs = {}) { llvm::IntrusiveRefCntPtr InMemoryFileSystem( new vfs::InMemoryFileSystem); llvm::IntrusiveRefCntPtr Files( @@ -90,8 +91,11 @@ public: auto Factory = llvm::make_unique(CollectorOpts); + std::vector Args = {"symbol_collector", "-fsyntax-only", + "-std=c++11", TestFileName}; + Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end()); tooling::ToolInvocation Invocation( - {"symbol_collector", "-fsyntax-only", "-std=c++11", TestFileName}, + Args, Factory->create(), Files.get(), std::make_shared()); @@ -264,6 +268,24 @@ TEST_F(SymbolCollectorTest, SymbolFormedFromMacroInMainFile) { CPath(TestFileName)))); } +TEST_F(SymbolCollectorTest, SymbolFormedByCLI) { + CollectorOpts.IndexMainFiles = false; + + Annotations Header(R"( + #ifdef NAME + $expansion[[class NAME {}]]; + #endif + )"); + + runSymbolCollector(Header.code(), /*Main=*/"", + /*ExtraArgs=*/{"-DNAME=name"}); + EXPECT_THAT(Symbols, + UnorderedElementsAre( + AllOf(QName("name"), + LocationOffsets(Header.offsetRange("expansion")), + CPath(TestHeaderName)))); +} + TEST_F(SymbolCollectorTest, IgnoreSymbolsInMainFile) { CollectorOpts.IndexMainFiles = false; const std::string Header = R"(