1 //===--- UnwrappedLineFormatter.cpp - Format C++ code ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "UnwrappedLineFormatter.h"
11 #include "WhitespaceManager.h"
12 #include "llvm/Support/Debug.h"
14 #define DEBUG_TYPE "format-formatter"
21 bool startsExternCBlock(const AnnotatedLine &Line) {
22 const FormatToken *Next = Line.First->getNextNonComment();
23 const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
24 return Line.First->is(tok::kw_extern) && Next && Next->isStringLiteral() &&
25 NextNext && NextNext->is(tok::l_brace);
28 /// \brief Tracks the indent level of \c AnnotatedLines across levels.
30 /// \c nextLine must be called for each \c AnnotatedLine, after which \c
31 /// getIndent() will return the indent for the last line \c nextLine was called
33 /// If the line is not formatted (and thus the indent does not change), calling
34 /// \c adjustToUnmodifiedLine after the call to \c nextLine will cause
35 /// subsequent lines on the same level to be indented at the same level as the
37 class LevelIndentTracker {
39 LevelIndentTracker(const FormatStyle &Style,
40 const AdditionalKeywords &Keywords, unsigned StartLevel,
42 : Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) {
43 for (unsigned i = 0; i != StartLevel; ++i)
44 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
47 /// \brief Returns the indent for the current line.
48 unsigned getIndent() const { return Indent; }
50 /// \brief Update the indent state given that \p Line is going to be formatted
52 void nextLine(const AnnotatedLine &Line) {
53 Offset = getIndentOffset(*Line.First);
54 if (Line.InPPDirective) {
55 Indent = Line.Level * Style.IndentWidth + AdditionalIndent;
57 while (IndentForLevel.size() <= Line.Level)
58 IndentForLevel.push_back(-1);
59 IndentForLevel.resize(Line.Level + 1);
60 Indent = getIndent(IndentForLevel, Line.Level);
62 if (static_cast<int>(Indent) + Offset >= 0)
66 /// \brief Update the level indent to adapt to the given \p Line.
68 /// When a line is not formatted, we move the subsequent lines on the same
69 /// level to the same indent.
70 /// Note that \c nextLine must have been called before this method.
71 void adjustToUnmodifiedLine(const AnnotatedLine &Line) {
72 unsigned LevelIndent = Line.First->OriginalColumn;
73 if (static_cast<int>(LevelIndent) - Offset >= 0)
74 LevelIndent -= Offset;
75 if ((Line.First->isNot(tok::comment) || IndentForLevel[Line.Level] == -1) &&
77 IndentForLevel[Line.Level] = LevelIndent;
81 /// \brief Get the offset of the line relatively to the level.
83 /// For example, 'public:' labels in classes are offset by 1 or 2
84 /// characters to the left from their level.
85 int getIndentOffset(const FormatToken &RootToken) {
86 if (Style.Language == FormatStyle::LK_Java ||
87 Style.Language == FormatStyle::LK_JavaScript)
89 if (RootToken.isAccessSpecifier(false) ||
90 RootToken.isObjCAccessSpecifier() ||
91 (RootToken.is(Keywords.kw_signals) && RootToken.Next &&
92 RootToken.Next->is(tok::colon)))
93 return Style.AccessModifierOffset;
97 /// \brief Get the indent of \p Level from \p IndentForLevel.
99 /// \p IndentForLevel must contain the indent for the level \c l
100 /// at \p IndentForLevel[l], or a value < 0 if the indent for
101 /// that level is unknown.
102 unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
103 if (IndentForLevel[Level] != -1)
104 return IndentForLevel[Level];
107 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
110 const FormatStyle &Style;
111 const AdditionalKeywords &Keywords;
112 const unsigned AdditionalIndent;
114 /// \brief The indent in characters for each level.
115 std::vector<int> IndentForLevel;
117 /// \brief Offset of the current line relative to the indent level.
119 /// For example, the 'public' keywords is often indented with a negative
123 /// \brief The current line's indent.
129 LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords,
130 const SmallVectorImpl<AnnotatedLine *> &Lines)
131 : Style(Style), Keywords(Keywords), End(Lines.end()),
132 Next(Lines.begin()) {}
134 /// \brief Returns the next line, merging multiple lines into one if possible.
135 const AnnotatedLine *getNextMergedLine(bool DryRun,
136 LevelIndentTracker &IndentTracker) {
139 const AnnotatedLine *Current = *Next;
140 IndentTracker.nextLine(*Current);
141 unsigned MergedLines =
142 tryFitMultipleLinesInOne(IndentTracker.getIndent(), Next, End);
143 if (MergedLines > 0 && Style.ColumnLimit == 0)
144 // Disallow line merging if there is a break at the start of one of the
146 for (unsigned i = 0; i < MergedLines; ++i)
147 if (Next[i + 1]->First->NewlinesBefore > 0)
150 for (unsigned i = 0; i < MergedLines; ++i)
151 join(*Next[i], *Next[i + 1]);
152 Next = Next + MergedLines + 1;
157 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
159 tryFitMultipleLinesInOne(unsigned Indent,
160 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
161 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
162 // Can't join the last line with anything.
165 // We can never merge stuff if there are trailing line comments.
166 const AnnotatedLine *TheLine = *I;
167 if (TheLine->Last->is(TT_LineComment))
169 if (I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
171 if (TheLine->InPPDirective &&
172 (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline))
175 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
179 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
180 // If we already exceed the column limit, we set 'Limit' to 0. The different
181 // tryMerge..() functions can then decide whether to still do merging.
182 Limit = TheLine->Last->TotalLength > Limit
184 : Limit - TheLine->Last->TotalLength;
186 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
187 // If necessary, change to something smarter.
188 bool MergeShortFunctions =
189 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
190 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty &&
191 I[1]->First->is(tok::r_brace)) ||
192 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
193 TheLine->Level != 0);
195 if (TheLine->Last->is(TT_FunctionLBrace) &&
196 TheLine->First != TheLine->Last) {
197 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
199 if (TheLine->Last->is(tok::l_brace)) {
200 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
201 ? tryMergeSimpleBlock(I, E, Limit)
204 if (I[1]->First->is(TT_FunctionLBrace) &&
205 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
206 if (I[1]->Last->is(TT_LineComment))
209 // Check for Limit <= 2 to account for the " {".
210 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
214 unsigned MergedLines = 0;
215 if (MergeShortFunctions) {
216 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
217 // If we managed to merge the block, count the function header, which is
218 // on a separate line.
224 if (TheLine->First->is(tok::kw_if)) {
225 return Style.AllowShortIfStatementsOnASingleLine
226 ? tryMergeSimpleControlStatement(I, E, Limit)
229 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
230 return Style.AllowShortLoopsOnASingleLine
231 ? tryMergeSimpleControlStatement(I, E, Limit)
234 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
235 return Style.AllowShortCaseLabelsOnASingleLine
236 ? tryMergeShortCaseLabels(I, E, Limit)
239 if (TheLine->InPPDirective &&
240 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
241 return tryMergeSimplePPDirective(I, E, Limit);
247 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
248 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
252 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
254 if (1 + I[1]->Last->TotalLength > Limit)
259 unsigned tryMergeSimpleControlStatement(
260 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
261 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
264 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
265 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
266 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
268 if (I[1]->InPPDirective != (*I)->InPPDirective ||
269 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
271 Limit = limitConsideringMacros(I + 1, E, Limit);
272 AnnotatedLine &Line = **I;
273 if (Line.Last->isNot(tok::r_paren))
275 if (1 + I[1]->Last->TotalLength > Limit)
277 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
280 // Only inline simple if's (no nested if or else).
281 if (I + 2 != E && Line.First->is(tok::kw_if) &&
282 I[2]->First->is(tok::kw_else))
288 tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
289 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
291 if (Limit == 0 || I + 1 == E ||
292 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
294 unsigned NumStmts = 0;
296 bool InPPDirective = I[0]->InPPDirective;
297 for (; NumStmts < 3; ++NumStmts) {
298 if (I + 1 + NumStmts == E)
300 const AnnotatedLine *Line = I[1 + NumStmts];
301 if (Line->InPPDirective != InPPDirective)
303 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
305 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
306 tok::kw_while, tok::comment))
308 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
310 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
316 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
317 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
319 AnnotatedLine &Line = **I;
321 // Don't merge ObjC @ keywords and methods.
322 // FIXME: If an option to allow short exception handling clauses on a single
323 // line is added, change this to not return for @try and friends.
324 if (Style.Language != FormatStyle::LK_Java &&
325 Line.First->isOneOf(tok::at, tok::minus, tok::plus))
328 // Check that the current line allows merging. This depends on whether we
329 // are in a control flow statements as well as several style flags.
330 if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
331 (Line.First->Next && Line.First->Next->is(tok::kw_else)))
333 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
334 tok::kw___try, tok::kw_catch, tok::kw___finally,
335 tok::kw_for, tok::r_brace) ||
336 Line.First->is(Keywords.kw___except)) {
337 if (!Style.AllowShortBlocksOnASingleLine)
339 if (!Style.AllowShortIfStatementsOnASingleLine &&
340 Line.First->is(tok::kw_if))
342 if (!Style.AllowShortLoopsOnASingleLine &&
343 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
345 // FIXME: Consider an option to allow short exception handling clauses on
347 // FIXME: This isn't covered by tests.
348 // FIXME: For catch, __except, __finally the first token on the line
349 // is '}', so this isn't correct here.
350 if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
351 Keywords.kw___except, tok::kw___finally))
355 FormatToken *Tok = I[1]->First;
356 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
357 (Tok->getNextNonComment() == nullptr ||
358 Tok->getNextNonComment()->is(tok::semi))) {
359 // We merge empty blocks even if the line exceeds the column limit.
360 Tok->SpacesRequiredBefore = 0;
361 Tok->CanBreakBefore = true;
363 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace) &&
364 !startsExternCBlock(Line)) {
365 // We don't merge short records.
366 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
367 Keywords.kw_interface))
370 // Check that we still have three lines and they fit into the limit.
371 if (I + 2 == E || I[2]->Type == LT_Invalid)
373 Limit = limitConsideringMacros(I + 2, E, Limit);
375 if (!nextTwoLinesFitInto(I, Limit))
378 // Second, check that the next line does not contain any braces - if it
379 // does, readability declines when putting it into a single line.
380 if (I[1]->Last->is(TT_LineComment))
383 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
388 // Last, check that the third line starts with a closing brace.
390 if (Tok->isNot(tok::r_brace))
393 // Don't merge "if (a) { .. } else {".
394 if (Tok->Next && Tok->Next->is(tok::kw_else))
402 /// Returns the modified column limit for \p I if it is inside a macro and
403 /// needs a trailing '\'.
405 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
406 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
408 if (I[0]->InPPDirective && I + 1 != E &&
409 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
410 return Limit < 2 ? 0 : Limit - 2;
415 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
417 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
419 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
422 bool containsMustBreak(const AnnotatedLine *Line) {
423 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
424 if (Tok->MustBreakBefore)
430 void join(AnnotatedLine &A, const AnnotatedLine &B) {
431 assert(!A.Last->Next);
432 assert(!B.First->Previous);
435 A.Last->Next = B.First;
436 B.First->Previous = A.Last;
437 B.First->CanBreakBefore = true;
438 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
439 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
440 Tok->TotalLength += LengthA;
445 const FormatStyle &Style;
446 const AdditionalKeywords &Keywords;
447 const SmallVectorImpl<AnnotatedLine*>::const_iterator End;
449 SmallVectorImpl<AnnotatedLine*>::const_iterator Next;
452 static void markFinalized(FormatToken *Tok) {
453 for (; Tok; Tok = Tok->Next) {
454 Tok->Finalized = true;
455 for (AnnotatedLine *Child : Tok->Children)
456 markFinalized(Child->First);
461 static void printLineState(const LineState &State) {
462 llvm::dbgs() << "State: ";
463 for (const ParenState &P : State.Stack) {
464 llvm::dbgs() << P.Indent << "|" << P.LastSpace << "|" << P.NestedBlockIndent
467 llvm::dbgs() << State.NextToken->TokenText << "\n";
471 /// \brief Base class for classes that format one \c AnnotatedLine.
472 class LineFormatter {
474 LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
475 const FormatStyle &Style,
476 UnwrappedLineFormatter *BlockFormatter)
477 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
478 BlockFormatter(BlockFormatter) {}
479 virtual ~LineFormatter() {}
481 /// \brief Formats an \c AnnotatedLine and returns the penalty.
483 /// If \p DryRun is \c false, directly applies the changes.
484 virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
488 /// \brief If the \p State's next token is an r_brace closing a nested block,
489 /// format the nested block before it.
491 /// Returns \c true if all children could be placed successfully and adapts
492 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
493 /// creates changes using \c Whitespaces.
495 /// The crucial idea here is that children always get formatted upon
496 /// encountering the closing brace right after the nested block. Now, if we
497 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
498 /// \c false), the entire block has to be kept on the same line (which is only
499 /// possible if it fits on the line, only contains a single statement, etc.
501 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
502 /// break after the "{", format all lines with correct indentation and the put
503 /// the closing "}" on yet another new line.
505 /// This enables us to keep the simple structure of the
506 /// \c UnwrappedLineFormatter, where we only have two options for each token:
507 /// break or don't break.
508 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
510 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
511 FormatToken &Previous = *State.NextToken->Previous;
512 if (!LBrace || LBrace->isNot(tok::l_brace) ||
513 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
514 // The previous token does not open a block. Nothing to do. We don't
515 // assert so that we can simply call this function for all tokens.
519 int AdditionalIndent = State.Stack.back().Indent -
520 Previous.Children[0]->Level * Style.IndentWidth;
523 BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
524 /*FixBadIndentation=*/true);
528 if (Previous.Children[0]->First->MustBreakBefore)
531 // Cannot merge multiple statements into a single line.
532 if (Previous.Children.size() > 1)
535 // Cannot merge into one line if this line ends on a comment.
536 if (Previous.is(tok::comment))
539 // We can't put the closing "}" on a line with a trailing comment.
540 if (Previous.Children[0]->Last->isTrailingComment())
543 // If the child line exceeds the column limit, we wouldn't want to merge it.
544 // We add +2 for the trailing " }".
545 if (Style.ColumnLimit > 0 &&
546 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
551 Whitespaces->replaceWhitespace(
552 *Previous.Children[0]->First,
553 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
554 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
556 Penalty += formatLine(*Previous.Children[0], State.Column + 1, DryRun);
558 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
562 ContinuationIndenter *Indenter;
565 WhitespaceManager *Whitespaces;
566 const FormatStyle &Style;
567 UnwrappedLineFormatter *BlockFormatter;
570 /// \brief Formatter that keeps the existing line breaks.
571 class NoColumnLimitLineFormatter : public LineFormatter {
573 NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
574 WhitespaceManager *Whitespaces,
575 const FormatStyle &Style,
576 UnwrappedLineFormatter *BlockFormatter)
577 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
579 /// \brief Formats the line, simply keeping all of the input's line breaking
581 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
582 bool DryRun) override {
585 Indenter->getInitialState(FirstIndent, &Line, /*DryRun=*/false);
586 while (State.NextToken) {
588 Indenter->mustBreak(State) ||
589 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
590 unsigned Penalty = 0;
591 formatChildren(State, Newline, /*DryRun=*/false, Penalty);
592 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
598 /// \brief Formatter that puts all tokens into a single line without breaks.
599 class NoLineBreakFormatter : public LineFormatter {
601 NoLineBreakFormatter(ContinuationIndenter *Indenter,
602 WhitespaceManager *Whitespaces, const FormatStyle &Style,
603 UnwrappedLineFormatter *BlockFormatter)
604 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
606 /// \brief Puts all tokens into a single line.
607 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
609 unsigned Penalty = 0;
610 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
611 while (State.NextToken) {
612 formatChildren(State, /*Newline=*/false, DryRun, Penalty);
613 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
619 /// \brief Finds the best way to break lines.
620 class OptimizingLineFormatter : public LineFormatter {
622 OptimizingLineFormatter(ContinuationIndenter *Indenter,
623 WhitespaceManager *Whitespaces,
624 const FormatStyle &Style,
625 UnwrappedLineFormatter *BlockFormatter)
626 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
628 /// \brief Formats the line by finding the best line breaks with line lengths
629 /// below the column limit.
630 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
632 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
634 // If the ObjC method declaration does not fit on a line, we should format
635 // it with one arg per line.
636 if (State.Line->Type == LT_ObjCMethodDecl)
637 State.Stack.back().BreakBeforeParameter = true;
639 // Find best solution in solution space.
640 return analyzeSolutionSpace(State, DryRun);
644 struct CompareLineStatePointers {
645 bool operator()(LineState *obj1, LineState *obj2) const {
646 return *obj1 < *obj2;
650 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
652 /// In case of equal penalties, we want to prefer states that were inserted
653 /// first. During state generation we make sure that we insert states first
654 /// that break the line as late as possible.
655 typedef std::pair<unsigned, unsigned> OrderedPenalty;
657 /// \brief An edge in the solution space from \c Previous->State to \c State,
658 /// inserting a newline dependent on the \c NewLine.
660 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
661 : State(State), NewLine(NewLine), Previous(Previous) {}
667 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
668 /// \c State has the given \c OrderedPenalty.
669 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
671 /// \brief The BFS queue type.
672 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
673 std::greater<QueueItem>> QueueType;
675 /// \brief Analyze the entire solution space starting from \p InitialState.
677 /// This implements a variant of Dijkstra's algorithm on the graph that spans
678 /// the solution space (\c LineStates are the nodes). The algorithm tries to
679 /// find the shortest path (the one with lowest penalty) from \p InitialState
680 /// to a state where all tokens are placed. Returns the penalty.
682 /// If \p DryRun is \c false, directly applies the changes.
683 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
684 std::set<LineState *, CompareLineStatePointers> Seen;
686 // Increasing count of \c StateNode items we have created. This is used to
687 // create a deterministic order independent of the container.
691 // Insert start element into queue.
693 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
694 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
697 unsigned Penalty = 0;
699 // While not empty, take first element and follow edges.
700 while (!Queue.empty()) {
701 Penalty = Queue.top().first.first;
702 StateNode *Node = Queue.top().second;
703 if (!Node->State.NextToken) {
704 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
709 // Cut off the analysis of certain solutions if the analysis gets too
710 // complex. See description of IgnoreStackForComparison.
712 Node->State.IgnoreStackForComparison = true;
714 if (!Seen.insert(&Node->State).second)
715 // State already examined with lower penalty.
718 FormatDecision LastFormat = Node->State.NextToken->Decision;
719 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
720 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
721 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
722 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
726 // We were unable to find a solution, do nothing.
727 // FIXME: Add diagnostic?
728 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
732 // Reconstruct the solution.
734 reconstructPath(InitialState, Queue.top().second);
736 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
737 DEBUG(llvm::dbgs() << "---\n");
742 /// \brief Add the following state to the analysis queue \c Queue.
744 /// Assume the current state is \p PreviousNode and has been reached with a
745 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
746 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
747 bool NewLine, unsigned *Count, QueueType *Queue) {
748 if (NewLine && !Indenter->canBreak(PreviousNode->State))
750 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
753 StateNode *Node = new (Allocator.Allocate())
754 StateNode(PreviousNode->State, NewLine, PreviousNode);
755 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
758 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
760 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
764 /// \brief Applies the best formatting by reconstructing the path in the
765 /// solution space that leads to \c Best.
766 void reconstructPath(LineState &State, StateNode *Best) {
767 std::deque<StateNode *> Path;
768 // We do not need a break before the initial token.
769 while (Best->Previous) {
770 Path.push_front(Best);
771 Best = Best->Previous;
773 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
775 unsigned Penalty = 0;
776 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
777 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
780 printLineState((*I)->Previous->State);
782 llvm::dbgs() << "Penalty for placing "
783 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
790 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
796 UnwrappedLineFormatter::format(const SmallVectorImpl<AnnotatedLine *> &Lines,
797 bool DryRun, int AdditionalIndent,
798 bool FixBadIndentation) {
799 LineJoiner Joiner(Style, Keywords, Lines);
801 // Try to look up already computed penalty in DryRun-mode.
802 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
803 &Lines, AdditionalIndent);
804 auto CacheIt = PenaltyCache.find(CacheKey);
805 if (DryRun && CacheIt != PenaltyCache.end())
806 return CacheIt->second;
808 assert(!Lines.empty());
809 unsigned Penalty = 0;
810 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
812 const AnnotatedLine *PreviousLine = nullptr;
813 const AnnotatedLine *NextLine = nullptr;
814 for (const AnnotatedLine *Line =
815 Joiner.getNextMergedLine(DryRun, IndentTracker);
816 Line; Line = NextLine) {
817 const AnnotatedLine &TheLine = *Line;
818 unsigned Indent = IndentTracker.getIndent();
819 bool FixIndentation =
820 FixBadIndentation && (Indent != TheLine.First->OriginalColumn);
821 bool ShouldFormat = TheLine.Affected || FixIndentation;
822 // We cannot format this line; if the reason is that the line had a
823 // parsing error, remember that.
824 if (ShouldFormat && TheLine.Type == LT_Invalid && IncompleteFormat)
825 *IncompleteFormat = true;
827 if (ShouldFormat && TheLine.Type != LT_Invalid) {
829 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level, Indent,
830 TheLine.InPPDirective);
832 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
833 unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
834 bool FitsIntoOneLine =
835 TheLine.Last->TotalLength + Indent <= ColumnLimit ||
836 TheLine.Type == LT_ImportStatement;
838 if (Style.ColumnLimit == 0)
839 NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
840 .formatLine(TheLine, Indent, DryRun);
841 else if (FitsIntoOneLine)
842 Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
843 .formatLine(TheLine, Indent, DryRun);
845 Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
846 .formatLine(TheLine, Indent, DryRun);
848 // If no token in the current line is affected, we still need to format
849 // affected children.
850 if (TheLine.ChildrenAffected)
851 format(TheLine.Children, DryRun);
853 // Adapt following lines on the current indent level to the same level
854 // unless the current \c AnnotatedLine is not at the beginning of a line.
856 TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
858 IndentTracker.adjustToUnmodifiedLine(TheLine);
860 bool ReformatLeadingWhitespace =
861 StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
862 TheLine.LeadingEmptyLinesAffected);
863 // Format the first token.
864 if (ReformatLeadingWhitespace)
865 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
866 TheLine.First->OriginalColumn,
867 TheLine.InPPDirective);
869 Whitespaces->addUntouchableToken(*TheLine.First,
870 TheLine.InPPDirective);
872 // Notify the WhitespaceManager about the unchanged whitespace.
873 for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
874 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
876 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
879 markFinalized(TheLine.First);
880 PreviousLine = &TheLine;
882 PenaltyCache[CacheKey] = Penalty;
886 void UnwrappedLineFormatter::formatFirstToken(FormatToken &RootToken,
887 const AnnotatedLine *PreviousLine,
888 unsigned IndentLevel,
890 bool InPPDirective) {
891 if (RootToken.is(tok::eof)) {
892 unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u);
893 Whitespaces->replaceWhitespace(RootToken, Newlines, /*IndentLevel=*/0,
894 /*Spaces=*/0, /*TargetColumn=*/0);
898 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
899 // Remove empty lines before "}" where applicable.
900 if (RootToken.is(tok::r_brace) &&
902 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
903 Newlines = std::min(Newlines, 1u);
904 if (Newlines == 0 && !RootToken.IsFirst)
906 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
909 // Remove empty lines after "{".
910 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
911 PreviousLine->Last->is(tok::l_brace) &&
912 PreviousLine->First->isNot(tok::kw_namespace) &&
913 !startsExternCBlock(*PreviousLine))
916 // Insert extra new line before access specifiers.
917 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
918 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
921 // Remove empty lines after access specifiers.
922 if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
923 (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline))
924 Newlines = std::min(1u, Newlines);
926 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
927 Indent, InPPDirective &&
928 !RootToken.HasUnescapedNewline);
932 UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
933 const AnnotatedLine *NextLine) const {
934 // In preprocessor directives reserve two chars for trailing " \" if the
935 // next line continues the preprocessor directive.
936 bool ContinuesPPDirective =
938 // If there is no next line, this is likely a child line and the parent
939 // continues the preprocessor directive.
941 (NextLine->InPPDirective &&
942 // If there is an unescaped newline between this line and the next, the
943 // next line starts a new preprocessor directive.
944 !NextLine->First->HasUnescapedNewline));
945 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
948 } // namespace format