Skip to content

Commit ef30ca3

Browse files
ZhongRuoyumahesh-attarde
authored andcommitted
[clang-format] Fix qualifier ordering for lines after PP directives (llvm#160731)
Lines appearing after preprocessor conditional blocks (like `#endif`) were not having their qualifiers reordered by `QualifierOrder`, while lines inside the conditional blocks were processed correctly. The issue was that tokens on lines following preprocessor directives have `MustBreakBefore` = `true`. The qualifier alignment logic was breaking immediately upon encountering any token with `MustBreakBefore` = `true`, preventing analysis of the entire line. The fix allows processing to continue when `MustBreakBefore` = `true` on the first token of a line, since this is expected behavior (the token legitimately starts a new line). Only tokens with `MustBreakBefore` = `true` that appear mid-line will cause the analysis loop to break. Fixes llvm#160487.
1 parent b04b10b commit ef30ca3

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

clang/lib/Format/QualifierAlignmentFixer.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -571,7 +571,7 @@ void LeftRightQualifierAlignmentFixer::fixQualifierAlignment(
571571

572572
for (const auto *Tok = First; Tok && Tok != Last && Tok->Next;
573573
Tok = Tok->Next) {
574-
if (Tok->MustBreakBefore)
574+
if (Tok->MustBreakBefore && Tok != First)
575575
break;
576576
if (Tok->is(tok::comment))
577577
continue;

clang/unittests/Format/QualifierFixerTest.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1195,6 +1195,41 @@ TEST_F(QualifierFixerTest, QualifiersBrokenUpByPPDirectives) {
11951195
Style);
11961196
}
11971197

1198+
TEST_F(QualifierFixerTest, QualifierOrderingAfterPreprocessorDirectives) {
1199+
auto Style = getLLVMStyle();
1200+
Style.QualifierAlignment = FormatStyle::QAS_Custom;
1201+
Style.QualifierOrder = {"static", "inline", "const", "type"};
1202+
1203+
verifyFormat("#if 1\n"
1204+
"void foo(const int par);\n"
1205+
"const int var1;\n"
1206+
"#endif\n"
1207+
"\n"
1208+
"const int var2;\n"
1209+
"const int var3;",
1210+
"#if 1\n"
1211+
"void foo(int const par);\n"
1212+
"int const var1;\n"
1213+
"#endif\n"
1214+
"\n"
1215+
"int const var2;\n"
1216+
"int const var3;",
1217+
Style);
1218+
verifyFormat("#if defined(FOO)\n"
1219+
"static const int x = 1;\n"
1220+
"#else\n"
1221+
"static const int x = 2;\n"
1222+
"#endif\n"
1223+
"static const int y = 3;",
1224+
"#if defined(FOO)\n"
1225+
"const static int x = 1;\n"
1226+
"#else\n"
1227+
"const static int x = 2;\n"
1228+
"#endif\n"
1229+
"const static int y = 3;",
1230+
Style);
1231+
}
1232+
11981233
TEST_F(QualifierFixerTest, UnsignedQualifier) {
11991234

12001235
FormatStyle Style = getLLVMStyle();

0 commit comments

Comments
 (0)