clang-tools 20.0.0git
ReorderFieldsAction.cpp
Go to the documentation of this file.
1//===-- tools/extra/clang-reorder-fields/ReorderFieldsAction.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 contains the definition of the
11/// ReorderFieldsAction::newASTConsumer method
12///
13//===----------------------------------------------------------------------===//
14
15#include "ReorderFieldsAction.h"
16#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/RecursiveASTVisitor.h"
21#include "clang/ASTMatchers/ASTMatchFinder.h"
22#include "clang/Lex/Lexer.h"
23#include "clang/Tooling/Refactoring.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SetVector.h"
26#include <string>
27
28namespace clang {
29namespace reorder_fields {
30using namespace clang::ast_matchers;
31using llvm::SmallSetVector;
32
33/// Finds the definition of a record by name.
34///
35/// \returns nullptr if the name is ambiguous or not found.
36static const RecordDecl *findDefinition(StringRef RecordName,
37 ASTContext &Context) {
38 auto Results =
39 match(recordDecl(hasName(RecordName), isDefinition()).bind("recordDecl"),
40 Context);
41 if (Results.empty()) {
42 llvm::errs() << "Definition of " << RecordName << " not found\n";
43 return nullptr;
44 }
45 if (Results.size() > 1) {
46 llvm::errs() << "The name " << RecordName
47 << " is ambiguous, several definitions found\n";
48 return nullptr;
49 }
50 return selectFirst<RecordDecl>("recordDecl", Results);
51}
52
53/// Calculates the new order of fields.
54///
55/// \returns empty vector if the list of fields doesn't match the definition.
56static SmallVector<unsigned, 4>
57getNewFieldsOrder(const RecordDecl *Definition,
58 ArrayRef<std::string> DesiredFieldsOrder) {
59 assert(Definition && "Definition is null");
60
61 llvm::StringMap<unsigned> NameToIndex;
62 for (const auto *Field : Definition->fields())
63 NameToIndex[Field->getName()] = Field->getFieldIndex();
64
65 if (DesiredFieldsOrder.size() != NameToIndex.size()) {
66 llvm::errs() << "Number of provided fields doesn't match definition.\n";
67 return {};
68 }
69 SmallVector<unsigned, 4> NewFieldsOrder;
70 for (const auto &Name : DesiredFieldsOrder) {
71 if (!NameToIndex.count(Name)) {
72 llvm::errs() << "Field " << Name << " not found in definition.\n";
73 return {};
74 }
75 NewFieldsOrder.push_back(NameToIndex[Name]);
76 }
77 assert(NewFieldsOrder.size() == NameToIndex.size());
78 return NewFieldsOrder;
79}
80
81// FIXME: error-handling
82/// Replaces one range of source code by another.
83static void
84addReplacement(SourceRange Old, SourceRange New, const ASTContext &Context,
85 std::map<std::string, tooling::Replacements> &Replacements) {
86 StringRef NewText =
87 Lexer::getSourceText(CharSourceRange::getTokenRange(New),
88 Context.getSourceManager(), Context.getLangOpts());
89 tooling::Replacement R(Context.getSourceManager(),
90 CharSourceRange::getTokenRange(Old), NewText,
91 Context.getLangOpts());
92 consumeError(Replacements[std::string(R.getFilePath())].add(R));
93}
94
95/// Find all member fields used in the given init-list initializer expr
96/// that belong to the same record
97///
98/// \returns a set of field declarations, empty if none were present
99static SmallSetVector<FieldDecl *, 1>
100findMembersUsedInInitExpr(const CXXCtorInitializer *Initializer,
101 ASTContext &Context) {
102 SmallSetVector<FieldDecl *, 1> Results;
103 // Note that this does not pick up member fields of base classes since
104 // for those accesses Sema::PerformObjectMemberConversion always inserts an
105 // UncheckedDerivedToBase ImplicitCastExpr between the this expr and the
106 // object expression
107 auto FoundExprs = match(
108 traverse(
109 TK_AsIs,
110 findAll(memberExpr(hasObjectExpression(cxxThisExpr())).bind("ME"))),
111 *Initializer->getInit(), Context);
112 for (BoundNodes &BN : FoundExprs)
113 if (auto *MemExpr = BN.getNodeAs<MemberExpr>("ME"))
114 if (auto *FD = dyn_cast<FieldDecl>(MemExpr->getMemberDecl()))
115 Results.insert(FD);
116 return Results;
117}
118
119/// Returns the full source range for the field declaration up to (not
120/// including) the trailing semicolumn, including potential macro invocations,
121/// e.g. `int a GUARDED_BY(mu);`.
122static SourceRange getFullFieldSourceRange(const FieldDecl &Field,
123 const ASTContext &Context) {
124 SourceRange Range = Field.getSourceRange();
125 SourceLocation End = Range.getEnd();
126 const SourceManager &SM = Context.getSourceManager();
127 const LangOptions &LangOpts = Context.getLangOpts();
128 while (true) {
129 std::optional<Token> CurrentToken = Lexer::findNextToken(End, SM, LangOpts);
130
131 if (!CurrentToken || CurrentToken->is(tok::semi))
132 break;
133
134 if (CurrentToken->is(tok::eof))
135 return Range; // Something is wrong, return the original range.
136 End = CurrentToken->getLastLoc();
137 }
138 return SourceRange(Range.getBegin(), End);
139}
140
141/// Reorders fields in the definition of a struct/class.
142///
143/// At the moment reordering of fields with
144/// different accesses (public/protected/private) is not supported.
145/// \returns true on success.
147 const RecordDecl *Definition, ArrayRef<unsigned> NewFieldsOrder,
148 const ASTContext &Context,
149 std::map<std::string, tooling::Replacements> &Replacements) {
150 assert(Definition && "Definition is null");
151
152 SmallVector<const FieldDecl *, 10> Fields;
153 for (const auto *Field : Definition->fields())
154 Fields.push_back(Field);
155
156 // Check that the permutation of the fields doesn't change the accesses
157 for (const auto *Field : Definition->fields()) {
158 const auto FieldIndex = Field->getFieldIndex();
159 if (Field->getAccess() != Fields[NewFieldsOrder[FieldIndex]]->getAccess()) {
160 llvm::errs() << "Currently reordering of fields with different accesses "
161 "is not supported\n";
162 return false;
163 }
164 }
165
166 for (const auto *Field : Definition->fields()) {
167 const auto FieldIndex = Field->getFieldIndex();
168 if (FieldIndex == NewFieldsOrder[FieldIndex])
169 continue;
172 getFullFieldSourceRange(*Fields[NewFieldsOrder[FieldIndex]], Context),
173 Context, Replacements);
174 }
175 return true;
176}
177
178/// Reorders initializers in a C++ struct/class constructor.
179///
180/// A constructor can have initializers for an arbitrary subset of the class's
181/// fields. Thus, we need to ensure that we reorder just the initializers that
182/// are present.
184 const CXXConstructorDecl *CtorDecl, ArrayRef<unsigned> NewFieldsOrder,
185 ASTContext &Context,
186 std::map<std::string, tooling::Replacements> &Replacements) {
187 assert(CtorDecl && "Constructor declaration is null");
188 if (CtorDecl->isImplicit() || CtorDecl->getNumCtorInitializers() <= 1)
189 return;
190
191 // The method FunctionDecl::isThisDeclarationADefinition returns false
192 // for a defaulted function unless that function has been implicitly defined.
193 // Thus this assert needs to be after the previous checks.
194 assert(CtorDecl->isThisDeclarationADefinition() && "Not a definition");
195
196 SmallVector<unsigned, 10> NewFieldsPositions(NewFieldsOrder.size());
197 for (unsigned i = 0, e = NewFieldsOrder.size(); i < e; ++i)
198 NewFieldsPositions[NewFieldsOrder[i]] = i;
199
200 SmallVector<const CXXCtorInitializer *, 10> OldWrittenInitializersOrder;
201 SmallVector<const CXXCtorInitializer *, 10> NewWrittenInitializersOrder;
202 for (const auto *Initializer : CtorDecl->inits()) {
203 if (!Initializer->isMemberInitializer() || !Initializer->isWritten())
204 continue;
205
206 // Warn if this reordering violates initialization expr dependencies.
207 const FieldDecl *ThisM = Initializer->getMember();
208 const auto UsedMembers = findMembersUsedInInitExpr(Initializer, Context);
209 for (const FieldDecl *UM : UsedMembers) {
210 if (NewFieldsPositions[UM->getFieldIndex()] >
211 NewFieldsPositions[ThisM->getFieldIndex()]) {
212 DiagnosticsEngine &DiagEngine = Context.getDiagnostics();
213 auto Description = ("reordering field " + UM->getName() + " after " +
214 ThisM->getName() + " makes " + UM->getName() +
215 " uninitialized when used in init expression")
216 .str();
217 unsigned ID = DiagEngine.getDiagnosticIDs()->getCustomDiagID(
218 DiagnosticIDs::Warning, Description);
219 DiagEngine.Report(Initializer->getSourceLocation(), ID);
220 }
221 }
222
223 OldWrittenInitializersOrder.push_back(Initializer);
224 NewWrittenInitializersOrder.push_back(Initializer);
225 }
226 auto ByFieldNewPosition = [&](const CXXCtorInitializer *LHS,
227 const CXXCtorInitializer *RHS) {
228 assert(LHS && RHS);
229 return NewFieldsPositions[LHS->getMember()->getFieldIndex()] <
230 NewFieldsPositions[RHS->getMember()->getFieldIndex()];
231 };
232 llvm::sort(NewWrittenInitializersOrder, ByFieldNewPosition);
233 assert(OldWrittenInitializersOrder.size() ==
234 NewWrittenInitializersOrder.size());
235 for (unsigned i = 0, e = NewWrittenInitializersOrder.size(); i < e; ++i)
236 if (OldWrittenInitializersOrder[i] != NewWrittenInitializersOrder[i])
237 addReplacement(OldWrittenInitializersOrder[i]->getSourceRange(),
238 NewWrittenInitializersOrder[i]->getSourceRange(), Context,
239 Replacements);
240}
241
242/// Reorders initializers in the brace initialization of an aggregate.
243///
244/// At the moment partial initialization is not supported.
245/// \returns true on success
247 const InitListExpr *InitListEx, ArrayRef<unsigned> NewFieldsOrder,
248 const ASTContext &Context,
249 std::map<std::string, tooling::Replacements> &Replacements) {
250 assert(InitListEx && "Init list expression is null");
251 // We care only about InitListExprs which originate from source code.
252 // Implicit InitListExprs are created by the semantic analyzer.
253 if (!InitListEx->isExplicit())
254 return true;
255 // The method InitListExpr::getSyntacticForm may return nullptr indicating
256 // that the current initializer list also serves as its syntactic form.
257 if (const auto *SyntacticForm = InitListEx->getSyntacticForm())
258 InitListEx = SyntacticForm;
259 // If there are no initializers we do not need to change anything.
260 if (!InitListEx->getNumInits())
261 return true;
262 if (InitListEx->getNumInits() != NewFieldsOrder.size()) {
263 llvm::errs() << "Currently only full initialization is supported\n";
264 return false;
265 }
266 for (unsigned i = 0, e = InitListEx->getNumInits(); i < e; ++i)
267 if (i != NewFieldsOrder[i])
268 addReplacement(InitListEx->getInit(i)->getSourceRange(),
269 InitListEx->getInit(NewFieldsOrder[i])->getSourceRange(),
270 Context, Replacements);
271 return true;
272}
273
274namespace {
275class ReorderingConsumer : public ASTConsumer {
276 StringRef RecordName;
277 ArrayRef<std::string> DesiredFieldsOrder;
278 std::map<std::string, tooling::Replacements> &Replacements;
279
280public:
281 ReorderingConsumer(StringRef RecordName,
282 ArrayRef<std::string> DesiredFieldsOrder,
283 std::map<std::string, tooling::Replacements> &Replacements)
284 : RecordName(RecordName), DesiredFieldsOrder(DesiredFieldsOrder),
285 Replacements(Replacements) {}
286
287 ReorderingConsumer(const ReorderingConsumer &) = delete;
288 ReorderingConsumer &operator=(const ReorderingConsumer &) = delete;
289
290 void HandleTranslationUnit(ASTContext &Context) override {
291 const RecordDecl *RD = findDefinition(RecordName, Context);
292 if (!RD)
293 return;
294 SmallVector<unsigned, 4> NewFieldsOrder =
295 getNewFieldsOrder(RD, DesiredFieldsOrder);
296 if (NewFieldsOrder.empty())
297 return;
298 if (!reorderFieldsInDefinition(RD, NewFieldsOrder, Context, Replacements))
299 return;
300
301 // CXXRD will be nullptr if C code (not C++) is being processed.
302 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
303 if (CXXRD)
304 for (const auto *C : CXXRD->ctors())
305 if (const auto *D = dyn_cast<CXXConstructorDecl>(C->getDefinition()))
306 reorderFieldsInConstructor(cast<const CXXConstructorDecl>(D),
307 NewFieldsOrder, Context, Replacements);
308
309 // We only need to reorder init list expressions for
310 // plain C structs or C++ aggregate types.
311 // For other types the order of constructor parameters is used,
312 // which we don't change at the moment.
313 // Now (v0) partial initialization is not supported.
314 if (!CXXRD || CXXRD->isAggregate())
315 for (auto Result :
316 match(initListExpr(hasType(equalsNode(RD))).bind("initListExpr"),
317 Context))
319 Result.getNodeAs<InitListExpr>("initListExpr"), NewFieldsOrder,
320 Context, Replacements)) {
321 Replacements.clear();
322 return;
323 }
324 }
325};
326} // end anonymous namespace
327
328std::unique_ptr<ASTConsumer> ReorderFieldsAction::newASTConsumer() {
329 return std::make_unique<ReorderingConsumer>(RecordName, DesiredFieldsOrder,
330 Replacements);
331}
332
333} // namespace reorder_fields
334} // namespace clang
llvm::SmallString< 256U > Name
std::vector< CodeCompletionResult > Results
const Criteria C
CharSourceRange Range
SourceRange for the file name.
const FieldDecl * Field
This file contains the declarations of the ReorderFieldsAction class and the FieldPosition struct.
std::unique_ptr< ASTConsumer > newASTConsumer()
static void reorderFieldsInConstructor(const CXXConstructorDecl *CtorDecl, ArrayRef< unsigned > NewFieldsOrder, ASTContext &Context, std::map< std::string, tooling::Replacements > &Replacements)
Reorders initializers in a C++ struct/class constructor.
static const RecordDecl * findDefinition(StringRef RecordName, ASTContext &Context)
Finds the definition of a record by name.
static bool reorderFieldsInInitListExpr(const InitListExpr *InitListEx, ArrayRef< unsigned > NewFieldsOrder, const ASTContext &Context, std::map< std::string, tooling::Replacements > &Replacements)
Reorders initializers in the brace initialization of an aggregate.
static void addReplacement(SourceRange Old, SourceRange New, const ASTContext &Context, std::map< std::string, tooling::Replacements > &Replacements)
Replaces one range of source code by another.
static SourceRange getFullFieldSourceRange(const FieldDecl &Field, const ASTContext &Context)
Returns the full source range for the field declaration up to (not including) the trailing semicolumn...
static SmallSetVector< FieldDecl *, 1 > findMembersUsedInInitExpr(const CXXCtorInitializer *Initializer, ASTContext &Context)
Find all member fields used in the given init-list initializer expr that belong to the same record.
static bool reorderFieldsInDefinition(const RecordDecl *Definition, ArrayRef< unsigned > NewFieldsOrder, const ASTContext &Context, std::map< std::string, tooling::Replacements > &Replacements)
Reorders fields in the definition of a struct/class.
static SmallVector< unsigned, 4 > getNewFieldsOrder(const RecordDecl *Definition, ArrayRef< std::string > DesiredFieldsOrder)
Calculates the new order of fields.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//