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->Last->is(TT_ExportLBrace) &&
448 !Style.BraceWrapping.AfterExportBlock))) {
450 ? tryMergeSimpleBlock(I, E, Limit)
454 if (NextLine.First->is(TT_ControlStatementLBrace)) {
458 return Style.BraceWrapping.AfterControlStatement ==
460 ? tryMergeSimpleBlock(I, E, Limit)
463 if (PreviousLine && TheLine->First->is(tok::l_brace)) {
464 switch (PreviousLine->First->Tok.getKind()) {
467 if (PreviousLine->First->Next &&
468 PreviousLine->First->Next->isOneOf(tok::objc_autoreleasepool,
469 tok::objc_synchronized)) {
475 case tok::kw_default:
486 if (PreviousLine && Style.BraceWrapping.SplitEmptyRecord &&
487 TheLine->Last->is(tok::l_brace) && PreviousLine->Last) {
493 if (
Previous->is(tok::greater) && !PreviousLine->InPPDirective)
495 if (
Previous->is(tok::identifier)) {
498 if (PreviousPrevious &&
499 PreviousPrevious->isOneOf(tok::kw_class, tok::kw_struct,
508 if (TheLine->First->is(TT_SwitchExpressionLabel)) {
509 return Style.AllowShortCaseExpressionOnASingleLine
510 ? tryMergeShortCaseLabels(I, E, Limit)
514 if (TheLine->Last->is(tok::l_brace)) {
515 bool ShouldMerge =
false;
517 if (TheLine->Last->is(TT_EnumLBrace)) {
518 ShouldMerge = Style.AllowShortEnumsOnASingleLine;
519 }
else if (TheLine->Last->is(TT_CompoundRequirementLBrace)) {
520 ShouldMerge = Style.AllowShortCompoundRequirementOnASingleLine;
521 }
else if (TheLine->Last->isOneOf(TT_ClassLBrace, TT_StructLBrace,
523 return tryMergeRecord(I, E, Limit);
524 }
else if (TheLine->Last->is(TT_RecordLBrace) && Style.isJava()) {
527 ShouldMerge = !Style.BraceWrapping.AfterClass ||
528 (NextLine.First->is(tok::r_brace) &&
529 !Style.BraceWrapping.SplitEmptyRecord);
530 }
else if (TheLine->InPPDirective ||
531 TheLine->First->isNoneOf(tok::kw_class, tok::kw_enum,
532 tok::kw_struct, tok::kw_union)) {
535 ShouldMerge = !Style.BraceWrapping.AfterFunction ||
536 (NextLine.First->is(tok::r_brace) &&
537 !Style.BraceWrapping.SplitEmptyFunction);
539 return ShouldMerge ? tryMergeSimpleBlock(I, E, Limit) : 0;
543 if (NextLine.First->is(TT_FunctionLBrace) &&
544 Style.BraceWrapping.AfterFunction) {
545 if (NextLine.Last->is(TT_LineComment))
549 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
553 unsigned MergedLines = 0;
554 if (MergeShortFunctions ||
555 (Style.AllowShortFunctionsOnASingleLine.Empty &&
556 NextLine.First == NextLine.Last && I + 2 != E &&
557 I[2]->First->is(tok::r_brace))) {
558 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
566 auto IsElseLine = [&TheLine]() ->
bool {
568 if (
First->is(tok::kw_else))
571 return First->is(tok::r_brace) &&
First->Next &&
572 First->Next->is(tok::kw_else);
574 if (TheLine->First->is(tok::kw_if) ||
575 (IsElseLine() && (Style.AllowShortIfStatementsOnASingleLine ==
577 return Style.AllowShortIfStatementsOnASingleLine
578 ? tryMergeSimpleControlStatement(I, E, Limit)
581 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while, tok::kw_do,
583 return Style.AllowShortLoopsOnASingleLine
584 ? tryMergeSimpleControlStatement(I, E, Limit)
587 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
588 return Style.AllowShortCaseLabelsOnASingleLine
589 ? tryMergeShortCaseLabels(I, E, Limit)
592 if (TheLine->InPPDirective &&
593 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
594 return tryMergeSimplePPDirective(I, E, Limit);
602 const auto *
Line = I[0];
603 const auto *NextLine = I[1];
606 if (
Line->Last->isOneOf(TT_ClassLBrace, TT_StructLBrace, TT_UnionLBrace)) {
607 auto ShouldWrapLBrace = [&](TokenType LBraceType) {
608 switch (LBraceType) {
610 return Style.BraceWrapping.AfterClass;
611 case TT_StructLBrace:
612 return Style.BraceWrapping.AfterStruct;
614 return Style.BraceWrapping.AfterUnion;
620 auto TryMergeShortRecord = [&] {
621 switch (Style.AllowShortRecordOnASingleLine) {
627 return NextLine->First->is(tok::r_brace);
632 (!ShouldWrapLBrace(
Line->Last->getType()) ||
633 (!Style.BraceWrapping.SplitEmptyRecord && TryMergeShortRecord()))) {
634 return tryMergeSimpleBlock(I, E, Limit);
640 if (NextLine->First->isOneOf(TT_ClassLBrace, TT_StructLBrace,
642 if (I + 2 == E || I[2]->
First->is(tok::r_brace) ||
647 return tryMergeSimpleBlock(I, E, Limit);
651 if (I != AnnotatedLines.begin() &&
652 I[-1]->First->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union)) {
653 const bool IsEmptyBlock =
654 Line->Last->is(tok::l_brace) && NextLine->First->is(tok::r_brace);
656 if ((IsEmptyBlock && !Style.BraceWrapping.SplitEmptyRecord) ||
659 return tryMergeSimpleBlock(I, E, Limit);
672 if (I + 2 != E && I[2]->InPPDirective && !I[2]->
First->HasUnescapedNewline)
674 if (1 + I[1]->
Last->TotalLength > Limit)
687 const bool OpenBraceWrapped = Style.BraceWrapping.AfterNamespace;
688 const auto *BraceOpenLine = I + OpenBraceWrapped;
690 assert(*BraceOpenLine);
691 if (BraceOpenLine[0]->
Last->isNot(TT_NamespaceLBrace))
694 if (std::distance(BraceOpenLine, E) <= 2)
697 if (BraceOpenLine[0]->
Last->is(tok::comment))
700 assert(BraceOpenLine[1]);
701 const auto &L1 = *BraceOpenLine[1];
702 if (L1.InPPDirective != (*I)->InPPDirective ||
703 (L1.InPPDirective && L1.First->HasUnescapedNewline)) {
707 assert(BraceOpenLine[2]);
708 const auto &L2 = *BraceOpenLine[2];
712 Limit = limitConsideringMacros(I + 1, E, Limit);
714 const auto LinesToBeMerged = OpenBraceWrapped + 2;
718 if (L1.First->is(tok::kw_namespace)) {
719 if (L1.Last->is(tok::comment) || !Style.CompactNamespaces)
723 const auto InnerLimit = Limit - L1.Last->TotalLength - 3;
724 const auto MergedLines =
725 tryMergeNamespace(BraceOpenLine + 1, E, InnerLimit);
726 if (MergedLines == 0)
728 const auto N = MergedLines + LinesToBeMerged;
730 if (
auto Distance = std::distance(I, E);
731 static_cast<std::remove_const_t<decltype(N)
>>(Distance) <= N) {
736 if (I[N]->
First->is(TT_NamespaceRBrace) &&
737 !I[N]->First->MustBreakBefore &&
738 BraceOpenLine[MergedLines + 1]->Last->isNot(tok::comment) &&
739 nextNLinesFitInto(I, I + N + 1, Limit)) {
749 if (L1.Last->isNot(tok::semi))
753 if (L2.First->isNot(TT_NamespaceRBrace) || L2.First->MustBreakBefore)
756 if (!nextTwoLinesFitInto(I, Limit))
759 return LinesToBeMerged;
768 if (Style.BraceWrapping.AfterControlStatement ==
770 I[1]->First->is(tok::l_brace) &&
774 if (I[1]->InPPDirective != (*I)->InPPDirective ||
775 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) {
778 Limit = limitConsideringMacros(I + 1, E, Limit);
779 AnnotatedLine &
Line = **I;
780 if (
Line.First->isNoneOf(tok::kw_do, tok::kw_else) &&
781 Line.Last->isNoneOf(tok::kw_else, tok::r_paren)) {
785 if (
Line.First->is(tok::kw_do) &&
Line.Last->isNot(tok::kw_do))
787 if (1 + I[1]->
Last->TotalLength > Limit)
790 if (I[1]->
First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
791 TT_ForEachMacro, TT_LineComment)) {
795 if (Style.AllowShortIfStatementsOnASingleLine ==
797 if (I + 2 != E &&
Line.startsWith(tok::kw_if) &&
798 I[2]->First->is(tok::kw_else)) {
808 if (Limit == 0 || I + 1 == E ||
809 I[1]->
First->isOneOf(tok::kw_case, tok::kw_default)) {
812 if (I[0]->
Last->is(tok::l_brace) || I[1]->First->is(tok::l_brace))
814 unsigned NumStmts = 0;
816 bool EndsWithComment =
false;
817 bool InPPDirective = I[0]->InPPDirective;
818 bool InMacroBody = I[0]->InMacroBody;
819 const unsigned Level = I[0]->Level;
820 for (; NumStmts < 3; ++NumStmts) {
821 if (I + 1 + NumStmts == E)
823 const AnnotatedLine *
Line = I[1 + NumStmts];
824 if (
Line->InPPDirective != InPPDirective)
826 if (
Line->InMacroBody != InMacroBody)
828 if (
Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
830 if (
Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
835 if (
Line->First->is(tok::comment)) {
836 if (Level !=
Line->Level)
838 const auto *J = I + 2 + NumStmts;
839 for (; J != E; ++J) {
841 if (
Line->InPPDirective != InPPDirective)
843 if (
Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
845 if (
Line->First->isNot(tok::comment) || Level !=
Line->Level)
850 if (
Line->Last->is(tok::comment))
851 EndsWithComment =
true;
852 Length += I[1 + NumStmts]->Last->TotalLength + 1;
854 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
866 AnnotatedLine &
Line = **I;
871 if (!Style.isJava() &&
Line.First->isOneOf(tok::at, tok::minus, tok::plus))
876 if (
Line.First->is(tok::kw_case) ||
877 (
Line.First->Next &&
Line.First->Next->is(tok::kw_else))) {
881 if (
Line.First->is(tok::kw_default)) {
883 if (
Tok &&
Tok->is(tok::colon))
887 auto IsCtrlStmt = [](
const auto &
Line) {
888 return Line.First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
889 tok::kw_do, tok::kw_for, TT_ForEachMacro);
892 const bool IsSplitBlock =
895 I[1]->First->isNot(tok::r_brace));
897 if (IsCtrlStmt(
Line) ||
898 Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
899 tok::kw___finally, tok::r_brace,
900 Keywords.kw___except) ||
901 Line.Last->is(TT_ExportLBrace)) {
906 if (!Style.AllowShortIfStatementsOnASingleLine &&
907 Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
908 !Style.BraceWrapping.AfterControlStatement &&
909 I[1]->First->isNot(tok::r_brace)) {
912 if (!Style.AllowShortIfStatementsOnASingleLine &&
913 Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
914 Style.BraceWrapping.AfterControlStatement ==
916 I + 2 != E && I[2]->First->isNot(tok::r_brace)) {
919 if (!Style.AllowShortLoopsOnASingleLine &&
920 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
922 !Style.BraceWrapping.AfterControlStatement &&
923 I[1]->First->isNot(tok::r_brace)) {
926 if (!Style.AllowShortLoopsOnASingleLine &&
927 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
929 Style.BraceWrapping.AfterControlStatement ==
931 I + 2 != E && I[2]->First->isNot(tok::r_brace)) {
939 if (
Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
940 Keywords.kw___except, tok::kw___finally)) {
945 if (
Line.endsWith(tok::l_brace)) {
946 if (Style.BraceWrapping.AfterExportBlock &&
947 Line.First->is(TT_ExportLBrace)) {
952 Line.First->is(TT_BlockLBrace)) {
956 if (IsSplitBlock &&
Line.First ==
Line.Last &&
957 I > AnnotatedLines.begin() &&
958 (I[-1]->endsWith(tok::kw_else) || IsCtrlStmt(*I[-1]))) {
962 auto ShouldMerge = [
Tok]() {
963 if (
Tok->isNot(tok::r_brace) ||
Tok->MustBreakBefore)
966 return !
Next ||
Next->is(tok::semi);
971 Tok->SpacesRequiredBefore =
973 Line.Last->is(tok::comment);
974 Tok->CanBreakBefore =
true;
976 }
else if (Limit != 0 && !
Line.startsWithNamespace() &&
977 !startsExternCBlock(
Line)) {
979 if (
Line.Last->isOneOf(TT_EnumLBrace, TT_RecordLBrace))
982 if (
Line.Last->isOneOf(TT_ClassLBrace, TT_StructLBrace,
992 Limit = limitConsideringMacros(I + 2, E, Limit);
994 if (!nextTwoLinesFitInto(I, Limit))
1000 if (I[1]->
Last->is(TT_LineComment))
1005 if (
Tok->is(tok::r_brace) &&
1006 (!
Tok->MatchingParen ||
1015 if (
Tok->isNot(tok::r_brace))
1019 if (
Tok->Next &&
Tok->Next->is(tok::kw_else))
1029 Line.First->is(TT_ControlStatementLBrace) &&
1030 Style.BraceWrapping.AfterControlStatement ==
1037 }
else if (I[1]->
First->is(tok::l_brace)) {
1038 if (I[1]->
Last->is(TT_LineComment))
1042 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
1045 unsigned MergedLines = 0;
1047 auto TryMergeBlock = [&] {
1052 return I[1]->First == I[1]->Last && I + 2 != E &&
1053 I[2]->First->is(tok::r_brace);
1056 if (TryMergeBlock()) {
1057 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
1060 if (MergedLines > 0)
1073 if (I[0]->InPPDirective && I + 1 != E &&
1074 !I[1]->
First->HasUnescapedNewline && I[1]->First->isNot(tok::eof)) {
1075 return Limit < 2 ? 0 : Limit - 2;
1082 if (I[1]->
First->MustBreakBefore || I[2]->First->MustBreakBefore)
1084 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
1090 unsigned JoinedLength = 0;
1091 for (
const auto *J = I + 1; J != E; ++J) {
1092 if ((*J)->First->MustBreakBefore)
1095 JoinedLength += 1 + (*J)->Last->TotalLength;
1096 if (JoinedLength > Limit)
1102 bool containsMustBreak(
const AnnotatedLine *
Line) {
1103 assert(
Line->First);
1107 if (
Tok->MustBreakBefore)
1112 void join(AnnotatedLine &A,
const AnnotatedLine &B) {
1113 assert(!A.Last->Next);
1114 assert(!B.First->Previous);
1115 if (B.Affected || B.LeadingEmptyLinesAffected) {
1116 assert(B.Affected || A.Last->Children.empty());
1119 A.Last->Next = B.First;
1120 B.First->Previous = A.Last;
1121 B.First->CanBreakBefore =
true;
1122 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1124 Tok->TotalLength += LengthA;
1130 const AdditionalKeywords &Keywords;
1134 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
1138 if (
Tok->is(tok::hash) && !
Tok->Previous &&
Tok->Next &&
1139 Tok->Next->isOneOf(tok::pp_if, tok::pp_ifdef, tok::pp_ifndef,
1140 tok::pp_elif, tok::pp_elifdef, tok::pp_elifndef,
1141 tok::pp_else, tok::pp_endif)) {
1157 Tok->SpacesRequiredBefore = 0;
1158 if (!
Tok->MustBreakBeforeFinalized)
1159 Tok->MustBreakBefore = 0;
1161 Tok->Finalized =
true;
1167static void printLineState(
const LineState &State) {
1168 llvm::dbgs() <<
"State: ";
1169 for (
const ParenState &P : State.Stack) {
1170 llvm::dbgs() << (P.Tok ? P.Tok->TokenText :
"F") <<
"|" << P.Indent.Total
1171 <<
"|" << P.LastSpace <<
"|" << P.NestedBlockIndent <<
" ";
1173 llvm::dbgs() << State.NextToken->TokenText <<
"\n";
1178class LineFormatter {
1180 LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
1182 UnwrappedLineFormatter *BlockFormatter)
1183 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
1184 BlockFormatter(BlockFormatter) {}
1185 virtual ~LineFormatter() {}
1190 virtual unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1191 unsigned FirstStartColumn,
bool DryRun) = 0;
1214 bool formatChildren(LineState &State,
bool NewLine,
bool DryRun,
1215 unsigned &Penalty) {
1216 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1217 bool HasLBrace = LBrace && LBrace->is(tok::l_brace) && LBrace->is(
BK_Block);
1219 if (
Previous.Children.empty() || (!HasLBrace && !LBrace->MacroParent)) {
1225 if (NewLine ||
Previous.MacroParent) {
1226 const ParenState &P = State.Stack.back();
1228 int AdditionalIndent =
1229 P.Indent.Total -
Previous.Children[0]->Level * Style.IndentWidth;
1231 BlockFormatter->format(
Previous.Children, DryRun, AdditionalIndent,
1236 if (
Previous.Children[0]->First->MustBreakBefore)
1247 const AnnotatedLine *Child =
Previous.Children[0];
1249 if (Child->Last->isTrailingComment())
1254 if (Style.ColumnLimit > 0 &&
1255 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit) {
1260 Whitespaces->replaceWhitespace(
1261 *Child->First, 0, 1,
1262 State.Column,
nullptr,
1263 State.Line->InPPDirective);
1266 formatLine(*Child, State.Column + 1, 0, DryRun);
1268 markFinalized(Child->First);
1270 State.Column += 1 + Child->Last->TotalLength;
1274 ContinuationIndenter *Indenter;
1277 WhitespaceManager *Whitespaces;
1279 UnwrappedLineFormatter *BlockFormatter;
1283class NoColumnLimitLineFormatter :
public LineFormatter {
1285 NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
1286 WhitespaceManager *Whitespaces,
1288 UnwrappedLineFormatter *BlockFormatter)
1289 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1293 unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1294 unsigned FirstStartColumn,
bool DryRun)
override {
1296 LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
1298 while (State.NextToken) {
1300 Indenter->mustBreak(State) ||
1301 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
1302 unsigned Penalty = 0;
1303 formatChildren(State, Newline,
false, Penalty);
1304 Indenter->addTokenToState(State, Newline,
false);
1311class NoLineBreakFormatter :
public LineFormatter {
1313 NoLineBreakFormatter(ContinuationIndenter *Indenter,
1314 WhitespaceManager *Whitespaces,
const FormatStyle &Style,
1315 UnwrappedLineFormatter *BlockFormatter)
1316 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1319 unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1320 unsigned FirstStartColumn,
bool DryRun)
override {
1321 unsigned Penalty = 0;
1323 Indenter->getInitialState(FirstIndent, FirstStartColumn, &
Line, DryRun);
1324 while (State.NextToken) {
1325 formatChildren(State,
false, DryRun, Penalty);
1326 Indenter->addTokenToState(
1327 State, State.NextToken->MustBreakBefore, DryRun);
1334class OptimizingLineFormatter :
public LineFormatter {
1336 OptimizingLineFormatter(ContinuationIndenter *Indenter,
1337 WhitespaceManager *Whitespaces,
1339 UnwrappedLineFormatter *BlockFormatter)
1340 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1344 unsigned formatLine(
const AnnotatedLine &
Line,
unsigned FirstIndent,
1345 unsigned FirstStartColumn,
bool DryRun)
override {
1347 Indenter->getInitialState(FirstIndent, FirstStartColumn, &
Line, DryRun);
1352 State.Stack.back().BreakBeforeParameter =
true;
1355 return analyzeSolutionSpace(State, DryRun);
1359 struct CompareLineStatePointers {
1360 bool operator()(LineState *obj1, LineState *obj2)
const {
1361 return *obj1 < *obj2;
1370 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1375 StateNode(
const LineState &State,
bool NewLine, StateNode *
Previous)
1384 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1387 typedef std::priority_queue<QueueItem, SmallVector<QueueItem>,
1388 std::greater<QueueItem>>
1399 unsigned analyzeSolutionSpace(LineState &InitialState,
bool DryRun) {
1400 std::set<LineState *, CompareLineStatePointers> Seen;
1408 StateNode *RootNode =
1409 new (Allocator.Allocate()) StateNode(InitialState,
false,
nullptr);
1410 Queue.push(QueueItem(OrderedPenalty(0, Count), RootNode));
1413 unsigned Penalty = 0;
1416 while (!Queue.empty()) {
1418 if (Count > 25'000'000)
1421 Penalty = Queue.top().first.first;
1422 StateNode *Node = Queue.top().second;
1423 if (!Node->State.NextToken) {
1424 LLVM_DEBUG(llvm::dbgs()
1425 <<
"\n---\nPenalty for line: " << Penalty <<
"\n");
1433 Node->State.IgnoreStackForComparison =
true;
1435 if (!Seen.insert(&Node->State).second) {
1440 FormatDecision LastFormat = Node->State.NextToken->getDecision();
1442 addNextStateToQueue(Penalty, Node,
false, &Count, &Queue);
1444 addNextStateToQueue(Penalty, Node,
true, &Count, &Queue);
1447 if (Queue.empty()) {
1450 LLVM_DEBUG(llvm::dbgs() <<
"Could not find a solution.\n");
1456 reconstructPath(InitialState, Queue.top().second);
1458 LLVM_DEBUG(llvm::dbgs()
1459 <<
"Total number of analyzed states: " << Count <<
"\n");
1460 LLVM_DEBUG(llvm::dbgs() <<
"---\n");
1469 void addNextStateToQueue(
unsigned Penalty, StateNode *PreviousNode,
1470 bool NewLine,
unsigned *Count, QueueType *Queue) {
1471 if (NewLine && !Indenter->canBreak(PreviousNode->State))
1473 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
1476 StateNode *Node =
new (Allocator.Allocate())
1477 StateNode(PreviousNode->State, NewLine, PreviousNode);
1478 if (!formatChildren(Node->State, NewLine,
true, Penalty))
1481 Penalty += Indenter->addTokenToState(Node->State, NewLine,
true);
1483 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1489 void reconstructPath(LineState &State, StateNode *Best) {
1492 while (Best->Previous) {
1493 Path.push_back(Best);
1494 Best = Best->Previous;
1496 for (
const auto &Node : llvm::reverse(Path)) {
1497 unsigned Penalty = 0;
1498 formatChildren(State, Node->NewLine,
false, Penalty);
1499 Penalty += Indenter->addTokenToState(State, Node->NewLine,
false);
1502 printLineState(Node->Previous->State);
1503 if (Node->NewLine) {
1504 llvm::dbgs() <<
"Penalty for placing "
1505 << Node->Previous->State.NextToken->Tok.getName()
1506 <<
" on a new line: " << Penalty <<
"\n";
1512 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1519 int AdditionalIndent,
bool FixBadIndentation,
unsigned FirstStartColumn,
1520 unsigned NextStartColumn,
unsigned LastStartColumn) {
1521 LineJoiner Joiner(Style, Keywords, Lines);
1524 std::pair<const SmallVectorImpl<AnnotatedLine *> *,
unsigned> CacheKey(
1525 &Lines, AdditionalIndent);
1526 auto CacheIt = PenaltyCache.find(CacheKey);
1527 if (DryRun && CacheIt != PenaltyCache.end())
1528 return CacheIt->second;
1530 assert(!Lines.empty());
1531 unsigned Penalty = 0;
1532 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
1541 bool FirstLine =
true;
1543 Joiner.getNextMergedLine(DryRun, IndentTracker);
1544 Line; PrevPrevLine = PreviousLine, PreviousLine =
Line,
Line = NextLine,
1545 FirstLine =
false) {
1546 assert(
Line->First);
1548 unsigned Indent = IndentTracker.getIndent();
1554 bool PreviousRBrace =
1555 PreviousLine && PreviousLine->
startsWith(tok::r_brace);
1556 bool ContinueFormatting =
1557 TheLine.
Level > RangeMinLevel ||
1558 (TheLine.
Level == RangeMinLevel && !PreviousRBrace &&
1561 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
1563 bool ShouldFormat = TheLine.
Affected || FixIndentation;
1567 Status->FormatComplete =
false;
1574 bool LastLine = TheLine.
First->
is(tok::eof);
1575 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines,
Indent,
1576 LastLine ? LastStartColumn : NextStartColumn +
Indent);
1579 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1580 unsigned ColumnLimit = getColumnLimit(TheLine.
InPPDirective, NextLine);
1581 bool FitsIntoOneLine =
1585 (!Style.isJavaScript() || !Style.JavaScriptWrapImports)) ||
1586 (Style.isCSharp() &&
1588 if (Style.ColumnLimit == 0) {
1589 NoColumnLimitLineFormatter(Indenter, Whitespaces, Style,
this)
1590 .formatLine(TheLine, NextStartColumn +
Indent,
1591 FirstLine ? FirstStartColumn : 0, DryRun);
1592 }
else if (FitsIntoOneLine) {
1593 Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style,
this)
1594 .formatLine(TheLine, NextStartColumn +
Indent,
1595 FirstLine ? FirstStartColumn : 0, DryRun);
1597 Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style,
this)
1598 .formatLine(TheLine, NextStartColumn +
Indent,
1599 FirstLine ? FirstStartColumn : 0, DryRun);
1601 RangeMinLevel = std::min(RangeMinLevel, TheLine.
Level);
1607 if (!
Tok->Children.empty())
1613 bool StartsNewLine =
1616 IndentTracker.adjustToUnmodifiedLine(TheLine);
1618 bool ReformatLeadingWhitespace =
1619 StartsNewLine && ((PreviousLine && PreviousLine->
Affected) ||
1622 if (ReformatLeadingWhitespace) {
1623 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines,
1627 Whitespaces->addUntouchableToken(*TheLine.
First,
1635 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1639 markFinalized(TheLine.
First);
1641 PenaltyCache[CacheKey] = Penalty;
1650 const auto &RootToken = *
Line.First;
1652 return RootToken.NewlinesBefore;
1654 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1656 if (RootToken.is(tok::r_brace) &&
1658 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)) &&
1664 if (!PreviousLine &&
Line.Level > 0)
1666 if (
Newlines == 0 && !RootToken.IsFirst)
1668 if (RootToken.IsFirst &&
1669 (!Style.KeepEmptyLines.AtStartOfFile || !RootToken.HasUnescapedNewline)) {
1674 if (!Style.KeepEmptyLines.AtStartOfBlock && PreviousLine &&
1675 PreviousLine->
Last->
is(tok::l_brace) &&
1679 !startsExternCBlock(*PreviousLine)) {
1685 if (PreviousLine && PreviousLine->
endsWith(TT_NamespaceLBrace)) {
1688 else if (!
Line.startsWithNamespace())
1692 if (
Line.startsWith(TT_NamespaceRBrace)) {
1695 else if (!PreviousLine->
startsWith(TT_NamespaceRBrace))
1701 if (PreviousLine && RootToken.isAccessSpecifier()) {
1702 switch (Style.EmptyLineBeforeAccessModifier) {
1708 Newlines = std::max(RootToken.NewlinesBefore, 1u);
1713 if (PreviousLine->
First->isAccessSpecifier())
1718 if (PreviousLine->
Last->
is(tok::comment))
1719 previousToken = PreviousLine->
Last->getPreviousNonComment();
1721 previousToken = PreviousLine->
Last;
1722 if ((!previousToken || previousToken->
isNot(tok::l_brace)) &&
1731 if (PreviousLine && PreviousLine->
First->isAccessSpecifier() &&
1732 (!PreviousLine->
InPPDirective || !RootToken.HasUnescapedNewline)) {
1735 if (!RootToken.isAccessSpecifier()) {
1736 switch (Style.EmptyLineAfterAccessModifier) {
1744 if (RootToken.is(tok::r_brace))
1756void UnwrappedLineFormatter::formatFirstToken(
1757 const AnnotatedLine &
Line,
const AnnotatedLine *PreviousLine,
1758 const AnnotatedLine *PrevPrevLine,
1760 unsigned NewlineIndent) {
1762 if (RootToken.is(tok::eof)) {
1764 RootToken.NewlinesBefore,
1765 Style.KeepEmptyLines.AtEndOfFile ? Style.MaxEmptyLinesToKeep + 1 : 1);
1766 unsigned TokenIndent =
Newlines ? NewlineIndent : 0;
1772 if (RootToken.Newlines < 0) {
1773 RootToken.Newlines =
1775 assert(RootToken.Newlines >= 0);
1778 if (RootToken.Newlines > 0)
1783 if (!Style.isJavaScript() &&
1790 Whitespaces->replaceWhitespace(RootToken, RootToken.Newlines,
Indent,
Indent,
1792 Line.InPPDirective &&
1793 !RootToken.HasUnescapedNewline);
1797UnwrappedLineFormatter::getColumnLimit(
bool InPPDirective,
1801 bool ContinuesPPDirective =
1806 (NextLine->InPPDirective &&
1809 !NextLine->First->HasUnescapedNewline));
1810 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)