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) {
115 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp())
117 const auto &RootToken = *
Line.First;
119 RootToken.isAccessSpecifier(
false) ||
120 RootToken.isObjCAccessSpecifier() ||
121 (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
122 RootToken.Next && RootToken.Next->is(tok::colon))) {
126 return Style.IndentAccessModifiers ? -Style.IndentWidth
127 : Style.AccessModifierOffset;
137 unsigned getIndent(
unsigned Level)
const {
138 assert(Level < IndentForLevel.size());
139 if (IndentForLevel[Level] != -1)
140 return IndentForLevel[Level];
143 return getIndent(Level - 1) + Style.IndentWidth;
146 const FormatStyle &Style;
147 const AdditionalKeywords &Keywords;
148 const unsigned AdditionalIndent;
154 SmallVector<int> IndentForLevel;
167getMatchingNamespaceToken(
const AnnotatedLine *
Line,
168 const ArrayRef<AnnotatedLine *> &AnnotatedLines) {
169 if (!
Line->startsWith(tok::r_brace))
171 size_t StartLineIndex =
Line->MatchingOpeningBlockLineIndex;
174 assert(StartLineIndex < AnnotatedLines.size());
175 return AnnotatedLines[StartLineIndex]->First->getNamespaceToken();
179 const FormatToken *NamespaceToken =
Line->First->getNamespaceToken();
180 return NamespaceToken ? NamespaceToken->TokenText : StringRef();
184getMatchingNamespaceTokenText(
const AnnotatedLine *
Line,
185 const ArrayRef<AnnotatedLine *> &AnnotatedLines) {
186 const FormatToken *NamespaceToken =
187 getMatchingNamespaceToken(
Line, AnnotatedLines);
188 return NamespaceToken ? NamespaceToken->TokenText : StringRef();
193 LineJoiner(
const FormatStyle &Style,
const AdditionalKeywords &Keywords,
194 const SmallVectorImpl<AnnotatedLine *> &Lines)
195 : Style(Style), Keywords(Keywords), End(Lines.end()), Next(Lines.begin()),
196 AnnotatedLines(Lines) {}
199 const AnnotatedLine *getNextMergedLine(
bool DryRun,
200 LevelIndentTracker &IndentTracker) {
203 const AnnotatedLine *Current = *Next;
204 IndentTracker.nextLine(*Current);
205 unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next, End);
206 if (MergedLines > 0 && Style.ColumnLimit == 0) {
209 for (
unsigned i = 0; i < MergedLines; ++i)
210 if (Next[i + 1]->
First->NewlinesBefore > 0)
214 for (
unsigned i = 0; i < MergedLines; ++i)
215 join(*Next[0], *Next[i + 1]);
216 Next = Next + MergedLines + 1;
223 tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker,
224 ArrayRef<AnnotatedLine *>::const_iterator I,
225 ArrayRef<AnnotatedLine *>::const_iterator
E) {
230 const AnnotatedLine *TheLine = *I;
231 if (TheLine->Last->is(TT_LineComment))
233 const auto &NextLine = *I[1];
234 if (NextLine.Type ==
LT_Invalid || NextLine.First->MustBreakBefore)
236 if (TheLine->InPPDirective &&
237 (!NextLine.InPPDirective || NextLine.First->HasUnescapedNewline)) {
241 const auto Indent = IndentTracker.getIndent();
242 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
246 Style.ColumnLimit == 0 ?
UINT_MAX : Style.ColumnLimit - Indent;
249 Limit = TheLine->Last->TotalLength > Limit
251 : Limit - TheLine->Last->TotalLength;
253 if (TheLine->Last->is(TT_FunctionLBrace) &&
254 TheLine->First == TheLine->Last) {
255 const bool EmptyFunctionBody = NextLine.First->is(tok::r_brace);
256 if ((EmptyFunctionBody && !Style.BraceWrapping.SplitEmptyFunction) ||
257 (!EmptyFunctionBody &&
259 return tryMergeSimpleBlock(I,
E, Limit);
263 const auto *PreviousLine = I != AnnotatedLines.begin() ? I[-1] :
nullptr;
265 if (PreviousLine && TheLine->Last->is(tok::l_brace) &&
266 TheLine->First == TheLine->Last) {
267 bool EmptyBlock = NextLine.First->is(tok::r_brace);
269 const FormatToken *Tok = PreviousLine->First;
270 if (Tok && Tok->is(tok::comment))
271 Tok = Tok->getNextNonComment();
273 if (Tok && Tok->getNamespaceToken()) {
274 return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock
275 ? tryMergeSimpleBlock(I,
E, Limit)
279 if (Tok && Tok->is(tok::kw_typedef))
280 Tok = Tok->getNextNonComment();
281 if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union,
282 tok::kw_extern, Keywords.kw_interface)) {
283 return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock
284 ? tryMergeSimpleBlock(I,
E, Limit)
288 if (Tok && Tok->is(tok::kw_template) &&
289 Style.BraceWrapping.SplitEmptyRecord && EmptyBlock) {
294 auto ShouldMergeShortFunctions = [
this, &I, &NextLine, PreviousLine,
299 NextLine.First->is(tok::r_brace)) {
303 if (Style.AllowShortFunctionsOnASingleLine &
307 if (Style.isJavaScript() && TheLine->Last->is(TT_FunctionLBrace))
310 if (TheLine->Level != 0) {
316 const AnnotatedLine *
Line =
nullptr;
317 for (
auto J = I - 1; J >= AnnotatedLines.begin(); --J) {
319 if (((*J)->InPPDirective && !(*J)->InMacroBody) ||
320 (*J)->isComment() || (*J)->Level > TheLine->Level) {
323 if ((*J)->Level < TheLine->Level ||
325 (*J)->First->is(tok::l_brace))) {
335 const auto *LastNonComment =
Line->getLastNonComment();
338 assert(LastNonComment);
339 return isRecordLBrace(*LastNonComment);
346 bool MergeShortFunctions = ShouldMergeShortFunctions();
348 const auto *FirstNonComment = TheLine->getFirstNonComment();
349 if (!FirstNonComment)
355 if (Style.AllowShortNamespacesOnASingleLine &&
356 TheLine->First->is(tok::kw_namespace)) {
357 const auto result = tryMergeNamespace(I,
E, Limit);
362 if (Style.CompactNamespaces) {
363 if (
const auto *NSToken = TheLine->First->getNamespaceToken()) {
365 assert(TheLine->MatchingClosingBlockLineIndex > 0);
366 for (
auto ClosingLineIndex = TheLine->MatchingClosingBlockLineIndex - 1;
368 ClosingLineIndex == I[J]->MatchingClosingBlockLineIndex &&
369 I[J]->
Last->TotalLength < Limit;
370 ++J, --ClosingLineIndex) {
371 Limit -= I[J]->Last->TotalLength + 1;
375 auto *ClosingLine = AnnotatedLines.begin() + ClosingLineIndex + 1;
376 const int OutdentBy = I[J]->Level - TheLine->Level;
377 assert(OutdentBy >= 0);
378 for (
auto *CompactedLine = I + J; CompactedLine <= ClosingLine;
380 if (!(*CompactedLine)->InPPDirective) {
381 const int Level = (*CompactedLine)->Level;
382 (*CompactedLine)->Level = std::max(Level - OutdentBy, 0);
389 if (
auto nsToken = getMatchingNamespaceToken(TheLine, AnnotatedLines)) {
391 unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
392 for (; I + 1 + i !=
E &&
393 nsToken->TokenText ==
394 getMatchingNamespaceTokenText(I[i + 1], AnnotatedLines) &&
395 openingLine == I[i + 1]->MatchingOpeningBlockLineIndex;
396 i++, --openingLine) {
398 I[i + 1]->First->SpacesRequiredBefore =
399 I[i]->Last->isNot(tok::r_brace);
402 IndentTracker.nextLine(*I[i + 1]);
408 const auto *LastNonComment = TheLine->getLastNonComment();
409 assert(LastNonComment);
414 if (LastNonComment->is(TT_FunctionLBrace) &&
415 TheLine->First != LastNonComment) {
416 return MergeShortFunctions ? tryMergeSimpleBlock(I,
E, Limit) : 0;
420 if (TheLine->Last->is(tok::l_brace) && FirstNonComment != TheLine->Last &&
421 (FirstNonComment->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for,
423 TheLine->startsWithExportBlock())) {
425 ? tryMergeSimpleBlock(I,
E, Limit)
429 if (NextLine.First->is(TT_ControlStatementLBrace)) {
433 return Style.BraceWrapping.AfterControlStatement ==
435 ? tryMergeSimpleBlock(I,
E, Limit)
438 if (PreviousLine && TheLine->First->is(tok::l_brace)) {
439 switch (PreviousLine->First->Tok.getKind()) {
442 if (PreviousLine->First->Next &&
443 PreviousLine->First->Next->isOneOf(tok::objc_autoreleasepool,
444 tok::objc_synchronized)) {
450 case tok::kw_default:
461 if (PreviousLine && Style.BraceWrapping.SplitEmptyRecord &&
462 TheLine->Last->is(tok::l_brace) && PreviousLine->Last) {
463 const FormatToken *
Previous = PreviousLine->Last;
468 if (
Previous->is(tok::greater) && !PreviousLine->InPPDirective)
470 if (
Previous->is(tok::identifier)) {
471 const FormatToken *PreviousPrevious =
473 if (PreviousPrevious &&
474 PreviousPrevious->isOneOf(tok::kw_class, tok::kw_struct)) {
482 if (TheLine->First->is(TT_SwitchExpressionLabel)) {
483 return Style.AllowShortCaseExpressionOnASingleLine
484 ? tryMergeShortCaseLabels(I,
E, Limit)
488 if (TheLine->Last->is(tok::l_brace)) {
489 bool ShouldMerge =
false;
491 if (TheLine->Last->is(TT_EnumLBrace)) {
492 ShouldMerge = Style.AllowShortEnumsOnASingleLine;
493 }
else if (TheLine->Last->is(TT_CompoundRequirementLBrace)) {
494 ShouldMerge = Style.AllowShortCompoundRequirementOnASingleLine;
495 }
else if (TheLine->Last->isOneOf(TT_ClassLBrace, TT_StructLBrace)) {
499 ShouldMerge = !Style.BraceWrapping.AfterClass ||
500 (NextLine.First->is(tok::r_brace) &&
501 !Style.BraceWrapping.SplitEmptyRecord);
502 }
else if (TheLine->InPPDirective ||
503 !TheLine->First->isOneOf(tok::kw_class, tok::kw_enum,
507 ShouldMerge = !Style.BraceWrapping.AfterFunction ||
508 (NextLine.First->is(tok::r_brace) &&
509 !Style.BraceWrapping.SplitEmptyFunction);
511 return ShouldMerge ? tryMergeSimpleBlock(I,
E, Limit) : 0;
515 if (NextLine.First->is(TT_FunctionLBrace) &&
516 Style.BraceWrapping.AfterFunction) {
517 if (NextLine.Last->is(TT_LineComment))
521 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
525 unsigned MergedLines = 0;
526 if (MergeShortFunctions ||
528 NextLine.First == NextLine.Last && I + 2 !=
E &&
529 I[2]->First->is(tok::r_brace))) {
530 MergedLines = tryMergeSimpleBlock(I + 1,
E, Limit);
538 auto IsElseLine = [&TheLine]() ->
bool {
539 const FormatToken *
First = TheLine->First;
540 if (
First->is(tok::kw_else))
543 return First->is(tok::r_brace) &&
First->Next &&
544 First->Next->is(tok::kw_else);
546 if (TheLine->First->is(tok::kw_if) ||
547 (IsElseLine() && (Style.AllowShortIfStatementsOnASingleLine ==
549 return Style.AllowShortIfStatementsOnASingleLine
550 ? tryMergeSimpleControlStatement(I,
E, Limit)
553 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while, tok::kw_do,
555 return Style.AllowShortLoopsOnASingleLine
556 ? tryMergeSimpleControlStatement(I,
E, Limit)
559 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
560 return Style.AllowShortCaseLabelsOnASingleLine
561 ? tryMergeShortCaseLabels(I,
E, Limit)
564 if (TheLine->InPPDirective &&
565 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
566 return tryMergeSimplePPDirective(I,
E, Limit);
572 tryMergeSimplePPDirective(ArrayRef<AnnotatedLine *>::const_iterator I,
573 ArrayRef<AnnotatedLine *>::const_iterator
E,
577 if (I + 2 !=
E && I[2]->InPPDirective && !I[2]->
First->HasUnescapedNewline)
579 if (1 + I[1]->
Last->TotalLength > Limit)
584 unsigned tryMergeNamespace(ArrayRef<AnnotatedLine *>::const_iterator I,
585 ArrayRef<AnnotatedLine *>::const_iterator
E,
592 const bool OpenBraceWrapped = Style.BraceWrapping.AfterNamespace;
593 const auto *BraceOpenLine = I + OpenBraceWrapped;
595 assert(*BraceOpenLine);
596 if (BraceOpenLine[0]->
Last->isNot(TT_NamespaceLBrace))
599 if (std::distance(BraceOpenLine,
E) <= 2)
602 if (BraceOpenLine[0]->
Last->is(tok::comment))
605 assert(BraceOpenLine[1]);
606 const auto &L1 = *BraceOpenLine[1];
607 if (L1.InPPDirective != (*I)->InPPDirective ||
608 (L1.InPPDirective && L1.First->HasUnescapedNewline)) {
612 assert(BraceOpenLine[2]);
613 const auto &L2 = *BraceOpenLine[2];
617 Limit = limitConsideringMacros(I + 1,
E, Limit);
619 const auto LinesToBeMerged = OpenBraceWrapped + 2;
620 if (!nextNLinesFitInto(I, I + LinesToBeMerged, Limit))
625 if (L1.First->is(tok::kw_namespace)) {
626 if (L1.Last->is(tok::comment) || !Style.CompactNamespaces)
629 assert(Limit >= L1.Last->TotalLength + 3);
630 const auto InnerLimit = Limit - L1.Last->TotalLength - 3;
631 const auto MergedLines =
632 tryMergeNamespace(BraceOpenLine + 1,
E, InnerLimit);
633 if (MergedLines == 0)
635 const auto N = MergedLines + LinesToBeMerged;
637 if (std::distance(I,
E) <= N)
641 if (I[N]->
First->is(TT_NamespaceRBrace) &&
642 !I[N]->First->MustBreakBefore &&
643 BraceOpenLine[MergedLines + 1]->Last->isNot(tok::comment) &&
644 nextNLinesFitInto(I, I + N + 1, Limit)) {
654 if (L1.Last->isNot(tok::semi))
658 if (L2.First->isNot(TT_NamespaceRBrace) || L2.First->MustBreakBefore)
662 return LinesToBeMerged;
666 tryMergeSimpleControlStatement(ArrayRef<AnnotatedLine *>::const_iterator I,
667 ArrayRef<AnnotatedLine *>::const_iterator
E,
671 if (Style.BraceWrapping.AfterControlStatement ==
673 I[1]->First->is(tok::l_brace) &&
677 if (I[1]->InPPDirective != (*I)->InPPDirective ||
678 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) {
681 Limit = limitConsideringMacros(I + 1,
E, Limit);
682 AnnotatedLine &
Line = **I;
683 if (
Line.First->isNot(tok::kw_do) &&
Line.First->isNot(tok::kw_else) &&
684 Line.Last->isNot(tok::kw_else) &&
Line.Last->isNot(tok::r_paren)) {
688 if (
Line.First->is(tok::kw_do) &&
Line.Last->isNot(tok::kw_do))
690 if (1 + I[1]->
Last->TotalLength > Limit)
693 if (I[1]->
First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
694 TT_ForEachMacro, TT_LineComment)) {
698 if (Style.AllowShortIfStatementsOnASingleLine ==
700 if (I + 2 !=
E &&
Line.startsWith(tok::kw_if) &&
701 I[2]->First->is(tok::kw_else)) {
708 unsigned tryMergeShortCaseLabels(ArrayRef<AnnotatedLine *>::const_iterator I,
709 ArrayRef<AnnotatedLine *>::const_iterator
E,
711 if (Limit == 0 || I + 1 ==
E ||
712 I[1]->
First->isOneOf(tok::kw_case, tok::kw_default)) {
715 if (I[0]->
Last->is(tok::l_brace) || I[1]->First->is(tok::l_brace))
717 unsigned NumStmts = 0;
719 bool EndsWithComment =
false;
720 bool InPPDirective = I[0]->InPPDirective;
721 bool InMacroBody = I[0]->InMacroBody;
722 const unsigned Level = I[0]->Level;
723 for (; NumStmts < 3; ++NumStmts) {
724 if (I + 1 + NumStmts ==
E)
726 const AnnotatedLine *
Line = I[1 + NumStmts];
727 if (
Line->InPPDirective != InPPDirective)
729 if (
Line->InMacroBody != InMacroBody)
731 if (
Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
733 if (
Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
738 if (
Line->First->is(tok::comment)) {
739 if (Level !=
Line->Level)
741 const auto *J = I + 2 + NumStmts;
742 for (; J !=
E; ++J) {
744 if (
Line->InPPDirective != InPPDirective)
746 if (
Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
748 if (
Line->First->isNot(tok::comment) || Level !=
Line->Level)
753 if (
Line->Last->is(tok::comment))
754 EndsWithComment =
true;
755 Length += I[1 + NumStmts]->Last->TotalLength + 1;
757 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
762 unsigned tryMergeSimpleBlock(ArrayRef<AnnotatedLine *>::const_iterator I,
763 ArrayRef<AnnotatedLine *>::const_iterator
E,
769 AnnotatedLine &
Line = **I;
774 if (!Style.isJava() &&
Line.First->isOneOf(tok::at, tok::minus, tok::plus))
779 if (
Line.First->is(tok::kw_case) ||
780 (
Line.First->Next &&
Line.First->Next->is(tok::kw_else))) {
784 if (
Line.First->is(tok::kw_default)) {
785 const FormatToken *Tok =
Line.First->getNextNonComment();
786 if (Tok && Tok->is(tok::colon))
790 auto IsCtrlStmt = [](
const auto &
Line) {
791 return Line.First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
792 tok::kw_do, tok::kw_for, TT_ForEachMacro);
795 const bool IsSplitBlock =
798 I[1]->First->isNot(tok::r_brace));
800 if (IsCtrlStmt(
Line) ||
801 Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
802 tok::kw___finally, tok::r_brace,
803 Keywords.kw___except) ||
804 Line.startsWithExportBlock()) {
809 if (!Style.AllowShortIfStatementsOnASingleLine &&
810 Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
811 !Style.BraceWrapping.AfterControlStatement &&
812 I[1]->First->isNot(tok::r_brace)) {
815 if (!Style.AllowShortIfStatementsOnASingleLine &&
816 Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
817 Style.BraceWrapping.AfterControlStatement ==
819 I + 2 !=
E && I[2]->First->isNot(tok::r_brace)) {
822 if (!Style.AllowShortLoopsOnASingleLine &&
823 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
825 !Style.BraceWrapping.AfterControlStatement &&
826 I[1]->First->isNot(tok::r_brace)) {
829 if (!Style.AllowShortLoopsOnASingleLine &&
830 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
832 Style.BraceWrapping.AfterControlStatement ==
834 I + 2 !=
E && I[2]->First->isNot(tok::r_brace)) {
842 if (
Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
843 Keywords.kw___except, tok::kw___finally)) {
848 if (
Line.endsWith(tok::l_brace)) {
850 Line.First->is(TT_BlockLBrace)) {
854 if (IsSplitBlock &&
Line.First ==
Line.Last &&
855 I > AnnotatedLines.begin() &&
856 (I[-1]->endsWith(tok::kw_else) || IsCtrlStmt(*I[-1]))) {
859 FormatToken *Tok = I[1]->First;
860 auto ShouldMerge = [Tok]() {
861 if (Tok->isNot(tok::r_brace) || Tok->MustBreakBefore)
863 const FormatToken *Next = Tok->getNextNonComment();
864 return !Next || Next->is(tok::semi);
869 Tok->SpacesRequiredBefore =
871 Line.Last->is(tok::comment);
872 Tok->CanBreakBefore =
true;
874 }
else if (Limit != 0 && !
Line.startsWithNamespace() &&
875 !startsExternCBlock(
Line)) {
877 if (isRecordLBrace(*
Line.Last))
883 Limit = limitConsideringMacros(I + 2,
E, Limit);
885 if (!nextTwoLinesFitInto(I, Limit))
890 if (I[1]->
Last->is(TT_LineComment))
900 if (Tok->isNot(tok::r_brace))
904 if (Tok->Next && Tok->Next->is(tok::kw_else))
914 Line.First->is(TT_ControlStatementLBrace) &&
915 Style.BraceWrapping.AfterControlStatement ==
922 }
else if (I[1]->
First->is(tok::l_brace)) {
923 if (I[1]->
Last->is(TT_LineComment))
927 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
930 unsigned MergedLines = 0;
932 (I[1]->First == I[1]->Last && I + 2 !=
E &&
933 I[2]->First->is(tok::r_brace))) {
934 MergedLines = tryMergeSimpleBlock(I + 1,
E, Limit);
947 unsigned limitConsideringMacros(ArrayRef<AnnotatedLine *>::const_iterator I,
948 ArrayRef<AnnotatedLine *>::const_iterator
E,
950 if (I[0]->InPPDirective && I + 1 !=
E &&
951 !I[1]->
First->HasUnescapedNewline && I[1]->First->isNot(tok::eof)) {
952 return Limit < 2 ? 0 : Limit - 2;
957 bool nextTwoLinesFitInto(ArrayRef<AnnotatedLine *>::const_iterator I,
959 if (I[1]->
First->MustBreakBefore || I[2]->First->MustBreakBefore)
961 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
964 bool nextNLinesFitInto(ArrayRef<AnnotatedLine *>::const_iterator I,
965 ArrayRef<AnnotatedLine *>::const_iterator
E,
967 unsigned JoinedLength = 0;
968 for (
const auto *J = I + 1; J !=
E; ++J) {
969 if ((*J)->First->MustBreakBefore)
972 JoinedLength += 1 + (*J)->Last->TotalLength;
973 if (JoinedLength > Limit)
979 bool containsMustBreak(
const AnnotatedLine *
Line) {
983 for (
const FormatToken *Tok =
Line->First->Next; Tok; Tok = Tok->Next)
984 if (Tok->MustBreakBefore)
989 void join(AnnotatedLine &A,
const AnnotatedLine &B) {
990 assert(!A.Last->Next);
991 assert(!B.First->Previous);
992 if (B.Affected || B.LeadingEmptyLinesAffected) {
993 assert(B.Affected || A.Last->Children.empty());
996 A.Last->Next = B.First;
997 B.First->Previous = A.Last;
998 B.First->CanBreakBefore =
true;
999 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1000 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1001 Tok->TotalLength += LengthA;
1006 const FormatStyle &Style;
1007 const AdditionalKeywords &Keywords;
1008 const ArrayRef<AnnotatedLine *>::const_iterator End;
1010 ArrayRef<AnnotatedLine *>::const_iterator Next;
1011 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
1014static void markFinalized(FormatToken *Tok) {
1015 if (Tok->is(tok::hash) && !Tok->Previous && Tok->Next &&
1016 Tok->Next->isOneOf(tok::pp_if, tok::pp_ifdef, tok::pp_ifndef,
1017 tok::pp_elif, tok::pp_elifdef, tok::pp_elifndef,
1018 tok::pp_else, tok::pp_endif)) {
1021 for (; Tok; Tok = Tok->Next) {
1034 Tok->SpacesRequiredBefore = 0;
1035 if (!Tok->MustBreakBeforeFinalized)
1036 Tok->MustBreakBefore = 0;
1038 Tok->Finalized =
true;
1044static void printLineState(
const LineState &State) {
1045 llvm::dbgs() <<
"State: ";
1046 for (
const ParenState &
P : State.Stack) {
1047 llvm::dbgs() << (
P.Tok ?
P.Tok->TokenText :
"F") <<
"|" <<
P.Indent <<
"|"
1048 <<
P.LastSpace <<
"|" <<
P.NestedBlockIndent <<
" ";
1050 llvm::dbgs() << State.NextToken->TokenText <<
"\n";
1055class LineFormatter {
1057 LineFormatter(ContinuationIndenter *
Indenter, WhitespaceManager *Whitespaces,
1058 const FormatStyle &Style,
1059 UnwrappedLineFormatter *BlockFormatter)
1061 BlockFormatter(BlockFormatter) {}
1062 virtual ~LineFormatter() {}
1067 virtual unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1068 unsigned FirstStartColumn,
bool DryRun) = 0;
1091 bool formatChildren(LineState &State,
bool NewLine,
bool DryRun,
1092 unsigned &Penalty) {
1093 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1094 bool HasLBrace = LBrace && LBrace->is(tok::l_brace) && LBrace->is(
BK_Block);
1095 FormatToken &
Previous = *State.NextToken->Previous;
1096 if (
Previous.Children.empty() || (!HasLBrace && !LBrace->MacroParent)) {
1103 const ParenState &
P = State.Stack.back();
1105 int AdditionalIndent =
1106 P.Indent -
Previous.Children[0]->Level * Style.IndentWidth;
1108 BlockFormatter->format(
Previous.Children, DryRun, AdditionalIndent,
1113 if (
Previous.Children[0]->First->MustBreakBefore)
1124 const AnnotatedLine *Child =
Previous.Children[0];
1126 if (Child->Last->isTrailingComment())
1131 if (Style.ColumnLimit > 0 &&
1132 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit) {
1137 Whitespaces->replaceWhitespace(
1138 *Child->First, 0, 1,
1139 State.Column,
false,
1140 State.Line->InPPDirective);
1143 formatLine(*Child, State.Column + 1, 0, DryRun);
1145 markFinalized(Child->First);
1147 State.Column += 1 + Child->Last->TotalLength;
1154 WhitespaceManager *Whitespaces;
1155 const FormatStyle &Style;
1156 UnwrappedLineFormatter *BlockFormatter;
1160class NoColumnLimitLineFormatter :
public LineFormatter {
1162 NoColumnLimitLineFormatter(ContinuationIndenter *
Indenter,
1163 WhitespaceManager *Whitespaces,
1164 const FormatStyle &Style,
1165 UnwrappedLineFormatter *BlockFormatter)
1166 : LineFormatter(
Indenter, Whitespaces, Style, BlockFormatter) {}
1170 unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1171 unsigned FirstStartColumn,
bool DryRun)
override {
1173 LineState State =
Indenter->getInitialState(FirstIndent, FirstStartColumn,
1175 while (State.NextToken) {
1178 (
Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
1179 unsigned Penalty = 0;
1180 formatChildren(State, Newline,
false, Penalty);
1181 Indenter->addTokenToState(State, Newline,
false);
1188class NoLineBreakFormatter :
public LineFormatter {
1190 NoLineBreakFormatter(ContinuationIndenter *
Indenter,
1191 WhitespaceManager *Whitespaces,
const FormatStyle &Style,
1192 UnwrappedLineFormatter *BlockFormatter)
1193 : LineFormatter(
Indenter, Whitespaces, Style, BlockFormatter) {}
1196 unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1197 unsigned FirstStartColumn,
bool DryRun)
override {
1198 unsigned Penalty = 0;
1200 Indenter->getInitialState(FirstIndent, FirstStartColumn, &
Line, DryRun);
1201 while (State.NextToken) {
1202 formatChildren(State,
false, DryRun, Penalty);
1204 State, State.NextToken->MustBreakBefore, DryRun);
1211class OptimizingLineFormatter :
public LineFormatter {
1213 OptimizingLineFormatter(ContinuationIndenter *
Indenter,
1214 WhitespaceManager *Whitespaces,
1215 const FormatStyle &Style,
1216 UnwrappedLineFormatter *BlockFormatter)
1217 : LineFormatter(
Indenter, Whitespaces, Style, BlockFormatter) {}
1221 unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1222 unsigned FirstStartColumn,
bool DryRun)
override {
1224 Indenter->getInitialState(FirstIndent, FirstStartColumn, &
Line, DryRun);
1229 State.Stack.back().BreakBeforeParameter =
true;
1232 return analyzeSolutionSpace(State, DryRun);
1236 struct CompareLineStatePointers {
1237 bool operator()(LineState *obj1, LineState *obj2)
const {
1238 return *obj1 < *obj2;
1247 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1252 StateNode(
const LineState &State,
bool NewLine, StateNode *Previous)
1261 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1264 typedef std::priority_queue<QueueItem, SmallVector<QueueItem>,
1265 std::greater<QueueItem>>
1276 unsigned analyzeSolutionSpace(LineState &InitialState,
bool DryRun) {
1277 std::set<LineState *, CompareLineStatePointers> Seen;
1285 StateNode *RootNode =
1286 new (Allocator.Allocate()) StateNode(InitialState,
false,
nullptr);
1287 Queue.push(QueueItem(OrderedPenalty(0, Count), RootNode));
1290 unsigned Penalty = 0;
1293 while (!Queue.empty()) {
1295 if (Count > 25'000'000)
1298 Penalty = Queue.top().first.first;
1299 StateNode *
Node = Queue.top().second;
1300 if (!
Node->State.NextToken) {
1301 LLVM_DEBUG(llvm::dbgs()
1302 <<
"\n---\nPenalty for line: " << Penalty <<
"\n");
1310 Node->State.IgnoreStackForComparison =
true;
1312 if (!Seen.insert(&
Node->State).second) {
1319 addNextStateToQueue(Penalty,
Node,
false, &Count, &Queue);
1321 addNextStateToQueue(Penalty,
Node,
true, &Count, &Queue);
1324 if (Queue.empty()) {
1327 LLVM_DEBUG(llvm::dbgs() <<
"Could not find a solution.\n");
1333 reconstructPath(InitialState, Queue.top().second);
1335 LLVM_DEBUG(llvm::dbgs()
1336 <<
"Total number of analyzed states: " << Count <<
"\n");
1337 LLVM_DEBUG(llvm::dbgs() <<
"---\n");
1346 void addNextStateToQueue(
unsigned Penalty, StateNode *PreviousNode,
1347 bool NewLine,
unsigned *Count, QueueType *Queue) {
1353 StateNode *
Node =
new (Allocator.Allocate())
1354 StateNode(PreviousNode->State,
NewLine, PreviousNode);
1355 if (!formatChildren(
Node->State,
NewLine,
true, Penalty))
1360 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count),
Node));
1366 void reconstructPath(LineState &State, StateNode *Best) {
1369 while (Best->Previous) {
1370 Path.push_back(Best);
1371 Best = Best->Previous;
1373 for (
const auto &
Node : llvm::reverse(
Path)) {
1374 unsigned Penalty = 0;
1375 formatChildren(State,
Node->NewLine,
false, Penalty);
1376 Penalty +=
Indenter->addTokenToState(State,
Node->NewLine,
false);
1379 printLineState(
Node->Previous->State);
1380 if (
Node->NewLine) {
1381 llvm::dbgs() <<
"Penalty for placing "
1382 <<
Node->Previous->State.NextToken->Tok.getName()
1383 <<
" on a new line: " << Penalty <<
"\n";
1389 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1396 int AdditionalIndent,
bool FixBadIndentation,
unsigned FirstStartColumn,
1397 unsigned NextStartColumn,
unsigned LastStartColumn) {
1398 LineJoiner Joiner(Style, Keywords, Lines);
1401 std::pair<const SmallVectorImpl<AnnotatedLine *> *,
unsigned> CacheKey(
1402 &Lines, AdditionalIndent);
1403 auto CacheIt = PenaltyCache.find(CacheKey);
1404 if (DryRun && CacheIt != PenaltyCache.end())
1405 return CacheIt->second;
1407 assert(!Lines.empty());
1408 unsigned Penalty = 0;
1409 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
1418 bool FirstLine =
true;
1420 Joiner.getNextMergedLine(DryRun, IndentTracker);
1421 Line; PrevPrevLine = PreviousLine, PreviousLine =
Line,
Line = NextLine,
1422 FirstLine =
false) {
1423 assert(
Line->First);
1425 unsigned Indent = IndentTracker.getIndent();
1431 bool PreviousRBrace =
1432 PreviousLine && PreviousLine->
startsWith(tok::r_brace);
1433 bool ContinueFormatting =
1434 TheLine.
Level > RangeMinLevel ||
1435 (TheLine.
Level == RangeMinLevel && !PreviousRBrace &&
1438 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
1440 bool ShouldFormat = TheLine.
Affected || FixIndentation;
1451 bool LastLine = TheLine.
First->
is(tok::eof);
1452 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines, Indent,
1453 LastLine ? LastStartColumn : NextStartColumn + Indent);
1456 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1457 unsigned ColumnLimit = getColumnLimit(TheLine.
InPPDirective, NextLine);
1458 bool FitsIntoOneLine =
1462 (!Style.isJavaScript() || !Style.JavaScriptWrapImports)) ||
1463 (Style.isCSharp() &&
1465 if (Style.ColumnLimit == 0) {
1466 NoColumnLimitLineFormatter(
Indenter, Whitespaces, Style,
this)
1467 .formatLine(TheLine, NextStartColumn + Indent,
1468 FirstLine ? FirstStartColumn : 0, DryRun);
1469 }
else if (FitsIntoOneLine) {
1470 Penalty += NoLineBreakFormatter(
Indenter, Whitespaces, Style,
this)
1471 .formatLine(TheLine, NextStartColumn + Indent,
1472 FirstLine ? FirstStartColumn : 0, DryRun);
1474 Penalty += OptimizingLineFormatter(
Indenter, Whitespaces, Style,
this)
1475 .formatLine(TheLine, NextStartColumn + Indent,
1476 FirstLine ? FirstStartColumn : 0, DryRun);
1478 RangeMinLevel = std::min(RangeMinLevel, TheLine.
Level);
1484 if (!Tok->Children.empty())
1485 format(Tok->Children, DryRun);
1490 bool StartsNewLine =
1493 IndentTracker.adjustToUnmodifiedLine(TheLine);
1495 bool ReformatLeadingWhitespace =
1496 StartsNewLine && ((PreviousLine && PreviousLine->
Affected) ||
1499 if (ReformatLeadingWhitespace) {
1500 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines,
1504 Whitespaces->addUntouchableToken(*TheLine.
First,
1510 Whitespaces->addUntouchableToken(*Tok, TheLine.
InPPDirective);
1512 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1516 markFinalized(TheLine.
First);
1518 PenaltyCache[CacheKey] = Penalty;
1527 const auto &RootToken = *
Line.First;
1531 if (RootToken.is(tok::r_brace) &&
1533 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)) &&
1536 Newlines = std::min(Newlines, 1u);
1539 if (!PreviousLine &&
Line.Level > 0)
1540 Newlines = std::min(Newlines, 1u);
1541 if (Newlines == 0 && !RootToken.IsFirst)
1543 if (RootToken.IsFirst &&
1550 PreviousLine->
Last->
is(tok::l_brace) &&
1554 !startsExternCBlock(*PreviousLine)) {
1560 if (PreviousLine && PreviousLine->
endsWith(TT_NamespaceLBrace)) {
1563 else if (!
Line.startsWithNamespace())
1564 Newlines = std::max(Newlines, 2u);
1567 if (
Line.startsWith(TT_NamespaceRBrace)) {
1570 else if (!PreviousLine->
startsWith(TT_NamespaceRBrace))
1571 Newlines = std::max(Newlines, 2u);
1576 if (PreviousLine && RootToken.isAccessSpecifier()) {
1583 Newlines = std::max(RootToken.NewlinesBefore, 1u);
1586 if (PreviousLine->
Last->
isOneOf(tok::semi, tok::r_brace) && Newlines <= 1)
1593 if (PreviousLine->
Last->
is(tok::comment))
1596 previousToken = PreviousLine->
Last;
1597 if ((!previousToken || previousToken->
isNot(tok::l_brace)) &&
1607 (!PreviousLine->
InPPDirective || !RootToken.HasUnescapedNewline)) {
1610 if (!RootToken.isAccessSpecifier()) {
1616 Newlines = std::max(Newlines, 1u);
1619 if (RootToken.is(tok::r_brace))
1622 Newlines = std::max(Newlines, 2u);
1631void UnwrappedLineFormatter::formatFirstToken(
1632 const AnnotatedLine &
Line,
const AnnotatedLine *PreviousLine,
1633 const AnnotatedLine *PrevPrevLine,
1635 unsigned NewlineIndent) {
1636 FormatToken &RootToken = *
Line.First;
1637 if (RootToken.is(tok::eof)) {
1638 unsigned Newlines = std::min(
1639 RootToken.NewlinesBefore,
1640 Style.KeepEmptyLines.AtEndOfFile ? Style.MaxEmptyLinesToKeep + 1 : 1);
1641 unsigned TokenIndent = Newlines ? NewlineIndent : 0;
1642 Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
1647 if (RootToken.Newlines < 0) {
1648 RootToken.Newlines =
1650 assert(RootToken.Newlines >= 0);
1653 if (RootToken.Newlines > 0)
1654 Indent = NewlineIndent;
1658 if (!Style.isJavaScript() &&
1665 Whitespaces->replaceWhitespace(RootToken, RootToken.Newlines, Indent, Indent,
1667 Line.InPPDirective &&
1668 !RootToken.HasUnescapedNewline);
1672UnwrappedLineFormatter::getColumnLimit(
bool InPPDirective,
1673 const AnnotatedLine *NextLine)
const {
1676 bool ContinuesPPDirective =
1681 (NextLine->InPPDirective &&
1684 !NextLine->First->HasUnescapedNewline));
1685 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.
The JSON file list parser is used to communicate input to InstallAPI.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))