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))
197 if (I[1]->Type ==
LT_Invalid || I[1]->First->MustBreakBefore)
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->Last->is(tok::l_brace)) {
328 return !Style.BraceWrapping.AfterFunction ||
329 (I[1]->First->is(tok::r_brace) &&
330 !Style.BraceWrapping.SplitEmptyRecord)
331 ? tryMergeSimpleBlock(I, E, Limit)
335 if (I[1]->First->is(TT_FunctionLBrace) &&
336 Style.BraceWrapping.AfterFunction) {
337 if (I[1]->Last->is(TT_LineComment))
341 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
345 unsigned MergedLines = 0;
346 if (MergeShortFunctions ||
348 I[1]->First == I[1]->Last && I + 2 != E &&
349 I[2]->First->is(tok::r_brace))) {
350 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
358 if (TheLine->First->is(tok::kw_if)) {
359 return Style.AllowShortIfStatementsOnASingleLine
360 ? tryMergeSimpleControlStatement(I, E, Limit)
363 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
364 return Style.AllowShortLoopsOnASingleLine
365 ? tryMergeSimpleControlStatement(I, E, Limit)
368 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
369 return Style.AllowShortCaseLabelsOnASingleLine
370 ? tryMergeShortCaseLabels(I, E, Limit)
373 if (TheLine->InPPDirective &&
374 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
375 return tryMergeSimplePPDirective(I, E, Limit);
381 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
382 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
386 if (I + 2 != E && I[2]->
InPPDirective && !I[2]->First->HasUnescapedNewline)
388 if (1 + I[1]->Last->TotalLength > Limit)
393 unsigned tryMergeSimpleControlStatement(
394 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
395 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
unsigned Limit) {
398 if (Style.BraceWrapping.AfterControlStatement &&
399 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
402 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
404 Limit = limitConsideringMacros(I + 1, E, Limit);
405 AnnotatedLine &Line = **I;
406 if (Line.Last->isNot(tok::r_paren))
408 if (1 + I[1]->Last->TotalLength > Limit)
410 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
414 if (I + 2 != E && Line.startsWith(tok::kw_if) &&
415 I[2]->First->is(tok::kw_else))
421 tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
422 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
424 if (Limit == 0 || I + 1 == E ||
425 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
427 unsigned NumStmts = 0;
429 bool EndsWithComment =
false;
431 const unsigned Level = I[0]->Level;
432 for (; NumStmts < 3; ++NumStmts) {
433 if (I + 1 + NumStmts == E)
435 const AnnotatedLine *Line = I[1 + NumStmts];
436 if (Line->InPPDirective != InPPDirective)
438 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
440 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
444 if (Line->First->is(tok::comment)) {
445 if (Level != Line->Level)
447 SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts;
448 for (; J != E; ++J) {
450 if (Line->InPPDirective != InPPDirective)
452 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
454 if (Line->First->isNot(tok::comment) || Level != Line->Level)
459 if (Line->Last->is(tok::comment))
460 EndsWithComment =
true;
461 Length += I[1 + NumStmts]->Last->TotalLength + 1;
463 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
469 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
470 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
472 AnnotatedLine &Line = **I;
478 Line.First->isOneOf(tok::at, tok::minus, tok::plus))
483 if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
484 (Line.First->Next && Line.First->Next->is(tok::kw_else)))
486 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
487 tok::kw___try, tok::kw_catch, tok::kw___finally,
488 tok::kw_for, tok::r_brace, Keywords.kw___except)) {
489 if (!Style.AllowShortBlocksOnASingleLine)
493 if (!Style.AllowShortIfStatementsOnASingleLine &&
494 Line.startsWith(tok::kw_if) &&
495 !Style.BraceWrapping.AfterControlStatement &&
496 !I[1]->First->is(tok::r_brace))
498 if (!Style.AllowShortIfStatementsOnASingleLine &&
499 Line.startsWith(tok::kw_if) &&
500 Style.BraceWrapping.AfterControlStatement && I + 2 != E &&
501 !I[2]->First->is(tok::r_brace))
503 if (!Style.AllowShortLoopsOnASingleLine &&
504 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
505 !Style.BraceWrapping.AfterControlStatement &&
506 !I[1]->First->is(tok::r_brace))
508 if (!Style.AllowShortLoopsOnASingleLine &&
509 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
510 Style.BraceWrapping.AfterControlStatement && I + 2 != E &&
511 !I[2]->First->is(tok::r_brace))
518 if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
519 Keywords.kw___except, tok::kw___finally))
523 if (Line.Last->is(tok::l_brace)) {
524 FormatToken *
Tok = I[1]->First;
525 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
526 (Tok->getNextNonComment() ==
nullptr ||
527 Tok->getNextNonComment()->is(tok::semi))) {
530 Tok->CanBreakBefore =
true;
532 }
else if (Limit != 0 && !Line.startsWith(tok::kw_namespace) &&
533 !startsExternCBlock(Line)) {
535 FormatToken *RecordTok = Line.First;
537 while (RecordTok->Next &&
538 RecordTok->isOneOf(tok::kw_typedef, tok::kw_export,
539 Keywords.kw_declare, Keywords.kw_abstract,
541 RecordTok = RecordTok->Next;
543 RecordTok->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
544 Keywords.kw_interface))
550 Limit = limitConsideringMacros(I + 2, E, Limit);
552 if (!nextTwoLinesFitInto(I, Limit))
557 if (I[1]->Last->is(TT_LineComment))
560 if (Tok->is(tok::l_brace) && Tok->BlockKind !=
BK_BracedInit)
567 if (Tok->isNot(tok::r_brace))
571 if (Tok->Next && Tok->Next->is(tok::kw_else))
576 }
else if (I[1]->First->is(tok::l_brace)) {
577 if (I[1]->Last->is(TT_LineComment))
581 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
584 unsigned MergedLines = 0;
585 if (Style.AllowShortBlocksOnASingleLine ||
586 (I[1]->First == I[1]->Last && I + 2 != E &&
587 I[2]->First->is(tok::r_brace))) {
588 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
602 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
603 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
606 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(
tok::eof)) {
607 return Limit < 2 ? 0 : Limit - 2;
612 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
614 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
616 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
619 bool containsMustBreak(
const AnnotatedLine *Line) {
627 void join(AnnotatedLine &A,
const AnnotatedLine &B) {
628 assert(!A.Last->Next);
629 assert(!B.First->Previous);
632 A.Last->Next = B.First;
633 B.First->Previous = A.Last;
634 B.First->CanBreakBefore =
true;
635 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
642 const FormatStyle &
Style;
643 const AdditionalKeywords &Keywords;
644 const SmallVectorImpl<AnnotatedLine *>::const_iterator
End;
646 SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
647 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
650 static void markFinalized(FormatToken *
Tok) {
652 Tok->Finalized =
true;
653 for (AnnotatedLine *Child : Tok->Children)
654 markFinalized(Child->First);
659 static void printLineState(
const LineState &
State) {
660 llvm::dbgs() <<
"State: ";
661 for (
const ParenState &
P : State.Stack) {
662 llvm::dbgs() << (P.Tok ? P.Tok->TokenText :
"F") <<
"|" << P.Indent <<
"|" 663 << P.LastSpace <<
"|" << P.NestedBlockIndent <<
" ";
665 llvm::dbgs() << State.NextToken->TokenText <<
"\n";
670 class LineFormatter {
672 LineFormatter(ContinuationIndenter *
Indenter, WhitespaceManager *Whitespaces,
673 const FormatStyle &
Style,
674 UnwrappedLineFormatter *BlockFormatter)
675 :
Indenter(Indenter), Whitespaces(Whitespaces),
Style(Style),
676 BlockFormatter(BlockFormatter) {}
677 virtual ~LineFormatter() {}
682 virtual unsigned formatLine(
const AnnotatedLine &Line,
683 unsigned FirstIndent,
684 unsigned FirstStartColumn,
708 bool formatChildren(LineState &State,
bool NewLine,
bool DryRun,
710 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
711 FormatToken &
Previous = *State.NextToken->Previous;
712 if (!LBrace || LBrace->isNot(tok::l_brace) ||
713 LBrace->BlockKind !=
BK_Block || Previous.Children.size() == 0)
719 int AdditionalIndent = State.Stack.back().Indent -
720 Previous.Children[0]->Level * Style.IndentWidth;
723 BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
728 if (Previous.Children[0]->First->MustBreakBefore)
732 if (Previous.is(tok::comment))
736 if (Previous.Children.size() > 1)
739 const AnnotatedLine *Child = Previous.Children[0];
741 if (Child->Last->isTrailingComment())
746 if (Style.ColumnLimit > 0 &&
747 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit)
751 Whitespaces->replaceWhitespace(
753 State.Column, State.Line->InPPDirective);
756 formatLine(*Child, State.Column + 1, 0, DryRun);
758 State.Column += 1 + Child->Last->TotalLength;
765 WhitespaceManager *Whitespaces;
766 const FormatStyle &
Style;
767 UnwrappedLineFormatter *BlockFormatter;
771 class NoColumnLimitLineFormatter :
public LineFormatter {
773 NoColumnLimitLineFormatter(ContinuationIndenter *
Indenter,
774 WhitespaceManager *Whitespaces,
775 const FormatStyle &
Style,
776 UnwrappedLineFormatter *BlockFormatter)
777 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
781 unsigned formatLine(
const AnnotatedLine &Line,
unsigned FirstIndent,
782 unsigned FirstStartColumn,
bool DryRun)
override {
784 LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
786 while (State.NextToken) {
788 Indenter->mustBreak(State) ||
789 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
790 unsigned Penalty = 0;
791 formatChildren(State, Newline,
false, Penalty);
792 Indenter->addTokenToState(State, Newline,
false);
799 class NoLineBreakFormatter :
public LineFormatter {
801 NoLineBreakFormatter(ContinuationIndenter *
Indenter,
802 WhitespaceManager *Whitespaces,
const FormatStyle &
Style,
803 UnwrappedLineFormatter *BlockFormatter)
804 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
807 unsigned formatLine(
const AnnotatedLine &Line,
unsigned FirstIndent,
808 unsigned FirstStartColumn,
bool DryRun)
override {
809 unsigned Penalty = 0;
811 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
812 while (State.NextToken) {
813 formatChildren(State,
false, DryRun, Penalty);
814 Indenter->addTokenToState(
815 State, State.NextToken->MustBreakBefore, DryRun);
822 class OptimizingLineFormatter :
public LineFormatter {
824 OptimizingLineFormatter(ContinuationIndenter *
Indenter,
825 WhitespaceManager *Whitespaces,
826 const FormatStyle &
Style,
827 UnwrappedLineFormatter *BlockFormatter)
828 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
832 unsigned formatLine(
const AnnotatedLine &Line,
unsigned FirstIndent,
833 unsigned FirstStartColumn,
bool DryRun)
override {
835 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
840 State.Stack.back().BreakBeforeParameter =
true;
843 return analyzeSolutionSpace(State, DryRun);
847 struct CompareLineStatePointers {
848 bool operator()(LineState *obj1, LineState *obj2)
const {
849 return *obj1 < *obj2;
858 typedef std::pair<unsigned, unsigned> OrderedPenalty;
872 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
875 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
876 std::greater<QueueItem>>
887 unsigned analyzeSolutionSpace(LineState &InitialState,
bool DryRun) {
888 std::set<LineState *, CompareLineStatePointers> Seen;
897 new (Allocator.Allocate()) StateNode(InitialState,
false,
nullptr);
898 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
901 unsigned Penalty = 0;
904 while (!Queue.empty()) {
905 Penalty = Queue.top().first.first;
906 StateNode *Node = Queue.top().second;
907 if (!Node->State.NextToken) {
908 LLVM_DEBUG(llvm::dbgs()
909 <<
"\n---\nPenalty for line: " << Penalty <<
"\n");
917 Node->State.IgnoreStackForComparison =
true;
919 if (!Seen.insert(&Node->State).second)
925 addNextStateToQueue(Penalty, Node,
false, &Count, &Queue);
927 addNextStateToQueue(Penalty, Node,
true, &Count, &Queue);
933 LLVM_DEBUG(llvm::dbgs() <<
"Could not find a solution.\n");
939 reconstructPath(InitialState, Queue.top().second);
941 LLVM_DEBUG(llvm::dbgs()
942 <<
"Total number of analyzed states: " << Count <<
"\n");
943 LLVM_DEBUG(llvm::dbgs() <<
"---\n");
952 void addNextStateToQueue(
unsigned Penalty, StateNode *PreviousNode,
953 bool NewLine,
unsigned *Count, QueueType *Queue) {
954 if (NewLine && !Indenter->canBreak(PreviousNode->State))
956 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
959 StateNode *
Node =
new (Allocator.Allocate())
960 StateNode(PreviousNode->State, NewLine, PreviousNode);
961 if (!formatChildren(Node->State, NewLine,
true, Penalty))
964 Penalty += Indenter->addTokenToState(Node->State, NewLine,
true);
966 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
972 void reconstructPath(LineState &State, StateNode *Best) {
973 std::deque<StateNode *> Path;
975 while (Best->Previous) {
976 Path.push_front(Best);
977 Best = Best->Previous;
979 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
981 unsigned Penalty = 0;
982 formatChildren(State, (*I)->NewLine,
false, Penalty);
983 Penalty += Indenter->addTokenToState(State, (*I)->NewLine,
false);
986 printLineState((*I)->Previous->State);
988 llvm::dbgs() <<
"Penalty for placing " 989 << (*I)->Previous->State.NextToken->Tok.getName() <<
": " 996 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1003 bool DryRun,
int AdditionalIndent,
1004 bool FixBadIndentation,
1005 unsigned FirstStartColumn,
1006 unsigned NextStartColumn,
1007 unsigned LastStartColumn) {
1008 LineJoiner Joiner(
Style, Keywords, Lines);
1011 std::pair<const SmallVectorImpl<AnnotatedLine *> *,
unsigned> CacheKey(
1012 &Lines, AdditionalIndent);
1013 auto CacheIt = PenaltyCache.find(CacheKey);
1014 if (DryRun && CacheIt != PenaltyCache.end())
1015 return CacheIt->second;
1017 assert(!Lines.empty());
1018 unsigned Penalty = 0;
1019 LevelIndentTracker IndentTracker(
Style, Keywords, Lines[0]->
Level,
1027 bool FirstLine =
true;
1029 Joiner.getNextMergedLine(DryRun, IndentTracker);
1030 Line;
Line = NextLine, FirstLine =
false) {
1032 unsigned Indent = IndentTracker.getIndent();
1038 bool PreviousRBrace =
1039 PreviousLine && PreviousLine->
startsWith(tok::r_brace);
1040 bool ContinueFormatting =
1041 TheLine.
Level > RangeMinLevel ||
1042 (TheLine.
Level == RangeMinLevel && !PreviousRBrace &&
1045 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
1047 bool ShouldFormat = TheLine.
Affected || FixIndentation;
1051 Status->FormatComplete =
false;
1059 formatFirstToken(TheLine, PreviousLine, Lines, Indent,
1060 LastLine ? LastStartColumn : NextStartColumn + Indent);
1063 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1064 unsigned ColumnLimit = getColumnLimit(TheLine.
InPPDirective, NextLine);
1065 bool FitsIntoOneLine =
1071 NoColumnLimitLineFormatter(
Indenter, Whitespaces,
Style,
this)
1072 .formatLine(TheLine, NextStartColumn + Indent,
1073 FirstLine ? FirstStartColumn : 0, DryRun);
1074 else if (FitsIntoOneLine)
1075 Penalty += NoLineBreakFormatter(
Indenter, Whitespaces,
Style,
this)
1076 .formatLine(TheLine, NextStartColumn + Indent,
1077 FirstLine ? FirstStartColumn : 0, DryRun);
1079 Penalty += OptimizingLineFormatter(
Indenter, Whitespaces,
Style,
this)
1080 .formatLine(TheLine, NextStartColumn + Indent,
1081 FirstLine ? FirstStartColumn : 0, DryRun);
1093 bool StartsNewLine =
1096 IndentTracker.adjustToUnmodifiedLine(TheLine);
1098 bool ReformatLeadingWhitespace =
1099 StartsNewLine && ((PreviousLine && PreviousLine->
Affected) ||
1102 if (ReformatLeadingWhitespace)
1103 formatFirstToken(TheLine, PreviousLine, Lines,
1107 Whitespaces->addUntouchableToken(*TheLine.
First,
1114 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1118 markFinalized(TheLine.
First);
1119 PreviousLine = &TheLine;
1121 PenaltyCache[CacheKey] = Penalty;
1125 void UnwrappedLineFormatter::formatFirstToken(
1128 unsigned NewlineIndent) {
1132 unsigned TokenIndent = Newlines ? NewlineIndent : 0;
1133 Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
1140 if (RootToken.
is(tok::r_brace) &&
1147 if (PreviousLine ==
nullptr && Line.
Level > 0)
1149 if (Newlines == 0 && !RootToken.
IsFirst)
1156 PreviousLine->
Last->
is(tok::l_brace) &&
1157 PreviousLine->
First->
isNot(tok::kw_namespace) &&
1158 !startsExternCBlock(*PreviousLine))
1162 if (PreviousLine && PreviousLine->
Last->
isOneOf(tok::semi, tok::r_brace) &&
1172 Indent = NewlineIndent;
1178 Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent,
1188 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
Dataflow Directional Tag Classes.
__DEVICE__ int min(int __a, int __b)