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);
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) {
96 if (Style.Language == FormatStyle::LK_Java ||
97 Style.Language == FormatStyle::LK_JavaScript || Style.isCSharp())
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 const FormatToken *getMatchingNamespaceToken(
138 const AnnotatedLine *Line,
139 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
140 if (!Line->startsWith(tok::r_brace))
142 size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex;
145 assert(StartLineIndex < AnnotatedLines.size());
146 return AnnotatedLines[StartLineIndex]->First->getNamespaceToken();
150 const FormatToken *NamespaceToken = Line->First->getNamespaceToken();
151 return NamespaceToken ? NamespaceToken->TokenText : StringRef();
154 StringRef getMatchingNamespaceTokenText(
155 const AnnotatedLine *Line,
156 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
157 const FormatToken *NamespaceToken =
158 getMatchingNamespaceToken(Line, AnnotatedLines);
159 return NamespaceToken ? NamespaceToken->TokenText : StringRef();
164 LineJoiner(
const FormatStyle &
Style,
const AdditionalKeywords &Keywords,
165 const SmallVectorImpl<AnnotatedLine *> &Lines)
166 :
Style(Style), Keywords(Keywords),
End(Lines.end()), Next(Lines.begin()),
167 AnnotatedLines(Lines) {}
170 const AnnotatedLine *getNextMergedLine(
bool DryRun,
171 LevelIndentTracker &IndentTracker) {
174 const AnnotatedLine *Current = *Next;
175 IndentTracker.nextLine(*Current);
176 unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next,
End);
177 if (MergedLines > 0 && Style.ColumnLimit == 0)
180 for (
unsigned i = 0;
i < MergedLines; ++
i)
181 if (Next[
i + 1]->First->NewlinesBefore > 0)
184 for (
unsigned i = 0;
i < MergedLines; ++
i)
185 join(*Next[0], *Next[
i + 1]);
186 Next = Next + MergedLines + 1;
193 tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker,
194 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
195 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
196 const unsigned Indent = IndentTracker.getIndent();
202 const AnnotatedLine *TheLine = *I;
203 if (TheLine->Last->is(TT_LineComment))
207 if (TheLine->InPPDirective &&
208 (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline))
211 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
218 Limit = TheLine->Last->TotalLength > Limit
220 : Limit - TheLine->Last->TotalLength;
222 if (TheLine->Last->is(TT_FunctionLBrace) &&
223 TheLine->First == TheLine->Last &&
224 !Style.BraceWrapping.SplitEmptyFunction &&
225 I[1]->First->is(tok::r_brace))
226 return tryMergeSimpleBlock(I, E, Limit);
229 if (TheLine->Last->is(tok::l_brace) && TheLine->First == TheLine->Last &&
230 I != AnnotatedLines.begin()) {
231 bool EmptyBlock = I[1]->First->is(tok::r_brace);
233 const FormatToken *
Tok = I[-1]->First;
234 if (Tok && Tok->is(tok::comment))
237 if (Tok && Tok->getNamespaceToken())
238 return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock
239 ? tryMergeSimpleBlock(I, E, Limit)
242 if (Tok && Tok->is(tok::kw_typedef))
244 if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union,
245 tok::kw_extern, Keywords.kw_interface))
246 return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock
247 ? tryMergeSimpleBlock(I, E, Limit)
253 bool MergeShortFunctions =
254 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
255 (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
256 I[1]->First->is(tok::r_brace)) ||
257 (Style.AllowShortFunctionsOnASingleLine & FormatStyle::SFS_InlineOnly &&
258 TheLine->Level != 0);
260 if (Style.CompactNamespaces) {
261 if (
auto nsToken = TheLine->First->getNamespaceToken()) {
263 unsigned closingLine = TheLine->MatchingClosingBlockLineIndex - 1;
264 for (; I + 1 + i != E &&
266 closingLine == I[i + 1]->MatchingClosingBlockLineIndex &&
267 I[i + 1]->Last->TotalLength < Limit;
268 i++, closingLine--) {
270 IndentTracker.skipLine(*I[i + 1]);
272 Limit -= I[i + 1]->Last->TotalLength;
277 if (
auto nsToken = getMatchingNamespaceToken(TheLine, AnnotatedLines)) {
279 unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
280 for (; I + 1 + i != E &&
281 nsToken->TokenText ==
282 getMatchingNamespaceTokenText(I[i + 1], AnnotatedLines) &&
283 openingLine == I[i + 1]->MatchingOpeningBlockLineIndex;
284 i++, openingLine--) {
286 I[i + 1]->First->SpacesRequiredBefore = !I[
i]->Last->is(tok::r_brace);
289 IndentTracker.nextLine(*I[i + 1]);
296 if (TheLine->Last->is(TT_FunctionLBrace) &&
297 TheLine->First != TheLine->Last) {
298 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
301 if (TheLine->Last->is(tok::l_brace) && TheLine->First != TheLine->Last &&
302 TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
303 return Style.AllowShortBlocksOnASingleLine
304 ? tryMergeSimpleBlock(I, E, Limit)
308 if (I[1]->First->is(tok::l_brace) &&
309 TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
310 return Style.BraceWrapping.AfterControlStatement
311 ? tryMergeSimpleBlock(I, E, Limit)
316 if (TheLine->First->is(tok::l_brace) && TheLine->First == TheLine->Last &&
317 I != AnnotatedLines.begin() &&
318 I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
319 unsigned MergedLines = 0;
320 if (Style.AllowShortBlocksOnASingleLine) {
321 MergedLines = tryMergeSimpleBlock(I - 1, E, Limit);
330 if (TheLine->First->is(tok::l_brace) && I != AnnotatedLines.begin() &&
331 I[-1]->First->is(tok::at) && I[-1]->First->Next) {
333 if (kwId == clang::tok::objc_autoreleasepool ||
334 kwId == clang::tok::objc_synchronized)
338 if (TheLine->First->is(tok::l_brace) && I != AnnotatedLines.begin() &&
339 I[-1]->First->isOneOf(tok::kw_case, tok::kw_default))
342 if (TheLine->Last->is(tok::l_brace)) {
343 return !Style.BraceWrapping.AfterFunction ||
344 (I[1]->First->is(tok::r_brace) &&
345 !Style.BraceWrapping.SplitEmptyRecord)
346 ? tryMergeSimpleBlock(I, E, Limit)
350 if (I[1]->First->is(TT_FunctionLBrace) &&
351 Style.BraceWrapping.AfterFunction) {
352 if (I[1]->Last->is(TT_LineComment))
356 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
360 unsigned MergedLines = 0;
361 if (MergeShortFunctions ||
362 (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
363 I[1]->First == I[1]->Last && I + 2 != E &&
364 I[2]->First->is(tok::r_brace))) {
365 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
373 if (TheLine->First->is(tok::kw_if)) {
374 return Style.AllowShortIfStatementsOnASingleLine
375 ? tryMergeSimpleControlStatement(I, E, Limit)
378 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
379 return Style.AllowShortLoopsOnASingleLine
380 ? tryMergeSimpleControlStatement(I, E, Limit)
383 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
384 return Style.AllowShortCaseLabelsOnASingleLine
385 ? tryMergeShortCaseLabels(I, E, Limit)
388 if (TheLine->InPPDirective &&
389 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
390 return tryMergeSimplePPDirective(I, E, Limit);
396 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
397 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
401 if (I + 2 != E && I[2]->
InPPDirective && !I[2]->First->HasUnescapedNewline)
403 if (1 + I[1]->Last->TotalLength > Limit)
408 unsigned tryMergeSimpleControlStatement(
409 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
410 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
unsigned Limit) {
413 if (Style.BraceWrapping.AfterControlStatement &&
414 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
417 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
419 Limit = limitConsideringMacros(I + 1, E, Limit);
420 AnnotatedLine &Line = **I;
421 if (Line.Last->isNot(tok::r_paren))
423 if (1 + I[1]->Last->TotalLength > Limit)
425 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
429 if (Style.AllowShortIfStatementsOnASingleLine != FormatStyle::SIS_Always) {
430 if (I + 2 != E && Line.startsWith(tok::kw_if) &&
431 I[2]->First->is(tok::kw_else))
438 tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
439 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
441 if (Limit == 0 || I + 1 == E ||
442 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
444 if (I[0]->Last->is(tok::l_brace) || I[1]->First->is(tok::l_brace))
446 unsigned NumStmts = 0;
448 bool EndsWithComment =
false;
450 const unsigned Level = I[0]->Level;
451 for (; NumStmts < 3; ++NumStmts) {
452 if (I + 1 + NumStmts == E)
454 const AnnotatedLine *Line = I[1 + NumStmts];
455 if (Line->InPPDirective != InPPDirective)
457 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
459 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
463 if (Line->First->is(tok::comment)) {
464 if (Level != Line->Level)
466 SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts;
467 for (; J != E; ++J) {
469 if (Line->InPPDirective != InPPDirective)
471 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
473 if (Line->First->isNot(tok::comment) || Level != Line->Level)
478 if (Line->Last->is(tok::comment))
479 EndsWithComment =
true;
480 Length += I[1 + NumStmts]->Last->TotalLength + 1;
482 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
488 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
489 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
491 AnnotatedLine &Line = **I;
496 if (Style.Language != FormatStyle::LK_Java &&
497 Line.First->isOneOf(tok::at, tok::minus, tok::plus))
502 if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
503 (Line.First->Next && Line.First->Next->is(tok::kw_else)))
506 if (Line.First->is(tok::kw_default)) {
508 if (Tok && Tok->is(tok::colon))
511 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
512 tok::kw___try, tok::kw_catch, tok::kw___finally,
513 tok::kw_for, tok::r_brace, Keywords.kw___except)) {
514 if (!Style.AllowShortBlocksOnASingleLine)
518 if (!Style.AllowShortIfStatementsOnASingleLine &&
519 Line.startsWith(tok::kw_if) &&
520 !Style.BraceWrapping.AfterControlStatement &&
521 !I[1]->First->is(tok::r_brace))
523 if (!Style.AllowShortIfStatementsOnASingleLine &&
524 Line.startsWith(tok::kw_if) &&
525 Style.BraceWrapping.AfterControlStatement && I + 2 != E &&
526 !I[2]->First->is(tok::r_brace))
528 if (!Style.AllowShortLoopsOnASingleLine &&
529 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
530 !Style.BraceWrapping.AfterControlStatement &&
531 !I[1]->First->is(tok::r_brace))
533 if (!Style.AllowShortLoopsOnASingleLine &&
534 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
535 Style.BraceWrapping.AfterControlStatement && I + 2 != E &&
536 !I[2]->First->is(tok::r_brace))
543 if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
544 Keywords.kw___except, tok::kw___finally))
548 if (Line.Last->is(tok::l_brace)) {
549 FormatToken *
Tok = I[1]->First;
550 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
551 (Tok->getNextNonComment() ==
nullptr ||
552 Tok->getNextNonComment()->is(tok::semi))) {
555 Tok->CanBreakBefore =
true;
557 }
else if (Limit != 0 && !Line.startsWithNamespace() &&
558 !startsExternCBlock(Line)) {
560 FormatToken *RecordTok = Line.First;
562 while (RecordTok->Next &&
563 RecordTok->isOneOf(tok::kw_typedef, tok::kw_export,
564 Keywords.kw_declare, Keywords.kw_abstract,
566 RecordTok = RecordTok->Next;
568 RecordTok->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
569 Keywords.kw_interface))
575 Limit = limitConsideringMacros(I + 2, E, Limit);
577 if (!nextTwoLinesFitInto(I, Limit))
582 if (I[1]->Last->is(TT_LineComment))
585 if (Tok->is(tok::l_brace) && Tok->BlockKind !=
BK_BracedInit)
592 if (Tok->isNot(tok::r_brace))
596 if (Tok->Next && Tok->Next->is(tok::kw_else))
601 }
else if (I[1]->First->is(tok::l_brace)) {
602 if (I[1]->Last->is(TT_LineComment))
606 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
609 unsigned MergedLines = 0;
610 if (Style.AllowShortBlocksOnASingleLine ||
611 (I[1]->First == I[1]->Last && I + 2 != E &&
612 I[2]->First->is(tok::r_brace))) {
613 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
627 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
628 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
631 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(
tok::eof)) {
632 return Limit < 2 ? 0 : Limit - 2;
637 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
639 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
641 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
644 bool containsMustBreak(
const AnnotatedLine *Line) {
652 void join(AnnotatedLine &A,
const AnnotatedLine &B) {
653 assert(!A.Last->Next);
654 assert(!B.First->Previous);
657 A.Last->Next = B.First;
658 B.First->Previous = A.Last;
659 B.First->CanBreakBefore =
true;
660 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
667 const FormatStyle &
Style;
668 const AdditionalKeywords &Keywords;
669 const SmallVectorImpl<AnnotatedLine *>::const_iterator
End;
671 SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
672 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
675 static void markFinalized(FormatToken *
Tok) {
677 Tok->Finalized =
true;
678 for (AnnotatedLine *Child : Tok->Children)
679 markFinalized(Child->First);
684 static void printLineState(
const LineState &
State) {
685 llvm::dbgs() <<
"State: ";
686 for (
const ParenState &
P : State.Stack) {
687 llvm::dbgs() << (P.Tok ? P.Tok->TokenText :
"F") <<
"|" << P.Indent <<
"|" 688 << P.LastSpace <<
"|" << P.NestedBlockIndent <<
" ";
690 llvm::dbgs() << State.NextToken->TokenText <<
"\n";
695 class LineFormatter {
697 LineFormatter(ContinuationIndenter *
Indenter, WhitespaceManager *Whitespaces,
698 const FormatStyle &
Style,
699 UnwrappedLineFormatter *BlockFormatter)
700 :
Indenter(Indenter), Whitespaces(Whitespaces),
Style(Style),
701 BlockFormatter(BlockFormatter) {}
702 virtual ~LineFormatter() {}
707 virtual unsigned formatLine(
const AnnotatedLine &Line,
unsigned FirstIndent,
708 unsigned FirstStartColumn,
bool DryRun) = 0;
731 bool formatChildren(LineState &State,
bool NewLine,
bool DryRun,
733 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
734 FormatToken &
Previous = *State.NextToken->Previous;
735 if (!LBrace || LBrace->isNot(tok::l_brace) ||
736 LBrace->BlockKind !=
BK_Block || Previous.Children.size() == 0)
742 int AdditionalIndent = State.Stack.back().Indent -
743 Previous.Children[0]->Level * Style.IndentWidth;
746 BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
751 if (Previous.Children[0]->First->MustBreakBefore)
755 if (Previous.is(tok::comment))
759 if (Previous.Children.size() > 1)
762 const AnnotatedLine *Child = Previous.Children[0];
764 if (Child->Last->isTrailingComment())
769 if (Style.ColumnLimit > 0 &&
770 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit)
774 Whitespaces->replaceWhitespace(
776 State.Column, State.Line->InPPDirective);
779 formatLine(*Child, State.Column + 1, 0, DryRun);
781 State.Column += 1 + Child->Last->TotalLength;
788 WhitespaceManager *Whitespaces;
789 const FormatStyle &
Style;
790 UnwrappedLineFormatter *BlockFormatter;
794 class NoColumnLimitLineFormatter :
public LineFormatter {
796 NoColumnLimitLineFormatter(ContinuationIndenter *
Indenter,
797 WhitespaceManager *Whitespaces,
798 const FormatStyle &
Style,
799 UnwrappedLineFormatter *BlockFormatter)
800 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
804 unsigned formatLine(
const AnnotatedLine &Line,
unsigned FirstIndent,
805 unsigned FirstStartColumn,
bool DryRun)
override {
807 LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
809 while (State.NextToken) {
811 Indenter->mustBreak(State) ||
812 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
813 unsigned Penalty = 0;
814 formatChildren(State, Newline,
false, Penalty);
815 Indenter->addTokenToState(State, Newline,
false);
822 class NoLineBreakFormatter :
public LineFormatter {
824 NoLineBreakFormatter(ContinuationIndenter *
Indenter,
825 WhitespaceManager *Whitespaces,
const FormatStyle &
Style,
826 UnwrappedLineFormatter *BlockFormatter)
827 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
830 unsigned formatLine(
const AnnotatedLine &Line,
unsigned FirstIndent,
831 unsigned FirstStartColumn,
bool DryRun)
override {
832 unsigned Penalty = 0;
834 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
835 while (State.NextToken) {
836 formatChildren(State,
false, DryRun, Penalty);
837 Indenter->addTokenToState(
838 State, State.NextToken->MustBreakBefore, DryRun);
845 class OptimizingLineFormatter :
public LineFormatter {
847 OptimizingLineFormatter(ContinuationIndenter *
Indenter,
848 WhitespaceManager *Whitespaces,
849 const FormatStyle &
Style,
850 UnwrappedLineFormatter *BlockFormatter)
851 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
855 unsigned formatLine(
const AnnotatedLine &Line,
unsigned FirstIndent,
856 unsigned FirstStartColumn,
bool DryRun)
override {
858 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
863 State.Stack.back().BreakBeforeParameter =
true;
866 return analyzeSolutionSpace(State, DryRun);
870 struct CompareLineStatePointers {
871 bool operator()(LineState *obj1, LineState *obj2)
const {
872 return *obj1 < *obj2;
881 typedef std::pair<unsigned, unsigned> OrderedPenalty;
895 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
898 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
899 std::greater<QueueItem>>
910 unsigned analyzeSolutionSpace(LineState &InitialState,
bool DryRun) {
911 std::set<LineState *, CompareLineStatePointers> Seen;
920 new (Allocator.Allocate()) StateNode(InitialState,
false,
nullptr);
921 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
924 unsigned Penalty = 0;
927 while (!Queue.empty()) {
928 Penalty = Queue.top().first.first;
929 StateNode *Node = Queue.top().second;
930 if (!Node->State.NextToken) {
931 LLVM_DEBUG(llvm::dbgs()
932 <<
"\n---\nPenalty for line: " << Penalty <<
"\n");
940 Node->State.IgnoreStackForComparison =
true;
942 if (!Seen.insert(&Node->State).second)
948 addNextStateToQueue(Penalty, Node,
false, &Count, &Queue);
950 addNextStateToQueue(Penalty, Node,
true, &Count, &Queue);
956 LLVM_DEBUG(llvm::dbgs() <<
"Could not find a solution.\n");
962 reconstructPath(InitialState, Queue.top().second);
964 LLVM_DEBUG(llvm::dbgs()
965 <<
"Total number of analyzed states: " << Count <<
"\n");
966 LLVM_DEBUG(llvm::dbgs() <<
"---\n");
975 void addNextStateToQueue(
unsigned Penalty, StateNode *PreviousNode,
976 bool NewLine,
unsigned *Count, QueueType *Queue) {
977 if (NewLine && !Indenter->canBreak(PreviousNode->State))
979 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
982 StateNode *
Node =
new (Allocator.Allocate())
983 StateNode(PreviousNode->State, NewLine, PreviousNode);
984 if (!formatChildren(Node->State, NewLine,
true, Penalty))
987 Penalty += Indenter->addTokenToState(Node->State, NewLine,
true);
989 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
995 void reconstructPath(LineState &State, StateNode *Best) {
996 std::deque<StateNode *> Path;
998 while (Best->Previous) {
999 Path.push_front(Best);
1000 Best = Best->Previous;
1002 for (
auto I = Path.begin(), E = Path.end(); I != E; ++I) {
1003 unsigned Penalty = 0;
1004 formatChildren(State, (*I)->NewLine,
false, Penalty);
1005 Penalty += Indenter->addTokenToState(State, (*I)->NewLine,
false);
1008 printLineState((*I)->Previous->State);
1009 if ((*I)->NewLine) {
1010 llvm::dbgs() <<
"Penalty for placing " 1011 << (*I)->Previous->State.NextToken->Tok.getName()
1012 <<
" on a new line: " << Penalty <<
"\n";
1018 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1025 int AdditionalIndent,
bool FixBadIndentation,
unsigned FirstStartColumn,
1026 unsigned NextStartColumn,
unsigned LastStartColumn) {
1027 LineJoiner Joiner(
Style, Keywords, Lines);
1030 std::pair<const SmallVectorImpl<AnnotatedLine *> *,
unsigned> CacheKey(
1031 &Lines, AdditionalIndent);
1032 auto CacheIt = PenaltyCache.find(CacheKey);
1033 if (DryRun && CacheIt != PenaltyCache.end())
1034 return CacheIt->second;
1036 assert(!Lines.empty());
1037 unsigned Penalty = 0;
1038 LevelIndentTracker IndentTracker(
Style, Keywords, Lines[0]->
Level,
1046 bool FirstLine =
true;
1048 Joiner.getNextMergedLine(DryRun, IndentTracker);
1049 Line;
Line = NextLine, FirstLine =
false) {
1051 unsigned Indent = IndentTracker.getIndent();
1057 bool PreviousRBrace =
1058 PreviousLine && PreviousLine->
startsWith(tok::r_brace);
1059 bool ContinueFormatting =
1060 TheLine.
Level > RangeMinLevel ||
1061 (TheLine.
Level == RangeMinLevel && !PreviousRBrace &&
1064 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
1066 bool ShouldFormat = TheLine.
Affected || FixIndentation;
1070 Status->FormatComplete =
false;
1078 formatFirstToken(TheLine, PreviousLine, Lines, Indent,
1079 LastLine ? LastStartColumn : NextStartColumn + Indent);
1082 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1083 unsigned ColumnLimit = getColumnLimit(TheLine.
InPPDirective, NextLine);
1084 bool FitsIntoOneLine =
1087 (
Style.Language != FormatStyle::LK_JavaScript ||
1088 !
Style.JavaScriptWrapImports)) ||
1089 (
Style.isCSharp() &&
1091 if (
Style.ColumnLimit == 0)
1092 NoColumnLimitLineFormatter(
Indenter, Whitespaces,
Style,
this)
1093 .formatLine(TheLine, NextStartColumn + Indent,
1094 FirstLine ? FirstStartColumn : 0, DryRun);
1095 else if (FitsIntoOneLine)
1096 Penalty += NoLineBreakFormatter(
Indenter, Whitespaces,
Style,
this)
1097 .formatLine(TheLine, NextStartColumn + Indent,
1098 FirstLine ? FirstStartColumn : 0, DryRun);
1100 Penalty += OptimizingLineFormatter(
Indenter, Whitespaces,
Style,
this)
1101 .formatLine(TheLine, NextStartColumn + Indent,
1102 FirstLine ? FirstStartColumn : 0, DryRun);
1114 bool StartsNewLine =
1117 IndentTracker.adjustToUnmodifiedLine(TheLine);
1119 bool ReformatLeadingWhitespace =
1120 StartsNewLine && ((PreviousLine && PreviousLine->
Affected) ||
1123 if (ReformatLeadingWhitespace)
1124 formatFirstToken(TheLine, PreviousLine, Lines,
1128 Whitespaces->addUntouchableToken(*TheLine.
First,
1135 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1139 markFinalized(TheLine.
First);
1140 PreviousLine = &TheLine;
1142 PenaltyCache[CacheKey] = Penalty;
1146 void UnwrappedLineFormatter::formatFirstToken(
1149 unsigned NewlineIndent) {
1153 unsigned TokenIndent = Newlines ? NewlineIndent : 0;
1154 Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
1161 if (RootToken.
is(tok::r_brace) &&
1168 if (PreviousLine ==
nullptr && Line.
Level > 0)
1170 if (Newlines == 0 && !RootToken.
IsFirst)
1176 if (!
Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1177 PreviousLine->
Last->
is(tok::l_brace) &&
1179 !startsExternCBlock(*PreviousLine))
1183 if (PreviousLine && PreviousLine->
Last->
isOneOf(tok::semi, tok::r_brace) &&
1193 Indent = NewlineIndent;
1196 if (
Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
1201 Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent,
1211 bool ContinuesPPDirective =
1220 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
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.
static void skipLine(const char *&First, const char *const End)
__DEVICE__ int min(int __a, int __b)
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)