diff --git a/clang-tools-extra/clangd/Selection.h b/clang-tools-extra/clangd/Selection.h --- a/clang-tools-extra/clangd/Selection.h +++ b/clang-tools-extra/clangd/Selection.h @@ -128,8 +128,8 @@ DynTypedNode ASTNode; // The extent to which this node is covered by the selection. Selection Selected; - // Walk up the AST to get the DeclContext of this Node, - // which is not the node itself. + // Walk up the AST to get the lexical DeclContext of this Node, which is not + // the node itself. const DeclContext &getDeclContext() const; // Printable node kind, like "CXXRecordDecl" or "AutoTypeLoc". std::string kind() const; diff --git a/clang-tools-extra/clangd/Selection.cpp b/clang-tools-extra/clangd/Selection.cpp --- a/clang-tools-extra/clangd/Selection.cpp +++ b/clang-tools-extra/clangd/Selection.cpp @@ -897,7 +897,7 @@ if (CurrentNode != this) if (auto *DC = dyn_cast(Current)) return *DC; - return *Current->getDeclContext(); + return *Current->getLexicalDeclContext(); } } llvm_unreachable("A tree must always be rooted at TranslationUnitDecl."); diff --git a/clang-tools-extra/clangd/unittests/SelectionTests.cpp b/clang-tools-extra/clangd/unittests/SelectionTests.cpp --- a/clang-tools-extra/clangd/unittests/SelectionTests.cpp +++ b/clang-tools-extra/clangd/unittests/SelectionTests.cpp @@ -739,6 +739,21 @@ EXPECT_EQ(1u, Seen) << "one tree for nontrivial selection"; } +TEST(SelectionTest, DeclContextIsLexical) { + llvm::Annotations Test("namespace a { void $1^foo(); } void a::$2^foo();"); + auto AST = TestTU::withCode(Test.code()).build(); + { + auto ST = SelectionTree::createRight(AST.getASTContext(), AST.getTokens(), + Test.point("1"), Test.point("1")); + EXPECT_FALSE(ST.commonAncestor()->getDeclContext().isTranslationUnit()); + } + { + auto ST = SelectionTree::createRight(AST.getASTContext(), AST.getTokens(), + Test.point("2"), Test.point("2")); + EXPECT_TRUE(ST.commonAncestor()->getDeclContext().isTranslationUnit()); + } +} + } // namespace } // namespace clangd } // namespace clang