12 #include "llvm/Support/Debug.h"
15 #define DEBUG_TYPE "format-formatter"
22 bool startsExternCBlock(
const AnnotatedLine &
Line) {
24 const FormatToken *NextNext = Next ? Next->getNextNonComment() :
nullptr;
25 return Line.
startsWith(tok::kw_extern) && Next && Next->isStringLiteral() &&
26 NextNext && NextNext->is(tok::l_brace);
29 bool isRecordLBrace(
const FormatToken &Tok) {
30 return Tok.isOneOf(TT_ClassLBrace, TT_EnumLBrace, TT_RecordLBrace,
31 TT_StructLBrace, TT_UnionLBrace);
43 class LevelIndentTracker {
45 LevelIndentTracker(
const FormatStyle &Style,
46 const AdditionalKeywords &Keywords,
unsigned StartLevel,
48 : Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) {
49 for (
unsigned i = 0; i != StartLevel; ++i)
50 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
54 unsigned getIndent()
const {
return Indent; }
58 void nextLine(
const AnnotatedLine &
Line) {
62 while (IndentForLevel.size() <=
Line.Level)
63 IndentForLevel.push_back(-1);
64 if (
Line.InPPDirective) {
65 unsigned IndentWidth =
66 (Style.PPIndentWidth >= 0) ? Style.PPIndentWidth : Style.IndentWidth;
67 Indent =
Line.Level * IndentWidth + AdditionalIndent;
69 IndentForLevel.resize(
Line.Level + 1);
74 if (
Line.First->is(TT_CSharpGenericTypeConstraint))
75 Indent =
Line.Level * Style.IndentWidth + Style.ContinuationIndentWidth;
81 while (IndentForLevel.size() <=
Line.Level)
82 IndentForLevel.push_back(
Indent);
90 void adjustToUnmodifiedLine(
const AnnotatedLine &
Line) {
91 unsigned LevelIndent =
Line.First->OriginalColumn;
92 if (
static_cast<int>(LevelIndent) -
Offset >= 0)
94 if ((!
Line.First->is(tok::comment) || IndentForLevel[
Line.Level] == -1) &&
95 !
Line.InPPDirective) {
96 IndentForLevel[
Line.Level] = LevelIndent;
105 int getIndentOffset(
const FormatToken &RootToken) {
111 auto IsAccessModifier = [
this, &RootToken]() {
112 if (RootToken.isAccessSpecifier(Style.isCpp())) {
114 }
else if (RootToken.isObjCAccessSpecifier()) {
118 else if ((RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
119 RootToken.Next && RootToken.Next->is(tok::colon))) {
121 }
else if (RootToken.Next &&
122 RootToken.Next->isOneOf(Keywords.kw_slots,
123 Keywords.kw_qslots) &&
124 RootToken.Next->Next && RootToken.Next->Next->is(tok::colon)) {
128 else if (!RootToken.Next && RootToken.isAccessSpecifier(
false)) {
134 if (IsAccessModifier()) {
138 return Style.IndentAccessModifiers ? -Style.IndentWidth
139 : Style.AccessModifierOffset;
149 unsigned getIndent(
unsigned Level)
const {
150 if (IndentForLevel[
Level] != -1)
151 return IndentForLevel[
Level];
154 return getIndent(
Level - 1) + Style.IndentWidth;
157 const FormatStyle &Style;
158 const AdditionalKeywords &Keywords;
159 const unsigned AdditionalIndent;
162 std::vector<int> IndentForLevel;
174 const FormatToken *getMatchingNamespaceToken(
175 const AnnotatedLine *
Line,
176 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
182 assert(StartLineIndex < AnnotatedLines.size());
183 return AnnotatedLines[StartLineIndex]->First->getNamespaceToken();
188 return NamespaceToken ? NamespaceToken->
TokenText : StringRef();
191 StringRef getMatchingNamespaceTokenText(
192 const AnnotatedLine *
Line,
193 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
194 const FormatToken *NamespaceToken =
195 getMatchingNamespaceToken(
Line, AnnotatedLines);
196 return NamespaceToken ? NamespaceToken->TokenText : StringRef();
201 LineJoiner(
const FormatStyle &Style,
const AdditionalKeywords &Keywords,
202 const SmallVectorImpl<AnnotatedLine *> &Lines)
203 : Style(Style), Keywords(Keywords),
End(Lines.end()), Next(Lines.begin()),
204 AnnotatedLines(Lines) {}
207 const AnnotatedLine *getNextMergedLine(
bool DryRun,
208 LevelIndentTracker &IndentTracker) {
211 const AnnotatedLine *Current = *Next;
212 IndentTracker.nextLine(*Current);
213 unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next,
End);
214 if (MergedLines > 0 && Style.ColumnLimit == 0) {
217 for (
unsigned i = 0; i < MergedLines; ++i)
218 if (Next[i + 1]->First->NewlinesBefore > 0)
222 for (
unsigned i = 0; i < MergedLines; ++i)
223 join(*Next[0], *Next[i + 1]);
224 Next = Next + MergedLines + 1;
231 tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker,
232 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
233 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
234 const unsigned Indent = IndentTracker.getIndent();
240 const AnnotatedLine *TheLine = *I;
241 if (TheLine->Last->is(TT_LineComment))
243 const auto &NextLine = *I[1];
244 if (NextLine.Type ==
LT_Invalid || NextLine.First->MustBreakBefore)
246 if (TheLine->InPPDirective &&
247 (!NextLine.InPPDirective || NextLine.First->HasUnescapedNewline)) {
251 if (Style.ColumnLimit > 0 &&
Indent > Style.ColumnLimit)
258 Limit = TheLine->Last->TotalLength > Limit
260 : Limit - TheLine->Last->TotalLength;
262 if (TheLine->Last->is(TT_FunctionLBrace) &&
263 TheLine->First == TheLine->Last &&
264 !Style.BraceWrapping.SplitEmptyFunction &&
265 NextLine.First->is(tok::r_brace)) {
266 return tryMergeSimpleBlock(I, E, Limit);
269 const auto *PreviousLine = I != AnnotatedLines.begin() ? I[-1] :
nullptr;
271 if (PreviousLine && TheLine->Last->is(tok::l_brace) &&
272 TheLine->First == TheLine->Last) {
273 bool EmptyBlock = NextLine.First->is(tok::r_brace);
275 const FormatToken *Tok = PreviousLine->First;
276 if (Tok && Tok->is(tok::comment))
277 Tok = Tok->getNextNonComment();
279 if (Tok && Tok->getNamespaceToken()) {
280 return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock
281 ? tryMergeSimpleBlock(I, E, Limit)
285 if (Tok && Tok->is(tok::kw_typedef))
286 Tok = Tok->getNextNonComment();
287 if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union,
288 tok::kw_extern, Keywords.kw_interface)) {
289 return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock
290 ? tryMergeSimpleBlock(I, E, Limit)
294 if (Tok && Tok->is(tok::kw_template) &&
295 Style.BraceWrapping.SplitEmptyRecord && EmptyBlock) {
300 auto ShouldMergeShortFunctions = [
this, &I, &NextLine, PreviousLine,
305 NextLine.First->is(tok::r_brace)) {
309 if (Style.AllowShortFunctionsOnASingleLine &
313 if (Style.isJavaScript() && TheLine->Last->is(TT_FunctionLBrace))
316 if (TheLine->Level != 0) {
322 const AnnotatedLine *
Line =
nullptr;
323 for (
auto J = I - 1; J >= AnnotatedLines.begin(); --J) {
325 if (!(*J)->InPPDirective && !(*J)->isComment() &&
326 (*J)->Level < TheLine->Level) {
336 const FormatToken *LastNonComment =
Line->Last;
337 assert(LastNonComment);
338 if (LastNonComment->is(tok::comment)) {
339 LastNonComment = LastNonComment->getPreviousNonComment();
342 assert(LastNonComment);
344 return isRecordLBrace(*LastNonComment);
351 bool MergeShortFunctions = ShouldMergeShortFunctions();
353 const FormatToken *FirstNonComment = TheLine->First;
354 if (FirstNonComment->is(tok::comment)) {
355 FirstNonComment = FirstNonComment->getNextNonComment();
356 if (!FirstNonComment)
362 if (Style.CompactNamespaces) {
363 if (
auto nsToken = TheLine->First->getNamespaceToken()) {
365 unsigned closingLine = TheLine->MatchingClosingBlockLineIndex - 1;
366 for (; I + 1 + i != E &&
368 closingLine == I[i + 1]->MatchingClosingBlockLineIndex &&
369 I[i + 1]->Last->TotalLength < Limit;
370 i++, --closingLine) {
372 IndentTracker.skipLine(*I[i + 1]);
374 Limit -= I[i + 1]->Last->TotalLength;
379 if (
auto nsToken = getMatchingNamespaceToken(TheLine, AnnotatedLines)) {
381 unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
382 for (; I + 1 + i != E &&
383 nsToken->TokenText ==
384 getMatchingNamespaceTokenText(I[i + 1], AnnotatedLines) &&
385 openingLine == I[i + 1]->MatchingOpeningBlockLineIndex;
386 i++, --openingLine) {
388 I[i + 1]->First->SpacesRequiredBefore = !I[i]->Last->is(tok::r_brace);
391 IndentTracker.nextLine(*I[i + 1]);
398 if (TheLine->Last->is(TT_FunctionLBrace) && TheLine->First != TheLine->Last)
399 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
401 if (TheLine->Last->is(tok::l_brace) && FirstNonComment != TheLine->Last &&
402 FirstNonComment->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for,
405 ? tryMergeSimpleBlock(I, E, Limit)
409 if (NextLine.First->is(tok::l_brace)) {
410 if ((TheLine->First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
411 tok::kw_for, tok::kw_switch, tok::kw_try,
412 tok::kw_do, TT_ForEachMacro) ||
413 (TheLine->First->is(tok::r_brace) && TheLine->First->Next &&
414 TheLine->First->Next->isOneOf(tok::kw_else, tok::kw_catch))) &&
415 Style.BraceWrapping.AfterControlStatement ==
420 return (Style.ColumnLimit == 0 || TheLine->Level * Style.IndentWidth +
421 TheLine->Last->TotalLength <=
426 if (TheLine->First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
427 tok::kw_for, TT_ForEachMacro)) {
428 return (Style.BraceWrapping.AfterControlStatement ==
430 ? tryMergeSimpleBlock(I, E, Limit)
433 if (TheLine->First->isOneOf(tok::kw_else, tok::kw_catch) &&
434 Style.BraceWrapping.AfterControlStatement ==
441 return (Style.ColumnLimit == 0 ||
442 TheLine->Last->TotalLength <= Style.ColumnLimit)
447 if (PreviousLine && TheLine->First->is(tok::l_brace)) {
448 switch (PreviousLine->First->Tok.getKind()) {
451 if (PreviousLine->First->Next) {
453 PreviousLine->First->Next->Tok.getObjCKeywordID();
454 if (kwId == tok::objc_autoreleasepool ||
455 kwId == tok::objc_synchronized) {
462 case tok::kw_default:
473 if (PreviousLine && Style.BraceWrapping.SplitEmptyRecord &&
474 TheLine->Last->is(tok::l_brace) && PreviousLine->Last) {
475 const FormatToken *
Previous = PreviousLine->Last;
480 if (
Previous->is(tok::greater) && !PreviousLine->InPPDirective)
482 if (
Previous->is(tok::identifier)) {
483 const FormatToken *PreviousPrevious =
485 if (PreviousPrevious &&
486 PreviousPrevious->isOneOf(tok::kw_class, tok::kw_struct)) {
494 if (TheLine->Last->is(tok::l_brace)) {
495 bool ShouldMerge =
false;
497 if (TheLine->Last->is(TT_EnumLBrace)) {
498 ShouldMerge = Style.AllowShortEnumsOnASingleLine;
499 }
else if (TheLine->Last->isOneOf(TT_ClassLBrace, TT_StructLBrace)) {
503 ShouldMerge = !Style.BraceWrapping.AfterClass ||
504 (NextLine.First->is(tok::r_brace) &&
505 !Style.BraceWrapping.SplitEmptyRecord);
509 assert(TheLine->InPPDirective ||
510 !TheLine->First->isOneOf(tok::kw_class, tok::kw_enum,
512 ShouldMerge = !Style.BraceWrapping.AfterFunction ||
513 (NextLine.First->is(tok::r_brace) &&
514 !Style.BraceWrapping.SplitEmptyFunction);
516 return ShouldMerge ? tryMergeSimpleBlock(I, E, Limit) : 0;
520 if (NextLine.First->is(TT_FunctionLBrace) &&
521 Style.BraceWrapping.AfterFunction) {
522 if (NextLine.Last->is(TT_LineComment))
526 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
530 unsigned MergedLines = 0;
531 if (MergeShortFunctions ||
533 NextLine.First == NextLine.Last && I + 2 != E &&
534 I[2]->First->is(tok::r_brace))) {
535 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
543 auto IsElseLine = [&TheLine]() ->
bool {
544 const FormatToken *First = TheLine->First;
545 if (First->is(tok::kw_else))
548 return First->is(tok::r_brace) && First->Next &&
549 First->Next->is(tok::kw_else);
551 if (TheLine->First->is(tok::kw_if) ||
552 (IsElseLine() && (Style.AllowShortIfStatementsOnASingleLine ==
554 return Style.AllowShortIfStatementsOnASingleLine
555 ? tryMergeSimpleControlStatement(I, E, Limit)
558 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while, tok::kw_do,
560 return Style.AllowShortLoopsOnASingleLine
561 ? tryMergeSimpleControlStatement(I, E, Limit)
564 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
565 return Style.AllowShortCaseLabelsOnASingleLine
566 ? tryMergeShortCaseLabels(I, E, Limit)
569 if (TheLine->InPPDirective &&
570 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
571 return tryMergeSimplePPDirective(I, E, Limit);
577 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
578 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
582 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
584 if (1 + I[1]->Last->TotalLength > Limit)
589 unsigned tryMergeSimpleControlStatement(
590 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
591 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
unsigned Limit) {
594 if (Style.BraceWrapping.AfterControlStatement ==
596 I[1]->First->is(tok::l_brace) &&
600 if (I[1]->InPPDirective != (*I)->InPPDirective ||
601 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) {
604 Limit = limitConsideringMacros(I + 1, E, Limit);
605 AnnotatedLine &
Line = **I;
606 if (!
Line.First->is(tok::kw_do) && !
Line.First->is(tok::kw_else) &&
607 !
Line.Last->is(tok::kw_else) &&
Line.Last->isNot(tok::r_paren)) {
611 if (
Line.First->is(tok::kw_do) && !
Line.Last->is(tok::kw_do))
613 if (1 + I[1]->Last->TotalLength > Limit)
616 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
617 TT_ForEachMacro, TT_LineComment)) {
621 if (Style.AllowShortIfStatementsOnASingleLine ==
623 if (I + 2 != E &&
Line.startsWith(tok::kw_if) &&
624 I[2]->First->is(tok::kw_else)) {
632 tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
633 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
635 if (Limit == 0 || I + 1 == E ||
636 I[1]->First->isOneOf(tok::kw_case, tok::kw_default)) {
639 if (I[0]->Last->is(tok::l_brace) || I[1]->First->is(tok::l_brace))
641 unsigned NumStmts = 0;
643 bool EndsWithComment =
false;
644 bool InPPDirective = I[0]->InPPDirective;
645 const unsigned Level = I[0]->Level;
646 for (; NumStmts < 3; ++NumStmts) {
647 if (I + 1 + NumStmts == E)
649 const AnnotatedLine *
Line = I[1 + NumStmts];
650 if (
Line->InPPDirective != InPPDirective)
652 if (
Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
654 if (
Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
659 if (
Line->First->is(tok::comment)) {
662 SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts;
663 for (; J != E; ++J) {
665 if (
Line->InPPDirective != InPPDirective)
667 if (
Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
669 if (
Line->First->isNot(tok::comment) ||
Level !=
Line->Level)
674 if (
Line->Last->is(tok::comment))
675 EndsWithComment =
true;
676 Length += I[1 + NumStmts]->Last->TotalLength + 1;
678 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
684 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
685 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
691 AnnotatedLine &
Line = **I;
697 Line.First->isOneOf(tok::at, tok::minus, tok::plus)) {
703 if (
Line.First->is(tok::kw_case) ||
704 (
Line.First->Next &&
Line.First->Next->is(tok::kw_else))) {
708 if (
Line.First->is(tok::kw_default)) {
709 const FormatToken *Tok =
Line.First->getNextNonComment();
710 if (Tok && Tok->is(tok::colon))
713 if (
Line.First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while, tok::kw_do,
714 tok::kw_try, tok::kw___try, tok::kw_catch,
715 tok::kw___finally, tok::kw_for, TT_ForEachMacro,
716 tok::r_brace, Keywords.kw___except)) {
720 !I[1]->First->is(tok::r_brace)) {
725 if (!Style.AllowShortIfStatementsOnASingleLine &&
726 Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
727 !Style.BraceWrapping.AfterControlStatement &&
728 !I[1]->First->is(tok::r_brace)) {
731 if (!Style.AllowShortIfStatementsOnASingleLine &&
732 Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
733 Style.BraceWrapping.AfterControlStatement ==
735 I + 2 != E && !I[2]->First->is(tok::r_brace)) {
738 if (!Style.AllowShortLoopsOnASingleLine &&
739 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
741 !Style.BraceWrapping.AfterControlStatement &&
742 !I[1]->First->is(tok::r_brace)) {
745 if (!Style.AllowShortLoopsOnASingleLine &&
746 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
748 Style.BraceWrapping.AfterControlStatement ==
750 I + 2 != E && !I[2]->First->is(tok::r_brace)) {
758 if (
Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
759 Keywords.kw___except, tok::kw___finally)) {
764 if (
Line.Last->is(tok::l_brace)) {
765 FormatToken *Tok = I[1]->First;
766 auto ShouldMerge = [Tok]() {
767 if (Tok->isNot(tok::r_brace) || Tok->MustBreakBefore)
769 const FormatToken *Next = Tok->getNextNonComment();
770 return !Next || Next->is(tok::semi);
775 Tok->SpacesRequiredBefore = Style.SpaceInEmptyBlock ? 1 : 0;
776 Tok->CanBreakBefore =
true;
778 }
else if (Limit != 0 && !
Line.startsWithNamespace() &&
779 !startsExternCBlock(
Line)) {
781 if (isRecordLBrace(*
Line.Last))
787 Limit = limitConsideringMacros(I + 2, E, Limit);
789 if (!nextTwoLinesFitInto(I, Limit))
794 if (I[1]->Last->is(TT_LineComment))
804 if (Tok->isNot(tok::r_brace))
808 if (Tok->Next && Tok->Next->is(tok::kw_else))
817 if (
Line.First ==
Line.Last &&
Line.First->isNot(TT_FunctionLBrace) &&
818 Style.BraceWrapping.AfterControlStatement ==
825 }
else if (I[1]->First->is(tok::l_brace)) {
826 if (I[1]->Last->is(TT_LineComment))
830 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
833 unsigned MergedLines = 0;
835 (I[1]->First == I[1]->Last && I + 2 != E &&
836 I[2]->First->is(tok::r_brace))) {
837 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
851 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
852 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
854 if (I[0]->InPPDirective && I + 1 != E &&
855 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(
tok::eof)) {
856 return Limit < 2 ? 0 : Limit - 2;
861 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
863 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
865 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
868 bool containsMustBreak(
const AnnotatedLine *
Line) {
869 for (
const FormatToken *Tok =
Line->First; Tok; Tok = Tok->Next)
870 if (Tok->MustBreakBefore)
875 void join(AnnotatedLine &A,
const AnnotatedLine &B) {
876 assert(!A.Last->Next);
877 assert(!B.First->Previous);
880 A.Last->Next = B.First;
881 B.First->Previous = A.Last;
882 B.First->CanBreakBefore =
true;
883 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
884 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
885 Tok->TotalLength += LengthA;
890 const FormatStyle &Style;
891 const AdditionalKeywords &Keywords;
892 const SmallVectorImpl<AnnotatedLine *>::const_iterator
End;
894 SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
895 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
898 static void markFinalized(FormatToken *Tok) {
899 for (; Tok; Tok = Tok->Next) {
900 Tok->Finalized =
true;
901 for (AnnotatedLine *Child : Tok->Children)
902 markFinalized(Child->First);
907 static void printLineState(
const LineState &
State) {
908 llvm::dbgs() <<
"State: ";
910 llvm::dbgs() << (
P.Tok ?
P.Tok->TokenText :
"F") <<
"|" <<
P.Indent <<
"|"
911 <<
P.LastSpace <<
"|" <<
P.NestedBlockIndent <<
" ";
918 class LineFormatter {
920 LineFormatter(ContinuationIndenter *
Indenter, WhitespaceManager *Whitespaces,
921 const FormatStyle &Style,
922 UnwrappedLineFormatter *BlockFormatter)
924 BlockFormatter(BlockFormatter) {}
925 virtual ~LineFormatter() {}
930 virtual unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
931 unsigned FirstStartColumn,
bool DryRun) = 0;
954 bool formatChildren(LineState &
State,
bool NewLine,
bool DryRun,
956 const FormatToken *LBrace =
State.NextToken->getPreviousNonComment();
958 if (!LBrace || LBrace->isNot(tok::l_brace) || LBrace->isNot(
BK_Block) ||
966 const ParenState &
P =
State.Stack.back();
968 int AdditionalIndent =
969 P.Indent -
Previous.Children[0]->Level * Style.IndentWidth;
972 P.NestedBlockIndent ==
P.LastSpace) {
973 if (
State.NextToken->MatchingParen &&
974 State.NextToken->MatchingParen->is(TT_LambdaLBrace)) {
975 State.Stack.pop_back();
977 if (LBrace->is(TT_LambdaLBrace))
978 AdditionalIndent = 0;
982 BlockFormatter->format(
Previous.Children, DryRun, AdditionalIndent,
987 if (
Previous.Children[0]->First->MustBreakBefore)
998 const AnnotatedLine *Child =
Previous.Children[0];
1000 if (Child->Last->isTrailingComment())
1005 if (Style.ColumnLimit > 0 &&
1006 Child->Last->TotalLength +
State.Column + 2 > Style.ColumnLimit) {
1011 Whitespaces->replaceWhitespace(
1012 *Child->First, 0, 1,
1013 State.Column,
false,
1014 State.Line->InPPDirective);
1017 formatLine(*Child,
State.Column + 1, 0, DryRun);
1019 State.Column += 1 + Child->Last->TotalLength;
1026 WhitespaceManager *Whitespaces;
1027 const FormatStyle &Style;
1028 UnwrappedLineFormatter *BlockFormatter;
1032 class NoColumnLimitLineFormatter :
public LineFormatter {
1034 NoColumnLimitLineFormatter(ContinuationIndenter *
Indenter,
1035 WhitespaceManager *Whitespaces,
1036 const FormatStyle &Style,
1037 UnwrappedLineFormatter *BlockFormatter)
1038 : LineFormatter(
Indenter, Whitespaces, Style, BlockFormatter) {}
1042 unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1043 unsigned FirstStartColumn,
bool DryRun)
override {
1045 LineState
State =
Indenter->getInitialState(FirstIndent, FirstStartColumn,
1047 while (
State.NextToken) {
1051 unsigned Penalty = 0;
1052 formatChildren(
State, Newline,
false, Penalty);
1060 class NoLineBreakFormatter :
public LineFormatter {
1062 NoLineBreakFormatter(ContinuationIndenter *
Indenter,
1063 WhitespaceManager *Whitespaces,
const FormatStyle &Style,
1064 UnwrappedLineFormatter *BlockFormatter)
1065 : LineFormatter(
Indenter, Whitespaces, Style, BlockFormatter) {}
1068 unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1069 unsigned FirstStartColumn,
bool DryRun)
override {
1070 unsigned Penalty = 0;
1072 Indenter->getInitialState(FirstIndent, FirstStartColumn, &
Line, DryRun);
1073 while (
State.NextToken) {
1074 formatChildren(
State,
false, DryRun, Penalty);
1076 State,
State.NextToken->MustBreakBefore, DryRun);
1083 class OptimizingLineFormatter :
public LineFormatter {
1085 OptimizingLineFormatter(ContinuationIndenter *
Indenter,
1086 WhitespaceManager *Whitespaces,
1087 const FormatStyle &Style,
1088 UnwrappedLineFormatter *BlockFormatter)
1089 : LineFormatter(
Indenter, Whitespaces, Style, BlockFormatter) {}
1093 unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1094 unsigned FirstStartColumn,
bool DryRun)
override {
1096 Indenter->getInitialState(FirstIndent, FirstStartColumn, &
Line, DryRun);
1101 State.Stack.back().BreakBeforeParameter =
true;
1104 return analyzeSolutionSpace(
State, DryRun);
1108 struct CompareLineStatePointers {
1109 bool operator()(LineState *obj1, LineState *obj2)
const {
1110 return *obj1 < *obj2;
1119 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1133 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1136 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1137 std::greater<QueueItem>>
1148 unsigned analyzeSolutionSpace(LineState &InitialState,
bool DryRun) {
1149 std::set<LineState *, CompareLineStatePointers> Seen;
1157 StateNode *RootNode =
1158 new (Allocator.Allocate()) StateNode(InitialState,
false,
nullptr);
1159 Queue.push(QueueItem(OrderedPenalty(0, Count), RootNode));
1162 unsigned Penalty = 0;
1165 while (!Queue.empty()) {
1166 Penalty = Queue.top().first.first;
1167 StateNode *
Node = Queue.top().second;
1168 if (!
Node->State.NextToken) {
1169 LLVM_DEBUG(llvm::dbgs()
1170 <<
"\n---\nPenalty for line: " << Penalty <<
"\n");
1178 Node->State.IgnoreStackForComparison =
true;
1180 if (!Seen.insert(&
Node->State).second) {
1187 addNextStateToQueue(Penalty,
Node,
false, &Count, &Queue);
1189 addNextStateToQueue(Penalty,
Node,
true, &Count, &Queue);
1192 if (Queue.empty()) {
1195 LLVM_DEBUG(llvm::dbgs() <<
"Could not find a solution.\n");
1201 reconstructPath(InitialState, Queue.top().second);
1203 LLVM_DEBUG(llvm::dbgs()
1204 <<
"Total number of analyzed states: " << Count <<
"\n");
1205 LLVM_DEBUG(llvm::dbgs() <<
"---\n");
1214 void addNextStateToQueue(
unsigned Penalty, StateNode *PreviousNode,
1215 bool NewLine,
unsigned *Count, QueueType *Queue) {
1221 StateNode *
Node =
new (Allocator.Allocate())
1222 StateNode(PreviousNode->State,
NewLine, PreviousNode);
1223 if (!formatChildren(
Node->State,
NewLine,
true, Penalty))
1228 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count),
Node));
1234 void reconstructPath(LineState &
State, StateNode *Best) {
1237 while (Best->Previous) {
1238 Path.push_back(Best);
1239 Best = Best->Previous;
1241 for (
const auto &
Node : llvm::reverse(Path)) {
1242 unsigned Penalty = 0;
1243 formatChildren(
State,
Node->NewLine,
false, Penalty);
1247 printLineState(
Node->Previous->State);
1248 if (
Node->NewLine) {
1249 llvm::dbgs() <<
"Penalty for placing "
1250 <<
Node->Previous->State.NextToken->Tok.getName()
1251 <<
" on a new line: " << Penalty <<
"\n";
1257 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1264 int AdditionalIndent,
bool FixBadIndentation,
unsigned FirstStartColumn,
1265 unsigned NextStartColumn,
unsigned LastStartColumn) {
1266 LineJoiner Joiner(Style, Keywords, Lines);
1269 std::pair<const SmallVectorImpl<AnnotatedLine *> *,
unsigned> CacheKey(
1270 &Lines, AdditionalIndent);
1271 auto CacheIt = PenaltyCache.find(CacheKey);
1272 if (DryRun && CacheIt != PenaltyCache.end())
1273 return CacheIt->second;
1275 assert(!Lines.empty());
1276 unsigned Penalty = 0;
1277 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->
Level,
1286 bool FirstLine =
true;
1288 Joiner.getNextMergedLine(DryRun, IndentTracker);
1289 Line; PrevPrevLine = PreviousLine, PreviousLine =
Line,
Line = NextLine,
1290 FirstLine =
false) {
1291 assert(
Line->First);
1293 unsigned Indent = IndentTracker.getIndent();
1299 bool PreviousRBrace =
1300 PreviousLine && PreviousLine->
startsWith(tok::r_brace);
1301 bool ContinueFormatting =
1302 TheLine.
Level > RangeMinLevel ||
1303 (TheLine.
Level == RangeMinLevel && !PreviousRBrace &&
1306 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
1308 bool ShouldFormat = TheLine.
Affected || FixIndentation;
1320 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines,
Indent,
1321 LastLine ? LastStartColumn : NextStartColumn +
Indent);
1324 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1325 unsigned ColumnLimit = getColumnLimit(TheLine.
InPPDirective, NextLine);
1326 bool FitsIntoOneLine =
1329 (!Style.isJavaScript() || !Style.JavaScriptWrapImports)) ||
1330 (Style.isCSharp() &&
1332 if (Style.ColumnLimit == 0) {
1333 NoColumnLimitLineFormatter(
Indenter, Whitespaces, Style,
this)
1334 .formatLine(TheLine, NextStartColumn +
Indent,
1335 FirstLine ? FirstStartColumn : 0, DryRun);
1336 }
else if (FitsIntoOneLine) {
1337 Penalty += NoLineBreakFormatter(
Indenter, Whitespaces, Style,
this)
1338 .formatLine(TheLine, NextStartColumn +
Indent,
1339 FirstLine ? FirstStartColumn : 0, DryRun);
1341 Penalty += OptimizingLineFormatter(
Indenter, Whitespaces, Style,
this)
1342 .formatLine(TheLine, NextStartColumn +
Indent,
1343 FirstLine ? FirstStartColumn : 0, DryRun);
1351 if (!Tok->Children.empty())
1352 format(Tok->Children, DryRun);
1357 bool StartsNewLine =
1360 IndentTracker.adjustToUnmodifiedLine(TheLine);
1362 bool ReformatLeadingWhitespace =
1363 StartsNewLine && ((PreviousLine && PreviousLine->
Affected) ||
1366 if (ReformatLeadingWhitespace) {
1367 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines,
1371 Whitespaces->addUntouchableToken(*TheLine.
First,
1377 Whitespaces->addUntouchableToken(*Tok, TheLine.
InPPDirective);
1379 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1383 markFinalized(TheLine.
First);
1385 PenaltyCache[CacheKey] = Penalty;
1389 void UnwrappedLineFormatter::formatFirstToken(
1393 unsigned NewlineIndent) {
1397 unsigned TokenIndent = Newlines ? NewlineIndent : 0;
1398 Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
1405 if (RootToken.
is(tok::r_brace) &&
1413 if (PreviousLine ==
nullptr &&
Line.Level > 0)
1415 if (Newlines == 0 && !RootToken.
IsFirst)
1421 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1422 PreviousLine->
Last->
is(tok::l_brace) &&
1426 !startsExternCBlock(*PreviousLine)) {
1432 switch (Style.EmptyLineBeforeAccessModifier) {
1441 if (PreviousLine->
Last->
isOneOf(tok::semi, tok::r_brace) && Newlines <= 1)
1447 const FormatToken *previousToken;
1448 if (PreviousLine->
Last->
is(tok::comment))
1451 previousToken = PreviousLine->
Last;
1452 if ((!previousToken || !previousToken->is(tok::l_brace)) && Newlines <= 1)
1464 switch (Style.EmptyLineAfterAccessModifier) {
1472 if (RootToken.
is(tok::r_brace))
1486 if (!Style.isJavaScript() &&
1493 Whitespaces->replaceWhitespace(RootToken, Newlines,
Indent,
Indent,
1495 Line.InPPDirective &&
1500 UnwrappedLineFormatter::getColumnLimit(
bool InPPDirective,
1501 const AnnotatedLine *NextLine)
const {
1504 bool ContinuesPPDirective =
1509 (NextLine->InPPDirective &&
1512 !NextLine->First->HasUnescapedNewline));
1513 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);