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"
29namespace reorder_fields {
31using llvm::SmallSetVector;
37 ASTContext &Context) {
39 match(recordDecl(hasName(RecordName), isDefinition()).bind(
"recordDecl"),
42 llvm::errs() <<
"Definition of " << RecordName <<
" not found\n";
46 llvm::errs() <<
"The name " << RecordName
47 <<
" is ambiguous, several definitions found\n";
50 return selectFirst<RecordDecl>(
"recordDecl",
Results);
56static SmallVector<unsigned, 4>
58 ArrayRef<std::string> DesiredFieldsOrder) {
59 assert(Definition &&
"Definition is null");
61 llvm::StringMap<unsigned> NameToIndex;
62 for (
const auto *
Field : Definition->fields())
63 NameToIndex[
Field->getName()] =
Field->getFieldIndex();
65 if (DesiredFieldsOrder.size() != NameToIndex.size()) {
66 llvm::errs() <<
"Number of provided fields doesn't match definition.\n";
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";
75 NewFieldsOrder.push_back(NameToIndex[
Name]);
77 assert(NewFieldsOrder.size() == NameToIndex.size());
78 return NewFieldsOrder;
85 std::map<std::string, tooling::Replacements> &Replacements) {
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));
99static SmallSetVector<FieldDecl *, 1>
101 ASTContext &Context) {
102 SmallSetVector<FieldDecl *, 1>
Results;
107 auto FoundExprs = match(
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()))
125 const RecordDecl *Definition, ArrayRef<unsigned> NewFieldsOrder,
126 const ASTContext &Context,
127 std::map<std::string, tooling::Replacements> &Replacements) {
128 assert(Definition &&
"Definition is null");
130 SmallVector<const FieldDecl *, 10> Fields;
131 for (
const auto *
Field : Definition->fields())
132 Fields.push_back(
Field);
135 for (
const auto *
Field : Definition->fields()) {
136 const auto FieldIndex =
Field->getFieldIndex();
137 if (
Field->getAccess() != Fields[NewFieldsOrder[FieldIndex]]->getAccess()) {
138 llvm::errs() <<
"Currently reordering of fields with different accesses "
139 "is not supported\n";
144 for (
const auto *
Field : Definition->fields()) {
145 const auto FieldIndex =
Field->getFieldIndex();
146 if (FieldIndex == NewFieldsOrder[FieldIndex])
149 Fields[NewFieldsOrder[FieldIndex]]->getSourceRange(),
150 Context, Replacements);
161 const CXXConstructorDecl *CtorDecl, ArrayRef<unsigned> NewFieldsOrder,
163 std::map<std::string, tooling::Replacements> &Replacements) {
164 assert(CtorDecl &&
"Constructor declaration is null");
165 if (CtorDecl->isImplicit() || CtorDecl->getNumCtorInitializers() <= 1)
171 assert(CtorDecl->isThisDeclarationADefinition() &&
"Not a definition");
173 SmallVector<unsigned, 10> NewFieldsPositions(NewFieldsOrder.size());
174 for (
unsigned i = 0, e = NewFieldsOrder.size(); i < e; ++i)
175 NewFieldsPositions[NewFieldsOrder[i]] = i;
177 SmallVector<const CXXCtorInitializer *, 10> OldWrittenInitializersOrder;
178 SmallVector<const CXXCtorInitializer *, 10> NewWrittenInitializersOrder;
179 for (
const auto *Initializer : CtorDecl->inits()) {
180 if (!Initializer->isMemberInitializer() || !Initializer->isWritten())
184 const FieldDecl *ThisM = Initializer->getMember();
186 for (
const FieldDecl *UM : UsedMembers) {
187 if (NewFieldsPositions[UM->getFieldIndex()] >
188 NewFieldsPositions[ThisM->getFieldIndex()]) {
189 DiagnosticsEngine &DiagEngine = Context.getDiagnostics();
190 auto Description = (
"reordering field " + UM->getName() +
" after " +
191 ThisM->getName() +
" makes " + UM->getName() +
192 " uninitialized when used in init expression")
194 unsigned ID = DiagEngine.getDiagnosticIDs()->getCustomDiagID(
195 DiagnosticIDs::Warning, Description);
196 DiagEngine.Report(Initializer->getSourceLocation(),
ID);
200 OldWrittenInitializersOrder.push_back(Initializer);
201 NewWrittenInitializersOrder.push_back(Initializer);
203 auto ByFieldNewPosition = [&](
const CXXCtorInitializer *LHS,
204 const CXXCtorInitializer *RHS) {
206 return NewFieldsPositions[LHS->getMember()->getFieldIndex()] <
207 NewFieldsPositions[RHS->getMember()->getFieldIndex()];
209 llvm::sort(NewWrittenInitializersOrder, ByFieldNewPosition);
210 assert(OldWrittenInitializersOrder.size() ==
211 NewWrittenInitializersOrder.size());
212 for (
unsigned i = 0, e = NewWrittenInitializersOrder.size(); i < e; ++i)
213 if (OldWrittenInitializersOrder[i] != NewWrittenInitializersOrder[i])
215 NewWrittenInitializersOrder[i]->getSourceRange(), Context,
224 const InitListExpr *InitListEx, ArrayRef<unsigned> NewFieldsOrder,
225 const ASTContext &Context,
226 std::map<std::string, tooling::Replacements> &Replacements) {
227 assert(InitListEx &&
"Init list expression is null");
230 if (!InitListEx->isExplicit())
234 if (
const auto *SyntacticForm = InitListEx->getSyntacticForm())
235 InitListEx = SyntacticForm;
237 if (!InitListEx->getNumInits())
239 if (InitListEx->getNumInits() != NewFieldsOrder.size()) {
240 llvm::errs() <<
"Currently only full initialization is supported\n";
243 for (
unsigned i = 0, e = InitListEx->getNumInits(); i < e; ++i)
244 if (i != NewFieldsOrder[i])
246 InitListEx->getInit(NewFieldsOrder[i])->getSourceRange(),
247 Context, Replacements);
253 StringRef RecordName;
254 ArrayRef<std::string> DesiredFieldsOrder;
255 std::map<std::string, tooling::Replacements> &Replacements;
258 ReorderingConsumer(StringRef RecordName,
259 ArrayRef<std::string> DesiredFieldsOrder,
260 std::map<std::string, tooling::Replacements> &Replacements)
261 : RecordName(RecordName), DesiredFieldsOrder(DesiredFieldsOrder),
262 Replacements(Replacements) {}
264 ReorderingConsumer(
const ReorderingConsumer &) =
delete;
265 ReorderingConsumer &operator=(
const ReorderingConsumer &) =
delete;
267 void HandleTranslationUnit(ASTContext &Context)
override {
271 SmallVector<unsigned, 4> NewFieldsOrder =
273 if (NewFieldsOrder.empty())
279 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
281 for (
const auto *
C : CXXRD->ctors())
282 if (
const auto *D = dyn_cast<CXXConstructorDecl>(
C->getDefinition()))
284 NewFieldsOrder, Context, Replacements);
291 if (!CXXRD || CXXRD->isAggregate())
293 match(initListExpr(hasType(equalsNode(RD))).bind(
"initListExpr"),
296 Result.getNodeAs<InitListExpr>(
"initListExpr"), NewFieldsOrder,
297 Context, Replacements)) {
298 Replacements.clear();
306 return std::make_unique<ReorderingConsumer>(RecordName, DesiredFieldsOrder,
llvm::SmallString< 256U > Name
std::vector< CodeCompletionResult > Results
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 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++ -*-===//