13 #include "llvm/Support/Debug.h" 16 #define DEBUG_TYPE "format-formatter" 23 bool 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);
39 class LevelIndentTracker {
41 LevelIndentTracker(
const FormatStyle &
Style,
42 const AdditionalKeywords &Keywords,
unsigned StartLevel,
44 :
Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) {
45 for (
unsigned i = 0; i != StartLevel; ++i)
46 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
50 unsigned getIndent()
const {
return Indent; }
54 void nextLine(
const AnnotatedLine &Line) {
55 Offset = getIndentOffset(*Line.First);
58 while (IndentForLevel.size() <= Line.Level)
59 IndentForLevel.push_back(-1);
60 if (Line.InPPDirective) {
61 Indent = Line.Level * Style.IndentWidth + AdditionalIndent;
63 IndentForLevel.resize(Line.Level + 1);
64 Indent = getIndent(IndentForLevel, Line.Level);
66 if (static_cast<int>(Indent) +
Offset >= 0)
72 void skipLine(
const AnnotatedLine &Line) {
73 while (IndentForLevel.size() <= Line.Level)
74 IndentForLevel.push_back(Indent);
82 void adjustToUnmodifiedLine(
const AnnotatedLine &Line) {
83 unsigned LevelIndent = Line.First->OriginalColumn;
84 if (static_cast<int>(LevelIndent) -
Offset >= 0)
86 if ((!Line.First->is(tok::comment) || IndentForLevel[Line.Level] == -1) &&
88 IndentForLevel[Line.Level] = LevelIndent;
96 int getIndentOffset(
const FormatToken &RootToken) {
100 if (RootToken.isAccessSpecifier(
false) ||
101 RootToken.isObjCAccessSpecifier() ||
102 (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
103 RootToken.Next && RootToken.Next->is(tok::colon)))
104 return Style.AccessModifierOffset;
113 unsigned getIndent(ArrayRef<int> IndentForLevel,
unsigned Level) {
114 if (IndentForLevel[Level] != -1)
115 return IndentForLevel[
Level];
118 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
121 const FormatStyle &
Style;
122 const AdditionalKeywords &Keywords;
123 const unsigned AdditionalIndent;
126 std::vector<int> IndentForLevel;
138 bool isNamespaceDeclaration(
const AnnotatedLine *Line) {
139 const FormatToken *NamespaceTok = Line->First;
140 return NamespaceTok && NamespaceTok->getNamespaceToken();
143 bool isEndOfNamespace(
const AnnotatedLine *Line,
144 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
145 if (!Line->startsWith(tok::r_brace))
147 size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex;
150 assert(StartLineIndex < AnnotatedLines.size());
151 return isNamespaceDeclaration(AnnotatedLines[StartLineIndex]);
156 LineJoiner(
const FormatStyle &
Style,
const AdditionalKeywords &Keywords,
157 const SmallVectorImpl<AnnotatedLine *> &Lines)
158 :
Style(Style), Keywords(Keywords),
End(Lines.end()), Next(Lines.begin()),
159 AnnotatedLines(Lines) {}
162 const AnnotatedLine *getNextMergedLine(
bool DryRun,
163 LevelIndentTracker &IndentTracker) {
166 const AnnotatedLine *Current = *Next;
167 IndentTracker.nextLine(*Current);
168 unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next,
End);
169 if (MergedLines > 0 && Style.ColumnLimit == 0)
172 for (
unsigned i = 0; i < MergedLines; ++i)
173 if (Next[i + 1]->First->NewlinesBefore > 0)
176 for (
unsigned i = 0; i < MergedLines; ++i)
177 join(*Next[0], *Next[i + 1]);
178 Next = Next + MergedLines + 1;
185 tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker,
186 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
187 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
188 const unsigned Indent = IndentTracker.getIndent();
194 const AnnotatedLine *TheLine = *I;
195 if (TheLine->Last->is(TT_LineComment))
199 if (TheLine->InPPDirective &&
200 (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline))
203 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
207 Style.ColumnLimit == 0 ?
UINT_MAX : Style.ColumnLimit - Indent;
210 Limit = TheLine->Last->TotalLength > Limit
212 : Limit - TheLine->Last->TotalLength;
214 if (TheLine->Last->is(TT_FunctionLBrace) &&
215 TheLine->First == TheLine->Last &&
216 !Style.BraceWrapping.SplitEmptyFunction &&
217 I[1]->First->is(tok::r_brace))
218 return tryMergeSimpleBlock(I, E, Limit);
221 if (TheLine->Last->is(tok::l_brace) && TheLine->First == TheLine->Last &&
222 I != AnnotatedLines.begin()) {
223 bool EmptyBlock = I[1]->First->is(tok::r_brace);
225 const FormatToken *
Tok = I[-1]->First;
226 if (Tok && Tok->is(tok::comment))
229 if (Tok && Tok->getNamespaceToken())
230 return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock
231 ? tryMergeSimpleBlock(I, E, Limit)
234 if (Tok && Tok->is(tok::kw_typedef))
236 if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union,
237 tok::kw_extern, Keywords.kw_interface))
238 return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock
239 ? tryMergeSimpleBlock(I, E, Limit)
245 bool MergeShortFunctions =
248 I[1]->First->is(tok::r_brace)) ||
250 TheLine->Level != 0);
252 if (Style.CompactNamespaces) {
253 if (isNamespaceDeclaration(TheLine)) {
255 unsigned closingLine = TheLine->MatchingClosingBlockLineIndex - 1;
256 for (; I + 1 + i != E && isNamespaceDeclaration(I[i + 1]) &&
257 closingLine == I[i + 1]->MatchingClosingBlockLineIndex &&
258 I[i + 1]->Last->TotalLength < Limit;
259 i++, closingLine--) {
261 IndentTracker.skipLine(*I[i + 1]);
263 Limit -= I[i + 1]->Last->TotalLength;
268 if (isEndOfNamespace(TheLine, AnnotatedLines)) {
270 unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
271 for (; I + 1 + i != E && isEndOfNamespace(I[i + 1], AnnotatedLines) &&
272 openingLine == I[i + 1]->MatchingOpeningBlockLineIndex;
273 i++, openingLine--) {
275 I[i + 1]->First->SpacesRequiredBefore = !I[i]->Last->is(tok::r_brace);
278 IndentTracker.nextLine(*I[i + 1]);
285 if (TheLine->Last->is(TT_FunctionLBrace) &&
286 TheLine->First != TheLine->Last) {
287 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
290 if (TheLine->Last->is(tok::l_brace) && TheLine->First != TheLine->Last &&
291 TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
292 return Style.AllowShortBlocksOnASingleLine
293 ? tryMergeSimpleBlock(I, E, Limit)
297 if (I[1]->First->is(tok::l_brace) &&
298 TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
299 return Style.BraceWrapping.AfterControlStatement
300 ? tryMergeSimpleBlock(I, E, Limit)
305 if (TheLine->First->is(tok::l_brace) && TheLine->First == TheLine->Last &&
306 I != AnnotatedLines.begin() &&
307 I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
308 unsigned MergedLines = 0;
309 if (Style.AllowShortBlocksOnASingleLine) {
310 MergedLines = tryMergeSimpleBlock(I - 1, E, Limit);
319 if (TheLine->First->is(tok::l_brace) && I != AnnotatedLines.begin() &&
320 I[-1]->First->is(tok::at) && I[-1]->First->Next) {
322 if (kwId == clang::tok::objc_autoreleasepool ||
323 kwId == clang::tok::objc_synchronized)
327 if (TheLine->First->is(tok::l_brace) && I != AnnotatedLines.begin() &&
328 I[-1]->First->isOneOf(tok::kw_case, tok::kw_default))
331 if (TheLine->Last->is(tok::l_brace)) {
332 return !Style.BraceWrapping.AfterFunction ||
333 (I[1]->First->is(tok::r_brace) &&
334 !Style.BraceWrapping.SplitEmptyRecord)
335 ? tryMergeSimpleBlock(I, E, Limit)
339 if (I[1]->First->is(TT_FunctionLBrace) &&
340 Style.BraceWrapping.AfterFunction) {
341 if (I[1]->Last->is(TT_LineComment))
345 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
349 unsigned MergedLines = 0;
350 if (MergeShortFunctions ||
352 I[1]->First == I[1]->Last && I + 2 != E &&
353 I[2]->First->is(tok::r_brace))) {
354 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
362 if (TheLine->First->is(tok::kw_if)) {
363 return Style.AllowShortIfStatementsOnASingleLine
364 ? tryMergeSimpleControlStatement(I, E, Limit)
367 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
368 return Style.AllowShortLoopsOnASingleLine
369 ? tryMergeSimpleControlStatement(I, E, Limit)
372 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
373 return Style.AllowShortCaseLabelsOnASingleLine
374 ? tryMergeShortCaseLabels(I, E, Limit)
377 if (TheLine->InPPDirective &&
378 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
379 return tryMergeSimplePPDirective(I, E, Limit);
385 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
386 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
390 if (I + 2 != E && I[2]->
InPPDirective && !I[2]->First->HasUnescapedNewline)
392 if (1 + I[1]->Last->TotalLength > Limit)
397 unsigned tryMergeSimpleControlStatement(
398 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
399 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
unsigned Limit) {
402 if (Style.BraceWrapping.AfterControlStatement &&
403 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
406 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
408 Limit = limitConsideringMacros(I + 1, E, Limit);
409 AnnotatedLine &Line = **I;
410 if (Line.Last->isNot(tok::r_paren))
412 if (1 + I[1]->Last->TotalLength > Limit)
414 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
418 if (I + 2 != E && Line.startsWith(tok::kw_if) &&
419 I[2]->First->is(tok::kw_else))
425 tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
426 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
428 if (Limit == 0 || I + 1 == E ||
429 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
431 if (I[0]->Last->is(tok::l_brace) || I[1]->First->is(tok::l_brace))
433 unsigned NumStmts = 0;
435 bool EndsWithComment =
false;
437 const unsigned Level = I[0]->Level;
438 for (; NumStmts < 3; ++NumStmts) {
439 if (I + 1 + NumStmts == E)
441 const AnnotatedLine *Line = I[1 + NumStmts];
442 if (Line->InPPDirective != InPPDirective)
444 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
446 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
450 if (Line->First->is(tok::comment)) {
451 if (Level != Line->Level)
453 SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts;
454 for (; J != E; ++J) {
456 if (Line->InPPDirective != InPPDirective)
458 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
460 if (Line->First->isNot(tok::comment) || Level != Line->Level)
465 if (Line->Last->is(tok::comment))
466 EndsWithComment =
true;
467 Length += I[1 + NumStmts]->Last->TotalLength + 1;
469 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
475 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
476 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
478 AnnotatedLine &Line = **I;
484 Line.First->isOneOf(tok::at, tok::minus, tok::plus))
489 if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
490 (Line.First->Next && Line.First->Next->is(tok::kw_else)))
493 if (Line.First->is(tok::kw_default)) {
495 if (Tok && Tok->is(tok::colon))
498 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
499 tok::kw___try, tok::kw_catch, tok::kw___finally,
500 tok::kw_for, tok::r_brace, Keywords.kw___except)) {
501 if (!Style.AllowShortBlocksOnASingleLine)
505 if (!Style.AllowShortIfStatementsOnASingleLine &&
506 Line.startsWith(tok::kw_if) &&
507 !Style.BraceWrapping.AfterControlStatement &&
508 !I[1]->First->is(tok::r_brace))
510 if (!Style.AllowShortIfStatementsOnASingleLine &&
511 Line.startsWith(tok::kw_if) &&
512 Style.BraceWrapping.AfterControlStatement && I + 2 != E &&
513 !I[2]->First->is(tok::r_brace))
515 if (!Style.AllowShortLoopsOnASingleLine &&
516 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
517 !Style.BraceWrapping.AfterControlStatement &&
518 !I[1]->First->is(tok::r_brace))
520 if (!Style.AllowShortLoopsOnASingleLine &&
521 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
522 Style.BraceWrapping.AfterControlStatement && I + 2 != E &&
523 !I[2]->First->is(tok::r_brace))
530 if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
531 Keywords.kw___except, tok::kw___finally))
535 if (Line.Last->is(tok::l_brace)) {
536 FormatToken *
Tok = I[1]->First;
537 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
538 (Tok->getNextNonComment() ==
nullptr ||
539 Tok->getNextNonComment()->is(tok::semi))) {
542 Tok->CanBreakBefore =
true;
544 }
else if (Limit != 0 && !Line.startsWithNamespace() &&
545 !startsExternCBlock(Line)) {
547 FormatToken *RecordTok = Line.First;
549 while (RecordTok->Next &&
550 RecordTok->isOneOf(tok::kw_typedef, tok::kw_export,
551 Keywords.kw_declare, Keywords.kw_abstract,
553 RecordTok = RecordTok->Next;
555 RecordTok->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
556 Keywords.kw_interface))
562 Limit = limitConsideringMacros(I + 2, E, Limit);
564 if (!nextTwoLinesFitInto(I, Limit))
569 if (I[1]->Last->is(TT_LineComment))
572 if (Tok->is(tok::l_brace) && Tok->BlockKind !=
BK_BracedInit)
579 if (Tok->isNot(tok::r_brace))
583 if (Tok->Next && Tok->Next->is(tok::kw_else))
588 }
else if (I[1]->First->is(tok::l_brace)) {
589 if (I[1]->Last->is(TT_LineComment))
593 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
596 unsigned MergedLines = 0;
597 if (Style.AllowShortBlocksOnASingleLine ||
598 (I[1]->First == I[1]->Last && I + 2 != E &&
599 I[2]->First->is(tok::r_brace))) {
600 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
614 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
615 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
618 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(
tok::eof)) {
619 return Limit < 2 ? 0 : Limit - 2;
624 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
626 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
628 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
631 bool containsMustBreak(
const AnnotatedLine *Line) {
639 void join(AnnotatedLine &A,
const AnnotatedLine &B) {
640 assert(!A.Last->Next);
641 assert(!B.First->Previous);
644 A.Last->Next = B.First;
645 B.First->Previous = A.Last;
646 B.First->CanBreakBefore =
true;
647 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
654 const FormatStyle &
Style;
655 const AdditionalKeywords &Keywords;
656 const SmallVectorImpl<AnnotatedLine *>::const_iterator
End;
658 SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
659 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
662 static void markFinalized(FormatToken *
Tok) {
664 Tok->Finalized =
true;
665 for (AnnotatedLine *Child : Tok->Children)
666 markFinalized(Child->First);
671 static void printLineState(
const LineState &
State) {
672 llvm::dbgs() <<
"State: ";
673 for (
const ParenState &
P : State.Stack) {
674 llvm::dbgs() << (P.Tok ? P.Tok->TokenText :
"F") <<
"|" << P.Indent <<
"|" 675 << P.LastSpace <<
"|" << P.NestedBlockIndent <<
" ";
677 llvm::dbgs() << State.NextToken->TokenText <<
"\n";
682 class LineFormatter {
684 LineFormatter(ContinuationIndenter *
Indenter, WhitespaceManager *Whitespaces,
685 const FormatStyle &
Style,
686 UnwrappedLineFormatter *BlockFormatter)
687 :
Indenter(Indenter), Whitespaces(Whitespaces),
Style(Style),
688 BlockFormatter(BlockFormatter) {}
689 virtual ~LineFormatter() {}
694 virtual unsigned formatLine(
const AnnotatedLine &Line,
695 unsigned FirstIndent,
696 unsigned FirstStartColumn,
720 bool formatChildren(LineState &State,
bool NewLine,
bool DryRun,
722 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
723 FormatToken &
Previous = *State.NextToken->Previous;
724 if (!LBrace || LBrace->isNot(tok::l_brace) ||
725 LBrace->BlockKind !=
BK_Block || Previous.Children.size() == 0)
731 int AdditionalIndent = State.Stack.back().Indent -
732 Previous.Children[0]->Level * Style.IndentWidth;
735 BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
740 if (Previous.Children[0]->First->MustBreakBefore)
744 if (Previous.is(tok::comment))
748 if (Previous.Children.size() > 1)
751 const AnnotatedLine *Child = Previous.Children[0];
753 if (Child->Last->isTrailingComment())
758 if (Style.ColumnLimit > 0 &&
759 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit)
763 Whitespaces->replaceWhitespace(
765 State.Column, State.Line->InPPDirective);
768 formatLine(*Child, State.Column + 1, 0, DryRun);
770 State.Column += 1 + Child->Last->TotalLength;
777 WhitespaceManager *Whitespaces;
778 const FormatStyle &
Style;
779 UnwrappedLineFormatter *BlockFormatter;
783 class NoColumnLimitLineFormatter :
public LineFormatter {
785 NoColumnLimitLineFormatter(ContinuationIndenter *
Indenter,
786 WhitespaceManager *Whitespaces,
787 const FormatStyle &
Style,
788 UnwrappedLineFormatter *BlockFormatter)
789 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
793 unsigned formatLine(
const AnnotatedLine &Line,
unsigned FirstIndent,
794 unsigned FirstStartColumn,
bool DryRun)
override {
796 LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
798 while (State.NextToken) {
800 Indenter->mustBreak(State) ||
801 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
802 unsigned Penalty = 0;
803 formatChildren(State, Newline,
false, Penalty);
804 Indenter->addTokenToState(State, Newline,
false);
811 class NoLineBreakFormatter :
public LineFormatter {
813 NoLineBreakFormatter(ContinuationIndenter *
Indenter,
814 WhitespaceManager *Whitespaces,
const FormatStyle &
Style,
815 UnwrappedLineFormatter *BlockFormatter)
816 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
819 unsigned formatLine(
const AnnotatedLine &Line,
unsigned FirstIndent,
820 unsigned FirstStartColumn,
bool DryRun)
override {
821 unsigned Penalty = 0;
823 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
824 while (State.NextToken) {
825 formatChildren(State,
false, DryRun, Penalty);
826 Indenter->addTokenToState(
827 State, State.NextToken->MustBreakBefore, DryRun);
834 class OptimizingLineFormatter :
public LineFormatter {
836 OptimizingLineFormatter(ContinuationIndenter *
Indenter,
837 WhitespaceManager *Whitespaces,
838 const FormatStyle &
Style,
839 UnwrappedLineFormatter *BlockFormatter)
840 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
844 unsigned formatLine(
const AnnotatedLine &Line,
unsigned FirstIndent,
845 unsigned FirstStartColumn,
bool DryRun)
override {
847 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
852 State.Stack.back().BreakBeforeParameter =
true;
855 return analyzeSolutionSpace(State, DryRun);
859 struct CompareLineStatePointers {
860 bool operator()(LineState *obj1, LineState *obj2)
const {
861 return *obj1 < *obj2;
870 typedef std::pair<unsigned, unsigned> OrderedPenalty;
884 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
887 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
888 std::greater<QueueItem>>
899 unsigned analyzeSolutionSpace(LineState &InitialState,
bool DryRun) {
900 std::set<LineState *, CompareLineStatePointers> Seen;
909 new (Allocator.Allocate()) StateNode(InitialState,
false,
nullptr);
910 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
913 unsigned Penalty = 0;
916 while (!Queue.empty()) {
917 Penalty = Queue.top().first.first;
918 StateNode *Node = Queue.top().second;
919 if (!Node->State.NextToken) {
920 LLVM_DEBUG(llvm::dbgs()
921 <<
"\n---\nPenalty for line: " << Penalty <<
"\n");
929 Node->State.IgnoreStackForComparison =
true;
931 if (!Seen.insert(&Node->State).second)
937 addNextStateToQueue(Penalty, Node,
false, &Count, &Queue);
939 addNextStateToQueue(Penalty, Node,
true, &Count, &Queue);
945 LLVM_DEBUG(llvm::dbgs() <<
"Could not find a solution.\n");
951 reconstructPath(InitialState, Queue.top().second);
953 LLVM_DEBUG(llvm::dbgs()
954 <<
"Total number of analyzed states: " << Count <<
"\n");
955 LLVM_DEBUG(llvm::dbgs() <<
"---\n");
964 void addNextStateToQueue(
unsigned Penalty, StateNode *PreviousNode,
965 bool NewLine,
unsigned *Count, QueueType *Queue) {
966 if (NewLine && !Indenter->canBreak(PreviousNode->State))
968 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
971 StateNode *
Node =
new (Allocator.Allocate())
972 StateNode(PreviousNode->State, NewLine, PreviousNode);
973 if (!formatChildren(Node->State, NewLine,
true, Penalty))
976 Penalty += Indenter->addTokenToState(Node->State, NewLine,
true);
978 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
984 void reconstructPath(LineState &State, StateNode *Best) {
985 std::deque<StateNode *> Path;
987 while (Best->Previous) {
988 Path.push_front(Best);
989 Best = Best->Previous;
991 for (
auto I = Path.begin(), E = Path.end(); I != E; ++I) {
992 unsigned Penalty = 0;
993 formatChildren(State, (*I)->NewLine,
false, Penalty);
994 Penalty += Indenter->addTokenToState(State, (*I)->NewLine,
false);
997 printLineState((*I)->Previous->State);
999 llvm::dbgs() <<
"Penalty for placing " 1000 << (*I)->Previous->State.NextToken->Tok.getName()
1001 <<
" on a new line: " << Penalty <<
"\n";
1007 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1014 bool DryRun,
int AdditionalIndent,
1015 bool FixBadIndentation,
1016 unsigned FirstStartColumn,
1017 unsigned NextStartColumn,
1018 unsigned LastStartColumn) {
1019 LineJoiner Joiner(
Style, Keywords, Lines);
1022 std::pair<const SmallVectorImpl<AnnotatedLine *> *,
unsigned> CacheKey(
1023 &Lines, AdditionalIndent);
1024 auto CacheIt = PenaltyCache.find(CacheKey);
1025 if (DryRun && CacheIt != PenaltyCache.end())
1026 return CacheIt->second;
1028 assert(!Lines.empty());
1029 unsigned Penalty = 0;
1030 LevelIndentTracker IndentTracker(
Style, Keywords, Lines[0]->
Level,
1038 bool FirstLine =
true;
1040 Joiner.getNextMergedLine(DryRun, IndentTracker);
1041 Line;
Line = NextLine, FirstLine =
false) {
1043 unsigned Indent = IndentTracker.getIndent();
1049 bool PreviousRBrace =
1050 PreviousLine && PreviousLine->
startsWith(tok::r_brace);
1051 bool ContinueFormatting =
1052 TheLine.
Level > RangeMinLevel ||
1053 (TheLine.
Level == RangeMinLevel && !PreviousRBrace &&
1056 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
1058 bool ShouldFormat = TheLine.
Affected || FixIndentation;
1062 Status->FormatComplete =
false;
1070 formatFirstToken(TheLine, PreviousLine, Lines, Indent,
1071 LastLine ? LastStartColumn : NextStartColumn + Indent);
1074 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1075 unsigned ColumnLimit = getColumnLimit(TheLine.
InPPDirective, NextLine);
1076 bool FitsIntoOneLine =
1082 NoColumnLimitLineFormatter(
Indenter, Whitespaces,
Style,
this)
1083 .formatLine(TheLine, NextStartColumn + Indent,
1084 FirstLine ? FirstStartColumn : 0, DryRun);
1085 else if (FitsIntoOneLine)
1086 Penalty += NoLineBreakFormatter(
Indenter, Whitespaces,
Style,
this)
1087 .formatLine(TheLine, NextStartColumn + Indent,
1088 FirstLine ? FirstStartColumn : 0, DryRun);
1090 Penalty += OptimizingLineFormatter(
Indenter, Whitespaces,
Style,
this)
1091 .formatLine(TheLine, NextStartColumn + Indent,
1092 FirstLine ? FirstStartColumn : 0, DryRun);
1104 bool StartsNewLine =
1107 IndentTracker.adjustToUnmodifiedLine(TheLine);
1109 bool ReformatLeadingWhitespace =
1110 StartsNewLine && ((PreviousLine && PreviousLine->
Affected) ||
1113 if (ReformatLeadingWhitespace)
1114 formatFirstToken(TheLine, PreviousLine, Lines,
1118 Whitespaces->addUntouchableToken(*TheLine.
First,
1125 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1129 markFinalized(TheLine.
First);
1130 PreviousLine = &TheLine;
1132 PenaltyCache[CacheKey] = Penalty;
1136 void UnwrappedLineFormatter::formatFirstToken(
1139 unsigned NewlineIndent) {
1143 unsigned TokenIndent = Newlines ? NewlineIndent : 0;
1144 Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
1151 if (RootToken.
is(tok::r_brace) &&
1158 if (PreviousLine ==
nullptr && Line.
Level > 0)
1160 if (Newlines == 0 && !RootToken.
IsFirst)
1167 PreviousLine->
Last->
is(tok::l_brace) &&
1169 !startsExternCBlock(*PreviousLine))
1173 if (PreviousLine && PreviousLine->
Last->
isOneOf(tok::semi, tok::r_brace) &&
1183 Indent = NewlineIndent;
1189 Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent,
1199 bool ContinuesPPDirective =
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
WhitespaceManager class manages whitespace around tokens and their replacements.
const AnnotatedLine * Line
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
ObjCKeywordKind
Provides a namespace for Objective-C keywords which start with an '@'.
ast_type_traits::DynTypedNode Node
Optional< types::ID > Type
Dataflow Directional Tag Classes.
__DEVICE__ int min(int __a, int __b)