diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -1808,7 +1808,8 @@ removeBraces(Line->Children, Result); if (!Line->Affected) continue; - for (FormatToken *Token = Line->First; Token; Token = Token->Next) { + for (FormatToken *Token = Line->First; Token && !Token->Finalized; + Token = Token->Next) { if (!Token->Optional) continue; assert(Token->isOneOf(tok::l_brace, tok::r_brace)); diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -24805,6 +24805,19 @@ "}", Style); + verifyFormat("// clang-format off\n" + "// comment\n" + "while (i > 0) { --i; }\n" + "// clang-format on\n" + "while (j < 0)\n" + " ++j;", + "// clang-format off\n" + "// comment\n" + "while (i > 0) { --i; }\n" + "// clang-format on\n" + "while (j < 0) { ++j; }", + Style); + verifyFormat("if (a)\n" " b; // comment\n" "else if (c)\n"