[clang-tools-extra] [clangd] Add AddUsingReplaceAll tweak to replace all qualified refere… (PR #204151)

Dimitri Ratz via cfe-commits cfe-commits at lists.llvm.org
Tue Nov 3 00:47:25 PST 2026


https://github.com/ratzdi updated https://github.com/llvm/llvm-project/pull/204151

>From 6724b163ac711f6c0ad641b0668b9f6395613929 Mon Sep 17 00:00:00 2001
From: Dimitri Ratz <dimitri.ratz at protonmail.com>
Date: Tue, 16 Jun 2026 13:48:16 +0200
Subject: [PATCH 01/16] [clangd] Add AddUsingReplaceAll tweak to replace all
 qualified references Adds a new refactoring code action that is triggered on
 a fully qualified name and removes its namespace qualifier from every
 occurrence in the file, inserting a using-declaration at an appropriate
 location. This complements the existing AddUsing tweak, which only rewrites
 the single reference under the cursor. Implementation notes: -
 collectEnclosingUsings() replaces a RecursiveASTVisitor-based traversal   by
 walking the DeclContext chain directly, reducing traversal cost from   O(AST
 nodes) to O(scope depth * decls per scope). - Qualifier extraction is guarded
 via getNamespaceFromQualifier() to reject   non-namespace qualifiers (e.g.
 record-type qualifiers) defensively. - apply() validates the prepared state
 before building replacements and only   rewrites references whose canonical
 target matches the selection. - References inside macro arguments are
 rewritten; macro-body expansions are   left untouched. Tests cover: basic
 multi-reference rewrites, macro arguments, global (::) qualifiers with
 nested-namespace syntax, multiple nested macro layers, and unavailability for
 non-namespace qualifiers such as record-type qualifiers.

---
 .../refactor/tweaks/AddUsingReplaceAll.cpp    | 445 ++++++++++++++++++
 .../clangd/refactor/tweaks/CMakeLists.txt     |   1 +
 .../clangd/unittests/CMakeLists.txt           |   1 +
 .../tweaks/AddUsingReplaceAllTests.cpp        | 174 +++++++
 4 files changed, 621 insertions(+)
 create mode 100644 clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
 create mode 100644 clang-tools-extra/clangd/unittests/tweaks/AddUsingReplaceAllTests.cpp

diff --git a/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp b/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
new file mode 100644
index 00000000000000..d2dc4f793cf12c
--- /dev/null
+++ b/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
@@ -0,0 +1,445 @@
+//===--- AddUsingReplaceAll.cpp ---------------------------------*- C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "AST.h"
+#include "Config.h"
+#include "FindTarget.h"
+#include "SourceCode.h"
+#include "refactor/Tweak.h"
+#include "support/Logger.h"
+
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclBase.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/NestedNameSpecifier.h"
+#include "clang/AST/Type.h"
+#include "clang/AST/TypeLoc.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Tooling/Core/Replacement.h"
+#include "clang/Tooling/Syntax/Tokens.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/raw_ostream.h"
+#include <string>
+#include <tuple>
+#include <utility>
+
+namespace clang {
+namespace clangd {
+namespace {
+
+/// Tweak for removing full namespace qualifier under cursor on DeclRefExpr and
+/// types and adding "using" statement instead. This tweak replaces all
+/// occurrences of the qualified symbol in the file, not just the one under the
+/// cursor, but it also requires more preparation and is more expensive to
+/// compute, so it is hidden behind a separate action from AddUsing, which only
+/// removes the qualifier under the cursor.
+class AddUsingReplaceAll : public Tweak {
+public:
+  const char *id() const override;
+
+  bool prepare(const Selection &Inputs) override;
+  Expected<Effect> apply(const Selection &Inputs) override;
+  std::string title() const override;
+  llvm::StringLiteral kind() const override {
+    return CodeAction::REFACTOR_KIND;
+  }
+
+private:
+  NestedNameSpecifierLoc QualifierToRemove;
+  std::string QualifierToSpell;
+  llvm::StringRef SpelledQualifier;
+  llvm::StringRef SpelledName;
+  SourceLocation MustInsertAfterLoc;
+  llvm::DenseSet<const NamedDecl *> RewriteTargets;
+};
+REGISTER_TWEAK(AddUsingReplaceAll)
+
+std::string AddUsingReplaceAll::title() const {
+  return std::string(llvm::formatv(
+      "Add using-declaration for {0} and replace qualified references",
+      SpelledName));
+}
+
+/// Collects all UsingDecls visible at the selection by walking the enclosing
+/// DeclContext chain directly, sorted by source location. This avoids a full
+/// AST traversal and only visits O(depth * declarations-per-scope) nodes.
+///
+/// A using-declaration declared in a scope S is visible at SelectionCtx iff
+/// S is an ancestor of SelectionCtx, i.e. exactly the contexts we walk when
+/// ascending via getLexicalParent().
+std::vector<const UsingDecl *>
+collectEnclosingUsings(const DeclContext *SelectionCtx,
+                       const SourceManager &SM) {
+  std::vector<const UsingDecl *> Result;
+  for (const DeclContext *Ctx = SelectionCtx; Ctx;
+       Ctx = Ctx->getLexicalParent()) {
+    for (const Decl *D : Ctx->decls()) {
+      const auto *UD = dyn_cast<UsingDecl>(D);
+      if (!UD)
+        continue;
+      if (SM.getFileID(UD->getUsingLoc()) != SM.getMainFileID())
+        continue;
+      Result.push_back(UD);
+    }
+  }
+  // Merge into a single sorted list so findInsertionPoint can break early.
+  llvm::sort(Result, [&](const UsingDecl *A, const UsingDecl *B) {
+    return SM.isBeforeInTranslationUnit(A->getUsingLoc(), B->getUsingLoc());
+  });
+  return Result;
+}
+
+struct InsertionPointData {
+  SourceLocation Loc;
+  std::string Suffix;
+  bool AlwaysFullyQualify = false;
+};
+
+const NamespaceDecl *getNamespaceFromQualifier(NestedNameSpecifier Qualifier) {
+  if (!Qualifier || Qualifier.getKind() != NestedNameSpecifier::Kind::Namespace)
+    return nullptr;
+  return dyn_cast_or_null<NamespaceDecl>(
+      Qualifier.getAsNamespaceAndPrefix().Namespace);
+}
+
+llvm::Expected<InsertionPointData>
+findInsertionPoint(const Tweak::Selection &Inputs,
+                   const NestedNameSpecifierLoc &QualifierToRemove,
+                   const llvm::StringRef Name,
+                   const SourceLocation MustInsertAfterLoc) {
+  auto &SM = Inputs.AST->getSourceManager();
+
+  const auto *TargetNamespace =
+      getNamespaceFromQualifier(QualifierToRemove.getNestedNameSpecifier());
+  if (!TargetNamespace)
+    return error("Qualifier is not a valid namespace qualifier");
+
+  SourceLocation LastUsingLoc;
+  const std::vector<const UsingDecl *> Usings = collectEnclosingUsings(
+      &Inputs.ASTSelection.commonAncestor()->getDeclContext(), SM);
+
+  auto IsValidPoint = [&](const SourceLocation Loc) {
+    return MustInsertAfterLoc.isInvalid() ||
+           SM.isBeforeInTranslationUnit(MustInsertAfterLoc, Loc);
+  };
+
+  bool AlwaysFullyQualify = true;
+  for (const auto *U : Usings) {
+    if (!U->getQualifier().isFullyQualified())
+      AlwaysFullyQualify = false;
+
+    if (const auto *Namespace = getNamespaceFromQualifier(U->getQualifier())) {
+      if (Namespace->getCanonicalDecl() ==
+              TargetNamespace->getCanonicalDecl() &&
+          U->getName() == Name)
+        return InsertionPointData();
+    }
+
+    LastUsingLoc = U->getUsingLoc();
+  }
+  if (LastUsingLoc.isValid() && IsValidPoint(LastUsingLoc)) {
+    InsertionPointData Out;
+    Out.Loc = LastUsingLoc;
+    Out.AlwaysFullyQualify = AlwaysFullyQualify;
+    return Out;
+  }
+
+  const DeclContext *ParentDeclCtx =
+      &Inputs.ASTSelection.commonAncestor()->getDeclContext();
+  while (ParentDeclCtx && !ParentDeclCtx->isFileContext())
+    ParentDeclCtx = ParentDeclCtx->getLexicalParent();
+
+  if (auto *ND = llvm::dyn_cast_or_null<NamespaceDecl>(ParentDeclCtx)) {
+    auto Toks = Inputs.AST->getTokens().expandedTokens(ND->getSourceRange());
+    const auto *Tok = llvm::find_if(Toks, [](const syntax::Token &Tok) {
+      return Tok.kind() == tok::l_brace;
+    });
+    if (Tok == Toks.end() || Tok->endLocation().isInvalid())
+      return error("Namespace with no {{");
+    if (!Tok->endLocation().isMacroID() && IsValidPoint(Tok->endLocation())) {
+      InsertionPointData Out;
+      Out.Loc = Tok->endLocation();
+      Out.Suffix = "\n";
+      return Out;
+    }
+  }
+
+  auto TLDs = Inputs.AST->getLocalTopLevelDecls();
+  for (const auto &TLD : TLDs) {
+    if (!IsValidPoint(TLD->getBeginLoc()))
+      continue;
+    InsertionPointData Out;
+    Out.Loc = SM.getExpansionLoc(TLD->getBeginLoc());
+    Out.Suffix = "\n\n";
+    return Out;
+  }
+  return error("Cannot find place to insert \"using\"");
+}
+
+bool isNamespaceForbidden(const Tweak::Selection &Inputs,
+                          NestedNameSpecifier Namespace) {
+  const auto *NS =
+      dyn_cast<NamespaceDecl>(Namespace.getAsNamespaceAndPrefix().Namespace);
+  if (!NS)
+    return true;
+  std::string NamespaceStr = printNamespaceScope(*NS);
+
+  for (StringRef Banned : Config::current().Style.FullyQualifiedNamespaces) {
+    StringRef PrefixMatch = NamespaceStr;
+    if (PrefixMatch.consume_front(Banned) && PrefixMatch.consume_front("::"))
+      return true;
+  }
+
+  return false;
+}
+
+std::string getNNSLAsString(NestedNameSpecifierLoc NNSL,
+                            const PrintingPolicy &Policy) {
+  std::string Out;
+  llvm::raw_string_ostream OutStream(Out);
+  NNSL.getNestedNameSpecifier().print(OutStream, Policy);
+  return OutStream.str();
+}
+
+const NamedDecl *canonicalDecl(const NamedDecl *D) {
+  return D ? llvm::dyn_cast<NamedDecl>(D->getCanonicalDecl()) : nullptr;
+}
+
+bool AddUsingReplaceAll::prepare(const Selection &Inputs) {
+  auto &SM = Inputs.AST->getSourceManager();
+  const auto &TB = Inputs.AST->getTokens();
+
+  QualifierToRemove = NestedNameSpecifierLoc();
+  QualifierToSpell.clear();
+  SpelledQualifier = llvm::StringRef();
+  SpelledName = llvm::StringRef();
+  MustInsertAfterLoc = SourceLocation();
+  RewriteTargets.clear();
+
+  if (isHeaderFile(SM.getFileEntryRefForID(SM.getMainFileID())->getName(),
+                   Inputs.AST->getLangOpts()))
+    return false;
+
+  auto *Node = Inputs.ASTSelection.commonAncestor();
+  if (!Node)
+    return false;
+
+  for (; Node->Parent; Node = Node->Parent) {
+    if (Node->ASTNode.get<NestedNameSpecifierLoc>())
+      continue;
+    if (auto *T = Node->ASTNode.get<TypeLoc>()) {
+      if (Node->Parent->ASTNode.get<NestedNameSpecifierLoc>())
+        continue;
+      if (isa<TagType, TemplateSpecializationType, TypedefType, UsingType,
+              UnresolvedUsingType>(T->getTypePtr()))
+        break;
+      if (Node->Parent->ASTNode.get<TypeLoc>())
+        continue;
+    }
+    break;
+  }
+  if (!Node)
+    return false;
+
+  SourceRange SpelledNameRange;
+  if (auto *D = Node->ASTNode.get<DeclRefExpr>()) {
+    if (D->getDecl()->getIdentifier()) {
+      QualifierToRemove = D->getQualifierLoc();
+      SpelledNameRange = D->getSourceRange();
+      if (auto AngleLoc = D->getLAngleLoc(); AngleLoc.isValid())
+        SpelledNameRange.setEnd(AngleLoc.getLocWithOffset(-1));
+      MustInsertAfterLoc = D->getDecl()->getBeginLoc();
+      if (const auto *Canonical = canonicalDecl(D->getDecl()))
+        RewriteTargets.insert(Canonical);
+    }
+  } else if (auto *T = Node->ASTNode.get<TypeLoc>()) {
+    switch (T->getTypeLocClass()) {
+    case TypeLoc::TemplateSpecialization: {
+      auto TL = T->castAs<TemplateSpecializationTypeLoc>();
+      QualifierToRemove = TL.getQualifierLoc();
+      if (!QualifierToRemove)
+        break;
+      SpelledNameRange = TL.getTemplateNameLoc();
+      if (auto *TD = TL.getTypePtr()->getTemplateName().getAsTemplateDecl(
+              /*IgnoreDeduced=*/true)) {
+        MustInsertAfterLoc = TD->getBeginLoc();
+        if (const auto *Canonical = canonicalDecl(TD))
+          RewriteTargets.insert(Canonical);
+      }
+      break;
+    }
+    case TypeLoc::Enum:
+    case TypeLoc::Record:
+    case TypeLoc::InjectedClassName: {
+      auto TL = T->castAs<TagTypeLoc>();
+      QualifierToRemove = TL.getQualifierLoc();
+      if (!QualifierToRemove)
+        break;
+      SpelledNameRange = TL.getNameLoc();
+      MustInsertAfterLoc = TL.getDecl()->getBeginLoc();
+      if (const auto *Canonical = canonicalDecl(TL.getDecl()))
+        RewriteTargets.insert(Canonical);
+      break;
+    }
+    case TypeLoc::Typedef: {
+      auto TL = T->castAs<TypedefTypeLoc>();
+      QualifierToRemove = TL.getQualifierLoc();
+      if (!QualifierToRemove)
+        break;
+      SpelledNameRange = TL.getNameLoc();
+      MustInsertAfterLoc = TL.getDecl()->getBeginLoc();
+      if (const auto *Canonical = canonicalDecl(TL.getDecl()))
+        RewriteTargets.insert(Canonical);
+      break;
+    }
+    case TypeLoc::UnresolvedUsing: {
+      auto TL = T->castAs<UnresolvedUsingTypeLoc>();
+      QualifierToRemove = TL.getQualifierLoc();
+      if (!QualifierToRemove)
+        break;
+      SpelledNameRange = TL.getNameLoc();
+      MustInsertAfterLoc = TL.getDecl()->getBeginLoc();
+      if (const auto *Canonical = canonicalDecl(TL.getDecl()))
+        RewriteTargets.insert(Canonical);
+      break;
+    }
+    case TypeLoc::Using: {
+      auto TL = T->castAs<UsingTypeLoc>();
+      QualifierToRemove = TL.getQualifierLoc();
+      if (!QualifierToRemove)
+        break;
+      SpelledNameRange = TL.getNameLoc();
+      MustInsertAfterLoc = TL.getDecl()->getBeginLoc();
+      if (const auto *Canonical = canonicalDecl(TL.getDecl()))
+        RewriteTargets.insert(Canonical);
+      break;
+    }
+    default:
+      break;
+    }
+    if (QualifierToRemove)
+      SpelledNameRange.setBegin(QualifierToRemove.getBeginLoc());
+  }
+
+  if (!QualifierToRemove || RewriteTargets.empty() ||
+      QualifierToRemove.getNestedNameSpecifier().getKind() !=
+          NestedNameSpecifier::Kind::Namespace ||
+      isNamespaceForbidden(Inputs, QualifierToRemove.getNestedNameSpecifier()))
+    return false;
+
+  if (SM.isMacroBodyExpansion(QualifierToRemove.getBeginLoc()) ||
+      !SM.isWrittenInSameFile(QualifierToRemove.getBeginLoc(),
+                              QualifierToRemove.getEndLoc()))
+    return false;
+
+  auto SpelledTokens =
+      TB.spelledForExpanded(TB.expandedTokens(SpelledNameRange));
+  if (!SpelledTokens)
+    return false;
+  auto SpelledRange =
+      syntax::Token::range(SM, SpelledTokens->front(), SpelledTokens->back());
+  std::tie(SpelledQualifier, SpelledName) =
+      splitQualifiedName(SpelledRange.text(SM));
+  QualifierToSpell = getNNSLAsString(
+      QualifierToRemove, Inputs.AST->getASTContext().getPrintingPolicy());
+  if (!llvm::StringRef(QualifierToSpell).ends_with(SpelledQualifier) ||
+      SpelledName.empty())
+    return false;
+  return true;
+}
+
+Expected<Tweak::Effect> AddUsingReplaceAll::apply(const Selection &Inputs) {
+  auto &SM = Inputs.AST->getSourceManager();
+
+  const auto *TargetNamespace =
+      getNamespaceFromQualifier(QualifierToRemove.getNestedNameSpecifier());
+  if (!TargetNamespace)
+    return error("Invalid namespace qualifier in prepared state");
+  if (SpelledName.empty() || QualifierToSpell.empty() || RewriteTargets.empty())
+    return error("Incomplete prepared state for AddUsingReplaceAll");
+
+  tooling::Replacements Repls;
+
+  auto InsertionPoint = findInsertionPoint(Inputs, QualifierToRemove,
+                                           SpelledName, MustInsertAfterLoc);
+  if (!InsertionPoint)
+    return InsertionPoint.takeError();
+
+  if (InsertionPoint->Loc.isValid()) {
+    std::string UsingText;
+    llvm::raw_string_ostream UsingTextStream(UsingText);
+    UsingTextStream << "using ";
+    if (InsertionPoint->AlwaysFullyQualify &&
+        !QualifierToRemove.getNestedNameSpecifier().isFullyQualified())
+      UsingTextStream << "::";
+    UsingTextStream << QualifierToSpell << SpelledName << ";"
+                    << InsertionPoint->Suffix;
+
+    assert(SM.getFileID(InsertionPoint->Loc) == SM.getMainFileID());
+    if (auto Err = Repls.add(tooling::Replacement(SM, InsertionPoint->Loc, 0,
+                                                  UsingTextStream.str())))
+      return std::move(Err);
+  }
+
+  for (const auto &D : Inputs.AST->getLocalTopLevelDecls()) {
+    findExplicitReferences(
+        D,
+        [&](ReferenceLoc Ref) {
+          if (!Ref.Qualifier || Ref.Targets.empty() || Ref.IsDecl)
+            return;
+          if (!getNamespaceFromQualifier(
+                  Ref.Qualifier.getNestedNameSpecifier()))
+            return;
+
+          SourceLocation QualifierLoc = Ref.Qualifier.getBeginLoc();
+          SourceLocation NameLoc = Ref.NameLoc;
+          if (QualifierLoc.isMacroID()) {
+            if (!SM.isMacroArgExpansion(QualifierLoc))
+              return;
+            QualifierLoc = SM.getFileLoc(QualifierLoc);
+          }
+          if (NameLoc.isMacroID()) {
+            if (!SM.isMacroArgExpansion(NameLoc))
+              return;
+            NameLoc = SM.getFileLoc(NameLoc);
+          }
+          if (SM.getFileID(QualifierLoc) != SM.getMainFileID() ||
+              SM.getFileID(NameLoc) != SM.getMainFileID())
+            return;
+
+          bool MatchesTarget = false;
+          for (const auto *Target : Ref.Targets) {
+            if (const auto *Canonical = canonicalDecl(Target);
+                Canonical && RewriteTargets.contains(Canonical)) {
+              MatchesTarget = true;
+              break;
+            }
+          }
+          if (!MatchesTarget)
+            return;
+
+          unsigned BeginOffset = SM.getFileOffset(QualifierLoc);
+          unsigned EndOffset = SM.getFileOffset(NameLoc);
+          if (BeginOffset >= EndOffset)
+            return;
+
+          if (Repls.add(tooling::Replacement(SM, QualifierLoc,
+                                             EndOffset - BeginOffset, "")))
+            return;
+        },
+        Inputs.AST->getHeuristicResolver());
+  }
+
+  return Effect::mainFileEdit(SM, std::move(Repls));
+}
+
+} // namespace
+} // namespace clangd
+} // namespace clang
diff --git a/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt b/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
index 1d6e38088ad67a..8ed40760fef973 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
+++ b/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
@@ -13,6 +13,7 @@ set(LLVM_LINK_COMPONENTS
 # clangd/tool/CMakeLists.txt for an example.
 add_clang_library(clangDaemonTweaks OBJECT
   AddUsing.cpp
+  AddUsingReplaceAll.cpp
   AnnotateHighlightings.cpp
   DefineInline.cpp
   DefineOutline.cpp
diff --git a/clang-tools-extra/clangd/unittests/CMakeLists.txt b/clang-tools-extra/clangd/unittests/CMakeLists.txt
index d596ba77efd4ae..6b27865fbfd463 100644
--- a/clang-tools-extra/clangd/unittests/CMakeLists.txt
+++ b/clang-tools-extra/clangd/unittests/CMakeLists.txt
@@ -120,6 +120,7 @@ add_unittest(ClangdUnitTests ClangdTests
   support/TraceTests.cpp
 
   tweaks/AddUsingTests.cpp
+  tweaks/AddUsingReplaceAllTests.cpp
   tweaks/AnnotateHighlightingsTests.cpp
   tweaks/DefineInlineTests.cpp
   tweaks/DefineOutlineTests.cpp
diff --git a/clang-tools-extra/clangd/unittests/tweaks/AddUsingReplaceAllTests.cpp b/clang-tools-extra/clangd/unittests/tweaks/AddUsingReplaceAllTests.cpp
new file mode 100644
index 00000000000000..741f94c910244e
--- /dev/null
+++ b/clang-tools-extra/clangd/unittests/tweaks/AddUsingReplaceAllTests.cpp
@@ -0,0 +1,174 @@
+//===-- AddUsingReplaceAllTests.cpp -----------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "TweakTesting.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+
+TWEAK_TEST(AddUsingReplaceAll);
+
+TEST_F(AddUsingReplaceAllTest, Prepare) {
+  const char *Header = R"cpp(namespace ns { struct SomeStruct {}; })cpp";
+
+  EXPECT_AVAILABLE(std::string(Header) + R"cpp(
+ns::SomeStruct bar() {
+  n^s::SomeStruct x;
+  return x;
+})cpp");
+  EXPECT_UNAVAILABLE(std::string(Header) + R"cpp(
+ns::SomeStruct bar() {
+  ns::SomeStruct ^x;
+  return x;
+})cpp");
+
+  EXPECT_UNAVAILABLE(R"cpp(
+struct S {
+  static void f();
+};
+void fun() {
+  S::f^();
+}
+)cpp");
+}
+
+TEST_F(AddUsingReplaceAllTest, Apply) {
+  ExtraFiles["test.hpp"] = R"cpp(
+namespace one {
+namespace two {
+void ff();
+}
+})cpp";
+
+  EXPECT_EQ(apply(R"cpp(
+#include "test.hpp"
+
+void fun() {
+  one::two::f^f();
+  one::two::ff();
+}
+
+void other() {
+  one::two::ff();
+}
+)cpp"),
+            R"cpp(
+#include "test.hpp"
+
+using one::two::ff;
+
+void fun() {
+  ff();
+  ff();
+}
+
+void other() {
+  ff();
+}
+)cpp");
+}
+
+TEST_F(AddUsingReplaceAllTest, ApplyInsideMacroArgument) {
+  ExtraFiles["test.hpp"] = R"cpp(
+namespace one {
+namespace two {
+void ff();
+}
+})cpp";
+
+  EXPECT_EQ(apply(R"cpp(
+#include "test.hpp"
+#define CALL(name) name()
+
+void fun() {
+  CALL(one::two::f^f);
+  one::two::ff();
+}
+)cpp"),
+            R"cpp(
+#include "test.hpp"
+#define CALL(name) name()
+
+using one::two::ff;
+
+void fun() {
+  CALL(ff);
+  ff();
+}
+)cpp");
+}
+
+TEST_F(AddUsingReplaceAllTest, ApplyWithGlobalQualifierAndNestedNamespaceDecl) {
+  ExtraFiles["test.hpp"] = R"cpp(
+namespace one::two {
+void ff();
+}
+)cpp";
+
+  EXPECT_EQ(apply(R"cpp(
+#include "test.hpp"
+
+void fun() {
+  ::one::two::f^f();
+  one::two::ff();
+}
+)cpp"),
+            R"cpp(
+#include "test.hpp"
+
+using ::one::two::ff;
+
+void fun() {
+  ff();
+  ff();
+}
+)cpp");
+}
+
+TEST_F(AddUsingReplaceAllTest, ApplyWithMultipleMacros) {
+  ExtraFiles["test.hpp"] = R"cpp(
+namespace one {
+namespace two {
+void ff();
+}
+}
+)cpp";
+
+  EXPECT_EQ(apply(R"cpp(
+#include "test.hpp"
+#define ID(X) X
+#define CALL(name) name()
+#define CALL_FF one::two::ff()
+
+void fun() {
+  CALL(ID(one::two::f^f));
+  CALL_FF;
+  one::two::ff();
+}
+)cpp"),
+            R"cpp(
+#include "test.hpp"
+#define ID(X) X
+#define CALL(name) name()
+#define CALL_FF one::two::ff()
+
+using one::two::ff;
+
+void fun() {
+  CALL(ID(ff));
+  CALL_FF;
+  ff();
+}
+)cpp");
+}
+
+} // namespace
+} // namespace clangd
+} // namespace clang

>From f700f3602450a12909fb0ce08d4de03cb2dbfcbf Mon Sep 17 00:00:00 2001
From: Dimitri Ratz <dimitri.ratz at protonmail.com>
Date: Thu, 18 Jun 2026 09:25:20 +0200
Subject: [PATCH 02/16] [clangd] Refactor AddUsingReplaceAll tweak to use
 static functions and improve clarity

---
 .../refactor/tweaks/AddUsingReplaceAll.cpp    | 43 +++++++++----------
 1 file changed, 20 insertions(+), 23 deletions(-)

diff --git a/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp b/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
index d2dc4f793cf12c..b0141bb4da6b1c 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
@@ -16,8 +16,6 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclBase.h"
 #include "clang/AST/Expr.h"
-#include "clang/AST/NestedNameSpecifier.h"
-#include "clang/AST/Type.h"
 #include "clang/AST/TypeLoc.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Tooling/Core/Replacement.h"
@@ -32,14 +30,13 @@
 
 namespace clang {
 namespace clangd {
-namespace {
-
-/// Tweak for removing full namespace qualifier under cursor on DeclRefExpr and
-/// types and adding "using" statement instead. This tweak replaces all
-/// occurrences of the qualified symbol in the file, not just the one under the
-/// cursor, but it also requires more preparation and is more expensive to
-/// compute, so it is hidden behind a separate action from AddUsing, which only
-/// removes the qualifier under the cursor.
+
+/// Tweak for removing the full namespace qualifier under the cursor on
+/// DeclRefExpr and types and adding "using" statement instead. This tweak
+/// replaces all occurrences of the qualified symbol in the file, not just the
+/// one under the cursor, but it also requires more preparation and is more
+/// expensive to compute, so it is hidden behind a separate action from
+/// AddUsing, which only removes the qualifier under the cursor.
 class AddUsingReplaceAll : public Tweak {
 public:
   const char *id() const override;
@@ -62,9 +59,9 @@ class AddUsingReplaceAll : public Tweak {
 REGISTER_TWEAK(AddUsingReplaceAll)
 
 std::string AddUsingReplaceAll::title() const {
-  return std::string(llvm::formatv(
-      "Add using-declaration for {0} and replace qualified references",
-      SpelledName));
+  return std::string(llvm::formatv("Add using-declaration for {0} and replace "
+                                   "all qualified references in this file",
+                                   SpelledName));
 }
 
 /// Collects all UsingDecls visible at the selection by walking the enclosing
@@ -72,9 +69,9 @@ std::string AddUsingReplaceAll::title() const {
 /// AST traversal and only visits O(depth * declarations-per-scope) nodes.
 ///
 /// A using-declaration declared in a scope S is visible at SelectionCtx iff
-/// S is an ancestor of SelectionCtx, i.e. exactly the contexts we walk when
+/// S is an ancestor of SelectionCtx, i.e., exactly the contexts we walk when
 /// ascending via getLexicalParent().
-std::vector<const UsingDecl *>
+static std::vector<const UsingDecl *>
 collectEnclosingUsings(const DeclContext *SelectionCtx,
                        const SourceManager &SM) {
   std::vector<const UsingDecl *> Result;
@@ -102,14 +99,15 @@ struct InsertionPointData {
   bool AlwaysFullyQualify = false;
 };
 
-const NamespaceDecl *getNamespaceFromQualifier(NestedNameSpecifier Qualifier) {
+static const NamespaceDecl *
+getNamespaceFromQualifier(NestedNameSpecifier Qualifier) {
   if (!Qualifier || Qualifier.getKind() != NestedNameSpecifier::Kind::Namespace)
     return nullptr;
   return dyn_cast_or_null<NamespaceDecl>(
       Qualifier.getAsNamespaceAndPrefix().Namespace);
 }
 
-llvm::Expected<InsertionPointData>
+static llvm::Expected<InsertionPointData>
 findInsertionPoint(const Tweak::Selection &Inputs,
                    const NestedNameSpecifierLoc &QualifierToRemove,
                    const llvm::StringRef Name,
@@ -183,8 +181,8 @@ findInsertionPoint(const Tweak::Selection &Inputs,
   return error("Cannot find place to insert \"using\"");
 }
 
-bool isNamespaceForbidden(const Tweak::Selection &Inputs,
-                          NestedNameSpecifier Namespace) {
+static bool isNamespaceForbidden(const Tweak::Selection &Inputs,
+                                 NestedNameSpecifier Namespace) {
   const auto *NS =
       dyn_cast<NamespaceDecl>(Namespace.getAsNamespaceAndPrefix().Namespace);
   if (!NS)
@@ -200,15 +198,15 @@ bool isNamespaceForbidden(const Tweak::Selection &Inputs,
   return false;
 }
 
-std::string getNNSLAsString(NestedNameSpecifierLoc NNSL,
-                            const PrintingPolicy &Policy) {
+static std::string getNNSLAsString(NestedNameSpecifierLoc NNSL,
+                                   const PrintingPolicy &Policy) {
   std::string Out;
   llvm::raw_string_ostream OutStream(Out);
   NNSL.getNestedNameSpecifier().print(OutStream, Policy);
   return OutStream.str();
 }
 
-const NamedDecl *canonicalDecl(const NamedDecl *D) {
+static const NamedDecl *canonicalDecl(const NamedDecl *D) {
   return D ? llvm::dyn_cast<NamedDecl>(D->getCanonicalDecl()) : nullptr;
 }
 
@@ -440,6 +438,5 @@ Expected<Tweak::Effect> AddUsingReplaceAll::apply(const Selection &Inputs) {
   return Effect::mainFileEdit(SM, std::move(Repls));
 }
 
-} // namespace
 } // namespace clangd
 } // namespace clang

>From 91c092e3de06288f99f6f0a934050ae38adf34ed Mon Sep 17 00:00:00 2001
From: Dimitri Ratz <dimitri.ratz at protonmail.com>
Date: Thu, 18 Jun 2026 12:13:17 +0200
Subject: [PATCH 03/16] [clangd] Add ReplaceQualifiedWithAlias tweak to
 simplify references

Introduces a new refactoring action `ReplaceQualifiedWithAlias` that replaces fully qualified references in the current file with an alias, improving code readability. Includes implementation, tests, and CMake integration.
---
 .../clangd/refactor/tweaks/CMakeLists.txt     |   1 +
 .../tweaks/ReplaceQualifiedWithAlias.cpp      | 217 ++++++++++++++++++
 .../clangd/unittests/CMakeLists.txt           |   1 +
 .../tweaks/ReplaceQualifiedWithAliasTests.cpp | 158 +++++++++++++
 4 files changed, 377 insertions(+)
 create mode 100644 clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
 create mode 100644 clang-tools-extra/clangd/unittests/tweaks/ReplaceQualifiedWithAliasTests.cpp

diff --git a/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt b/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
index 8ed40760fef973..38a1a166524278 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
+++ b/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
@@ -28,6 +28,7 @@ add_clang_library(clangDaemonTweaks OBJECT
   OverridePureVirtuals.cpp
   PopulateSwitch.cpp
   RawStringLiteral.cpp
+  ReplaceQualifiedWithAlias.cpp
   RemoveUsingNamespace.cpp
   ScopifyEnum.cpp
   SpecialMembers.cpp
diff --git a/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp b/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
new file mode 100644
index 00000000000000..46b2fd8598dc85
--- /dev/null
+++ b/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
@@ -0,0 +1,217 @@
+//===--- ReplaceQualifiedWithAlias.cpp ---------------------------*- C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "FindTarget.h"
+#include "refactor/Tweak.h"
+#include "support/Logger.h"
+
+#include "clang/AST/Decl.h"
+#include "clang/AST/NestedNameSpecifier.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Tooling/Core/Replacement.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/FormatVariadic.h"
+#include <string>
+
+namespace clang {
+namespace clangd {
+namespace {
+
+class ReplaceQualifiedWithAlias : public Tweak {
+public:
+  const char *id() const override;
+
+  bool prepare(const Selection &Inputs) override;
+  Expected<Effect> apply(const Selection &Inputs) override;
+  std::string title() const override;
+  llvm::StringLiteral kind() const override {
+    return CodeAction::REFACTOR_KIND;
+  }
+
+private:
+  std::string AliasName;
+  SourceRange AliasDeclToSkip;
+  llvm::DenseSet<const NamedDecl *> RewriteTargets;
+};
+REGISTER_TWEAK(ReplaceQualifiedWithAlias)
+
+const NamedDecl *canonicalDecl(const NamedDecl *D) {
+  return D ? llvm::dyn_cast<NamedDecl>(D->getCanonicalDecl()) : nullptr;
+}
+
+bool isNamespaceQualifier(NestedNameSpecifierLoc Qualifier) {
+  return Qualifier && Qualifier.getNestedNameSpecifier().getKind() ==
+                          NestedNameSpecifier::Kind::Namespace;
+}
+
+SourceLocation getReferenceEnd(SourceLocation NameLoc, const SourceManager &SM,
+                               const LangOptions &LangOpts) {
+  std::optional<Token> Tok = Lexer::findNextToken(NameLoc, SM, LangOpts);
+  if (!Tok || Tok->isNot(tok::less))
+    return Lexer::getLocForEndOfToken(NameLoc, 0, SM, LangOpts);
+
+  unsigned Depth = 0;
+  while (Tok) {
+    switch (Tok->getKind()) {
+    case tok::less:
+      ++Depth;
+      break;
+    case tok::greater:
+      if (Depth == 0)
+        return Lexer::getLocForEndOfToken(Tok->getLocation(), 0, SM, LangOpts);
+      --Depth;
+      if (Depth == 0)
+        return Lexer::getLocForEndOfToken(Tok->getLocation(), 0, SM, LangOpts);
+      break;
+    case tok::greatergreater:
+      if (Depth <= 1)
+        return Lexer::getLocForEndOfToken(Tok->getLocation(), 0, SM, LangOpts);
+      Depth -= 2;
+      if (Depth == 0)
+        return Lexer::getLocForEndOfToken(Tok->getLocation(), 0, SM, LangOpts);
+      break;
+    default:
+      if (Depth == 0)
+        return Lexer::getLocForEndOfToken(Tok->getLocation(), 0, SM, LangOpts);
+      break;
+    }
+    Tok = Lexer::findNextToken(Tok->getLocation(), SM, LangOpts);
+  }
+  return Lexer::getLocForEndOfToken(NameLoc, 0, SM, LangOpts);
+}
+
+std::string ReplaceQualifiedWithAlias::title() const {
+  return std::string(
+      llvm::formatv("Replace qualified references with {0}", AliasName));
+}
+
+bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
+  AliasName.clear();
+  AliasDeclToSkip = SourceRange();
+  RewriteTargets.clear();
+
+  auto *Node = Inputs.ASTSelection.commonAncestor();
+  if (!Node)
+    return false;
+
+  for (auto *N = Node; N; N = N->Parent) {
+    const auto *Alias = N->ASTNode.get<TypeAliasDecl>();
+    if (!Alias)
+      continue;
+    if (!Alias->getIdentifier())
+      return false;
+
+    ReferenceLoc QualifiedRef;
+    bool FoundQualifiedRef = false;
+    findExplicitReferences(
+        Alias,
+        [&](ReferenceLoc Ref) {
+          if (FoundQualifiedRef || !Ref.Qualifier || Ref.Targets.empty())
+            return;
+          if (!isNamespaceQualifier(Ref.Qualifier))
+            return;
+          QualifiedRef = std::move(Ref);
+          FoundQualifiedRef = true;
+        },
+        Inputs.AST->getHeuristicResolver());
+
+    if (!FoundQualifiedRef)
+      return false;
+
+    for (const auto *Target : QualifiedRef.Targets) {
+      if (const auto *Canonical = canonicalDecl(Target))
+        RewriteTargets.insert(Canonical);
+    }
+    if (RewriteTargets.empty())
+      return false;
+
+    AliasName = Alias->getNameAsString();
+    AliasDeclToSkip = Alias->getSourceRange();
+    return true;
+  }
+
+  return false;
+}
+
+Expected<Tweak::Effect>
+ReplaceQualifiedWithAlias::apply(const Selection &Inputs) {
+  auto &SM = Inputs.AST->getSourceManager();
+  const auto &LangOpts = Inputs.AST->getLangOpts();
+
+  if (AliasName.empty() || RewriteTargets.empty())
+    return error("Incomplete prepared state for ReplaceQualifiedWithAlias");
+
+  SourceLocation SkipBegin = AliasDeclToSkip.getBegin();
+  SourceLocation SkipEnd = AliasDeclToSkip.getEnd();
+  if (SkipBegin.isValid())
+    SkipBegin = SM.getExpansionLoc(SkipBegin);
+  if (SkipEnd.isValid())
+    SkipEnd = SM.getExpansionLoc(SkipEnd);
+
+  tooling::Replacements Repls;
+  for (const auto &D : Inputs.AST->getLocalTopLevelDecls()) {
+    findExplicitReferences(
+        D,
+        [&](ReferenceLoc Ref) {
+          if (!Ref.Qualifier || Ref.Targets.empty() || Ref.IsDecl)
+            return;
+          if (!isNamespaceQualifier(Ref.Qualifier))
+            return;
+
+          bool MatchesTarget = false;
+          for (const auto *Target : Ref.Targets) {
+            if (const auto *Canonical = canonicalDecl(Target);
+                Canonical && RewriteTargets.contains(Canonical)) {
+              MatchesTarget = true;
+              break;
+            }
+          }
+          if (!MatchesTarget)
+            return;
+
+          SourceLocation QualifierLoc = Ref.Qualifier.getBeginLoc();
+          SourceLocation NameLoc = Ref.NameLoc;
+          if (QualifierLoc.isMacroID()) {
+            if (!SM.isMacroArgExpansion(QualifierLoc))
+              return;
+            QualifierLoc = SM.getFileLoc(QualifierLoc);
+          }
+          if (NameLoc.isMacroID()) {
+            if (!SM.isMacroArgExpansion(NameLoc))
+              return;
+            NameLoc = SM.getFileLoc(NameLoc);
+          }
+          if (SM.getFileID(QualifierLoc) != SM.getMainFileID() ||
+              SM.getFileID(NameLoc) != SM.getMainFileID())
+            return;
+
+          if (SkipBegin.isValid() && SkipEnd.isValid() &&
+              SM.isPointWithin(NameLoc, SkipBegin, SkipEnd))
+            return;
+
+          unsigned BeginOffset = SM.getFileOffset(QualifierLoc);
+          SourceLocation EndLoc = getReferenceEnd(NameLoc, SM, LangOpts);
+          if (BeginOffset > SM.getFileOffset(EndLoc))
+            return;
+
+          if (auto Err = Repls.add(tooling::Replacement(
+                  SM, QualifierLoc, SM.getFileOffset(EndLoc) - BeginOffset,
+                  AliasName)))
+            consumeError(std::move(Err));
+        },
+        Inputs.AST->getHeuristicResolver());
+  }
+
+  return Effect::mainFileEdit(SM, std::move(Repls));
+}
+
+} // namespace
+} // namespace clangd
+} // namespace clang
diff --git a/clang-tools-extra/clangd/unittests/CMakeLists.txt b/clang-tools-extra/clangd/unittests/CMakeLists.txt
index 6b27865fbfd463..8eae604ad1e898 100644
--- a/clang-tools-extra/clangd/unittests/CMakeLists.txt
+++ b/clang-tools-extra/clangd/unittests/CMakeLists.txt
@@ -137,6 +137,7 @@ add_unittest(ClangdUnitTests ClangdTests
   tweaks/OverridePureVirtualsTests.cpp
   tweaks/PopulateSwitchTests.cpp
   tweaks/RawStringLiteralTests.cpp
+  tweaks/ReplaceQualifiedWithAliasTests.cpp
   tweaks/RemoveUsingNamespaceTests.cpp
   tweaks/ScopifyEnumTests.cpp
   tweaks/ShowSelectionTreeTests.cpp
diff --git a/clang-tools-extra/clangd/unittests/tweaks/ReplaceQualifiedWithAliasTests.cpp b/clang-tools-extra/clangd/unittests/tweaks/ReplaceQualifiedWithAliasTests.cpp
new file mode 100644
index 00000000000000..c35037216267d4
--- /dev/null
+++ b/clang-tools-extra/clangd/unittests/tweaks/ReplaceQualifiedWithAliasTests.cpp
@@ -0,0 +1,158 @@
+//===-- ReplaceQualifiedWithAliasTests.cpp -----------------------*- C++
+//-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "TweakTesting.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+
+TWEAK_TEST(ReplaceQualifiedWithAlias);
+
+TEST_F(ReplaceQualifiedWithAliasTest, Prepare) {
+  const char *Header = R"cpp(
+namespace ns { struct Foo {}; }
+)cpp";
+
+  EXPECT_AVAILABLE(std::string(Header) + R"cpp(
+using Y = ns::F^oo;
+ns::Foo A;
+)cpp");
+
+  EXPECT_UNAVAILABLE(std::string(Header) + R"cpp(
+using Y = ns::Foo;^
+ns::Foo A;
+)cpp");
+}
+
+TEST_F(ReplaceQualifiedWithAliasTest, Apply) {
+  EXPECT_EQ(apply(R"cpp(
+namespace ns {
+struct Foo {};
+}
+
+using Y = ns::F^oo;
+
+ns::Foo A;
+void f() {
+  ns::Foo B;
+}
+)cpp"),
+            R"cpp(
+namespace ns {
+struct Foo {};
+}
+
+using Y = ns::Foo;
+
+Y A;
+void f() {
+  Y B;
+}
+)cpp");
+}
+
+TEST_F(ReplaceQualifiedWithAliasTest, ApplyInsideMacroArgument) {
+  EXPECT_EQ(apply(R"cpp(
+namespace ns {
+struct Foo {};
+}
+
+#define ID(X) X
+using Y = ns::F^oo;
+
+ID(ns::Foo) A;
+)cpp"),
+            R"cpp(
+namespace ns {
+struct Foo {};
+}
+
+#define ID(X) X
+using Y = ns::Foo;
+
+ID(Y) A;
+)cpp");
+}
+
+TEST_F(ReplaceQualifiedWithAliasTest, KeepAliasDeclarationUnchanged) {
+  EXPECT_EQ(apply(R"cpp(
+namespace ns {
+template <typename T> struct Foo {};
+}
+
+using Y = ns::F^oo<int>;
+
+ns::Foo<int> A;
+)cpp"),
+            R"cpp(
+namespace ns {
+template <typename T> struct Foo {};
+}
+
+using Y = ns::Foo<int>;
+
+Y A;
+)cpp");
+}
+
+TEST_F(ReplaceQualifiedWithAliasTest, ApplyNestedNamespaces) {
+  EXPECT_EQ(apply(R"cpp(
+namespace a {
+namespace b {
+struct Foo {};
+}
+}
+
+using Y = a::b::F^oo;
+
+a::b::Foo A;
+::a::b::Foo B;
+)cpp"),
+            R"cpp(
+namespace a {
+namespace b {
+struct Foo {};
+}
+}
+
+using Y = a::b::Foo;
+
+Y A;
+Y B;
+)cpp");
+}
+
+TEST_F(ReplaceQualifiedWithAliasTest, ApplyWithCompetingAlias) {
+  EXPECT_EQ(apply(R"cpp(
+namespace ns {
+struct Foo {};
+}
+
+using Y = ns::F^oo;
+using Z = ns::Foo;
+
+ns::Foo A;
+)cpp"),
+            R"cpp(
+namespace ns {
+struct Foo {};
+}
+
+using Y = ns::Foo;
+using Z = Y;
+
+Y A;
+)cpp");
+}
+
+} // namespace
+} // namespace clangd
+} // namespace clang

>From 5ae3e840539652580e31473ea3d4c394609b80ea Mon Sep 17 00:00:00 2001
From: Dimitri Ratz <dimitri.ratz at protonmail.com>
Date: Wed, 24 Jun 2026 08:49:30 +0200
Subject: [PATCH 04/16] [clangd]: in tweak ReplaceQualifiedWithAlias, consider
 using declarations.

---
 .../refactor/tweaks/ReplaceQualifiedWithAlias.cpp      | 10 ++++++++--
 .../tweaks/ReplaceQualifiedWithAliasTests.cpp          |  5 +++++
 2 files changed, 13 insertions(+), 2 deletions(-)

diff --git a/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp b/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
index 46b2fd8598dc85..804d27dd1afb43 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
@@ -102,9 +102,15 @@ bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
     return false;
 
   for (auto *N = Node; N; N = N->Parent) {
-    const auto *Alias = N->ASTNode.get<TypeAliasDecl>();
-    if (!Alias)
+    const NamedDecl *Alias = nullptr;
+    if (const auto *TAD = N->ASTNode.get<TypeAliasDecl>(); TAD) {
+      Alias = TAD;
+    } else if (const auto *UD = N->ASTNode.get<UsingDecl>(); UD) {
+      Alias = UD;
+    } else {
       continue;
+    }
+
     if (!Alias->getIdentifier())
       return false;
 
diff --git a/clang-tools-extra/clangd/unittests/tweaks/ReplaceQualifiedWithAliasTests.cpp b/clang-tools-extra/clangd/unittests/tweaks/ReplaceQualifiedWithAliasTests.cpp
index c35037216267d4..0b16e58e97168b 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/ReplaceQualifiedWithAliasTests.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/ReplaceQualifiedWithAliasTests.cpp
@@ -24,6 +24,11 @@ namespace ns { struct Foo {}; }
   EXPECT_AVAILABLE(std::string(Header) + R"cpp(
 using Y = ns::F^oo;
 ns::Foo A;
+)cpp");
+
+  EXPECT_AVAILABLE(std::string(Header) + R"cpp(
+using ns::F^oo;
+ns::Foo A;
 )cpp");
 
   EXPECT_UNAVAILABLE(std::string(Header) + R"cpp(

>From d5ed26a9bdaf035d94d1a81c61d59d46d6870820 Mon Sep 17 00:00:00 2001
From: Dimitri Ratz <dimitri.ratz at protonmail.com>
Date: Thu, 25 Jun 2026 09:16:59 +0200
Subject: [PATCH 05/16] [clangd]: Enhance ReplaceQualifiedWithAlias to handle
 using declarations

Improves the `ReplaceQualifiedWithAlias` tweak by adding support for analyzing using declarations when replacing qualified references with aliases. Updates include extended logic for detection, validation, and processing of using declarations, along with new unit tests to ensure correctness.
---
 .../tweaks/ReplaceQualifiedWithAlias.cpp      | 142 +++++++++++++++---
 .../tweaks/ReplaceQualifiedWithAliasTests.cpp |  67 +++++++++
 2 files changed, 192 insertions(+), 17 deletions(-)

diff --git a/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp b/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
index 804d27dd1afb43..83c2981819d737 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
@@ -16,6 +16,7 @@
 #include "clang/Lex/Lexer.h"
 #include "clang/Tooling/Core/Replacement.h"
 #include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/FormatVariadic.h"
 #include <string>
@@ -51,6 +52,16 @@ bool isNamespaceQualifier(NestedNameSpecifierLoc Qualifier) {
                           NestedNameSpecifier::Kind::Namespace;
 }
 
+void collectUsingDecls(const DeclContext *DC,
+                       llvm::SmallVectorImpl<const UsingDecl *> &Out) {
+  for (const Decl *D : DC->decls()) {
+    if (const auto *UD = llvm::dyn_cast<UsingDecl>(D))
+      Out.push_back(UD);
+    if (const auto *Nested = llvm::dyn_cast<DeclContext>(D))
+      collectUsingDecls(Nested, Out);
+  }
+}
+
 SourceLocation getReferenceEnd(SourceLocation NameLoc, const SourceManager &SM,
                                const LangOptions &LangOpts) {
   std::optional<Token> Tok = Lexer::findNextToken(NameLoc, SM, LangOpts);
@@ -101,19 +112,12 @@ bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
   if (!Node)
     return false;
 
-  for (auto *N = Node; N; N = N->Parent) {
-    const NamedDecl *Alias = nullptr;
-    if (const auto *TAD = N->ASTNode.get<TypeAliasDecl>(); TAD) {
-      Alias = TAD;
-    } else if (const auto *UD = N->ASTNode.get<UsingDecl>(); UD) {
-      Alias = UD;
-    } else {
-      continue;
-    }
-
+  auto SetFromAlias = [&](const NamedDecl *Alias) -> bool {
     if (!Alias->getIdentifier())
       return false;
 
+    llvm::DenseSet<const NamedDecl *> Targets;
+
     ReferenceLoc QualifiedRef;
     bool FoundQualifiedRef = false;
     findExplicitReferences(
@@ -128,19 +132,123 @@ bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
         },
         Inputs.AST->getHeuristicResolver());
 
-    if (!FoundQualifiedRef)
-      return false;
-
-    for (const auto *Target : QualifiedRef.Targets) {
-      if (const auto *Canonical = canonicalDecl(Target))
-        RewriteTargets.insert(Canonical);
+    if (FoundQualifiedRef) {
+      for (const auto *Target : QualifiedRef.Targets) {
+        if (const auto *Canonical = canonicalDecl(Target))
+          Targets.insert(Canonical);
+      }
+    } else if (const auto *UD = llvm::dyn_cast<UsingDecl>(Alias)) {
+      for (const auto *Shadow : UD->shadows()) {
+        if (const auto *Canonical = canonicalDecl(Shadow->getTargetDecl()))
+          Targets.insert(Canonical);
+      }
     }
-    if (RewriteTargets.empty())
+
+    if (Targets.empty())
       return false;
 
+    RewriteTargets = std::move(Targets);
     AliasName = Alias->getNameAsString();
     AliasDeclToSkip = Alias->getSourceRange();
     return true;
+  };
+
+  for (auto *N = Node; N; N = N->Parent) {
+    if (const auto *TAD = N->ASTNode.get<TypeAliasDecl>(); TAD) {
+      if (SetFromAlias(TAD))
+        return true;
+    } else if (const auto *UD = N->ASTNode.get<UsingDecl>(); UD) {
+      if (SetFromAlias(UD))
+        return true;
+    }
+  }
+
+  llvm::DenseSet<const NamedDecl *> SelectedTargets;
+  std::string SelectedName;
+  bool FoundSelectedQualifiedRef = false;
+  for (const auto &D : Inputs.AST->getLocalTopLevelDecls()) {
+    findExplicitReferences(
+        D,
+        [&](ReferenceLoc Ref) {
+          if (FoundSelectedQualifiedRef || !Ref.Qualifier || Ref.Targets.empty())
+            return;
+          if (!isNamespaceQualifier(Ref.Qualifier))
+            return;
+
+          auto &SM = Inputs.AST->getSourceManager();
+          const auto &LangOpts = Inputs.AST->getLangOpts();
+
+          SourceLocation QualifierLoc = Ref.Qualifier.getBeginLoc();
+          SourceLocation NameLoc = Ref.NameLoc;
+          if (QualifierLoc.isMacroID()) {
+            if (!SM.isMacroArgExpansion(QualifierLoc))
+              return;
+            QualifierLoc = SM.getFileLoc(QualifierLoc);
+          }
+          if (NameLoc.isMacroID()) {
+            if (!SM.isMacroArgExpansion(NameLoc))
+              return;
+            NameLoc = SM.getFileLoc(NameLoc);
+          }
+          if (SM.getFileID(QualifierLoc) != SM.getMainFileID() ||
+              SM.getFileID(NameLoc) != SM.getMainFileID())
+            return;
+
+          unsigned BeginOffset = SM.getFileOffset(QualifierLoc);
+          SourceLocation EndLoc = getReferenceEnd(NameLoc, SM, LangOpts);
+          if (BeginOffset > SM.getFileOffset(EndLoc))
+            return;
+
+          if (Inputs.SelectionBegin < BeginOffset ||
+              Inputs.SelectionBegin > SM.getFileOffset(EndLoc))
+            return;
+
+          SelectedName =
+              Lexer::getSourceText(CharSourceRange::getTokenRange(NameLoc),
+                                   SM, LangOpts)
+                  .str();
+          for (const auto *Target : Ref.Targets) {
+            if (const auto *Canonical = canonicalDecl(Target))
+              SelectedTargets.insert(Canonical);
+          }
+          FoundSelectedQualifiedRef = true;
+        },
+        Inputs.AST->getHeuristicResolver());
+    if (FoundSelectedQualifiedRef)
+      break;
+  }
+
+  if (!FoundSelectedQualifiedRef)
+    return false;
+
+  llvm::SmallVector<const UsingDecl *> VisibleUsingDecls;
+  collectUsingDecls(Inputs.AST->getASTContext().getTranslationUnitDecl(),
+                    VisibleUsingDecls);
+  auto &SM = Inputs.AST->getSourceManager();
+  for (const auto *UD : VisibleUsingDecls) {
+    if (!UD->getIdentifier())
+      continue;
+    if (!SelectedName.empty() && UD->getName() != SelectedName)
+      continue;
+    SourceLocation UDLoc = UD->getLocation();
+    if (UDLoc.isInvalid() ||
+        SM.getFileID(SM.getExpansionLoc(UDLoc)) != SM.getMainFileID())
+      continue;
+
+    bool MatchesSelection = false;
+    for (const auto *Shadow : UD->shadows()) {
+      const auto *Canonical = canonicalDecl(Shadow->getTargetDecl());
+      if (Canonical &&
+          (SelectedTargets.empty() || SelectedTargets.contains(Canonical))) {
+        MatchesSelection = true;
+        break;
+      }
+    }
+    if (!MatchesSelection)
+      continue;
+
+    if (SetFromAlias(UD))
+      return true;
   }
 
   return false;
diff --git a/clang-tools-extra/clangd/unittests/tweaks/ReplaceQualifiedWithAliasTests.cpp b/clang-tools-extra/clangd/unittests/tweaks/ReplaceQualifiedWithAliasTests.cpp
index 0b16e58e97168b..28f9fdbc2e9384 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/ReplaceQualifiedWithAliasTests.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/ReplaceQualifiedWithAliasTests.cpp
@@ -158,6 +158,73 @@ Y A;
 )cpp");
 }
 
+TEST_F(ReplaceQualifiedWithAliasTest, MustNotReplaceExistingUsingDecl) {
+  EXPECT_EQ(apply(R"cpp(
+namespace b {
+    int test1;
+}
+
+namespace d {
+    int test1;
+}
+
+namespace a {
+    using b::test1;
+
+    void foo() {
+        b::test1 = 1;
+        b::test1 = 1;
+    }
+} // namespace a
+
+namespace c {
+    using d::test1;
+} // namespace c
+
+using namespace a;
+using namespace b;
+
+void foo() {
+    b::te^st1 = 1;
+    a::test1 = 1;
+    c::test1 = 1;
+}
+
+)cpp"),
+            R"cpp(
+namespace b {
+    int test1;
+}
+
+namespace d {
+    int test1;
+}
+
+namespace a {
+    using b::test1;
+
+    void foo() {
+        test1 = 1;
+        test1 = 1;
+    }
+} // namespace a
+
+namespace c {
+    using d::test1;
+} // namespace c
+
+using namespace a;
+using namespace b;
+
+void foo() {
+    test1 = 1;
+    a::test1 = 1;
+    c::test1 = 1;
+}
+
+)cpp");
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang

>From 990750705424239f581dfe12fed7cdcb9da64b4d Mon Sep 17 00:00:00 2001
From: Dimitri Ratz <dimitri.ratz at protonmail.com>
Date: Thu, 25 Jun 2026 09:37:24 +0200
Subject: [PATCH 06/16] [clangd] Enhance AddUsingReplaceAll to handle insertion
 and replacement errors

Improves error handling in the `AddUsingReplaceAll` tweak by logging detailed error messages for insertion and replacement failures and propagating errors accordingly.
---
 .../refactor/tweaks/AddUsingReplaceAll.cpp    | 22 +++++++++++++++----
 1 file changed, 18 insertions(+), 4 deletions(-)

diff --git a/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp b/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
index b0141bb4da6b1c..ac8c06337ee6fd 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
@@ -367,8 +367,11 @@ Expected<Tweak::Effect> AddUsingReplaceAll::apply(const Selection &Inputs) {
 
   auto InsertionPoint = findInsertionPoint(Inputs, QualifierToRemove,
                                            SpelledName, MustInsertAfterLoc);
-  if (!InsertionPoint)
-    return InsertionPoint.takeError();
+  if (!InsertionPoint) {
+    std::string Msg = llvm::toString(InsertionPoint.takeError());
+    elog("AddUsingReplaceAll: {0}", Msg);
+    return error(Msg);
+  }
 
   if (InsertionPoint->Loc.isValid()) {
     std::string UsingText;
@@ -386,10 +389,14 @@ Expected<Tweak::Effect> AddUsingReplaceAll::apply(const Selection &Inputs) {
       return std::move(Err);
   }
 
+  bool HasReplacementError = false;
+  std::string ReplacementError;
   for (const auto &D : Inputs.AST->getLocalTopLevelDecls()) {
     findExplicitReferences(
         D,
         [&](ReferenceLoc Ref) {
+          if (HasReplacementError)
+            return;
           if (!Ref.Qualifier || Ref.Targets.empty() || Ref.IsDecl)
             return;
           if (!getNamespaceFromQualifier(
@@ -428,13 +435,20 @@ Expected<Tweak::Effect> AddUsingReplaceAll::apply(const Selection &Inputs) {
           if (BeginOffset >= EndOffset)
             return;
 
-          if (Repls.add(tooling::Replacement(SM, QualifierLoc,
-                                             EndOffset - BeginOffset, "")))
+          if (auto Err = Repls.add(tooling::Replacement(
+                  SM, QualifierLoc, EndOffset - BeginOffset, ""))) {
+            ReplacementError = llvm::toString(std::move(Err));
+            elog("AddUsingReplaceAll: {0}", ReplacementError);
+            HasReplacementError = true;
             return;
+          }
         },
         Inputs.AST->getHeuristicResolver());
   }
 
+  if (HasReplacementError)
+    return error(ReplacementError);
+
   return Effect::mainFileEdit(SM, std::move(Repls));
 }
 

>From 26b2214a88a691df69d294b4df9501972b4ba588 Mon Sep 17 00:00:00 2001
From: Dimitri Ratz <dimitri.ratz at protonmail.com>
Date: Thu, 25 Jun 2026 09:51:27 +0200
Subject: [PATCH 07/16] [clangd] Add comments to clarify logic in
 ReplaceQualifiedWithAlias and AddUsingReplaceAll tweaks

Adds detailed comments throughout the implementation of `ReplaceQualifiedWithAlias` and `AddUsingReplaceAll` tweaks to explain the purpose, logic, and key decisions made in the code. Improves maintainability and readability of the tweaks.
---
 .../refactor/tweaks/AddUsingReplaceAll.cpp    | 26 +++++++++++++++++++
 .../tweaks/ReplaceQualifiedWithAlias.cpp      | 22 ++++++++++++++++
 2 files changed, 48 insertions(+)

diff --git a/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp b/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
index ac8c06337ee6fd..bf4de7e03b3da0 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
@@ -53,7 +53,10 @@ class AddUsingReplaceAll : public Tweak {
   std::string QualifierToSpell;
   llvm::StringRef SpelledQualifier;
   llvm::StringRef SpelledName;
+  // The selected declaration must stay after the inserted using-declaration.
   SourceLocation MustInsertAfterLoc;
+  // Canonical declarations whose explicit qualified references will be
+  // rewritten in the main file.
   llvm::DenseSet<const NamedDecl *> RewriteTargets;
 };
 REGISTER_TWEAK(AddUsingReplaceAll)
@@ -214,6 +217,8 @@ bool AddUsingReplaceAll::prepare(const Selection &Inputs) {
   auto &SM = Inputs.AST->getSourceManager();
   const auto &TB = Inputs.AST->getTokens();
 
+  // Clear any state from a previous invocation before analyzing the new
+  // selection.
   QualifierToRemove = NestedNameSpecifierLoc();
   QualifierToSpell.clear();
   SpelledQualifier = llvm::StringRef();
@@ -225,6 +230,8 @@ bool AddUsingReplaceAll::prepare(const Selection &Inputs) {
                    Inputs.AST->getLangOpts()))
     return false;
 
+  // Normalize the selection to the outermost AST node that still represents
+  // the qualified spelling we want to rewrite.
   auto *Node = Inputs.ASTSelection.commonAncestor();
   if (!Node)
     return false;
@@ -247,6 +254,8 @@ bool AddUsingReplaceAll::prepare(const Selection &Inputs) {
     return false;
 
   SourceRange SpelledNameRange;
+  // Capture the qualified spelling, the namespace qualifier to remove, and
+  // the declaration that constrains where a new using-declaration may go.
   if (auto *D = Node->ASTNode.get<DeclRefExpr>()) {
     if (D->getDecl()->getIdentifier()) {
       QualifierToRemove = D->getQualifierLoc();
@@ -322,16 +331,22 @@ bool AddUsingReplaceAll::prepare(const Selection &Inputs) {
     default:
       break;
     }
+    // For type spellings, the qualifier is part of the type name range rather
+    // than a separate expression node.
     if (QualifierToRemove)
       SpelledNameRange.setBegin(QualifierToRemove.getBeginLoc());
   }
 
+  // Only handle fully namespace-qualified spellings that can be rewritten
+  // consistently across the file.
   if (!QualifierToRemove || RewriteTargets.empty() ||
       QualifierToRemove.getNestedNameSpecifier().getKind() !=
           NestedNameSpecifier::Kind::Namespace ||
       isNamespaceForbidden(Inputs, QualifierToRemove.getNestedNameSpecifier()))
     return false;
 
+  // Macro body expansions and cross-file spellings are too ambiguous for this
+  // refactoring.
   if (SM.isMacroBodyExpansion(QualifierToRemove.getBeginLoc()) ||
       !SM.isWrittenInSameFile(QualifierToRemove.getBeginLoc(),
                               QualifierToRemove.getEndLoc()))
@@ -345,6 +360,8 @@ bool AddUsingReplaceAll::prepare(const Selection &Inputs) {
       syntax::Token::range(SM, SpelledTokens->front(), SpelledTokens->back());
   std::tie(SpelledQualifier, SpelledName) =
       splitQualifiedName(SpelledRange.text(SM));
+  // Keep the exact source spelling for the qualifier so the inserted using
+  // matches the style of the original code.
   QualifierToSpell = getNNSLAsString(
       QualifierToRemove, Inputs.AST->getASTContext().getPrintingPolicy());
   if (!llvm::StringRef(QualifierToSpell).ends_with(SpelledQualifier) ||
@@ -356,6 +373,7 @@ bool AddUsingReplaceAll::prepare(const Selection &Inputs) {
 Expected<Tweak::Effect> AddUsingReplaceAll::apply(const Selection &Inputs) {
   auto &SM = Inputs.AST->getSourceManager();
 
+  // Fail loudly if apply() is reached without the state produced by prepare().
   const auto *TargetNamespace =
       getNamespaceFromQualifier(QualifierToRemove.getNestedNameSpecifier());
   if (!TargetNamespace)
@@ -365,6 +383,8 @@ Expected<Tweak::Effect> AddUsingReplaceAll::apply(const Selection &Inputs) {
 
   tooling::Replacements Repls;
 
+  // Find a legal insertion point based on nearby using-declarations, namespace
+  // scope, or the start of the file.
   auto InsertionPoint = findInsertionPoint(Inputs, QualifierToRemove,
                                            SpelledName, MustInsertAfterLoc);
   if (!InsertionPoint) {
@@ -374,6 +394,8 @@ Expected<Tweak::Effect> AddUsingReplaceAll::apply(const Selection &Inputs) {
   }
 
   if (InsertionPoint->Loc.isValid()) {
+    // Emit the new using-declaration with any extra qualification required by
+    // existing local style.
     std::string UsingText;
     llvm::raw_string_ostream UsingTextStream(UsingText);
     UsingTextStream << "using ";
@@ -391,6 +413,8 @@ Expected<Tweak::Effect> AddUsingReplaceAll::apply(const Selection &Inputs) {
 
   bool HasReplacementError = false;
   std::string ReplacementError;
+  // Walk every top-level declaration in the file and rewrite only the
+  // explicit references that resolve to one of the prepared targets.
   for (const auto &D : Inputs.AST->getLocalTopLevelDecls()) {
     findExplicitReferences(
         D,
@@ -435,6 +459,8 @@ Expected<Tweak::Effect> AddUsingReplaceAll::apply(const Selection &Inputs) {
           if (BeginOffset >= EndOffset)
             return;
 
+          // Drop the namespace qualifier, leaving the referenced name in
+          // place.
           if (auto Err = Repls.add(tooling::Replacement(
                   SM, QualifierLoc, EndOffset - BeginOffset, ""))) {
             ReplacementError = llvm::toString(std::move(Err));
diff --git a/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp b/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
index 83c2981819d737..acc9cab430037a 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
@@ -62,6 +62,8 @@ void collectUsingDecls(const DeclContext *DC,
   }
 }
 
+// Returns the end of a qualified reference, extending past any template
+// argument list so rewrites replace the full spelled name.
 SourceLocation getReferenceEnd(SourceLocation NameLoc, const SourceManager &SM,
                                const LangOptions &LangOpts) {
   std::optional<Token> Tok = Lexer::findNextToken(NameLoc, SM, LangOpts);
@@ -104,6 +106,7 @@ std::string ReplaceQualifiedWithAlias::title() const {
 }
 
 bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
+  // Reset all cached state before inspecting the new selection.
   AliasName.clear();
   AliasDeclToSkip = SourceRange();
   RewriteTargets.clear();
@@ -120,6 +123,8 @@ bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
 
     ReferenceLoc QualifiedRef;
     bool FoundQualifiedRef = false;
+    // Prefer the alias's own qualified reference when it exists, because it
+    // gives us the exact namespace spelling that should be rewritten.
     findExplicitReferences(
         Alias,
         [&](ReferenceLoc Ref) {
@@ -147,12 +152,15 @@ bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
     if (Targets.empty())
       return false;
 
+    // Cache the alias spelling and the canonical declarations it stands for.
     RewriteTargets = std::move(Targets);
     AliasName = Alias->getNameAsString();
     AliasDeclToSkip = Alias->getSourceRange();
     return true;
   };
 
+  // First look for an alias declaration in the current selection or one of
+  // its ancestors. This is the narrowest and most reliable source of truth.
   for (auto *N = Node; N; N = N->Parent) {
     if (const auto *TAD = N->ASTNode.get<TypeAliasDecl>(); TAD) {
       if (SetFromAlias(TAD))
@@ -166,6 +174,9 @@ bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
   llvm::DenseSet<const NamedDecl *> SelectedTargets;
   std::string SelectedName;
   bool FoundSelectedQualifiedRef = false;
+  // If the selection is a qualified reference instead of an alias, derive the
+  // target set from that reference and then search for a matching alias in the
+  // file.
   for (const auto &D : Inputs.AST->getLocalTopLevelDecls()) {
     findExplicitReferences(
         D,
@@ -203,6 +214,8 @@ bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
               Inputs.SelectionBegin > SM.getFileOffset(EndLoc))
             return;
 
+          // Record the referred-to name so we can prefer aliases with the same
+          // identifier when several are visible.
           SelectedName =
               Lexer::getSourceText(CharSourceRange::getTokenRange(NameLoc),
                                    SM, LangOpts)
@@ -225,6 +238,8 @@ bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
   collectUsingDecls(Inputs.AST->getASTContext().getTranslationUnitDecl(),
                     VisibleUsingDecls);
   auto &SM = Inputs.AST->getSourceManager();
+  // Search visible using-declarations for one that shadows the same target
+  // set, then reuse its alias spelling.
   for (const auto *UD : VisibleUsingDecls) {
     if (!UD->getIdentifier())
       continue;
@@ -259,9 +274,12 @@ ReplaceQualifiedWithAlias::apply(const Selection &Inputs) {
   auto &SM = Inputs.AST->getSourceManager();
   const auto &LangOpts = Inputs.AST->getLangOpts();
 
+  // prepare() must have populated the alias name and target set.
   if (AliasName.empty() || RewriteTargets.empty())
     return error("Incomplete prepared state for ReplaceQualifiedWithAlias");
 
+  // Skip the selected alias declaration itself so we do not rewrite the alias
+  // name inside its own definition.
   SourceLocation SkipBegin = AliasDeclToSkip.getBegin();
   SourceLocation SkipEnd = AliasDeclToSkip.getEnd();
   if (SkipBegin.isValid())
@@ -270,6 +288,8 @@ ReplaceQualifiedWithAlias::apply(const Selection &Inputs) {
     SkipEnd = SM.getExpansionLoc(SkipEnd);
 
   tooling::Replacements Repls;
+  // Rewrite every explicit namespace-qualified reference that resolves to one
+  // of the canonical declarations represented by the alias.
   for (const auto &D : Inputs.AST->getLocalTopLevelDecls()) {
     findExplicitReferences(
         D,
@@ -306,6 +326,7 @@ ReplaceQualifiedWithAlias::apply(const Selection &Inputs) {
               SM.getFileID(NameLoc) != SM.getMainFileID())
             return;
 
+          // Leave the selected alias definition untouched.
           if (SkipBegin.isValid() && SkipEnd.isValid() &&
               SM.isPointWithin(NameLoc, SkipBegin, SkipEnd))
             return;
@@ -315,6 +336,7 @@ ReplaceQualifiedWithAlias::apply(const Selection &Inputs) {
           if (BeginOffset > SM.getFileOffset(EndLoc))
             return;
 
+          // Replace the qualified spelling with the alias name only.
           if (auto Err = Repls.add(tooling::Replacement(
                   SM, QualifierLoc, SM.getFileOffset(EndLoc) - BeginOffset,
                   AliasName)))

>From dbdbb2bff97a2d9ddfe526e802633213f16c067a Mon Sep 17 00:00:00 2001
From: Dimitri Ratz <dimitri.ratz at protonmail.com>
Date: Thu, 25 Jun 2026 10:08:02 +0200
Subject: [PATCH 08/16] [clangd] Fix format.

---
 .../clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp   | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp b/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
index acc9cab430037a..cf9d7c0495da82 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
@@ -181,7 +181,8 @@ bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
     findExplicitReferences(
         D,
         [&](ReferenceLoc Ref) {
-          if (FoundSelectedQualifiedRef || !Ref.Qualifier || Ref.Targets.empty())
+          if (FoundSelectedQualifiedRef || !Ref.Qualifier ||
+              Ref.Targets.empty())
             return;
           if (!isNamespaceQualifier(Ref.Qualifier))
             return;
@@ -217,8 +218,8 @@ bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
           // Record the referred-to name so we can prefer aliases with the same
           // identifier when several are visible.
           SelectedName =
-              Lexer::getSourceText(CharSourceRange::getTokenRange(NameLoc),
-                                   SM, LangOpts)
+              Lexer::getSourceText(CharSourceRange::getTokenRange(NameLoc), SM,
+                                   LangOpts)
                   .str();
           for (const auto *Target : Ref.Targets) {
             if (const auto *Canonical = canonicalDecl(Target))

>From 38453073dff0c125b627fa669f92265d7189f9e1 Mon Sep 17 00:00:00 2001
From: Dimitri Ratz <dimitri.ratz at protonmail.com>
Date: Wed, 8 Jul 2026 16:10:50 +0200
Subject: [PATCH 09/16] [clangd] Speed up ReplaceQualifiedWithAlias::prepare()
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

prepare() is called on every cursor movement to determine which tweaks
are available. It must be fast. Previously, prepare() iterated over
every top-level declaration in the file and called findExplicitReferences()
on each one — a full O(file-size) AST traversal — and then apply() repeated
this exact traversal to generate replacements.

This commit eliminates the duplicate traversal:

- prepare() now scopes its findExplicitReferences() call to the single
  Decl or Stmt that directly contains the selected cursor position.
  This resolves the target canonical declarations of the selected
  qualified reference in O(selection-scope) time.

- To verify a matching using-declaration exists, prepare() calls
  collectUsingDecls() (which only walks declarations, not expressions or
  statements) and checks alias targets via collectAliasTargets(). This
  avoids calling findExplicitReferences() on the whole file in prepare().

- apply() performs the one necessary full-file findExplicitReferences()
  traversal to rewrite all occurrences.

The net effect is that the expensive full-file traversal runs exactly
once (in apply()) instead of twice (in prepare() and apply()).

A helper collectAliasTargets() is extracted to share the alias-target
resolution logic between the alias-selected and reference-selected paths.
---
 .../refactor/tweaks/AddUsingReplaceAll.cpp    |   4 +-
 .../tweaks/ReplaceQualifiedWithAlias.cpp      | 227 ++++++++++--------
 2 files changed, 125 insertions(+), 106 deletions(-)

diff --git a/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp b/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
index bf4de7e03b3da0..ec2da8a3853a41 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
@@ -32,9 +32,9 @@ namespace clang {
 namespace clangd {
 
 /// Tweak for removing the full namespace qualifier under the cursor on
-/// DeclRefExpr and types and adding "using" statement instead. This tweak
+/// DeclRefExpr and types and adding the "using" statement instead. This tweak
 /// replaces all occurrences of the qualified symbol in the file, not just the
-/// one under the cursor, but it also requires more preparation and is more
+/// one under the cursor. However, it also requires more preparation and is more
 /// expensive to compute, so it is hidden behind a separate action from
 /// AddUsing, which only removes the qualifier under the cursor.
 class AddUsingReplaceAll : public Tweak {
diff --git a/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp b/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
index cf9d7c0495da82..6d1decd010ad31 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
@@ -39,6 +39,8 @@ class ReplaceQualifiedWithAlias : public Tweak {
 private:
   std::string AliasName;
   SourceRange AliasDeclToSkip;
+  llvm::DenseSet<const NamedDecl *> SelectedTargets;
+  std::string SelectedName;
   llvm::DenseSet<const NamedDecl *> RewriteTargets;
 };
 REGISTER_TWEAK(ReplaceQualifiedWithAlias)
@@ -62,6 +64,45 @@ void collectUsingDecls(const DeclContext *DC,
   }
 }
 
+bool collectAliasTargets(const NamedDecl *Alias, const Tweak::Selection &Inputs,
+                         llvm::DenseSet<const NamedDecl *> &Targets);
+
+bool collectAliasTargets(const NamedDecl *Alias, const Tweak::Selection &Inputs,
+                         llvm::DenseSet<const NamedDecl *> &Targets) {
+  ReferenceLoc QualifiedRef;
+  bool FoundQualifiedRef = false;
+  // Prefer the alias's own qualified reference when it exists, because it
+  // gives us the exact namespace spelling that should be rewritten.
+  findExplicitReferences(
+      Alias,
+      [&](ReferenceLoc Ref) {
+        if (FoundQualifiedRef || !Ref.Qualifier || Ref.Targets.empty())
+          return;
+        if (!isNamespaceQualifier(Ref.Qualifier))
+          return;
+        QualifiedRef = std::move(Ref);
+        FoundQualifiedRef = true;
+      },
+      Inputs.AST->getHeuristicResolver());
+
+  if (FoundQualifiedRef) {
+    for (const auto *Target : QualifiedRef.Targets) {
+      if (const auto *Canonical = canonicalDecl(Target))
+        Targets.insert(Canonical);
+    }
+    return !Targets.empty();
+  }
+
+  if (const auto *UD = llvm::dyn_cast<UsingDecl>(Alias)) {
+    for (const auto *Shadow : UD->shadows()) {
+      if (const auto *Canonical = canonicalDecl(Shadow->getTargetDecl()))
+        Targets.insert(Canonical);
+    }
+  }
+
+  return !Targets.empty();
+}
+
 // Returns the end of a qualified reference, extending past any template
 // argument list so rewrites replace the full spelled name.
 SourceLocation getReferenceEnd(SourceLocation NameLoc, const SourceManager &SM,
@@ -109,6 +150,8 @@ bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
   // Reset all cached state before inspecting the new selection.
   AliasName.clear();
   AliasDeclToSkip = SourceRange();
+  SelectedTargets.clear();
+  SelectedName.clear();
   RewriteTargets.clear();
 
   auto *Node = Inputs.ASTSelection.commonAncestor();
@@ -120,36 +163,7 @@ bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
       return false;
 
     llvm::DenseSet<const NamedDecl *> Targets;
-
-    ReferenceLoc QualifiedRef;
-    bool FoundQualifiedRef = false;
-    // Prefer the alias's own qualified reference when it exists, because it
-    // gives us the exact namespace spelling that should be rewritten.
-    findExplicitReferences(
-        Alias,
-        [&](ReferenceLoc Ref) {
-          if (FoundQualifiedRef || !Ref.Qualifier || Ref.Targets.empty())
-            return;
-          if (!isNamespaceQualifier(Ref.Qualifier))
-            return;
-          QualifiedRef = std::move(Ref);
-          FoundQualifiedRef = true;
-        },
-        Inputs.AST->getHeuristicResolver());
-
-    if (FoundQualifiedRef) {
-      for (const auto *Target : QualifiedRef.Targets) {
-        if (const auto *Canonical = canonicalDecl(Target))
-          Targets.insert(Canonical);
-      }
-    } else if (const auto *UD = llvm::dyn_cast<UsingDecl>(Alias)) {
-      for (const auto *Shadow : UD->shadows()) {
-        if (const auto *Canonical = canonicalDecl(Shadow->getTargetDecl()))
-          Targets.insert(Canonical);
-      }
-    }
-
-    if (Targets.empty())
+    if (!collectAliasTargets(Alias, Inputs, Targets))
       return false;
 
     // Cache the alias spelling and the canonical declarations it stands for.
@@ -159,6 +173,66 @@ bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
     return true;
   };
 
+  auto FindSelectedQualifiedRef = [&](const SelectionTree::Node *N) -> bool {
+    const SelectionTree::Node *Root = N;
+    while (Root && !Root->ASTNode.get<Decl>() && !Root->ASTNode.get<Stmt>())
+      Root = Root->Parent;
+    if (!Root)
+      return false;
+
+    bool FoundSelectedQualifiedRef = false;
+    auto ReportRef = [&](ReferenceLoc Ref) {
+      if (FoundSelectedQualifiedRef || !Ref.Qualifier || Ref.Targets.empty())
+        return;
+      if (!isNamespaceQualifier(Ref.Qualifier))
+        return;
+
+      auto &SM = Inputs.AST->getSourceManager();
+      const auto &LangOpts = Inputs.AST->getLangOpts();
+
+      SourceLocation QualifierLoc = Ref.Qualifier.getBeginLoc();
+      SourceLocation NameLoc = Ref.NameLoc;
+      if (QualifierLoc.isMacroID()) {
+        if (!SM.isMacroArgExpansion(QualifierLoc))
+          return;
+        QualifierLoc = SM.getFileLoc(QualifierLoc);
+      }
+      if (NameLoc.isMacroID()) {
+        if (!SM.isMacroArgExpansion(NameLoc))
+          return;
+        NameLoc = SM.getFileLoc(NameLoc);
+      }
+      if (SM.getFileID(QualifierLoc) != SM.getMainFileID() ||
+          SM.getFileID(NameLoc) != SM.getMainFileID())
+        return;
+
+      unsigned BeginOffset = SM.getFileOffset(QualifierLoc);
+      SourceLocation EndLoc = getReferenceEnd(NameLoc, SM, LangOpts);
+      if (BeginOffset > SM.getFileOffset(EndLoc))
+        return;
+
+      if (Inputs.SelectionBegin < BeginOffset ||
+          Inputs.SelectionBegin > SM.getFileOffset(EndLoc))
+        return;
+
+      SelectedName = Lexer::getSourceText(
+                         CharSourceRange::getTokenRange(NameLoc), SM, LangOpts)
+                         .str();
+      for (const auto *Target : Ref.Targets) {
+        if (const auto *Canonical = canonicalDecl(Target))
+          SelectedTargets.insert(Canonical);
+      }
+      FoundSelectedQualifiedRef = true;
+    };
+
+    if (const auto *D = Root->ASTNode.get<Decl>()) {
+      findExplicitReferences(D, ReportRef, Inputs.AST->getHeuristicResolver());
+    } else if (const auto *S = Root->ASTNode.get<Stmt>()) {
+      findExplicitReferences(S, ReportRef, Inputs.AST->getHeuristicResolver());
+    }
+    return FoundSelectedQualifiedRef;
+  };
+
   // First look for an alias declaration in the current selection or one of
   // its ancestors. This is the narrowest and most reliable source of truth.
   for (auto *N = Node; N; N = N->Parent) {
@@ -171,77 +245,18 @@ bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
     }
   }
 
-  llvm::DenseSet<const NamedDecl *> SelectedTargets;
-  std::string SelectedName;
-  bool FoundSelectedQualifiedRef = false;
-  // If the selection is a qualified reference instead of an alias, derive the
-  // target set from that reference and then search for a matching alias in the
-  // file.
-  for (const auto &D : Inputs.AST->getLocalTopLevelDecls()) {
-    findExplicitReferences(
-        D,
-        [&](ReferenceLoc Ref) {
-          if (FoundSelectedQualifiedRef || !Ref.Qualifier ||
-              Ref.Targets.empty())
-            return;
-          if (!isNamespaceQualifier(Ref.Qualifier))
-            return;
-
-          auto &SM = Inputs.AST->getSourceManager();
-          const auto &LangOpts = Inputs.AST->getLangOpts();
-
-          SourceLocation QualifierLoc = Ref.Qualifier.getBeginLoc();
-          SourceLocation NameLoc = Ref.NameLoc;
-          if (QualifierLoc.isMacroID()) {
-            if (!SM.isMacroArgExpansion(QualifierLoc))
-              return;
-            QualifierLoc = SM.getFileLoc(QualifierLoc);
-          }
-          if (NameLoc.isMacroID()) {
-            if (!SM.isMacroArgExpansion(NameLoc))
-              return;
-            NameLoc = SM.getFileLoc(NameLoc);
-          }
-          if (SM.getFileID(QualifierLoc) != SM.getMainFileID() ||
-              SM.getFileID(NameLoc) != SM.getMainFileID())
-            return;
-
-          unsigned BeginOffset = SM.getFileOffset(QualifierLoc);
-          SourceLocation EndLoc = getReferenceEnd(NameLoc, SM, LangOpts);
-          if (BeginOffset > SM.getFileOffset(EndLoc))
-            return;
-
-          if (Inputs.SelectionBegin < BeginOffset ||
-              Inputs.SelectionBegin > SM.getFileOffset(EndLoc))
-            return;
-
-          // Record the referred-to name so we can prefer aliases with the same
-          // identifier when several are visible.
-          SelectedName =
-              Lexer::getSourceText(CharSourceRange::getTokenRange(NameLoc), SM,
-                                   LangOpts)
-                  .str();
-          for (const auto *Target : Ref.Targets) {
-            if (const auto *Canonical = canonicalDecl(Target))
-              SelectedTargets.insert(Canonical);
-          }
-          FoundSelectedQualifiedRef = true;
-        },
-        Inputs.AST->getHeuristicResolver());
-    if (FoundSelectedQualifiedRef)
-      break;
-  }
-
-  if (!FoundSelectedQualifiedRef)
+  if (!FindSelectedQualifiedRef(Node))
     return false;
 
-  llvm::SmallVector<const UsingDecl *> VisibleUsingDecls;
-  collectUsingDecls(Inputs.AST->getASTContext().getTranslationUnitDecl(),
-                    VisibleUsingDecls);
+  // Search the file for a using-declaration that covers the selected reference.
+  // This avoids a full findExplicitReferences() traversal of the whole file;
+  // collectUsingDecls() only walks declarations, not expressions or statements.
+  // The expensive per-occurrence rewrite is deferred to apply().
   auto &SM = Inputs.AST->getSourceManager();
-  // Search visible using-declarations for one that shadows the same target
-  // set, then reuse its alias spelling.
-  for (const auto *UD : VisibleUsingDecls) {
+  llvm::SmallVector<const UsingDecl *> FileUsingDecls;
+  collectUsingDecls(Inputs.AST->getASTContext().getTranslationUnitDecl(),
+                    FileUsingDecls);
+  for (const auto *UD : FileUsingDecls) {
     if (!UD->getIdentifier())
       continue;
     if (!SelectedName.empty() && UD->getName() != SelectedName)
@@ -251,11 +266,13 @@ bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
         SM.getFileID(SM.getExpansionLoc(UDLoc)) != SM.getMainFileID())
       continue;
 
+    llvm::DenseSet<const NamedDecl *> AliasTargets;
+    if (!collectAliasTargets(UD, Inputs, AliasTargets))
+      continue;
+
     bool MatchesSelection = false;
-    for (const auto *Shadow : UD->shadows()) {
-      const auto *Canonical = canonicalDecl(Shadow->getTargetDecl());
-      if (Canonical &&
-          (SelectedTargets.empty() || SelectedTargets.contains(Canonical))) {
+    for (const auto *Target : AliasTargets) {
+      if (SelectedTargets.contains(Target)) {
         MatchesSelection = true;
         break;
       }
@@ -263,8 +280,10 @@ bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
     if (!MatchesSelection)
       continue;
 
-    if (SetFromAlias(UD))
-      return true;
+    RewriteTargets = std::move(AliasTargets);
+    AliasName = UD->getNameAsString();
+    AliasDeclToSkip = UD->getSourceRange();
+    return true;
   }
 
   return false;

>From 0baf711b93669fa88501bcc97c3c1eddb2e6be3a Mon Sep 17 00:00:00 2001
From: Dimitri Ratz <dimitri.ratz at protonmail.com>
Date: Mon, 26 Oct 2026 11:04:35 +0100
Subject: [PATCH 10/16] [clangd] Refactor AddUsingReplaceAll and
 ReplaceQualifiedWithAlias to share common logic for rewriting
 namespace-qualified references

---
 clang-tools-extra/CMakeLists.txt              |   1 +
 .../refactor/tweaks/AddUsingReplaceAll.cpp    | 246 ++-----------
 .../clangd/refactor/tweaks/CMakeLists.txt     |   1 +
 .../refactor/tweaks/QualifiedNameRewrite.cpp  | 331 ++++++++++++++++++
 .../refactor/tweaks/QualifiedNameRewrite.h    | 110 ++++++
 .../tweaks/ReplaceQualifiedWithAlias.cpp      | 239 +++----------
 6 files changed, 515 insertions(+), 413 deletions(-)
 create mode 100644 clang-tools-extra/clangd/refactor/tweaks/QualifiedNameRewrite.cpp
 create mode 100644 clang-tools-extra/clangd/refactor/tweaks/QualifiedNameRewrite.h

diff --git a/clang-tools-extra/CMakeLists.txt b/clang-tools-extra/CMakeLists.txt
index 87050db4e0e75f..19e06d4416bd93 100644
--- a/clang-tools-extra/CMakeLists.txt
+++ b/clang-tools-extra/CMakeLists.txt
@@ -30,6 +30,7 @@ add_subdirectory(clang-query)
 add_subdirectory(include-cleaner)
 add_subdirectory(pp-trace)
 add_subdirectory(tool-template)
+add_subdirectory(cpp-lens)
 
 option(CLANG_TOOLS_EXTRA_INCLUDE_DOCS "Generate build targets for the Clang Extra Tools docs."
   ${LLVM_INCLUDE_DOCS})
diff --git a/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp b/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
index ec2da8a3853a41..0979f6b0555c7b 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
@@ -9,6 +9,7 @@
 #include "AST.h"
 #include "Config.h"
 #include "FindTarget.h"
+#include "QualifiedNameRewrite.h"
 #include "SourceCode.h"
 #include "refactor/Tweak.h"
 #include "support/Logger.h"
@@ -71,7 +72,7 @@ std::string AddUsingReplaceAll::title() const {
 /// DeclContext chain directly, sorted by source location. This avoids a full
 /// AST traversal and only visits O(depth * declarations-per-scope) nodes.
 ///
-/// A using-declaration declared in a scope S is visible at SelectionCtx iff
+/// A using-declaration declared in a scope S is visible at SelectionCtx if
 /// S is an ancestor of SelectionCtx, i.e., exactly the contexts we walk when
 /// ascending via getLexicalParent().
 static std::vector<const UsingDecl *>
@@ -102,14 +103,6 @@ struct InsertionPointData {
   bool AlwaysFullyQualify = false;
 };
 
-static const NamespaceDecl *
-getNamespaceFromQualifier(NestedNameSpecifier Qualifier) {
-  if (!Qualifier || Qualifier.getKind() != NestedNameSpecifier::Kind::Namespace)
-    return nullptr;
-  return dyn_cast_or_null<NamespaceDecl>(
-      Qualifier.getAsNamespaceAndPrefix().Namespace);
-}
-
 static llvm::Expected<InsertionPointData>
 findInsertionPoint(const Tweak::Selection &Inputs,
                    const NestedNameSpecifierLoc &QualifierToRemove,
@@ -201,21 +194,8 @@ static bool isNamespaceForbidden(const Tweak::Selection &Inputs,
   return false;
 }
 
-static std::string getNNSLAsString(NestedNameSpecifierLoc NNSL,
-                                   const PrintingPolicy &Policy) {
-  std::string Out;
-  llvm::raw_string_ostream OutStream(Out);
-  NNSL.getNestedNameSpecifier().print(OutStream, Policy);
-  return OutStream.str();
-}
-
-static const NamedDecl *canonicalDecl(const NamedDecl *D) {
-  return D ? llvm::dyn_cast<NamedDecl>(D->getCanonicalDecl()) : nullptr;
-}
-
 bool AddUsingReplaceAll::prepare(const Selection &Inputs) {
   auto &SM = Inputs.AST->getSourceManager();
-  const auto &TB = Inputs.AST->getTokens();
 
   // Clear any state from a previous invocation before analyzing the new
   // selection.
@@ -230,143 +210,19 @@ bool AddUsingReplaceAll::prepare(const Selection &Inputs) {
                    Inputs.AST->getLangOpts()))
     return false;
 
-  // Normalize the selection to the outermost AST node that still represents
-  // the qualified spelling we want to rewrite.
-  auto *Node = Inputs.ASTSelection.commonAncestor();
-  if (!Node)
+  const auto &Prepared = prepareQualifiedSelection(
+      Inputs, QualifiedRewriteClient::AddUsingReplaceAll);
+  if (!Prepared.HasQualifiedRef ||
+      isNamespaceForbidden(
+          Inputs, Prepared.QualifierToRemove.getNestedNameSpecifier()))
     return false;
 
-  for (; Node->Parent; Node = Node->Parent) {
-    if (Node->ASTNode.get<NestedNameSpecifierLoc>())
-      continue;
-    if (auto *T = Node->ASTNode.get<TypeLoc>()) {
-      if (Node->Parent->ASTNode.get<NestedNameSpecifierLoc>())
-        continue;
-      if (isa<TagType, TemplateSpecializationType, TypedefType, UsingType,
-              UnresolvedUsingType>(T->getTypePtr()))
-        break;
-      if (Node->Parent->ASTNode.get<TypeLoc>())
-        continue;
-    }
-    break;
-  }
-  if (!Node)
-    return false;
-
-  SourceRange SpelledNameRange;
-  // Capture the qualified spelling, the namespace qualifier to remove, and
-  // the declaration that constrains where a new using-declaration may go.
-  if (auto *D = Node->ASTNode.get<DeclRefExpr>()) {
-    if (D->getDecl()->getIdentifier()) {
-      QualifierToRemove = D->getQualifierLoc();
-      SpelledNameRange = D->getSourceRange();
-      if (auto AngleLoc = D->getLAngleLoc(); AngleLoc.isValid())
-        SpelledNameRange.setEnd(AngleLoc.getLocWithOffset(-1));
-      MustInsertAfterLoc = D->getDecl()->getBeginLoc();
-      if (const auto *Canonical = canonicalDecl(D->getDecl()))
-        RewriteTargets.insert(Canonical);
-    }
-  } else if (auto *T = Node->ASTNode.get<TypeLoc>()) {
-    switch (T->getTypeLocClass()) {
-    case TypeLoc::TemplateSpecialization: {
-      auto TL = T->castAs<TemplateSpecializationTypeLoc>();
-      QualifierToRemove = TL.getQualifierLoc();
-      if (!QualifierToRemove)
-        break;
-      SpelledNameRange = TL.getTemplateNameLoc();
-      if (auto *TD = TL.getTypePtr()->getTemplateName().getAsTemplateDecl(
-              /*IgnoreDeduced=*/true)) {
-        MustInsertAfterLoc = TD->getBeginLoc();
-        if (const auto *Canonical = canonicalDecl(TD))
-          RewriteTargets.insert(Canonical);
-      }
-      break;
-    }
-    case TypeLoc::Enum:
-    case TypeLoc::Record:
-    case TypeLoc::InjectedClassName: {
-      auto TL = T->castAs<TagTypeLoc>();
-      QualifierToRemove = TL.getQualifierLoc();
-      if (!QualifierToRemove)
-        break;
-      SpelledNameRange = TL.getNameLoc();
-      MustInsertAfterLoc = TL.getDecl()->getBeginLoc();
-      if (const auto *Canonical = canonicalDecl(TL.getDecl()))
-        RewriteTargets.insert(Canonical);
-      break;
-    }
-    case TypeLoc::Typedef: {
-      auto TL = T->castAs<TypedefTypeLoc>();
-      QualifierToRemove = TL.getQualifierLoc();
-      if (!QualifierToRemove)
-        break;
-      SpelledNameRange = TL.getNameLoc();
-      MustInsertAfterLoc = TL.getDecl()->getBeginLoc();
-      if (const auto *Canonical = canonicalDecl(TL.getDecl()))
-        RewriteTargets.insert(Canonical);
-      break;
-    }
-    case TypeLoc::UnresolvedUsing: {
-      auto TL = T->castAs<UnresolvedUsingTypeLoc>();
-      QualifierToRemove = TL.getQualifierLoc();
-      if (!QualifierToRemove)
-        break;
-      SpelledNameRange = TL.getNameLoc();
-      MustInsertAfterLoc = TL.getDecl()->getBeginLoc();
-      if (const auto *Canonical = canonicalDecl(TL.getDecl()))
-        RewriteTargets.insert(Canonical);
-      break;
-    }
-    case TypeLoc::Using: {
-      auto TL = T->castAs<UsingTypeLoc>();
-      QualifierToRemove = TL.getQualifierLoc();
-      if (!QualifierToRemove)
-        break;
-      SpelledNameRange = TL.getNameLoc();
-      MustInsertAfterLoc = TL.getDecl()->getBeginLoc();
-      if (const auto *Canonical = canonicalDecl(TL.getDecl()))
-        RewriteTargets.insert(Canonical);
-      break;
-    }
-    default:
-      break;
-    }
-    // For type spellings, the qualifier is part of the type name range rather
-    // than a separate expression node.
-    if (QualifierToRemove)
-      SpelledNameRange.setBegin(QualifierToRemove.getBeginLoc());
-  }
-
-  // Only handle fully namespace-qualified spellings that can be rewritten
-  // consistently across the file.
-  if (!QualifierToRemove || RewriteTargets.empty() ||
-      QualifierToRemove.getNestedNameSpecifier().getKind() !=
-          NestedNameSpecifier::Kind::Namespace ||
-      isNamespaceForbidden(Inputs, QualifierToRemove.getNestedNameSpecifier()))
-    return false;
-
-  // Macro body expansions and cross-file spellings are too ambiguous for this
-  // refactoring.
-  if (SM.isMacroBodyExpansion(QualifierToRemove.getBeginLoc()) ||
-      !SM.isWrittenInSameFile(QualifierToRemove.getBeginLoc(),
-                              QualifierToRemove.getEndLoc()))
-    return false;
-
-  auto SpelledTokens =
-      TB.spelledForExpanded(TB.expandedTokens(SpelledNameRange));
-  if (!SpelledTokens)
-    return false;
-  auto SpelledRange =
-      syntax::Token::range(SM, SpelledTokens->front(), SpelledTokens->back());
-  std::tie(SpelledQualifier, SpelledName) =
-      splitQualifiedName(SpelledRange.text(SM));
-  // Keep the exact source spelling for the qualifier so the inserted using
-  // matches the style of the original code.
-  QualifierToSpell = getNNSLAsString(
-      QualifierToRemove, Inputs.AST->getASTContext().getPrintingPolicy());
-  if (!llvm::StringRef(QualifierToSpell).ends_with(SpelledQualifier) ||
-      SpelledName.empty())
-    return false;
+  QualifierToRemove = Prepared.QualifierToRemove;
+  QualifierToSpell = Prepared.QualifierToSpell;
+  SpelledQualifier = Prepared.SpelledQualifier;
+  SpelledName = Prepared.SpelledName;
+  MustInsertAfterLoc = Prepared.MustInsertAfterLoc;
+  RewriteTargets = Prepared.Targets;
   return true;
 }
 
@@ -415,62 +271,26 @@ Expected<Tweak::Effect> AddUsingReplaceAll::apply(const Selection &Inputs) {
   std::string ReplacementError;
   // Walk every top-level declaration in the file and rewrite only the
   // explicit references that resolve to one of the prepared targets.
-  for (const auto &D : Inputs.AST->getLocalTopLevelDecls()) {
-    findExplicitReferences(
-        D,
-        [&](ReferenceLoc Ref) {
-          if (HasReplacementError)
-            return;
-          if (!Ref.Qualifier || Ref.Targets.empty() || Ref.IsDecl)
-            return;
-          if (!getNamespaceFromQualifier(
-                  Ref.Qualifier.getNestedNameSpecifier()))
-            return;
-
-          SourceLocation QualifierLoc = Ref.Qualifier.getBeginLoc();
-          SourceLocation NameLoc = Ref.NameLoc;
-          if (QualifierLoc.isMacroID()) {
-            if (!SM.isMacroArgExpansion(QualifierLoc))
-              return;
-            QualifierLoc = SM.getFileLoc(QualifierLoc);
-          }
-          if (NameLoc.isMacroID()) {
-            if (!SM.isMacroArgExpansion(NameLoc))
-              return;
-            NameLoc = SM.getFileLoc(NameLoc);
-          }
-          if (SM.getFileID(QualifierLoc) != SM.getMainFileID() ||
-              SM.getFileID(NameLoc) != SM.getMainFileID())
-            return;
-
-          bool MatchesTarget = false;
-          for (const auto *Target : Ref.Targets) {
-            if (const auto *Canonical = canonicalDecl(Target);
-                Canonical && RewriteTargets.contains(Canonical)) {
-              MatchesTarget = true;
-              break;
-            }
-          }
-          if (!MatchesTarget)
-            return;
-
-          unsigned BeginOffset = SM.getFileOffset(QualifierLoc);
-          unsigned EndOffset = SM.getFileOffset(NameLoc);
-          if (BeginOffset >= EndOffset)
-            return;
-
-          // Drop the namespace qualifier, leaving the referenced name in
-          // place.
-          if (auto Err = Repls.add(tooling::Replacement(
-                  SM, QualifierLoc, EndOffset - BeginOffset, ""))) {
-            ReplacementError = llvm::toString(std::move(Err));
-            elog("AddUsingReplaceAll: {0}", ReplacementError);
-            HasReplacementError = true;
-            return;
-          }
-        },
-        Inputs.AST->getHeuristicResolver());
-  }
+  forEachQualifiedReferenceToRewrite(
+      Inputs, RewriteTargets, [&](const QualifiedReference &Ref) {
+        if (HasReplacementError)
+          return;
+
+        unsigned BeginOffset = SM.getFileOffset(Ref.QualifierLoc);
+        unsigned EndOffset = SM.getFileOffset(Ref.NameLoc);
+        if (BeginOffset >= EndOffset)
+          return;
+
+        // Drop the namespace qualifier, leaving the referenced name in
+        // place.
+        if (auto Err = Repls.add(tooling::Replacement(
+                SM, Ref.QualifierLoc, EndOffset - BeginOffset, ""))) {
+          ReplacementError = llvm::toString(std::move(Err));
+          elog("AddUsingReplaceAll: {0}", ReplacementError);
+          HasReplacementError = true;
+          return;
+        }
+      });
 
   if (HasReplacementError)
     return error(ReplacementError);
diff --git a/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt b/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
index 38a1a166524278..bf3f56cfaf35ee 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
+++ b/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
@@ -27,6 +27,7 @@ add_clang_library(clangDaemonTweaks OBJECT
   ObjCMemberwiseInitializer.cpp
   OverridePureVirtuals.cpp
   PopulateSwitch.cpp
+  QualifiedNameRewrite.cpp
   RawStringLiteral.cpp
   ReplaceQualifiedWithAlias.cpp
   RemoveUsingNamespace.cpp
diff --git a/clang-tools-extra/clangd/refactor/tweaks/QualifiedNameRewrite.cpp b/clang-tools-extra/clangd/refactor/tweaks/QualifiedNameRewrite.cpp
new file mode 100644
index 00000000000000..93e797365a97e4
--- /dev/null
+++ b/clang-tools-extra/clangd/refactor/tweaks/QualifiedNameRewrite.cpp
@@ -0,0 +1,331 @@
+//===--- QualifiedNameRewrite.cpp -------------------------------*- C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "QualifiedNameRewrite.h"
+
+#include "AST.h"
+#include "ParsedAST.h"
+
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclBase.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/TypeLoc.h"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Tooling/Syntax/Tokens.h"
+#include "llvm/Support/Casting.h"
+#include "llvm/Support/raw_ostream.h"
+#include <tuple>
+
+namespace clang {
+namespace clangd {
+
+const NamedDecl *canonicalDecl(const NamedDecl *D) {
+  return D ? llvm::dyn_cast<NamedDecl>(D->getCanonicalDecl()) : nullptr;
+}
+
+bool isNamespaceQualifier(NestedNameSpecifierLoc Qualifier) {
+  return Qualifier && Qualifier.getNestedNameSpecifier().getKind() ==
+                          NestedNameSpecifier::Kind::Namespace;
+}
+
+const NamespaceDecl *getNamespaceFromQualifier(NestedNameSpecifier Qualifier) {
+  if (!Qualifier || Qualifier.getKind() != NestedNameSpecifier::Kind::Namespace)
+    return nullptr;
+  return llvm::dyn_cast_or_null<NamespaceDecl>(
+      Qualifier.getAsNamespaceAndPrefix().Namespace);
+}
+
+bool normalizeToMainFile(SourceLocation &Loc, const SourceManager &SM) {
+  if (Loc.isMacroID()) {
+    if (!SM.isMacroArgExpansion(Loc))
+      return false;
+    Loc = SM.getFileLoc(Loc);
+  }
+  return SM.getFileID(Loc) == SM.getMainFileID();
+}
+
+bool referenceMatchesTargets(const ReferenceLoc &Ref,
+                             const llvm::DenseSet<const NamedDecl *> &Targets) {
+  for (const auto *Target : Ref.Targets) {
+    if (const auto *Canonical = canonicalDecl(Target);
+        Canonical && Targets.contains(Canonical))
+      return true;
+  }
+  return false;
+}
+
+SourceLocation getReferenceEnd(SourceLocation NameLoc, const SourceManager &SM,
+                               const LangOptions &LangOpts) {
+  std::optional<Token> Tok = Lexer::findNextToken(NameLoc, SM, LangOpts);
+  if (!Tok || Tok->isNot(tok::less))
+    return Lexer::getLocForEndOfToken(NameLoc, 0, SM, LangOpts);
+
+  unsigned Depth = 0;
+  while (Tok) {
+    switch (Tok->getKind()) {
+    case tok::less:
+      ++Depth;
+      break;
+    case tok::greater:
+      if (Depth == 0)
+        return Lexer::getLocForEndOfToken(Tok->getLocation(), 0, SM, LangOpts);
+      --Depth;
+      if (Depth == 0)
+        return Lexer::getLocForEndOfToken(Tok->getLocation(), 0, SM, LangOpts);
+      break;
+    case tok::greatergreater:
+      if (Depth <= 1)
+        return Lexer::getLocForEndOfToken(Tok->getLocation(), 0, SM, LangOpts);
+      Depth -= 2;
+      if (Depth == 0)
+        return Lexer::getLocForEndOfToken(Tok->getLocation(), 0, SM, LangOpts);
+      break;
+    default:
+      if (Depth == 0)
+        return Lexer::getLocForEndOfToken(Tok->getLocation(), 0, SM, LangOpts);
+      break;
+    }
+    Tok = Lexer::findNextToken(Tok->getLocation(), SM, LangOpts);
+  }
+  return Lexer::getLocForEndOfToken(NameLoc, 0, SM, LangOpts);
+}
+
+void forEachQualifiedReferenceToRewrite(
+    const Tweak::Selection &Inputs,
+    const llvm::DenseSet<const NamedDecl *> &Targets,
+    llvm::function_ref<void(const QualifiedReference &)> Callback) {
+  auto &SM = Inputs.AST->getSourceManager();
+
+  for (const auto *D : Inputs.AST->getLocalTopLevelDecls()) {
+    findExplicitReferences(
+        D,
+        [&](ReferenceLoc Ref) {
+          if (!Ref.Qualifier || Ref.Targets.empty() || Ref.IsDecl)
+            return;
+          if (!isNamespaceQualifier(Ref.Qualifier))
+            return;
+          if (!referenceMatchesTargets(Ref, Targets))
+            return;
+
+          QualifiedReference QRef;
+          QRef.QualifierLoc = Ref.Qualifier.getBeginLoc();
+          QRef.NameLoc = Ref.NameLoc;
+          if (!normalizeToMainFile(QRef.QualifierLoc, SM) ||
+              !normalizeToMainFile(QRef.NameLoc, SM))
+            return;
+
+          Callback(QRef);
+        },
+        Inputs.AST->getHeuristicResolver());
+  }
+}
+
+namespace {
+
+std::string getNNSLAsString(NestedNameSpecifierLoc NNSL,
+                            const PrintingPolicy &Policy) {
+  std::string Out;
+  llvm::raw_string_ostream OutStream(Out);
+  NNSL.getNestedNameSpecifier().print(OutStream, Policy);
+  return OutStream.str();
+}
+
+PreparedQualifiedSelection
+computePreparedQualifiedSelection(const Tweak::Selection &Inputs) {
+  PreparedQualifiedSelection Out;
+  const auto *Node = Inputs.ASTSelection.commonAncestor();
+  if (!Node)
+    return Out;
+
+  for (const auto *N = Node; N; N = N->Parent) {
+    if (const auto *TAD = N->ASTNode.get<TypeAliasDecl>()) {
+      if (TAD->getIdentifier())
+        Out.SelectedAliasDecl = TAD;
+      break;
+    }
+    if (const auto *UD = N->ASTNode.get<UsingDecl>()) {
+      if (UD->getIdentifier())
+        Out.SelectedAliasDecl = UD;
+      break;
+    }
+  }
+
+  // Normalize the selection to the outermost AST node that still represents
+  // the qualified spelling we want to rewrite.
+  for (; Node->Parent; Node = Node->Parent) {
+    if (Node->ASTNode.get<NestedNameSpecifierLoc>())
+      continue;
+    if (const auto *T = Node->ASTNode.get<TypeLoc>()) {
+      if (Node->Parent->ASTNode.get<NestedNameSpecifierLoc>())
+        continue;
+      if (llvm::isa<TagType, TemplateSpecializationType, TypedefType, UsingType,
+                    UnresolvedUsingType>(T->getTypePtr()))
+        break;
+      if (Node->Parent->ASTNode.get<TypeLoc>())
+        continue;
+    }
+    break;
+  }
+
+  SourceRange SpelledNameRange;
+  if (const auto *D = Node->ASTNode.get<DeclRefExpr>()) {
+    if (D->getDecl()->getIdentifier()) {
+      Out.QualifierToRemove = D->getQualifierLoc();
+      SpelledNameRange = D->getSourceRange();
+      if (auto AngleLoc = D->getLAngleLoc(); AngleLoc.isValid())
+        SpelledNameRange.setEnd(AngleLoc.getLocWithOffset(-1));
+      Out.MustInsertAfterLoc = D->getDecl()->getBeginLoc();
+      if (const auto *Canonical = canonicalDecl(D->getDecl()))
+        Out.Targets.insert(Canonical);
+    }
+  } else if (const auto *T = Node->ASTNode.get<TypeLoc>()) {
+    switch (T->getTypeLocClass()) {
+    case TypeLoc::TemplateSpecialization: {
+      auto TL = T->castAs<TemplateSpecializationTypeLoc>();
+      Out.QualifierToRemove = TL.getQualifierLoc();
+      if (!Out.QualifierToRemove)
+        break;
+      SpelledNameRange = TL.getTemplateNameLoc();
+      if (auto *TD = TL.getTypePtr()->getTemplateName().getAsTemplateDecl(
+              /*IgnoreDeduced=*/true)) {
+        Out.MustInsertAfterLoc = TD->getBeginLoc();
+        if (const auto *Canonical = canonicalDecl(TD))
+          Out.Targets.insert(Canonical);
+      }
+      break;
+    }
+    case TypeLoc::Enum:
+    case TypeLoc::Record:
+    case TypeLoc::InjectedClassName: {
+      auto TL = T->castAs<TagTypeLoc>();
+      Out.QualifierToRemove = TL.getQualifierLoc();
+      if (!Out.QualifierToRemove)
+        break;
+      SpelledNameRange = TL.getNameLoc();
+      Out.MustInsertAfterLoc = TL.getDecl()->getBeginLoc();
+      if (const auto *Canonical = canonicalDecl(TL.getDecl()))
+        Out.Targets.insert(Canonical);
+      break;
+    }
+    case TypeLoc::Typedef: {
+      auto TL = T->castAs<TypedefTypeLoc>();
+      Out.QualifierToRemove = TL.getQualifierLoc();
+      if (!Out.QualifierToRemove)
+        break;
+      SpelledNameRange = TL.getNameLoc();
+      Out.MustInsertAfterLoc = TL.getDecl()->getBeginLoc();
+      if (const auto *Canonical = canonicalDecl(TL.getDecl()))
+        Out.Targets.insert(Canonical);
+      break;
+    }
+    case TypeLoc::UnresolvedUsing: {
+      auto TL = T->castAs<UnresolvedUsingTypeLoc>();
+      Out.QualifierToRemove = TL.getQualifierLoc();
+      if (!Out.QualifierToRemove)
+        break;
+      SpelledNameRange = TL.getNameLoc();
+      Out.MustInsertAfterLoc = TL.getDecl()->getBeginLoc();
+      if (const auto *Canonical = canonicalDecl(TL.getDecl()))
+        Out.Targets.insert(Canonical);
+      break;
+    }
+    case TypeLoc::Using: {
+      auto TL = T->castAs<UsingTypeLoc>();
+      Out.QualifierToRemove = TL.getQualifierLoc();
+      if (!Out.QualifierToRemove)
+        break;
+      SpelledNameRange = TL.getNameLoc();
+      Out.MustInsertAfterLoc = TL.getDecl()->getBeginLoc();
+      if (const auto *Canonical = canonicalDecl(TL.getDecl()))
+        Out.Targets.insert(Canonical);
+      break;
+    }
+    default:
+      break;
+    }
+    if (Out.QualifierToRemove)
+      SpelledNameRange.setBegin(Out.QualifierToRemove.getBeginLoc());
+  }
+
+  if (!Out.QualifierToRemove || Out.Targets.empty() ||
+      !isNamespaceQualifier(Out.QualifierToRemove))
+    return Out;
+
+  auto &SM = Inputs.AST->getSourceManager();
+  if (SM.isMacroBodyExpansion(Out.QualifierToRemove.getBeginLoc()) ||
+      !SM.isWrittenInSameFile(Out.QualifierToRemove.getBeginLoc(),
+                              Out.QualifierToRemove.getEndLoc()))
+    return Out;
+
+  const auto &TB = Inputs.AST->getTokens();
+  auto SpelledTokens =
+      TB.spelledForExpanded(TB.expandedTokens(SpelledNameRange));
+  if (!SpelledTokens)
+    return Out;
+  auto SpelledRange =
+      syntax::Token::range(SM, SpelledTokens->front(), SpelledTokens->back());
+  std::tie(Out.SpelledQualifier, Out.SpelledName) =
+      splitQualifiedName(SpelledRange.text(SM));
+  Out.QualifierToSpell = getNNSLAsString(
+      Out.QualifierToRemove, Inputs.AST->getASTContext().getPrintingPolicy());
+  if (!llvm::StringRef(Out.QualifierToSpell).ends_with(Out.SpelledQualifier) ||
+      Out.SpelledName.empty())
+    return Out;
+
+  Out.HasQualifiedRef = true;
+  return Out;
+}
+
+struct CachedPreparedSelection {
+  const Tweak::Selection *SelectionPtr = nullptr;
+  const ParsedAST *AST = nullptr;
+  const ASTContext *ASTCtx = nullptr;
+  const char *CodeData = nullptr;
+  unsigned SelectionBegin = 0;
+  unsigned SelectionEnd = 0;
+  const SelectionTree::Node *CommonAncestor = nullptr;
+  unsigned ConsumedClientsMask = 0;
+  PreparedQualifiedSelection Prepared;
+};
+
+} // namespace
+
+const PreparedQualifiedSelection &
+prepareQualifiedSelection(const Tweak::Selection &Inputs,
+                          QualifiedRewriteClient Client) {
+  static thread_local CachedPreparedSelection Cache;
+  const auto ClientBit = static_cast<unsigned>(Client);
+  const SelectionTree::Node *CommonAncestor =
+      Inputs.ASTSelection.commonAncestor();
+  const ASTContext *ASTCtx = &Inputs.AST->getASTContext();
+
+  if (Cache.SelectionPtr == &Inputs && Cache.AST == Inputs.AST &&
+      Cache.ASTCtx == ASTCtx && Cache.CodeData == Inputs.Code.data() &&
+      Cache.SelectionBegin == Inputs.SelectionBegin &&
+      Cache.SelectionEnd == Inputs.SelectionEnd &&
+      Cache.CommonAncestor == CommonAncestor &&
+      (Cache.ConsumedClientsMask & ClientBit) == 0) {
+    Cache.ConsumedClientsMask |= ClientBit;
+    return Cache.Prepared;
+  }
+
+  Cache.SelectionPtr = &Inputs;
+  Cache.AST = Inputs.AST;
+  Cache.ASTCtx = ASTCtx;
+  Cache.CodeData = Inputs.Code.data();
+  Cache.SelectionBegin = Inputs.SelectionBegin;
+  Cache.SelectionEnd = Inputs.SelectionEnd;
+  Cache.CommonAncestor = CommonAncestor;
+  Cache.ConsumedClientsMask = ClientBit;
+  Cache.Prepared = computePreparedQualifiedSelection(Inputs);
+  return Cache.Prepared;
+}
+
+} // namespace clangd
+} // namespace clang
diff --git a/clang-tools-extra/clangd/refactor/tweaks/QualifiedNameRewrite.h b/clang-tools-extra/clangd/refactor/tweaks/QualifiedNameRewrite.h
new file mode 100644
index 00000000000000..c27e523119d30a
--- /dev/null
+++ b/clang-tools-extra/clangd/refactor/tweaks/QualifiedNameRewrite.h
@@ -0,0 +1,110 @@
+//===--- QualifiedNameRewrite.h ---------------------------------*- C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Shared helpers for tweaks that rewrite namespace-qualified references in the
+// main file, such as AddUsingReplaceAll and ReplaceQualifiedWithAlias. These
+// tweaks differ only in the replacement they emit; the logic for locating and
+// filtering the qualified references to rewrite is identical and lives here.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_REFACTOR_TWEAKS_QUALIFIEDNAMEREWRITE_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_REFACTOR_TWEAKS_QUALIFIEDNAMEREWRITE_H
+
+#include "FindTarget.h"
+#include "refactor/Tweak.h"
+
+#include "clang/AST/Decl.h"
+#include "clang/AST/NestedNameSpecifier.h"
+#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/STLFunctionalExtras.h"
+
+namespace clang {
+namespace clangd {
+
+/// Returns the canonical NamedDecl for \p D, or nullptr.
+const NamedDecl *canonicalDecl(const NamedDecl *D);
+
+/// True if \p Qualifier is a namespace qualifier (e.g. 'ns::').
+bool isNamespaceQualifier(NestedNameSpecifierLoc Qualifier);
+
+/// Returns the NamespaceDecl behind a namespace qualifier, or nullptr if
+/// \p Qualifier is not a (valid) namespace qualifier.
+const NamespaceDecl *getNamespaceFromQualifier(NestedNameSpecifier Qualifier);
+
+/// Normalizes \p Loc to a location written in the main file.
+///
+/// References inside macro arguments are mapped to their spelling location via
+/// getFileLoc(); macro-body expansions and locations outside the main file are
+/// rejected. Returns true and updates \p Loc on success, false otherwise.
+bool normalizeToMainFile(SourceLocation &Loc, const SourceManager &SM);
+
+/// True if any of \p Ref's targets canonically matches an entry in \p Targets.
+bool referenceMatchesTargets(const ReferenceLoc &Ref,
+                             const llvm::DenseSet<const NamedDecl *> &Targets);
+
+/// Returns the end of a qualified reference starting at \p NameLoc, extending
+/// past any template argument list so rewrites replace the full spelled name.
+SourceLocation getReferenceEnd(SourceLocation NameLoc, const SourceManager &SM,
+                               const LangOptions &LangOpts);
+
+/// A namespace-qualified reference that passed all rewrite filters, with its
+/// locations already normalized to the main file.
+struct QualifiedReference {
+  /// Start of the qualifier, e.g. 'ns::' in 'ns::foo'.
+  SourceLocation QualifierLoc;
+  /// Start of the last name part, e.g. 'foo' in 'ns::foo<int>'.
+  SourceLocation NameLoc;
+};
+
+/// Walks every local top-level declaration and invokes \p Callback for each
+/// explicit, namespace-qualified reference (not a declaration) that resolves to
+/// one of \p Targets. Locations passed to \p Callback are normalized to the
+/// main file. The callback decides which replacement, if any, to emit.
+void forEachQualifiedReferenceToRewrite(
+    const Tweak::Selection &Inputs,
+    const llvm::DenseSet<const NamedDecl *> &Targets,
+    llvm::function_ref<void(const QualifiedReference &)> Callback);
+
+enum class QualifiedRewriteClient : unsigned {
+  AddUsingReplaceAll = 1 << 0,
+  ReplaceQualifiedWithAlias = 1 << 1,
+};
+
+/// Result of analyzing a Tweak::Selection for namespace-qualified reference
+/// rewrite tweaks (AddUsingReplaceAll and ReplaceQualifiedWithAlias).
+struct PreparedQualifiedSelection {
+  /// Enclosing TypeAliasDecl or UsingDecl when the selection is inside an alias
+  /// declaration.
+  const NamedDecl *SelectedAliasDecl = nullptr;
+
+  /// True if the selection is on a valid namespace-qualified reference in the
+  /// main file outside macro bodies.
+  bool HasQualifiedRef = false;
+  NestedNameSpecifierLoc QualifierToRemove;
+  std::string QualifierToSpell;
+  llvm::StringRef SpelledQualifier;
+  llvm::StringRef SpelledName;
+  SourceLocation MustInsertAfterLoc;
+  llvm::DenseSet<const NamedDecl *> Targets;
+};
+
+/// Analyzes \p Inputs once per Tweak::Selection and caches the result so that
+/// AddUsingReplaceAll::prepare() and ReplaceQualifiedWithAlias::prepare() share
+/// a single execution for the same selection.
+const PreparedQualifiedSelection &
+prepareQualifiedSelection(const Tweak::Selection &Inputs,
+                          QualifiedRewriteClient Client);
+
+} // namespace clangd
+} // namespace clang
+
+#endif
diff --git a/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp b/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
index 6d1decd010ad31..d3e83310af0649 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
@@ -7,6 +7,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "FindTarget.h"
+#include "QualifiedNameRewrite.h"
 #include "refactor/Tweak.h"
 #include "support/Logger.h"
 
@@ -39,21 +40,10 @@ class ReplaceQualifiedWithAlias : public Tweak {
 private:
   std::string AliasName;
   SourceRange AliasDeclToSkip;
-  llvm::DenseSet<const NamedDecl *> SelectedTargets;
-  std::string SelectedName;
   llvm::DenseSet<const NamedDecl *> RewriteTargets;
 };
 REGISTER_TWEAK(ReplaceQualifiedWithAlias)
 
-const NamedDecl *canonicalDecl(const NamedDecl *D) {
-  return D ? llvm::dyn_cast<NamedDecl>(D->getCanonicalDecl()) : nullptr;
-}
-
-bool isNamespaceQualifier(NestedNameSpecifierLoc Qualifier) {
-  return Qualifier && Qualifier.getNestedNameSpecifier().getKind() ==
-                          NestedNameSpecifier::Kind::Namespace;
-}
-
 void collectUsingDecls(const DeclContext *DC,
                        llvm::SmallVectorImpl<const UsingDecl *> &Out) {
   for (const Decl *D : DC->decls()) {
@@ -64,9 +54,6 @@ void collectUsingDecls(const DeclContext *DC,
   }
 }
 
-bool collectAliasTargets(const NamedDecl *Alias, const Tweak::Selection &Inputs,
-                         llvm::DenseSet<const NamedDecl *> &Targets);
-
 bool collectAliasTargets(const NamedDecl *Alias, const Tweak::Selection &Inputs,
                          llvm::DenseSet<const NamedDecl *> &Targets) {
   ReferenceLoc QualifiedRef;
@@ -103,44 +90,6 @@ bool collectAliasTargets(const NamedDecl *Alias, const Tweak::Selection &Inputs,
   return !Targets.empty();
 }
 
-// Returns the end of a qualified reference, extending past any template
-// argument list so rewrites replace the full spelled name.
-SourceLocation getReferenceEnd(SourceLocation NameLoc, const SourceManager &SM,
-                               const LangOptions &LangOpts) {
-  std::optional<Token> Tok = Lexer::findNextToken(NameLoc, SM, LangOpts);
-  if (!Tok || Tok->isNot(tok::less))
-    return Lexer::getLocForEndOfToken(NameLoc, 0, SM, LangOpts);
-
-  unsigned Depth = 0;
-  while (Tok) {
-    switch (Tok->getKind()) {
-    case tok::less:
-      ++Depth;
-      break;
-    case tok::greater:
-      if (Depth == 0)
-        return Lexer::getLocForEndOfToken(Tok->getLocation(), 0, SM, LangOpts);
-      --Depth;
-      if (Depth == 0)
-        return Lexer::getLocForEndOfToken(Tok->getLocation(), 0, SM, LangOpts);
-      break;
-    case tok::greatergreater:
-      if (Depth <= 1)
-        return Lexer::getLocForEndOfToken(Tok->getLocation(), 0, SM, LangOpts);
-      Depth -= 2;
-      if (Depth == 0)
-        return Lexer::getLocForEndOfToken(Tok->getLocation(), 0, SM, LangOpts);
-      break;
-    default:
-      if (Depth == 0)
-        return Lexer::getLocForEndOfToken(Tok->getLocation(), 0, SM, LangOpts);
-      break;
-    }
-    Tok = Lexer::findNextToken(Tok->getLocation(), SM, LangOpts);
-  }
-  return Lexer::getLocForEndOfToken(NameLoc, 0, SM, LangOpts);
-}
-
 std::string ReplaceQualifiedWithAlias::title() const {
   return std::string(
       llvm::formatv("Replace qualified references with {0}", AliasName));
@@ -150,116 +99,42 @@ bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
   // Reset all cached state before inspecting the new selection.
   AliasName.clear();
   AliasDeclToSkip = SourceRange();
-  SelectedTargets.clear();
-  SelectedName.clear();
   RewriteTargets.clear();
 
-  auto *Node = Inputs.ASTSelection.commonAncestor();
-  if (!Node)
-    return false;
-
-  auto SetFromAlias = [&](const NamedDecl *Alias) -> bool {
-    if (!Alias->getIdentifier())
-      return false;
-
-    llvm::DenseSet<const NamedDecl *> Targets;
-    if (!collectAliasTargets(Alias, Inputs, Targets))
-      return false;
-
-    // Cache the alias spelling and the canonical declarations it stands for.
-    RewriteTargets = std::move(Targets);
-    AliasName = Alias->getNameAsString();
-    AliasDeclToSkip = Alias->getSourceRange();
-    return true;
-  };
-
-  auto FindSelectedQualifiedRef = [&](const SelectionTree::Node *N) -> bool {
-    const SelectionTree::Node *Root = N;
-    while (Root && !Root->ASTNode.get<Decl>() && !Root->ASTNode.get<Stmt>())
-      Root = Root->Parent;
-    if (!Root)
-      return false;
-
-    bool FoundSelectedQualifiedRef = false;
-    auto ReportRef = [&](ReferenceLoc Ref) {
-      if (FoundSelectedQualifiedRef || !Ref.Qualifier || Ref.Targets.empty())
-        return;
-      if (!isNamespaceQualifier(Ref.Qualifier))
-        return;
-
-      auto &SM = Inputs.AST->getSourceManager();
-      const auto &LangOpts = Inputs.AST->getLangOpts();
-
-      SourceLocation QualifierLoc = Ref.Qualifier.getBeginLoc();
-      SourceLocation NameLoc = Ref.NameLoc;
-      if (QualifierLoc.isMacroID()) {
-        if (!SM.isMacroArgExpansion(QualifierLoc))
-          return;
-        QualifierLoc = SM.getFileLoc(QualifierLoc);
-      }
-      if (NameLoc.isMacroID()) {
-        if (!SM.isMacroArgExpansion(NameLoc))
-          return;
-        NameLoc = SM.getFileLoc(NameLoc);
-      }
-      if (SM.getFileID(QualifierLoc) != SM.getMainFileID() ||
-          SM.getFileID(NameLoc) != SM.getMainFileID())
-        return;
-
-      unsigned BeginOffset = SM.getFileOffset(QualifierLoc);
-      SourceLocation EndLoc = getReferenceEnd(NameLoc, SM, LangOpts);
-      if (BeginOffset > SM.getFileOffset(EndLoc))
-        return;
-
-      if (Inputs.SelectionBegin < BeginOffset ||
-          Inputs.SelectionBegin > SM.getFileOffset(EndLoc))
-        return;
-
-      SelectedName = Lexer::getSourceText(
-                         CharSourceRange::getTokenRange(NameLoc), SM, LangOpts)
-                         .str();
-      for (const auto *Target : Ref.Targets) {
-        if (const auto *Canonical = canonicalDecl(Target))
-          SelectedTargets.insert(Canonical);
-      }
-      FoundSelectedQualifiedRef = true;
-    };
-
-    if (const auto *D = Root->ASTNode.get<Decl>()) {
-      findExplicitReferences(D, ReportRef, Inputs.AST->getHeuristicResolver());
-    } else if (const auto *S = Root->ASTNode.get<Stmt>()) {
-      findExplicitReferences(S, ReportRef, Inputs.AST->getHeuristicResolver());
-    }
-    return FoundSelectedQualifiedRef;
-  };
+  const auto &Prepared = prepareQualifiedSelection(
+      Inputs, QualifiedRewriteClient::ReplaceQualifiedWithAlias);
 
   // First look for an alias declaration in the current selection or one of
   // its ancestors. This is the narrowest and most reliable source of truth.
-  for (auto *N = Node; N; N = N->Parent) {
-    if (const auto *TAD = N->ASTNode.get<TypeAliasDecl>(); TAD) {
-      if (SetFromAlias(TAD))
-        return true;
-    } else if (const auto *UD = N->ASTNode.get<UsingDecl>(); UD) {
-      if (SetFromAlias(UD))
-        return true;
+  if (const auto *Alias = Prepared.SelectedAliasDecl) {
+    llvm::DenseSet<const NamedDecl *> Targets;
+    if (collectAliasTargets(Alias, Inputs, Targets)) {
+      RewriteTargets = std::move(Targets);
+      AliasName = Alias->getNameAsString();
+      AliasDeclToSkip = Alias->getSourceRange();
+      return true;
     }
   }
 
-  if (!FindSelectedQualifiedRef(Node))
+  if (!Prepared.HasQualifiedRef)
     return false;
 
-  // Search the file for a using-declaration that covers the selected reference.
-  // This avoids a full findExplicitReferences() traversal of the whole file;
-  // collectUsingDecls() only walks declarations, not expressions or statements.
-  // The expensive per-occurrence rewrite is deferred to apply().
+  // Search the main file's top-level declarations for a using-declaration that
+  // covers the selected reference. Walking getLocalTopLevelDecls() instead of
+  // getTranslationUnitDecl() avoids visiting declarations from included
+  // headers.
   auto &SM = Inputs.AST->getSourceManager();
   llvm::SmallVector<const UsingDecl *> FileUsingDecls;
-  collectUsingDecls(Inputs.AST->getASTContext().getTranslationUnitDecl(),
-                    FileUsingDecls);
+  for (const Decl *D : Inputs.AST->getLocalTopLevelDecls()) {
+    if (const auto *UD = llvm::dyn_cast<UsingDecl>(D))
+      FileUsingDecls.push_back(UD);
+    if (const auto *Nested = llvm::dyn_cast<DeclContext>(D))
+      collectUsingDecls(Nested, FileUsingDecls);
+  }
   for (const auto *UD : FileUsingDecls) {
     if (!UD->getIdentifier())
       continue;
-    if (!SelectedName.empty() && UD->getName() != SelectedName)
+    if (!Prepared.SpelledName.empty() && UD->getName() != Prepared.SpelledName)
       continue;
     SourceLocation UDLoc = UD->getLocation();
     if (UDLoc.isInvalid() ||
@@ -272,7 +147,7 @@ bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
 
     bool MatchesSelection = false;
     for (const auto *Target : AliasTargets) {
-      if (SelectedTargets.contains(Target)) {
+      if (Prepared.Targets.contains(Target)) {
         MatchesSelection = true;
         break;
       }
@@ -310,60 +185,24 @@ ReplaceQualifiedWithAlias::apply(const Selection &Inputs) {
   tooling::Replacements Repls;
   // Rewrite every explicit namespace-qualified reference that resolves to one
   // of the canonical declarations represented by the alias.
-  for (const auto &D : Inputs.AST->getLocalTopLevelDecls()) {
-    findExplicitReferences(
-        D,
-        [&](ReferenceLoc Ref) {
-          if (!Ref.Qualifier || Ref.Targets.empty() || Ref.IsDecl)
-            return;
-          if (!isNamespaceQualifier(Ref.Qualifier))
-            return;
-
-          bool MatchesTarget = false;
-          for (const auto *Target : Ref.Targets) {
-            if (const auto *Canonical = canonicalDecl(Target);
-                Canonical && RewriteTargets.contains(Canonical)) {
-              MatchesTarget = true;
-              break;
-            }
-          }
-          if (!MatchesTarget)
-            return;
-
-          SourceLocation QualifierLoc = Ref.Qualifier.getBeginLoc();
-          SourceLocation NameLoc = Ref.NameLoc;
-          if (QualifierLoc.isMacroID()) {
-            if (!SM.isMacroArgExpansion(QualifierLoc))
-              return;
-            QualifierLoc = SM.getFileLoc(QualifierLoc);
-          }
-          if (NameLoc.isMacroID()) {
-            if (!SM.isMacroArgExpansion(NameLoc))
-              return;
-            NameLoc = SM.getFileLoc(NameLoc);
-          }
-          if (SM.getFileID(QualifierLoc) != SM.getMainFileID() ||
-              SM.getFileID(NameLoc) != SM.getMainFileID())
-            return;
-
-          // Leave the selected alias definition untouched.
-          if (SkipBegin.isValid() && SkipEnd.isValid() &&
-              SM.isPointWithin(NameLoc, SkipBegin, SkipEnd))
-            return;
+  forEachQualifiedReferenceToRewrite(
+      Inputs, RewriteTargets, [&](const QualifiedReference &Ref) {
+        // Leave the selected alias definition untouched.
+        if (SkipBegin.isValid() && SkipEnd.isValid() &&
+            SM.isPointWithin(Ref.NameLoc, SkipBegin, SkipEnd))
+          return;
 
-          unsigned BeginOffset = SM.getFileOffset(QualifierLoc);
-          SourceLocation EndLoc = getReferenceEnd(NameLoc, SM, LangOpts);
-          if (BeginOffset > SM.getFileOffset(EndLoc))
-            return;
+        unsigned BeginOffset = SM.getFileOffset(Ref.QualifierLoc);
+        SourceLocation EndLoc = getReferenceEnd(Ref.NameLoc, SM, LangOpts);
+        if (BeginOffset > SM.getFileOffset(EndLoc))
+          return;
 
-          // Replace the qualified spelling with the alias name only.
-          if (auto Err = Repls.add(tooling::Replacement(
-                  SM, QualifierLoc, SM.getFileOffset(EndLoc) - BeginOffset,
-                  AliasName)))
-            consumeError(std::move(Err));
-        },
-        Inputs.AST->getHeuristicResolver());
-  }
+        // Replace the qualified spelling with the alias name only.
+        if (auto Err = Repls.add(tooling::Replacement(
+                SM, Ref.QualifierLoc, SM.getFileOffset(EndLoc) - BeginOffset,
+                AliasName)))
+          consumeError(std::move(Err));
+      });
 
   return Effect::mainFileEdit(SM, std::move(Repls));
 }

>From adc34d539f30435071d8e98401ea82e01afaa5a0 Mon Sep 17 00:00:00 2001
From: Dimitri Ratz <dimitri.ratz at protonmail.com>
Date: Wed, 28 Oct 2026 17:47:13 +0100
Subject: [PATCH 11/16] [clangd] Respect namespace scope when replacing
 qualified names with aliases

---
 .../refactor/tweaks/AddUsingReplaceAll.cpp    |  87 +++---
 .../tweaks/ReplaceQualifiedWithAlias.cpp      | 268 +++++++++++++-----
 .../tweaks/ReplaceQualifiedWithAliasTests.cpp |  55 ++++
 3 files changed, 300 insertions(+), 110 deletions(-)

diff --git a/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp b/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
index 0979f6b0555c7b..08e4aa1561bade 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
@@ -68,35 +68,6 @@ std::string AddUsingReplaceAll::title() const {
                                    SpelledName));
 }
 
-/// Collects all UsingDecls visible at the selection by walking the enclosing
-/// DeclContext chain directly, sorted by source location. This avoids a full
-/// AST traversal and only visits O(depth * declarations-per-scope) nodes.
-///
-/// A using-declaration declared in a scope S is visible at SelectionCtx if
-/// S is an ancestor of SelectionCtx, i.e., exactly the contexts we walk when
-/// ascending via getLexicalParent().
-static std::vector<const UsingDecl *>
-collectEnclosingUsings(const DeclContext *SelectionCtx,
-                       const SourceManager &SM) {
-  std::vector<const UsingDecl *> Result;
-  for (const DeclContext *Ctx = SelectionCtx; Ctx;
-       Ctx = Ctx->getLexicalParent()) {
-    for (const Decl *D : Ctx->decls()) {
-      const auto *UD = dyn_cast<UsingDecl>(D);
-      if (!UD)
-        continue;
-      if (SM.getFileID(UD->getUsingLoc()) != SM.getMainFileID())
-        continue;
-      Result.push_back(UD);
-    }
-  }
-  // Merge into a single sorted list so findInsertionPoint can break early.
-  llvm::sort(Result, [&](const UsingDecl *A, const UsingDecl *B) {
-    return SM.isBeforeInTranslationUnit(A->getUsingLoc(), B->getUsingLoc());
-  });
-  return Result;
-}
-
 struct InsertionPointData {
   SourceLocation Loc;
   std::string Suffix;
@@ -114,30 +85,64 @@ findInsertionPoint(const Tweak::Selection &Inputs,
       getNamespaceFromQualifier(QualifierToRemove.getNestedNameSpecifier());
   if (!TargetNamespace)
     return error("Qualifier is not a valid namespace qualifier");
-
-  SourceLocation LastUsingLoc;
-  const std::vector<const UsingDecl *> Usings = collectEnclosingUsings(
-      &Inputs.ASTSelection.commonAncestor()->getDeclContext(), SM);
+  const auto *CanonicalTargetNS = TargetNamespace->getCanonicalDecl();
 
   auto IsValidPoint = [&](const SourceLocation Loc) {
     return MustInsertAfterLoc.isInvalid() ||
            SM.isBeforeInTranslationUnit(MustInsertAfterLoc, Loc);
   };
 
+  SourceLocation LastUsingLoc;
   bool AlwaysFullyQualify = true;
-  for (const auto *U : Usings) {
-    if (!U->getQualifier().isFullyQualified())
+  bool AlreadyExists = false;
+
+  auto ProcessDecl = [&](const Decl *D) {
+    const auto *UD = dyn_cast<UsingDecl>(D);
+    if (!UD)
+      return;
+    SourceLocation UsingLoc = UD->getUsingLoc();
+    if (SM.getFileID(UsingLoc) != SM.getMainFileID())
+      return;
+
+    if (!UD->getQualifier().isFullyQualified())
       AlwaysFullyQualify = false;
 
-    if (const auto *Namespace = getNamespaceFromQualifier(U->getQualifier())) {
-      if (Namespace->getCanonicalDecl() ==
-              TargetNamespace->getCanonicalDecl() &&
-          U->getName() == Name)
-        return InsertionPointData();
+    if (const auto *Namespace = getNamespaceFromQualifier(UD->getQualifier())) {
+      if (Namespace->getCanonicalDecl() == CanonicalTargetNS &&
+          UD->getName() == Name) {
+        AlreadyExists = true;
+        return;
+      }
     }
 
-    LastUsingLoc = U->getUsingLoc();
+    if (LastUsingLoc.isInvalid() ||
+        SM.isBeforeInTranslationUnit(LastUsingLoc, UsingLoc))
+      LastUsingLoc = UsingLoc;
+  };
+
+  // Walk enclosing file/namespace contexts (skipping functions and classes) and
+  // use getLocalTopLevelDecls() at translation-unit scope to avoid traversing
+  // declarations from included headers.
+  for (const DeclContext *Ctx =
+           &Inputs.ASTSelection.commonAncestor()->getDeclContext();
+       Ctx; Ctx = Ctx->getLexicalParent()) {
+    if (!Ctx->isFileContext())
+      continue;
+    if (isa<TranslationUnitDecl>(Ctx)) {
+      for (const Decl *D : Inputs.AST->getLocalTopLevelDecls()) {
+        ProcessDecl(D);
+        if (AlreadyExists)
+          return InsertionPointData();
+      }
+    } else {
+      for (const Decl *D : Ctx->decls()) {
+        ProcessDecl(D);
+        if (AlreadyExists)
+          return InsertionPointData();
+      }
+    }
   }
+
   if (LastUsingLoc.isValid() && IsValidPoint(LastUsingLoc)) {
     InsertionPointData Out;
     Out.Loc = LastUsingLoc;
diff --git a/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp b/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
index d3e83310af0649..4d3eca8842b0b6 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
@@ -12,6 +12,7 @@
 #include "support/Logger.h"
 
 #include "clang/AST/Decl.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/AST/NestedNameSpecifier.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Lex/Lexer.h"
@@ -38,24 +39,29 @@ class ReplaceQualifiedWithAlias : public Tweak {
   }
 
 private:
+  const NamedDecl *SelectedAlias = nullptr;
   std::string AliasName;
   SourceRange AliasDeclToSkip;
   llvm::DenseSet<const NamedDecl *> RewriteTargets;
 };
 REGISTER_TWEAK(ReplaceQualifiedWithAlias)
 
-void collectUsingDecls(const DeclContext *DC,
-                       llvm::SmallVectorImpl<const UsingDecl *> &Out) {
-  for (const Decl *D : DC->decls()) {
-    if (const auto *UD = llvm::dyn_cast<UsingDecl>(D))
-      Out.push_back(UD);
-    if (const auto *Nested = llvm::dyn_cast<DeclContext>(D))
-      collectUsingDecls(Nested, Out);
+bool collectUsingTargets(const UsingDecl *UD,
+                         llvm::DenseSet<const NamedDecl *> &Targets) {
+  if (!isNamespaceQualifier(UD->getQualifierLoc()))
+    return false;
+  for (const auto *Shadow : UD->shadows()) {
+    if (const auto *Canonical = canonicalDecl(Shadow->getTargetDecl()))
+      Targets.insert(Canonical);
   }
+  return !Targets.empty();
 }
 
 bool collectAliasTargets(const NamedDecl *Alias, const Tweak::Selection &Inputs,
                          llvm::DenseSet<const NamedDecl *> &Targets) {
+  if (const auto *UD = llvm::dyn_cast<UsingDecl>(Alias))
+    return collectUsingTargets(UD, Targets);
+
   ReferenceLoc QualifiedRef;
   bool FoundQualifiedRef = false;
   // Prefer the alias's own qualified reference when it exists, because it
@@ -77,17 +83,103 @@ bool collectAliasTargets(const NamedDecl *Alias, const Tweak::Selection &Inputs,
       if (const auto *Canonical = canonicalDecl(Target))
         Targets.insert(Canonical);
     }
-    return !Targets.empty();
   }
 
-  if (const auto *UD = llvm::dyn_cast<UsingDecl>(Alias)) {
-    for (const auto *Shadow : UD->shadows()) {
-      if (const auto *Canonical = canonicalDecl(Shadow->getTargetDecl()))
-        Targets.insert(Canonical);
+  return !Targets.empty();
+}
+
+/// Computes the set of primary file/namespace DeclContexts visible for
+/// unqualified lookup at (\p UseCtx, \p UseLoc), including namespaces nominated
+/// by active using-directives before \p UseLoc.
+llvm::SmallPtrSet<const DeclContext *, 8>
+collectVisibleContexts(const DeclContext *UseCtx, SourceLocation UseLoc,
+                       ParsedAST &AST) {
+  llvm::SmallPtrSet<const DeclContext *, 8> Visible;
+  for (const DeclContext *Ctx = UseCtx; Ctx; Ctx = Ctx->getParent()) {
+    if (Ctx->isFileContext())
+      Visible.insert(Ctx->getPrimaryContext());
+  }
+
+  auto &SM = AST.getSourceManager();
+  bool Changed = true;
+  while (Changed) {
+    Changed = false;
+    auto ScanDecl = [&](auto &&Self, const Decl *D) -> void {
+      SourceLocation DLoc = SM.getExpansionLoc(D->getBeginLoc());
+      if (DLoc.isValid() && UseLoc.isValid() &&
+          SM.isBeforeInTranslationUnit(UseLoc, DLoc))
+        return;
+
+      if (const auto *UDD = llvm::dyn_cast<UsingDirectiveDecl>(D)) {
+        if (Visible.contains(UDD->getDeclContext()->getPrimaryContext())) {
+          if (const auto *Nom = UDD->getNominatedNamespace()) {
+            if (Visible.insert(Nom->getPrimaryContext()).second)
+              Changed = true;
+          }
+        }
+        return;
+      }
+
+      if (llvm::isa<NamespaceDecl, LinkageSpecDecl, ExportDecl>(D)) {
+        for (const Decl *Child : llvm::cast<DeclContext>(D)->decls())
+          Self(Self, Child);
+      }
+    };
+
+    for (const Decl *D : AST.getLocalTopLevelDecls())
+      ScanDecl(ScanDecl, D);
+  }
+  return Visible;
+}
+
+const UsingDecl *findMatchingUsingDecl(
+    const Decl *D, const SourceManager &SM, SourceLocation SelectionLoc,
+    const llvm::SmallPtrSetImpl<const DeclContext *> &VisibleContexts,
+    llvm::StringRef SpelledName,
+    const llvm::DenseSet<const NamedDecl *> &SelectedTargets,
+    llvm::DenseSet<const NamedDecl *> &MatchedTargets) {
+  SourceLocation DLoc = SM.getExpansionLoc(D->getBeginLoc());
+  if (DLoc.isValid() && SelectionLoc.isValid() &&
+      SM.isBeforeInTranslationUnit(SelectionLoc, DLoc))
+    return nullptr;
+
+  if (const auto *UD = llvm::dyn_cast<UsingDecl>(D)) {
+    if (!UD->getIdentifier())
+      return nullptr;
+    if (!SpelledName.empty() && UD->getName() != SpelledName)
+      return nullptr;
+    if (!VisibleContexts.contains(UD->getDeclContext()->getPrimaryContext()))
+      return nullptr;
+    SourceLocation UDLoc = UD->getLocation();
+    if (UDLoc.isInvalid() ||
+        SM.getFileID(SM.getExpansionLoc(UDLoc)) != SM.getMainFileID())
+      return nullptr;
+
+    llvm::DenseSet<const NamedDecl *> AliasTargets;
+    if (!collectUsingTargets(UD, AliasTargets))
+      return nullptr;
+
+    for (const auto *Target : AliasTargets) {
+      if (SelectedTargets.contains(Target)) {
+        MatchedTargets = std::move(AliasTargets);
+        return UD;
+      }
     }
+    return nullptr;
   }
 
-  return !Targets.empty();
+  // Only descend into file/namespace-level scopes (skipping functions,
+  // classes, and enums).
+  if (llvm::isa<NamespaceDecl, LinkageSpecDecl, ExportDecl>(D)) {
+    for (const Decl *Child : llvm::cast<DeclContext>(D)->decls()) {
+      if (const auto *UD =
+              findMatchingUsingDecl(Child, SM, SelectionLoc, VisibleContexts,
+                                    SpelledName, SelectedTargets,
+                                    MatchedTargets))
+        return UD;
+    }
+  }
+  return nullptr;
 }
 
 std::string ReplaceQualifiedWithAlias::title() const {
@@ -97,6 +189,7 @@ std::string ReplaceQualifiedWithAlias::title() const {
 
 bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
   // Reset all cached state before inspecting the new selection.
+  SelectedAlias = nullptr;
   AliasName.clear();
   AliasDeclToSkip = SourceRange();
   RewriteTargets.clear();
@@ -109,6 +202,7 @@ bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
   if (const auto *Alias = Prepared.SelectedAliasDecl) {
     llvm::DenseSet<const NamedDecl *> Targets;
     if (collectAliasTargets(Alias, Inputs, Targets)) {
+      SelectedAlias = Alias;
       RewriteTargets = std::move(Targets);
       AliasName = Alias->getNameAsString();
       AliasDeclToSkip = Alias->getSourceRange();
@@ -119,46 +213,28 @@ bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
   if (!Prepared.HasQualifiedRef)
     return false;
 
-  // Search the main file's top-level declarations for a using-declaration that
-  // covers the selected reference. Walking getLocalTopLevelDecls() instead of
-  // getTranslationUnitDecl() avoids visiting declarations from included
-  // headers.
+  // Search the main file's top-level and namespace declarations for a
+  // using-declaration that is visible at the selection and covers the selected
+  // reference.
   auto &SM = Inputs.AST->getSourceManager();
-  llvm::SmallVector<const UsingDecl *> FileUsingDecls;
-  for (const Decl *D : Inputs.AST->getLocalTopLevelDecls()) {
-    if (const auto *UD = llvm::dyn_cast<UsingDecl>(D))
-      FileUsingDecls.push_back(UD);
-    if (const auto *Nested = llvm::dyn_cast<DeclContext>(D))
-      collectUsingDecls(Nested, FileUsingDecls);
-  }
-  for (const auto *UD : FileUsingDecls) {
-    if (!UD->getIdentifier())
-      continue;
-    if (!Prepared.SpelledName.empty() && UD->getName() != Prepared.SpelledName)
-      continue;
-    SourceLocation UDLoc = UD->getLocation();
-    if (UDLoc.isInvalid() ||
-        SM.getFileID(SM.getExpansionLoc(UDLoc)) != SM.getMainFileID())
-      continue;
-
-    llvm::DenseSet<const NamedDecl *> AliasTargets;
-    if (!collectAliasTargets(UD, Inputs, AliasTargets))
-      continue;
+  SourceLocation SelectionLoc =
+      SM.getExpansionLoc(Prepared.QualifierToRemove.getBeginLoc());
+  const DeclContext *SelectionCtx =
+      &Inputs.ASTSelection.commonAncestor()->getDeclContext();
+  auto VisibleContexts =
+      collectVisibleContexts(SelectionCtx, SelectionLoc, *Inputs.AST);
 
-    bool MatchesSelection = false;
-    for (const auto *Target : AliasTargets) {
-      if (Prepared.Targets.contains(Target)) {
-        MatchesSelection = true;
-        break;
-      }
+  llvm::DenseSet<const NamedDecl *> AliasTargets;
+  for (const Decl *D : Inputs.AST->getLocalTopLevelDecls()) {
+    if (const auto *UD = findMatchingUsingDecl(
+            D, SM, SelectionLoc, VisibleContexts, Prepared.SpelledName,
+            Prepared.Targets, AliasTargets)) {
+      SelectedAlias = UD;
+      RewriteTargets = std::move(AliasTargets);
+      AliasName = UD->getNameAsString();
+      AliasDeclToSkip = UD->getSourceRange();
+      return true;
     }
-    if (!MatchesSelection)
-      continue;
-
-    RewriteTargets = std::move(AliasTargets);
-    AliasName = UD->getNameAsString();
-    AliasDeclToSkip = UD->getSourceRange();
-    return true;
   }
 
   return false;
@@ -170,7 +246,7 @@ ReplaceQualifiedWithAlias::apply(const Selection &Inputs) {
   const auto &LangOpts = Inputs.AST->getLangOpts();
 
   // prepare() must have populated the alias name and target set.
-  if (AliasName.empty() || RewriteTargets.empty())
+  if (!SelectedAlias || AliasName.empty() || RewriteTargets.empty())
     return error("Incomplete prepared state for ReplaceQualifiedWithAlias");
 
   // Skip the selected alias declaration itself so we do not rewrite the alias
@@ -182,27 +258,81 @@ ReplaceQualifiedWithAlias::apply(const Selection &Inputs) {
   if (SkipEnd.isValid())
     SkipEnd = SM.getExpansionLoc(SkipEnd);
 
+  SourceLocation AliasLoc = SM.getExpansionLoc(SelectedAlias->getBeginLoc());
+  const DeclContext *AliasPrimaryCtx =
+      SelectedAlias->getDeclContext()->getPrimaryContext();
+  const bool AliasAtTU = llvm::isa<TranslationUnitDecl>(AliasPrimaryCtx);
+
   tooling::Replacements Repls;
-  // Rewrite every explicit namespace-qualified reference that resolves to one
-  // of the canonical declarations represented by the alias.
-  forEachQualifiedReferenceToRewrite(
-      Inputs, RewriteTargets, [&](const QualifiedReference &Ref) {
-        // Leave the selected alias definition untouched.
-        if (SkipBegin.isValid() && SkipEnd.isValid() &&
-            SM.isPointWithin(Ref.NameLoc, SkipBegin, SkipEnd))
-          return;
+  auto RewriteRef = [&](const QualifiedReference &Ref) {
+    if (SkipBegin.isValid() && SkipEnd.isValid() &&
+        SM.isPointWithin(Ref.NameLoc, SkipBegin, SkipEnd))
+      return;
+    if (AliasLoc.isValid() &&
+        SM.isBeforeInTranslationUnit(Ref.QualifierLoc, AliasLoc))
+      return;
 
-        unsigned BeginOffset = SM.getFileOffset(Ref.QualifierLoc);
-        SourceLocation EndLoc = getReferenceEnd(Ref.NameLoc, SM, LangOpts);
-        if (BeginOffset > SM.getFileOffset(EndLoc))
-          return;
+    unsigned BeginOffset = SM.getFileOffset(Ref.QualifierLoc);
+    SourceLocation EndLoc = getReferenceEnd(Ref.NameLoc, SM, LangOpts);
+    if (BeginOffset > SM.getFileOffset(EndLoc))
+      return;
+
+    if (auto Err = Repls.add(tooling::Replacement(
+            SM, Ref.QualifierLoc, SM.getFileOffset(EndLoc) - BeginOffset,
+            AliasName)))
+      consumeError(std::move(Err));
+  };
+
+  if (AliasAtTU) {
+    forEachQualifiedReferenceToRewrite(Inputs, RewriteTargets, RewriteRef);
+    return Effect::mainFileEdit(SM, std::move(Repls));
+  }
+
+  // When the alias is declared inside a namespace, only rewrite references in
+  // declarations where that namespace is visible (either directly enclosed by
+  // the namespace or via an active using-directive).
+  auto ProcessDecl = [&](auto &&Self, const Decl *D) -> void {
+    if (llvm::isa<NamespaceDecl, LinkageSpecDecl, ExportDecl>(D)) {
+      const auto *DC = llvm::cast<DeclContext>(D);
+      if (!AliasPrimaryCtx->Encloses(DC)) {
+        for (const Decl *Child : DC->decls())
+          Self(Self, Child);
+        return;
+      }
+    }
+
+    SourceLocation DLoc = SM.getExpansionLoc(D->getBeginLoc());
+    const DeclContext *UseCtx = llvm::isa<DeclContext>(D)
+                                    ? llvm::cast<DeclContext>(D)
+                                    : D->getDeclContext();
+    auto Visible = collectVisibleContexts(UseCtx, DLoc, *Inputs.AST);
+    if (!Visible.contains(AliasPrimaryCtx))
+      return;
+
+    findExplicitReferences(
+        D,
+        [&](ReferenceLoc Ref) {
+          if (!Ref.Qualifier || Ref.Targets.empty() || Ref.IsDecl)
+            return;
+          if (!isNamespaceQualifier(Ref.Qualifier))
+            return;
+          if (!referenceMatchesTargets(Ref, RewriteTargets))
+            return;
+
+          QualifiedReference QRef;
+          QRef.QualifierLoc = Ref.Qualifier.getBeginLoc();
+          QRef.NameLoc = Ref.NameLoc;
+          if (!normalizeToMainFile(QRef.QualifierLoc, SM) ||
+              !normalizeToMainFile(QRef.NameLoc, SM))
+            return;
+
+          RewriteRef(QRef);
+        },
+        Inputs.AST->getHeuristicResolver());
+  };
 
-        // Replace the qualified spelling with the alias name only.
-        if (auto Err = Repls.add(tooling::Replacement(
-                SM, Ref.QualifierLoc, SM.getFileOffset(EndLoc) - BeginOffset,
-                AliasName)))
-          consumeError(std::move(Err));
-      });
+  for (const Decl *D : Inputs.AST->getLocalTopLevelDecls())
+    ProcessDecl(ProcessDecl, D);
 
   return Effect::mainFileEdit(SM, std::move(Repls));
 }
diff --git a/clang-tools-extra/clangd/unittests/tweaks/ReplaceQualifiedWithAliasTests.cpp b/clang-tools-extra/clangd/unittests/tweaks/ReplaceQualifiedWithAliasTests.cpp
index 28f9fdbc2e9384..2e119e400aeeb2 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/ReplaceQualifiedWithAliasTests.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/ReplaceQualifiedWithAliasTests.cpp
@@ -225,6 +225,61 @@ void foo() {
 )cpp");
 }
 
+TEST_F(ReplaceQualifiedWithAliasTest, RespectNamespaceScopeVisibility) {
+  EXPECT_UNAVAILABLE(R"cpp(
+namespace ns_a {
+int a;
+}
+
+namespace ns_c {
+using ns_a::a;
+
+struct S {
+  int foo() { return ns_a::a; }
+};
+}
+
+struct W {
+  int corge() { return ns_a::^a; }
+};
+)cpp");
+
+  EXPECT_EQ(apply(R"cpp(
+namespace ns_a {
+int a;
+}
+
+namespace ns_c {
+using ns_a::a;
+
+struct S {
+  int foo() { return ns_a::^a; }
+};
+}
+
+struct W {
+  int corge() { return ns_a::a; }
+};
+)cpp"),
+            R"cpp(
+namespace ns_a {
+int a;
+}
+
+namespace ns_c {
+using ns_a::a;
+
+struct S {
+  int foo() { return a; }
+};
+}
+
+struct W {
+  int corge() { return ns_a::a; }
+};
+)cpp");
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang

>From b6e0a889cec1aaab9c5f758fa80ea7e82cef1c0b Mon Sep 17 00:00:00 2001
From: Dimitri Ratz <dimitri.ratz at protonmail.com>
Date: Thu, 29 Oct 2026 10:07:58 +0100
Subject: [PATCH 12/16] [clangd] add missing includes.

---
 .../clangd/refactor/tweaks/QualifiedNameRewrite.cpp             | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/clang-tools-extra/clangd/refactor/tweaks/QualifiedNameRewrite.cpp b/clang-tools-extra/clangd/refactor/tweaks/QualifiedNameRewrite.cpp
index 93e797365a97e4..6184893d65091d 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/QualifiedNameRewrite.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/QualifiedNameRewrite.cpp
@@ -13,6 +13,8 @@
 
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclBase.h"
+#include "clang/AST/DeclCXX.h"
+#include "clang/AST/DeclTemplate.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/TypeLoc.h"
 #include "clang/Basic/TokenKinds.h"

>From 93cf555cb87af41f08e9bb6eb5782c87800c4583 Mon Sep 17 00:00:00 2001
From: Dimitri Ratz <dimitri.ratz at protonmail.com>
Date: Thu, 29 Oct 2026 10:08:22 +0100
Subject: [PATCH 13/16] [clangd] fix code format.

---
 .../clangd/refactor/tweaks/AddUsingReplaceAll.cpp          | 4 ++--
 .../clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp   | 7 +++----
 2 files changed, 5 insertions(+), 6 deletions(-)

diff --git a/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp b/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
index 08e4aa1561bade..6ede1f2c6c268c 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/AddUsingReplaceAll.cpp
@@ -218,8 +218,8 @@ bool AddUsingReplaceAll::prepare(const Selection &Inputs) {
   const auto &Prepared = prepareQualifiedSelection(
       Inputs, QualifiedRewriteClient::AddUsingReplaceAll);
   if (!Prepared.HasQualifiedRef ||
-      isNamespaceForbidden(
-          Inputs, Prepared.QualifierToRemove.getNestedNameSpecifier()))
+      isNamespaceForbidden(Inputs,
+                           Prepared.QualifierToRemove.getNestedNameSpecifier()))
     return false;
 
   QualifierToRemove = Prepared.QualifierToRemove;
diff --git a/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp b/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
index 4d3eca8842b0b6..1d5cf85527df17 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
@@ -172,10 +172,9 @@ const UsingDecl *findMatchingUsingDecl(
   // classes, and enums).
   if (llvm::isa<NamespaceDecl, LinkageSpecDecl, ExportDecl>(D)) {
     for (const Decl *Child : llvm::cast<DeclContext>(D)->decls()) {
-      if (const auto *UD =
-              findMatchingUsingDecl(Child, SM, SelectionLoc, VisibleContexts,
-                                    SpelledName, SelectedTargets,
-                                    MatchedTargets))
+      if (const auto *UD = findMatchingUsingDecl(
+              Child, SM, SelectionLoc, VisibleContexts, SpelledName,
+              SelectedTargets, MatchedTargets))
         return UD;
     }
   }

>From ba1b4698a46b21ac74f0a0d8f7680650aeaf842d Mon Sep 17 00:00:00 2001
From: Dimitri Ratz <dimitri.ratz at protonmail.com>
Date: Thu, 29 Oct 2026 10:35:31 +0100
Subject: [PATCH 14/16] [clangd] removed wrong add_subdirectory from cmake in
 clang-tools-extra.

---
 clang-tools-extra/CMakeLists.txt | 1 -
 1 file changed, 1 deletion(-)

diff --git a/clang-tools-extra/CMakeLists.txt b/clang-tools-extra/CMakeLists.txt
index 4864278c2a6dd9..89e89195277b0d 100644
--- a/clang-tools-extra/CMakeLists.txt
+++ b/clang-tools-extra/CMakeLists.txt
@@ -32,7 +32,6 @@ add_subdirectory(clang-query)
 add_subdirectory(include-cleaner)
 add_subdirectory(pp-trace)
 add_subdirectory(tool-template)
-add_subdirectory(cpp-lens)
 
 option(CLANG_TOOLS_EXTRA_INCLUDE_DOCS "Generate build targets for the Clang Extra Tools docs."
   ${LLVM_INCLUDE_DOCS})

>From e4000bfa3359a8f8953dcd706b7946b23e28a71a Mon Sep 17 00:00:00 2001
From: Dimitri Ratz <dimitri.ratz at protonmail.com>
Date: Tue, 3 Nov 2026 09:43:51 +0100
Subject: [PATCH 15/16] =?UTF-8?q?[clangd]=20Avoid=20expensive=20(O(N=C2=B2?=
 =?UTF-8?q?)=20AST=20traversal=20in=20ReplaceQualifiedWithAlias::collectVi?=
 =?UTF-8?q?sibleContexts?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

collectVisibleContexts() previously re-traversed the whole file/namespace
scope of the TU (with a fixpoint loop over using-directives) on every call.
Because apply() calls it once per declaration inside the recursive
ProcessDecl walk, this made apply() O(N^2) in the number of
namespace-scope declarations.

Collect all file/namespace-scope using-directives once up front via the new
collectUsingDirectives() helper (a single O(N) pass) and have
collectVisibleContexts() run its fixpoint over that precomputed list instead
of walking the AST. The seeding of enclosing file/namespace contexts and the
"before UseLoc" filtering are preserved, so the computed visibility set is
identical. Both prepare() and apply() now build the directive list once.

This reduces apply() from O(N^2) to roughly linear in N, with no change in
behavior (existing ReplaceQualifiedWithAliasTests still cover nested
namespaces, competing aliases, using-directives and macro arguments).

Note: collectUsingDirectives() is intentionally called separately in both
prepare() and apply(). Although both run on the same AST within the apply
flow, caching the result across them would not pay off: prepare() only
computes the directive list in its using-declaration search branch and
returns early (without computing it) when the alias is found directly under
the cursor -- which is exactly the common namespace-scoped-alias case where
apply() needs the list. The call is a single O(N) pass (a constant factor,
not a complexity change), and apply() already performs an O(N) traversal via
findExplicitReferences.
---
 .../tweaks/ReplaceQualifiedWithAlias.cpp      | 85 ++++++++++++-------
 1 file changed, 55 insertions(+), 30 deletions(-)

diff --git a/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp b/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
index 1d5cf85527df17..76b2910109cdf7 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
@@ -17,6 +17,7 @@
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Lex/Lexer.h"
 #include "clang/Tooling/Core/Replacement.h"
+#include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
@@ -88,46 +89,67 @@ bool collectAliasTargets(const NamedDecl *Alias, const Tweak::Selection &Inputs,
   return !Targets.empty();
 }
 
+/// A using-directive gathered from the file/namespace-scope AST, holding the
+/// information needed to answer visibility queries without re-traversing the
+/// AST for every query.
+struct UsingDirectiveInfo {
+  const DeclContext *ActiveCtx; // primary context the directive is active in
+  const DeclContext *Nominated; // primary nominated namespace
+  SourceLocation Loc;           // expansion loc of the directive
+};
+
+/// Collects all file/namespace-scope using-directives of the TU in a single
+/// pass, so that repeated visibility queries do not each re-traverse the AST.
+llvm::SmallVector<UsingDirectiveInfo>
+collectUsingDirectives(ParsedAST &AST) {
+  auto &SM = AST.getSourceManager();
+  llvm::SmallVector<UsingDirectiveInfo> Directives;
+  auto ScanDecl = [&](auto &&Self, const Decl *D) -> void {
+    if (const auto *UDD = llvm::dyn_cast<UsingDirectiveDecl>(D)) {
+      if (const auto *Nom = UDD->getNominatedNamespace())
+        Directives.push_back({UDD->getDeclContext()->getPrimaryContext(),
+                              Nom->getPrimaryContext(),
+                              SM.getExpansionLoc(UDD->getBeginLoc())});
+      return;
+    }
+
+    if (llvm::isa<NamespaceDecl, LinkageSpecDecl, ExportDecl>(D)) {
+      for (const Decl *Child : llvm::cast<DeclContext>(D)->decls())
+        Self(Self, Child);
+    }
+  };
+
+  for (const Decl *D : AST.getLocalTopLevelDecls())
+    ScanDecl(ScanDecl, D);
+  return Directives;
+}
+
 /// Computes the set of primary file/namespace DeclContexts visible for
 /// unqualified lookup at (\p UseCtx, \p UseLoc), including namespaces nominated
-/// by active using-directives before \p UseLoc.
+/// by active using-directives before \p UseLoc. \p Directives must contain all
+/// file/namespace-scope using-directives of the TU (see collectUsingDirectives).
 llvm::SmallPtrSet<const DeclContext *, 8>
 collectVisibleContexts(const DeclContext *UseCtx, SourceLocation UseLoc,
-                       ParsedAST &AST) {
+                       llvm::ArrayRef<UsingDirectiveInfo> Directives,
+                       const SourceManager &SM) {
   llvm::SmallPtrSet<const DeclContext *, 8> Visible;
   for (const DeclContext *Ctx = UseCtx; Ctx; Ctx = Ctx->getParent()) {
     if (Ctx->isFileContext())
       Visible.insert(Ctx->getPrimaryContext());
   }
 
-  auto &SM = AST.getSourceManager();
   bool Changed = true;
   while (Changed) {
     Changed = false;
-    auto ScanDecl = [&](auto &&Self, const Decl *D) -> void {
-      SourceLocation DLoc = SM.getExpansionLoc(D->getBeginLoc());
-      if (DLoc.isValid() && UseLoc.isValid() &&
-          SM.isBeforeInTranslationUnit(UseLoc, DLoc))
-        return;
-
-      if (const auto *UDD = llvm::dyn_cast<UsingDirectiveDecl>(D)) {
-        if (Visible.contains(UDD->getDeclContext()->getPrimaryContext())) {
-          if (const auto *Nom = UDD->getNominatedNamespace()) {
-            if (Visible.insert(Nom->getPrimaryContext()).second)
-              Changed = true;
-          }
-        }
-        return;
-      }
-
-      if (llvm::isa<NamespaceDecl, LinkageSpecDecl, ExportDecl>(D)) {
-        for (const Decl *Child : llvm::cast<DeclContext>(D)->decls())
-          Self(Self, Child);
-      }
-    };
-
-    for (const Decl *D : AST.getLocalTopLevelDecls())
-      ScanDecl(ScanDecl, D);
+    for (const UsingDirectiveInfo &UDD : Directives) {
+      if (UDD.Loc.isValid() && UseLoc.isValid() &&
+          SM.isBeforeInTranslationUnit(UseLoc, UDD.Loc))
+        continue;
+      if (!Visible.contains(UDD.ActiveCtx))
+        continue;
+      if (Visible.insert(UDD.Nominated).second)
+        Changed = true;
+    }
   }
   return Visible;
 }
@@ -220,8 +242,9 @@ bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
       SM.getExpansionLoc(Prepared.QualifierToRemove.getBeginLoc());
   const DeclContext *SelectionCtx =
       &Inputs.ASTSelection.commonAncestor()->getDeclContext();
+  auto Directives = collectUsingDirectives(*Inputs.AST);
   auto VisibleContexts =
-      collectVisibleContexts(SelectionCtx, SelectionLoc, *Inputs.AST);
+      collectVisibleContexts(SelectionCtx, SelectionLoc, Directives, SM);
 
   llvm::DenseSet<const NamedDecl *> AliasTargets;
   for (const Decl *D : Inputs.AST->getLocalTopLevelDecls()) {
@@ -289,7 +312,9 @@ ReplaceQualifiedWithAlias::apply(const Selection &Inputs) {
 
   // When the alias is declared inside a namespace, only rewrite references in
   // declarations where that namespace is visible (either directly enclosed by
-  // the namespace or via an active using-directive).
+  // the namespace or via an active using-directive). Collect all using-
+  // directives once up front so visibility checks do not re-traverse the AST.
+  auto Directives = collectUsingDirectives(*Inputs.AST);
   auto ProcessDecl = [&](auto &&Self, const Decl *D) -> void {
     if (llvm::isa<NamespaceDecl, LinkageSpecDecl, ExportDecl>(D)) {
       const auto *DC = llvm::cast<DeclContext>(D);
@@ -304,7 +329,7 @@ ReplaceQualifiedWithAlias::apply(const Selection &Inputs) {
     const DeclContext *UseCtx = llvm::isa<DeclContext>(D)
                                     ? llvm::cast<DeclContext>(D)
                                     : D->getDeclContext();
-    auto Visible = collectVisibleContexts(UseCtx, DLoc, *Inputs.AST);
+    auto Visible = collectVisibleContexts(UseCtx, DLoc, Directives, SM);
     if (!Visible.contains(AliasPrimaryCtx))
       return;
 

>From 227acb7ab1ccf18ece5e90f0650dd58f7d0c447e Mon Sep 17 00:00:00 2001
From: Dimitri Ratz <dimitri.ratz at protonmail.com>
Date: Tue, 3 Nov 2026 09:47:02 +0100
Subject: [PATCH 16/16] format: minor fix.

---
 .../clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp    | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp b/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
index 76b2910109cdf7..962b90226585b1 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ReplaceQualifiedWithAlias.cpp
@@ -100,8 +100,7 @@ struct UsingDirectiveInfo {
 
 /// Collects all file/namespace-scope using-directives of the TU in a single
 /// pass, so that repeated visibility queries do not each re-traverse the AST.
-llvm::SmallVector<UsingDirectiveInfo>
-collectUsingDirectives(ParsedAST &AST) {
+llvm::SmallVector<UsingDirectiveInfo> collectUsingDirectives(ParsedAST &AST) {
   auto &SM = AST.getSourceManager();
   llvm::SmallVector<UsingDirectiveInfo> Directives;
   auto ScanDecl = [&](auto &&Self, const Decl *D) -> void {
@@ -127,7 +126,8 @@ collectUsingDirectives(ParsedAST &AST) {
 /// Computes the set of primary file/namespace DeclContexts visible for
 /// unqualified lookup at (\p UseCtx, \p UseLoc), including namespaces nominated
 /// by active using-directives before \p UseLoc. \p Directives must contain all
-/// file/namespace-scope using-directives of the TU (see collectUsingDirectives).
+/// file/namespace-scope using-directives of the TU (see
+/// collectUsingDirectives).
 llvm::SmallPtrSet<const DeclContext *, 8>
 collectVisibleContexts(const DeclContext *UseCtx, SourceLocation UseLoc,
                        llvm::ArrayRef<UsingDirectiveInfo> Directives,



More information about the cfe-commits mailing list