[clang-tools-extra] [clangd] Extract to function: Support extracting a sub-expression (PR #234182)

Christian Kandeler via cfe-commits cfe-commits at lists.llvm.org
Wed Oct 28 04:10:47 PDT 2026


https://github.com/ckandeler updated https://github.com/llvm/llvm-project/pull/234182

>From e8719bdec52bdf7aa3edd3f5e4ecfbb83b6a8ecd Mon Sep 17 00:00:00 2001
From: Christian Kandeler <christian.kandeler at qt.io>
Date: Thu, 15 Oct 2026 16:29:43 +0200
Subject: [PATCH 1/3] [clangd] Extract to function: Support extracting a
 sub-expression

Previously, the tweak only extracted whole statements. This adds a
second extraction path for a single sub-expression embedded in a
larger expression or statement (e.g. just `a < 5` within
`if (a < 5 && c)`).

Reuses the existing statement-extraction machinery almost entirely:
capture/mutation analysis already operates generically on Stmt/Expr
via dyn_cast, and since Expr is-a Stmt, inserting the target Expr into
ExtractionZone::RootStmts (now optionally tagged via a new SingleExpr
field) makes it work unchanged. The genuinely new pieces are: finding
and validating the target expression (adapted from the equivalent
logic in ExtractVariable.cpp); deducing the return
type from the expression's own type instead of an existing return
statement; and wrapping the copied-out body in "return ...;".

Scope, deliberately narrower than ExtractVariable for a first pass:
- Only an expression that maps exactly onto a single AST node is
  supported; ExtractVariable's associative-binary-operator span
  widening (e.g. `a + [[b + c]] + d`) isn't replicated yet.
- Only rvalue-producing expressions: extracting an lvalue (e.g. pulling
  `a[i]` out of `a[i] = 5;`) would need the extracted function to
  return a reference to stay usable as an assignment target, which
  isn't supported yet.
- A bare lambda expression (as opposed to a call to one, which is an
  ordinary call and already supported) is excluded: its closure type
  can't be named for a return type, and a reference capture of an
  unmutated scalar would end up binding to a by-value parameter copy
  instead of the caller's real variable, silently turning a safe
  capture into a dangling one.
- A case label's value, a bit-field's width, an enum constant's,
  constexpr variable's, or constinit variable's initializer, a
  non-type template argument, a static_assert condition, and a
  noexcept-specifier's operand must all be constant expressions; a
  check detects these contexts and, in C++, marks the extracted
  function constexpr to keep the call there well-formed (falling back
  to rejecting the extraction if the return or a parameter type
  somehow isn't a literal type, a precondition for any constexpr
  function). C has no analogous escape hatch (its C23 constexpr
  applies only to object declarations, never functions), so there the
  extraction is rejected outright. Two kinds of slot are deliberately
  left alone: array bounds in declarators (redundant to handle --
  already unreachable here because of an unrelated, pre-existing
  SelectionTree quirk around how array declarators claim their
  tokens), and attribute/builtin-call arguments (each has its own ad
  hoc SelectionTree shape to verify, for constructs rare enough not to
  be worth it yet).

Assisted-by: Claude Code

Closes clangd/clangd#698
---
 .../refactor/tweaks/ExtractFunction.cpp       | 306 +++++++++++++++---
 .../unittests/tweaks/ExtractFunctionTests.cpp | 231 +++++++++++--
 clang-tools-extra/docs/ReleaseNotes.md        |   7 +-
 3 files changed, 467 insertions(+), 77 deletions(-)

diff --git a/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp b/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
index 7b60b95bd61f23..7fbdcbc20f7b82 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
@@ -60,6 +60,7 @@
 #include "refactor/Tweak.h"
 #include "support/Logger.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/Attr.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclBase.h"
 #include "clang/AST/ExprCXX.h"
@@ -158,6 +159,106 @@ bool isConditionClause(const Stmt *Parent, const Stmt *Child) {
   return false;
 }
 
+// Whether N sits in a slot that must be a constant expression: a case
+// label, a bit-field width, an enum constant's initializer, a constexpr or
+// constinit variable's initializer, a non-type template argument, a
+// static_assert condition, or a noexcept-specifier's operand. Extracting
+// out of such a slot is still possible in C++ by marking the extracted
+// function constexpr (see findExpressionExtractionZone), but C has no
+// analogous escape hatch (its C23 constexpr applies only to objects,
+// never functions), so there the context must be rejected outright (this
+// matters for static_assert, which C also has).
+//
+// Deliberately not exhaustive. Known gaps, left alone for concrete
+// reasons rather than just unlisted:
+// - Array bounds in declarators: would be redundant to handle here.
+//   SelectionTree::commonAncestor() never offers the bound expression
+//   as a candidate to begin with, because Selection.cpp's token-claiming
+//   for ArrayTypeLoc claims the whole bracketed span (including the
+//   bound expression's own tokens) for itself, making the TypeLoc --
+//   not an Expr -- the first node commonAncestor() stops its descent
+//   at. Extraction from that slot is already unavailable as a result.
+// - Attribute arguments (e.g. GNU __attribute__((aligned(N)))) and
+//   builtin-call arguments (e.g. __builtin_assume_aligned's alignment):
+//   each has its own ad hoc SelectionTree shape to verify per attribute
+//   or builtin, for constructs rare enough in practice that it isn't
+//   worth the per-case verification cost yet.
+bool isConstantExpressionContext(const Node *N) {
+  // Sema wraps a "manifestly constant evaluated" expression (exactly
+  // these contexts: case labels, bit-field widths, enum initializers,
+  // constexpr variable initializers, and others) in invisible nodes --
+  // at least a ConstantExpr caching its evaluated value, sometimes also
+  // an ImplicitCastExpr -- that aren't the real construct itself and
+  // share N's own source range. outerImplicit() walks up through any
+  // number of those to the real parent.
+  const Node *Parent = N->outerImplicit().Parent;
+  if (!Parent)
+    return false;
+  if (Parent->ASTNode.get<CaseStmt>())
+    return true;
+  if (const auto *Field = Parent->ASTNode.get<FieldDecl>())
+    return Field->isBitField();
+  if (Parent->ASTNode.get<EnumConstantDecl>())
+    return true;
+  if (const auto *Var = Parent->ASTNode.get<VarDecl>())
+    // constinit (unlike constexpr) isn't tracked as a VarDecl bit; it's
+    // just an attribute, but requires a constant initializer all the same.
+    return Var->isConstexpr() || Var->hasAttr<ConstInitAttr>();
+  // A TemplateSpecializationTypeLoc's Expr children (as opposed to TypeLoc
+  // children) are exactly its non-type template arguments -- the
+  // SelectionTree has no separate node for the intervening
+  // TemplateArgumentLoc. Other ways to name a non-type template argument
+  // (a bare function-template call's explicit arguments, a variable
+  // template) aren't verified and so aren't covered here yet.
+  if (Parent->ASTNode.get<TemplateSpecializationTypeLoc>())
+    return true;
+  if (Parent->ASTNode.get<StaticAssertDecl>())
+    return true;
+  // A FunctionProtoTypeLoc's only Expr child is its noexcept-specifier's
+  // operand (verified empirically that a parameter's default argument,
+  // the other candidate Expr near a function's type, instead has that
+  // ParmVarDecl itself as its parent, not the enclosing
+  // FunctionProtoTypeLoc).
+  if (Parent->ASTNode.get<FunctionProtoTypeLoc>())
+    return true;
+  return false;
+}
+
+// Whether E is eligible for extraction to a function. Callers must already
+// know E is a single, fully-selected expression that isn't itself (part
+// of) a root statement -- checked separately, by trying statement
+// extraction first.
+bool eligibleForExpressionExtraction(const Expr *E) {
+  // findEnclosingFunction already rejects a templated enclosing function,
+  // but guard directly too: there's no reasonable deduced return type for
+  // an expression whose own type still depends on a template parameter.
+  if (E->isTypeDependent() || E->isValueDependent())
+    return false;
+
+  // Nothing to return.
+  if (E->getType()->isVoidType())
+    return false;
+
+  // An lvalue would need the extracted function to return a reference to
+  // stay usable the same way it was (e.g. as an assignment target).
+  // FIXME: support lvalue-returning extraction.
+  if (E->isLValue())
+    return false;
+
+  // A plain reference to a name (e.g. a variable, or an enum constant,
+  // which -- unlike a variable -- is a prvalue and so isn't otherwise
+  // excluded above) isn't interesting to extract on its own.
+  if (isa<DeclRefExpr>(E))
+    return false;
+
+  // Extracting from a bare lambda expression would involve non-trivial effort
+  // and be of questionable value.
+  if (isa<LambdaExpr>(E))
+    return false;
+
+  return true;
+}
+
 // A RootStmt is a statement that's fully selected including all its children
 // and its parent is unselected.
 // Check if a node is a root statement.
@@ -260,6 +361,17 @@ struct ExtractionZone {
   SourceRange EnclosingFuncRange;
   // Set of statements that form the ExtractionZone.
   llvm::DenseSet<const Stmt *> RootStmts;
+  // Set (instead of Parent/RootStmts above) when this zone is a single
+  // sub-expression being extracted, rather than one or more whole
+  // statements -- see findExpressionExtractionZone. Still also present in
+  // RootStmts (Expr is-a Stmt), so the capture/mutation-analysis visitor
+  // needs no changes to handle this case.
+  const Expr *SingleExpr = nullptr;
+  // Only meaningful when SingleExpr is set: whether SingleExpr sits in a
+  // slot that requires a constant expression (see
+  // isConstantExpressionContext), so the extracted function must be
+  // declared constexpr to keep the call there well-formed.
+  bool RequiresConstexpr = false;
 
   SourceLocation getInsertionPoint() const {
     return EnclosingFuncRange.getBegin();
@@ -268,6 +380,16 @@ struct ExtractionZone {
   // The last root statement is important to decide where we need to insert a
   // semicolon after the extraction.
   const Node *getLastRootStmt() const { return Parent->Children.back(); }
+  // The Stmt (in the generalized sense that Expr is-a Stmt) to use for
+  // ExtractionSemicolonPolicy::compute() purposes: the extracted Expr
+  // itself for an expression zone (compute() already special-cases a bare
+  // Expr to mean "needed in the extracted function, not in the original",
+  // exactly matching inline call-site substitution), or the last root
+  // statement otherwise.
+  const Stmt *getRepresentativeStmt() const {
+    return SingleExpr ? static_cast<const Stmt *>(SingleExpr)
+                      : getLastRootStmt()->ASTNode.get<Stmt>();
+  }
 
   // Checks if declarations inside extraction zone are accessed afterwards.
   //
@@ -320,7 +442,7 @@ struct ExtractionZone {
 // This is a very naive check (does it end with a return stmt).
 // Doing some rudimentary control flow analysis would cover more cases.
 bool alwaysReturns(const ExtractionZone &EZ) {
-  const Stmt *Last = EZ.getLastRootStmt()->ASTNode.get<Stmt>();
+  const Stmt *Last = EZ.getRepresentativeStmt();
   // Unwrap enclosing (unconditional) compound statement.
   while (const auto *CS = llvm::dyn_cast<CompoundStmt>(Last)) {
     if (CS->body_empty())
@@ -468,8 +590,10 @@ llvm::SmallVector<const Expr *, 4> relevantCallOperands(const CallExpr *Call) {
   return Operands;
 }
 
-// Whether extracting S on its own, as a single root statement, would add
-// no real abstraction over leaving it where it is:
+// Whether extracting S on its own -- a single root statement, or (since
+// Expr is-a Stmt) a bare sub-expression being extracted on its own, e.g.
+// the `func()` in `int A = [[func()]];` -- would add no real abstraction
+// over leaving it where it is:
 // - A value-less `return;` has nothing to abstract over at all.
 // - A call (to a function, method, or operator), or a return of one, is
 //   a pure 1:1 forwarding wrapper if every relevant operand (see
@@ -540,9 +664,9 @@ bool validSingleChild(const Node *Child, const FunctionDecl *EnclosingFunc,
   return true;
 }
 
-std::optional<ExtractionZone> findExtractionZone(const Node *CommonAnc,
-                                                 const SourceManager &SM,
-                                                 const LangOptions &LangOpts) {
+std::optional<ExtractionZone>
+findStatementExtractionZone(const Node *CommonAnc, const SourceManager &SM,
+                            const LangOptions &LangOpts) {
   ExtractionZone ExtZone;
   ExtZone.Parent = getParentOfRootStmts(CommonAnc);
   if (!ExtZone.Parent || ExtZone.Parent->Children.empty())
@@ -570,6 +694,66 @@ std::optional<ExtractionZone> findExtractionZone(const Node *CommonAnc,
   return ExtZone;
 }
 
+// Like findStatementExtractionZone, but for a single sub-expression
+// embedded within a larger expression or statement (e.g. just `a < 5`
+// within `if (a < 5 && c)`), rather than one or more whole statements.
+// Only reached when statement extraction has already failed, since a
+// selection that resolves to a genuine root statement should always be
+// offered as that instead.
+std::optional<ExtractionZone>
+findExpressionExtractionZone(const Node *CommonAnc, const SourceManager &SM,
+                             const LangOptions &LangOpts) {
+  if (!CommonAnc)
+    return std::nullopt;
+  // Invisible wrapper nodes (e.g. an LValueToRValue ImplicitCastExpr) own
+  // no selected characters of their own, so the common ancestor can land
+  // on one of these instead of the expression the user actually selected.
+  const Node &Target = CommonAnc->ignoreImplicit();
+  if (Target.Selected != SelectionTree::Complete)
+    return std::nullopt;
+  const Expr *E = Target.ASTNode.get<Expr>();
+  if (!E || !eligibleForExpressionExtraction(E))
+    return std::nullopt;
+  // E itself (not wrapped in a ReturnStmt) is exactly the "Stmt" a
+  // bare-expression extraction replaces, so the same pure-forwarding
+  // check applies directly: `int A = [[func()]];` becoming
+  // `int A = extracted();` is just as much a rename as a whole
+  // statement's `func();` becoming `extracted();`.
+  if (isTrivialExtraction(E, SM))
+    return std::nullopt;
+  bool RequiresConstexpr = isConstantExpressionContext(&Target);
+  // C has no constexpr-function escape hatch for this (see
+  // isConstantExpressionContext), so there's no way to make the
+  // extraction compile.
+  if (RequiresConstexpr && !LangOpts.CPlusPlus)
+    return std::nullopt;
+
+  ExtractionZone ExtZone;
+  ExtZone.SingleExpr = E;
+  ExtZone.RequiresConstexpr = RequiresConstexpr;
+  ExtZone.EnclosingFunction = findEnclosingFunction(&Target);
+  if (!ExtZone.EnclosingFunction)
+    return std::nullopt;
+  if (auto FuncRange =
+          computeEnclosingFuncRange(ExtZone.EnclosingFunction, SM, LangOpts))
+    ExtZone.EnclosingFuncRange = *FuncRange;
+  if (auto ZoneRange = toHalfOpenFileRange(SM, LangOpts, E->getSourceRange()))
+    ExtZone.ZoneRange = *ZoneRange;
+  if (ExtZone.EnclosingFuncRange.isInvalid() || ExtZone.ZoneRange.isInvalid())
+    return std::nullopt;
+
+  ExtZone.RootStmts.insert(E);
+  return ExtZone;
+}
+
+std::optional<ExtractionZone> findExtractionZone(const Node *CommonAnc,
+                                                 const SourceManager &SM,
+                                                 const LangOptions &LangOpts) {
+  if (auto StmtZone = findStatementExtractionZone(CommonAnc, SM, LangOpts))
+    return StmtZone;
+  return findExpressionExtractionZone(CommonAnc, SM, LangOpts);
+}
+
 // Stores information about the extracted function and provides methods for
 // rendering it.
 struct NewFunction {
@@ -595,6 +779,13 @@ struct NewFunction {
   const DeclContext *SyntacticDC = nullptr;
   const DeclContext *ForwardDeclarationSyntacticDC = nullptr;
   bool CallerReturnsValue = false;
+  // Set for a single-expression extraction (see
+  // findExpressionExtractionZone): the copied-out body is the bare
+  // expression's own source text, which getFuncBody() must still prefix
+  // with "return " -- unlike CallerReturnsValue's `return` prefix, this
+  // is unconditional and belongs to the function's own body, not to how
+  // the call site uses the result.
+  bool IsExpressionExtraction = false;
   bool Static = false;
   ConstexprSpecKind Constexpr = ConstexprSpecKind::Unspecified;
   bool Const = false;
@@ -747,38 +938,40 @@ NewFunction::getFuncBody(const SourceManager &SM) const {
   // - add return statement
   // - Add semicolon
   std::string Body = toSourceCode(SM, BodyRange).str();
-  if (PointerRewriteSites.empty())
-    return Body + (SemicolonPolicy.isNeededInExtractedFunction() ? ";" : "");
-
-  // Splice in each site's rewrite. These are all independent
-  // insertions/single-token replacements at distinct, non-overlapping
-  // source locations (two DeclRefExprs can't share a location, and a dot
-  // always follows its own identifier), so none of this should actually
-  // be able to fail -- but if that assumption is ever wrong, surface it
-  // as an extraction failure instead of silently emitting broken code.
-  tooling::Replacements Repls;
-  unsigned BodyBeginOffset = SM.getFileOffset(BodyRange.getBegin());
-  for (const auto &Site : PointerRewriteSites) {
-    unsigned SiteOffset = SM.getFileOffset(Site.Loc) - BodyBeginOffset;
-    if (Site.DotLoc) {
-      // Leave the identifier itself untouched; turn the member access
-      // that follows it into "->" instead of wrapping in a dereference.
-      unsigned DotOffset = SM.getFileOffset(*Site.DotLoc) - BodyBeginOffset;
-      if (auto Err = Repls.add(tooling::Replacement("", DotOffset, 1, "->")))
-        return std::move(Err);
-    } else {
-      if (auto Err = Repls.add(tooling::Replacement("", SiteOffset, 0, "(*")))
-        return std::move(Err);
-      if (auto Err = Repls.add(
-              tooling::Replacement("", SiteOffset + Site.NameLength, 0, ")")))
-        return std::move(Err);
+  if (!PointerRewriteSites.empty()) {
+    // Splice in each site's rewrite. These are all independent
+    // insertions/single-token replacements at distinct, non-overlapping
+    // source locations (two DeclRefExprs can't share a location, and a dot
+    // always follows its own identifier), so none of this should actually
+    // be able to fail -- but if that assumption is ever wrong, surface it
+    // as an extraction failure instead of silently emitting broken code.
+    tooling::Replacements Repls;
+    unsigned BodyBeginOffset = SM.getFileOffset(BodyRange.getBegin());
+    for (const auto &Site : PointerRewriteSites) {
+      unsigned SiteOffset = SM.getFileOffset(Site.Loc) - BodyBeginOffset;
+      if (Site.DotLoc) {
+        // Leave the identifier itself untouched; turn the member access
+        // that follows it into "->" instead of wrapping in a dereference.
+        unsigned DotOffset = SM.getFileOffset(*Site.DotLoc) - BodyBeginOffset;
+        if (auto Err = Repls.add(tooling::Replacement("", DotOffset, 1, "->")))
+          return std::move(Err);
+      } else {
+        if (auto Err = Repls.add(tooling::Replacement("", SiteOffset, 0, "(*")))
+          return std::move(Err);
+        if (auto Err = Repls.add(
+                tooling::Replacement("", SiteOffset + Site.NameLength, 0, ")")))
+          return std::move(Err);
+      }
     }
+    llvm::Expected<std::string> NewBody =
+        tooling::applyAllReplacements(Body, Repls);
+    if (!NewBody)
+      return NewBody.takeError();
+    Body = std::move(*NewBody);
   }
-  llvm::Expected<std::string> NewBody =
-      tooling::applyAllReplacements(Body, Repls);
-  if (!NewBody)
-    return NewBody.takeError();
-  return *NewBody + (SemicolonPolicy.isNeededInExtractedFunction() ? ";" : "");
+  if (IsExpressionExtraction)
+    Body = "return " + Body;
+  return Body + (SemicolonPolicy.isNeededInExtractedFunction() ? ";" : "");
 }
 
 std::string NewFunction::Parameter::render(const DeclContext &Context) const {
@@ -1435,8 +1628,7 @@ getSemicolonPolicy(ExtractionZone &ExtZone, const SourceManager &SM,
   SourceRange FuncBodyRange = {ExtZone.ZoneRange.getBegin(),
                                ExtZone.ZoneRange.getEnd().getLocWithOffset(-1)};
   auto SemicolonPolicy = tooling::ExtractionSemicolonPolicy::compute(
-      ExtZone.getLastRootStmt()->ASTNode.get<Stmt>(), FuncBodyRange, SM,
-      LangOpts);
+      ExtZone.getRepresentativeStmt(), FuncBodyRange, SM, LangOpts);
   // Update ZoneRange.
   ExtZone.ZoneRange.setEnd(FuncBodyRange.getEnd().getLocWithOffset(1));
   return SemicolonPolicy;
@@ -1523,12 +1715,42 @@ llvm::Expected<NewFunction> getExtractedFunction(ExtractionZone &ExtZone,
   ExtractedFunc.BodyRange = ExtZone.ZoneRange;
   ExtractedFunc.DefinitionPoint = ExtZone.getInsertionPoint();
 
-  ExtractedFunc.CallerReturnsValue = CapturedInfo.AlwaysReturns;
+  if (ExtZone.SingleExpr) {
+    // The extracted function's body is just "return <expr>;" (see
+    // NewFunction::getFuncBody), and the call site substitutes the call
+    // in place of the expression itself -- not as `return extracted();`,
+    // which is what CallerReturnsValue would otherwise render.
+    ExtractedFunc.IsExpressionExtraction = true;
+    ExtractedFunc.CallerReturnsValue = false;
+    ExtractedFunc.ReturnType = ExtZone.SingleExpr->getType();
+  } else {
+    ExtractedFunc.CallerReturnsValue = CapturedInfo.AlwaysReturns;
+    if (!generateReturnProperties(ExtractedFunc, *ExtZone.EnclosingFunction,
+                                  CapturedInfo))
+      return error("Too complex to extract.");
+  }
   if (!createParameters(ExtractedFunc, CapturedInfo,
-                        ExtZone.EnclosingFunction->getASTContext(), LangOpts) ||
-      !generateReturnProperties(ExtractedFunc, *ExtZone.EnclosingFunction,
-                                CapturedInfo))
+                        ExtZone.EnclosingFunction->getASTContext(), LangOpts))
     return error("Too complex to extract.");
+
+  if (ExtZone.RequiresConstexpr) {
+    // Declaring a constexpr function at all requires every parameter and
+    // the return type to be a literal type. Expected to hold in practice
+    // here -- every type this tweak ever generates is either a scalar or
+    // a reference, and both are unconditionally literal types regardless
+    // of what a reference refers to -- but check rather than emit
+    // uncompilable code if some future change (e.g. by-value class-type
+    // parameters) breaks that invariant.
+    const ASTContext &Ctx = ExtZone.EnclosingFunction->getASTContext();
+    bool AllLiteral = ExtractedFunc.ReturnType->isLiteralType(Ctx);
+    for (const auto &P : ExtractedFunc.Parameters)
+      AllLiteral = AllLiteral && P.TypeInfo->isLiteralType(Ctx);
+    if (!AllLiteral)
+      return error("Too complex to extract.");
+    if (ExtractedFunc.Constexpr == ConstexprSpecKind::Unspecified)
+      ExtractedFunc.Constexpr = ConstexprSpecKind::Constexpr;
+  }
+
   return ExtractedFunc;
 }
 
diff --git a/clang-tools-extra/clangd/unittests/tweaks/ExtractFunctionTests.cpp b/clang-tools-extra/clangd/unittests/tweaks/ExtractFunctionTests.cpp
index 981373b8933474..376883b6ea171b 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/ExtractFunctionTests.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/ExtractFunctionTests.cpp
@@ -663,19 +663,24 @@ TEST_F(ExtractFunctionTest, SingleStatement) {
     })cpp"),
               HasSubstr("extracted"));
   // Selecting a subexpression of an operator call (rather than the whole
-  // statement) must not be extracted: it is not a standalone statement, and
-  // "extracting" it would replace only part of the expression.
-  EXPECT_EQ(apply(R"cpp(
+  // statement) isn't a standalone statement, so it's not handled by
+  // statement extraction -- but it's exactly what expression extraction
+  // is for: the call substitutes in place of the "3" alone, leaving the
+  // rest of the expression (the "stream <<" part) untouched.
+  EXPECT_THAT(apply(R"cpp(
     struct Stream {};
     Stream &operator<<(Stream &, int);
     Stream stream;
     void test() {
       stream << [[3]];
     })cpp"),
-            "unavailable");
+              HasSubstr("stream << extracted();"));
   // Same as above, but the selected subexpression is itself an
   // (Unselected-but-fully-covered) CXXOperatorCallExpr nested as an argument
-  // of an outer call, rather than a Complete leaf expression.
+  // of an outer call, rather than a Complete leaf expression. Unlike the
+  // "3" case above, `stream << 3` returns `Stream &` -- an lvalue -- so
+  // this one is still rejected (expression extraction doesn't support
+  // lvalue-returning extraction yet).
   EXPECT_EQ(apply(R"cpp(
     struct Stream {};
     Stream &operator<<(Stream &, int);
@@ -689,22 +694,31 @@ TEST_F(ExtractFunctionTest, SingleStatement) {
 
 TEST_F(ExtractFunctionTest, ControlFlowConditions) {
   Context = File;
-  // The condition of an `if` is not a discardable statement -- its value is
-  // consumed by the `if` itself.
-  EXPECT_EQ(apply(R"cpp(
+  // The condition of an `if` is not a discardable statement -- its value
+  // is consumed by the `if` itself -- so this isn't handled by statement
+  // extraction. It's squarely what expression extraction is for, though
+  // (this is clangd/clangd#698's own motivating example): the call
+  // substitutes in place of the condition, which still works exactly the
+  // same way.
+  EXPECT_THAT(apply(R"cpp(
     int example(int event1, bool event2, double event3) {
       if ([[event1 == 2 && event2 && event3 == 10.3]])
         return 1;
       return 0;
     })cpp"),
-            "unavailable");
+              HasSubstr("if (extracted(event1, event2, event3))"));
   // Same, but for other control-flow constructs' conditions.
-  EXPECT_EQ(apply("void f(int x) { while ([[x > 0]]) --x; }"), "unavailable");
-  EXPECT_EQ(apply("void f(int x) { do {} while ([[x > 0]]); }"), "unavailable");
-  EXPECT_EQ(apply("void f(int x) { for (; [[x > 0]];) ; }"), "unavailable");
-  EXPECT_EQ(apply("void f(int x) { switch ([[x + 1]]) {} }"), "unavailable");
-  // A condition-variable declaration (`if (T x = ...)`) is likewise not a
-  // discardable statement: its truthiness *is* the condition.
+  EXPECT_THAT(apply("void f(int x) { while ([[x > 0]]) --x; }"),
+              HasSubstr("while (extracted(x)) --x;"));
+  EXPECT_THAT(apply("void f(int x) { do {} while ([[x > 0]]); }"),
+              HasSubstr("do {} while (extracted(x));"));
+  EXPECT_THAT(apply("void f(int x) { for (; [[x > 0]];) ; }"),
+              HasSubstr("for (; extracted(x);) ;"));
+  EXPECT_THAT(apply("void f(int x) { switch ([[x + 1]]) {} }"),
+              HasSubstr("switch (extracted(x)) {}"));
+  // A condition-variable declaration (`if (T x = ...)`) is different: the
+  // selection there is a declaration, not an expression, so there's no
+  // single Expr node for expression extraction to find either.
   EXPECT_EQ(apply("bool cond(); void f() { if ([[bool b = cond()]]) ; }"),
             "unavailable");
   // Unlike the condition, a loop's initializer and increment clauses have
@@ -751,24 +765,25 @@ TEST_F(ExtractFunctionTest, RangeBasedFor) {
 
 TEST_F(ExtractFunctionTest, VarDeclInitializer) {
   Context = File;
-  // The initializer of a variable declaration is not a discardable
-  // statement either: its value is required to initialize the variable, so
-  // replacing it with a call to a void-returning extracted function would
-  // not compile. Ascending from the initializer lands on the VarDecl itself (a
-  // Decl, not a Stmt or Expr), which the general "is this a genuine statement"
-  // check must also reject.
-  EXPECT_EQ(apply(R"cpp(
-    int func();
-    void f() { auto A = [[func()]]; }
+  // The initializer of a variable declaration isn't a discardable
+  // statement -- its value is required to initialize the variable -- but
+  // that's no obstacle to expression extraction: substituting the call
+  // in place of the initializer still produces a value, same as before.
+  // (func(1), not func(): a bare zero-argument call would be a pure
+  // forwarding wrapper, suppressed regardless of this test's own
+  // concern -- see RejectPureForwarding* below for that check's own
+  // coverage, including this exact VarDecl-initializer context.)
+  EXPECT_THAT(apply(R"cpp(
+    int func(int);
+    void f() { auto A = [[func(1)]]; }
   )cpp"),
-            "unavailable");
-  // Same without `auto`: the type doesn't matter, only that a value is
-  // required.
-  EXPECT_EQ(apply(R"cpp(
-    int func();
-    void f() { int A = [[func()]]; }
+              HasSubstr("void f() { auto A = extracted(); }"));
+  // Same without `auto`: the type doesn't matter.
+  EXPECT_THAT(apply(R"cpp(
+    int func(int);
+    void f() { int A = [[func(1)]]; }
   )cpp"),
-            "unavailable");
+              HasSubstr("void f() { int A = extracted(); }"));
   // Sanity check: extracting the whole declaration statement (as opposed to
   // just its initializer) is unaffected.
   EXPECT_THAT(apply(R"cpp(
@@ -778,6 +793,19 @@ TEST_F(ExtractFunctionTest, VarDeclInitializer) {
               HasSubstr("extracted"));
 }
 
+TEST_F(ExtractFunctionTest, RejectPureForwardingVarDeclInitializer) {
+  Context = File;
+  // The forwarding-wrapper check applies to a bare expression extraction
+  // (Expr is-a Stmt) exactly as it does to a whole statement: `int A =
+  // func();` becoming `int A = extracted();` is just as much a pure
+  // rename.
+  EXPECT_EQ(apply(R"cpp(
+    int func();
+    void f() { auto A = [[func()]]; }
+  )cpp"),
+            "unavailable");
+}
+
 TEST_F(ExtractFunctionTest, ConstParameters) {
   Context = File;
   // A captured scalar that's only read becomes a by-value parameter;
@@ -1618,6 +1646,147 @@ TEST_F(ExtractFunctionTest, RejectPureForwardingStructuredBinding) {
             "unavailable");
 }
 
+TEST_F(ExtractFunctionTest, ExpressionExtractionFromCondition) {
+  // The original motivating case (clangd/clangd#698): extracting a
+  // sub-expression embedded inside a larger condition, not a whole
+  // statement.
+  Context = File;
+  EXPECT_THAT(apply("void f(int a) { if ([[a < 5]] && true) {} }"),
+              AllOf(HasSubstr("bool extracted(int a) {\nreturn a < 5;\n}"),
+                    HasSubstr("if (extracted(a) && true)")));
+}
+
+TEST_F(ExtractFunctionTest, ExpressionExtractionAssignmentRHS) {
+  // Unlike Extract Variable, extracting an assignment's RHS is useful
+  // here: the result isn't redundant, unlike `auto v = RHS; x = v;`.
+  Context = File;
+  EXPECT_THAT(apply("void f(int a, int b) { int x; x = [[a + b]]; }"),
+              HasSubstr("x = extracted(a, b);"));
+}
+
+TEST_F(ExtractFunctionTest, ExpressionExtractionRejectVoid) {
+  Context = File;
+  EXPECT_THAT(apply("void g(); void f() { (void)([[g()]]); }"),
+              StartsWith("unavailable"));
+}
+
+TEST_F(ExtractFunctionTest, ExpressionExtractionRejectLValue) {
+  // A bare variable reference is an lvalue; extracting it would need the
+  // extracted function to return a reference to stay usable as e.g. an
+  // assignment target. Not yet supported.
+  Context = File;
+  EXPECT_THAT(apply("void f(int a) { [[a]] = 5; }"), StartsWith("unavailable"));
+}
+
+TEST_F(ExtractFunctionTest, ExpressionExtractionConstexprCaseLabel) {
+  // A case label's value must be a constant expression. Rather than reject
+  // the extraction outright, mark the extracted function constexpr so the
+  // call there is still well-formed.
+  Context = File;
+  EXPECT_THAT(apply(R"cpp(
+    int f(int x) {
+      switch (x) {
+        case [[1 + 1]]:
+          return 0;
+      }
+      return 1;
+    })cpp"),
+              AllOf(HasSubstr("constexpr int extracted() {\nreturn 1 + 1;\n}"),
+                    HasSubstr("case extracted():")));
+}
+
+TEST_F(ExtractFunctionTest, ExpressionExtractionConstexprBitFieldWidth) {
+  Context = File;
+  EXPECT_THAT(apply(R"cpp(
+    void f() {
+      struct S {
+        int a : [[1 + 1]];
+      };
+    })cpp"),
+              AllOf(HasSubstr("constexpr int extracted() {\nreturn 1 + 1;\n}"),
+                    HasSubstr("int a : extracted();")));
+}
+
+TEST_F(ExtractFunctionTest, ExpressionExtractionConstexprEnumConstant) {
+  Context = File;
+  EXPECT_THAT(apply(R"cpp(
+    void f() {
+      enum E { A = [[1 + 1]] };
+    })cpp"),
+              AllOf(HasSubstr("constexpr int extracted() {\nreturn 1 + 1;\n}"),
+                    HasSubstr("A = extracted()")));
+}
+
+TEST_F(ExtractFunctionTest, ExpressionExtractionConstexprVarInitializer) {
+  Context = File;
+  EXPECT_THAT(apply("void f() { constexpr int x = [[1 + 1]]; }"),
+              AllOf(HasSubstr("constexpr int extracted() {\nreturn 1 + 1;\n}"),
+                    HasSubstr("constexpr int x = extracted();")));
+}
+
+TEST_F(ExtractFunctionTest, CFileRejectConstantExpressionContext) {
+  // C has no constexpr-function escape hatch (its C23 constexpr applies
+  // only to objects, never functions), so a constant-expression-required
+  // context is still rejected outright there.
+  FileName = "a.c";
+  Context = File;
+  EXPECT_THAT(apply(R"cpp(
+    int f(int x) {
+      switch (x) {
+        case [[1 + 1]]:
+          return 0;
+      }
+      return 1;
+    })cpp"),
+              StartsWith("unavailable"));
+}
+
+TEST_F(ExtractFunctionTest, ExpressionExtractionConstexprTemplateArgument) {
+  Context = File;
+  EXPECT_THAT(apply(R"cpp(
+    template <int N> struct Array { int data[N]; };
+    void f() { Array<[[1 + 2]]> a; })cpp"),
+              AllOf(HasSubstr("constexpr int extracted() {\nreturn 1 + 2;\n}"),
+                    HasSubstr("Array<extracted()> a;")));
+}
+
+TEST_F(ExtractFunctionTest, ExpressionExtractionConstexprConstinitVar) {
+  // constinit (unlike constexpr) isn't a VarDecl bit, just an attribute,
+  // but it requires a constant initializer all the same.
+  ExtraArgs.push_back("-std=c++20");
+  Context = File;
+  EXPECT_THAT(apply("void f() { static constinit int x = [[1 + 1]]; }"),
+              AllOf(HasSubstr("constexpr int extracted() {\nreturn 1 + 1;\n}"),
+                    HasSubstr("static constinit int x = extracted();")));
+}
+
+TEST_F(ExtractFunctionTest, ExpressionExtractionConstexprStaticAssert) {
+  Context = File;
+  EXPECT_THAT(
+      apply("void f() { static_assert([[1 + 1 == 2]], \"\"); }"),
+      AllOf(HasSubstr("constexpr bool extracted() {\nreturn 1 + 1 == 2;\n}"),
+            HasSubstr("static_assert(extracted(), \"\");")));
+}
+
+TEST_F(ExtractFunctionTest, ExpressionExtractionConstexprNoexcept) {
+  Context = File;
+  EXPECT_THAT(
+      apply("void f() noexcept([[1 + 1 == 2]]) {}"),
+      AllOf(HasSubstr("constexpr bool extracted() {\nreturn 1 + 1 == 2;\n}"),
+            HasSubstr("void f() noexcept(extracted()) {}")));
+}
+
+TEST_F(ExtractFunctionTest, ExpressionExtractionDefaultArgNotConstexpr) {
+  // A parameter's default argument, unlike the function's own
+  // noexcept-specifier, isn't required to be a constant expression --
+  // it's evaluated at each call site -- so no constexpr marking is
+  // needed (or wanted) here.
+  Context = File;
+  EXPECT_THAT(apply("void f(int x = [[1 + 1]]) {}"),
+              AllOf(HasSubstr("int extracted() {\nreturn 1 + 1;\n}"),
+                    Not(HasSubstr("constexpr"))));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
diff --git a/clang-tools-extra/docs/ReleaseNotes.md b/clang-tools-extra/docs/ReleaseNotes.md
index 361d14ec2242c2..b51c9c587fd386 100644
--- a/clang-tools-extra/docs/ReleaseNotes.md
+++ b/clang-tools-extra/docs/ReleaseNotes.md
@@ -92,10 +92,9 @@ infrastructure are described first, followed by tool-specific sections.
 
 - clangd now applies clang-tidy fix-it post-processing before exposing fixes.
 
-- The `Extract to function` tweak is now offered for selections consisting of
-  a single expression-statement (e.g. a lone function call or an overloaded
-  operator call such as `stream << 42;`), which it previously refused to
-  extract.
+- The `Extract to function` tweak is now offered for a single sub-expression
+  embedded in a larger expression or statement, e.g. just the `a < 5` in
+  `if (a < 5 && c)`, not just a selection spanning an entire statement.
 
 - The `Extract to function` tweak is now also available in C files, where
   it previously always refused to apply. Captured variables are passed by

>From a2050fa775a8244588a6223d9aecb0f72fed39b0 Mon Sep 17 00:00:00 2001
From: Christian Kandeler <christian.kandeler at qt.io>
Date: Tue, 27 Oct 2026 17:48:51 +0100
Subject: [PATCH 2/3] [clangd] Extract to function: Fix
 constant-expression-context detection

isConstantExpressionContext only looked at the selected node's immediate
parent, so a sub-expression nested inside a larger expression that itself
sits in a constant-expression-required context (e.g. the `1 + 1` in
`case (1 + 1) + 1:`) was missed, silently omitting the `constexpr` the
extracted function needs. Walk up through ordinary enclosing expressions
(operators, casts, member access, calls, etc.) instead of stopping at the
first one.

Also: recognize `if constexpr`'s condition as such a context; require
C++11 rather than just C++, since constexpr functions don't exist in
C++98/03 either; and reject array-typed expressions, since a function
can't return an array type (reachable via a prvalue struct's array
member, an xvalue since C++11).

Assisted-by: Claude Code
---
 .../refactor/tweaks/ExtractFunction.cpp       | 125 ++++++++++++------
 .../unittests/tweaks/ExtractFunctionTests.cpp |  70 ++++++++++
 2 files changed, 158 insertions(+), 37 deletions(-)

diff --git a/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp b/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
index 7fbdcbc20f7b82..f00a9d1e272f7c 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
@@ -123,10 +123,11 @@ bool isUnselectedRootStmtCandidate(const Node *N) {
 }
 
 // Whether Child is the condition (or condition-variable declaration) of a
-// control-flow Parent, or the range-expression of a range-based for. These
-// are the only slots whose *value* is actually consumed by the construct
-// itself -- to decide whether to keep looping/branching, or to build the
-// hidden begin/end iterators -- so replacing them with a call to a
+// control-flow Parent, the range-expression of a range-based for, or the
+// operand of a return. These are the only slots whose *value* is actually
+// consumed by the construct itself -- to decide whether to keep
+// looping/branching, to build the hidden begin/end iterators, or to be
+// returned to the caller -- so replacing them with a call to a
 // void-returning extracted function would not compile. Other slots, like a
 // loop's init-statement or increment expression, have their value discarded
 // just like an ordinary expression-statement (and any hazard from
@@ -156,6 +157,8 @@ bool isConditionClause(const Stmt *Parent, const Stmt *Child) {
            Child == Switch->getConditionVariableDeclStmt();
   if (const auto *ForRange = llvm::dyn_cast<CXXForRangeStmt>(Parent))
     return Child == ForRange->getRangeInit();
+  if (const auto *Return = llvm::dyn_cast<ReturnStmt>(Parent))
+    return Child == Return->getRetValue();
   return false;
 }
 
@@ -183,6 +186,23 @@ bool isConditionClause(const Stmt *Parent, const Stmt *Child) {
 //   each has its own ad hoc SelectionTree shape to verify per attribute
 //   or builtin, for constructs rare enough in practice that it isn't
 //   worth the per-case verification cost yet.
+// Whether Parent is an ordinary expression that passes along a requirement
+// that its own value be a constant expression to every subexpression that
+// directly contributes to computing it: if Parent itself turns out to sit
+// in a constant-expression context, so does its operand. This excludes the
+// standard operators whose expression operand isn't actually evaluated --
+// sizeof/alignof's expression form (UnaryExprOrTypeTraitExpr), the
+// noexcept operator (CXXNoexceptExpr), and typeid (CXXTypeidExpr) -- where
+// a non-constexpr call inside the operand is never a problem.
+bool propagatesConstantRequirement(const Expr *Parent) {
+  return isa<ParenExpr>(Parent) || isa<UnaryOperator>(Parent) ||
+         isa<BinaryOperator>(Parent) ||
+         isa<AbstractConditionalOperator>(Parent) || isa<CastExpr>(Parent) ||
+         isa<InitListExpr>(Parent) || isa<MemberExpr>(Parent) ||
+         isa<ArraySubscriptExpr>(Parent) || isa<CallExpr>(Parent) ||
+         isa<CXXConstructExpr>(Parent);
+}
+
 bool isConstantExpressionContext(const Node *N) {
   // Sema wraps a "manifestly constant evaluated" expression (exactly
   // these contexts: case labels, bit-field widths, enum initializers,
@@ -191,36 +211,58 @@ bool isConstantExpressionContext(const Node *N) {
   // an ImplicitCastExpr -- that aren't the real construct itself and
   // share N's own source range. outerImplicit() walks up through any
   // number of those to the real parent.
-  const Node *Parent = N->outerImplicit().Parent;
-  if (!Parent)
-    return false;
-  if (Parent->ASTNode.get<CaseStmt>())
-    return true;
-  if (const auto *Field = Parent->ASTNode.get<FieldDecl>())
-    return Field->isBitField();
-  if (Parent->ASTNode.get<EnumConstantDecl>())
-    return true;
-  if (const auto *Var = Parent->ASTNode.get<VarDecl>())
-    // constinit (unlike constexpr) isn't tracked as a VarDecl bit; it's
-    // just an attribute, but requires a constant initializer all the same.
-    return Var->isConstexpr() || Var->hasAttr<ConstInitAttr>();
-  // A TemplateSpecializationTypeLoc's Expr children (as opposed to TypeLoc
-  // children) are exactly its non-type template arguments -- the
-  // SelectionTree has no separate node for the intervening
-  // TemplateArgumentLoc. Other ways to name a non-type template argument
-  // (a bare function-template call's explicit arguments, a variable
-  // template) aren't verified and so aren't covered here yet.
-  if (Parent->ASTNode.get<TemplateSpecializationTypeLoc>())
-    return true;
-  if (Parent->ASTNode.get<StaticAssertDecl>())
-    return true;
-  // A FunctionProtoTypeLoc's only Expr child is its noexcept-specifier's
-  // operand (verified empirically that a parameter's default argument,
-  // the other candidate Expr near a function's type, instead has that
-  // ParmVarDecl itself as its parent, not the enclosing
-  // FunctionProtoTypeLoc).
-  if (Parent->ASTNode.get<FunctionProtoTypeLoc>())
-    return true;
+  //
+  // N itself need not be the whole constant expression: it may be a
+  // sub-expression nested inside a larger one (e.g. the `1 + 2` in
+  // `case (1 + 2) + 3:`), so this keeps climbing through ordinary
+  // operators (see propagatesConstantRequirement) until it either reaches
+  // one of the known constant-expression-requiring contexts below, or a
+  // node that doesn't propagate the requirement any further.
+  const Node *Cur = N;
+  while (const Node *Parent = Cur->outerImplicit().Parent) {
+    if (Parent->ASTNode.get<CaseStmt>())
+      return true;
+    if (const auto *Field = Parent->ASTNode.get<FieldDecl>())
+      return Field->isBitField();
+    if (Parent->ASTNode.get<EnumConstantDecl>())
+      return true;
+    if (const auto *Var = Parent->ASTNode.get<VarDecl>())
+      // constinit (unlike constexpr) isn't tracked as a VarDecl bit; it's
+      // just an attribute, but requires a constant initializer all the same.
+      return Var->isConstexpr() || Var->hasAttr<ConstInitAttr>();
+    // A TemplateSpecializationTypeLoc's Expr children (as opposed to TypeLoc
+    // children) are exactly its non-type template arguments -- the
+    // SelectionTree has no separate node for the intervening
+    // TemplateArgumentLoc. Other ways to name a non-type template argument
+    // (a bare function-template call's explicit arguments, a variable
+    // template) aren't verified and so aren't covered here yet.
+    if (Parent->ASTNode.get<TemplateSpecializationTypeLoc>())
+      return true;
+    if (Parent->ASTNode.get<StaticAssertDecl>())
+      return true;
+    // A FunctionProtoTypeLoc's only Expr child is its noexcept-specifier's
+    // operand (verified empirically that a parameter's default argument,
+    // the other candidate Expr near a function's type, instead has that
+    // ParmVarDecl itself as its parent, not the enclosing
+    // FunctionProtoTypeLoc).
+    if (Parent->ASTNode.get<FunctionProtoTypeLoc>())
+      return true;
+    // `if consteval`/`if !consteval` (isConsteval()) needs no check here:
+    // unlike `if constexpr`, it takes no parenthesized condition at all
+    // (If->getCond() is null for it), so there's nothing under it a
+    // selection could ever resolve to except ordinary statements in its
+    // then/else branches -- neither of which needs to itself be a constant
+    // expression.
+    if (const auto *If = Parent->ASTNode.get<IfStmt>()) {
+      const Stmt *Child = Cur->outerImplicit().ASTNode.get<Stmt>();
+      return If->isConstexpr() && (Child == If->getCond() ||
+                                   Child == If->getConditionVariableDeclStmt());
+    }
+    const auto *ParentExpr = Parent->ASTNode.get<Expr>();
+    if (!ParentExpr || !propagatesConstantRequirement(ParentExpr))
+      return false;
+    Cur = Parent;
+  }
   return false;
 }
 
@@ -245,6 +287,15 @@ bool eligibleForExpressionExtraction(const Expr *E) {
   if (E->isLValue())
     return false;
 
+  // A function can't return an array type. E->isLValue() above already
+  // excludes the common case (a plain array variable is an lvalue), but an
+  // array-typed xvalue can still reach here, e.g. accessing an array member
+  // through a prvalue struct (`getStruct().arr`): since C++11, member access
+  // on a non-lvalue base yields an xvalue, not a prvalue, so it isn't an
+  // lvalue either.
+  if (E->getType()->isArrayType())
+    return false;
+
   // A plain reference to a name (e.g. a variable, or an enum constant,
   // which -- unlike a variable -- is a prvalue and so isn't otherwise
   // excluded above) isn't interesting to extract on its own.
@@ -722,10 +773,10 @@ findExpressionExtractionZone(const Node *CommonAnc, const SourceManager &SM,
   if (isTrivialExtraction(E, SM))
     return std::nullopt;
   bool RequiresConstexpr = isConstantExpressionContext(&Target);
-  // C has no constexpr-function escape hatch for this (see
-  // isConstantExpressionContext), so there's no way to make the
+  // Neither C nor pre-C++11 has a constexpr-function escape hatch for this
+  // (see isConstantExpressionContext), so there's no way to make the
   // extraction compile.
-  if (RequiresConstexpr && !LangOpts.CPlusPlus)
+  if (RequiresConstexpr && !LangOpts.CPlusPlus11)
     return std::nullopt;
 
   ExtractionZone ExtZone;
diff --git a/clang-tools-extra/clangd/unittests/tweaks/ExtractFunctionTests.cpp b/clang-tools-extra/clangd/unittests/tweaks/ExtractFunctionTests.cpp
index 376883b6ea171b..1564b944afad8e 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/ExtractFunctionTests.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/ExtractFunctionTests.cpp
@@ -1664,6 +1664,18 @@ TEST_F(ExtractFunctionTest, ExpressionExtractionAssignmentRHS) {
               HasSubstr("x = extracted(a, b);"));
 }
 
+TEST_F(ExtractFunctionTest, ExpressionExtractionFromReturn) {
+  // A return statement's operand is a value-consuming slot just like a
+  // condition (see ExpressionExtractionFromCondition): replacing it with a
+  // call to a void-returning extracted function would not compile, so this
+  // must fall through from whole-statement to expression extraction.
+  Context = File;
+  EXPECT_THAT(apply("int f(int a, int b) { return [[a + b]]; }"),
+              AllOf(HasSubstr("int extracted(int a, int b) {\nreturn a + "
+                              "b;\n}"),
+                    HasSubstr("return extracted(a, b);")));
+}
+
 TEST_F(ExtractFunctionTest, ExpressionExtractionRejectVoid) {
   Context = File;
   EXPECT_THAT(apply("void g(); void f() { (void)([[g()]]); }"),
@@ -1678,6 +1690,21 @@ TEST_F(ExtractFunctionTest, ExpressionExtractionRejectLValue) {
   EXPECT_THAT(apply("void f(int a) { [[a]] = 5; }"), StartsWith("unavailable"));
 }
 
+TEST_F(ExtractFunctionTest, ExpressionExtractionRejectArrayType) {
+  // A function can't return an array type. Reached through a prvalue
+  // struct's array member, an xvalue since C++11 (member access on a
+  // non-lvalue base yields an xvalue, not a prvalue) -- so this isn't
+  // caught by ExpressionExtractionRejectLValue above.
+  Context = File;
+  EXPECT_THAT(apply(R"cpp(
+    struct S { int Arr[3]; };
+    S getS();
+    void use(const int *);
+    void f() { use([[getS().Arr]]); }
+  )cpp"),
+              StartsWith("unavailable"));
+}
+
 TEST_F(ExtractFunctionTest, ExpressionExtractionConstexprCaseLabel) {
   // A case label's value must be a constant expression. Rather than reject
   // the extraction outright, mark the extracted function constexpr so the
@@ -1695,6 +1722,34 @@ TEST_F(ExtractFunctionTest, ExpressionExtractionConstexprCaseLabel) {
                     HasSubstr("case extracted():")));
 }
 
+TEST_F(ExtractFunctionTest, ExpressionExtractionConstexprNestedCaseLabel) {
+  // The selected sub-expression isn't the whole case value, just an operand
+  // of the outer `+ 1`: the constant-expression requirement still has to
+  // propagate down to it through that enclosing BinaryOperator.
+  Context = File;
+  EXPECT_THAT(apply(R"cpp(
+    int f(int x) {
+      switch (x) {
+        case [[1 + 1]] + 1:
+          return 0;
+      }
+      return 1;
+    })cpp"),
+              AllOf(HasSubstr("constexpr int extracted() {\nreturn 1 + 1;\n}"),
+                    HasSubstr("case extracted() + 1:")));
+}
+
+TEST_F(ExtractFunctionTest, ExpressionExtractionConstexprIfConstexpr) {
+  Context = File;
+  ExtraArgs.push_back("-std=c++17");
+  EXPECT_THAT(apply(R"cpp(
+    void f() {
+      if constexpr ([[1 + 1]] > 0) {}
+    })cpp"),
+              AllOf(HasSubstr("constexpr int extracted() {\nreturn 1 + 1;\n}"),
+                    HasSubstr("if constexpr (extracted() > 0)")));
+}
+
 TEST_F(ExtractFunctionTest, ExpressionExtractionConstexprBitFieldWidth) {
   Context = File;
   EXPECT_THAT(apply(R"cpp(
@@ -1741,6 +1796,21 @@ TEST_F(ExtractFunctionTest, CFileRejectConstantExpressionContext) {
               StartsWith("unavailable"));
 }
 
+TEST_F(ExtractFunctionTest, PreCpp11RejectConstantExpressionContext) {
+  // constexpr functions don't exist before C++11 either, same as C.
+  Context = File;
+  ExtraArgs.push_back("-std=c++03");
+  EXPECT_THAT(apply(R"cpp(
+    int f(int x) {
+      switch (x) {
+        case [[1 + 1]]:
+          return 0;
+      }
+      return 1;
+    })cpp"),
+              StartsWith("unavailable"));
+}
+
 TEST_F(ExtractFunctionTest, ExpressionExtractionConstexprTemplateArgument) {
   Context = File;
   EXPECT_THAT(apply(R"cpp(

>From 0167cd1780a2df71ccda9f043bb1b51f82521fce Mon Sep 17 00:00:00 2001
From: Christian Kandeler <christian.kandeler at qt.io>
Date: Wed, 28 Oct 2026 12:09:35 +0100
Subject: [PATCH 3/3] [clangd] Extract to function: Reject a case label's value
 as a root statement

Whole-statement extraction didn't recognize a case label's value (or, for
a GNU case range, either bound) as a slot whose value is consumed by the
switch, so it could be wrongly offered as a standalone extractable
statement, producing a void-returning function called where a value was
required. In C++11 and later this is masked by an implementation detail:
Sema wraps the value in a ConstantExpr node, which -- being itself an
Expr -- already happens to make the existing child-vs-parent check reject
it. C and C++03 don't get that wrapper, so the bug surfaces there.

Assisted-by: Claude Code
---
 .../refactor/tweaks/ExtractFunction.cpp       | 32 +++++++++++++------
 .../unittests/tweaks/ExtractFunctionTests.cpp | 17 ++++++++++
 2 files changed, 39 insertions(+), 10 deletions(-)

diff --git a/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp b/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
index f00a9d1e272f7c..2e74b6f6c0b113 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
@@ -123,16 +123,26 @@ bool isUnselectedRootStmtCandidate(const Node *N) {
 }
 
 // Whether Child is the condition (or condition-variable declaration) of a
-// control-flow Parent, the range-expression of a range-based for, or the
-// operand of a return. These are the only slots whose *value* is actually
-// consumed by the construct itself -- to decide whether to keep
-// looping/branching, to build the hidden begin/end iterators, or to be
-// returned to the caller -- so replacing them with a call to a
-// void-returning extracted function would not compile. Other slots, like a
-// loop's init-statement or increment expression, have their value discarded
-// just like an ordinary expression-statement (and any hazard from
-// extracting a declaration that's used later is already caught by
-// ExtractionZone::requiresHoisting), so they remain extractable.
+// control-flow Parent, the range-expression of a range-based for, the
+// operand of a return, or a case label's value (or, for a GNU case range
+// `case A ... B:`, either bound). These are the only slots whose *value* is
+// actually consumed by the construct itself -- to decide whether to keep
+// looping/branching, to build the hidden begin/end iterators, to be
+// returned to the caller, or to select a switch arm -- so replacing them
+// with a call to a void-returning extracted function would not compile.
+// Other slots, like a loop's init-statement or increment expression, have
+// their value discarded just like an ordinary expression-statement (and
+// any hazard from extracting a declaration that's used later is already
+// caught by ExtractionZone::requiresHoisting), so they remain extractable.
+//
+// A case label's value additionally has to be a constant expression, which
+// callers needing that check separately via isConstantExpressionContext.
+// In C++11 and later, Sema wraps it in an invisible ConstantExpr node that
+// -- being itself an Expr -- already accidentally makes getEnclosingStmt
+// reject it as a root statement without this function's help; but C and
+// C++03 don't get that wrapper (verified via -ast-dump: the CaseStmt's
+// child is a bare, unwrapped expression there), so this check is the only
+// thing catching it in those modes.
 //
 // For CXXForRangeStmt, only RangeInit is ever reachable here: clangd's
 // SelectionTree has a custom traversal for range-based for loops (see
@@ -159,6 +169,8 @@ bool isConditionClause(const Stmt *Parent, const Stmt *Child) {
     return Child == ForRange->getRangeInit();
   if (const auto *Return = llvm::dyn_cast<ReturnStmt>(Parent))
     return Child == Return->getRetValue();
+  if (const auto *Case = llvm::dyn_cast<CaseStmt>(Parent))
+    return Child == Case->getLHS() || Child == Case->getRHS();
   return false;
 }
 
diff --git a/clang-tools-extra/clangd/unittests/tweaks/ExtractFunctionTests.cpp b/clang-tools-extra/clangd/unittests/tweaks/ExtractFunctionTests.cpp
index 1564b944afad8e..a33b8aa8173b45 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/ExtractFunctionTests.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/ExtractFunctionTests.cpp
@@ -1796,6 +1796,23 @@ TEST_F(ExtractFunctionTest, CFileRejectConstantExpressionContext) {
               StartsWith("unavailable"));
 }
 
+TEST_F(ExtractFunctionTest, CFileRejectCaseRangeBound) {
+  // A GNU case range's bounds (`case A ... B:`) are both consumed by the
+  // switch just like a plain case value -- this covers the upper bound,
+  // which the plain-case-label tests above don't exercise.
+  FileName = "a.c";
+  Context = File;
+  EXPECT_THAT(apply(R"cpp(
+    int f(int x) {
+      switch (x) {
+        case 1 ... [[1 + 4]]:
+          return 0;
+      }
+      return 1;
+    })cpp"),
+              StartsWith("unavailable"));
+}
+
 TEST_F(ExtractFunctionTest, PreCpp11RejectConstantExpressionContext) {
   // constexpr functions don't exist before C++11 either, same as C.
   Context = File;



More information about the cfe-commits mailing list