Skip to content

Commit 2183fe2

Browse files
committed
[clang-format] Parse the else part of #if 0
Fixes llvm#57539 Previously things outside of `#if` blocks were parsed as if only the first branch of the conditional compilation branch existed, unless the first condition is 0. In that case the outer parts would be parsed as if nothing inside the conditional parts existed. Now we use the second conditional branch if the first condition is 0. Reviewed By: owenpan Differential Revision: https://reviews.llvm.org/D133647
1 parent c9cffdd commit 2183fe2

File tree

2 files changed

+13
-16
lines changed

2 files changed

+13
-16
lines changed

clang/lib/Format/UnwrappedLineParser.cpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1124,7 +1124,9 @@ void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) {
11241124
++PPBranchLevel;
11251125
assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
11261126
if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
1127-
PPLevelBranchIndex.push_back(0);
1127+
// If the first branch is unreachable, set the BranchIndex to 1. This way
1128+
// the next branch will be parsed if there is one.
1129+
PPLevelBranchIndex.push_back(Unreachable ? 1 : 0);
11281130
PPLevelBranchCount.push_back(0);
11291131
}
11301132
PPChainBranchIndex.push(0);

clang/unittests/Format/FormatTest.cpp

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5993,6 +5993,16 @@ TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
59935993
");\n"
59945994
"#else\n"
59955995
"#endif");
5996+
5997+
// Verify that indentation is correct when there is an `#if 0` with an
5998+
// `#else`.
5999+
verifyFormat("#if 0\n"
6000+
"{\n"
6001+
"#else\n"
6002+
"{\n"
6003+
"#endif\n"
6004+
" x;\n"
6005+
"}");
59966006
}
59976007

59986008
TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
@@ -25367,27 +25377,12 @@ TEST_F(FormatTest, InsertBraces) {
2536725377

2536825378
verifyFormat("do {\n"
2536925379
"#if 0\n"
25370-
" if (a) {\n"
25371-
"#else\n"
25372-
" if (b) {\n"
25373-
"#endif\n"
25374-
"}\n"
25375-
"}\n"
25376-
"while (0)\n"
25377-
" ;",
25378-
Style);
25379-
// TODO: Replace the test above with the one below after #57539 is fixed.
25380-
#if 0
25381-
verifyFormat("do {\n"
25382-
"#if 0\n"
25383-
" if (a) {\n"
2538425380
"#else\n"
2538525381
" if (b) {\n"
2538625382
"#endif\n"
2538725383
" }\n"
2538825384
"} while (0);",
2538925385
Style);
25390-
#endif
2539125386

2539225387
Style.ColumnLimit = 15;
2539325388

0 commit comments

Comments
 (0)