[clang-tools-extra] [clangd] Show member names in structured binding inlay hints (PR #245943)

via cfe-commits cfe-commits at lists.llvm.org
Wed Nov 25 01:27:39 PST 2026


https://github.com/bsumt created https://github.com/llvm/llvm-project/pull/245943

For example, `auto [n=.name: string, age: int] = person;`. Additionally,
the hint is omitted when the binding has the same name as the member.

Hints at the same position are now sorted by an explicit display order,
so that the designator hint (member name) comes before the type hint.

Fixes clangd/clangd#2727

Assisted-by: Claude Code

🤖 Generated with [Claude Code](https://claude.com/claude-code)


>From fef12b25e2e53fa04625b2f07f0901818fc7f3ae Mon Sep 17 00:00:00 2001
From: 47vvt <bryansmrtono at gmail.com>
Date: Wed, 25 Nov 2026 15:36:14 +1100
Subject: [PATCH] [clangd] Show member names in structured binding inlay hints

For example, `auto [n=.name: string, age: int] = person;`. Additionally,
the hint is omitted when the binding has the same name as the member.

Hints at the same position are now sorted by an explicit display order,
so that the designator hint (member name) comes before the type hint.

Fixes clangd/clangd#2727

Assisted-by: Claude Code
---
 clang-tools-extra/clangd/InlayHints.cpp       | 48 +++++++++-
 clang-tools-extra/clangd/Protocol.h           |  9 +-
 .../clangd/unittests/InlayHintTests.cpp       | 91 +++++++++++++++++++
 clang-tools-extra/docs/ReleaseNotes.md        |  5 +
 4 files changed, 149 insertions(+), 4 deletions(-)

diff --git a/clang-tools-extra/clangd/InlayHints.cpp b/clang-tools-extra/clangd/InlayHints.cpp
index e982c2c2f19747..c0fdd5583c4557 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -630,6 +630,9 @@ class InlayHintVisitor : public RecursiveASTVisitor<InlayHintVisitor> {
             !Type.isNull() && !Type->isDependentType())
           addTypeHint(Binding->getLocation(), Type.getCanonicalType(),
                       /*Prefix=*/": ");
+
+        if (Cfg.InlayHints.Designators)
+          addBindingDesignatorHint(Binding);
       }
       return true;
     }
@@ -675,6 +678,24 @@ class InlayHintVisitor : public RecursiveASTVisitor<InlayHintVisitor> {
     return true;
   }
 
+  // For a binding to a data member (e.g. `auto [n, a] = Person{}`), show the
+  // name of the member it refers to, unless the binding has the same name.
+  void addBindingDesignatorHint(BindingDecl *Binding) {
+    // getBinding() is a MemberExpr for data members, but not for tuple-like or
+    // array bindings, or binding packs.
+    auto *ME = dyn_cast_or_null<MemberExpr>(Binding->getBinding());
+    if (!ME)
+      return;
+    auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
+    if (!FD || !FD->getIdentifier() || FD->getName() == Binding->getName())
+      return;
+
+    std::string HintText = ("." + FD->getName()).str();
+    addInlayHint(Binding->getLocation(), HintSide::Right,
+                 InlayHintKind::Designator,
+                 /*Prefix=*/"=", HintText, /*Suffix=*/"");
+  }
+
   ParmVarDecl *getOnlyParamInstantiation(ParmVarDecl *D) {
     auto *TemplateFunction = llvm::dyn_cast<FunctionDecl>(D->getDeclContext());
     if (!TemplateFunction)
@@ -1209,9 +1230,34 @@ std::vector<InlayHint> inlayHints(ParsedAST &AST,
                            HintOptions);
   Visitor.TraverseAST(AST.getASTContext());
 
+  // Display order of hints at the same position and range. The enum order
+  // would put a structured binding's Type hint before its Designator hint.
+  auto DisplayOrder = [](InlayHintKind Kind) -> int {
+    switch (Kind) {
+    case InlayHintKind::Designator:
+      return 0;
+    case InlayHintKind::Type:
+      return 1;
+    case InlayHintKind::Parameter:
+      return 2;
+    case InlayHintKind::BlockEnd:
+      return 3;
+    case InlayHintKind::DefaultArgument:
+      return 4;
+    }
+    llvm_unreachable("Unknown InlayHintKind");
+  };
+
+  auto Cmp = [DisplayOrder](const InlayHint &A, const InlayHint &B) -> bool {
+    return std::forward_as_tuple(A.position, A.range, DisplayOrder(A.kind),
+                                 A.label) <
+           std::forward_as_tuple(B.position, B.range, DisplayOrder(B.kind),
+                                 B.label);
+  };
+
   // De-duplicate hints. Duplicates can sometimes occur due to e.g. explicit
   // template instantiations.
-  llvm::sort(Results);
+  llvm::sort(Results, Cmp);
   Results.erase(llvm::unique(Results), Results.end());
 
   return Results;
diff --git a/clang-tools-extra/clangd/Protocol.h b/clang-tools-extra/clangd/Protocol.h
index e81603a7b1a35b..042f3cc0574699 100644
--- a/clang-tools-extra/clangd/Protocol.h
+++ b/clang-tools-extra/clangd/Protocol.h
@@ -1751,10 +1751,13 @@ enum class InlayHintKind {
   /// which shows the name of the corresponding parameter.
   Parameter = 2,
 
-  /// A hint before an element of an aggregate braced initializer list,
-  /// indicating what it is initializing.
+  /// A hint naming the data member or array element that something
+  /// corresponds to. Either before an element of an aggregate braced
+  /// initializer list, indicating what it is initializing:
   ///   Pair{^1, ^2};
-  /// Uses designator syntax, e.g. `.first:`.
+  /// or after a structured binding, indicating the member it refers to:
+  ///   auto [a^, b^] = Pair{1, 2};
+  /// Uses designator syntax, e.g. `.first=` or `=.first` respectively.
   /// This is a clangd extension.
   Designator = 3,
 
diff --git a/clang-tools-extra/clangd/unittests/InlayHintTests.cpp b/clang-tools-extra/clangd/unittests/InlayHintTests.cpp
index ed074a3d7a0d6b..66348b66e35cd5 100644
--- a/clang-tools-extra/clangd/unittests/InlayHintTests.cpp
+++ b/clang-tools-extra/clangd/unittests/InlayHintTests.cpp
@@ -1908,6 +1908,97 @@ TEST(DesignatorHints, ParenInitTemplate) {
                         ExpectedHint{".ptr=", "ptr"});
 }
 
+TEST(DesignatorHints, StructuredBindings) {
+  assertDesignatorHints(R"cpp(
+    struct Person {
+      const char *name;
+      int age;
+      const char *email;
+    };
+    Person p;
+    auto [$n[[n]], $a[[a]], $e[[e]]] = p;
+    // No hint when the binding name matches its field, but one when swapped.
+    auto &[name, $email[[email]], $age[[age]]] = p;
+  )cpp",
+                        ExpectedHint{"=.name", "n"}, ExpectedHint{"=.age", "a"},
+                        ExpectedHint{"=.email", "e"},
+                        ExpectedHint{"=.age", "email"},
+                        ExpectedHint{"=.email", "age"});
+}
+
+TEST(DesignatorHints, StructuredBindings_FieldKinds) {
+  assertDesignatorHints(R"cpp(
+    struct Base { int x, y; };
+    struct Derived : Base {};
+    struct Bits { int a : 3; int : 5; int b : 5; };
+    struct Refs { int &r; const int &cr; };
+    struct Mutable { mutable int m; };
+    void f(Derived d, Bits b, Refs r, const Mutable cm) {
+      auto [$x[[x1]], $y[[y1]]] = d;
+      auto [$a[[a1]], $b[[b1]]] = b;
+      auto [$r[[r1]], $cr[[cr1]]] = r;
+      auto &[$m[[m1]]] = cm;
+    }
+    // Packs have no hint.
+    template <typename = void> void g(Base b) {
+      auto [$first[[first]], ...rest] = b;
+    }
+  )cpp",
+                        ExpectedHint{"=.x", "x"}, ExpectedHint{"=.y", "y"},
+                        ExpectedHint{"=.a", "a"}, ExpectedHint{"=.b", "b"},
+                        ExpectedHint{"=.r", "r"}, ExpectedHint{"=.cr", "cr"},
+                        ExpectedHint{"=.m", "m"}, ExpectedHint{"=.x", "first"});
+}
+
+TEST(DesignatorHints, StructuredBindings_NotMembers) {
+  assertDesignatorHints(R"cpp(
+    // Array and tuple-like bindings have no field names.
+    struct IntPair { int a, b; };
+    namespace std {
+      template <typename T> struct tuple_size;
+      template <> struct tuple_size<IntPair> {
+        constexpr static unsigned value = 2;
+      };
+      template <unsigned I, typename T> struct tuple_element;
+      template <unsigned I> struct tuple_element<I, IntPair> {
+        using type = int;
+      };
+    }
+    template <unsigned I> int get(const IntPair &p) { return I ? p.b : p.a; }
+    void f(IntPair p) {
+      int arr[2];
+      auto [x, y] = arr;
+      auto [z, w] = p;
+    }
+    // Dependent bindings are not resolved.
+    template <typename T> void g(T t) { auto [u, v] = t; }
+    struct Point { int x, y; };
+    void h() { g(Point{}); }
+  )cpp");
+}
+
+TEST(InlayHints, StructuredBindingsTypeAndDesignator) {
+  Annotations Source(R"cpp(
+    struct Point { int x, y; };
+    auto [$a[[a]], $b[[b]]] = Point{};
+  )cpp");
+  auto AST = TestTU::withCode(Source.code()).build();
+  Config Cfg;
+  Cfg.InlayHints.DeducedTypes = true;
+  Cfg.InlayHints.Designators = true;
+  WithContextValue WithCfg(Config::Key, std::move(Cfg));
+  auto Hints = inlayHints(AST, std::nullopt, DefaultOptsForTests);
+  EXPECT_THAT(
+      Hints,
+      ElementsAre(HintMatcher(ExpectedHint{"=.x", "a", Right}, Source),
+                  HintMatcher(ExpectedHint{": int", "a", Right}, Source),
+                  HintMatcher(ExpectedHint{"=.y", "b", Right}, Source),
+                  HintMatcher(ExpectedHint{": int", "b", Right}, Source)));
+  // Both kinds of hint are placed after the binding's name.
+  for (const auto &Hint : Hints)
+    EXPECT_EQ(Hint.position, Hint.range.end);
+}
+
 TEST(InlayHints, RestrictRange) {
   Annotations Code(R"cpp(
     auto a = false;
diff --git a/clang-tools-extra/docs/ReleaseNotes.md b/clang-tools-extra/docs/ReleaseNotes.md
index 92ce213ff2bc0b..4bce3b60ca402d 100644
--- a/clang-tools-extra/docs/ReleaseNotes.md
+++ b/clang-tools-extra/docs/ReleaseNotes.md
@@ -64,6 +64,11 @@ infrastructure are described first, followed by tool-specific sections.
 
 #### Inlay hints
 
+- Structured bindings to data members now show which member each binding
+  refers to, e.g. `auto [n=.name, a=.age] = person;`. The hint is omitted when
+  the binding has the same name as the member. It is controlled by the
+  `InlayHints.Designators` configuration option.
+
 #### Diagnostics
 
 - Query-based custom clang-tidy checks can now be enabled with the



More information about the cfe-commits mailing list