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"
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);
29 /// \brief Tracks the indent level of \c AnnotatedLines across levels.
31 /// \c nextLine must be called for each \c AnnotatedLine, after which \c
32 /// getIndent() will return the indent for the last line \c nextLine was called
34 /// If the line is not formatted (and thus the indent does not change), calling
35 /// \c adjustToUnmodifiedLine after the call to \c nextLine will cause
36 /// subsequent lines on the same level to be indented at the same level as the
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);
48 /// \brief Returns the indent for the current line.
49 unsigned getIndent() const { return Indent; }
51 /// \brief Update the indent state given that \p Line is going to be formatted
53 void nextLine(const AnnotatedLine &Line) {
54 Offset = getIndentOffset(*Line.First);
55 // Update the indent level cache size so that we can rely on it
56 // having the right size in adjustToUnmodifiedline.
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)
69 /// \brief Update the indent state given that \p Line indent should be
71 void skipLine(const AnnotatedLine &Line) {
72 while (IndentForLevel.size() <= Line.Level)
73 IndentForLevel.push_back(Indent);
76 /// \brief Update the level indent to adapt to the given \p Line.
78 /// When a line is not formatted, we move the subsequent lines on the same
79 /// level to the same indent.
80 /// Note that \c nextLine must have been called before this method.
81 void adjustToUnmodifiedLine(const AnnotatedLine &Line) {
82 unsigned LevelIndent = Line.First->OriginalColumn;
83 if (static_cast<int>(LevelIndent) - Offset >= 0)
84 LevelIndent -= Offset;
85 if ((!Line.First->is(tok::comment) || IndentForLevel[Line.Level] == -1) &&
87 IndentForLevel[Line.Level] = LevelIndent;
91 /// \brief Get the offset of the line relatively to the level.
93 /// For example, 'public:' labels in classes are offset by 1 or 2
94 /// characters to the left from their level.
95 int getIndentOffset(const FormatToken &RootToken) {
96 if (Style.Language == FormatStyle::LK_Java ||
97 Style.Language == FormatStyle::LK_JavaScript)
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;
107 /// \brief Get the indent of \p Level from \p IndentForLevel.
109 /// \p IndentForLevel must contain the indent for the level \c l
110 /// at \p IndentForLevel[l], or a value < 0 if the indent for
111 /// that level is unknown.
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;
124 /// \brief The indent in characters for each level.
125 std::vector<int> IndentForLevel;
127 /// \brief Offset of the current line relative to the indent level.
129 /// For example, the 'public' keywords is often indented with a negative
133 /// \brief The current line's indent.
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;
147 if (StartLineIndex == UnwrappedLine::kInvalidIndex)
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) {}
160 /// \brief Returns the next line, merging multiple lines into one if possible.
161 const AnnotatedLine *getNextMergedLine(bool DryRun,
162 LevelIndentTracker &IndentTracker) {
165 const AnnotatedLine *Current = *Next;
166 IndentTracker.nextLine(*Current);
167 unsigned MergedLines =
168 tryFitMultipleLinesInOne(IndentTracker, Next, End);
169 if (MergedLines > 0 && Style.ColumnLimit == 0)
170 // Disallow line merging if there is a break at the start of one of the
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;
183 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
185 tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker,
186 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
187 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
188 const unsigned Indent = IndentTracker.getIndent();
190 // Can't join the last line with anything.
193 // We can never merge stuff if there are trailing line comments.
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;
208 // If we already exceed the column limit, we set 'Limit' to 0. The different
209 // tryMerge..() functions can then decide whether to still do merging.
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);
220 // Handle empty record blocks where the brace has already been wrapped
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))
227 Tok = Tok->getNextNonComment();
229 if (Tok && Tok->getNamespaceToken())
230 return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock
231 ? tryMergeSimpleBlock(I, E, Limit) : 0;
233 if (Tok && Tok->is(tok::kw_typedef))
234 Tok = Tok->getNextNonComment();
235 if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union,
236 Keywords.kw_interface))
237 return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock
238 ? tryMergeSimpleBlock(I, E, Limit) : 0;
241 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
242 // If necessary, change to something smarter.
243 bool MergeShortFunctions =
244 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
245 (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
246 I[1]->First->is(tok::r_brace)) ||
247 (Style.AllowShortFunctionsOnASingleLine & FormatStyle::SFS_InlineOnly &&
248 TheLine->Level != 0);
250 if (Style.CompactNamespaces) {
251 if (isNamespaceDeclaration(TheLine)) {
253 unsigned closingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
254 for (; I + 1 + i != E && isNamespaceDeclaration(I[i + 1]) &&
255 closingLine == I[i + 1]->MatchingOpeningBlockLineIndex &&
256 I[i + 1]->Last->TotalLength < Limit;
257 i++, closingLine--) {
258 // No extra indent for compacted namespaces
259 IndentTracker.skipLine(*I[i + 1]);
261 Limit -= I[i + 1]->Last->TotalLength;
266 if (isEndOfNamespace(TheLine, AnnotatedLines)) {
268 unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
269 for (; I + 1 + i != E && isEndOfNamespace(I[i + 1], AnnotatedLines) &&
270 openingLine == I[i + 1]->MatchingOpeningBlockLineIndex;
271 i++, openingLine--) {
272 // No space between consecutive braces
273 I[i + 1]->First->SpacesRequiredBefore = !I[i]->Last->is(tok::r_brace);
275 // Indent like the outer-most namespace
276 IndentTracker.nextLine(*I[i + 1]);
282 if (TheLine->Last->is(TT_FunctionLBrace) &&
283 TheLine->First != TheLine->Last) {
284 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
286 if (TheLine->Last->is(tok::l_brace)) {
287 return !Style.BraceWrapping.AfterFunction
288 ? tryMergeSimpleBlock(I, E, Limit)
291 if (I[1]->First->is(TT_FunctionLBrace) &&
292 Style.BraceWrapping.AfterFunction) {
293 if (I[1]->Last->is(TT_LineComment))
296 // Check for Limit <= 2 to account for the " {".
297 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
301 unsigned MergedLines = 0;
302 if (MergeShortFunctions ||
303 (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
304 I[1]->First == I[1]->Last && I + 2 != E &&
305 I[2]->First->is(tok::r_brace))) {
306 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
307 // If we managed to merge the block, count the function header, which is
308 // on a separate line.
314 if (TheLine->First->is(tok::kw_if)) {
315 return Style.AllowShortIfStatementsOnASingleLine
316 ? tryMergeSimpleControlStatement(I, E, Limit)
319 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
320 return Style.AllowShortLoopsOnASingleLine
321 ? tryMergeSimpleControlStatement(I, E, Limit)
324 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
325 return Style.AllowShortCaseLabelsOnASingleLine
326 ? tryMergeShortCaseLabels(I, E, Limit)
329 if (TheLine->InPPDirective &&
330 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
331 return tryMergeSimplePPDirective(I, E, Limit);
337 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
338 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
342 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
344 if (1 + I[1]->Last->TotalLength > Limit)
349 unsigned tryMergeSimpleControlStatement(
350 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
351 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
354 if (Style.BraceWrapping.AfterControlStatement &&
355 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
357 if (I[1]->InPPDirective != (*I)->InPPDirective ||
358 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
360 Limit = limitConsideringMacros(I + 1, E, Limit);
361 AnnotatedLine &Line = **I;
362 if (Line.Last->isNot(tok::r_paren))
364 if (1 + I[1]->Last->TotalLength > Limit)
366 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
369 // Only inline simple if's (no nested if or else).
370 if (I + 2 != E && Line.startsWith(tok::kw_if) &&
371 I[2]->First->is(tok::kw_else))
377 tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
378 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
380 if (Limit == 0 || I + 1 == E ||
381 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
383 unsigned NumStmts = 0;
385 bool InPPDirective = I[0]->InPPDirective;
386 for (; NumStmts < 3; ++NumStmts) {
387 if (I + 1 + NumStmts == E)
389 const AnnotatedLine *Line = I[1 + NumStmts];
390 if (Line->InPPDirective != InPPDirective)
392 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
394 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
395 tok::kw_while, tok::comment) ||
396 Line->Last->is(tok::comment))
398 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
400 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
406 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
407 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
409 AnnotatedLine &Line = **I;
411 // Don't merge ObjC @ keywords and methods.
412 // FIXME: If an option to allow short exception handling clauses on a single
413 // line is added, change this to not return for @try and friends.
414 if (Style.Language != FormatStyle::LK_Java &&
415 Line.First->isOneOf(tok::at, tok::minus, tok::plus))
418 // Check that the current line allows merging. This depends on whether we
419 // are in a control flow statements as well as several style flags.
420 if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
421 (Line.First->Next && Line.First->Next->is(tok::kw_else)))
423 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
424 tok::kw___try, tok::kw_catch, tok::kw___finally,
425 tok::kw_for, tok::r_brace, Keywords.kw___except)) {
426 if (!Style.AllowShortBlocksOnASingleLine)
428 if (!Style.AllowShortIfStatementsOnASingleLine &&
429 Line.startsWith(tok::kw_if))
431 if (!Style.AllowShortLoopsOnASingleLine &&
432 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
434 // FIXME: Consider an option to allow short exception handling clauses on
436 // FIXME: This isn't covered by tests.
437 // FIXME: For catch, __except, __finally the first token on the line
438 // is '}', so this isn't correct here.
439 if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
440 Keywords.kw___except, tok::kw___finally))
444 FormatToken *Tok = I[1]->First;
445 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
446 (Tok->getNextNonComment() == nullptr ||
447 Tok->getNextNonComment()->is(tok::semi))) {
448 // We merge empty blocks even if the line exceeds the column limit.
449 Tok->SpacesRequiredBefore = 0;
450 Tok->CanBreakBefore = true;
452 } else if (Limit != 0 && !Line.startsWith(tok::kw_namespace) &&
453 !startsExternCBlock(Line)) {
454 // We don't merge short records.
455 FormatToken *RecordTok =
456 Line.First->is(tok::kw_typedef) ? Line.First->Next : Line.First;
458 RecordTok->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
459 Keywords.kw_interface))
462 // Check that we still have three lines and they fit into the limit.
463 if (I + 2 == E || I[2]->Type == LT_Invalid)
465 Limit = limitConsideringMacros(I + 2, E, Limit);
467 if (!nextTwoLinesFitInto(I, Limit))
470 // Second, check that the next line does not contain any braces - if it
471 // does, readability declines when putting it into a single line.
472 if (I[1]->Last->is(TT_LineComment))
475 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
480 // Last, check that the third line starts with a closing brace.
482 if (Tok->isNot(tok::r_brace))
485 // Don't merge "if (a) { .. } else {".
486 if (Tok->Next && Tok->Next->is(tok::kw_else))
494 /// Returns the modified column limit for \p I if it is inside a macro and
495 /// needs a trailing '\'.
497 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
498 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
500 if (I[0]->InPPDirective && I + 1 != E &&
501 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
502 return Limit < 2 ? 0 : Limit - 2;
507 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
509 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
511 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
514 bool containsMustBreak(const AnnotatedLine *Line) {
515 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
516 if (Tok->MustBreakBefore)
522 void join(AnnotatedLine &A, const AnnotatedLine &B) {
523 assert(!A.Last->Next);
524 assert(!B.First->Previous);
527 A.Last->Next = B.First;
528 B.First->Previous = A.Last;
529 B.First->CanBreakBefore = true;
530 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
531 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
532 Tok->TotalLength += LengthA;
537 const FormatStyle &Style;
538 const AdditionalKeywords &Keywords;
539 const SmallVectorImpl<AnnotatedLine *>::const_iterator End;
541 SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
542 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
545 static void markFinalized(FormatToken *Tok) {
546 for (; Tok; Tok = Tok->Next) {
547 Tok->Finalized = true;
548 for (AnnotatedLine *Child : Tok->Children)
549 markFinalized(Child->First);
554 static void printLineState(const LineState &State) {
555 llvm::dbgs() << "State: ";
556 for (const ParenState &P : State.Stack) {
557 llvm::dbgs() << P.Indent << "|" << P.LastSpace << "|" << P.NestedBlockIndent
560 llvm::dbgs() << State.NextToken->TokenText << "\n";
564 /// \brief Base class for classes that format one \c AnnotatedLine.
565 class LineFormatter {
567 LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
568 const FormatStyle &Style,
569 UnwrappedLineFormatter *BlockFormatter)
570 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
571 BlockFormatter(BlockFormatter) {}
572 virtual ~LineFormatter() {}
574 /// \brief Formats an \c AnnotatedLine and returns the penalty.
576 /// If \p DryRun is \c false, directly applies the changes.
577 virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
581 /// \brief If the \p State's next token is an r_brace closing a nested block,
582 /// format the nested block before it.
584 /// Returns \c true if all children could be placed successfully and adapts
585 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
586 /// creates changes using \c Whitespaces.
588 /// The crucial idea here is that children always get formatted upon
589 /// encountering the closing brace right after the nested block. Now, if we
590 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
591 /// \c false), the entire block has to be kept on the same line (which is only
592 /// possible if it fits on the line, only contains a single statement, etc.
594 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
595 /// break after the "{", format all lines with correct indentation and the put
596 /// the closing "}" on yet another new line.
598 /// This enables us to keep the simple structure of the
599 /// \c UnwrappedLineFormatter, where we only have two options for each token:
600 /// break or don't break.
601 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
603 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
604 FormatToken &Previous = *State.NextToken->Previous;
605 if (!LBrace || LBrace->isNot(tok::l_brace) ||
606 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
607 // The previous token does not open a block. Nothing to do. We don't
608 // assert so that we can simply call this function for all tokens.
612 int AdditionalIndent = State.Stack.back().Indent -
613 Previous.Children[0]->Level * Style.IndentWidth;
616 BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
617 /*FixBadIndentation=*/true);
621 if (Previous.Children[0]->First->MustBreakBefore)
624 // Cannot merge into one line if this line ends on a comment.
625 if (Previous.is(tok::comment))
628 // Cannot merge multiple statements into a single line.
629 if (Previous.Children.size() > 1)
632 const AnnotatedLine *Child = Previous.Children[0];
633 // We can't put the closing "}" on a line with a trailing comment.
634 if (Child->Last->isTrailingComment())
637 // If the child line exceeds the column limit, we wouldn't want to merge it.
638 // We add +2 for the trailing " }".
639 if (Style.ColumnLimit > 0 &&
640 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit)
644 Whitespaces->replaceWhitespace(
645 *Child->First, /*Newlines=*/0, /*Spaces=*/1,
646 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
648 Penalty += formatLine(*Child, State.Column + 1, DryRun);
650 State.Column += 1 + Child->Last->TotalLength;
654 ContinuationIndenter *Indenter;
657 WhitespaceManager *Whitespaces;
658 const FormatStyle &Style;
659 UnwrappedLineFormatter *BlockFormatter;
662 /// \brief Formatter that keeps the existing line breaks.
663 class NoColumnLimitLineFormatter : public LineFormatter {
665 NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
666 WhitespaceManager *Whitespaces,
667 const FormatStyle &Style,
668 UnwrappedLineFormatter *BlockFormatter)
669 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
671 /// \brief Formats the line, simply keeping all of the input's line breaking
673 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
674 bool DryRun) override {
677 Indenter->getInitialState(FirstIndent, &Line, /*DryRun=*/false);
678 while (State.NextToken) {
680 Indenter->mustBreak(State) ||
681 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
682 unsigned Penalty = 0;
683 formatChildren(State, Newline, /*DryRun=*/false, Penalty);
684 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
690 /// \brief Formatter that puts all tokens into a single line without breaks.
691 class NoLineBreakFormatter : public LineFormatter {
693 NoLineBreakFormatter(ContinuationIndenter *Indenter,
694 WhitespaceManager *Whitespaces, const FormatStyle &Style,
695 UnwrappedLineFormatter *BlockFormatter)
696 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
698 /// \brief Puts all tokens into a single line.
699 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
700 bool DryRun) override {
701 unsigned Penalty = 0;
702 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
703 while (State.NextToken) {
704 formatChildren(State, /*Newline=*/false, DryRun, Penalty);
705 Indenter->addTokenToState(
706 State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun);
712 /// \brief Finds the best way to break lines.
713 class OptimizingLineFormatter : public LineFormatter {
715 OptimizingLineFormatter(ContinuationIndenter *Indenter,
716 WhitespaceManager *Whitespaces,
717 const FormatStyle &Style,
718 UnwrappedLineFormatter *BlockFormatter)
719 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
721 /// \brief Formats the line by finding the best line breaks with line lengths
722 /// below the column limit.
723 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
724 bool DryRun) override {
725 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
727 // If the ObjC method declaration does not fit on a line, we should format
728 // it with one arg per line.
729 if (State.Line->Type == LT_ObjCMethodDecl)
730 State.Stack.back().BreakBeforeParameter = true;
732 // Find best solution in solution space.
733 return analyzeSolutionSpace(State, DryRun);
737 struct CompareLineStatePointers {
738 bool operator()(LineState *obj1, LineState *obj2) const {
739 return *obj1 < *obj2;
743 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
745 /// In case of equal penalties, we want to prefer states that were inserted
746 /// first. During state generation we make sure that we insert states first
747 /// that break the line as late as possible.
748 typedef std::pair<unsigned, unsigned> OrderedPenalty;
750 /// \brief An edge in the solution space from \c Previous->State to \c State,
751 /// inserting a newline dependent on the \c NewLine.
753 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
754 : State(State), NewLine(NewLine), Previous(Previous) {}
760 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
761 /// \c State has the given \c OrderedPenalty.
762 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
764 /// \brief The BFS queue type.
765 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
766 std::greater<QueueItem>> QueueType;
768 /// \brief Analyze the entire solution space starting from \p InitialState.
770 /// This implements a variant of Dijkstra's algorithm on the graph that spans
771 /// the solution space (\c LineStates are the nodes). The algorithm tries to
772 /// find the shortest path (the one with lowest penalty) from \p InitialState
773 /// to a state where all tokens are placed. Returns the penalty.
775 /// If \p DryRun is \c false, directly applies the changes.
776 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
777 std::set<LineState *, CompareLineStatePointers> Seen;
779 // Increasing count of \c StateNode items we have created. This is used to
780 // create a deterministic order independent of the container.
784 // Insert start element into queue.
786 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
787 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
790 unsigned Penalty = 0;
792 // While not empty, take first element and follow edges.
793 while (!Queue.empty()) {
794 Penalty = Queue.top().first.first;
795 StateNode *Node = Queue.top().second;
796 if (!Node->State.NextToken) {
797 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
802 // Cut off the analysis of certain solutions if the analysis gets too
803 // complex. See description of IgnoreStackForComparison.
805 Node->State.IgnoreStackForComparison = true;
807 if (!Seen.insert(&Node->State).second)
808 // State already examined with lower penalty.
811 FormatDecision LastFormat = Node->State.NextToken->Decision;
812 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
813 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
814 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
815 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
819 // We were unable to find a solution, do nothing.
820 // FIXME: Add diagnostic?
821 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
825 // Reconstruct the solution.
827 reconstructPath(InitialState, Queue.top().second);
829 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
830 DEBUG(llvm::dbgs() << "---\n");
835 /// \brief Add the following state to the analysis queue \c Queue.
837 /// Assume the current state is \p PreviousNode and has been reached with a
838 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
839 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
840 bool NewLine, unsigned *Count, QueueType *Queue) {
841 if (NewLine && !Indenter->canBreak(PreviousNode->State))
843 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
846 StateNode *Node = new (Allocator.Allocate())
847 StateNode(PreviousNode->State, NewLine, PreviousNode);
848 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
851 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
853 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
857 /// \brief Applies the best formatting by reconstructing the path in the
858 /// solution space that leads to \c Best.
859 void reconstructPath(LineState &State, StateNode *Best) {
860 std::deque<StateNode *> Path;
861 // We do not need a break before the initial token.
862 while (Best->Previous) {
863 Path.push_front(Best);
864 Best = Best->Previous;
866 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
868 unsigned Penalty = 0;
869 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
870 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
873 printLineState((*I)->Previous->State);
875 llvm::dbgs() << "Penalty for placing "
876 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
883 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
886 } // anonymous namespace
889 UnwrappedLineFormatter::format(const SmallVectorImpl<AnnotatedLine *> &Lines,
890 bool DryRun, int AdditionalIndent,
891 bool FixBadIndentation) {
892 LineJoiner Joiner(Style, Keywords, Lines);
894 // Try to look up already computed penalty in DryRun-mode.
895 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
896 &Lines, AdditionalIndent);
897 auto CacheIt = PenaltyCache.find(CacheKey);
898 if (DryRun && CacheIt != PenaltyCache.end())
899 return CacheIt->second;
901 assert(!Lines.empty());
902 unsigned Penalty = 0;
903 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
905 const AnnotatedLine *PreviousLine = nullptr;
906 const AnnotatedLine *NextLine = nullptr;
908 // The minimum level of consecutive lines that have been formatted.
909 unsigned RangeMinLevel = UINT_MAX;
911 for (const AnnotatedLine *Line =
912 Joiner.getNextMergedLine(DryRun, IndentTracker);
913 Line; Line = NextLine) {
914 const AnnotatedLine &TheLine = *Line;
915 unsigned Indent = IndentTracker.getIndent();
917 // We continue formatting unchanged lines to adjust their indent, e.g. if a
918 // scope was added. However, we need to carefully stop doing this when we
919 // exit the scope of affected lines to prevent indenting a the entire
920 // remaining file if it currently missing a closing brace.
921 bool ContinueFormatting =
922 TheLine.Level > RangeMinLevel ||
923 (TheLine.Level == RangeMinLevel && !TheLine.startsWith(tok::r_brace));
925 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
926 Indent != TheLine.First->OriginalColumn;
927 bool ShouldFormat = TheLine.Affected || FixIndentation;
928 // We cannot format this line; if the reason is that the line had a
929 // parsing error, remember that.
930 if (ShouldFormat && TheLine.Type == LT_Invalid && Status) {
931 Status->FormatComplete = false;
933 SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation());
936 if (ShouldFormat && TheLine.Type != LT_Invalid) {
938 formatFirstToken(TheLine, PreviousLine, Indent);
940 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
941 unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
942 bool FitsIntoOneLine =
943 TheLine.Last->TotalLength + Indent <= ColumnLimit ||
944 (TheLine.Type == LT_ImportStatement &&
945 (Style.Language != FormatStyle::LK_JavaScript ||
946 !Style.JavaScriptWrapImports));
948 if (Style.ColumnLimit == 0)
949 NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
950 .formatLine(TheLine, Indent, DryRun);
951 else if (FitsIntoOneLine)
952 Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
953 .formatLine(TheLine, Indent, DryRun);
955 Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
956 .formatLine(TheLine, Indent, DryRun);
957 RangeMinLevel = std::min(RangeMinLevel, TheLine.Level);
959 // If no token in the current line is affected, we still need to format
960 // affected children.
961 if (TheLine.ChildrenAffected)
962 for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next)
963 if (!Tok->Children.empty())
964 format(Tok->Children, DryRun);
966 // Adapt following lines on the current indent level to the same level
967 // unless the current \c AnnotatedLine is not at the beginning of a line.
969 TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
971 IndentTracker.adjustToUnmodifiedLine(TheLine);
973 bool ReformatLeadingWhitespace =
974 StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
975 TheLine.LeadingEmptyLinesAffected);
976 // Format the first token.
977 if (ReformatLeadingWhitespace)
978 formatFirstToken(TheLine, PreviousLine,
979 TheLine.First->OriginalColumn);
981 Whitespaces->addUntouchableToken(*TheLine.First,
982 TheLine.InPPDirective);
984 // Notify the WhitespaceManager about the unchanged whitespace.
985 for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
986 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
988 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
989 RangeMinLevel = UINT_MAX;
992 markFinalized(TheLine.First);
993 PreviousLine = &TheLine;
995 PenaltyCache[CacheKey] = Penalty;
999 void UnwrappedLineFormatter::formatFirstToken(const AnnotatedLine &Line,
1000 const AnnotatedLine *PreviousLine,
1002 FormatToken& RootToken = *Line.First;
1003 if (RootToken.is(tok::eof)) {
1004 unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u);
1005 Whitespaces->replaceWhitespace(RootToken, Newlines, /*Spaces=*/0,
1006 /*StartOfTokenColumn=*/0);
1010 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1011 // Remove empty lines before "}" where applicable.
1012 if (RootToken.is(tok::r_brace) &&
1014 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1015 Newlines = std::min(Newlines, 1u);
1016 if (Newlines == 0 && !RootToken.IsFirst)
1018 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1021 // Remove empty lines after "{".
1022 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1023 PreviousLine->Last->is(tok::l_brace) &&
1024 PreviousLine->First->isNot(tok::kw_namespace) &&
1025 !startsExternCBlock(*PreviousLine))
1028 // Insert extra new line before access specifiers.
1029 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1030 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1033 // Remove empty lines after access specifiers.
1034 if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
1035 (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline))
1036 Newlines = std::min(1u, Newlines);
1038 Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent,
1039 Line.InPPDirective &&
1040 !RootToken.HasUnescapedNewline);
1044 UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
1045 const AnnotatedLine *NextLine) const {
1046 // In preprocessor directives reserve two chars for trailing " \" if the
1047 // next line continues the preprocessor directive.
1048 bool ContinuesPPDirective =
1050 // If there is no next line, this is likely a child line and the parent
1051 // continues the preprocessor directive.
1053 (NextLine->InPPDirective &&
1054 // If there is an unescaped newline between this line and the next, the
1055 // next line starts a new preprocessor directive.
1056 !NextLine->First->HasUnescapedNewline));
1057 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
1060 } // namespace format
1061 } // namespace clang