[clang-tools-extra] [clangd] Add AddUsingReplaceAll tweak to replace all qualified refere… (PR #204151)
Aleksandr Platonov via cfe-commits
cfe-commits at lists.llvm.org
Sat Nov 7 13:32:12 PST 2026
================
@@ -0,0 +1,366 @@
+//===--- 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 "QualifiedNameRewrite.h"
+#include "refactor/Tweak.h"
+#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"
+#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"
+#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:
+ const NamedDecl *SelectedAlias = nullptr;
+ std::string AliasName;
+ SourceRange AliasDeclToSkip;
+ llvm::DenseSet<const NamedDecl *> RewriteTargets;
+};
+REGISTER_TWEAK(ReplaceQualifiedWithAlias)
+
+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
+ // 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();
+}
+
+/// 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. \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,
+ 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());
+ }
+
+ bool Changed = true;
+ while (Changed) {
+ Changed = false;
+ 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;
+}
+
+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;
+ }
+
+ // 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 {
+ return std::string(
+ llvm::formatv("Replace qualified references with {0}", AliasName));
+}
+
+bool ReplaceQualifiedWithAlias::prepare(const Selection &Inputs) {
+ // Reset all cached state before inspecting the new selection.
+ SelectedAlias = nullptr;
+ AliasName.clear();
+ AliasDeclToSkip = SourceRange();
+ RewriteTargets.clear();
+
+ 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.
+ 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();
+ return true;
+ }
+ }
+
+ if (!Prepared.HasQualifiedRef)
+ return false;
+
+ // 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();
+ SourceLocation SelectionLoc =
+ SM.getExpansionLoc(Prepared.QualifierToRemove.getBeginLoc());
+ const DeclContext *SelectionCtx =
+ &Inputs.ASTSelection.commonAncestor()->getDeclContext();
+ auto Directives = collectUsingDirectives(*Inputs.AST);
----------------
ArcsinX wrote:
this still does the full AST traversal in prepare.
https://github.com/llvm/llvm-project/pull/204151
More information about the cfe-commits
mailing list