https://github.com/zyn0217 created https://github.com/llvm/llvm-project/pull/76329
We used to consider the `DeclContext` for selection nodes inside a lambda as the enclosing scope of the lambda expression, rather than the lambda itself. For example, ```cpp void foo(); auto lambda = [] { return ^foo(); }; ``` where `N` is the selection node for the expression `foo()`, `N.getDeclContext()` returns the `TranslationUnitDecl` previously, which IMO is wrong, since the `RecordDecl` of the lambda is closer. Seemingly, this affects nothing currently. >From c0b04507075b39e494d3e6fa39168bc47b92f338 Mon Sep 17 00:00:00 2001 From: Younan Zhang <zyn7...@gmail.com> Date: Sun, 24 Dec 2023 18:08:30 +0800 Subject: [PATCH] [clangd] Handle lambda scopes inside Node::getDeclContext() We used to consider the DeclContext for selection nodes inside a lambda as the scope of the lambda expression locates in. For example, ```cpp void foo(); auto lambda = [] { return ^foo(); }; ``` where N is the selection node for the expression `foo()`, `N.getDeclContext()` returns the TranslationUnitDecl previously, which IMO is wrong, since the RecordDecl of the lambda is closer. --- clang-tools-extra/clangd/Selection.cpp | 3 +++ .../clangd/unittests/SelectionTests.cpp | 13 +++++++++++++ 2 files changed, 16 insertions(+) diff --git a/clang-tools-extra/clangd/Selection.cpp b/clang-tools-extra/clangd/Selection.cpp index 8c6d5750ecefdb..a7413485b04ac3 100644 --- a/clang-tools-extra/clangd/Selection.cpp +++ b/clang-tools-extra/clangd/Selection.cpp @@ -1113,6 +1113,9 @@ const DeclContext &SelectionTree::Node::getDeclContext() const { return *DC; return *Current->getLexicalDeclContext(); } + if (auto *LE = CurrentNode->ASTNode.get<LambdaExpr>()) + if (CurrentNode != this) + return *LE->getLambdaClass(); } 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 index 4c019a1524f3c3..cdb50dfc1c3095 100644 --- a/clang-tools-extra/clangd/unittests/SelectionTests.cpp +++ b/clang-tools-extra/clangd/unittests/SelectionTests.cpp @@ -880,6 +880,19 @@ TEST(SelectionTest, DeclContextIsLexical) { } } +TEST(SelectionTest, DeclContextLambda) { + llvm::Annotations Test(R"cpp( + void foo(); + auto lambda = [] { + return $1^foo(); + }; + )cpp"); + 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()); +} + } // namespace } // namespace clangd } // namespace clang _______________________________________________ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits