12 #include "llvm/Support/Debug.h" 15 #define DEBUG_TYPE "format-formatter" 22 bool startsExternCBlock(
const AnnotatedLine &
Line) {
23 const FormatToken *Next = Line.First->getNextNonComment();
24 const FormatToken *NextNext = Next ? Next->getNextNonComment() :
nullptr;
25 return Line.startsWith(tok::kw_extern) && Next && Next->isStringLiteral() &&
26 NextNext && NextNext->is(tok::l_brace);
38 class LevelIndentTracker {
40 LevelIndentTracker(
const FormatStyle &
Style,
41 const AdditionalKeywords &Keywords,
unsigned StartLevel,
43 :
Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) {
44 for (
unsigned i = 0; i != StartLevel; ++i)
45 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
49 unsigned getIndent()
const {
return Indent; }
53 void nextLine(
const AnnotatedLine &Line) {
54 Offset = getIndentOffset(*Line.First);
57 while (IndentForLevel.size() <= Line.Level)
58 IndentForLevel.push_back(-1);
59 if (Line.InPPDirective) {
60 Indent = Line.Level * Style.IndentWidth + AdditionalIndent;
62 IndentForLevel.resize(Line.Level + 1);
63 Indent = getIndent(IndentForLevel, Line.Level);
65 if (static_cast<int>(Indent) +
Offset >= 0)
71 void skipLine(
const AnnotatedLine &Line) {
72 while (IndentForLevel.size() <= Line.Level)
73 IndentForLevel.push_back(Indent);
81 void adjustToUnmodifiedLine(
const AnnotatedLine &Line) {
82 unsigned LevelIndent = Line.First->OriginalColumn;
83 if (static_cast<int>(LevelIndent) -
Offset >= 0)
85 if ((!Line.First->is(tok::comment) || IndentForLevel[Line.Level] == -1) &&
87 IndentForLevel[Line.Level] = LevelIndent;
95 int getIndentOffset(
const FormatToken &RootToken) {
99 if (RootToken.isAccessSpecifier(
false) ||
100 RootToken.isObjCAccessSpecifier() ||
101 (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
102 RootToken.Next && RootToken.Next->is(tok::colon)))
103 return Style.AccessModifierOffset;
112 unsigned getIndent(ArrayRef<int> IndentForLevel,
unsigned Level) {
113 if (IndentForLevel[Level] != -1)
114 return IndentForLevel[
Level];
117 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
120 const FormatStyle &
Style;
121 const AdditionalKeywords &Keywords;
122 const unsigned AdditionalIndent;
125 std::vector<int> IndentForLevel;
137 bool isNamespaceDeclaration(
const AnnotatedLine *Line) {
138 const FormatToken *NamespaceTok = Line->First;
139 return NamespaceTok && NamespaceTok->getNamespaceToken();
142 bool isEndOfNamespace(
const AnnotatedLine *Line,
143 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
144 if (!Line->startsWith(tok::r_brace))
146 size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex;
149 assert(StartLineIndex < AnnotatedLines.size());
150 return isNamespaceDeclaration(AnnotatedLines[StartLineIndex]);
155 LineJoiner(
const FormatStyle &
Style,
const AdditionalKeywords &Keywords,
156 const SmallVectorImpl<AnnotatedLine *> &Lines)
157 :
Style(Style), Keywords(Keywords),
End(Lines.end()), Next(Lines.begin()),
158 AnnotatedLines(Lines) {}
161 const AnnotatedLine *getNextMergedLine(
bool DryRun,
162 LevelIndentTracker &IndentTracker) {
165 const AnnotatedLine *Current = *Next;
166 IndentTracker.nextLine(*Current);
167 unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next,
End);
168 if (MergedLines > 0 && Style.ColumnLimit == 0)
171 for (
unsigned i = 0; i < MergedLines; ++i)
172 if (Next[i + 1]->First->NewlinesBefore > 0)
175 for (
unsigned i = 0; i < MergedLines; ++i)
176 join(*Next[0], *Next[i + 1]);
177 Next = Next + MergedLines + 1;
184 tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker,
185 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
186 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
187 const unsigned Indent = IndentTracker.getIndent();
193 const AnnotatedLine *TheLine = *I;
194 if (TheLine->Last->is(TT_LineComment))
196 if (I[1]->Type ==
LT_Invalid || I[1]->First->MustBreakBefore)
198 if (TheLine->InPPDirective &&
199 (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline))
202 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
206 Style.ColumnLimit == 0 ?
UINT_MAX : Style.ColumnLimit - Indent;
209 Limit = TheLine->Last->TotalLength > Limit
211 : Limit - TheLine->Last->TotalLength;
213 if (TheLine->Last->is(TT_FunctionLBrace) &&
214 TheLine->First == TheLine->Last &&
215 !Style.BraceWrapping.SplitEmptyFunction &&
216 I[1]->First->is(tok::r_brace))
217 return tryMergeSimpleBlock(I, E, Limit);
220 if (TheLine->Last->is(tok::l_brace) && TheLine->First == TheLine->Last &&
221 I != AnnotatedLines.begin()) {
222 bool EmptyBlock = I[1]->First->is(tok::r_brace);
224 const FormatToken *
Tok = I[-1]->First;
225 if (Tok && Tok->is(tok::comment))
228 if (Tok && Tok->getNamespaceToken())
229 return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock
230 ? tryMergeSimpleBlock(I, E, Limit)
233 if (Tok && Tok->is(tok::kw_typedef))
235 if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union,
236 tok::kw_extern, Keywords.kw_interface))
237 return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock
238 ? tryMergeSimpleBlock(I, E, Limit)
244 bool MergeShortFunctions =
247 I[1]->First->is(tok::r_brace)) ||
249 TheLine->Level != 0);
251 if (Style.CompactNamespaces) {
252 if (isNamespaceDeclaration(TheLine)) {
254 unsigned closingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
255 for (; I + 1 + i != E && isNamespaceDeclaration(I[i + 1]) &&
256 closingLine == I[i + 1]->MatchingOpeningBlockLineIndex &&
257 I[i + 1]->Last->TotalLength < Limit;
258 i++, closingLine--) {
260 IndentTracker.skipLine(*I[i + 1]);
262 Limit -= I[i + 1]->Last->TotalLength;
267 if (isEndOfNamespace(TheLine, AnnotatedLines)) {
269 unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
270 for (; I + 1 + i != E && isEndOfNamespace(I[i + 1], AnnotatedLines) &&
271 openingLine == I[i + 1]->MatchingOpeningBlockLineIndex;
272 i++, openingLine--) {
274 I[i + 1]->First->SpacesRequiredBefore = !I[i]->Last->is(tok::r_brace);
277 IndentTracker.nextLine(*I[i + 1]);
284 if (TheLine->Last->is(TT_FunctionLBrace) &&
285 TheLine->First != TheLine->Last) {
286 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
289 if (TheLine->Last->is(tok::l_brace) && TheLine->First != TheLine->Last &&
290 TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
291 return Style.AllowShortBlocksOnASingleLine
292 ? tryMergeSimpleBlock(I, E, Limit)
296 if (I[1]->First->is(tok::l_brace) &&
297 TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
298 return Style.BraceWrapping.AfterControlStatement
299 ? tryMergeSimpleBlock(I, E, Limit)
304 if (TheLine->First->is(tok::l_brace) && TheLine->First == TheLine->Last &&
305 I != AnnotatedLines.begin() &&
306 I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
307 return Style.AllowShortBlocksOnASingleLine
308 ? tryMergeSimpleBlock(I - 1, E, Limit)
312 if (TheLine->Last->is(tok::l_brace)) {
313 return !Style.BraceWrapping.AfterFunction ||
314 (I[1]->First->is(tok::r_brace) &&
315 !Style.BraceWrapping.SplitEmptyRecord)
316 ? tryMergeSimpleBlock(I, E, Limit)
320 if (I[1]->First->is(TT_FunctionLBrace) &&
321 Style.BraceWrapping.AfterFunction) {
322 if (I[1]->Last->is(TT_LineComment))
326 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
330 unsigned MergedLines = 0;
331 if (MergeShortFunctions ||
333 I[1]->First == I[1]->Last && I + 2 != E &&
334 I[2]->First->is(tok::r_brace))) {
335 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
343 if (TheLine->First->is(tok::kw_if)) {
344 return Style.AllowShortIfStatementsOnASingleLine
345 ? tryMergeSimpleControlStatement(I, E, Limit)
348 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
349 return Style.AllowShortLoopsOnASingleLine
350 ? tryMergeSimpleControlStatement(I, E, Limit)
353 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
354 return Style.AllowShortCaseLabelsOnASingleLine
355 ? tryMergeShortCaseLabels(I, E, Limit)
358 if (TheLine->InPPDirective &&
359 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
360 return tryMergeSimplePPDirective(I, E, Limit);
366 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
367 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
371 if (I + 2 != E && I[2]->
InPPDirective && !I[2]->First->HasUnescapedNewline)
373 if (1 + I[1]->Last->TotalLength > Limit)
378 unsigned tryMergeSimpleControlStatement(
379 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
380 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
unsigned Limit) {
383 if (Style.BraceWrapping.AfterControlStatement &&
384 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
387 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
389 Limit = limitConsideringMacros(I + 1, E, Limit);
390 AnnotatedLine &Line = **I;
391 if (Line.Last->isNot(tok::r_paren))
393 if (1 + I[1]->Last->TotalLength > Limit)
395 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
399 if (I + 2 != E && Line.startsWith(tok::kw_if) &&
400 I[2]->First->is(tok::kw_else))
406 tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
407 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
409 if (Limit == 0 || I + 1 == E ||
410 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
412 unsigned NumStmts = 0;
414 bool EndsWithComment =
false;
416 const unsigned Level = I[0]->Level;
417 for (; NumStmts < 3; ++NumStmts) {
418 if (I + 1 + NumStmts == E)
420 const AnnotatedLine *Line = I[1 + NumStmts];
421 if (Line->InPPDirective != InPPDirective)
423 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
425 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
429 if (Line->First->is(tok::comment)) {
430 if (Level != Line->Level)
432 SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts;
433 for (; J != E; ++J) {
435 if (Line->InPPDirective != InPPDirective)
437 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
439 if (Line->First->isNot(tok::comment) || Level != Line->Level)
444 if (Line->Last->is(tok::comment))
445 EndsWithComment =
true;
446 Length += I[1 + NumStmts]->Last->TotalLength + 1;
448 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
454 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
455 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
457 AnnotatedLine &Line = **I;
463 Line.First->isOneOf(tok::at, tok::minus, tok::plus))
468 if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
469 (Line.First->Next && Line.First->Next->is(tok::kw_else)))
471 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
472 tok::kw___try, tok::kw_catch, tok::kw___finally,
473 tok::kw_for, tok::r_brace, Keywords.kw___except)) {
474 if (!Style.AllowShortBlocksOnASingleLine)
478 if (!Style.AllowShortIfStatementsOnASingleLine &&
479 Line.startsWith(tok::kw_if) &&
480 !Style.BraceWrapping.AfterControlStatement &&
481 !I[1]->First->is(tok::r_brace))
483 if (!Style.AllowShortIfStatementsOnASingleLine &&
484 Line.startsWith(tok::kw_if) &&
485 Style.BraceWrapping.AfterControlStatement && I + 2 != E &&
486 !I[2]->First->is(tok::r_brace))
488 if (!Style.AllowShortLoopsOnASingleLine &&
489 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
490 !Style.BraceWrapping.AfterControlStatement &&
491 !I[1]->First->is(tok::r_brace))
493 if (!Style.AllowShortLoopsOnASingleLine &&
494 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
495 Style.BraceWrapping.AfterControlStatement && I + 2 != E &&
496 !I[2]->First->is(tok::r_brace))
503 if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
504 Keywords.kw___except, tok::kw___finally))
508 if (Line.Last->is(tok::l_brace)) {
509 FormatToken *
Tok = I[1]->First;
510 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
511 (Tok->getNextNonComment() ==
nullptr ||
512 Tok->getNextNonComment()->is(tok::semi))) {
515 Tok->CanBreakBefore =
true;
517 }
else if (Limit != 0 && !Line.startsWith(tok::kw_namespace) &&
518 !startsExternCBlock(Line)) {
520 FormatToken *RecordTok = Line.First;
522 while (RecordTok->Next &&
523 RecordTok->isOneOf(tok::kw_typedef, tok::kw_export,
524 Keywords.kw_declare, Keywords.kw_abstract,
526 RecordTok = RecordTok->Next;
528 RecordTok->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
529 Keywords.kw_interface))
535 Limit = limitConsideringMacros(I + 2, E, Limit);
537 if (!nextTwoLinesFitInto(I, Limit))
542 if (I[1]->Last->is(TT_LineComment))
545 if (Tok->is(tok::l_brace) && Tok->BlockKind !=
BK_BracedInit)
552 if (Tok->isNot(tok::r_brace))
556 if (Tok->Next && Tok->Next->is(tok::kw_else))
561 }
else if (I[1]->First->is(tok::l_brace)) {
562 if (I[1]->Last->is(TT_LineComment))
566 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
569 unsigned MergedLines = 0;
570 if (Style.AllowShortBlocksOnASingleLine ||
571 (I[1]->First == I[1]->Last && I + 2 != E &&
572 I[2]->First->is(tok::r_brace))) {
573 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
587 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
588 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
591 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(
tok::eof)) {
592 return Limit < 2 ? 0 : Limit - 2;
597 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
599 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
601 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
604 bool containsMustBreak(
const AnnotatedLine *Line) {
612 void join(AnnotatedLine &A,
const AnnotatedLine &B) {
613 assert(!A.Last->Next);
614 assert(!B.First->Previous);
617 A.Last->Next = B.First;
618 B.First->Previous = A.Last;
619 B.First->CanBreakBefore =
true;
620 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
627 const FormatStyle &
Style;
628 const AdditionalKeywords &Keywords;
629 const SmallVectorImpl<AnnotatedLine *>::const_iterator
End;
631 SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
632 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
635 static void markFinalized(FormatToken *
Tok) {
637 Tok->Finalized =
true;
638 for (AnnotatedLine *Child : Tok->Children)
639 markFinalized(Child->First);
644 static void printLineState(
const LineState &
State) {
645 llvm::dbgs() <<
"State: ";
646 for (
const ParenState &
P : State.Stack) {
647 llvm::dbgs() << P.Indent <<
"|" << P.LastSpace <<
"|" << P.NestedBlockIndent
650 llvm::dbgs() << State.NextToken->TokenText <<
"\n";
655 class LineFormatter {
657 LineFormatter(ContinuationIndenter *
Indenter, WhitespaceManager *Whitespaces,
658 const FormatStyle &
Style,
659 UnwrappedLineFormatter *BlockFormatter)
660 :
Indenter(Indenter), Whitespaces(Whitespaces),
Style(Style),
661 BlockFormatter(BlockFormatter) {}
662 virtual ~LineFormatter() {}
667 virtual unsigned formatLine(
const AnnotatedLine &Line,
668 unsigned FirstIndent,
669 unsigned FirstStartColumn,
693 bool formatChildren(LineState &State,
bool NewLine,
bool DryRun,
695 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
696 FormatToken &
Previous = *State.NextToken->Previous;
697 if (!LBrace || LBrace->isNot(tok::l_brace) ||
698 LBrace->BlockKind !=
BK_Block || Previous.Children.size() == 0)
704 int AdditionalIndent = State.Stack.back().Indent -
705 Previous.Children[0]->Level * Style.IndentWidth;
708 BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
713 if (Previous.Children[0]->First->MustBreakBefore)
717 if (Previous.is(tok::comment))
721 if (Previous.Children.size() > 1)
724 const AnnotatedLine *Child = Previous.Children[0];
726 if (Child->Last->isTrailingComment())
731 if (Style.ColumnLimit > 0 &&
732 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit)
736 Whitespaces->replaceWhitespace(
738 State.Column, State.Line->InPPDirective);
741 formatLine(*Child, State.Column + 1, 0, DryRun);
743 State.Column += 1 + Child->Last->TotalLength;
750 WhitespaceManager *Whitespaces;
751 const FormatStyle &
Style;
752 UnwrappedLineFormatter *BlockFormatter;
756 class NoColumnLimitLineFormatter :
public LineFormatter {
758 NoColumnLimitLineFormatter(ContinuationIndenter *
Indenter,
759 WhitespaceManager *Whitespaces,
760 const FormatStyle &
Style,
761 UnwrappedLineFormatter *BlockFormatter)
762 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
766 unsigned formatLine(
const AnnotatedLine &Line,
unsigned FirstIndent,
767 unsigned FirstStartColumn,
bool DryRun)
override {
769 LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
771 while (State.NextToken) {
773 Indenter->mustBreak(State) ||
774 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
775 unsigned Penalty = 0;
776 formatChildren(State, Newline,
false, Penalty);
777 Indenter->addTokenToState(State, Newline,
false);
784 class NoLineBreakFormatter :
public LineFormatter {
786 NoLineBreakFormatter(ContinuationIndenter *
Indenter,
787 WhitespaceManager *Whitespaces,
const FormatStyle &
Style,
788 UnwrappedLineFormatter *BlockFormatter)
789 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
792 unsigned formatLine(
const AnnotatedLine &Line,
unsigned FirstIndent,
793 unsigned FirstStartColumn,
bool DryRun)
override {
794 unsigned Penalty = 0;
796 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
797 while (State.NextToken) {
798 formatChildren(State,
false, DryRun, Penalty);
799 Indenter->addTokenToState(
800 State, State.NextToken->MustBreakBefore, DryRun);
807 class OptimizingLineFormatter :
public LineFormatter {
809 OptimizingLineFormatter(ContinuationIndenter *
Indenter,
810 WhitespaceManager *Whitespaces,
811 const FormatStyle &
Style,
812 UnwrappedLineFormatter *BlockFormatter)
813 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
817 unsigned formatLine(
const AnnotatedLine &Line,
unsigned FirstIndent,
818 unsigned FirstStartColumn,
bool DryRun)
override {
820 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
825 State.Stack.back().BreakBeforeParameter =
true;
828 return analyzeSolutionSpace(State, DryRun);
832 struct CompareLineStatePointers {
833 bool operator()(LineState *obj1, LineState *obj2)
const {
834 return *obj1 < *obj2;
843 typedef std::pair<unsigned, unsigned> OrderedPenalty;
857 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
860 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
861 std::greater<QueueItem>>
872 unsigned analyzeSolutionSpace(LineState &InitialState,
bool DryRun) {
873 std::set<LineState *, CompareLineStatePointers> Seen;
882 new (Allocator.Allocate()) StateNode(InitialState,
false,
nullptr);
883 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
886 unsigned Penalty = 0;
889 while (!Queue.empty()) {
890 Penalty = Queue.top().first.first;
891 StateNode *Node = Queue.top().second;
892 if (!Node->State.NextToken) {
893 DEBUG(llvm::dbgs() <<
"\n---\nPenalty for line: " << Penalty <<
"\n");
901 Node->State.IgnoreStackForComparison =
true;
903 if (!Seen.insert(&Node->State).second)
909 addNextStateToQueue(Penalty, Node,
false, &Count, &Queue);
911 addNextStateToQueue(Penalty, Node,
true, &Count, &Queue);
917 DEBUG(llvm::dbgs() <<
"Could not find a solution.\n");
923 reconstructPath(InitialState, Queue.top().second);
925 DEBUG(llvm::dbgs() <<
"Total number of analyzed states: " << Count <<
"\n");
926 DEBUG(llvm::dbgs() <<
"---\n");
935 void addNextStateToQueue(
unsigned Penalty, StateNode *PreviousNode,
936 bool NewLine,
unsigned *Count, QueueType *Queue) {
937 if (NewLine && !Indenter->canBreak(PreviousNode->State))
939 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
942 StateNode *
Node =
new (Allocator.Allocate())
943 StateNode(PreviousNode->State, NewLine, PreviousNode);
944 if (!formatChildren(Node->State, NewLine,
true, Penalty))
947 Penalty += Indenter->addTokenToState(Node->State, NewLine,
true);
949 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
955 void reconstructPath(LineState &State, StateNode *Best) {
956 std::deque<StateNode *> Path;
958 while (Best->Previous) {
959 Path.push_front(Best);
960 Best = Best->Previous;
962 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
964 unsigned Penalty = 0;
965 formatChildren(State, (*I)->NewLine,
false, Penalty);
966 Penalty += Indenter->addTokenToState(State, (*I)->NewLine,
false);
969 printLineState((*I)->Previous->State);
971 llvm::dbgs() <<
"Penalty for placing " 972 << (*I)->Previous->State.NextToken->Tok.getName() <<
": " 979 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
986 bool DryRun,
int AdditionalIndent,
987 bool FixBadIndentation,
988 unsigned FirstStartColumn,
989 unsigned NextStartColumn,
990 unsigned LastStartColumn) {
991 LineJoiner Joiner(
Style, Keywords, Lines);
994 std::pair<const SmallVectorImpl<AnnotatedLine *> *,
unsigned> CacheKey(
995 &Lines, AdditionalIndent);
996 auto CacheIt = PenaltyCache.find(CacheKey);
997 if (DryRun && CacheIt != PenaltyCache.end())
998 return CacheIt->second;
1000 assert(!Lines.empty());
1001 unsigned Penalty = 0;
1002 LevelIndentTracker IndentTracker(
Style, Keywords, Lines[0]->
Level,
1010 bool FirstLine =
true;
1012 Joiner.getNextMergedLine(DryRun, IndentTracker);
1013 Line;
Line = NextLine, FirstLine =
false) {
1015 unsigned Indent = IndentTracker.getIndent();
1021 bool ContinueFormatting =
1022 TheLine.
Level > RangeMinLevel ||
1023 (TheLine.
Level == RangeMinLevel && !TheLine.
startsWith(tok::r_brace));
1025 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
1027 bool ShouldFormat = TheLine.
Affected || FixIndentation;
1031 Status->FormatComplete =
false;
1039 formatFirstToken(TheLine, PreviousLine,
1041 LastLine ? LastStartColumn : NextStartColumn + Indent);
1044 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1045 unsigned ColumnLimit = getColumnLimit(TheLine.
InPPDirective, NextLine);
1046 bool FitsIntoOneLine =
1052 NoColumnLimitLineFormatter(
Indenter, Whitespaces,
Style,
this)
1053 .formatLine(TheLine, NextStartColumn + Indent,
1054 FirstLine ? FirstStartColumn : 0, DryRun);
1055 else if (FitsIntoOneLine)
1056 Penalty += NoLineBreakFormatter(
Indenter, Whitespaces,
Style,
this)
1057 .formatLine(TheLine, NextStartColumn + Indent,
1058 FirstLine ? FirstStartColumn : 0, DryRun);
1060 Penalty += OptimizingLineFormatter(
Indenter, Whitespaces,
Style,
this)
1061 .formatLine(TheLine, NextStartColumn + Indent,
1062 FirstLine ? FirstStartColumn : 0, DryRun);
1074 bool StartsNewLine =
1077 IndentTracker.adjustToUnmodifiedLine(TheLine);
1079 bool ReformatLeadingWhitespace =
1080 StartsNewLine && ((PreviousLine && PreviousLine->
Affected) ||
1083 if (ReformatLeadingWhitespace)
1084 formatFirstToken(TheLine, PreviousLine,
1088 Whitespaces->addUntouchableToken(*TheLine.
First,
1095 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1099 markFinalized(TheLine.
First);
1100 PreviousLine = &TheLine;
1102 PenaltyCache[CacheKey] = Penalty;
1109 unsigned NewlineIndent) {
1113 unsigned TokenIndent = Newlines ? NewlineIndent : 0;
1114 Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
1121 if (RootToken.
is(tok::r_brace) &&
1126 if (PreviousLine ==
nullptr && Line.
Level > 0)
1128 if (Newlines == 0 && !RootToken.
IsFirst)
1135 PreviousLine->
Last->
is(tok::l_brace) &&
1136 PreviousLine->
First->
isNot(tok::kw_namespace) &&
1137 !startsExternCBlock(*PreviousLine))
1141 if (PreviousLine && PreviousLine->
Last->
isOneOf(tok::semi, tok::r_brace) &&
1151 Indent = NewlineIndent;
1157 Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent,
1167 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. ...
char __ovld __cnfn min(char x, char y)
Returns y if y < x, otherwise it returns x.
ast_type_traits::DynTypedNode Node
Dataflow Directional Tag Classes.