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 // Detect "(inline)? namespace" in the beginning of a line.
140 if (NamespaceTok->is(tok::kw_inline))
141 NamespaceTok = NamespaceTok->getNextNonComment();
142 return NamespaceTok && NamespaceTok->is(tok::kw_namespace);
145 bool isEndOfNamespace(const AnnotatedLine *Line,
146 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
147 if (!Line->startsWith(tok::r_brace))
149 size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex;
150 if (StartLineIndex == UnwrappedLine::kInvalidIndex)
152 assert(StartLineIndex < AnnotatedLines.size());
153 return isNamespaceDeclaration(AnnotatedLines[StartLineIndex]);
158 LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords,
159 const SmallVectorImpl<AnnotatedLine *> &Lines)
160 : Style(Style), Keywords(Keywords), End(Lines.end()), Next(Lines.begin()),
161 AnnotatedLines(Lines) {}
163 /// \brief Returns the next line, merging multiple lines into one if possible.
164 const AnnotatedLine *getNextMergedLine(bool DryRun,
165 LevelIndentTracker &IndentTracker) {
168 const AnnotatedLine *Current = *Next;
169 IndentTracker.nextLine(*Current);
170 unsigned MergedLines =
171 tryFitMultipleLinesInOne(IndentTracker, Next, End);
172 if (MergedLines > 0 && Style.ColumnLimit == 0)
173 // Disallow line merging if there is a break at the start of one of the
175 for (unsigned i = 0; i < MergedLines; ++i)
176 if (Next[i + 1]->First->NewlinesBefore > 0)
179 for (unsigned i = 0; i < MergedLines; ++i)
180 join(*Next[0], *Next[i + 1]);
181 Next = Next + MergedLines + 1;
186 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
188 tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker,
189 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
190 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
191 const unsigned Indent = IndentTracker.getIndent();
193 // Can't join the last line with anything.
196 // We can never merge stuff if there are trailing line comments.
197 const AnnotatedLine *TheLine = *I;
198 if (TheLine->Last->is(TT_LineComment))
200 if (I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
202 if (TheLine->InPPDirective &&
203 (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline))
206 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
210 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
211 // If we already exceed the column limit, we set 'Limit' to 0. The different
212 // tryMerge..() functions can then decide whether to still do merging.
213 Limit = TheLine->Last->TotalLength > Limit
215 : Limit - TheLine->Last->TotalLength;
217 if (TheLine->Last->is(TT_FunctionLBrace) &&
218 TheLine->First == TheLine->Last &&
219 !Style.BraceWrapping.SplitEmptyFunctionBody &&
220 I[1]->First->is(tok::r_brace))
221 return tryMergeSimpleBlock(I, E, Limit);
223 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
224 // If necessary, change to something smarter.
225 bool MergeShortFunctions =
226 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
227 (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
228 I[1]->First->is(tok::r_brace)) ||
229 (Style.AllowShortFunctionsOnASingleLine & FormatStyle::SFS_InlineOnly &&
230 TheLine->Level != 0);
232 if (Style.CompactNamespaces) {
233 if (isNamespaceDeclaration(TheLine)) {
235 unsigned closingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
236 for (; I + 1 + i != E && isNamespaceDeclaration(I[i + 1]) &&
237 closingLine == I[i + 1]->MatchingOpeningBlockLineIndex &&
238 I[i + 1]->Last->TotalLength < Limit;
239 i++, closingLine--) {
240 // No extra indent for compacted namespaces
241 IndentTracker.skipLine(*I[i + 1]);
243 Limit -= I[i + 1]->Last->TotalLength;
248 if (isEndOfNamespace(TheLine, AnnotatedLines)) {
250 unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
251 for (; I + 1 + i != E && isEndOfNamespace(I[i + 1], AnnotatedLines) &&
252 openingLine == I[i + 1]->MatchingOpeningBlockLineIndex;
253 i++, openingLine--) {
254 // No space between consecutive braces
255 I[i + 1]->First->SpacesRequiredBefore = !I[i]->Last->is(tok::r_brace);
257 // Indent like the outer-most namespace
258 IndentTracker.nextLine(*I[i + 1]);
264 if (TheLine->Last->is(TT_FunctionLBrace) &&
265 TheLine->First != TheLine->Last) {
266 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
268 if (TheLine->Last->is(tok::l_brace)) {
269 return !Style.BraceWrapping.AfterFunction
270 ? tryMergeSimpleBlock(I, E, Limit)
273 if (I[1]->First->is(TT_FunctionLBrace) &&
274 Style.BraceWrapping.AfterFunction) {
275 if (I[1]->Last->is(TT_LineComment))
278 // Check for Limit <= 2 to account for the " {".
279 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
283 unsigned MergedLines = 0;
284 if (MergeShortFunctions ||
285 (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
286 I[1]->First == I[1]->Last && I + 2 != E &&
287 I[2]->First->is(tok::r_brace))) {
288 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
289 // If we managed to merge the block, count the function header, which is
290 // on a separate line.
296 if (TheLine->First->is(tok::kw_if)) {
297 return Style.AllowShortIfStatementsOnASingleLine
298 ? tryMergeSimpleControlStatement(I, E, Limit)
301 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
302 return Style.AllowShortLoopsOnASingleLine
303 ? tryMergeSimpleControlStatement(I, E, Limit)
306 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
307 return Style.AllowShortCaseLabelsOnASingleLine
308 ? tryMergeShortCaseLabels(I, E, Limit)
311 if (TheLine->InPPDirective &&
312 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
313 return tryMergeSimplePPDirective(I, E, Limit);
319 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
320 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
324 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
326 if (1 + I[1]->Last->TotalLength > Limit)
331 unsigned tryMergeSimpleControlStatement(
332 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
333 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
336 if (Style.BraceWrapping.AfterControlStatement &&
337 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
339 if (I[1]->InPPDirective != (*I)->InPPDirective ||
340 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
342 Limit = limitConsideringMacros(I + 1, E, Limit);
343 AnnotatedLine &Line = **I;
344 if (Line.Last->isNot(tok::r_paren))
346 if (1 + I[1]->Last->TotalLength > Limit)
348 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
351 // Only inline simple if's (no nested if or else).
352 if (I + 2 != E && Line.startsWith(tok::kw_if) &&
353 I[2]->First->is(tok::kw_else))
359 tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
360 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
362 if (Limit == 0 || I + 1 == E ||
363 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
365 unsigned NumStmts = 0;
367 bool InPPDirective = I[0]->InPPDirective;
368 for (; NumStmts < 3; ++NumStmts) {
369 if (I + 1 + NumStmts == E)
371 const AnnotatedLine *Line = I[1 + NumStmts];
372 if (Line->InPPDirective != InPPDirective)
374 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
376 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
377 tok::kw_while, tok::comment) ||
378 Line->Last->is(tok::comment))
380 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
382 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
388 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
389 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
391 AnnotatedLine &Line = **I;
393 // Don't merge ObjC @ keywords and methods.
394 // FIXME: If an option to allow short exception handling clauses on a single
395 // line is added, change this to not return for @try and friends.
396 if (Style.Language != FormatStyle::LK_Java &&
397 Line.First->isOneOf(tok::at, tok::minus, tok::plus))
400 // Check that the current line allows merging. This depends on whether we
401 // are in a control flow statements as well as several style flags.
402 if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
403 (Line.First->Next && Line.First->Next->is(tok::kw_else)))
405 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
406 tok::kw___try, tok::kw_catch, tok::kw___finally,
407 tok::kw_for, tok::r_brace, Keywords.kw___except)) {
408 if (!Style.AllowShortBlocksOnASingleLine)
410 if (!Style.AllowShortIfStatementsOnASingleLine &&
411 Line.startsWith(tok::kw_if))
413 if (!Style.AllowShortLoopsOnASingleLine &&
414 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
416 // FIXME: Consider an option to allow short exception handling clauses on
418 // FIXME: This isn't covered by tests.
419 // FIXME: For catch, __except, __finally the first token on the line
420 // is '}', so this isn't correct here.
421 if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
422 Keywords.kw___except, tok::kw___finally))
426 FormatToken *Tok = I[1]->First;
427 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
428 (Tok->getNextNonComment() == nullptr ||
429 Tok->getNextNonComment()->is(tok::semi))) {
430 // We merge empty blocks even if the line exceeds the column limit.
431 Tok->SpacesRequiredBefore = 0;
432 Tok->CanBreakBefore = true;
434 } else if (Limit != 0 && !Line.startsWith(tok::kw_namespace) &&
435 !startsExternCBlock(Line)) {
436 // We don't merge short records.
437 FormatToken *RecordTok =
438 Line.First->is(tok::kw_typedef) ? Line.First->Next : Line.First;
440 RecordTok->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
441 Keywords.kw_interface))
444 // Check that we still have three lines and they fit into the limit.
445 if (I + 2 == E || I[2]->Type == LT_Invalid)
447 Limit = limitConsideringMacros(I + 2, E, Limit);
449 if (!nextTwoLinesFitInto(I, Limit))
452 // Second, check that the next line does not contain any braces - if it
453 // does, readability declines when putting it into a single line.
454 if (I[1]->Last->is(TT_LineComment))
457 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
462 // Last, check that the third line starts with a closing brace.
464 if (Tok->isNot(tok::r_brace))
467 // Don't merge "if (a) { .. } else {".
468 if (Tok->Next && Tok->Next->is(tok::kw_else))
476 /// Returns the modified column limit for \p I if it is inside a macro and
477 /// needs a trailing '\'.
479 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
480 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
482 if (I[0]->InPPDirective && I + 1 != E &&
483 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
484 return Limit < 2 ? 0 : Limit - 2;
489 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
491 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
493 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
496 bool containsMustBreak(const AnnotatedLine *Line) {
497 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
498 if (Tok->MustBreakBefore)
504 void join(AnnotatedLine &A, const AnnotatedLine &B) {
505 assert(!A.Last->Next);
506 assert(!B.First->Previous);
509 A.Last->Next = B.First;
510 B.First->Previous = A.Last;
511 B.First->CanBreakBefore = true;
512 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
513 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
514 Tok->TotalLength += LengthA;
519 const FormatStyle &Style;
520 const AdditionalKeywords &Keywords;
521 const SmallVectorImpl<AnnotatedLine *>::const_iterator End;
523 SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
524 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
527 static void markFinalized(FormatToken *Tok) {
528 for (; Tok; Tok = Tok->Next) {
529 Tok->Finalized = true;
530 for (AnnotatedLine *Child : Tok->Children)
531 markFinalized(Child->First);
536 static void printLineState(const LineState &State) {
537 llvm::dbgs() << "State: ";
538 for (const ParenState &P : State.Stack) {
539 llvm::dbgs() << P.Indent << "|" << P.LastSpace << "|" << P.NestedBlockIndent
542 llvm::dbgs() << State.NextToken->TokenText << "\n";
546 /// \brief Base class for classes that format one \c AnnotatedLine.
547 class LineFormatter {
549 LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
550 const FormatStyle &Style,
551 UnwrappedLineFormatter *BlockFormatter)
552 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
553 BlockFormatter(BlockFormatter) {}
554 virtual ~LineFormatter() {}
556 /// \brief Formats an \c AnnotatedLine and returns the penalty.
558 /// If \p DryRun is \c false, directly applies the changes.
559 virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
563 /// \brief If the \p State's next token is an r_brace closing a nested block,
564 /// format the nested block before it.
566 /// Returns \c true if all children could be placed successfully and adapts
567 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
568 /// creates changes using \c Whitespaces.
570 /// The crucial idea here is that children always get formatted upon
571 /// encountering the closing brace right after the nested block. Now, if we
572 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
573 /// \c false), the entire block has to be kept on the same line (which is only
574 /// possible if it fits on the line, only contains a single statement, etc.
576 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
577 /// break after the "{", format all lines with correct indentation and the put
578 /// the closing "}" on yet another new line.
580 /// This enables us to keep the simple structure of the
581 /// \c UnwrappedLineFormatter, where we only have two options for each token:
582 /// break or don't break.
583 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
585 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
586 FormatToken &Previous = *State.NextToken->Previous;
587 if (!LBrace || LBrace->isNot(tok::l_brace) ||
588 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
589 // The previous token does not open a block. Nothing to do. We don't
590 // assert so that we can simply call this function for all tokens.
594 int AdditionalIndent = State.Stack.back().Indent -
595 Previous.Children[0]->Level * Style.IndentWidth;
598 BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
599 /*FixBadIndentation=*/true);
603 if (Previous.Children[0]->First->MustBreakBefore)
606 // Cannot merge into one line if this line ends on a comment.
607 if (Previous.is(tok::comment))
610 // Cannot merge multiple statements into a single line.
611 if (Previous.Children.size() > 1)
614 const AnnotatedLine *Child = Previous.Children[0];
615 // We can't put the closing "}" on a line with a trailing comment.
616 if (Child->Last->isTrailingComment())
619 // If the child line exceeds the column limit, we wouldn't want to merge it.
620 // We add +2 for the trailing " }".
621 if (Style.ColumnLimit > 0 &&
622 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit)
626 Whitespaces->replaceWhitespace(
627 *Child->First, /*Newlines=*/0, /*Spaces=*/1,
628 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
630 Penalty += formatLine(*Child, State.Column + 1, DryRun);
632 State.Column += 1 + Child->Last->TotalLength;
636 ContinuationIndenter *Indenter;
639 WhitespaceManager *Whitespaces;
640 const FormatStyle &Style;
641 UnwrappedLineFormatter *BlockFormatter;
644 /// \brief Formatter that keeps the existing line breaks.
645 class NoColumnLimitLineFormatter : public LineFormatter {
647 NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
648 WhitespaceManager *Whitespaces,
649 const FormatStyle &Style,
650 UnwrappedLineFormatter *BlockFormatter)
651 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
653 /// \brief Formats the line, simply keeping all of the input's line breaking
655 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
656 bool DryRun) override {
659 Indenter->getInitialState(FirstIndent, &Line, /*DryRun=*/false);
660 while (State.NextToken) {
662 Indenter->mustBreak(State) ||
663 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
664 unsigned Penalty = 0;
665 formatChildren(State, Newline, /*DryRun=*/false, Penalty);
666 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
672 /// \brief Formatter that puts all tokens into a single line without breaks.
673 class NoLineBreakFormatter : public LineFormatter {
675 NoLineBreakFormatter(ContinuationIndenter *Indenter,
676 WhitespaceManager *Whitespaces, const FormatStyle &Style,
677 UnwrappedLineFormatter *BlockFormatter)
678 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
680 /// \brief Puts all tokens into a single line.
681 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
682 bool DryRun) override {
683 unsigned Penalty = 0;
684 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
685 while (State.NextToken) {
686 formatChildren(State, /*Newline=*/false, DryRun, Penalty);
687 Indenter->addTokenToState(
688 State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun);
694 /// \brief Finds the best way to break lines.
695 class OptimizingLineFormatter : public LineFormatter {
697 OptimizingLineFormatter(ContinuationIndenter *Indenter,
698 WhitespaceManager *Whitespaces,
699 const FormatStyle &Style,
700 UnwrappedLineFormatter *BlockFormatter)
701 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
703 /// \brief Formats the line by finding the best line breaks with line lengths
704 /// below the column limit.
705 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
706 bool DryRun) override {
707 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
709 // If the ObjC method declaration does not fit on a line, we should format
710 // it with one arg per line.
711 if (State.Line->Type == LT_ObjCMethodDecl)
712 State.Stack.back().BreakBeforeParameter = true;
714 // Find best solution in solution space.
715 return analyzeSolutionSpace(State, DryRun);
719 struct CompareLineStatePointers {
720 bool operator()(LineState *obj1, LineState *obj2) const {
721 return *obj1 < *obj2;
725 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
727 /// In case of equal penalties, we want to prefer states that were inserted
728 /// first. During state generation we make sure that we insert states first
729 /// that break the line as late as possible.
730 typedef std::pair<unsigned, unsigned> OrderedPenalty;
732 /// \brief An edge in the solution space from \c Previous->State to \c State,
733 /// inserting a newline dependent on the \c NewLine.
735 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
736 : State(State), NewLine(NewLine), Previous(Previous) {}
742 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
743 /// \c State has the given \c OrderedPenalty.
744 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
746 /// \brief The BFS queue type.
747 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
748 std::greater<QueueItem>> QueueType;
750 /// \brief Analyze the entire solution space starting from \p InitialState.
752 /// This implements a variant of Dijkstra's algorithm on the graph that spans
753 /// the solution space (\c LineStates are the nodes). The algorithm tries to
754 /// find the shortest path (the one with lowest penalty) from \p InitialState
755 /// to a state where all tokens are placed. Returns the penalty.
757 /// If \p DryRun is \c false, directly applies the changes.
758 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
759 std::set<LineState *, CompareLineStatePointers> Seen;
761 // Increasing count of \c StateNode items we have created. This is used to
762 // create a deterministic order independent of the container.
766 // Insert start element into queue.
768 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
769 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
772 unsigned Penalty = 0;
774 // While not empty, take first element and follow edges.
775 while (!Queue.empty()) {
776 Penalty = Queue.top().first.first;
777 StateNode *Node = Queue.top().second;
778 if (!Node->State.NextToken) {
779 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
784 // Cut off the analysis of certain solutions if the analysis gets too
785 // complex. See description of IgnoreStackForComparison.
787 Node->State.IgnoreStackForComparison = true;
789 if (!Seen.insert(&Node->State).second)
790 // State already examined with lower penalty.
793 FormatDecision LastFormat = Node->State.NextToken->Decision;
794 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
795 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
796 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
797 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
801 // We were unable to find a solution, do nothing.
802 // FIXME: Add diagnostic?
803 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
807 // Reconstruct the solution.
809 reconstructPath(InitialState, Queue.top().second);
811 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
812 DEBUG(llvm::dbgs() << "---\n");
817 /// \brief Add the following state to the analysis queue \c Queue.
819 /// Assume the current state is \p PreviousNode and has been reached with a
820 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
821 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
822 bool NewLine, unsigned *Count, QueueType *Queue) {
823 if (NewLine && !Indenter->canBreak(PreviousNode->State))
825 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
828 StateNode *Node = new (Allocator.Allocate())
829 StateNode(PreviousNode->State, NewLine, PreviousNode);
830 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
833 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
835 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
839 /// \brief Applies the best formatting by reconstructing the path in the
840 /// solution space that leads to \c Best.
841 void reconstructPath(LineState &State, StateNode *Best) {
842 std::deque<StateNode *> Path;
843 // We do not need a break before the initial token.
844 while (Best->Previous) {
845 Path.push_front(Best);
846 Best = Best->Previous;
848 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
850 unsigned Penalty = 0;
851 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
852 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
855 printLineState((*I)->Previous->State);
857 llvm::dbgs() << "Penalty for placing "
858 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
865 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
868 } // anonymous namespace
871 UnwrappedLineFormatter::format(const SmallVectorImpl<AnnotatedLine *> &Lines,
872 bool DryRun, int AdditionalIndent,
873 bool FixBadIndentation) {
874 LineJoiner Joiner(Style, Keywords, Lines);
876 // Try to look up already computed penalty in DryRun-mode.
877 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
878 &Lines, AdditionalIndent);
879 auto CacheIt = PenaltyCache.find(CacheKey);
880 if (DryRun && CacheIt != PenaltyCache.end())
881 return CacheIt->second;
883 assert(!Lines.empty());
884 unsigned Penalty = 0;
885 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
887 const AnnotatedLine *PreviousLine = nullptr;
888 const AnnotatedLine *NextLine = nullptr;
890 // The minimum level of consecutive lines that have been formatted.
891 unsigned RangeMinLevel = UINT_MAX;
893 for (const AnnotatedLine *Line =
894 Joiner.getNextMergedLine(DryRun, IndentTracker);
895 Line; Line = NextLine) {
896 const AnnotatedLine &TheLine = *Line;
897 unsigned Indent = IndentTracker.getIndent();
899 // We continue formatting unchanged lines to adjust their indent, e.g. if a
900 // scope was added. However, we need to carefully stop doing this when we
901 // exit the scope of affected lines to prevent indenting a the entire
902 // remaining file if it currently missing a closing brace.
903 bool ContinueFormatting =
904 TheLine.Level > RangeMinLevel ||
905 (TheLine.Level == RangeMinLevel && !TheLine.startsWith(tok::r_brace));
907 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
908 Indent != TheLine.First->OriginalColumn;
909 bool ShouldFormat = TheLine.Affected || FixIndentation;
910 // We cannot format this line; if the reason is that the line had a
911 // parsing error, remember that.
912 if (ShouldFormat && TheLine.Type == LT_Invalid && Status) {
913 Status->FormatComplete = false;
915 SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation());
918 if (ShouldFormat && TheLine.Type != LT_Invalid) {
920 formatFirstToken(TheLine, PreviousLine, Indent);
922 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
923 unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
924 bool FitsIntoOneLine =
925 TheLine.Last->TotalLength + Indent <= ColumnLimit ||
926 (TheLine.Type == LT_ImportStatement &&
927 (Style.Language != FormatStyle::LK_JavaScript ||
928 !Style.JavaScriptWrapImports));
930 if (Style.ColumnLimit == 0)
931 NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
932 .formatLine(TheLine, Indent, DryRun);
933 else if (FitsIntoOneLine)
934 Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
935 .formatLine(TheLine, Indent, DryRun);
937 Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
938 .formatLine(TheLine, Indent, DryRun);
939 RangeMinLevel = std::min(RangeMinLevel, TheLine.Level);
941 // If no token in the current line is affected, we still need to format
942 // affected children.
943 if (TheLine.ChildrenAffected)
944 for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next)
945 if (!Tok->Children.empty())
946 format(Tok->Children, DryRun);
948 // Adapt following lines on the current indent level to the same level
949 // unless the current \c AnnotatedLine is not at the beginning of a line.
951 TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
953 IndentTracker.adjustToUnmodifiedLine(TheLine);
955 bool ReformatLeadingWhitespace =
956 StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
957 TheLine.LeadingEmptyLinesAffected);
958 // Format the first token.
959 if (ReformatLeadingWhitespace)
960 formatFirstToken(TheLine, PreviousLine,
961 TheLine.First->OriginalColumn);
963 Whitespaces->addUntouchableToken(*TheLine.First,
964 TheLine.InPPDirective);
966 // Notify the WhitespaceManager about the unchanged whitespace.
967 for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
968 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
970 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
971 RangeMinLevel = UINT_MAX;
974 markFinalized(TheLine.First);
975 PreviousLine = &TheLine;
977 PenaltyCache[CacheKey] = Penalty;
981 void UnwrappedLineFormatter::formatFirstToken(const AnnotatedLine &Line,
982 const AnnotatedLine *PreviousLine,
984 FormatToken& RootToken = *Line.First;
985 if (RootToken.is(tok::eof)) {
986 unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u);
987 Whitespaces->replaceWhitespace(RootToken, Newlines, /*Spaces=*/0,
988 /*StartOfTokenColumn=*/0);
992 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
993 // Remove empty lines before "}" where applicable.
994 if (RootToken.is(tok::r_brace) &&
996 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
997 Newlines = std::min(Newlines, 1u);
998 if (Newlines == 0 && !RootToken.IsFirst)
1000 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1003 // Remove empty lines after "{".
1004 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1005 PreviousLine->Last->is(tok::l_brace) &&
1006 PreviousLine->First->isNot(tok::kw_namespace) &&
1007 !startsExternCBlock(*PreviousLine))
1010 // Insert extra new line before access specifiers.
1011 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1012 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1015 // Remove empty lines after access specifiers.
1016 if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
1017 (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline))
1018 Newlines = std::min(1u, Newlines);
1020 Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent,
1021 Line.InPPDirective &&
1022 !RootToken.HasUnescapedNewline);
1026 UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
1027 const AnnotatedLine *NextLine) const {
1028 // In preprocessor directives reserve two chars for trailing " \" if the
1029 // next line continues the preprocessor directive.
1030 bool ContinuesPPDirective =
1032 // If there is no next line, this is likely a child line and the parent
1033 // continues the preprocessor directive.
1035 (NextLine->InPPDirective &&
1036 // If there is an unescaped newline between this line and the next, the
1037 // next line starts a new preprocessor directive.
1038 !NextLine->First->HasUnescapedNewline));
1039 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
1042 } // namespace format
1043 } // namespace clang