1 //===--- UnwrappedLineFormatter.cpp - Format C++ code ---------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "UnwrappedLineFormatter.h"
10 #include "FormatToken.h"
11 #include "NamespaceEndCommentsFixer.h"
12 #include "WhitespaceManager.h"
13 #include "llvm/Support/Debug.h"
16 #define DEBUG_TYPE "format-formatter"
23 bool startsExternCBlock(const AnnotatedLine
&Line
) {
24 const FormatToken
*Next
= Line
.First
->getNextNonComment();
25 const FormatToken
*NextNext
= Next
? Next
->getNextNonComment() : nullptr;
26 return Line
.startsWith(tok::kw_extern
) && Next
&& Next
->isStringLiteral() &&
27 NextNext
&& NextNext
->is(tok::l_brace
);
30 bool isRecordLBrace(const FormatToken
&Tok
) {
31 return Tok
.isOneOf(TT_ClassLBrace
, TT_EnumLBrace
, TT_RecordLBrace
,
32 TT_StructLBrace
, TT_UnionLBrace
);
35 /// Tracks the indent level of \c AnnotatedLines across levels.
37 /// \c nextLine must be called for each \c AnnotatedLine, after which \c
38 /// getIndent() will return the indent for the last line \c nextLine was called
40 /// If the line is not formatted (and thus the indent does not change), calling
41 /// \c adjustToUnmodifiedLine after the call to \c nextLine will cause
42 /// subsequent lines on the same level to be indented at the same level as the
44 class LevelIndentTracker
{
46 LevelIndentTracker(const FormatStyle
&Style
,
47 const AdditionalKeywords
&Keywords
, unsigned StartLevel
,
49 : Style(Style
), Keywords(Keywords
), AdditionalIndent(AdditionalIndent
) {
50 for (unsigned i
= 0; i
!= StartLevel
; ++i
)
51 IndentForLevel
.push_back(Style
.IndentWidth
* i
+ AdditionalIndent
);
54 /// Returns the indent for the current line.
55 unsigned getIndent() const { return Indent
; }
57 /// Update the indent state given that \p Line is going to be formatted
59 void nextLine(const AnnotatedLine
&Line
) {
60 Offset
= getIndentOffset(*Line
.First
);
61 // Update the indent level cache size so that we can rely on it
62 // having the right size in adjustToUnmodifiedline.
63 if (Line
.Level
>= IndentForLevel
.size())
64 IndentForLevel
.resize(Line
.Level
+ 1, -1);
65 if (Style
.IndentPPDirectives
!= FormatStyle::PPDIS_None
&&
66 (Line
.InPPDirective
||
67 (Style
.IndentPPDirectives
== FormatStyle::PPDIS_BeforeHash
&&
68 Line
.Type
== LT_CommentAbovePPDirective
))) {
69 unsigned PPIndentWidth
=
70 (Style
.PPIndentWidth
>= 0) ? Style
.PPIndentWidth
: Style
.IndentWidth
;
71 Indent
= Line
.InMacroBody
72 ? Line
.PPLevel
* PPIndentWidth
+
73 (Line
.Level
- Line
.PPLevel
) * Style
.IndentWidth
74 : Line
.Level
* PPIndentWidth
;
75 Indent
+= AdditionalIndent
;
77 // When going to lower levels, forget previous higher levels so that we
78 // recompute future higher levels. But don't forget them if we enter a PP
79 // directive, since these do not terminate a C++ code block.
80 if (!Line
.InPPDirective
) {
81 assert(Line
.Level
<= IndentForLevel
.size());
82 IndentForLevel
.resize(Line
.Level
+ 1);
84 Indent
= getIndent(Line
.Level
);
86 if (static_cast<int>(Indent
) + Offset
>= 0)
88 if (Line
.IsContinuation
)
89 Indent
= Line
.Level
* Style
.IndentWidth
+ Style
.ContinuationIndentWidth
;
92 /// Update the level indent to adapt to the given \p Line.
94 /// When a line is not formatted, we move the subsequent lines on the same
95 /// level to the same indent.
96 /// Note that \c nextLine must have been called before this method.
97 void adjustToUnmodifiedLine(const AnnotatedLine
&Line
) {
98 if (Line
.InPPDirective
)
100 assert(Line
.Level
< IndentForLevel
.size());
101 if (Line
.First
->is(tok::comment
) && IndentForLevel
[Line
.Level
] != -1)
103 unsigned LevelIndent
= Line
.First
->OriginalColumn
;
104 if (static_cast<int>(LevelIndent
) - Offset
>= 0)
105 LevelIndent
-= Offset
;
106 IndentForLevel
[Line
.Level
] = LevelIndent
;
110 /// Get the offset of the line relatively to the level.
112 /// For example, 'public:' labels in classes are offset by 1 or 2
113 /// characters to the left from their level.
114 int getIndentOffset(const FormatToken
&RootToken
) {
115 if (Style
.Language
== FormatStyle::LK_Java
|| Style
.isJavaScript() ||
120 auto IsAccessModifier
= [this, &RootToken
]() {
121 if (RootToken
.isAccessSpecifier(Style
.isCpp())) {
123 } else if (RootToken
.isObjCAccessSpecifier()) {
126 // Handle Qt signals.
127 else if (RootToken
.isOneOf(Keywords
.kw_signals
, Keywords
.kw_qsignals
) &&
128 RootToken
.Next
&& RootToken
.Next
->is(tok::colon
)) {
130 } else if (RootToken
.Next
&&
131 RootToken
.Next
->isOneOf(Keywords
.kw_slots
,
132 Keywords
.kw_qslots
) &&
133 RootToken
.Next
->Next
&& RootToken
.Next
->Next
->is(tok::colon
)) {
136 // Handle malformed access specifier e.g. 'private' without trailing ':'.
137 else if (!RootToken
.Next
&& RootToken
.isAccessSpecifier(false)) {
143 if (IsAccessModifier()) {
144 // The AccessModifierOffset may be overridden by IndentAccessModifiers,
145 // in which case we take a negative value of the IndentWidth to simulate
146 // the upper indent level.
147 return Style
.IndentAccessModifiers
? -Style
.IndentWidth
148 : Style
.AccessModifierOffset
;
153 /// Get the indent of \p Level from \p IndentForLevel.
155 /// \p IndentForLevel must contain the indent for the level \c l
156 /// at \p IndentForLevel[l], or a value < 0 if the indent for
157 /// that level is unknown.
158 unsigned getIndent(unsigned Level
) const {
159 assert(Level
< IndentForLevel
.size());
160 if (IndentForLevel
[Level
] != -1)
161 return IndentForLevel
[Level
];
164 return getIndent(Level
- 1) + Style
.IndentWidth
;
167 const FormatStyle
&Style
;
168 const AdditionalKeywords
&Keywords
;
169 const unsigned AdditionalIndent
;
171 /// The indent in characters for each level. It remembers the indent of
172 /// previous lines (that are not PP directives) of equal or lower levels. This
173 /// is used to align formatted lines to the indent of previous non-formatted
174 /// lines. Think about the --lines parameter of clang-format.
175 SmallVector
<int> IndentForLevel
;
177 /// Offset of the current line relative to the indent level.
179 /// For example, the 'public' keywords is often indented with a negative
183 /// The current line's indent.
187 const FormatToken
*getMatchingNamespaceToken(
188 const AnnotatedLine
*Line
,
189 const SmallVectorImpl
<AnnotatedLine
*> &AnnotatedLines
) {
190 if (!Line
->startsWith(tok::r_brace
))
192 size_t StartLineIndex
= Line
->MatchingOpeningBlockLineIndex
;
193 if (StartLineIndex
== UnwrappedLine::kInvalidIndex
)
195 assert(StartLineIndex
< AnnotatedLines
.size());
196 return AnnotatedLines
[StartLineIndex
]->First
->getNamespaceToken();
199 StringRef
getNamespaceTokenText(const AnnotatedLine
*Line
) {
200 const FormatToken
*NamespaceToken
= Line
->First
->getNamespaceToken();
201 return NamespaceToken
? NamespaceToken
->TokenText
: StringRef();
204 StringRef
getMatchingNamespaceTokenText(
205 const AnnotatedLine
*Line
,
206 const SmallVectorImpl
<AnnotatedLine
*> &AnnotatedLines
) {
207 const FormatToken
*NamespaceToken
=
208 getMatchingNamespaceToken(Line
, AnnotatedLines
);
209 return NamespaceToken
? NamespaceToken
->TokenText
: StringRef();
214 LineJoiner(const FormatStyle
&Style
, const AdditionalKeywords
&Keywords
,
215 const SmallVectorImpl
<AnnotatedLine
*> &Lines
)
216 : Style(Style
), Keywords(Keywords
), End(Lines
.end()), Next(Lines
.begin()),
217 AnnotatedLines(Lines
) {}
219 /// Returns the next line, merging multiple lines into one if possible.
220 const AnnotatedLine
*getNextMergedLine(bool DryRun
,
221 LevelIndentTracker
&IndentTracker
) {
224 const AnnotatedLine
*Current
= *Next
;
225 IndentTracker
.nextLine(*Current
);
226 unsigned MergedLines
= tryFitMultipleLinesInOne(IndentTracker
, Next
, End
);
227 if (MergedLines
> 0 && Style
.ColumnLimit
== 0) {
228 // Disallow line merging if there is a break at the start of one of the
230 for (unsigned i
= 0; i
< MergedLines
; ++i
)
231 if (Next
[i
+ 1]->First
->NewlinesBefore
> 0)
235 for (unsigned i
= 0; i
< MergedLines
; ++i
)
236 join(*Next
[0], *Next
[i
+ 1]);
237 Next
= Next
+ MergedLines
+ 1;
242 /// Calculates how many lines can be merged into 1 starting at \p I.
244 tryFitMultipleLinesInOne(LevelIndentTracker
&IndentTracker
,
245 SmallVectorImpl
<AnnotatedLine
*>::const_iterator I
,
246 SmallVectorImpl
<AnnotatedLine
*>::const_iterator E
) {
247 const unsigned Indent
= IndentTracker
.getIndent();
249 // Can't join the last line with anything.
252 // We can never merge stuff if there are trailing line comments.
253 const AnnotatedLine
*TheLine
= *I
;
254 if (TheLine
->Last
->is(TT_LineComment
))
256 const auto &NextLine
= *I
[1];
257 if (NextLine
.Type
== LT_Invalid
|| NextLine
.First
->MustBreakBefore
)
259 if (TheLine
->InPPDirective
&&
260 (!NextLine
.InPPDirective
|| NextLine
.First
->HasUnescapedNewline
)) {
264 if (Style
.ColumnLimit
> 0 && Indent
> Style
.ColumnLimit
)
268 Style
.ColumnLimit
== 0 ? UINT_MAX
: Style
.ColumnLimit
- Indent
;
269 // If we already exceed the column limit, we set 'Limit' to 0. The different
270 // tryMerge..() functions can then decide whether to still do merging.
271 Limit
= TheLine
->Last
->TotalLength
> Limit
273 : Limit
- TheLine
->Last
->TotalLength
;
275 if (TheLine
->Last
->is(TT_FunctionLBrace
) &&
276 TheLine
->First
== TheLine
->Last
&&
277 !Style
.BraceWrapping
.SplitEmptyFunction
&&
278 NextLine
.First
->is(tok::r_brace
)) {
279 return tryMergeSimpleBlock(I
, E
, Limit
);
282 const auto *PreviousLine
= I
!= AnnotatedLines
.begin() ? I
[-1] : nullptr;
283 // Handle empty record blocks where the brace has already been wrapped.
284 if (PreviousLine
&& TheLine
->Last
->is(tok::l_brace
) &&
285 TheLine
->First
== TheLine
->Last
) {
286 bool EmptyBlock
= NextLine
.First
->is(tok::r_brace
);
288 const FormatToken
*Tok
= PreviousLine
->First
;
289 if (Tok
&& Tok
->is(tok::comment
))
290 Tok
= Tok
->getNextNonComment();
292 if (Tok
&& Tok
->getNamespaceToken()) {
293 return !Style
.BraceWrapping
.SplitEmptyNamespace
&& EmptyBlock
294 ? tryMergeSimpleBlock(I
, E
, Limit
)
298 if (Tok
&& Tok
->is(tok::kw_typedef
))
299 Tok
= Tok
->getNextNonComment();
300 if (Tok
&& Tok
->isOneOf(tok::kw_class
, tok::kw_struct
, tok::kw_union
,
301 tok::kw_extern
, Keywords
.kw_interface
)) {
302 return !Style
.BraceWrapping
.SplitEmptyRecord
&& EmptyBlock
303 ? tryMergeSimpleBlock(I
, E
, Limit
)
307 if (Tok
&& Tok
->is(tok::kw_template
) &&
308 Style
.BraceWrapping
.SplitEmptyRecord
&& EmptyBlock
) {
313 auto ShouldMergeShortFunctions
= [this, &I
, &NextLine
, PreviousLine
,
315 if (Style
.AllowShortFunctionsOnASingleLine
== FormatStyle::SFS_All
)
317 if (Style
.AllowShortFunctionsOnASingleLine
>= FormatStyle::SFS_Empty
&&
318 NextLine
.First
->is(tok::r_brace
)) {
322 if (Style
.AllowShortFunctionsOnASingleLine
&
323 FormatStyle::SFS_InlineOnly
) {
324 // Just checking TheLine->Level != 0 is not enough, because it
325 // provokes treating functions inside indented namespaces as short.
326 if (Style
.isJavaScript() && TheLine
->Last
->is(TT_FunctionLBrace
))
329 if (TheLine
->Level
!= 0) {
333 // TODO: Use IndentTracker to avoid loop?
334 // Find the last line with lower level.
335 const AnnotatedLine
*Line
= nullptr;
336 for (auto J
= I
- 1; J
>= AnnotatedLines
.begin(); --J
) {
338 if (!(*J
)->InPPDirective
&& !(*J
)->isComment() &&
339 (*J
)->Level
< TheLine
->Level
) {
348 // Check if the found line starts a record.
349 const FormatToken
*LastNonComment
= Line
->Last
;
350 assert(LastNonComment
);
351 if (LastNonComment
->is(tok::comment
)) {
352 LastNonComment
= LastNonComment
->getPreviousNonComment();
353 // There must be another token (usually `{`), because we chose a
354 // non-PPDirective and non-comment line that has a smaller level.
355 assert(LastNonComment
);
357 return isRecordLBrace(*LastNonComment
);
364 bool MergeShortFunctions
= ShouldMergeShortFunctions();
366 const FormatToken
*FirstNonComment
= TheLine
->First
;
367 if (FirstNonComment
->is(tok::comment
)) {
368 FirstNonComment
= FirstNonComment
->getNextNonComment();
369 if (!FirstNonComment
)
372 // FIXME: There are probably cases where we should use FirstNonComment
373 // instead of TheLine->First.
375 if (Style
.CompactNamespaces
) {
376 if (const auto *NSToken
= TheLine
->First
->getNamespaceToken()) {
378 assert(TheLine
->MatchingClosingBlockLineIndex
> 0);
379 for (auto ClosingLineIndex
= TheLine
->MatchingClosingBlockLineIndex
- 1;
380 I
+ J
!= E
&& NSToken
->TokenText
== getNamespaceTokenText(I
[J
]) &&
381 ClosingLineIndex
== I
[J
]->MatchingClosingBlockLineIndex
&&
382 I
[J
]->Last
->TotalLength
< Limit
;
383 ++J
, --ClosingLineIndex
) {
384 Limit
-= I
[J
]->Last
->TotalLength
;
386 // Reduce indent level for bodies of namespaces which were compacted,
387 // but only if their content was indented in the first place.
388 auto *ClosingLine
= AnnotatedLines
.begin() + ClosingLineIndex
+ 1;
389 const int OutdentBy
= I
[J
]->Level
- TheLine
->Level
;
390 assert(OutdentBy
>= 0);
391 for (auto *CompactedLine
= I
+ J
; CompactedLine
<= ClosingLine
;
393 if (!(*CompactedLine
)->InPPDirective
) {
394 const int Level
= (*CompactedLine
)->Level
;
395 (*CompactedLine
)->Level
= std::max(Level
- OutdentBy
, 0);
402 if (auto nsToken
= getMatchingNamespaceToken(TheLine
, AnnotatedLines
)) {
404 unsigned openingLine
= TheLine
->MatchingOpeningBlockLineIndex
- 1;
405 for (; I
+ 1 + i
!= E
&&
406 nsToken
->TokenText
==
407 getMatchingNamespaceTokenText(I
[i
+ 1], AnnotatedLines
) &&
408 openingLine
== I
[i
+ 1]->MatchingOpeningBlockLineIndex
;
409 i
++, --openingLine
) {
410 // No space between consecutive braces.
411 I
[i
+ 1]->First
->SpacesRequiredBefore
=
412 I
[i
]->Last
->isNot(tok::r_brace
);
414 // Indent like the outer-most namespace.
415 IndentTracker
.nextLine(*I
[i
+ 1]);
421 // Try to merge a function block with left brace unwrapped.
422 if (TheLine
->Last
->is(TT_FunctionLBrace
) && TheLine
->First
!= TheLine
->Last
)
423 return MergeShortFunctions
? tryMergeSimpleBlock(I
, E
, Limit
) : 0;
424 // Try to merge a control statement block with left brace unwrapped.
425 if (TheLine
->Last
->is(tok::l_brace
) && FirstNonComment
!= TheLine
->Last
&&
426 FirstNonComment
->isOneOf(tok::kw_if
, tok::kw_while
, tok::kw_for
,
428 return Style
.AllowShortBlocksOnASingleLine
!= FormatStyle::SBS_Never
429 ? tryMergeSimpleBlock(I
, E
, Limit
)
432 // Try to merge a control statement block with left brace wrapped.
433 if (NextLine
.First
->is(tok::l_brace
)) {
434 if ((TheLine
->First
->isOneOf(tok::kw_if
, tok::kw_else
, tok::kw_while
,
435 tok::kw_for
, tok::kw_switch
, tok::kw_try
,
436 tok::kw_do
, TT_ForEachMacro
) ||
437 (TheLine
->First
->is(tok::r_brace
) && TheLine
->First
->Next
&&
438 TheLine
->First
->Next
->isOneOf(tok::kw_else
, tok::kw_catch
))) &&
439 Style
.BraceWrapping
.AfterControlStatement
==
440 FormatStyle::BWACS_MultiLine
) {
441 // If possible, merge the next line's wrapped left brace with the
442 // current line. Otherwise, leave it on the next line, as this is a
443 // multi-line control statement.
444 return (Style
.ColumnLimit
== 0 || TheLine
->Level
* Style
.IndentWidth
+
445 TheLine
->Last
->TotalLength
<=
450 if (TheLine
->First
->isOneOf(tok::kw_if
, tok::kw_else
, tok::kw_while
,
451 tok::kw_for
, TT_ForEachMacro
)) {
452 return (Style
.BraceWrapping
.AfterControlStatement
==
453 FormatStyle::BWACS_Always
)
454 ? tryMergeSimpleBlock(I
, E
, Limit
)
457 if (TheLine
->First
->isOneOf(tok::kw_else
, tok::kw_catch
) &&
458 Style
.BraceWrapping
.AfterControlStatement
==
459 FormatStyle::BWACS_MultiLine
) {
460 // This case if different from the upper BWACS_MultiLine processing
461 // in that a preceding r_brace is not on the same line as else/catch
462 // most likely because of BeforeElse/BeforeCatch set to true.
463 // If the line length doesn't fit ColumnLimit, leave l_brace on the
464 // next line to respect the BWACS_MultiLine.
465 return (Style
.ColumnLimit
== 0 ||
466 TheLine
->Last
->TotalLength
<= Style
.ColumnLimit
)
471 if (PreviousLine
&& TheLine
->First
->is(tok::l_brace
)) {
472 switch (PreviousLine
->First
->Tok
.getKind()) {
474 // Don't merge block with left brace wrapped after ObjC special blocks.
475 if (PreviousLine
->First
->Next
) {
476 tok::ObjCKeywordKind kwId
=
477 PreviousLine
->First
->Next
->Tok
.getObjCKeywordID();
478 if (kwId
== tok::objc_autoreleasepool
||
479 kwId
== tok::objc_synchronized
) {
486 case tok::kw_default
:
487 // Don't merge block with left brace wrapped after case labels.
495 // Don't merge an empty template class or struct if SplitEmptyRecords
497 if (PreviousLine
&& Style
.BraceWrapping
.SplitEmptyRecord
&&
498 TheLine
->Last
->is(tok::l_brace
) && PreviousLine
->Last
) {
499 const FormatToken
*Previous
= PreviousLine
->Last
;
501 if (Previous
->is(tok::comment
))
502 Previous
= Previous
->getPreviousNonComment();
504 if (Previous
->is(tok::greater
) && !PreviousLine
->InPPDirective
)
506 if (Previous
->is(tok::identifier
)) {
507 const FormatToken
*PreviousPrevious
=
508 Previous
->getPreviousNonComment();
509 if (PreviousPrevious
&&
510 PreviousPrevious
->isOneOf(tok::kw_class
, tok::kw_struct
)) {
518 if (TheLine
->Last
->is(tok::l_brace
)) {
519 bool ShouldMerge
= false;
520 // Try to merge records.
521 if (TheLine
->Last
->is(TT_EnumLBrace
)) {
522 ShouldMerge
= Style
.AllowShortEnumsOnASingleLine
;
523 } else if (TheLine
->Last
->is(TT_RequiresExpressionLBrace
)) {
524 ShouldMerge
= Style
.AllowShortCompoundRequirementOnASingleLine
;
525 } else if (TheLine
->Last
->isOneOf(TT_ClassLBrace
, TT_StructLBrace
)) {
526 // NOTE: We use AfterClass (whereas AfterStruct exists) for both classes
527 // and structs, but it seems that wrapping is still handled correctly
529 ShouldMerge
= !Style
.BraceWrapping
.AfterClass
||
530 (NextLine
.First
->is(tok::r_brace
) &&
531 !Style
.BraceWrapping
.SplitEmptyRecord
);
532 } else if (TheLine
->InPPDirective
||
533 !TheLine
->First
->isOneOf(tok::kw_class
, tok::kw_enum
,
535 // Try to merge a block with left brace unwrapped that wasn't yet
537 ShouldMerge
= !Style
.BraceWrapping
.AfterFunction
||
538 (NextLine
.First
->is(tok::r_brace
) &&
539 !Style
.BraceWrapping
.SplitEmptyFunction
);
541 return ShouldMerge
? tryMergeSimpleBlock(I
, E
, Limit
) : 0;
544 // Try to merge a function block with left brace wrapped.
545 if (NextLine
.First
->is(TT_FunctionLBrace
) &&
546 Style
.BraceWrapping
.AfterFunction
) {
547 if (NextLine
.Last
->is(TT_LineComment
))
550 // Check for Limit <= 2 to account for the " {".
551 if (Limit
<= 2 || (Style
.ColumnLimit
== 0 && containsMustBreak(TheLine
)))
555 unsigned MergedLines
= 0;
556 if (MergeShortFunctions
||
557 (Style
.AllowShortFunctionsOnASingleLine
>= FormatStyle::SFS_Empty
&&
558 NextLine
.First
== NextLine
.Last
&& I
+ 2 != E
&&
559 I
[2]->First
->is(tok::r_brace
))) {
560 MergedLines
= tryMergeSimpleBlock(I
+ 1, E
, Limit
);
561 // If we managed to merge the block, count the function header, which is
562 // on a separate line.
568 auto IsElseLine
= [&TheLine
]() -> bool {
569 const FormatToken
*First
= TheLine
->First
;
570 if (First
->is(tok::kw_else
))
573 return First
->is(tok::r_brace
) && First
->Next
&&
574 First
->Next
->is(tok::kw_else
);
576 if (TheLine
->First
->is(tok::kw_if
) ||
577 (IsElseLine() && (Style
.AllowShortIfStatementsOnASingleLine
==
578 FormatStyle::SIS_AllIfsAndElse
))) {
579 return Style
.AllowShortIfStatementsOnASingleLine
580 ? tryMergeSimpleControlStatement(I
, E
, Limit
)
583 if (TheLine
->First
->isOneOf(tok::kw_for
, tok::kw_while
, tok::kw_do
,
585 return Style
.AllowShortLoopsOnASingleLine
586 ? tryMergeSimpleControlStatement(I
, E
, Limit
)
589 if (TheLine
->First
->isOneOf(tok::kw_case
, tok::kw_default
)) {
590 return Style
.AllowShortCaseLabelsOnASingleLine
591 ? tryMergeShortCaseLabels(I
, E
, Limit
)
594 if (TheLine
->InPPDirective
&&
595 (TheLine
->First
->HasUnescapedNewline
|| TheLine
->First
->IsFirst
)) {
596 return tryMergeSimplePPDirective(I
, E
, Limit
);
602 tryMergeSimplePPDirective(SmallVectorImpl
<AnnotatedLine
*>::const_iterator I
,
603 SmallVectorImpl
<AnnotatedLine
*>::const_iterator E
,
607 if (I
+ 2 != E
&& I
[2]->InPPDirective
&& !I
[2]->First
->HasUnescapedNewline
)
609 if (1 + I
[1]->Last
->TotalLength
> Limit
)
614 unsigned tryMergeSimpleControlStatement(
615 SmallVectorImpl
<AnnotatedLine
*>::const_iterator I
,
616 SmallVectorImpl
<AnnotatedLine
*>::const_iterator E
, unsigned Limit
) {
619 if (Style
.BraceWrapping
.AfterControlStatement
==
620 FormatStyle::BWACS_Always
&&
621 I
[1]->First
->is(tok::l_brace
) &&
622 Style
.AllowShortBlocksOnASingleLine
== FormatStyle::SBS_Never
) {
625 if (I
[1]->InPPDirective
!= (*I
)->InPPDirective
||
626 (I
[1]->InPPDirective
&& I
[1]->First
->HasUnescapedNewline
)) {
629 Limit
= limitConsideringMacros(I
+ 1, E
, Limit
);
630 AnnotatedLine
&Line
= **I
;
631 if (Line
.First
->isNot(tok::kw_do
) && Line
.First
->isNot(tok::kw_else
) &&
632 Line
.Last
->isNot(tok::kw_else
) && Line
.Last
->isNot(tok::r_paren
)) {
635 // Only merge `do while` if `do` is the only statement on the line.
636 if (Line
.First
->is(tok::kw_do
) && Line
.Last
->isNot(tok::kw_do
))
638 if (1 + I
[1]->Last
->TotalLength
> Limit
)
640 // Don't merge with loops, ifs, a single semicolon or a line comment.
641 if (I
[1]->First
->isOneOf(tok::semi
, tok::kw_if
, tok::kw_for
, tok::kw_while
,
642 TT_ForEachMacro
, TT_LineComment
)) {
645 // Only inline simple if's (no nested if or else), unless specified
646 if (Style
.AllowShortIfStatementsOnASingleLine
==
647 FormatStyle::SIS_WithoutElse
) {
648 if (I
+ 2 != E
&& Line
.startsWith(tok::kw_if
) &&
649 I
[2]->First
->is(tok::kw_else
)) {
657 tryMergeShortCaseLabels(SmallVectorImpl
<AnnotatedLine
*>::const_iterator I
,
658 SmallVectorImpl
<AnnotatedLine
*>::const_iterator E
,
660 if (Limit
== 0 || I
+ 1 == E
||
661 I
[1]->First
->isOneOf(tok::kw_case
, tok::kw_default
)) {
664 if (I
[0]->Last
->is(tok::l_brace
) || I
[1]->First
->is(tok::l_brace
))
666 unsigned NumStmts
= 0;
668 bool EndsWithComment
= false;
669 bool InPPDirective
= I
[0]->InPPDirective
;
670 bool InMacroBody
= I
[0]->InMacroBody
;
671 const unsigned Level
= I
[0]->Level
;
672 for (; NumStmts
< 3; ++NumStmts
) {
673 if (I
+ 1 + NumStmts
== E
)
675 const AnnotatedLine
*Line
= I
[1 + NumStmts
];
676 if (Line
->InPPDirective
!= InPPDirective
)
678 if (Line
->InMacroBody
!= InMacroBody
)
680 if (Line
->First
->isOneOf(tok::kw_case
, tok::kw_default
, tok::r_brace
))
682 if (Line
->First
->isOneOf(tok::kw_if
, tok::kw_for
, tok::kw_switch
,
687 if (Line
->First
->is(tok::comment
)) {
688 if (Level
!= Line
->Level
)
690 SmallVectorImpl
<AnnotatedLine
*>::const_iterator J
= I
+ 2 + NumStmts
;
691 for (; J
!= E
; ++J
) {
693 if (Line
->InPPDirective
!= InPPDirective
)
695 if (Line
->First
->isOneOf(tok::kw_case
, tok::kw_default
, tok::r_brace
))
697 if (Line
->First
->isNot(tok::comment
) || Level
!= Line
->Level
)
702 if (Line
->Last
->is(tok::comment
))
703 EndsWithComment
= true;
704 Length
+= I
[1 + NumStmts
]->Last
->TotalLength
+ 1; // 1 for the space.
706 if (NumStmts
== 0 || NumStmts
== 3 || Length
> Limit
)
712 tryMergeSimpleBlock(SmallVectorImpl
<AnnotatedLine
*>::const_iterator I
,
713 SmallVectorImpl
<AnnotatedLine
*>::const_iterator E
,
715 // Don't merge with a preprocessor directive.
716 if (I
[1]->Type
== LT_PreprocessorDirective
)
719 AnnotatedLine
&Line
= **I
;
721 // Don't merge ObjC @ keywords and methods.
722 // FIXME: If an option to allow short exception handling clauses on a single
723 // line is added, change this to not return for @try and friends.
724 if (Style
.Language
!= FormatStyle::LK_Java
&&
725 Line
.First
->isOneOf(tok::at
, tok::minus
, tok::plus
)) {
729 // Check that the current line allows merging. This depends on whether we
730 // are in a control flow statements as well as several style flags.
731 if (Line
.First
->is(tok::kw_case
) ||
732 (Line
.First
->Next
&& Line
.First
->Next
->is(tok::kw_else
))) {
735 // default: in switch statement
736 if (Line
.First
->is(tok::kw_default
)) {
737 const FormatToken
*Tok
= Line
.First
->getNextNonComment();
738 if (Tok
&& Tok
->is(tok::colon
))
742 auto IsCtrlStmt
= [](const auto &Line
) {
743 return Line
.First
->isOneOf(tok::kw_if
, tok::kw_else
, tok::kw_while
,
744 tok::kw_do
, tok::kw_for
, TT_ForEachMacro
);
747 const bool IsSplitBlock
=
748 Style
.AllowShortBlocksOnASingleLine
== FormatStyle::SBS_Never
||
749 (Style
.AllowShortBlocksOnASingleLine
== FormatStyle::SBS_Empty
&&
750 I
[1]->First
->isNot(tok::r_brace
));
752 if (IsCtrlStmt(Line
) ||
753 Line
.First
->isOneOf(tok::kw_try
, tok::kw___try
, tok::kw_catch
,
754 tok::kw___finally
, tok::r_brace
,
755 Keywords
.kw___except
)) {
758 // Don't merge when we can't except the case when
759 // the control statement block is empty
760 if (!Style
.AllowShortIfStatementsOnASingleLine
&&
761 Line
.First
->isOneOf(tok::kw_if
, tok::kw_else
) &&
762 !Style
.BraceWrapping
.AfterControlStatement
&&
763 I
[1]->First
->isNot(tok::r_brace
)) {
766 if (!Style
.AllowShortIfStatementsOnASingleLine
&&
767 Line
.First
->isOneOf(tok::kw_if
, tok::kw_else
) &&
768 Style
.BraceWrapping
.AfterControlStatement
==
769 FormatStyle::BWACS_Always
&&
770 I
+ 2 != E
&& I
[2]->First
->isNot(tok::r_brace
)) {
773 if (!Style
.AllowShortLoopsOnASingleLine
&&
774 Line
.First
->isOneOf(tok::kw_while
, tok::kw_do
, tok::kw_for
,
776 !Style
.BraceWrapping
.AfterControlStatement
&&
777 I
[1]->First
->isNot(tok::r_brace
)) {
780 if (!Style
.AllowShortLoopsOnASingleLine
&&
781 Line
.First
->isOneOf(tok::kw_while
, tok::kw_do
, tok::kw_for
,
783 Style
.BraceWrapping
.AfterControlStatement
==
784 FormatStyle::BWACS_Always
&&
785 I
+ 2 != E
&& I
[2]->First
->isNot(tok::r_brace
)) {
788 // FIXME: Consider an option to allow short exception handling clauses on
790 // FIXME: This isn't covered by tests.
791 // FIXME: For catch, __except, __finally the first token on the line
792 // is '}', so this isn't correct here.
793 if (Line
.First
->isOneOf(tok::kw_try
, tok::kw___try
, tok::kw_catch
,
794 Keywords
.kw___except
, tok::kw___finally
)) {
799 if (Line
.Last
->is(tok::l_brace
)) {
800 if (IsSplitBlock
&& Line
.First
== Line
.Last
&&
801 I
> AnnotatedLines
.begin() &&
802 (I
[-1]->endsWith(tok::kw_else
) || IsCtrlStmt(*I
[-1]))) {
805 FormatToken
*Tok
= I
[1]->First
;
806 auto ShouldMerge
= [Tok
]() {
807 if (Tok
->isNot(tok::r_brace
) || Tok
->MustBreakBefore
)
809 const FormatToken
*Next
= Tok
->getNextNonComment();
810 return !Next
|| Next
->is(tok::semi
);
814 // We merge empty blocks even if the line exceeds the column limit.
815 Tok
->SpacesRequiredBefore
= Style
.SpaceInEmptyBlock
? 1 : 0;
816 Tok
->CanBreakBefore
= true;
818 } else if (Limit
!= 0 && !Line
.startsWithNamespace() &&
819 !startsExternCBlock(Line
)) {
820 // We don't merge short records.
821 if (isRecordLBrace(*Line
.Last
))
824 // Check that we still have three lines and they fit into the limit.
825 if (I
+ 2 == E
|| I
[2]->Type
== LT_Invalid
)
827 Limit
= limitConsideringMacros(I
+ 2, E
, Limit
);
829 if (!nextTwoLinesFitInto(I
, Limit
))
832 // Second, check that the next line does not contain any braces - if it
833 // does, readability declines when putting it into a single line.
834 if (I
[1]->Last
->is(TT_LineComment
))
837 if (Tok
->is(tok::l_brace
) && Tok
->isNot(BK_BracedInit
))
842 // Last, check that the third line starts with a closing brace.
844 if (Tok
->isNot(tok::r_brace
))
847 // Don't merge "if (a) { .. } else {".
848 if (Tok
->Next
&& Tok
->Next
->is(tok::kw_else
))
851 // Don't merge a trailing multi-line control statement block like:
854 // { <-- current Line
857 if (Line
.First
== Line
.Last
&& Line
.First
->isNot(TT_FunctionLBrace
) &&
858 Style
.BraceWrapping
.AfterControlStatement
==
859 FormatStyle::BWACS_MultiLine
) {
865 } else if (I
[1]->First
->is(tok::l_brace
)) {
866 if (I
[1]->Last
->is(TT_LineComment
))
869 // Check for Limit <= 2 to account for the " {".
870 if (Limit
<= 2 || (Style
.ColumnLimit
== 0 && containsMustBreak(*I
)))
873 unsigned MergedLines
= 0;
874 if (Style
.AllowShortBlocksOnASingleLine
!= FormatStyle::SBS_Never
||
875 (I
[1]->First
== I
[1]->Last
&& I
+ 2 != E
&&
876 I
[2]->First
->is(tok::r_brace
))) {
877 MergedLines
= tryMergeSimpleBlock(I
+ 1, E
, Limit
);
878 // If we managed to merge the block, count the statement header, which
879 // is on a separate line.
888 /// Returns the modified column limit for \p I if it is inside a macro and
889 /// needs a trailing '\'.
891 limitConsideringMacros(SmallVectorImpl
<AnnotatedLine
*>::const_iterator I
,
892 SmallVectorImpl
<AnnotatedLine
*>::const_iterator E
,
894 if (I
[0]->InPPDirective
&& I
+ 1 != E
&&
895 !I
[1]->First
->HasUnescapedNewline
&& I
[1]->First
->isNot(tok::eof
)) {
896 return Limit
< 2 ? 0 : Limit
- 2;
901 bool nextTwoLinesFitInto(SmallVectorImpl
<AnnotatedLine
*>::const_iterator I
,
903 if (I
[1]->First
->MustBreakBefore
|| I
[2]->First
->MustBreakBefore
)
905 return 1 + I
[1]->Last
->TotalLength
+ 1 + I
[2]->Last
->TotalLength
<= Limit
;
908 bool containsMustBreak(const AnnotatedLine
*Line
) {
910 // Ignore the first token, because in this situation, it applies more to the
911 // last token of the previous line.
912 for (const FormatToken
*Tok
= Line
->First
->Next
; Tok
; Tok
= Tok
->Next
)
913 if (Tok
->MustBreakBefore
)
918 void join(AnnotatedLine
&A
, const AnnotatedLine
&B
) {
919 assert(!A
.Last
->Next
);
920 assert(!B
.First
->Previous
);
923 A
.Last
->Next
= B
.First
;
924 B
.First
->Previous
= A
.Last
;
925 B
.First
->CanBreakBefore
= true;
926 unsigned LengthA
= A
.Last
->TotalLength
+ B
.First
->SpacesRequiredBefore
;
927 for (FormatToken
*Tok
= B
.First
; Tok
; Tok
= Tok
->Next
) {
928 Tok
->TotalLength
+= LengthA
;
933 const FormatStyle
&Style
;
934 const AdditionalKeywords
&Keywords
;
935 const SmallVectorImpl
<AnnotatedLine
*>::const_iterator End
;
937 SmallVectorImpl
<AnnotatedLine
*>::const_iterator Next
;
938 const SmallVectorImpl
<AnnotatedLine
*> &AnnotatedLines
;
941 static void markFinalized(FormatToken
*Tok
) {
942 for (; Tok
; Tok
= Tok
->Next
) {
943 if (Tok
->MacroCtx
&& Tok
->MacroCtx
->Role
== MR_ExpandedArg
) {
944 // In the first pass we format all macro arguments in the expanded token
945 // stream. Instead of finalizing the macro arguments, we mark that they
946 // will be modified as unexpanded arguments (as part of the macro call
947 // formatting) in the next pass.
948 Tok
->MacroCtx
->Role
= MR_UnexpandedArg
;
949 // Reset whether spaces are required before this token, as that is context
950 // dependent, and that context may change when formatting the macro call.
951 // For example, given M(x) -> 2 * x, and the macro call M(var),
952 // the token 'var' will have SpacesRequiredBefore = 1 after being
953 // formatted as part of the expanded macro, but SpacesRequiredBefore = 0
954 // for its position within the macro call.
955 Tok
->SpacesRequiredBefore
= 0;
957 Tok
->Finalized
= true;
963 static void printLineState(const LineState
&State
) {
964 llvm::dbgs() << "State: ";
965 for (const ParenState
&P
: State
.Stack
) {
966 llvm::dbgs() << (P
.Tok
? P
.Tok
->TokenText
: "F") << "|" << P
.Indent
<< "|"
967 << P
.LastSpace
<< "|" << P
.NestedBlockIndent
<< " ";
969 llvm::dbgs() << State
.NextToken
->TokenText
<< "\n";
973 /// Base class for classes that format one \c AnnotatedLine.
974 class LineFormatter
{
976 LineFormatter(ContinuationIndenter
*Indenter
, WhitespaceManager
*Whitespaces
,
977 const FormatStyle
&Style
,
978 UnwrappedLineFormatter
*BlockFormatter
)
979 : Indenter(Indenter
), Whitespaces(Whitespaces
), Style(Style
),
980 BlockFormatter(BlockFormatter
) {}
981 virtual ~LineFormatter() {}
983 /// Formats an \c AnnotatedLine and returns the penalty.
985 /// If \p DryRun is \c false, directly applies the changes.
986 virtual unsigned formatLine(const AnnotatedLine
&Line
, unsigned FirstIndent
,
987 unsigned FirstStartColumn
, bool DryRun
) = 0;
990 /// If the \p State's next token is an r_brace closing a nested block,
991 /// format the nested block before it.
993 /// Returns \c true if all children could be placed successfully and adapts
994 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
995 /// creates changes using \c Whitespaces.
997 /// The crucial idea here is that children always get formatted upon
998 /// encountering the closing brace right after the nested block. Now, if we
999 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1000 /// \c false), the entire block has to be kept on the same line (which is only
1001 /// possible if it fits on the line, only contains a single statement, etc.
1003 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1004 /// break after the "{", format all lines with correct indentation and the put
1005 /// the closing "}" on yet another new line.
1007 /// This enables us to keep the simple structure of the
1008 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1009 /// break or don't break.
1010 bool formatChildren(LineState
&State
, bool NewLine
, bool DryRun
,
1011 unsigned &Penalty
) {
1012 const FormatToken
*LBrace
= State
.NextToken
->getPreviousNonComment();
1013 bool HasLBrace
= LBrace
&& LBrace
->is(tok::l_brace
) && LBrace
->is(BK_Block
);
1014 FormatToken
&Previous
= *State
.NextToken
->Previous
;
1015 if (Previous
.Children
.size() == 0 || (!HasLBrace
&& !LBrace
->MacroParent
)) {
1016 // The previous token does not open a block. Nothing to do. We don't
1017 // assert so that we can simply call this function for all tokens.
1021 if (NewLine
|| Previous
.MacroParent
) {
1022 const ParenState
&P
= State
.Stack
.back();
1024 int AdditionalIndent
=
1025 P
.Indent
- Previous
.Children
[0]->Level
* Style
.IndentWidth
;
1027 BlockFormatter
->format(Previous
.Children
, DryRun
, AdditionalIndent
,
1028 /*FixBadIndentation=*/true);
1032 if (Previous
.Children
[0]->First
->MustBreakBefore
)
1035 // Cannot merge into one line if this line ends on a comment.
1036 if (Previous
.is(tok::comment
))
1039 // Cannot merge multiple statements into a single line.
1040 if (Previous
.Children
.size() > 1)
1043 const AnnotatedLine
*Child
= Previous
.Children
[0];
1044 // We can't put the closing "}" on a line with a trailing comment.
1045 if (Child
->Last
->isTrailingComment())
1048 // If the child line exceeds the column limit, we wouldn't want to merge it.
1049 // We add +2 for the trailing " }".
1050 if (Style
.ColumnLimit
> 0 &&
1051 Child
->Last
->TotalLength
+ State
.Column
+ 2 > Style
.ColumnLimit
) {
1056 Whitespaces
->replaceWhitespace(
1057 *Child
->First
, /*Newlines=*/0, /*Spaces=*/1,
1058 /*StartOfTokenColumn=*/State
.Column
, /*IsAligned=*/false,
1059 State
.Line
->InPPDirective
);
1062 formatLine(*Child
, State
.Column
+ 1, /*FirstStartColumn=*/0, DryRun
);
1064 State
.Column
+= 1 + Child
->Last
->TotalLength
;
1068 ContinuationIndenter
*Indenter
;
1071 WhitespaceManager
*Whitespaces
;
1072 const FormatStyle
&Style
;
1073 UnwrappedLineFormatter
*BlockFormatter
;
1076 /// Formatter that keeps the existing line breaks.
1077 class NoColumnLimitLineFormatter
: public LineFormatter
{
1079 NoColumnLimitLineFormatter(ContinuationIndenter
*Indenter
,
1080 WhitespaceManager
*Whitespaces
,
1081 const FormatStyle
&Style
,
1082 UnwrappedLineFormatter
*BlockFormatter
)
1083 : LineFormatter(Indenter
, Whitespaces
, Style
, BlockFormatter
) {}
1085 /// Formats the line, simply keeping all of the input's line breaking
1087 unsigned formatLine(const AnnotatedLine
&Line
, unsigned FirstIndent
,
1088 unsigned FirstStartColumn
, bool DryRun
) override
{
1090 LineState State
= Indenter
->getInitialState(FirstIndent
, FirstStartColumn
,
1091 &Line
, /*DryRun=*/false);
1092 while (State
.NextToken
) {
1094 Indenter
->mustBreak(State
) ||
1095 (Indenter
->canBreak(State
) && State
.NextToken
->NewlinesBefore
> 0);
1096 unsigned Penalty
= 0;
1097 formatChildren(State
, Newline
, /*DryRun=*/false, Penalty
);
1098 Indenter
->addTokenToState(State
, Newline
, /*DryRun=*/false);
1104 /// Formatter that puts all tokens into a single line without breaks.
1105 class NoLineBreakFormatter
: public LineFormatter
{
1107 NoLineBreakFormatter(ContinuationIndenter
*Indenter
,
1108 WhitespaceManager
*Whitespaces
, const FormatStyle
&Style
,
1109 UnwrappedLineFormatter
*BlockFormatter
)
1110 : LineFormatter(Indenter
, Whitespaces
, Style
, BlockFormatter
) {}
1112 /// Puts all tokens into a single line.
1113 unsigned formatLine(const AnnotatedLine
&Line
, unsigned FirstIndent
,
1114 unsigned FirstStartColumn
, bool DryRun
) override
{
1115 unsigned Penalty
= 0;
1117 Indenter
->getInitialState(FirstIndent
, FirstStartColumn
, &Line
, DryRun
);
1118 while (State
.NextToken
) {
1119 formatChildren(State
, /*NewLine=*/false, DryRun
, Penalty
);
1120 Indenter
->addTokenToState(
1121 State
, /*Newline=*/State
.NextToken
->MustBreakBefore
, DryRun
);
1127 /// Finds the best way to break lines.
1128 class OptimizingLineFormatter
: public LineFormatter
{
1130 OptimizingLineFormatter(ContinuationIndenter
*Indenter
,
1131 WhitespaceManager
*Whitespaces
,
1132 const FormatStyle
&Style
,
1133 UnwrappedLineFormatter
*BlockFormatter
)
1134 : LineFormatter(Indenter
, Whitespaces
, Style
, BlockFormatter
) {}
1136 /// Formats the line by finding the best line breaks with line lengths
1137 /// below the column limit.
1138 unsigned formatLine(const AnnotatedLine
&Line
, unsigned FirstIndent
,
1139 unsigned FirstStartColumn
, bool DryRun
) override
{
1141 Indenter
->getInitialState(FirstIndent
, FirstStartColumn
, &Line
, DryRun
);
1143 // If the ObjC method declaration does not fit on a line, we should format
1144 // it with one arg per line.
1145 if (State
.Line
->Type
== LT_ObjCMethodDecl
)
1146 State
.Stack
.back().BreakBeforeParameter
= true;
1148 // Find best solution in solution space.
1149 return analyzeSolutionSpace(State
, DryRun
);
1153 struct CompareLineStatePointers
{
1154 bool operator()(LineState
*obj1
, LineState
*obj2
) const {
1155 return *obj1
< *obj2
;
1159 /// A pair of <penalty, count> that is used to prioritize the BFS on.
1161 /// In case of equal penalties, we want to prefer states that were inserted
1162 /// first. During state generation we make sure that we insert states first
1163 /// that break the line as late as possible.
1164 typedef std::pair
<unsigned, unsigned> OrderedPenalty
;
1166 /// An edge in the solution space from \c Previous->State to \c State,
1167 /// inserting a newline dependent on the \c NewLine.
1169 StateNode(const LineState
&State
, bool NewLine
, StateNode
*Previous
)
1170 : State(State
), NewLine(NewLine
), Previous(Previous
) {}
1173 StateNode
*Previous
;
1176 /// An item in the prioritized BFS search queue. The \c StateNode's
1177 /// \c State has the given \c OrderedPenalty.
1178 typedef std::pair
<OrderedPenalty
, StateNode
*> QueueItem
;
1180 /// The BFS queue type.
1181 typedef std::priority_queue
<QueueItem
, SmallVector
<QueueItem
>,
1182 std::greater
<QueueItem
>>
1185 /// Analyze the entire solution space starting from \p InitialState.
1187 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1188 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1189 /// find the shortest path (the one with lowest penalty) from \p InitialState
1190 /// to a state where all tokens are placed. Returns the penalty.
1192 /// If \p DryRun is \c false, directly applies the changes.
1193 unsigned analyzeSolutionSpace(LineState
&InitialState
, bool DryRun
) {
1194 std::set
<LineState
*, CompareLineStatePointers
> Seen
;
1196 // Increasing count of \c StateNode items we have created. This is used to
1197 // create a deterministic order independent of the container.
1201 // Insert start element into queue.
1202 StateNode
*RootNode
=
1203 new (Allocator
.Allocate()) StateNode(InitialState
, false, nullptr);
1204 Queue
.push(QueueItem(OrderedPenalty(0, Count
), RootNode
));
1207 unsigned Penalty
= 0;
1209 // While not empty, take first element and follow edges.
1210 while (!Queue
.empty()) {
1211 // Quit if we still haven't found a solution by now.
1212 if (Count
> 25000000)
1215 Penalty
= Queue
.top().first
.first
;
1216 StateNode
*Node
= Queue
.top().second
;
1217 if (!Node
->State
.NextToken
) {
1218 LLVM_DEBUG(llvm::dbgs()
1219 << "\n---\nPenalty for line: " << Penalty
<< "\n");
1224 // Cut off the analysis of certain solutions if the analysis gets too
1225 // complex. See description of IgnoreStackForComparison.
1227 Node
->State
.IgnoreStackForComparison
= true;
1229 if (!Seen
.insert(&Node
->State
).second
) {
1230 // State already examined with lower penalty.
1234 FormatDecision LastFormat
= Node
->State
.NextToken
->getDecision();
1235 if (LastFormat
== FD_Unformatted
|| LastFormat
== FD_Continue
)
1236 addNextStateToQueue(Penalty
, Node
, /*NewLine=*/false, &Count
, &Queue
);
1237 if (LastFormat
== FD_Unformatted
|| LastFormat
== FD_Break
)
1238 addNextStateToQueue(Penalty
, Node
, /*NewLine=*/true, &Count
, &Queue
);
1241 if (Queue
.empty()) {
1242 // We were unable to find a solution, do nothing.
1243 // FIXME: Add diagnostic?
1244 LLVM_DEBUG(llvm::dbgs() << "Could not find a solution.\n");
1248 // Reconstruct the solution.
1250 reconstructPath(InitialState
, Queue
.top().second
);
1252 LLVM_DEBUG(llvm::dbgs()
1253 << "Total number of analyzed states: " << Count
<< "\n");
1254 LLVM_DEBUG(llvm::dbgs() << "---\n");
1259 /// Add the following state to the analysis queue \c Queue.
1261 /// Assume the current state is \p PreviousNode and has been reached with a
1262 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
1263 void addNextStateToQueue(unsigned Penalty
, StateNode
*PreviousNode
,
1264 bool NewLine
, unsigned *Count
, QueueType
*Queue
) {
1265 if (NewLine
&& !Indenter
->canBreak(PreviousNode
->State
))
1267 if (!NewLine
&& Indenter
->mustBreak(PreviousNode
->State
))
1270 StateNode
*Node
= new (Allocator
.Allocate())
1271 StateNode(PreviousNode
->State
, NewLine
, PreviousNode
);
1272 if (!formatChildren(Node
->State
, NewLine
, /*DryRun=*/true, Penalty
))
1275 Penalty
+= Indenter
->addTokenToState(Node
->State
, NewLine
, true);
1277 Queue
->push(QueueItem(OrderedPenalty(Penalty
, *Count
), Node
));
1281 /// Applies the best formatting by reconstructing the path in the
1282 /// solution space that leads to \c Best.
1283 void reconstructPath(LineState
&State
, StateNode
*Best
) {
1284 llvm::SmallVector
<StateNode
*> Path
;
1285 // We do not need a break before the initial token.
1286 while (Best
->Previous
) {
1287 Path
.push_back(Best
);
1288 Best
= Best
->Previous
;
1290 for (const auto &Node
: llvm::reverse(Path
)) {
1291 unsigned Penalty
= 0;
1292 formatChildren(State
, Node
->NewLine
, /*DryRun=*/false, Penalty
);
1293 Penalty
+= Indenter
->addTokenToState(State
, Node
->NewLine
, false);
1296 printLineState(Node
->Previous
->State
);
1297 if (Node
->NewLine
) {
1298 llvm::dbgs() << "Penalty for placing "
1299 << Node
->Previous
->State
.NextToken
->Tok
.getName()
1300 << " on a new line: " << Penalty
<< "\n";
1306 llvm::SpecificBumpPtrAllocator
<StateNode
> Allocator
;
1309 } // anonymous namespace
1311 unsigned UnwrappedLineFormatter::format(
1312 const SmallVectorImpl
<AnnotatedLine
*> &Lines
, bool DryRun
,
1313 int AdditionalIndent
, bool FixBadIndentation
, unsigned FirstStartColumn
,
1314 unsigned NextStartColumn
, unsigned LastStartColumn
) {
1315 LineJoiner
Joiner(Style
, Keywords
, Lines
);
1317 // Try to look up already computed penalty in DryRun-mode.
1318 std::pair
<const SmallVectorImpl
<AnnotatedLine
*> *, unsigned> CacheKey(
1319 &Lines
, AdditionalIndent
);
1320 auto CacheIt
= PenaltyCache
.find(CacheKey
);
1321 if (DryRun
&& CacheIt
!= PenaltyCache
.end())
1322 return CacheIt
->second
;
1324 assert(!Lines
.empty());
1325 unsigned Penalty
= 0;
1326 LevelIndentTracker
IndentTracker(Style
, Keywords
, Lines
[0]->Level
,
1328 const AnnotatedLine
*PrevPrevLine
= nullptr;
1329 const AnnotatedLine
*PreviousLine
= nullptr;
1330 const AnnotatedLine
*NextLine
= nullptr;
1332 // The minimum level of consecutive lines that have been formatted.
1333 unsigned RangeMinLevel
= UINT_MAX
;
1335 bool FirstLine
= true;
1336 for (const AnnotatedLine
*Line
=
1337 Joiner
.getNextMergedLine(DryRun
, IndentTracker
);
1338 Line
; PrevPrevLine
= PreviousLine
, PreviousLine
= Line
, Line
= NextLine
,
1339 FirstLine
= false) {
1340 assert(Line
->First
);
1341 const AnnotatedLine
&TheLine
= *Line
;
1342 unsigned Indent
= IndentTracker
.getIndent();
1344 // We continue formatting unchanged lines to adjust their indent, e.g. if a
1345 // scope was added. However, we need to carefully stop doing this when we
1346 // exit the scope of affected lines to prevent indenting the entire
1347 // remaining file if it currently missing a closing brace.
1348 bool PreviousRBrace
=
1349 PreviousLine
&& PreviousLine
->startsWith(tok::r_brace
);
1350 bool ContinueFormatting
=
1351 TheLine
.Level
> RangeMinLevel
||
1352 (TheLine
.Level
== RangeMinLevel
&& !PreviousRBrace
&&
1353 !TheLine
.startsWith(tok::r_brace
));
1355 bool FixIndentation
= (FixBadIndentation
|| ContinueFormatting
) &&
1356 Indent
!= TheLine
.First
->OriginalColumn
;
1357 bool ShouldFormat
= TheLine
.Affected
|| FixIndentation
;
1358 // We cannot format this line; if the reason is that the line had a
1359 // parsing error, remember that.
1360 if (ShouldFormat
&& TheLine
.Type
== LT_Invalid
&& Status
) {
1361 Status
->FormatComplete
= false;
1363 SourceMgr
.getSpellingLineNumber(TheLine
.First
->Tok
.getLocation());
1366 if (ShouldFormat
&& TheLine
.Type
!= LT_Invalid
) {
1368 bool LastLine
= TheLine
.First
->is(tok::eof
);
1369 formatFirstToken(TheLine
, PreviousLine
, PrevPrevLine
, Lines
, Indent
,
1370 LastLine
? LastStartColumn
: NextStartColumn
+ Indent
);
1373 NextLine
= Joiner
.getNextMergedLine(DryRun
, IndentTracker
);
1374 unsigned ColumnLimit
= getColumnLimit(TheLine
.InPPDirective
, NextLine
);
1375 bool FitsIntoOneLine
=
1376 !TheLine
.ContainsMacroCall
&&
1377 (TheLine
.Last
->TotalLength
+ Indent
<= ColumnLimit
||
1378 (TheLine
.Type
== LT_ImportStatement
&&
1379 (!Style
.isJavaScript() || !Style
.JavaScriptWrapImports
)) ||
1380 (Style
.isCSharp() &&
1381 TheLine
.InPPDirective
)); // don't split #regions in C#
1382 if (Style
.ColumnLimit
== 0) {
1383 NoColumnLimitLineFormatter(Indenter
, Whitespaces
, Style
, this)
1384 .formatLine(TheLine
, NextStartColumn
+ Indent
,
1385 FirstLine
? FirstStartColumn
: 0, DryRun
);
1386 } else if (FitsIntoOneLine
) {
1387 Penalty
+= NoLineBreakFormatter(Indenter
, Whitespaces
, Style
, this)
1388 .formatLine(TheLine
, NextStartColumn
+ Indent
,
1389 FirstLine
? FirstStartColumn
: 0, DryRun
);
1391 Penalty
+= OptimizingLineFormatter(Indenter
, Whitespaces
, Style
, this)
1392 .formatLine(TheLine
, NextStartColumn
+ Indent
,
1393 FirstLine
? FirstStartColumn
: 0, DryRun
);
1395 RangeMinLevel
= std::min(RangeMinLevel
, TheLine
.Level
);
1397 // If no token in the current line is affected, we still need to format
1398 // affected children.
1399 if (TheLine
.ChildrenAffected
) {
1400 for (const FormatToken
*Tok
= TheLine
.First
; Tok
; Tok
= Tok
->Next
)
1401 if (!Tok
->Children
.empty())
1402 format(Tok
->Children
, DryRun
);
1405 // Adapt following lines on the current indent level to the same level
1406 // unless the current \c AnnotatedLine is not at the beginning of a line.
1407 bool StartsNewLine
=
1408 TheLine
.First
->NewlinesBefore
> 0 || TheLine
.First
->IsFirst
;
1410 IndentTracker
.adjustToUnmodifiedLine(TheLine
);
1412 bool ReformatLeadingWhitespace
=
1413 StartsNewLine
&& ((PreviousLine
&& PreviousLine
->Affected
) ||
1414 TheLine
.LeadingEmptyLinesAffected
);
1415 // Format the first token.
1416 if (ReformatLeadingWhitespace
) {
1417 formatFirstToken(TheLine
, PreviousLine
, PrevPrevLine
, Lines
,
1418 TheLine
.First
->OriginalColumn
,
1419 TheLine
.First
->OriginalColumn
);
1421 Whitespaces
->addUntouchableToken(*TheLine
.First
,
1422 TheLine
.InPPDirective
);
1425 // Notify the WhitespaceManager about the unchanged whitespace.
1426 for (FormatToken
*Tok
= TheLine
.First
->Next
; Tok
; Tok
= Tok
->Next
)
1427 Whitespaces
->addUntouchableToken(*Tok
, TheLine
.InPPDirective
);
1429 NextLine
= Joiner
.getNextMergedLine(DryRun
, IndentTracker
);
1430 RangeMinLevel
= UINT_MAX
;
1433 auto *Tok
= TheLine
.First
;
1434 if (Tok
->is(tok::hash
) && !Tok
->Previous
&& Tok
->Next
&&
1435 Tok
->Next
->isOneOf(tok::pp_if
, tok::pp_ifdef
, tok::pp_ifndef
,
1436 tok::pp_elif
, tok::pp_elifdef
, tok::pp_elifndef
,
1437 tok::pp_else
, tok::pp_endif
)) {
1443 PenaltyCache
[CacheKey
] = Penalty
;
1447 static auto computeNewlines(const AnnotatedLine
&Line
,
1448 const AnnotatedLine
*PreviousLine
,
1449 const AnnotatedLine
*PrevPrevLine
,
1450 const SmallVectorImpl
<AnnotatedLine
*> &Lines
,
1451 const FormatStyle
&Style
) {
1452 const auto &RootToken
= *Line
.First
;
1454 std::min(RootToken
.NewlinesBefore
, Style
.MaxEmptyLinesToKeep
+ 1);
1455 // Remove empty lines before "}" where applicable.
1456 if (RootToken
.is(tok::r_brace
) &&
1458 (RootToken
.Next
->is(tok::semi
) && !RootToken
.Next
->Next
)) &&
1459 // Do not remove empty lines before namespace closing "}".
1460 !getNamespaceToken(&Line
, Lines
)) {
1461 Newlines
= std::min(Newlines
, 1u);
1463 // Remove empty lines at the start of nested blocks (lambdas/arrow functions)
1464 if (!PreviousLine
&& Line
.Level
> 0)
1465 Newlines
= std::min(Newlines
, 1u);
1466 if (Newlines
== 0 && !RootToken
.IsFirst
)
1468 if (RootToken
.IsFirst
&& !RootToken
.HasUnescapedNewline
)
1471 // Remove empty lines after "{".
1472 if (!Style
.KeepEmptyLinesAtTheStartOfBlocks
&& PreviousLine
&&
1473 PreviousLine
->Last
->is(tok::l_brace
) &&
1474 !PreviousLine
->startsWithNamespace() &&
1475 !(PrevPrevLine
&& PrevPrevLine
->startsWithNamespace() &&
1476 PreviousLine
->startsWith(tok::l_brace
)) &&
1477 !startsExternCBlock(*PreviousLine
)) {
1481 // Insert or remove empty line before access specifiers.
1482 if (PreviousLine
&& RootToken
.isAccessSpecifier()) {
1483 switch (Style
.EmptyLineBeforeAccessModifier
) {
1484 case FormatStyle::ELBAMS_Never
:
1488 case FormatStyle::ELBAMS_Leave
:
1489 Newlines
= std::max(RootToken
.NewlinesBefore
, 1u);
1491 case FormatStyle::ELBAMS_LogicalBlock
:
1492 if (PreviousLine
->Last
->isOneOf(tok::semi
, tok::r_brace
) && Newlines
<= 1)
1494 if (PreviousLine
->First
->isAccessSpecifier())
1495 Newlines
= 1; // Previous is an access modifier remove all new lines.
1497 case FormatStyle::ELBAMS_Always
: {
1498 const FormatToken
*previousToken
;
1499 if (PreviousLine
->Last
->is(tok::comment
))
1500 previousToken
= PreviousLine
->Last
->getPreviousNonComment();
1502 previousToken
= PreviousLine
->Last
;
1503 if ((!previousToken
|| previousToken
->isNot(tok::l_brace
)) &&
1511 // Insert or remove empty line after access specifiers.
1512 if (PreviousLine
&& PreviousLine
->First
->isAccessSpecifier() &&
1513 (!PreviousLine
->InPPDirective
|| !RootToken
.HasUnescapedNewline
)) {
1514 // EmptyLineBeforeAccessModifier is handling the case when two access
1515 // modifiers follow each other.
1516 if (!RootToken
.isAccessSpecifier()) {
1517 switch (Style
.EmptyLineAfterAccessModifier
) {
1518 case FormatStyle::ELAAMS_Never
:
1521 case FormatStyle::ELAAMS_Leave
:
1522 Newlines
= std::max(Newlines
, 1u);
1524 case FormatStyle::ELAAMS_Always
:
1525 if (RootToken
.is(tok::r_brace
)) // Do not add at end of class.
1528 Newlines
= std::max(Newlines
, 2u);
1537 void UnwrappedLineFormatter::formatFirstToken(
1538 const AnnotatedLine
&Line
, const AnnotatedLine
*PreviousLine
,
1539 const AnnotatedLine
*PrevPrevLine
,
1540 const SmallVectorImpl
<AnnotatedLine
*> &Lines
, unsigned Indent
,
1541 unsigned NewlineIndent
) {
1542 FormatToken
&RootToken
= *Line
.First
;
1543 if (RootToken
.is(tok::eof
)) {
1545 std::min(RootToken
.NewlinesBefore
,
1546 Style
.KeepEmptyLinesAtEOF
? Style
.MaxEmptyLinesToKeep
+ 1 : 1);
1547 unsigned TokenIndent
= Newlines
? NewlineIndent
: 0;
1548 Whitespaces
->replaceWhitespace(RootToken
, Newlines
, TokenIndent
,
1553 if (RootToken
.Newlines
< 0) {
1554 RootToken
.Newlines
=
1555 computeNewlines(Line
, PreviousLine
, PrevPrevLine
, Lines
, Style
);
1556 assert(RootToken
.Newlines
>= 0);
1559 if (RootToken
.Newlines
> 0)
1560 Indent
= NewlineIndent
;
1562 // Preprocessor directives get indented before the hash only if specified. In
1563 // Javascript import statements are indented like normal statements.
1564 if (!Style
.isJavaScript() &&
1565 Style
.IndentPPDirectives
!= FormatStyle::PPDIS_BeforeHash
&&
1566 (Line
.Type
== LT_PreprocessorDirective
||
1567 Line
.Type
== LT_ImportStatement
)) {
1571 Whitespaces
->replaceWhitespace(RootToken
, RootToken
.Newlines
, Indent
, Indent
,
1572 /*IsAligned=*/false,
1573 Line
.InPPDirective
&&
1574 !RootToken
.HasUnescapedNewline
);
1578 UnwrappedLineFormatter::getColumnLimit(bool InPPDirective
,
1579 const AnnotatedLine
*NextLine
) const {
1580 // In preprocessor directives reserve two chars for trailing " \" if the
1581 // next line continues the preprocessor directive.
1582 bool ContinuesPPDirective
=
1584 // If there is no next line, this is likely a child line and the parent
1585 // continues the preprocessor directive.
1587 (NextLine
->InPPDirective
&&
1588 // If there is an unescaped newline between this line and the next, the
1589 // next line starts a new preprocessor directive.
1590 !NextLine
->First
->HasUnescapedNewline
));
1591 return Style
.ColumnLimit
- (ContinuesPPDirective
? 2 : 0);
1594 } // namespace format
1595 } // namespace clang