clang-tools 22.0.0git
ConcatNestedNamespacesCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "../utils/LexerUtils.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/AST/Decl.h"
13#include "clang/ASTMatchers/ASTMatchFinder.h"
14#include "clang/Basic/SourceLocation.h"
15#include <optional>
16
17namespace clang::tidy::modernize {
18
19static bool locationsInSameFile(const SourceManager &Sources,
20 SourceLocation Loc1, SourceLocation Loc2) {
21 return Loc1.isFileID() && Loc2.isFileID() &&
22 Sources.getFileID(Loc1) == Sources.getFileID(Loc2);
23}
24
25static StringRef getRawStringRef(const SourceRange &Range,
26 const SourceManager &Sources,
27 const LangOptions &LangOpts) {
28 const CharSourceRange TextRange =
29 Lexer::getAsCharRange(Range, Sources, LangOpts);
30 return Lexer::getSourceText(TextRange, Sources, LangOpts);
31}
32
33std::optional<SourceRange>
34NS::getCleanedNamespaceFrontRange(const SourceManager &SM,
35 const LangOptions &LangOpts) const {
36 // Front from namespace tp '{'
37 std::optional<Token> Tok = utils::lexer::findNextTokenSkippingComments(
38 back()->getLocation(), SM, LangOpts);
39 if (!Tok)
40 return std::nullopt;
41 while (Tok->getKind() != tok::TokenKind::l_brace) {
42 Tok = utils::lexer::findNextTokenSkippingComments(Tok->getEndLoc(), SM,
43 LangOpts);
44 if (!Tok)
45 return std::nullopt;
46 }
47 return SourceRange{front()->getBeginLoc(), Tok->getEndLoc()};
48}
50 return SourceRange{front()->getBeginLoc(), back()->getLocation()};
51}
52
54 return SourceRange{front()->getRBraceLoc(), front()->getRBraceLoc()};
55}
56SourceRange NS::getNamespaceBackRange(const SourceManager &SM,
57 const LangOptions &LangOpts) const {
58 // Back from '}' to conditional '// namespace xxx'
59 const SourceLocation Loc = front()->getRBraceLoc();
60 std::optional<Token> Tok =
62 if (!Tok)
64 if (Tok->getKind() != tok::TokenKind::comment)
66 const SourceRange TokRange =
67 SourceRange{Tok->getLocation(), Tok->getEndLoc()};
68 const StringRef TokText = getRawStringRef(TokRange, SM, LangOpts);
69 NamespaceName CloseComment{"namespace "};
70 appendCloseComment(CloseComment);
71 // current fix hint in readability/NamespaceCommentCheck.cpp use single line
72 // comment
73 constexpr size_t L = sizeof("//") - 1U;
74 if (TokText.take_front(L) == "//" &&
75 TokText.drop_front(L).trim() != CloseComment)
77 return SourceRange{front()->getRBraceLoc(), Tok->getEndLoc()};
78}
79
80void NS::appendName(NamespaceName &Str) const {
81 for (const NamespaceDecl *ND : *this) {
82 if (ND->isInlineNamespace())
83 Str.append("inline ");
84 Str.append(ND->getName());
85 if (ND != back())
86 Str.append("::");
87 }
88}
90 if (size() == 1)
91 Str.append(back()->getName());
92 else
93 appendName(Str);
94}
95
97 bool IsChild) const {
98 if (ND.isAnonymousNamespace() || !ND.attrs().empty())
99 return true;
100 if (getLangOpts().CPlusPlus20) {
101 // C++20 support inline nested namespace
102 const bool IsFirstNS = IsChild || !Namespaces.empty();
103 return ND.isInlineNamespace() && !IsFirstNS;
104 }
105 return ND.isInlineNamespace();
106}
107
109 const NamespaceDecl &ND) const {
110 const NamespaceDecl::decl_range Decls = ND.decls();
111 if (std::distance(Decls.begin(), Decls.end()) != 1)
112 return false;
113
114 const auto *ChildNamespace = dyn_cast<const NamespaceDecl>(*Decls.begin());
115 return ChildNamespace && !unsupportedNamespace(*ChildNamespace, true);
116}
117
119 ast_matchers::MatchFinder *Finder) {
120 Finder->addMatcher(ast_matchers::namespaceDecl().bind("namespace"), this);
121}
122
123void ConcatNestedNamespacesCheck::reportDiagnostic(
124 const SourceManager &SM, const LangOptions &LangOpts) {
125 const DiagnosticBuilder DB =
126 diag(Namespaces.front().front()->getBeginLoc(),
127 "nested namespaces can be concatenated", DiagnosticIDs::Warning);
128
129 SmallVector<SourceRange, 6> Fronts;
130 Fronts.reserve(Namespaces.size() - 1U);
131 SmallVector<SourceRange, 6> Backs;
132 Backs.reserve(Namespaces.size());
133
134 for (const NS &ND : Namespaces) {
135 std::optional<SourceRange> SR =
136 ND.getCleanedNamespaceFrontRange(SM, LangOpts);
137 if (!SR)
138 return;
139 Fronts.push_back(SR.value());
140 Backs.push_back(ND.getNamespaceBackRange(SM, LangOpts));
141 }
142 if (Fronts.empty() || Backs.empty())
143 return;
144
145 // the last one should be handled specially
146 Fronts.pop_back();
147 const SourceRange LastRBrace = Backs.pop_back_val();
148
149 NamespaceName ConcatNameSpace{"namespace "};
150 for (const NS &NS : Namespaces) {
151 NS.appendName(ConcatNameSpace);
152 if (&NS != &Namespaces.back()) // compare address directly
153 ConcatNameSpace.append("::");
154 }
155
156 for (const SourceRange &Front : Fronts)
157 DB << FixItHint::CreateRemoval(Front);
158 DB << FixItHint::CreateReplacement(
159 Namespaces.back().getReplacedNamespaceFrontRange(), ConcatNameSpace);
160 if (LastRBrace != Namespaces.back().getDefaultNamespaceBackRange())
161 DB << FixItHint::CreateReplacement(LastRBrace,
162 ("} // " + ConcatNameSpace).str());
163 for (const SourceRange &Back : llvm::reverse(Backs))
164 DB << FixItHint::CreateRemoval(Back);
165}
166
168 const ast_matchers::MatchFinder::MatchResult &Result) {
169 const NamespaceDecl &ND = *Result.Nodes.getNodeAs<NamespaceDecl>("namespace");
170 const SourceManager &Sources = *Result.SourceManager;
171
172 if (!locationsInSameFile(Sources, ND.getBeginLoc(), ND.getRBraceLoc()))
173 return;
174
175 if (unsupportedNamespace(ND, false))
176 return;
177
178 if (!ND.isNested())
179 Namespaces.push_back(NS{});
180 if (!Namespaces.empty())
181 // Otherwise it will crash with invalid input like `inline namespace
182 // a::b::c`.
183 Namespaces.back().push_back(&ND);
184
186 return;
187
188 if (Namespaces.size() > 1)
189 reportDiagnostic(Sources, getLangOpts());
190
191 Namespaces.clear();
192}
193
194} // namespace clang::tidy::modernize
bool unsupportedNamespace(const NamespaceDecl &ND, bool IsChild) const
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void appendName(NamespaceName &Str) const
std::optional< SourceRange > getCleanedNamespaceFrontRange(const SourceManager &SM, const LangOptions &LangOpts) const
SourceRange getNamespaceBackRange(const SourceManager &SM, const LangOptions &LangOpts) const
void appendCloseComment(NamespaceName &Str) const
llvm::SmallString< 40 > NamespaceName
static DeclarationName getName(const DependentScopeDeclRefExpr &D)
static StringRef getRawStringRef(const SourceRange &Range, const SourceManager &Sources, const LangOptions &LangOpts)
static bool locationsInSameFile(const SourceManager &Sources, SourceLocation Loc1, SourceLocation Loc2)
std::optional< Token > findNextTokenSkippingComments(SourceLocation Start, const SourceManager &SM, const LangOptions &LangOpts)
Definition LexerUtils.h:101
std::optional< Token > findNextTokenIncludingComments(SourceLocation Start, const SourceManager &SM, const LangOptions &LangOpts)
Definition LexerUtils.h:94