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;
186const FormatToken *getMatchingNamespaceToken(
187 const AnnotatedLine *
Line,
188 const SmallVectorImpl<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();
203StringRef getMatchingNamespaceTokenText(
204 const AnnotatedLine *
Line,
205 const SmallVectorImpl<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 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
245 SmallVectorImpl<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)
367 if (Style.CompactNamespaces) {
368 if (
const auto *NSToken = TheLine->First->getNamespaceToken()) {
370 assert(TheLine->MatchingClosingBlockLineIndex > 0);
371 for (
auto ClosingLineIndex = TheLine->MatchingClosingBlockLineIndex - 1;
373 ClosingLineIndex == I[J]->MatchingClosingBlockLineIndex &&
374 I[J]->
Last->TotalLength < Limit;
375 ++J, --ClosingLineIndex) {
376 Limit -= I[J]->Last->TotalLength;
380 auto *ClosingLine = AnnotatedLines.begin() + ClosingLineIndex + 1;
381 const int OutdentBy = I[J]->Level - TheLine->Level;
382 assert(OutdentBy >= 0);
383 for (
auto *CompactedLine = I + J; CompactedLine <= ClosingLine;
385 if (!(*CompactedLine)->InPPDirective) {
386 const int Level = (*CompactedLine)->Level;
387 (*CompactedLine)->Level = std::max(Level - OutdentBy, 0);
394 if (
auto nsToken = getMatchingNamespaceToken(TheLine, AnnotatedLines)) {
396 unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
397 for (; I + 1 + i !=
E &&
398 nsToken->TokenText ==
399 getMatchingNamespaceTokenText(I[i + 1], AnnotatedLines) &&
400 openingLine == I[i + 1]->MatchingOpeningBlockLineIndex;
401 i++, --openingLine) {
403 I[i + 1]->First->SpacesRequiredBefore =
404 I[i]->Last->isNot(tok::r_brace);
407 IndentTracker.nextLine(*I[i + 1]);
413 const auto *LastNonComment = TheLine->getLastNonComment();
414 assert(LastNonComment);
419 if (LastNonComment->is(TT_FunctionLBrace) &&
420 TheLine->First != LastNonComment) {
421 return MergeShortFunctions ? tryMergeSimpleBlock(I,
E, Limit) : 0;
424 if (TheLine->Last->is(tok::l_brace) && FirstNonComment != TheLine->Last &&
425 FirstNonComment->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for,
428 ? tryMergeSimpleBlock(I,
E, Limit)
432 if (NextLine.First->is(tok::l_brace)) {
433 if ((TheLine->First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
434 tok::kw_for, tok::kw_switch, tok::kw_try,
435 tok::kw_do, TT_ForEachMacro) ||
436 (TheLine->First->is(tok::r_brace) && TheLine->First->Next &&
437 TheLine->First->Next->isOneOf(tok::kw_else, tok::kw_catch))) &&
438 Style.BraceWrapping.AfterControlStatement ==
443 return (Style.ColumnLimit == 0 || TheLine->Level * Style.IndentWidth +
444 TheLine->Last->TotalLength <=
449 if (TheLine->First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
450 tok::kw_for, TT_ForEachMacro)) {
451 return (Style.BraceWrapping.AfterControlStatement ==
453 ? tryMergeSimpleBlock(I,
E, Limit)
456 if (TheLine->First->isOneOf(tok::kw_else, tok::kw_catch) &&
457 Style.BraceWrapping.AfterControlStatement ==
464 return (Style.ColumnLimit == 0 ||
465 TheLine->Last->TotalLength <= Style.ColumnLimit)
470 if (PreviousLine && TheLine->First->is(tok::l_brace)) {
471 switch (PreviousLine->First->Tok.getKind()) {
474 if (PreviousLine->First->Next) {
476 PreviousLine->First->Next->Tok.getObjCKeywordID();
477 if (kwId == tok::objc_autoreleasepool ||
478 kwId == tok::objc_synchronized) {
485 case tok::kw_default:
496 if (PreviousLine && Style.BraceWrapping.SplitEmptyRecord &&
497 TheLine->Last->is(tok::l_brace) && PreviousLine->Last) {
498 const FormatToken *
Previous = PreviousLine->Last;
503 if (
Previous->is(tok::greater) && !PreviousLine->InPPDirective)
505 if (
Previous->is(tok::identifier)) {
506 const FormatToken *PreviousPrevious =
508 if (PreviousPrevious &&
509 PreviousPrevious->isOneOf(tok::kw_class, tok::kw_struct)) {
517 if (TheLine->First->is(TT_SwitchExpressionLabel)) {
518 return Style.AllowShortCaseExpressionOnASingleLine
519 ? tryMergeShortCaseLabels(I,
E, Limit)
523 if (TheLine->Last->is(tok::l_brace)) {
524 bool ShouldMerge =
false;
526 if (TheLine->Last->is(TT_EnumLBrace)) {
527 ShouldMerge = Style.AllowShortEnumsOnASingleLine;
528 }
else if (TheLine->Last->is(TT_RequiresExpressionLBrace)) {
529 ShouldMerge = Style.AllowShortCompoundRequirementOnASingleLine;
530 }
else if (TheLine->Last->isOneOf(TT_ClassLBrace, TT_StructLBrace)) {
534 ShouldMerge = !Style.BraceWrapping.AfterClass ||
535 (NextLine.First->is(tok::r_brace) &&
536 !Style.BraceWrapping.SplitEmptyRecord);
537 }
else if (TheLine->InPPDirective ||
538 !TheLine->First->isOneOf(tok::kw_class, tok::kw_enum,
542 ShouldMerge = !Style.BraceWrapping.AfterFunction ||
543 (NextLine.First->is(tok::r_brace) &&
544 !Style.BraceWrapping.SplitEmptyFunction);
546 return ShouldMerge ? tryMergeSimpleBlock(I,
E, Limit) : 0;
550 if (NextLine.First->is(TT_FunctionLBrace) &&
551 Style.BraceWrapping.AfterFunction) {
552 if (NextLine.Last->is(TT_LineComment))
556 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
560 unsigned MergedLines = 0;
561 if (MergeShortFunctions ||
563 NextLine.First == NextLine.Last && I + 2 !=
E &&
564 I[2]->First->is(tok::r_brace))) {
565 MergedLines = tryMergeSimpleBlock(I + 1,
E, Limit);
573 auto IsElseLine = [&TheLine]() ->
bool {
574 const FormatToken *
First = TheLine->First;
575 if (
First->is(tok::kw_else))
578 return First->is(tok::r_brace) &&
First->Next &&
579 First->Next->is(tok::kw_else);
581 if (TheLine->First->is(tok::kw_if) ||
582 (IsElseLine() && (Style.AllowShortIfStatementsOnASingleLine ==
584 return Style.AllowShortIfStatementsOnASingleLine
585 ? tryMergeSimpleControlStatement(I,
E, Limit)
588 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while, tok::kw_do,
590 return Style.AllowShortLoopsOnASingleLine
591 ? tryMergeSimpleControlStatement(I,
E, Limit)
594 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
595 return Style.AllowShortCaseLabelsOnASingleLine
596 ? tryMergeShortCaseLabels(I,
E, Limit)
599 if (TheLine->InPPDirective &&
600 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
601 return tryMergeSimplePPDirective(I,
E, Limit);
607 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
608 SmallVectorImpl<AnnotatedLine *>::const_iterator
E,
612 if (I + 2 !=
E && I[2]->InPPDirective && !I[2]->
First->HasUnescapedNewline)
614 if (1 + I[1]->
Last->TotalLength > Limit)
619 unsigned tryMergeSimpleControlStatement(
620 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
621 SmallVectorImpl<AnnotatedLine *>::const_iterator
E,
unsigned Limit) {
624 if (Style.BraceWrapping.AfterControlStatement ==
626 I[1]->First->is(tok::l_brace) &&
630 if (I[1]->InPPDirective != (*I)->InPPDirective ||
631 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) {
634 Limit = limitConsideringMacros(I + 1,
E, Limit);
635 AnnotatedLine &
Line = **I;
636 if (
Line.First->isNot(tok::kw_do) &&
Line.First->isNot(tok::kw_else) &&
637 Line.Last->isNot(tok::kw_else) &&
Line.Last->isNot(tok::r_paren)) {
641 if (
Line.First->is(tok::kw_do) &&
Line.Last->isNot(tok::kw_do))
643 if (1 + I[1]->
Last->TotalLength > Limit)
646 if (I[1]->
First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
647 TT_ForEachMacro, TT_LineComment)) {
651 if (Style.AllowShortIfStatementsOnASingleLine ==
653 if (I + 2 !=
E &&
Line.startsWith(tok::kw_if) &&
654 I[2]->First->is(tok::kw_else)) {
662 tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
663 SmallVectorImpl<AnnotatedLine *>::const_iterator
E,
665 if (Limit == 0 || I + 1 ==
E ||
666 I[1]->
First->isOneOf(tok::kw_case, tok::kw_default)) {
669 if (I[0]->
Last->is(tok::l_brace) || I[1]->First->is(tok::l_brace))
671 unsigned NumStmts = 0;
673 bool EndsWithComment =
false;
674 bool InPPDirective = I[0]->InPPDirective;
675 bool InMacroBody = I[0]->InMacroBody;
676 const unsigned Level = I[0]->Level;
677 for (; NumStmts < 3; ++NumStmts) {
678 if (I + 1 + NumStmts ==
E)
680 const AnnotatedLine *
Line = I[1 + NumStmts];
681 if (
Line->InPPDirective != InPPDirective)
683 if (
Line->InMacroBody != InMacroBody)
685 if (
Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
687 if (
Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
692 if (
Line->First->is(tok::comment)) {
693 if (Level !=
Line->Level)
695 SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts;
696 for (; J !=
E; ++J) {
698 if (
Line->InPPDirective != InPPDirective)
700 if (
Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
702 if (
Line->First->isNot(tok::comment) || Level !=
Line->Level)
707 if (
Line->Last->is(tok::comment))
708 EndsWithComment =
true;
709 Length += I[1 + NumStmts]->Last->TotalLength + 1;
711 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
717 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
718 SmallVectorImpl<AnnotatedLine *>::const_iterator
E,
724 AnnotatedLine &
Line = **I;
730 Line.First->isOneOf(tok::at, tok::minus, tok::plus)) {
736 if (
Line.First->is(tok::kw_case) ||
737 (
Line.First->Next &&
Line.First->Next->is(tok::kw_else))) {
741 if (
Line.First->is(tok::kw_default)) {
742 const FormatToken *Tok =
Line.First->getNextNonComment();
743 if (Tok && Tok->is(tok::colon))
747 auto IsCtrlStmt = [](
const auto &
Line) {
748 return Line.First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
749 tok::kw_do, tok::kw_for, TT_ForEachMacro);
752 const bool IsSplitBlock =
755 I[1]->First->isNot(tok::r_brace));
757 if (IsCtrlStmt(
Line) ||
758 Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
759 tok::kw___finally, tok::r_brace,
760 Keywords.kw___except)) {
765 if (!Style.AllowShortIfStatementsOnASingleLine &&
766 Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
767 !Style.BraceWrapping.AfterControlStatement &&
768 I[1]->First->isNot(tok::r_brace)) {
771 if (!Style.AllowShortIfStatementsOnASingleLine &&
772 Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
773 Style.BraceWrapping.AfterControlStatement ==
775 I + 2 !=
E && I[2]->First->isNot(tok::r_brace)) {
778 if (!Style.AllowShortLoopsOnASingleLine &&
779 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
781 !Style.BraceWrapping.AfterControlStatement &&
782 I[1]->First->isNot(tok::r_brace)) {
785 if (!Style.AllowShortLoopsOnASingleLine &&
786 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
788 Style.BraceWrapping.AfterControlStatement ==
790 I + 2 !=
E && I[2]->First->isNot(tok::r_brace)) {
798 if (
Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
799 Keywords.kw___except, tok::kw___finally)) {
804 if (
Line.endsWith(tok::l_brace)) {
806 Line.First->is(TT_BlockLBrace)) {
810 if (IsSplitBlock &&
Line.First ==
Line.Last &&
811 I > AnnotatedLines.begin() &&
812 (I[-1]->endsWith(tok::kw_else) || IsCtrlStmt(*I[-1]))) {
815 FormatToken *Tok = I[1]->First;
816 auto ShouldMerge = [Tok]() {
817 if (Tok->isNot(tok::r_brace) || Tok->MustBreakBefore)
819 const FormatToken *Next = Tok->getNextNonComment();
820 return !Next || Next->is(tok::semi);
825 Tok->SpacesRequiredBefore =
826 (Style.SpaceInEmptyBlock ||
Line.Last->is(tok::comment)) ? 1 : 0;
827 Tok->CanBreakBefore =
true;
829 }
else if (Limit != 0 && !
Line.startsWithNamespace() &&
830 !startsExternCBlock(
Line)) {
832 if (isRecordLBrace(*
Line.Last))
838 Limit = limitConsideringMacros(I + 2,
E, Limit);
840 if (!nextTwoLinesFitInto(I, Limit))
845 if (I[1]->
Last->is(TT_LineComment))
855 if (Tok->isNot(tok::r_brace))
859 if (Tok->Next && Tok->Next->is(tok::kw_else))
868 if (
Line.First ==
Line.Last &&
Line.First->isNot(TT_FunctionLBrace) &&
869 Style.BraceWrapping.AfterControlStatement ==
876 }
else if (I[1]->
First->is(tok::l_brace)) {
877 if (I[1]->
Last->is(TT_LineComment))
881 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
884 unsigned MergedLines = 0;
886 (I[1]->First == I[1]->Last && I + 2 !=
E &&
887 I[2]->First->is(tok::r_brace))) {
888 MergedLines = tryMergeSimpleBlock(I + 1,
E, Limit);
902 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
903 SmallVectorImpl<AnnotatedLine *>::const_iterator
E,
905 if (I[0]->InPPDirective && I + 1 !=
E &&
906 !I[1]->
First->HasUnescapedNewline && I[1]->First->isNot(tok::eof)) {
907 return Limit < 2 ? 0 : Limit - 2;
912 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
914 if (I[1]->
First->MustBreakBefore || I[2]->First->MustBreakBefore)
916 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
919 bool containsMustBreak(
const AnnotatedLine *
Line) {
923 for (
const FormatToken *Tok =
Line->First->Next; Tok; Tok = Tok->Next)
924 if (Tok->MustBreakBefore)
929 void join(AnnotatedLine &A,
const AnnotatedLine &B) {
930 assert(!A.Last->Next);
931 assert(!B.First->Previous);
934 A.Last->Next = B.First;
935 B.First->Previous = A.Last;
936 B.First->CanBreakBefore =
true;
937 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
938 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
939 Tok->TotalLength += LengthA;
944 const FormatStyle &Style;
945 const AdditionalKeywords &Keywords;
946 const SmallVectorImpl<AnnotatedLine *>::const_iterator End;
948 SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
949 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
952static void markFinalized(FormatToken *Tok) {
953 if (Tok->is(tok::hash) && !Tok->Previous && Tok->Next &&
954 Tok->Next->isOneOf(tok::pp_if, tok::pp_ifdef, tok::pp_ifndef,
955 tok::pp_elif, tok::pp_elifdef, tok::pp_elifndef,
956 tok::pp_else, tok::pp_endif)) {
959 for (; Tok; Tok = Tok->Next) {
972 Tok->SpacesRequiredBefore = 0;
973 if (!Tok->MustBreakBeforeFinalized)
974 Tok->MustBreakBefore = 0;
976 Tok->Finalized =
true;
982static void printLineState(
const LineState &State) {
983 llvm::dbgs() <<
"State: ";
984 for (
const ParenState &
P : State.Stack) {
985 llvm::dbgs() << (
P.Tok ?
P.Tok->TokenText :
"F") <<
"|" <<
P.Indent <<
"|"
986 <<
P.LastSpace <<
"|" <<
P.NestedBlockIndent <<
" ";
988 llvm::dbgs() << State.NextToken->TokenText <<
"\n";
995 LineFormatter(ContinuationIndenter *
Indenter, WhitespaceManager *Whitespaces,
996 const FormatStyle &Style,
997 UnwrappedLineFormatter *BlockFormatter)
999 BlockFormatter(BlockFormatter) {}
1000 virtual ~LineFormatter() {}
1005 virtual unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1006 unsigned FirstStartColumn,
bool DryRun) = 0;
1029 bool formatChildren(LineState &State,
bool NewLine,
bool DryRun,
1030 unsigned &Penalty) {
1031 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1032 bool HasLBrace = LBrace && LBrace->is(tok::l_brace) && LBrace->is(
BK_Block);
1033 FormatToken &
Previous = *State.NextToken->Previous;
1034 if (
Previous.Children.size() == 0 || (!HasLBrace && !LBrace->MacroParent)) {
1041 const ParenState &
P = State.Stack.back();
1043 int AdditionalIndent =
1044 P.Indent -
Previous.Children[0]->Level * Style.IndentWidth;
1046 BlockFormatter->format(
Previous.Children, DryRun, AdditionalIndent,
1051 if (
Previous.Children[0]->First->MustBreakBefore)
1062 const AnnotatedLine *Child =
Previous.Children[0];
1064 if (Child->Last->isTrailingComment())
1069 if (Style.ColumnLimit > 0 &&
1070 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit) {
1075 Whitespaces->replaceWhitespace(
1076 *Child->First, 0, 1,
1077 State.Column,
false,
1078 State.Line->InPPDirective);
1081 formatLine(*Child, State.Column + 1, 0, DryRun);
1083 markFinalized(Child->First);
1085 State.Column += 1 + Child->Last->TotalLength;
1092 WhitespaceManager *Whitespaces;
1093 const FormatStyle &Style;
1094 UnwrappedLineFormatter *BlockFormatter;
1098class NoColumnLimitLineFormatter :
public LineFormatter {
1100 NoColumnLimitLineFormatter(ContinuationIndenter *
Indenter,
1101 WhitespaceManager *Whitespaces,
1102 const FormatStyle &Style,
1103 UnwrappedLineFormatter *BlockFormatter)
1104 : LineFormatter(
Indenter, Whitespaces, Style, BlockFormatter) {}
1108 unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1109 unsigned FirstStartColumn,
bool DryRun)
override {
1111 LineState State =
Indenter->getInitialState(FirstIndent, FirstStartColumn,
1113 while (State.NextToken) {
1116 (
Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
1117 unsigned Penalty = 0;
1118 formatChildren(State, Newline,
false, Penalty);
1119 Indenter->addTokenToState(State, Newline,
false);
1126class NoLineBreakFormatter :
public LineFormatter {
1128 NoLineBreakFormatter(ContinuationIndenter *
Indenter,
1129 WhitespaceManager *Whitespaces,
const FormatStyle &Style,
1130 UnwrappedLineFormatter *BlockFormatter)
1131 : LineFormatter(
Indenter, Whitespaces, Style, BlockFormatter) {}
1134 unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1135 unsigned FirstStartColumn,
bool DryRun)
override {
1136 unsigned Penalty = 0;
1138 Indenter->getInitialState(FirstIndent, FirstStartColumn, &
Line, DryRun);
1139 while (State.NextToken) {
1140 formatChildren(State,
false, DryRun, Penalty);
1142 State, State.NextToken->MustBreakBefore, DryRun);
1149class OptimizingLineFormatter :
public LineFormatter {
1151 OptimizingLineFormatter(ContinuationIndenter *
Indenter,
1152 WhitespaceManager *Whitespaces,
1153 const FormatStyle &Style,
1154 UnwrappedLineFormatter *BlockFormatter)
1155 : LineFormatter(
Indenter, Whitespaces, Style, BlockFormatter) {}
1159 unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1160 unsigned FirstStartColumn,
bool DryRun)
override {
1162 Indenter->getInitialState(FirstIndent, FirstStartColumn, &
Line, DryRun);
1167 State.Stack.back().BreakBeforeParameter =
true;
1170 return analyzeSolutionSpace(State, DryRun);
1174 struct CompareLineStatePointers {
1175 bool operator()(LineState *obj1, LineState *obj2)
const {
1176 return *obj1 < *obj2;
1185 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1190 StateNode(
const LineState &State,
bool NewLine, StateNode *Previous)
1199 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1202 typedef std::priority_queue<QueueItem, SmallVector<QueueItem>,
1203 std::greater<QueueItem>>
1214 unsigned analyzeSolutionSpace(LineState &InitialState,
bool DryRun) {
1215 std::set<LineState *, CompareLineStatePointers> Seen;
1223 StateNode *RootNode =
1224 new (Allocator.Allocate()) StateNode(InitialState,
false,
nullptr);
1225 Queue.push(QueueItem(OrderedPenalty(0, Count), RootNode));
1228 unsigned Penalty = 0;
1231 while (!Queue.empty()) {
1233 if (Count > 25'000'000)
1236 Penalty = Queue.top().first.first;
1237 StateNode *
Node = Queue.top().second;
1238 if (!
Node->State.NextToken) {
1239 LLVM_DEBUG(llvm::dbgs()
1240 <<
"\n---\nPenalty for line: " << Penalty <<
"\n");
1248 Node->State.IgnoreStackForComparison =
true;
1250 if (!Seen.insert(&
Node->State).second) {
1257 addNextStateToQueue(Penalty,
Node,
false, &Count, &Queue);
1259 addNextStateToQueue(Penalty,
Node,
true, &Count, &Queue);
1262 if (Queue.empty()) {
1265 LLVM_DEBUG(llvm::dbgs() <<
"Could not find a solution.\n");
1271 reconstructPath(InitialState, Queue.top().second);
1273 LLVM_DEBUG(llvm::dbgs()
1274 <<
"Total number of analyzed states: " << Count <<
"\n");
1275 LLVM_DEBUG(llvm::dbgs() <<
"---\n");
1284 void addNextStateToQueue(
unsigned Penalty, StateNode *PreviousNode,
1285 bool NewLine,
unsigned *Count, QueueType *Queue) {
1291 StateNode *
Node =
new (Allocator.Allocate())
1292 StateNode(PreviousNode->State,
NewLine, PreviousNode);
1293 if (!formatChildren(
Node->State,
NewLine,
true, Penalty))
1298 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count),
Node));
1304 void reconstructPath(LineState &State, StateNode *Best) {
1307 while (Best->Previous) {
1308 Path.push_back(Best);
1309 Best = Best->Previous;
1311 for (
const auto &
Node : llvm::reverse(
Path)) {
1312 unsigned Penalty = 0;
1313 formatChildren(State,
Node->NewLine,
false, Penalty);
1314 Penalty +=
Indenter->addTokenToState(State,
Node->NewLine,
false);
1317 printLineState(
Node->Previous->State);
1318 if (
Node->NewLine) {
1319 llvm::dbgs() <<
"Penalty for placing "
1320 <<
Node->Previous->State.NextToken->Tok.getName()
1321 <<
" on a new line: " << Penalty <<
"\n";
1327 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1334 int AdditionalIndent,
bool FixBadIndentation,
unsigned FirstStartColumn,
1335 unsigned NextStartColumn,
unsigned LastStartColumn) {
1336 LineJoiner Joiner(Style, Keywords, Lines);
1339 std::pair<const SmallVectorImpl<AnnotatedLine *> *,
unsigned> CacheKey(
1340 &Lines, AdditionalIndent);
1341 auto CacheIt = PenaltyCache.find(CacheKey);
1342 if (DryRun && CacheIt != PenaltyCache.end())
1343 return CacheIt->second;
1345 assert(!Lines.empty());
1346 unsigned Penalty = 0;
1347 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
1356 bool FirstLine =
true;
1358 Joiner.getNextMergedLine(DryRun, IndentTracker);
1359 Line; PrevPrevLine = PreviousLine, PreviousLine =
Line,
Line = NextLine,
1360 FirstLine =
false) {
1361 assert(
Line->First);
1363 unsigned Indent = IndentTracker.getIndent();
1369 bool PreviousRBrace =
1370 PreviousLine && PreviousLine->
startsWith(tok::r_brace);
1371 bool ContinueFormatting =
1372 TheLine.
Level > RangeMinLevel ||
1373 (TheLine.
Level == RangeMinLevel && !PreviousRBrace &&
1376 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
1378 bool ShouldFormat = TheLine.
Affected || FixIndentation;
1389 bool LastLine = TheLine.
First->
is(tok::eof);
1390 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines, Indent,
1391 LastLine ? LastStartColumn : NextStartColumn + Indent);
1394 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1395 unsigned ColumnLimit = getColumnLimit(TheLine.
InPPDirective, NextLine);
1396 bool FitsIntoOneLine =
1400 (!Style.isJavaScript() || !Style.JavaScriptWrapImports)) ||
1401 (Style.isCSharp() &&
1403 if (Style.ColumnLimit == 0) {
1404 NoColumnLimitLineFormatter(
Indenter, Whitespaces, Style,
this)
1405 .formatLine(TheLine, NextStartColumn + Indent,
1406 FirstLine ? FirstStartColumn : 0, DryRun);
1407 }
else if (FitsIntoOneLine) {
1408 Penalty += NoLineBreakFormatter(
Indenter, Whitespaces, Style,
this)
1409 .formatLine(TheLine, NextStartColumn + Indent,
1410 FirstLine ? FirstStartColumn : 0, DryRun);
1412 Penalty += OptimizingLineFormatter(
Indenter, Whitespaces, Style,
this)
1413 .formatLine(TheLine, NextStartColumn + Indent,
1414 FirstLine ? FirstStartColumn : 0, DryRun);
1416 RangeMinLevel = std::min(RangeMinLevel, TheLine.
Level);
1422 if (!Tok->Children.empty())
1423 format(Tok->Children, DryRun);
1428 bool StartsNewLine =
1431 IndentTracker.adjustToUnmodifiedLine(TheLine);
1433 bool ReformatLeadingWhitespace =
1434 StartsNewLine && ((PreviousLine && PreviousLine->
Affected) ||
1437 if (ReformatLeadingWhitespace) {
1438 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines,
1442 Whitespaces->addUntouchableToken(*TheLine.
First,
1448 Whitespaces->addUntouchableToken(*Tok, TheLine.
InPPDirective);
1450 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1454 markFinalized(TheLine.
First);
1456 PenaltyCache[CacheKey] = Penalty;
1465 const auto &RootToken = *
Line.First;
1469 if (RootToken.is(tok::r_brace) &&
1471 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)) &&
1474 Newlines = std::min(Newlines, 1u);
1477 if (!PreviousLine &&
Line.Level > 0)
1478 Newlines = std::min(Newlines, 1u);
1479 if (Newlines == 0 && !RootToken.IsFirst)
1481 if (RootToken.IsFirst &&
1488 PreviousLine->
Last->
is(tok::l_brace) &&
1492 !startsExternCBlock(*PreviousLine)) {
1497 if (PreviousLine && RootToken.isAccessSpecifier()) {
1504 Newlines = std::max(RootToken.NewlinesBefore, 1u);
1507 if (PreviousLine->
Last->
isOneOf(tok::semi, tok::r_brace) && Newlines <= 1)
1514 if (PreviousLine->
Last->
is(tok::comment))
1517 previousToken = PreviousLine->
Last;
1518 if ((!previousToken || previousToken->
isNot(tok::l_brace)) &&
1528 (!PreviousLine->
InPPDirective || !RootToken.HasUnescapedNewline)) {
1531 if (!RootToken.isAccessSpecifier()) {
1537 Newlines = std::max(Newlines, 1u);
1540 if (RootToken.is(tok::r_brace))
1543 Newlines = std::max(Newlines, 2u);
1552void UnwrappedLineFormatter::formatFirstToken(
1553 const AnnotatedLine &
Line,
const AnnotatedLine *PreviousLine,
1554 const AnnotatedLine *PrevPrevLine,
1556 unsigned NewlineIndent) {
1557 FormatToken &RootToken = *
Line.First;
1558 if (RootToken.is(tok::eof)) {
1559 unsigned Newlines = std::min(
1560 RootToken.NewlinesBefore,
1561 Style.KeepEmptyLines.AtEndOfFile ? Style.MaxEmptyLinesToKeep + 1 : 1);
1562 unsigned TokenIndent = Newlines ? NewlineIndent : 0;
1563 Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
1568 if (RootToken.Newlines < 0) {
1569 RootToken.Newlines =
1571 assert(RootToken.Newlines >= 0);
1574 if (RootToken.Newlines > 0)
1575 Indent = NewlineIndent;
1579 if (!Style.isJavaScript() &&
1586 Whitespaces->replaceWhitespace(RootToken, RootToken.Newlines, Indent, Indent,
1588 Line.InPPDirective &&
1589 !RootToken.HasUnescapedNewline);
1593UnwrappedLineFormatter::getColumnLimit(
bool InPPDirective,
1594 const AnnotatedLine *NextLine)
const {
1597 bool ContinuesPPDirective =
1602 (NextLine->InPPDirective &&
1605 !NextLine->First->HasUnescapedNewline));
1606 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())))