diff --git a/lib/Format/Format.cpp b/lib/Format/Format.cpp index fe8567de64b8ab5a724b9f3d3b5f7b364228e94c..98cb81ef416105436493b14bcc8aa6aeb37fdde1 100644 --- a/lib/Format/Format.cpp +++ b/lib/Format/Format.cpp @@ -1118,12 +1118,21 @@ public: std::vector<int> IndentForLevel; bool PreviousLineWasTouched = false; const AnnotatedToken *PreviousLineLastToken = 0; + bool FormatPPDirective = false; for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(), E = AnnotatedLines.end(); I != E; ++I) { const AnnotatedLine &TheLine = *I; const FormatToken &FirstTok = TheLine.First.FormatTok; int Offset = getIndentOffset(TheLine.First); + + // Check whether this line is part of a formatted preprocessor directive. + if (FirstTok.HasUnescapedNewline) + FormatPPDirective = false; + if (!FormatPPDirective && TheLine.InPPDirective && + (touchesLine(TheLine) || touchesPPDirective(I + 1, E))) + FormatPPDirective = true; + while (IndentForLevel.size() <= TheLine.Level) IndentForLevel.push_back(-1); IndentForLevel.resize(TheLine.Level + 1); @@ -1135,7 +1144,7 @@ public: /*WhitespaceStartColumn*/ 0); } } else if (TheLine.Type != LT_Invalid && - (WasMoved || touchesLine(TheLine))) { + (WasMoved || FormatPPDirective || touchesLine(TheLine))) { unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level); unsigned Indent = LevelIndent; if (static_cast<int>(Indent) + Offset >= 0) @@ -1412,6 +1421,17 @@ private: return touchesRanges(LineRange); } + bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I, + std::vector<AnnotatedLine>::iterator E) { + for (; I != E; ++I) { + if (I->First.FormatTok.HasUnescapedNewline) + return false; + if (touchesLine(*I)) + return true; + } + return false; + } + bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) { const FormatToken *First = &TheLine.First.FormatTok; CharSourceRange LineRange = CharSourceRange::getCharRange( diff --git a/unittests/Format/FormatTest.cpp b/unittests/Format/FormatTest.cpp index fab34e8684e96968a06b32a312bc97faceb302e6..f8ccf86070422f3b7fc8c91d0a69f0456d89d951 100644 --- a/unittests/Format/FormatTest.cpp +++ b/unittests/Format/FormatTest.cpp @@ -1289,9 +1289,29 @@ TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); } -TEST_F(FormatTest, LayoutSingleUnwrappedLineInMacro) { - EXPECT_EQ("# define A\\\n b;", - format("# define A b;", 11, 2, getLLVMStyleWithColumns(11))); +TEST_F(FormatTest, AlwaysFormatsEntireMacroDefinitions) { + EXPECT_EQ("int i;\n" + "#define A \\\n" + " int i; \\\n" + " int j\n" + "int k;", + format("int i;\n" + "#define A \\\n" + " int i ; \\\n" + " int j\n" + "int k;", + 8, 0, getGoogleStyle())); // 8: position of "#define". + EXPECT_EQ("int i;\n" + "#define A \\\n" + " int i; \\\n" + " int j\n" + "int k;", + format("int i;\n" + "#define A \\\n" + " int i ; \\\n" + " int j\n" + "int k;", + 45, 0, getGoogleStyle())); // 45: position of "j". } TEST_F(FormatTest, MacroDefinitionInsideStatement) {