13#include "llvm/Support/Debug.h"
16#define DEBUG_TYPE "format-formatter"
23bool startsExternCBlock(
const AnnotatedLine &
Line) {
24 const FormatToken *Next =
Line.First->getNextNonComment();
25 const FormatToken *NextNext = Next ? Next->getNextNonComment() :
nullptr;
26 return Line.startsWith(tok::kw_extern) && Next && Next->isStringLiteral() &&
27 NextNext && NextNext->is(tok::l_brace);
30bool isRecordLBrace(
const FormatToken &Tok) {
31 return Tok.isOneOf(TT_ClassLBrace, TT_EnumLBrace, TT_RecordLBrace,
32 TT_StructLBrace, TT_UnionLBrace);
44class LevelIndentTracker {
46 LevelIndentTracker(
const FormatStyle &Style,
47 const AdditionalKeywords &Keywords,
unsigned StartLevel,
49 : Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) {
50 for (
unsigned i = 0; i != StartLevel; ++i)
51 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
55 unsigned getIndent()
const {
return Indent; }
59 void nextLine(
const AnnotatedLine &
Line) {
60 Offset = getIndentOffset(
Line);
63 if (
Line.Level >= IndentForLevel.size())
64 IndentForLevel.resize(
Line.Level + 1, -1);
66 (
Line.InPPDirective ||
69 unsigned PPIndentWidth =
70 (Style.PPIndentWidth >= 0) ? Style.PPIndentWidth : Style.IndentWidth;
71 Indent =
Line.InMacroBody
72 ?
Line.PPLevel * PPIndentWidth +
73 (
Line.Level -
Line.PPLevel) * Style.IndentWidth
74 :
Line.Level * PPIndentWidth;
75 Indent += AdditionalIndent;
80 if (!
Line.InPPDirective) {
81 assert(
Line.Level <= IndentForLevel.size());
82 IndentForLevel.resize(
Line.Level + 1);
84 Indent = getIndent(
Line.Level);
86 if (
static_cast<int>(Indent) + Offset >= 0)
88 if (
Line.IsContinuation)
89 Indent =
Line.Level * Style.IndentWidth + Style.ContinuationIndentWidth;
97 void adjustToUnmodifiedLine(
const AnnotatedLine &
Line) {
98 if (
Line.InPPDirective ||
Line.IsContinuation)
100 assert(
Line.Level < IndentForLevel.size());
101 if (
Line.First->is(tok::comment) && IndentForLevel[
Line.Level] != -1)
103 unsigned LevelIndent =
Line.First->OriginalColumn;
104 if (
static_cast<int>(LevelIndent) - Offset >= 0)
105 LevelIndent -= Offset;
106 IndentForLevel[
Line.Level] = LevelIndent;
114 int getIndentOffset(
const AnnotatedLine &
Line) {
120 auto IsAccessModifier = [&](
const FormatToken &RootToken) {
124 const auto *Next = RootToken.Next;
127 if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
128 Next && Next->is(tok::colon)) {
132 if (Next && Next->isOneOf(Keywords.kw_slots, Keywords.kw_qslots) &&
133 Next->Next && Next->Next->is(tok::colon)) {
138 return !Next && RootToken.isAccessSpecifier(
false);
141 if (IsAccessModifier(*
Line.First)) {
145 return Style.IndentAccessModifiers ? -Style.IndentWidth
146 : Style.AccessModifierOffset;
157 unsigned getIndent(
unsigned Level)
const {
158 assert(Level < IndentForLevel.size());
159 if (IndentForLevel[Level] != -1)
160 return IndentForLevel[Level];
163 return getIndent(Level - 1) + Style.IndentWidth;
166 const FormatStyle &Style;
167 const AdditionalKeywords &Keywords;
168 const unsigned AdditionalIndent;
174 SmallVector<int> IndentForLevel;
187getMatchingNamespaceToken(
const AnnotatedLine *
Line,
188 const ArrayRef<AnnotatedLine *> &AnnotatedLines) {
189 if (!
Line->startsWith(tok::r_brace))
191 size_t StartLineIndex =
Line->MatchingOpeningBlockLineIndex;
194 assert(StartLineIndex < AnnotatedLines.size());
195 return AnnotatedLines[StartLineIndex]->First->getNamespaceToken();
199 const FormatToken *NamespaceToken =
Line->First->getNamespaceToken();
200 return NamespaceToken ? NamespaceToken->TokenText : StringRef();
204getMatchingNamespaceTokenText(
const AnnotatedLine *
Line,
205 const ArrayRef<AnnotatedLine *> &AnnotatedLines) {
206 const FormatToken *NamespaceToken =
207 getMatchingNamespaceToken(
Line, AnnotatedLines);
208 return NamespaceToken ? NamespaceToken->TokenText : StringRef();
213 LineJoiner(
const FormatStyle &Style,
const AdditionalKeywords &Keywords,
214 const SmallVectorImpl<AnnotatedLine *> &Lines)
215 : Style(Style), Keywords(Keywords), End(Lines.end()), Next(Lines.begin()),
216 AnnotatedLines(Lines) {}
219 const AnnotatedLine *getNextMergedLine(
bool DryRun,
220 LevelIndentTracker &IndentTracker) {
223 const AnnotatedLine *Current = *Next;
224 IndentTracker.nextLine(*Current);
225 unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next, End);
226 if (MergedLines > 0 && Style.ColumnLimit == 0) {
229 for (
unsigned i = 0; i < MergedLines; ++i)
230 if (Next[i + 1]->
First->NewlinesBefore > 0)
234 for (
unsigned i = 0; i < MergedLines; ++i)
235 join(*Next[0], *Next[i + 1]);
236 Next = Next + MergedLines + 1;
243 tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker,
244 ArrayRef<AnnotatedLine *>::const_iterator I,
245 ArrayRef<AnnotatedLine *>::const_iterator
E) {
246 const unsigned Indent = IndentTracker.getIndent();
252 const AnnotatedLine *TheLine = *I;
253 if (TheLine->Last->is(TT_LineComment))
255 const auto &NextLine = *I[1];
256 if (NextLine.Type ==
LT_Invalid || NextLine.First->MustBreakBefore)
258 if (TheLine->InPPDirective &&
259 (!NextLine.InPPDirective || NextLine.First->HasUnescapedNewline)) {
263 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
267 Style.ColumnLimit == 0 ?
UINT_MAX : Style.ColumnLimit - Indent;
270 Limit = TheLine->Last->TotalLength > Limit
272 : Limit - TheLine->Last->TotalLength;
274 if (TheLine->Last->is(TT_FunctionLBrace) &&
275 TheLine->First == TheLine->Last &&
276 !Style.BraceWrapping.SplitEmptyFunction &&
277 NextLine.First->is(tok::r_brace)) {
278 return tryMergeSimpleBlock(I,
E, Limit);
281 const auto *PreviousLine = I != AnnotatedLines.begin() ? I[-1] :
nullptr;
283 if (PreviousLine && TheLine->Last->is(tok::l_brace) &&
284 TheLine->First == TheLine->Last) {
285 bool EmptyBlock = NextLine.First->is(tok::r_brace);
287 const FormatToken *Tok = PreviousLine->First;
288 if (Tok && Tok->is(tok::comment))
289 Tok = Tok->getNextNonComment();
291 if (Tok && Tok->getNamespaceToken()) {
292 return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock
293 ? tryMergeSimpleBlock(I,
E, Limit)
297 if (Tok && Tok->is(tok::kw_typedef))
298 Tok = Tok->getNextNonComment();
299 if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union,
300 tok::kw_extern, Keywords.kw_interface)) {
301 return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock
302 ? tryMergeSimpleBlock(I,
E, Limit)
306 if (Tok && Tok->is(tok::kw_template) &&
307 Style.BraceWrapping.SplitEmptyRecord && EmptyBlock) {
312 auto ShouldMergeShortFunctions = [
this, &I, &NextLine, PreviousLine,
317 NextLine.First->is(tok::r_brace)) {
321 if (Style.AllowShortFunctionsOnASingleLine &
325 if (Style.isJavaScript() && TheLine->Last->is(TT_FunctionLBrace))
328 if (TheLine->Level != 0) {
334 const AnnotatedLine *
Line =
nullptr;
335 for (
auto J = I - 1; J >= AnnotatedLines.begin(); --J) {
337 if (!(*J)->InPPDirective && !(*J)->isComment() &&
338 (*J)->Level < TheLine->Level) {
348 const auto *LastNonComment =
Line->getLastNonComment();
351 assert(LastNonComment);
352 return isRecordLBrace(*LastNonComment);
359 bool MergeShortFunctions = ShouldMergeShortFunctions();
361 const auto *FirstNonComment = TheLine->getFirstNonComment();
362 if (!FirstNonComment)
368 if (Style.AllowShortNamespacesOnASingleLine &&
369 TheLine->First->is(tok::kw_namespace) &&
370 TheLine->Last->is(tok::l_brace)) {
371 const auto result = tryMergeNamespace(I,
E, Limit);
376 if (Style.CompactNamespaces) {
377 if (
const auto *NSToken = TheLine->First->getNamespaceToken()) {
379 assert(TheLine->MatchingClosingBlockLineIndex > 0);
380 for (
auto ClosingLineIndex = TheLine->MatchingClosingBlockLineIndex - 1;
382 ClosingLineIndex == I[J]->MatchingClosingBlockLineIndex &&
383 I[J]->
Last->TotalLength < Limit;
384 ++J, --ClosingLineIndex) {
385 Limit -= I[J]->Last->TotalLength + 1;
389 auto *ClosingLine = AnnotatedLines.begin() + ClosingLineIndex + 1;
390 const int OutdentBy = I[J]->Level - TheLine->Level;
391 assert(OutdentBy >= 0);
392 for (
auto *CompactedLine = I + J; CompactedLine <= ClosingLine;
394 if (!(*CompactedLine)->InPPDirective) {
395 const int Level = (*CompactedLine)->Level;
396 (*CompactedLine)->Level = std::max(Level - OutdentBy, 0);
403 if (
auto nsToken = getMatchingNamespaceToken(TheLine, AnnotatedLines)) {
405 unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
406 for (; I + 1 + i !=
E &&
407 nsToken->TokenText ==
408 getMatchingNamespaceTokenText(I[i + 1], AnnotatedLines) &&
409 openingLine == I[i + 1]->MatchingOpeningBlockLineIndex;
410 i++, --openingLine) {
412 I[i + 1]->First->SpacesRequiredBefore =
413 I[i]->Last->isNot(tok::r_brace);
416 IndentTracker.nextLine(*I[i + 1]);
422 const auto *LastNonComment = TheLine->getLastNonComment();
423 assert(LastNonComment);
428 if (LastNonComment->is(TT_FunctionLBrace) &&
429 TheLine->First != LastNonComment) {
430 return MergeShortFunctions ? tryMergeSimpleBlock(I,
E, Limit) : 0;
434 if (TheLine->Last->is(tok::l_brace) && FirstNonComment != TheLine->Last &&
435 FirstNonComment->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for,
438 ? tryMergeSimpleBlock(I,
E, Limit)
442 if (NextLine.First->is(tok::l_brace)) {
443 if ((TheLine->First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
444 tok::kw_for, tok::kw_switch, tok::kw_try,
445 tok::kw_do, TT_ForEachMacro) ||
446 (TheLine->First->is(tok::r_brace) && TheLine->First->Next &&
447 TheLine->First->Next->isOneOf(tok::kw_else, tok::kw_catch))) &&
448 Style.BraceWrapping.AfterControlStatement ==
453 return (Style.ColumnLimit == 0 || TheLine->Level * Style.IndentWidth +
454 TheLine->Last->TotalLength <=
459 if (TheLine->First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
460 tok::kw_for, TT_ForEachMacro)) {
461 return (Style.BraceWrapping.AfterControlStatement ==
463 ? tryMergeSimpleBlock(I,
E, Limit)
466 if (TheLine->First->isOneOf(tok::kw_else, tok::kw_catch) &&
467 Style.BraceWrapping.AfterControlStatement ==
474 return (Style.ColumnLimit == 0 ||
475 TheLine->Last->TotalLength <= Style.ColumnLimit)
480 if (PreviousLine && TheLine->First->is(tok::l_brace)) {
481 switch (PreviousLine->First->Tok.getKind()) {
484 if (PreviousLine->First->Next) {
486 PreviousLine->First->Next->Tok.getObjCKeywordID();
487 if (kwId == tok::objc_autoreleasepool ||
488 kwId == tok::objc_synchronized) {
495 case tok::kw_default:
506 if (PreviousLine && Style.BraceWrapping.SplitEmptyRecord &&
507 TheLine->Last->is(tok::l_brace) && PreviousLine->Last) {
508 const FormatToken *
Previous = PreviousLine->Last;
513 if (
Previous->is(tok::greater) && !PreviousLine->InPPDirective)
515 if (
Previous->is(tok::identifier)) {
516 const FormatToken *PreviousPrevious =
518 if (PreviousPrevious &&
519 PreviousPrevious->isOneOf(tok::kw_class, tok::kw_struct)) {
527 if (TheLine->First->is(TT_SwitchExpressionLabel)) {
528 return Style.AllowShortCaseExpressionOnASingleLine
529 ? tryMergeShortCaseLabels(I,
E, Limit)
533 if (TheLine->Last->is(tok::l_brace)) {
534 bool ShouldMerge =
false;
536 if (TheLine->Last->is(TT_EnumLBrace)) {
537 ShouldMerge = Style.AllowShortEnumsOnASingleLine;
538 }
else if (TheLine->Last->is(TT_CompoundRequirementLBrace)) {
539 ShouldMerge = Style.AllowShortCompoundRequirementOnASingleLine;
540 }
else if (TheLine->Last->isOneOf(TT_ClassLBrace, TT_StructLBrace)) {
544 ShouldMerge = !Style.BraceWrapping.AfterClass ||
545 (NextLine.First->is(tok::r_brace) &&
546 !Style.BraceWrapping.SplitEmptyRecord);
547 }
else if (TheLine->InPPDirective ||
548 !TheLine->First->isOneOf(tok::kw_class, tok::kw_enum,
552 ShouldMerge = !Style.BraceWrapping.AfterFunction ||
553 (NextLine.First->is(tok::r_brace) &&
554 !Style.BraceWrapping.SplitEmptyFunction);
556 return ShouldMerge ? tryMergeSimpleBlock(I,
E, Limit) : 0;
560 if (NextLine.First->is(TT_FunctionLBrace) &&
561 Style.BraceWrapping.AfterFunction) {
562 if (NextLine.Last->is(TT_LineComment))
566 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
570 unsigned MergedLines = 0;
571 if (MergeShortFunctions ||
573 NextLine.First == NextLine.Last && I + 2 !=
E &&
574 I[2]->First->is(tok::r_brace))) {
575 MergedLines = tryMergeSimpleBlock(I + 1,
E, Limit);
583 auto IsElseLine = [&TheLine]() ->
bool {
584 const FormatToken *
First = TheLine->First;
585 if (
First->is(tok::kw_else))
588 return First->is(tok::r_brace) &&
First->Next &&
589 First->Next->is(tok::kw_else);
591 if (TheLine->First->is(tok::kw_if) ||
592 (IsElseLine() && (Style.AllowShortIfStatementsOnASingleLine ==
594 return Style.AllowShortIfStatementsOnASingleLine
595 ? tryMergeSimpleControlStatement(I,
E, Limit)
598 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while, tok::kw_do,
600 return Style.AllowShortLoopsOnASingleLine
601 ? tryMergeSimpleControlStatement(I,
E, Limit)
604 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
605 return Style.AllowShortCaseLabelsOnASingleLine
606 ? tryMergeShortCaseLabels(I,
E, Limit)
609 if (TheLine->InPPDirective &&
610 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
611 return tryMergeSimplePPDirective(I,
E, Limit);
617 tryMergeSimplePPDirective(ArrayRef<AnnotatedLine *>::const_iterator I,
618 ArrayRef<AnnotatedLine *>::const_iterator
E,
622 if (I + 2 !=
E && I[2]->InPPDirective && !I[2]->
First->HasUnescapedNewline)
624 if (1 + I[1]->
Last->TotalLength > Limit)
629 unsigned tryMergeNamespace(ArrayRef<AnnotatedLine *>::const_iterator I,
630 ArrayRef<AnnotatedLine *>::const_iterator
E,
636 const auto &L1 = *I[1];
637 if (L1.InPPDirective != (*I)->InPPDirective ||
638 (L1.InPPDirective && L1.First->HasUnescapedNewline)) {
642 if (std::distance(I,
E) <= 2)
646 const auto &L2 = *I[2];
650 Limit = limitConsideringMacros(I + 1,
E, Limit);
652 if (!nextTwoLinesFitInto(I, Limit))
657 if (L1.First->is(tok::kw_namespace)) {
658 if (L1.Last->is(tok::comment) || !Style.CompactNamespaces)
661 assert(Limit >= L1.Last->TotalLength + 3);
662 const auto InnerLimit = Limit - L1.Last->TotalLength - 3;
663 const auto MergedLines = tryMergeNamespace(I + 1,
E, InnerLimit);
664 if (MergedLines == 0)
666 const auto N = MergedLines + 2;
668 if (std::distance(I,
E) <= N)
672 if (I[N]->
First->is(tok::r_brace) && !I[N]->First->MustBreakBefore &&
673 I[MergedLines + 1]->Last->isNot(tok::comment) &&
674 nextNLinesFitInto(I, I + N + 1, Limit)) {
684 if (L1.Last->isNot(tok::semi))
688 if (L2.First->isNot(tok::r_brace) || L2.First->MustBreakBefore)
696 tryMergeSimpleControlStatement(ArrayRef<AnnotatedLine *>::const_iterator I,
697 ArrayRef<AnnotatedLine *>::const_iterator
E,
701 if (Style.BraceWrapping.AfterControlStatement ==
703 I[1]->First->is(tok::l_brace) &&
707 if (I[1]->InPPDirective != (*I)->InPPDirective ||
708 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) {
711 Limit = limitConsideringMacros(I + 1,
E, Limit);
712 AnnotatedLine &
Line = **I;
713 if (
Line.First->isNot(tok::kw_do) &&
Line.First->isNot(tok::kw_else) &&
714 Line.Last->isNot(tok::kw_else) &&
Line.Last->isNot(tok::r_paren)) {
718 if (
Line.First->is(tok::kw_do) &&
Line.Last->isNot(tok::kw_do))
720 if (1 + I[1]->
Last->TotalLength > Limit)
723 if (I[1]->
First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
724 TT_ForEachMacro, TT_LineComment)) {
728 if (Style.AllowShortIfStatementsOnASingleLine ==
730 if (I + 2 !=
E &&
Line.startsWith(tok::kw_if) &&
731 I[2]->First->is(tok::kw_else)) {
738 unsigned tryMergeShortCaseLabels(ArrayRef<AnnotatedLine *>::const_iterator I,
739 ArrayRef<AnnotatedLine *>::const_iterator
E,
741 if (Limit == 0 || I + 1 ==
E ||
742 I[1]->
First->isOneOf(tok::kw_case, tok::kw_default)) {
745 if (I[0]->
Last->is(tok::l_brace) || I[1]->First->is(tok::l_brace))
747 unsigned NumStmts = 0;
749 bool EndsWithComment =
false;
750 bool InPPDirective = I[0]->InPPDirective;
751 bool InMacroBody = I[0]->InMacroBody;
752 const unsigned Level = I[0]->Level;
753 for (; NumStmts < 3; ++NumStmts) {
754 if (I + 1 + NumStmts ==
E)
756 const AnnotatedLine *
Line = I[1 + NumStmts];
757 if (
Line->InPPDirective != InPPDirective)
759 if (
Line->InMacroBody != InMacroBody)
761 if (
Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
763 if (
Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
768 if (
Line->First->is(tok::comment)) {
769 if (Level !=
Line->Level)
771 const auto *J = I + 2 + NumStmts;
772 for (; J !=
E; ++J) {
774 if (
Line->InPPDirective != InPPDirective)
776 if (
Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
778 if (
Line->First->isNot(tok::comment) || Level !=
Line->Level)
783 if (
Line->Last->is(tok::comment))
784 EndsWithComment =
true;
785 Length += I[1 + NumStmts]->Last->TotalLength + 1;
787 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
792 unsigned tryMergeSimpleBlock(ArrayRef<AnnotatedLine *>::const_iterator I,
793 ArrayRef<AnnotatedLine *>::const_iterator
E,
799 AnnotatedLine &
Line = **I;
805 Line.First->isOneOf(tok::at, tok::minus, tok::plus)) {
811 if (
Line.First->is(tok::kw_case) ||
812 (
Line.First->Next &&
Line.First->Next->is(tok::kw_else))) {
816 if (
Line.First->is(tok::kw_default)) {
817 const FormatToken *Tok =
Line.First->getNextNonComment();
818 if (Tok && Tok->is(tok::colon))
822 auto IsCtrlStmt = [](
const auto &
Line) {
823 return Line.First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
824 tok::kw_do, tok::kw_for, TT_ForEachMacro);
827 const bool IsSplitBlock =
830 I[1]->First->isNot(tok::r_brace));
832 if (IsCtrlStmt(
Line) ||
833 Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
834 tok::kw___finally, tok::r_brace,
835 Keywords.kw___except)) {
840 if (!Style.AllowShortIfStatementsOnASingleLine &&
841 Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
842 !Style.BraceWrapping.AfterControlStatement &&
843 I[1]->First->isNot(tok::r_brace)) {
846 if (!Style.AllowShortIfStatementsOnASingleLine &&
847 Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
848 Style.BraceWrapping.AfterControlStatement ==
850 I + 2 !=
E && I[2]->First->isNot(tok::r_brace)) {
853 if (!Style.AllowShortLoopsOnASingleLine &&
854 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
856 !Style.BraceWrapping.AfterControlStatement &&
857 I[1]->First->isNot(tok::r_brace)) {
860 if (!Style.AllowShortLoopsOnASingleLine &&
861 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
863 Style.BraceWrapping.AfterControlStatement ==
865 I + 2 !=
E && I[2]->First->isNot(tok::r_brace)) {
873 if (
Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
874 Keywords.kw___except, tok::kw___finally)) {
879 if (
Line.endsWith(tok::l_brace)) {
881 Line.First->is(TT_BlockLBrace)) {
885 if (IsSplitBlock &&
Line.First ==
Line.Last &&
886 I > AnnotatedLines.begin() &&
887 (I[-1]->endsWith(tok::kw_else) || IsCtrlStmt(*I[-1]))) {
890 FormatToken *Tok = I[1]->First;
891 auto ShouldMerge = [Tok]() {
892 if (Tok->isNot(tok::r_brace) || Tok->MustBreakBefore)
894 const FormatToken *Next = Tok->getNextNonComment();
895 return !Next || Next->is(tok::semi);
900 Tok->SpacesRequiredBefore =
901 (Style.SpaceInEmptyBlock ||
Line.Last->is(tok::comment)) ? 1 : 0;
902 Tok->CanBreakBefore =
true;
904 }
else if (Limit != 0 && !
Line.startsWithNamespace() &&
905 !startsExternCBlock(
Line)) {
907 if (isRecordLBrace(*
Line.Last))
913 Limit = limitConsideringMacros(I + 2,
E, Limit);
915 if (!nextTwoLinesFitInto(I, Limit))
920 if (I[1]->
Last->is(TT_LineComment))
930 if (Tok->isNot(tok::r_brace))
934 if (Tok->Next && Tok->Next->is(tok::kw_else))
943 if (
Line.First ==
Line.Last &&
Line.First->isNot(TT_FunctionLBrace) &&
944 Style.BraceWrapping.AfterControlStatement ==
951 }
else if (I[1]->
First->is(tok::l_brace)) {
952 if (I[1]->
Last->is(TT_LineComment))
956 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
959 unsigned MergedLines = 0;
961 (I[1]->First == I[1]->Last && I + 2 !=
E &&
962 I[2]->First->is(tok::r_brace))) {
963 MergedLines = tryMergeSimpleBlock(I + 1,
E, Limit);
976 unsigned limitConsideringMacros(ArrayRef<AnnotatedLine *>::const_iterator I,
977 ArrayRef<AnnotatedLine *>::const_iterator
E,
979 if (I[0]->InPPDirective && I + 1 !=
E &&
980 !I[1]->
First->HasUnescapedNewline && I[1]->First->isNot(tok::eof)) {
981 return Limit < 2 ? 0 : Limit - 2;
986 bool nextTwoLinesFitInto(ArrayRef<AnnotatedLine *>::const_iterator I,
988 if (I[1]->
First->MustBreakBefore || I[2]->First->MustBreakBefore)
990 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
993 bool nextNLinesFitInto(ArrayRef<AnnotatedLine *>::const_iterator I,
994 ArrayRef<AnnotatedLine *>::const_iterator
E,
996 unsigned JoinedLength = 0;
997 for (
const auto *J = I + 1; J !=
E; ++J) {
998 if ((*J)->First->MustBreakBefore)
1001 JoinedLength += 1 + (*J)->Last->TotalLength;
1002 if (JoinedLength > Limit)
1008 bool containsMustBreak(
const AnnotatedLine *
Line) {
1009 assert(
Line->First);
1012 for (
const FormatToken *Tok =
Line->First->Next; Tok; Tok = Tok->Next)
1013 if (Tok->MustBreakBefore)
1018 void join(AnnotatedLine &A,
const AnnotatedLine &B) {
1019 assert(!A.Last->Next);
1020 assert(!B.First->Previous);
1023 A.Last->Next = B.First;
1024 B.First->Previous = A.Last;
1025 B.First->CanBreakBefore =
true;
1026 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1027 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1028 Tok->TotalLength += LengthA;
1033 const FormatStyle &Style;
1034 const AdditionalKeywords &Keywords;
1035 const ArrayRef<AnnotatedLine *>::const_iterator End;
1037 ArrayRef<AnnotatedLine *>::const_iterator Next;
1038 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
1041static void markFinalized(FormatToken *Tok) {
1042 if (Tok->is(tok::hash) && !Tok->Previous && Tok->Next &&
1043 Tok->Next->isOneOf(tok::pp_if, tok::pp_ifdef, tok::pp_ifndef,
1044 tok::pp_elif, tok::pp_elifdef, tok::pp_elifndef,
1045 tok::pp_else, tok::pp_endif)) {
1048 for (; Tok; Tok = Tok->Next) {
1061 Tok->SpacesRequiredBefore = 0;
1062 if (!Tok->MustBreakBeforeFinalized)
1063 Tok->MustBreakBefore = 0;
1065 Tok->Finalized =
true;
1071static void printLineState(
const LineState &State) {
1072 llvm::dbgs() <<
"State: ";
1073 for (
const ParenState &
P : State.Stack) {
1074 llvm::dbgs() << (
P.Tok ?
P.Tok->TokenText :
"F") <<
"|" <<
P.Indent <<
"|"
1075 <<
P.LastSpace <<
"|" <<
P.NestedBlockIndent <<
" ";
1077 llvm::dbgs() << State.NextToken->TokenText <<
"\n";
1082class LineFormatter {
1084 LineFormatter(ContinuationIndenter *
Indenter, WhitespaceManager *Whitespaces,
1085 const FormatStyle &Style,
1086 UnwrappedLineFormatter *BlockFormatter)
1088 BlockFormatter(BlockFormatter) {}
1089 virtual ~LineFormatter() {}
1094 virtual unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1095 unsigned FirstStartColumn,
bool DryRun) = 0;
1118 bool formatChildren(LineState &State,
bool NewLine,
bool DryRun,
1119 unsigned &Penalty) {
1120 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1121 bool HasLBrace = LBrace && LBrace->is(tok::l_brace) && LBrace->is(
BK_Block);
1122 FormatToken &
Previous = *State.NextToken->Previous;
1123 if (
Previous.Children.size() == 0 || (!HasLBrace && !LBrace->MacroParent)) {
1130 const ParenState &
P = State.Stack.back();
1132 int AdditionalIndent =
1133 P.Indent -
Previous.Children[0]->Level * Style.IndentWidth;
1135 BlockFormatter->format(
Previous.Children, DryRun, AdditionalIndent,
1140 if (
Previous.Children[0]->First->MustBreakBefore)
1151 const AnnotatedLine *Child =
Previous.Children[0];
1153 if (Child->Last->isTrailingComment())
1158 if (Style.ColumnLimit > 0 &&
1159 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit) {
1164 Whitespaces->replaceWhitespace(
1165 *Child->First, 0, 1,
1166 State.Column,
false,
1167 State.Line->InPPDirective);
1170 formatLine(*Child, State.Column + 1, 0, DryRun);
1172 markFinalized(Child->First);
1174 State.Column += 1 + Child->Last->TotalLength;
1181 WhitespaceManager *Whitespaces;
1182 const FormatStyle &Style;
1183 UnwrappedLineFormatter *BlockFormatter;
1187class NoColumnLimitLineFormatter :
public LineFormatter {
1189 NoColumnLimitLineFormatter(ContinuationIndenter *
Indenter,
1190 WhitespaceManager *Whitespaces,
1191 const FormatStyle &Style,
1192 UnwrappedLineFormatter *BlockFormatter)
1193 : LineFormatter(
Indenter, Whitespaces, Style, BlockFormatter) {}
1197 unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1198 unsigned FirstStartColumn,
bool DryRun)
override {
1200 LineState State =
Indenter->getInitialState(FirstIndent, FirstStartColumn,
1202 while (State.NextToken) {
1205 (
Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
1206 unsigned Penalty = 0;
1207 formatChildren(State, Newline,
false, Penalty);
1208 Indenter->addTokenToState(State, Newline,
false);
1215class NoLineBreakFormatter :
public LineFormatter {
1217 NoLineBreakFormatter(ContinuationIndenter *
Indenter,
1218 WhitespaceManager *Whitespaces,
const FormatStyle &Style,
1219 UnwrappedLineFormatter *BlockFormatter)
1220 : LineFormatter(
Indenter, Whitespaces, Style, BlockFormatter) {}
1223 unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1224 unsigned FirstStartColumn,
bool DryRun)
override {
1225 unsigned Penalty = 0;
1227 Indenter->getInitialState(FirstIndent, FirstStartColumn, &
Line, DryRun);
1228 while (State.NextToken) {
1229 formatChildren(State,
false, DryRun, Penalty);
1231 State, State.NextToken->MustBreakBefore, DryRun);
1238class OptimizingLineFormatter :
public LineFormatter {
1240 OptimizingLineFormatter(ContinuationIndenter *
Indenter,
1241 WhitespaceManager *Whitespaces,
1242 const FormatStyle &Style,
1243 UnwrappedLineFormatter *BlockFormatter)
1244 : LineFormatter(
Indenter, Whitespaces, Style, BlockFormatter) {}
1248 unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1249 unsigned FirstStartColumn,
bool DryRun)
override {
1251 Indenter->getInitialState(FirstIndent, FirstStartColumn, &
Line, DryRun);
1256 State.Stack.back().BreakBeforeParameter =
true;
1259 return analyzeSolutionSpace(State, DryRun);
1263 struct CompareLineStatePointers {
1264 bool operator()(LineState *obj1, LineState *obj2)
const {
1265 return *obj1 < *obj2;
1274 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1279 StateNode(
const LineState &State,
bool NewLine, StateNode *Previous)
1288 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1291 typedef std::priority_queue<QueueItem, SmallVector<QueueItem>,
1292 std::greater<QueueItem>>
1303 unsigned analyzeSolutionSpace(LineState &InitialState,
bool DryRun) {
1304 std::set<LineState *, CompareLineStatePointers> Seen;
1312 StateNode *RootNode =
1313 new (Allocator.Allocate()) StateNode(InitialState,
false,
nullptr);
1314 Queue.push(QueueItem(OrderedPenalty(0, Count), RootNode));
1317 unsigned Penalty = 0;
1320 while (!Queue.empty()) {
1322 if (Count > 25'000'000)
1325 Penalty = Queue.top().first.first;
1326 StateNode *
Node = Queue.top().second;
1327 if (!
Node->State.NextToken) {
1328 LLVM_DEBUG(llvm::dbgs()
1329 <<
"\n---\nPenalty for line: " << Penalty <<
"\n");
1337 Node->State.IgnoreStackForComparison =
true;
1339 if (!Seen.insert(&
Node->State).second) {
1346 addNextStateToQueue(Penalty,
Node,
false, &Count, &Queue);
1348 addNextStateToQueue(Penalty,
Node,
true, &Count, &Queue);
1351 if (Queue.empty()) {
1354 LLVM_DEBUG(llvm::dbgs() <<
"Could not find a solution.\n");
1360 reconstructPath(InitialState, Queue.top().second);
1362 LLVM_DEBUG(llvm::dbgs()
1363 <<
"Total number of analyzed states: " << Count <<
"\n");
1364 LLVM_DEBUG(llvm::dbgs() <<
"---\n");
1373 void addNextStateToQueue(
unsigned Penalty, StateNode *PreviousNode,
1374 bool NewLine,
unsigned *Count, QueueType *Queue) {
1380 StateNode *
Node =
new (Allocator.Allocate())
1381 StateNode(PreviousNode->State,
NewLine, PreviousNode);
1382 if (!formatChildren(
Node->State,
NewLine,
true, Penalty))
1387 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count),
Node));
1393 void reconstructPath(LineState &State, StateNode *Best) {
1396 while (Best->Previous) {
1397 Path.push_back(Best);
1398 Best = Best->Previous;
1400 for (
const auto &
Node : llvm::reverse(
Path)) {
1401 unsigned Penalty = 0;
1402 formatChildren(State,
Node->NewLine,
false, Penalty);
1403 Penalty +=
Indenter->addTokenToState(State,
Node->NewLine,
false);
1406 printLineState(
Node->Previous->State);
1407 if (
Node->NewLine) {
1408 llvm::dbgs() <<
"Penalty for placing "
1409 <<
Node->Previous->State.NextToken->Tok.getName()
1410 <<
" on a new line: " << Penalty <<
"\n";
1416 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1423 int AdditionalIndent,
bool FixBadIndentation,
unsigned FirstStartColumn,
1424 unsigned NextStartColumn,
unsigned LastStartColumn) {
1425 LineJoiner Joiner(Style, Keywords, Lines);
1428 std::pair<const SmallVectorImpl<AnnotatedLine *> *,
unsigned> CacheKey(
1429 &Lines, AdditionalIndent);
1430 auto CacheIt = PenaltyCache.find(CacheKey);
1431 if (DryRun && CacheIt != PenaltyCache.end())
1432 return CacheIt->second;
1434 assert(!Lines.empty());
1435 unsigned Penalty = 0;
1436 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
1445 bool FirstLine =
true;
1447 Joiner.getNextMergedLine(DryRun, IndentTracker);
1448 Line; PrevPrevLine = PreviousLine, PreviousLine =
Line,
Line = NextLine,
1449 FirstLine =
false) {
1450 assert(
Line->First);
1452 unsigned Indent = IndentTracker.getIndent();
1458 bool PreviousRBrace =
1459 PreviousLine && PreviousLine->
startsWith(tok::r_brace);
1460 bool ContinueFormatting =
1461 TheLine.
Level > RangeMinLevel ||
1462 (TheLine.
Level == RangeMinLevel && !PreviousRBrace &&
1465 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
1467 bool ShouldFormat = TheLine.
Affected || FixIndentation;
1478 bool LastLine = TheLine.
First->
is(tok::eof);
1479 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines, Indent,
1480 LastLine ? LastStartColumn : NextStartColumn + Indent);
1483 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1484 unsigned ColumnLimit = getColumnLimit(TheLine.
InPPDirective, NextLine);
1485 bool FitsIntoOneLine =
1489 (!Style.isJavaScript() || !Style.JavaScriptWrapImports)) ||
1490 (Style.isCSharp() &&
1492 if (Style.ColumnLimit == 0) {
1493 NoColumnLimitLineFormatter(
Indenter, Whitespaces, Style,
this)
1494 .formatLine(TheLine, NextStartColumn + Indent,
1495 FirstLine ? FirstStartColumn : 0, DryRun);
1496 }
else if (FitsIntoOneLine) {
1497 Penalty += NoLineBreakFormatter(
Indenter, Whitespaces, Style,
this)
1498 .formatLine(TheLine, NextStartColumn + Indent,
1499 FirstLine ? FirstStartColumn : 0, DryRun);
1501 Penalty += OptimizingLineFormatter(
Indenter, Whitespaces, Style,
this)
1502 .formatLine(TheLine, NextStartColumn + Indent,
1503 FirstLine ? FirstStartColumn : 0, DryRun);
1505 RangeMinLevel = std::min(RangeMinLevel, TheLine.
Level);
1511 if (!Tok->Children.empty())
1512 format(Tok->Children, DryRun);
1517 bool StartsNewLine =
1520 IndentTracker.adjustToUnmodifiedLine(TheLine);
1522 bool ReformatLeadingWhitespace =
1523 StartsNewLine && ((PreviousLine && PreviousLine->
Affected) ||
1526 if (ReformatLeadingWhitespace) {
1527 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines,
1531 Whitespaces->addUntouchableToken(*TheLine.
First,
1537 Whitespaces->addUntouchableToken(*Tok, TheLine.
InPPDirective);
1539 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1543 markFinalized(TheLine.
First);
1545 PenaltyCache[CacheKey] = Penalty;
1554 const auto &RootToken = *
Line.First;
1558 if (RootToken.is(tok::r_brace) &&
1560 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)) &&
1563 Newlines = std::min(Newlines, 1u);
1566 if (!PreviousLine &&
Line.Level > 0)
1567 Newlines = std::min(Newlines, 1u);
1568 if (Newlines == 0 && !RootToken.IsFirst)
1570 if (RootToken.IsFirst &&
1577 PreviousLine->
Last->
is(tok::l_brace) &&
1581 !startsExternCBlock(*PreviousLine)) {
1587 if (PreviousLine && PreviousLine->
endsWith(TT_NamespaceLBrace)) {
1590 else if (!
Line.startsWithNamespace())
1591 Newlines = std::max(Newlines, 2u);
1594 if (
Line.startsWith(TT_NamespaceRBrace)) {
1597 else if (!PreviousLine->
startsWith(TT_NamespaceRBrace))
1598 Newlines = std::max(Newlines, 2u);
1603 if (PreviousLine && RootToken.isAccessSpecifier()) {
1610 Newlines = std::max(RootToken.NewlinesBefore, 1u);
1613 if (PreviousLine->
Last->
isOneOf(tok::semi, tok::r_brace) && Newlines <= 1)
1620 if (PreviousLine->
Last->
is(tok::comment))
1623 previousToken = PreviousLine->
Last;
1624 if ((!previousToken || previousToken->
isNot(tok::l_brace)) &&
1634 (!PreviousLine->
InPPDirective || !RootToken.HasUnescapedNewline)) {
1637 if (!RootToken.isAccessSpecifier()) {
1643 Newlines = std::max(Newlines, 1u);
1646 if (RootToken.is(tok::r_brace))
1649 Newlines = std::max(Newlines, 2u);
1658void UnwrappedLineFormatter::formatFirstToken(
1659 const AnnotatedLine &
Line,
const AnnotatedLine *PreviousLine,
1660 const AnnotatedLine *PrevPrevLine,
1662 unsigned NewlineIndent) {
1663 FormatToken &RootToken = *
Line.First;
1664 if (RootToken.is(tok::eof)) {
1665 unsigned Newlines = std::min(
1666 RootToken.NewlinesBefore,
1667 Style.KeepEmptyLines.AtEndOfFile ? Style.MaxEmptyLinesToKeep + 1 : 1);
1668 unsigned TokenIndent = Newlines ? NewlineIndent : 0;
1669 Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
1674 if (RootToken.Newlines < 0) {
1675 RootToken.Newlines =
1677 assert(RootToken.Newlines >= 0);
1680 if (RootToken.Newlines > 0)
1681 Indent = NewlineIndent;
1685 if (!Style.isJavaScript() &&
1692 Whitespaces->replaceWhitespace(RootToken, RootToken.Newlines, Indent, Indent,
1694 Line.InPPDirective &&
1695 !RootToken.HasUnescapedNewline);
1699UnwrappedLineFormatter::getColumnLimit(
bool InPPDirective,
1700 const AnnotatedLine *NextLine)
const {
1703 bool ContinuesPPDirective =
1708 (NextLine->InPPDirective &&
1711 !NextLine->First->HasUnescapedNewline));
1712 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
WhitespaceManager class manages whitespace around tokens and their replacements.
unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
ObjCKeywordKind
Provides a namespace for Objective-C keywords which start with an '@'.
The JSON file list parser is used to communicate input to InstallAPI.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))