Skip to content

Commit 91285e2

Browse files
authored
[clang-reorder-fields] Handle macros fields declarations. (#118005)
Right now fields with macro declarations break the tool: ``` struct Foo { Mutex mu; int x GUARDED_BY(mu); int y; }; ``` reordered by mu,y,x yields: ``` struct Foo { Mutex mu; int y GUARDED_BY(mu); int x; }; ```
1 parent e034c4e commit 91285e2

File tree

2 files changed

+35
-3
lines changed

2 files changed

+35
-3
lines changed

clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,28 @@ findMembersUsedInInitExpr(const CXXCtorInitializer *Initializer,
116116
return Results;
117117
}
118118

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);`.
122+
static 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+
119141
/// Reorders fields in the definition of a struct/class.
120142
///
121143
/// At the moment reordering of fields with
@@ -145,9 +167,10 @@ static bool reorderFieldsInDefinition(
145167
const auto FieldIndex = Field->getFieldIndex();
146168
if (FieldIndex == NewFieldsOrder[FieldIndex])
147169
continue;
148-
addReplacement(Field->getSourceRange(),
149-
Fields[NewFieldsOrder[FieldIndex]]->getSourceRange(),
150-
Context, Replacements);
170+
addReplacement(
171+
getFullFieldSourceRange(*Field, Context),
172+
getFullFieldSourceRange(*Fields[NewFieldsOrder[FieldIndex]], Context),
173+
Context, Replacements);
151174
}
152175
return true;
153176
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// RUN: clang-reorder-fields -record-name Foo -fields-order y,x %s -- | FileCheck %s
2+
3+
#define GUARDED_BY(x) __attribute__((guarded_by(x)))
4+
5+
class Foo {
6+
int x GUARDED_BY(x); // CHECK: {{^ int y;}}
7+
int y; // CHECK-NEXT: {{^ int x GUARDED_BY\(x\);}}
8+
};
9+

0 commit comments

Comments
 (0)