diff --git a/clang-tools-extra/clangd/Selection.cpp b/clang-tools-extra/clangd/Selection.cpp index a53673e074804b..88ab1c5d058eec 100644 --- a/clang-tools-extra/clangd/Selection.cpp +++ b/clang-tools-extra/clangd/Selection.cpp @@ -897,7 +897,7 @@ const DeclContext &SelectionTree::Node::getDeclContext() const { 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/Selection.h b/clang-tools-extra/clangd/Selection.h index 775006f40f6cc6..f80ee83c4b94c8 100644 --- a/clang-tools-extra/clangd/Selection.h +++ b/clang-tools-extra/clangd/Selection.h @@ -128,8 +128,8 @@ class SelectionTree { 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/unittests/SelectionTests.cpp b/clang-tools-extra/clangd/unittests/SelectionTests.cpp index 1c3bc209584867..6c6782a097db5a 100644 --- a/clang-tools-extra/clangd/unittests/SelectionTests.cpp +++ b/clang-tools-extra/clangd/unittests/SelectionTests.cpp @@ -739,6 +739,21 @@ TEST(SelectionTest, CreateAll) { 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