13#include "llvm/Support/Debug.h"
16#define DEBUG_TYPE "format-formatter"
23bool startsExternCBlock(
const AnnotatedLine &
Line) {
26 return Line.startsWith(tok::kw_extern) &&
Next &&
Next->isStringLiteral() &&
27 NextNext && NextNext->is(tok::l_brace);
31 return Tok.isOneOf(TT_ClassLBrace, TT_EnumLBrace, TT_RecordLBrace,
32 TT_StructLBrace, TT_UnionLBrace);
44class LevelIndentTracker {
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);
67 Indent =
Line.InMacroBody
68 ? (
Line.Level -
Line.PPLevel) * Style.IndentWidth +
70 :
Line.First->OriginalColumn;
72 (
Line.InPPDirective ||
75 unsigned PPIndentWidth =
76 (Style.PPIndentWidth >= 0) ? Style.PPIndentWidth : Style.IndentWidth;
77 Indent =
Line.InMacroBody
78 ?
Line.PPLevel * PPIndentWidth +
79 (
Line.Level -
Line.PPLevel) * Style.IndentWidth
80 :
Line.Level * PPIndentWidth;
81 Indent += AdditionalIndent;
86 if (!
Line.InPPDirective) {
87 assert(
Line.Level <= IndentForLevel.size());
88 IndentForLevel.resize(
Line.Level + 1);
90 Indent = getIndent(
Line.Level);
92 if (
static_cast<int>(Indent) + Offset >= 0)
94 if (
Line.IsContinuation)
95 Indent =
Line.Level * Style.IndentWidth + Style.ContinuationIndentWidth;
103 void adjustToUnmodifiedLine(
const AnnotatedLine &
Line) {
104 if (
Line.InPPDirective ||
Line.IsContinuation)
106 assert(
Line.Level < IndentForLevel.size());
107 if (
Line.First->is(tok::comment) && IndentForLevel[
Line.Level] != -1)
109 unsigned LevelIndent =
Line.First->OriginalColumn;
110 if (
static_cast<int>(LevelIndent) - Offset >= 0)
111 LevelIndent -= Offset;
112 IndentForLevel[
Line.Level] = LevelIndent;
120 int getIndentOffset(
const AnnotatedLine &
Line) {
121 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp())
124 const auto &RootToken = *
Line.First;
127 RootToken.Next && RootToken.Next->is(TT_GotoLabelColon)) {
128 return -
static_cast<int>(Style.IndentWidth / 2);
132 RootToken.isAccessSpecifier(
false) ||
133 RootToken.isObjCAccessSpecifier() ||
134 (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
135 RootToken.Next && RootToken.Next->is(tok::colon))) {
139 return Style.IndentAccessModifiers ? -Style.IndentWidth
140 : Style.AccessModifierOffset;
150 unsigned getIndent(
unsigned Level)
const {
151 assert(Level < IndentForLevel.size());
152 if (IndentForLevel[Level] != -1)
153 return IndentForLevel[Level];
156 return getIndent(Level - 1) + Style.IndentWidth;
160 const AdditionalKeywords &Keywords;
161 const unsigned AdditionalIndent;
180getMatchingNamespaceToken(
const AnnotatedLine *
Line,
182 if (!
Line->startsWith(tok::r_brace))
184 size_t StartLineIndex =
Line->MatchingOpeningBlockLineIndex;
187 assert(StartLineIndex < AnnotatedLines.size());
188 return AnnotatedLines[StartLineIndex]->First->getNamespaceToken();
193 return NamespaceToken ? NamespaceToken->TokenText : StringRef();
197getMatchingNamespaceTokenText(
const AnnotatedLine *
Line,
200 getMatchingNamespaceToken(
Line, AnnotatedLines);
201 return NamespaceToken ? NamespaceToken->TokenText : StringRef();
206 LineJoiner(
const FormatStyle &Style,
const AdditionalKeywords &Keywords,
207 const SmallVectorImpl<AnnotatedLine *> &Lines)
208 : Style(Style), Keywords(Keywords), End(Lines.end()),
Next(Lines.begin()),
209 AnnotatedLines(Lines) {}
212 const AnnotatedLine *getNextMergedLine(
bool DryRun,
213 LevelIndentTracker &IndentTracker) {
216 const AnnotatedLine *Current = *
Next;
217 IndentTracker.nextLine(*Current);
218 unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker,
Next, End);
219 if (MergedLines > 0 && Style.ColumnLimit == 0) {
222 for (
unsigned i = 0; i < MergedLines; ++i)
223 if (
Next[i + 1]->
First->NewlinesBefore > 0)
227 for (
unsigned i = 0; i < MergedLines; ++i)
236 tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker,
243 const AnnotatedLine *TheLine = *I;
244 if (TheLine->Last->is(TT_LineComment))
246 const auto &NextLine = *I[1];
247 if (NextLine.Type ==
LT_Invalid || NextLine.First->MustBreakBefore)
249 if (TheLine->InPPDirective &&
250 (!NextLine.InPPDirective || NextLine.First->HasUnescapedNewline)) {
254 const auto Indent = IndentTracker.getIndent();
255 if (Style.ColumnLimit > 0 &&
Indent > Style.ColumnLimit)
262 Limit = TheLine->Last->TotalLength > Limit
264 : Limit - TheLine->Last->TotalLength;
266 if (TheLine->Last->is(TT_FunctionLBrace) &&
267 TheLine->First == TheLine->Last) {
268 const bool EmptyFunctionBody = NextLine.First->is(tok::r_brace);
269 if ((EmptyFunctionBody && !Style.BraceWrapping.SplitEmptyFunction) ||
270 (!EmptyFunctionBody &&
272 return tryMergeSimpleBlock(I, E, Limit);
278 if (NextLine.First->isOneOf(TT_ClassLBrace, TT_StructLBrace,
280 if (
unsigned MergedLines = tryMergeRecord(I, E, Limit))
284 const auto *PreviousLine = I != AnnotatedLines.begin() ? I[-1] :
nullptr;
287 if (PreviousLine && TheLine->Last->is(tok::l_brace) &&
288 TheLine->First == TheLine->Last) {
289 const bool EmptyBlock = NextLine.First->is(tok::r_brace);
293 if (
Tok &&
Tok->getNamespaceToken()) {
294 return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock
295 ? tryMergeSimpleBlock(I, E, Limit)
299 if (
Tok &&
Tok->is(tok::kw_typedef))
300 Tok =
Tok->getNextNonComment();
302 if (
Tok &&
Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union))
303 return tryMergeRecord(I, E, Limit);
305 if (
Tok &&
Tok->isOneOf(tok::kw_extern, Keywords.kw_interface)) {
306 return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock
307 ? tryMergeSimpleBlock(I, E, Limit)
311 if (
Tok &&
Tok->is(tok::kw_template) &&
312 Style.BraceWrapping.SplitEmptyRecord && EmptyBlock) {
317 auto ShouldMergeShortFunctions = [&] {
318 if (Style.AllowShortFunctionsOnASingleLine.isAll())
321 if (Style.AllowShortFunctionsOnASingleLine.Empty &&
322 NextLine.First->is(tok::r_brace)) {
326 if (Style.AllowShortFunctionsOnASingleLine.Inline &&
327 !Style.AllowShortFunctionsOnASingleLine.Other) {
328 if (Style.isJavaScript() && TheLine->Last->is(TT_FunctionLBrace))
333 if (
const auto Level = TheLine->Level; Level > 0) {
339 const AnnotatedLine *
Line =
nullptr;
340 for (
auto J = I - 1; J >= AnnotatedLines.begin(); --J) {
343 if (TheLine->InMacroBody && !L->InMacroBody)
345 if (L->isComment() || (!TheLine->InPPDirective && L->InPPDirective))
347 if (L->Level < Level ||
348 (L->Level == Level && L->First->is(tok::l_brace) &&
359 const auto *LastNonComment =
Line->getLastNonComment();
362 assert(LastNonComment);
363 return isRecordLBrace(*LastNonComment);
370 bool MergeShortFunctions = ShouldMergeShortFunctions();
372 const auto *FirstNonComment = TheLine->getFirstNonComment();
373 if (!FirstNonComment)
379 if (Style.AllowShortNamespacesOnASingleLine &&
380 TheLine->First->is(tok::kw_namespace)) {
381 const auto result = tryMergeNamespace(I, E, Limit);
386 if (Style.CompactNamespaces) {
387 if (
const auto *NSToken = TheLine->First->getNamespaceToken()) {
389 assert(TheLine->MatchingClosingBlockLineIndex > 0);
390 for (
auto ClosingLineIndex = TheLine->MatchingClosingBlockLineIndex - 1;
392 ClosingLineIndex == I[J]->MatchingClosingBlockLineIndex &&
393 I[J]->
Last->TotalLength < Limit;
394 ++J, --ClosingLineIndex) {
395 Limit -= I[J]->Last->TotalLength + 1;
399 auto *ClosingLine = AnnotatedLines.begin() + ClosingLineIndex + 1;
400 const int OutdentBy = I[J]->Level - TheLine->Level;
401 assert(OutdentBy >= 0);
402 for (
auto *CompactedLine = I + J; CompactedLine <= ClosingLine;
404 if (!(*CompactedLine)->InPPDirective) {
405 const int Level = (*CompactedLine)->Level;
406 (*CompactedLine)->Level = std::max(Level - OutdentBy, 0);
413 if (
auto nsToken = getMatchingNamespaceToken(TheLine, AnnotatedLines)) {
415 unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
416 for (; I + 1 + i != E &&
417 nsToken->TokenText ==
418 getMatchingNamespaceTokenText(I[i + 1], AnnotatedLines) &&
419 openingLine == I[i + 1]->MatchingOpeningBlockLineIndex;
420 i++, --openingLine) {
422 I[i + 1]->First->SpacesRequiredBefore =
423 I[i]->Last->isNot(tok::r_brace);
426 IndentTracker.nextLine(*I[i + 1]);
432 const auto *LastNonComment = TheLine->getLastNonComment();
433 assert(LastNonComment);
438 if (LastNonComment->is(TT_FunctionLBrace) &&
439 TheLine->First != LastNonComment) {
440 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
444 if (TheLine->Last->is(tok::l_brace) && FirstNonComment != TheLine->Last &&
445 (FirstNonComment->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for,
447 TheLine->startsWithExportBlock())) {
449 ? tryMergeSimpleBlock(I, E, Limit)
453 if (NextLine.First->is(TT_ControlStatementLBrace)) {
457 return Style.BraceWrapping.AfterControlStatement ==
459 ? tryMergeSimpleBlock(I, E, Limit)
462 if (PreviousLine && TheLine->First->is(tok::l_brace)) {
463 switch (PreviousLine->First->Tok.getKind()) {
466 if (PreviousLine->First->Next &&
467 PreviousLine->First->Next->isOneOf(tok::objc_autoreleasepool,
468 tok::objc_synchronized)) {
474 case tok::kw_default:
485 if (PreviousLine && Style.BraceWrapping.SplitEmptyRecord &&
486 TheLine->Last->is(tok::l_brace) && PreviousLine->Last) {
492 if (
Previous->is(tok::greater) && !PreviousLine->InPPDirective)
494 if (
Previous->is(tok::identifier)) {
497 if (PreviousPrevious &&
498 PreviousPrevious->isOneOf(tok::kw_class, tok::kw_struct,
507 if (TheLine->First->is(TT_SwitchExpressionLabel)) {
508 return Style.AllowShortCaseExpressionOnASingleLine
509 ? tryMergeShortCaseLabels(I, E, Limit)
513 if (TheLine->Last->is(tok::l_brace)) {
514 bool ShouldMerge =
false;
516 if (TheLine->Last->is(TT_EnumLBrace)) {
517 ShouldMerge = Style.AllowShortEnumsOnASingleLine;
518 }
else if (TheLine->Last->is(TT_CompoundRequirementLBrace)) {
519 ShouldMerge = Style.AllowShortCompoundRequirementOnASingleLine;
520 }
else if (TheLine->Last->isOneOf(TT_ClassLBrace, TT_StructLBrace,
522 (TheLine->Last->is(TT_RecordLBrace) && Style.isJava())) {
523 return tryMergeRecord(I, E, Limit);
524 }
else if (TheLine->InPPDirective ||
525 TheLine->First->isNoneOf(tok::kw_class, tok::kw_enum,
526 tok::kw_struct, tok::kw_union)) {
529 ShouldMerge = !Style.BraceWrapping.AfterFunction ||
530 (NextLine.First->is(tok::r_brace) &&
531 !Style.BraceWrapping.SplitEmptyFunction);
533 return ShouldMerge ? tryMergeSimpleBlock(I, E, Limit) : 0;
537 if (NextLine.First->is(TT_FunctionLBrace) &&
538 Style.BraceWrapping.AfterFunction) {
539 if (NextLine.Last->is(TT_LineComment))
543 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
547 unsigned MergedLines = 0;
548 if (MergeShortFunctions ||
549 (Style.AllowShortFunctionsOnASingleLine.Empty &&
550 NextLine.First == NextLine.Last && I + 2 != E &&
551 I[2]->First->is(tok::r_brace))) {
552 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
560 auto IsElseLine = [&TheLine]() ->
bool {
562 if (
First->is(tok::kw_else))
565 return First->is(tok::r_brace) &&
First->Next &&
566 First->Next->is(tok::kw_else);
568 if (TheLine->First->is(tok::kw_if) ||
569 (IsElseLine() && (Style.AllowShortIfStatementsOnASingleLine ==
571 return Style.AllowShortIfStatementsOnASingleLine
572 ? tryMergeSimpleControlStatement(I, E, Limit)
575 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while, tok::kw_do,
577 return Style.AllowShortLoopsOnASingleLine
578 ? tryMergeSimpleControlStatement(I, E, Limit)
581 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
582 return Style.AllowShortCaseLabelsOnASingleLine
583 ? tryMergeShortCaseLabels(I, E, Limit)
586 if (TheLine->InPPDirective &&
587 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
588 return tryMergeSimplePPDirective(I, E, Limit);
596 const auto *
Line = I[0];
597 const auto *NextLine = I[1];
600 if (
Line->Last->isOneOf(TT_ClassLBrace, TT_StructLBrace, TT_UnionLBrace)) {
601 auto ShouldWrapLBrace = [&](TokenType LBraceType) {
602 switch (LBraceType) {
604 return Style.BraceWrapping.AfterClass;
605 case TT_StructLBrace:
606 return Style.BraceWrapping.AfterStruct;
608 return Style.BraceWrapping.AfterUnion;
614 auto TryMergeShortRecord = [&] {
615 switch (Style.AllowShortRecordOnASingleLine) {
621 return NextLine->First->is(tok::r_brace);
626 (!ShouldWrapLBrace(
Line->Last->getType()) ||
627 (!Style.BraceWrapping.SplitEmptyRecord && TryMergeShortRecord()))) {
628 return tryMergeSimpleBlock(I, E, Limit);
634 if (NextLine->First->isOneOf(TT_ClassLBrace, TT_StructLBrace,
636 if (I + 2 == E || I[2]->
First->is(tok::r_brace) ||
641 return tryMergeSimpleBlock(I, E, Limit);
645 if (I != AnnotatedLines.begin() &&
646 I[-1]->First->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union)) {
647 const bool IsEmptyBlock =
648 Line->Last->is(tok::l_brace) && NextLine->First->is(tok::r_brace);
650 if ((IsEmptyBlock && !Style.BraceWrapping.SplitEmptyRecord) ||
653 return tryMergeSimpleBlock(I, E, Limit);
666 if (I + 2 != E && I[2]->InPPDirective && !I[2]->
First->HasUnescapedNewline)
668 if (1 + I[1]->
Last->TotalLength > Limit)
681 const bool OpenBraceWrapped = Style.BraceWrapping.AfterNamespace;
682 const auto *BraceOpenLine = I + OpenBraceWrapped;
684 assert(*BraceOpenLine);
685 if (BraceOpenLine[0]->
Last->isNot(TT_NamespaceLBrace))
688 if (std::distance(BraceOpenLine, E) <= 2)
691 if (BraceOpenLine[0]->
Last->is(tok::comment))
694 assert(BraceOpenLine[1]);
695 const auto &L1 = *BraceOpenLine[1];
696 if (L1.InPPDirective != (*I)->InPPDirective ||
697 (L1.InPPDirective && L1.First->HasUnescapedNewline)) {
701 assert(BraceOpenLine[2]);
702 const auto &L2 = *BraceOpenLine[2];
706 Limit = limitConsideringMacros(I + 1, E, Limit);
708 const auto LinesToBeMerged = OpenBraceWrapped + 2;
712 if (L1.First->is(tok::kw_namespace)) {
713 if (L1.Last->is(tok::comment) || !Style.CompactNamespaces)
717 const auto InnerLimit = Limit - L1.Last->TotalLength - 3;
718 const auto MergedLines =
719 tryMergeNamespace(BraceOpenLine + 1, E, InnerLimit);
720 if (MergedLines == 0)
722 const auto N = MergedLines + LinesToBeMerged;
724 if (
auto Distance = std::distance(I, E);
725 static_cast<std::remove_const_t<decltype(N)
>>(Distance) <= N) {
730 if (I[N]->
First->is(TT_NamespaceRBrace) &&
731 !I[N]->First->MustBreakBefore &&
732 BraceOpenLine[MergedLines + 1]->Last->isNot(tok::comment) &&
733 nextNLinesFitInto(I, I + N + 1, Limit)) {
743 if (L1.Last->isNot(tok::semi))
747 if (L2.First->isNot(TT_NamespaceRBrace) || L2.First->MustBreakBefore)
750 if (!nextTwoLinesFitInto(I, Limit))
753 return LinesToBeMerged;
762 if (Style.BraceWrapping.AfterControlStatement ==
764 I[1]->First->is(tok::l_brace) &&
768 if (I[1]->InPPDirective != (*I)->InPPDirective ||
769 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) {
772 Limit = limitConsideringMacros(I + 1, E, Limit);
773 AnnotatedLine &
Line = **I;
774 if (
Line.First->isNoneOf(tok::kw_do, tok::kw_else) &&
775 Line.Last->isNoneOf(tok::kw_else, tok::r_paren)) {
779 if (
Line.First->is(tok::kw_do) &&
Line.Last->isNot(tok::kw_do))
781 if (1 + I[1]->
Last->TotalLength > Limit)
784 if (I[1]->
First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
785 TT_ForEachMacro, TT_LineComment)) {
789 if (Style.AllowShortIfStatementsOnASingleLine ==
791 if (I + 2 != E &&
Line.startsWith(tok::kw_if) &&
792 I[2]->First->is(tok::kw_else)) {
802 if (Limit == 0 || I + 1 == E ||
803 I[1]->
First->isOneOf(tok::kw_case, tok::kw_default)) {
806 if (I[0]->
Last->is(tok::l_brace) || I[1]->First->is(tok::l_brace))
808 unsigned NumStmts = 0;
810 bool EndsWithComment =
false;
811 bool InPPDirective = I[0]->InPPDirective;
812 bool InMacroBody = I[0]->InMacroBody;
813 const unsigned Level = I[0]->Level;
814 for (; NumStmts < 3; ++NumStmts) {
815 if (I + 1 + NumStmts == E)
817 const AnnotatedLine *
Line = I[1 + NumStmts];
818 if (
Line->InPPDirective != InPPDirective)
820 if (
Line->InMacroBody != InMacroBody)
822 if (
Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
824 if (
Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
829 if (
Line->First->is(tok::comment)) {
830 if (Level !=
Line->Level)
832 const auto *J = I + 2 + NumStmts;
833 for (; J != E; ++J) {
835 if (
Line->InPPDirective != InPPDirective)
837 if (
Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
839 if (
Line->First->isNot(tok::comment) || Level !=
Line->Level)
844 if (
Line->Last->is(tok::comment))
845 EndsWithComment =
true;
846 Length += I[1 + NumStmts]->Last->TotalLength + 1;
848 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
860 AnnotatedLine &
Line = **I;
865 if (!Style.isJava() &&
Line.First->isOneOf(tok::at, tok::minus, tok::plus))
870 if (
Line.First->is(tok::kw_case) ||
871 (
Line.First->Next &&
Line.First->Next->is(tok::kw_else))) {
875 if (
Line.First->is(tok::kw_default)) {
877 if (
Tok &&
Tok->is(tok::colon))
881 auto IsCtrlStmt = [](
const auto &
Line) {
882 return Line.First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
883 tok::kw_do, tok::kw_for, TT_ForEachMacro);
886 const bool IsSplitBlock =
889 I[1]->First->isNot(tok::r_brace));
891 if (IsCtrlStmt(
Line) ||
892 Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
893 tok::kw___finally, tok::r_brace,
894 Keywords.kw___except) ||
895 Line.startsWithExportBlock()) {
900 if (!Style.AllowShortIfStatementsOnASingleLine &&
901 Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
902 !Style.BraceWrapping.AfterControlStatement &&
903 I[1]->First->isNot(tok::r_brace)) {
906 if (!Style.AllowShortIfStatementsOnASingleLine &&
907 Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
908 Style.BraceWrapping.AfterControlStatement ==
910 I + 2 != E && I[2]->First->isNot(tok::r_brace)) {
913 if (!Style.AllowShortLoopsOnASingleLine &&
914 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
916 !Style.BraceWrapping.AfterControlStatement &&
917 I[1]->First->isNot(tok::r_brace)) {
920 if (!Style.AllowShortLoopsOnASingleLine &&
921 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
923 Style.BraceWrapping.AfterControlStatement ==
925 I + 2 != E && I[2]->First->isNot(tok::r_brace)) {
933 if (
Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
934 Keywords.kw___except, tok::kw___finally)) {
939 if (
Line.endsWith(tok::l_brace)) {
941 Line.First->is(TT_BlockLBrace)) {
945 if (IsSplitBlock &&
Line.First ==
Line.Last &&
946 I > AnnotatedLines.begin() &&
947 (I[-1]->endsWith(tok::kw_else) || IsCtrlStmt(*I[-1]))) {
951 auto ShouldMerge = [
Tok]() {
952 if (
Tok->isNot(tok::r_brace) ||
Tok->MustBreakBefore)
955 return !
Next ||
Next->is(tok::semi);
960 Tok->SpacesRequiredBefore =
962 Line.Last->is(tok::comment);
963 Tok->CanBreakBefore =
true;
965 }
else if (Limit != 0 && !
Line.startsWithNamespace() &&
966 !startsExternCBlock(
Line)) {
968 if (
Line.Last->isOneOf(TT_EnumLBrace, TT_RecordLBrace))
971 if (
Line.Last->isOneOf(TT_ClassLBrace, TT_StructLBrace,
981 Limit = limitConsideringMacros(I + 2, E, Limit);
983 if (!nextTwoLinesFitInto(I, Limit))
989 if (I[1]->
Last->is(TT_LineComment))
994 if (
Tok->is(tok::r_brace) &&
995 (!
Tok->MatchingParen ||
1004 if (
Tok->isNot(tok::r_brace))
1008 if (
Tok->Next &&
Tok->Next->is(tok::kw_else))
1018 Line.First->is(TT_ControlStatementLBrace) &&
1019 Style.BraceWrapping.AfterControlStatement ==
1026 }
else if (I[1]->
First->is(tok::l_brace)) {
1027 if (I[1]->
Last->is(TT_LineComment))
1031 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
1034 unsigned MergedLines = 0;
1036 auto TryMergeBlock = [&] {
1041 return I[1]->First == I[1]->Last && I + 2 != E &&
1042 I[2]->First->is(tok::r_brace);
1045 if (TryMergeBlock()) {
1046 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
1049 if (MergedLines > 0)
1062 if (I[0]->InPPDirective && I + 1 != E &&
1063 !I[1]->
First->HasUnescapedNewline && I[1]->First->isNot(tok::eof)) {
1064 return Limit < 2 ? 0 : Limit - 2;
1071 if (I[1]->
First->MustBreakBefore || I[2]->First->MustBreakBefore)
1073 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
1079 unsigned JoinedLength = 0;
1080 for (
const auto *J = I + 1; J != E; ++J) {
1081 if ((*J)->First->MustBreakBefore)
1084 JoinedLength += 1 + (*J)->Last->TotalLength;
1085 if (JoinedLength > Limit)
1091 bool containsMustBreak(
const AnnotatedLine *
Line) {
1092 assert(
Line->First);
1096 if (
Tok->MustBreakBefore)
1101 void join(AnnotatedLine &A,
const AnnotatedLine &B) {
1102 assert(!A.Last->Next);
1103 assert(!B.First->Previous);
1104 if (B.Affected || B.LeadingEmptyLinesAffected) {
1105 assert(B.Affected || A.Last->Children.empty());
1108 A.Last->Next = B.First;
1109 B.First->Previous = A.Last;
1110 B.First->CanBreakBefore =
true;
1111 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1113 Tok->TotalLength += LengthA;
1119 const AdditionalKeywords &Keywords;
1123 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
1127 if (
Tok->is(tok::hash) && !
Tok->Previous &&
Tok->Next &&
1128 Tok->Next->isOneOf(tok::pp_if, tok::pp_ifdef, tok::pp_ifndef,
1129 tok::pp_elif, tok::pp_elifdef, tok::pp_elifndef,
1130 tok::pp_else, tok::pp_endif)) {
1146 Tok->SpacesRequiredBefore = 0;
1147 if (!
Tok->MustBreakBeforeFinalized)
1148 Tok->MustBreakBefore = 0;
1150 Tok->Finalized =
true;
1156static void printLineState(
const LineState &State) {
1157 llvm::dbgs() <<
"State: ";
1158 for (
const ParenState &P : State.Stack) {
1159 llvm::dbgs() << (P.Tok ? P.Tok->TokenText :
"F") <<
"|" << P.Indent.Total
1160 <<
"|" << P.LastSpace <<
"|" << P.NestedBlockIndent <<
" ";
1162 llvm::dbgs() << State.NextToken->TokenText <<
"\n";
1167class LineFormatter {
1169 LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
1171 UnwrappedLineFormatter *BlockFormatter)
1172 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
1173 BlockFormatter(BlockFormatter) {}
1174 virtual ~LineFormatter() {}
1179 virtual unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1180 unsigned FirstStartColumn,
bool DryRun) = 0;
1203 bool formatChildren(LineState &State,
bool NewLine,
bool DryRun,
1204 unsigned &Penalty) {
1205 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1206 bool HasLBrace = LBrace && LBrace->is(tok::l_brace) && LBrace->is(
BK_Block);
1208 if (
Previous.Children.empty() || (!HasLBrace && !LBrace->MacroParent)) {
1214 if (NewLine ||
Previous.MacroParent) {
1215 const ParenState &P = State.Stack.back();
1217 int AdditionalIndent =
1218 P.Indent.Total -
Previous.Children[0]->Level * Style.IndentWidth;
1220 BlockFormatter->format(
Previous.Children, DryRun, AdditionalIndent,
1225 if (
Previous.Children[0]->First->MustBreakBefore)
1236 const AnnotatedLine *Child =
Previous.Children[0];
1238 if (Child->Last->isTrailingComment())
1243 if (Style.ColumnLimit > 0 &&
1244 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit) {
1249 Whitespaces->replaceWhitespace(
1250 *Child->First, 0, 1,
1251 State.Column,
nullptr,
1252 State.Line->InPPDirective);
1255 formatLine(*Child, State.Column + 1, 0, DryRun);
1257 markFinalized(Child->First);
1259 State.Column += 1 + Child->Last->TotalLength;
1263 ContinuationIndenter *Indenter;
1266 WhitespaceManager *Whitespaces;
1268 UnwrappedLineFormatter *BlockFormatter;
1272class NoColumnLimitLineFormatter :
public LineFormatter {
1274 NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
1275 WhitespaceManager *Whitespaces,
1277 UnwrappedLineFormatter *BlockFormatter)
1278 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1282 unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1283 unsigned FirstStartColumn,
bool DryRun)
override {
1285 LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
1287 while (State.NextToken) {
1289 Indenter->mustBreak(State) ||
1290 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
1291 unsigned Penalty = 0;
1292 formatChildren(State, Newline,
false, Penalty);
1293 Indenter->addTokenToState(State, Newline,
false);
1300class NoLineBreakFormatter :
public LineFormatter {
1302 NoLineBreakFormatter(ContinuationIndenter *Indenter,
1303 WhitespaceManager *Whitespaces,
const FormatStyle &Style,
1304 UnwrappedLineFormatter *BlockFormatter)
1305 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1308 unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1309 unsigned FirstStartColumn,
bool DryRun)
override {
1310 unsigned Penalty = 0;
1312 Indenter->getInitialState(FirstIndent, FirstStartColumn, &
Line, DryRun);
1313 while (State.NextToken) {
1314 formatChildren(State,
false, DryRun, Penalty);
1315 Indenter->addTokenToState(
1316 State, State.NextToken->MustBreakBefore, DryRun);
1323class OptimizingLineFormatter :
public LineFormatter {
1325 OptimizingLineFormatter(ContinuationIndenter *Indenter,
1326 WhitespaceManager *Whitespaces,
1328 UnwrappedLineFormatter *BlockFormatter)
1329 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1333 unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1334 unsigned FirstStartColumn,
bool DryRun)
override {
1336 Indenter->getInitialState(FirstIndent, FirstStartColumn, &
Line, DryRun);
1341 State.Stack.back().BreakBeforeParameter =
true;
1344 return analyzeSolutionSpace(State, DryRun);
1348 struct CompareLineStatePointers {
1349 bool operator()(LineState *obj1, LineState *obj2)
const {
1350 return *obj1 < *obj2;
1359 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1364 StateNode(
const LineState &State,
bool NewLine, StateNode *
Previous)
1373 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1376 typedef std::priority_queue<QueueItem, SmallVector<QueueItem>,
1377 std::greater<QueueItem>>
1388 unsigned analyzeSolutionSpace(LineState &InitialState,
bool DryRun) {
1389 std::set<LineState *, CompareLineStatePointers> Seen;
1397 StateNode *RootNode =
1398 new (Allocator.Allocate()) StateNode(InitialState,
false,
nullptr);
1399 Queue.push(QueueItem(OrderedPenalty(0, Count), RootNode));
1402 unsigned Penalty = 0;
1405 while (!Queue.empty()) {
1407 if (Count > 25'000'000)
1410 Penalty = Queue.top().first.first;
1411 StateNode *Node = Queue.top().second;
1412 if (!Node->State.NextToken) {
1413 LLVM_DEBUG(llvm::dbgs()
1414 <<
"\n---\nPenalty for line: " << Penalty <<
"\n");
1422 Node->State.IgnoreStackForComparison =
true;
1424 if (!Seen.insert(&Node->State).second) {
1429 FormatDecision LastFormat = Node->State.NextToken->getDecision();
1431 addNextStateToQueue(Penalty, Node,
false, &Count, &Queue);
1433 addNextStateToQueue(Penalty, Node,
true, &Count, &Queue);
1436 if (Queue.empty()) {
1439 LLVM_DEBUG(llvm::dbgs() <<
"Could not find a solution.\n");
1445 reconstructPath(InitialState, Queue.top().second);
1447 LLVM_DEBUG(llvm::dbgs()
1448 <<
"Total number of analyzed states: " << Count <<
"\n");
1449 LLVM_DEBUG(llvm::dbgs() <<
"---\n");
1458 void addNextStateToQueue(
unsigned Penalty, StateNode *PreviousNode,
1459 bool NewLine,
unsigned *Count, QueueType *Queue) {
1460 if (NewLine && !Indenter->canBreak(PreviousNode->State))
1462 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
1465 StateNode *Node =
new (Allocator.Allocate())
1466 StateNode(PreviousNode->State, NewLine, PreviousNode);
1467 if (!formatChildren(Node->State, NewLine,
true, Penalty))
1470 Penalty += Indenter->addTokenToState(Node->State, NewLine,
true);
1472 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1478 void reconstructPath(LineState &State, StateNode *Best) {
1481 while (Best->Previous) {
1482 Path.push_back(Best);
1483 Best = Best->Previous;
1485 for (
const auto &Node : llvm::reverse(Path)) {
1486 unsigned Penalty = 0;
1487 formatChildren(State, Node->NewLine,
false, Penalty);
1488 Penalty += Indenter->addTokenToState(State, Node->NewLine,
false);
1491 printLineState(Node->Previous->State);
1492 if (Node->NewLine) {
1493 llvm::dbgs() <<
"Penalty for placing "
1494 << Node->Previous->State.NextToken->Tok.getName()
1495 <<
" on a new line: " << Penalty <<
"\n";
1501 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1508 int AdditionalIndent,
bool FixBadIndentation,
unsigned FirstStartColumn,
1509 unsigned NextStartColumn,
unsigned LastStartColumn) {
1510 LineJoiner Joiner(Style, Keywords, Lines);
1513 std::pair<const SmallVectorImpl<AnnotatedLine *> *,
unsigned> CacheKey(
1514 &Lines, AdditionalIndent);
1515 auto CacheIt = PenaltyCache.find(CacheKey);
1516 if (DryRun && CacheIt != PenaltyCache.end())
1517 return CacheIt->second;
1519 assert(!Lines.empty());
1520 unsigned Penalty = 0;
1521 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
1530 bool FirstLine =
true;
1532 Joiner.getNextMergedLine(DryRun, IndentTracker);
1533 Line; PrevPrevLine = PreviousLine, PreviousLine =
Line,
Line = NextLine,
1534 FirstLine =
false) {
1535 assert(
Line->First);
1537 unsigned Indent = IndentTracker.getIndent();
1543 bool PreviousRBrace =
1544 PreviousLine && PreviousLine->
startsWith(tok::r_brace);
1545 bool ContinueFormatting =
1546 TheLine.
Level > RangeMinLevel ||
1547 (TheLine.
Level == RangeMinLevel && !PreviousRBrace &&
1550 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
1552 bool ShouldFormat = TheLine.
Affected || FixIndentation;
1556 Status->FormatComplete =
false;
1563 bool LastLine = TheLine.
First->
is(tok::eof);
1564 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines,
Indent,
1565 LastLine ? LastStartColumn : NextStartColumn +
Indent);
1568 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1569 unsigned ColumnLimit = getColumnLimit(TheLine.
InPPDirective, NextLine);
1570 bool FitsIntoOneLine =
1574 (!Style.isJavaScript() || !Style.JavaScriptWrapImports)) ||
1575 (Style.isCSharp() &&
1577 if (Style.ColumnLimit == 0) {
1578 NoColumnLimitLineFormatter(Indenter, Whitespaces, Style,
this)
1579 .formatLine(TheLine, NextStartColumn +
Indent,
1580 FirstLine ? FirstStartColumn : 0, DryRun);
1581 }
else if (FitsIntoOneLine) {
1582 Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style,
this)
1583 .formatLine(TheLine, NextStartColumn +
Indent,
1584 FirstLine ? FirstStartColumn : 0, DryRun);
1586 Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style,
this)
1587 .formatLine(TheLine, NextStartColumn +
Indent,
1588 FirstLine ? FirstStartColumn : 0, DryRun);
1590 RangeMinLevel = std::min(RangeMinLevel, TheLine.
Level);
1596 if (!
Tok->Children.empty())
1602 bool StartsNewLine =
1605 IndentTracker.adjustToUnmodifiedLine(TheLine);
1607 bool ReformatLeadingWhitespace =
1608 StartsNewLine && ((PreviousLine && PreviousLine->
Affected) ||
1611 if (ReformatLeadingWhitespace) {
1612 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines,
1616 Whitespaces->addUntouchableToken(*TheLine.
First,
1624 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1628 markFinalized(TheLine.
First);
1630 PenaltyCache[CacheKey] = Penalty;
1639 const auto &RootToken = *
Line.First;
1641 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1643 if (RootToken.is(tok::r_brace) &&
1645 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)) &&
1651 if (!PreviousLine &&
Line.Level > 0)
1653 if (
Newlines == 0 && !RootToken.IsFirst)
1655 if (RootToken.IsFirst &&
1656 (!Style.KeepEmptyLines.AtStartOfFile || !RootToken.HasUnescapedNewline)) {
1661 if (!Style.KeepEmptyLines.AtStartOfBlock && PreviousLine &&
1662 PreviousLine->
Last->
is(tok::l_brace) &&
1666 !startsExternCBlock(*PreviousLine)) {
1672 if (PreviousLine && PreviousLine->
endsWith(TT_NamespaceLBrace)) {
1675 else if (!
Line.startsWithNamespace())
1679 if (
Line.startsWith(TT_NamespaceRBrace)) {
1682 else if (!PreviousLine->
startsWith(TT_NamespaceRBrace))
1688 if (PreviousLine && RootToken.isAccessSpecifier()) {
1689 switch (Style.EmptyLineBeforeAccessModifier) {
1695 Newlines = std::max(RootToken.NewlinesBefore, 1u);
1700 if (PreviousLine->
First->isAccessSpecifier())
1705 if (PreviousLine->
Last->
is(tok::comment))
1706 previousToken = PreviousLine->
Last->getPreviousNonComment();
1708 previousToken = PreviousLine->
Last;
1709 if ((!previousToken || previousToken->
isNot(tok::l_brace)) &&
1718 if (PreviousLine && PreviousLine->
First->isAccessSpecifier() &&
1719 (!PreviousLine->
InPPDirective || !RootToken.HasUnescapedNewline)) {
1722 if (!RootToken.isAccessSpecifier()) {
1723 switch (Style.EmptyLineAfterAccessModifier) {
1731 if (RootToken.is(tok::r_brace))
1743void UnwrappedLineFormatter::formatFirstToken(
1744 const AnnotatedLine &
Line,
const AnnotatedLine *PreviousLine,
1745 const AnnotatedLine *PrevPrevLine,
1747 unsigned NewlineIndent) {
1749 if (RootToken.is(tok::eof)) {
1751 RootToken.NewlinesBefore,
1752 Style.KeepEmptyLines.AtEndOfFile ? Style.MaxEmptyLinesToKeep + 1 : 1);
1753 unsigned TokenIndent =
Newlines ? NewlineIndent : 0;
1759 if (RootToken.Newlines < 0) {
1760 RootToken.Newlines =
1762 assert(RootToken.Newlines >= 0);
1765 if (RootToken.Newlines > 0)
1770 if (!Style.isJavaScript() &&
1777 Whitespaces->replaceWhitespace(RootToken, RootToken.Newlines,
Indent,
Indent,
1779 Line.InPPDirective &&
1780 !RootToken.HasUnescapedNewline);
1784UnwrappedLineFormatter::getColumnLimit(
bool InPPDirective,
1788 bool ContinuesPPDirective =
1793 (NextLine->InPPDirective &&
1796 !NextLine->First->HasUnescapedNewline));
1797 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
WhitespaceManager class manages whitespace around tokens and their replacements.
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Top level wrappers for InstallAPI frontend operations.
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)