clang 19.0.0git
UsingDeclarationsSorter.cpp
Go to the documentation of this file.
1//===--- UsingDeclarationsSorter.cpp ----------------------------*- C++ -*-===//
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///
9/// \file
10/// This file implements UsingDeclarationsSorter, a TokenAnalyzer that
11/// sorts consecutive using declarations.
12///
13//===----------------------------------------------------------------------===//
14
16
17#define DEBUG_TYPE "using-declarations-sorter"
18
19namespace clang {
20namespace format {
21
22namespace {
23
24// The order of using declaration is defined as follows:
25// Split the strings by "::" and discard any initial empty strings. The last
26// element of each list is a non-namespace name; all others are namespace
27// names. Sort the lists of names lexicographically, where the sort order of
28// individual names is that all non-namespace names come before all namespace
29// names, and within those groups, names are in case-insensitive lexicographic
30// order.
31int compareLabelsLexicographicNumeric(StringRef A, StringRef B) {
32 SmallVector<StringRef, 2> NamesA;
33 A.split(NamesA, "::", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
34 SmallVector<StringRef, 2> NamesB;
35 B.split(NamesB, "::", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
36 size_t SizeA = NamesA.size();
37 size_t SizeB = NamesB.size();
38 for (size_t I = 0, E = std::min(SizeA, SizeB); I < E; ++I) {
39 if (I + 1 == SizeA) {
40 // I is the last index of NamesA and NamesA[I] is a non-namespace name.
41
42 // Non-namespace names come before all namespace names.
43 if (SizeB > SizeA)
44 return -1;
45
46 // Two names within a group compare case-insensitively.
47 return NamesA[I].compare_insensitive(NamesB[I]);
48 }
49
50 // I is the last index of NamesB and NamesB[I] is a non-namespace name.
51 // Non-namespace names come before all namespace names.
52 if (I + 1 == SizeB)
53 return 1;
54
55 // Two namespaces names within a group compare case-insensitively.
56 int C = NamesA[I].compare_insensitive(NamesB[I]);
57 if (C != 0)
58 return C;
59 }
60 return 0;
61}
62
63int compareLabelsLexicographic(StringRef A, StringRef B) {
64 SmallVector<StringRef, 2> NamesA;
65 A.split(NamesA, "::", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
66 SmallVector<StringRef, 2> NamesB;
67 B.split(NamesB, "::", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
68 size_t SizeA = NamesA.size();
69 size_t SizeB = NamesB.size();
70 for (size_t I = 0, E = std::min(SizeA, SizeB); I < E; ++I) {
71 // Two namespaces names within a group compare case-insensitively.
72 int C = NamesA[I].compare_insensitive(NamesB[I]);
73 if (C != 0)
74 return C;
75 }
76 if (SizeA < SizeB)
77 return -1;
78 return SizeA == SizeB ? 0 : 1;
79}
80
81int compareLabels(
82 StringRef A, StringRef B,
83 FormatStyle::SortUsingDeclarationsOptions SortUsingDeclarations) {
84 if (SortUsingDeclarations == FormatStyle::SUD_LexicographicNumeric)
85 return compareLabelsLexicographicNumeric(A, B);
86 return compareLabelsLexicographic(A, B);
87}
88
89struct UsingDeclaration {
90 const AnnotatedLine *Line;
91 std::string Label;
92
93 UsingDeclaration(const AnnotatedLine *Line, const std::string &Label)
94 : Line(Line), Label(Label) {}
95};
96
97/// Computes the label of a using declaration starting at tthe using token
98/// \p UsingTok.
99/// If \p UsingTok doesn't begin a using declaration, returns the empty string.
100/// Note that this detects specifically using declarations, as in:
101/// using A::B::C;
102/// and not type aliases, as in:
103/// using A = B::C;
104/// Type aliases are in general not safe to permute.
105std::string computeUsingDeclarationLabel(const FormatToken *UsingTok) {
106 assert(UsingTok && UsingTok->is(tok::kw_using) && "Expecting a using token");
107 std::string Label;
108 const FormatToken *Tok = UsingTok->Next;
109 if (Tok && Tok->is(tok::kw_typename)) {
110 Label.append("typename ");
111 Tok = Tok->Next;
112 }
113 if (Tok && Tok->is(tok::coloncolon)) {
114 Label.append("::");
115 Tok = Tok->Next;
116 }
117 bool HasIdentifier = false;
118 while (Tok && Tok->is(tok::identifier)) {
119 HasIdentifier = true;
120 Label.append(Tok->TokenText.str());
121 Tok = Tok->Next;
122 if (!Tok || Tok->isNot(tok::coloncolon))
123 break;
124 Label.append("::");
125 Tok = Tok->Next;
126 }
127 if (HasIdentifier && Tok && Tok->isOneOf(tok::semi, tok::comma))
128 return Label;
129 return "";
130}
131
132void endUsingDeclarationBlock(
133 SmallVectorImpl<UsingDeclaration> *UsingDeclarations,
134 const SourceManager &SourceMgr, tooling::Replacements *Fixes,
135 FormatStyle::SortUsingDeclarationsOptions SortUsingDeclarations) {
136 bool BlockAffected = false;
137 for (const UsingDeclaration &Declaration : *UsingDeclarations) {
138 if (Declaration.Line->Affected) {
139 BlockAffected = true;
140 break;
141 }
142 }
143 if (!BlockAffected) {
144 UsingDeclarations->clear();
145 return;
146 }
147 SmallVector<UsingDeclaration, 4> SortedUsingDeclarations(
148 UsingDeclarations->begin(), UsingDeclarations->end());
149 auto Comp = [SortUsingDeclarations](const UsingDeclaration &Lhs,
150 const UsingDeclaration &Rhs) -> bool {
151 return compareLabels(Lhs.Label, Rhs.Label, SortUsingDeclarations) < 0;
152 };
153 llvm::stable_sort(SortedUsingDeclarations, Comp);
154 SortedUsingDeclarations.erase(
155 std::unique(SortedUsingDeclarations.begin(),
156 SortedUsingDeclarations.end(),
157 [](const UsingDeclaration &a, const UsingDeclaration &b) {
158 return a.Label == b.Label;
159 }),
160 SortedUsingDeclarations.end());
161 for (size_t I = 0, E = UsingDeclarations->size(); I < E; ++I) {
162 if (I >= SortedUsingDeclarations.size()) {
163 // This using declaration has been deduplicated, delete it.
164 auto Begin =
165 (*UsingDeclarations)[I].Line->First->WhitespaceRange.getBegin();
166 auto End = (*UsingDeclarations)[I].Line->Last->Tok.getEndLoc();
168 auto Err = Fixes->add(tooling::Replacement(SourceMgr, Range, ""));
169 if (Err) {
170 llvm::errs() << "Error while sorting using declarations: "
171 << llvm::toString(std::move(Err)) << "\n";
172 }
173 continue;
174 }
175 if ((*UsingDeclarations)[I].Line == SortedUsingDeclarations[I].Line)
176 continue;
177 auto Begin = (*UsingDeclarations)[I].Line->First->Tok.getLocation();
178 auto End = (*UsingDeclarations)[I].Line->Last->Tok.getEndLoc();
179 auto SortedBegin =
180 SortedUsingDeclarations[I].Line->First->Tok.getLocation();
181 auto SortedEnd = SortedUsingDeclarations[I].Line->Last->Tok.getEndLoc();
182 StringRef Text(SourceMgr.getCharacterData(SortedBegin),
183 SourceMgr.getCharacterData(SortedEnd) -
184 SourceMgr.getCharacterData(SortedBegin));
185 LLVM_DEBUG({
186 StringRef OldText(SourceMgr.getCharacterData(Begin),
187 SourceMgr.getCharacterData(End) -
188 SourceMgr.getCharacterData(Begin));
189 llvm::dbgs() << "Replacing '" << OldText << "' with '" << Text << "'\n";
190 });
192 auto Err = Fixes->add(tooling::Replacement(SourceMgr, Range, Text));
193 if (Err) {
194 llvm::errs() << "Error while sorting using declarations: "
195 << llvm::toString(std::move(Err)) << "\n";
196 }
197 }
198 UsingDeclarations->clear();
199}
200
201} // namespace
202
204 const FormatStyle &Style)
205 : TokenAnalyzer(Env, Style) {}
206
207std::pair<tooling::Replacements, unsigned> UsingDeclarationsSorter::analyze(
208 TokenAnnotator &Annotator, SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
209 FormatTokenLexer &Tokens) {
210 const SourceManager &SourceMgr = Env.getSourceManager();
213 SmallVector<UsingDeclaration, 4> UsingDeclarations;
214 for (const AnnotatedLine *Line : AnnotatedLines) {
215 const auto *FirstTok = Line->First;
216 if (Line->InPPDirective || !Line->startsWith(tok::kw_using) ||
217 FirstTok->Finalized) {
218 endUsingDeclarationBlock(&UsingDeclarations, SourceMgr, &Fixes,
220 continue;
221 }
222 if (FirstTok->NewlinesBefore > 1) {
223 endUsingDeclarationBlock(&UsingDeclarations, SourceMgr, &Fixes,
225 }
226 const auto *UsingTok =
227 FirstTok->is(tok::comment) ? FirstTok->getNextNonComment() : FirstTok;
228 std::string Label = computeUsingDeclarationLabel(UsingTok);
229 if (Label.empty()) {
230 endUsingDeclarationBlock(&UsingDeclarations, SourceMgr, &Fixes,
232 continue;
233 }
234 UsingDeclarations.push_back(UsingDeclaration(Line, Label));
235 }
236 endUsingDeclarationBlock(&UsingDeclarations, SourceMgr, &Fixes,
238 return {Fixes, 0};
239}
240
241} // namespace format
242} // namespace clang
StringRef Text
Definition: Format.cpp:2953
const Environment & Env
Definition: HTMLLogger.cpp:148
SourceLocation Begin
std::string Label
This file declares UsingDeclarationsSorter, a TokenAnalyzer that sorts consecutive using declarations...
__device__ __2f16 b
static CharSourceRange getCharRange(SourceRange R)
This class handles loading and caching of source files into memory.
bool computeAffectedLines(SmallVectorImpl< AnnotatedLine * > &Lines)
SourceManager & getSourceManager() const
Definition: TokenAnalyzer.h:38
AffectedRangeManager AffectedRangeMgr
Definition: TokenAnalyzer.h:98
const Environment & Env
Definition: TokenAnalyzer.h:96
Determines extra information about the tokens comprising an UnwrappedLine.
std::pair< tooling::Replacements, unsigned > analyze(TokenAnnotator &Annotator, SmallVectorImpl< AnnotatedLine * > &AnnotatedLines, FormatTokenLexer &Tokens) override
UsingDeclarationsSorter(const Environment &Env, const FormatStyle &Style)
Maintains a set of replacements that are conflict-free.
Definition: Replacement.h:212
bool Comp(InterpState &S, CodePtr OpPC)
1) Pops the value from the stack.
Definition: Interp.h:708
The JSON file list parser is used to communicate input to InstallAPI.
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition: Format.h:55
SortUsingDeclarationsOptions
Using declaration sorting options.
Definition: Format.h:4063
@ SUD_LexicographicNumeric
Using declarations are sorted in the order defined as follows: Split the strings by "::" and discard ...
Definition: Format.h:4099
SortUsingDeclarationsOptions SortUsingDeclarations
Controls if and how clang-format will sort using declarations.
Definition: Format.h:4104