[NFC][RemoveDIs] Prefer iterators over inst-pointers in InstCombine
[llvm-project.git] / clang / lib / Format / UnwrappedLineFormatter.cpp
blob0dcf3b7c8dd06bc6bfe8cd6fa12770bd40157611
1 //===--- UnwrappedLineFormatter.cpp - Format C++ code ---------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
9 #include "UnwrappedLineFormatter.h"
10 #include "FormatToken.h"
11 #include "NamespaceEndCommentsFixer.h"
12 #include "WhitespaceManager.h"
13 #include "llvm/Support/Debug.h"
14 #include <queue>
16 #define DEBUG_TYPE "format-formatter"
18 namespace clang {
19 namespace format {
21 namespace {
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.
36 ///
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
39 /// with.
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
43 /// given line.
44 class LevelIndentTracker {
45 public:
46 LevelIndentTracker(const FormatStyle &Style,
47 const AdditionalKeywords &Keywords, unsigned StartLevel,
48 int AdditionalIndent)
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
58 /// next.
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;
76 } else {
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)
87 Indent += Offset;
88 if (Line.IsContinuation)
89 Indent = Line.Level * Style.IndentWidth + Style.ContinuationIndentWidth;
92 /// Update the level indent to adapt to the given \p Line.
93 ///
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)
99 return;
100 assert(Line.Level < IndentForLevel.size());
101 if (Line.First->is(tok::comment) && IndentForLevel[Line.Level] != -1)
102 return;
103 unsigned LevelIndent = Line.First->OriginalColumn;
104 if (static_cast<int>(LevelIndent) - Offset >= 0)
105 LevelIndent -= Offset;
106 IndentForLevel[Line.Level] = LevelIndent;
109 private:
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() ||
116 Style.isCSharp()) {
117 return 0;
120 auto IsAccessModifier = [this, &RootToken]() {
121 if (RootToken.isAccessSpecifier(Style.isCpp())) {
122 return true;
123 } else if (RootToken.isObjCAccessSpecifier()) {
124 return true;
126 // Handle Qt signals.
127 else if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
128 RootToken.Next && RootToken.Next->is(tok::colon)) {
129 return true;
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)) {
134 return true;
136 // Handle malformed access specifier e.g. 'private' without trailing ':'.
137 else if (!RootToken.Next && RootToken.isAccessSpecifier(false)) {
138 return true;
140 return 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;
150 return 0;
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];
162 if (Level == 0)
163 return 0;
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
180 /// offset.
181 int Offset = 0;
183 /// The current line's indent.
184 unsigned Indent = 0;
187 const FormatToken *getMatchingNamespaceToken(
188 const AnnotatedLine *Line,
189 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
190 if (!Line->startsWith(tok::r_brace))
191 return nullptr;
192 size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex;
193 if (StartLineIndex == UnwrappedLine::kInvalidIndex)
194 return nullptr;
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();
212 class LineJoiner {
213 public:
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) {
222 if (Next == End)
223 return nullptr;
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
229 // input lines.
230 for (unsigned i = 0; i < MergedLines; ++i)
231 if (Next[i + 1]->First->NewlinesBefore > 0)
232 MergedLines = 0;
234 if (!DryRun)
235 for (unsigned i = 0; i < MergedLines; ++i)
236 join(*Next[0], *Next[i + 1]);
237 Next = Next + MergedLines + 1;
238 return Current;
241 private:
242 /// Calculates how many lines can be merged into 1 starting at \p I.
243 unsigned
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.
250 if (I + 1 == E)
251 return 0;
252 // We can never merge stuff if there are trailing line comments.
253 const AnnotatedLine *TheLine = *I;
254 if (TheLine->Last->is(TT_LineComment))
255 return 0;
256 const auto &NextLine = *I[1];
257 if (NextLine.Type == LT_Invalid || NextLine.First->MustBreakBefore)
258 return 0;
259 if (TheLine->InPPDirective &&
260 (!NextLine.InPPDirective || NextLine.First->HasUnescapedNewline)) {
261 return 0;
264 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
265 return 0;
267 unsigned Limit =
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)
295 : 0;
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)
304 : 0;
307 if (Tok && Tok->is(tok::kw_template) &&
308 Style.BraceWrapping.SplitEmptyRecord && EmptyBlock) {
309 return 0;
313 auto ShouldMergeShortFunctions = [this, &I, &NextLine, PreviousLine,
314 TheLine]() {
315 if (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All)
316 return true;
317 if (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
318 NextLine.First->is(tok::r_brace)) {
319 return true;
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))
327 return true;
329 if (TheLine->Level != 0) {
330 if (!PreviousLine)
331 return false;
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) {
337 assert(*J);
338 if (!(*J)->InPPDirective && !(*J)->isComment() &&
339 (*J)->Level < TheLine->Level) {
340 Line = *J;
341 break;
345 if (!Line)
346 return false;
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);
361 return false;
364 bool MergeShortFunctions = ShouldMergeShortFunctions();
366 const FormatToken *FirstNonComment = TheLine->First;
367 if (FirstNonComment->is(tok::comment)) {
368 FirstNonComment = FirstNonComment->getNextNonComment();
369 if (!FirstNonComment)
370 return 0;
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()) {
377 int J = 1;
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;
392 ++CompactedLine) {
393 if (!(*CompactedLine)->InPPDirective) {
394 const int Level = (*CompactedLine)->Level;
395 (*CompactedLine)->Level = std::max(Level - OutdentBy, 0);
399 return J - 1;
402 if (auto nsToken = getMatchingNamespaceToken(TheLine, AnnotatedLines)) {
403 int i = 0;
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]);
417 return i;
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,
427 TT_ForEachMacro)) {
428 return Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never
429 ? tryMergeSimpleBlock(I, E, Limit)
430 : 0;
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 <=
446 Style.ColumnLimit)
448 : 0;
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)
455 : 0;
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)
468 : 0;
471 if (PreviousLine && TheLine->First->is(tok::l_brace)) {
472 switch (PreviousLine->First->Tok.getKind()) {
473 case tok::at:
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) {
480 return 0;
483 break;
485 case tok::kw_case:
486 case tok::kw_default:
487 // Don't merge block with left brace wrapped after case labels.
488 return 0;
490 default:
491 break;
495 // Don't merge an empty template class or struct if SplitEmptyRecords
496 // is defined.
497 if (PreviousLine && Style.BraceWrapping.SplitEmptyRecord &&
498 TheLine->Last->is(tok::l_brace) && PreviousLine->Last) {
499 const FormatToken *Previous = PreviousLine->Last;
500 if (Previous) {
501 if (Previous->is(tok::comment))
502 Previous = Previous->getPreviousNonComment();
503 if (Previous) {
504 if (Previous->is(tok::greater) && !PreviousLine->InPPDirective)
505 return 0;
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)) {
511 return 0;
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->isOneOf(TT_ClassLBrace, TT_StructLBrace)) {
524 // NOTE: We use AfterClass (whereas AfterStruct exists) for both classes
525 // and structs, but it seems that wrapping is still handled correctly
526 // elsewhere.
527 ShouldMerge = !Style.BraceWrapping.AfterClass ||
528 (NextLine.First->is(tok::r_brace) &&
529 !Style.BraceWrapping.SplitEmptyRecord);
530 } else if (TheLine->InPPDirective ||
531 !TheLine->First->isOneOf(tok::kw_class, tok::kw_enum,
532 tok::kw_struct)) {
533 // Try to merge a block with left brace unwrapped that wasn't yet
534 // covered.
535 ShouldMerge = !Style.BraceWrapping.AfterFunction ||
536 (NextLine.First->is(tok::r_brace) &&
537 !Style.BraceWrapping.SplitEmptyFunction);
539 return ShouldMerge ? tryMergeSimpleBlock(I, E, Limit) : 0;
542 // Try to merge a function block with left brace wrapped.
543 if (NextLine.First->is(TT_FunctionLBrace) &&
544 Style.BraceWrapping.AfterFunction) {
545 if (NextLine.Last->is(TT_LineComment))
546 return 0;
548 // Check for Limit <= 2 to account for the " {".
549 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
550 return 0;
551 Limit -= 2;
553 unsigned MergedLines = 0;
554 if (MergeShortFunctions ||
555 (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
556 NextLine.First == NextLine.Last && I + 2 != E &&
557 I[2]->First->is(tok::r_brace))) {
558 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
559 // If we managed to merge the block, count the function header, which is
560 // on a separate line.
561 if (MergedLines > 0)
562 ++MergedLines;
564 return MergedLines;
566 auto IsElseLine = [&TheLine]() -> bool {
567 const FormatToken *First = TheLine->First;
568 if (First->is(tok::kw_else))
569 return true;
571 return First->is(tok::r_brace) && First->Next &&
572 First->Next->is(tok::kw_else);
574 if (TheLine->First->is(tok::kw_if) ||
575 (IsElseLine() && (Style.AllowShortIfStatementsOnASingleLine ==
576 FormatStyle::SIS_AllIfsAndElse))) {
577 return Style.AllowShortIfStatementsOnASingleLine
578 ? tryMergeSimpleControlStatement(I, E, Limit)
579 : 0;
581 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while, tok::kw_do,
582 TT_ForEachMacro)) {
583 return Style.AllowShortLoopsOnASingleLine
584 ? tryMergeSimpleControlStatement(I, E, Limit)
585 : 0;
587 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
588 return Style.AllowShortCaseLabelsOnASingleLine
589 ? tryMergeShortCaseLabels(I, E, Limit)
590 : 0;
592 if (TheLine->InPPDirective &&
593 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
594 return tryMergeSimplePPDirective(I, E, Limit);
596 return 0;
599 unsigned
600 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
601 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
602 unsigned Limit) {
603 if (Limit == 0)
604 return 0;
605 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
606 return 0;
607 if (1 + I[1]->Last->TotalLength > Limit)
608 return 0;
609 return 1;
612 unsigned tryMergeSimpleControlStatement(
613 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
614 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
615 if (Limit == 0)
616 return 0;
617 if (Style.BraceWrapping.AfterControlStatement ==
618 FormatStyle::BWACS_Always &&
619 I[1]->First->is(tok::l_brace) &&
620 Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) {
621 return 0;
623 if (I[1]->InPPDirective != (*I)->InPPDirective ||
624 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) {
625 return 0;
627 Limit = limitConsideringMacros(I + 1, E, Limit);
628 AnnotatedLine &Line = **I;
629 if (Line.First->isNot(tok::kw_do) && Line.First->isNot(tok::kw_else) &&
630 Line.Last->isNot(tok::kw_else) && Line.Last->isNot(tok::r_paren)) {
631 return 0;
633 // Only merge `do while` if `do` is the only statement on the line.
634 if (Line.First->is(tok::kw_do) && Line.Last->isNot(tok::kw_do))
635 return 0;
636 if (1 + I[1]->Last->TotalLength > Limit)
637 return 0;
638 // Don't merge with loops, ifs, a single semicolon or a line comment.
639 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
640 TT_ForEachMacro, TT_LineComment)) {
641 return 0;
643 // Only inline simple if's (no nested if or else), unless specified
644 if (Style.AllowShortIfStatementsOnASingleLine ==
645 FormatStyle::SIS_WithoutElse) {
646 if (I + 2 != E && Line.startsWith(tok::kw_if) &&
647 I[2]->First->is(tok::kw_else)) {
648 return 0;
651 return 1;
654 unsigned
655 tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
656 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
657 unsigned Limit) {
658 if (Limit == 0 || I + 1 == E ||
659 I[1]->First->isOneOf(tok::kw_case, tok::kw_default)) {
660 return 0;
662 if (I[0]->Last->is(tok::l_brace) || I[1]->First->is(tok::l_brace))
663 return 0;
664 unsigned NumStmts = 0;
665 unsigned Length = 0;
666 bool EndsWithComment = false;
667 bool InPPDirective = I[0]->InPPDirective;
668 bool InMacroBody = I[0]->InMacroBody;
669 const unsigned Level = I[0]->Level;
670 for (; NumStmts < 3; ++NumStmts) {
671 if (I + 1 + NumStmts == E)
672 break;
673 const AnnotatedLine *Line = I[1 + NumStmts];
674 if (Line->InPPDirective != InPPDirective)
675 break;
676 if (Line->InMacroBody != InMacroBody)
677 break;
678 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
679 break;
680 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
681 tok::kw_while) ||
682 EndsWithComment) {
683 return 0;
685 if (Line->First->is(tok::comment)) {
686 if (Level != Line->Level)
687 return 0;
688 SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts;
689 for (; J != E; ++J) {
690 Line = *J;
691 if (Line->InPPDirective != InPPDirective)
692 break;
693 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
694 break;
695 if (Line->First->isNot(tok::comment) || Level != Line->Level)
696 return 0;
698 break;
700 if (Line->Last->is(tok::comment))
701 EndsWithComment = true;
702 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
704 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
705 return 0;
706 return NumStmts;
709 unsigned
710 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
711 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
712 unsigned Limit) {
713 // Don't merge with a preprocessor directive.
714 if (I[1]->Type == LT_PreprocessorDirective)
715 return 0;
717 AnnotatedLine &Line = **I;
719 // Don't merge ObjC @ keywords and methods.
720 // FIXME: If an option to allow short exception handling clauses on a single
721 // line is added, change this to not return for @try and friends.
722 if (Style.Language != FormatStyle::LK_Java &&
723 Line.First->isOneOf(tok::at, tok::minus, tok::plus)) {
724 return 0;
727 // Check that the current line allows merging. This depends on whether we
728 // are in a control flow statements as well as several style flags.
729 if (Line.First->is(tok::kw_case) ||
730 (Line.First->Next && Line.First->Next->is(tok::kw_else))) {
731 return 0;
733 // default: in switch statement
734 if (Line.First->is(tok::kw_default)) {
735 const FormatToken *Tok = Line.First->getNextNonComment();
736 if (Tok && Tok->is(tok::colon))
737 return 0;
740 auto IsCtrlStmt = [](const auto &Line) {
741 return Line.First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
742 tok::kw_do, tok::kw_for, TT_ForEachMacro);
745 const bool IsSplitBlock =
746 Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never ||
747 (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Empty &&
748 I[1]->First->isNot(tok::r_brace));
750 if (IsCtrlStmt(Line) ||
751 Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
752 tok::kw___finally, tok::r_brace,
753 Keywords.kw___except)) {
754 if (IsSplitBlock)
755 return 0;
756 // Don't merge when we can't except the case when
757 // the control statement block is empty
758 if (!Style.AllowShortIfStatementsOnASingleLine &&
759 Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
760 !Style.BraceWrapping.AfterControlStatement &&
761 I[1]->First->isNot(tok::r_brace)) {
762 return 0;
764 if (!Style.AllowShortIfStatementsOnASingleLine &&
765 Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
766 Style.BraceWrapping.AfterControlStatement ==
767 FormatStyle::BWACS_Always &&
768 I + 2 != E && I[2]->First->isNot(tok::r_brace)) {
769 return 0;
771 if (!Style.AllowShortLoopsOnASingleLine &&
772 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
773 TT_ForEachMacro) &&
774 !Style.BraceWrapping.AfterControlStatement &&
775 I[1]->First->isNot(tok::r_brace)) {
776 return 0;
778 if (!Style.AllowShortLoopsOnASingleLine &&
779 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
780 TT_ForEachMacro) &&
781 Style.BraceWrapping.AfterControlStatement ==
782 FormatStyle::BWACS_Always &&
783 I + 2 != E && I[2]->First->isNot(tok::r_brace)) {
784 return 0;
786 // FIXME: Consider an option to allow short exception handling clauses on
787 // a single line.
788 // FIXME: This isn't covered by tests.
789 // FIXME: For catch, __except, __finally the first token on the line
790 // is '}', so this isn't correct here.
791 if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
792 Keywords.kw___except, tok::kw___finally)) {
793 return 0;
797 if (Line.Last->is(tok::l_brace)) {
798 if (IsSplitBlock && Line.First == Line.Last &&
799 I > AnnotatedLines.begin() &&
800 (I[-1]->endsWith(tok::kw_else) || IsCtrlStmt(*I[-1]))) {
801 return 0;
803 FormatToken *Tok = I[1]->First;
804 auto ShouldMerge = [Tok]() {
805 if (Tok->isNot(tok::r_brace) || Tok->MustBreakBefore)
806 return false;
807 const FormatToken *Next = Tok->getNextNonComment();
808 return !Next || Next->is(tok::semi);
811 if (ShouldMerge()) {
812 // We merge empty blocks even if the line exceeds the column limit.
813 Tok->SpacesRequiredBefore = Style.SpaceInEmptyBlock ? 1 : 0;
814 Tok->CanBreakBefore = true;
815 return 1;
816 } else if (Limit != 0 && !Line.startsWithNamespace() &&
817 !startsExternCBlock(Line)) {
818 // We don't merge short records.
819 if (isRecordLBrace(*Line.Last))
820 return 0;
822 // Check that we still have three lines and they fit into the limit.
823 if (I + 2 == E || I[2]->Type == LT_Invalid)
824 return 0;
825 Limit = limitConsideringMacros(I + 2, E, Limit);
827 if (!nextTwoLinesFitInto(I, Limit))
828 return 0;
830 // Second, check that the next line does not contain any braces - if it
831 // does, readability declines when putting it into a single line.
832 if (I[1]->Last->is(TT_LineComment))
833 return 0;
834 do {
835 if (Tok->is(tok::l_brace) && Tok->isNot(BK_BracedInit))
836 return 0;
837 Tok = Tok->Next;
838 } while (Tok);
840 // Last, check that the third line starts with a closing brace.
841 Tok = I[2]->First;
842 if (Tok->isNot(tok::r_brace))
843 return 0;
845 // Don't merge "if (a) { .. } else {".
846 if (Tok->Next && Tok->Next->is(tok::kw_else))
847 return 0;
849 // Don't merge a trailing multi-line control statement block like:
850 // } else if (foo &&
851 // bar)
852 // { <-- current Line
853 // baz();
854 // }
855 if (Line.First == Line.Last && Line.First->isNot(TT_FunctionLBrace) &&
856 Style.BraceWrapping.AfterControlStatement ==
857 FormatStyle::BWACS_MultiLine) {
858 return 0;
861 return 2;
863 } else if (I[1]->First->is(tok::l_brace)) {
864 if (I[1]->Last->is(TT_LineComment))
865 return 0;
867 // Check for Limit <= 2 to account for the " {".
868 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
869 return 0;
870 Limit -= 2;
871 unsigned MergedLines = 0;
872 if (Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never ||
873 (I[1]->First == I[1]->Last && I + 2 != E &&
874 I[2]->First->is(tok::r_brace))) {
875 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
876 // If we managed to merge the block, count the statement header, which
877 // is on a separate line.
878 if (MergedLines > 0)
879 ++MergedLines;
881 return MergedLines;
883 return 0;
886 /// Returns the modified column limit for \p I if it is inside a macro and
887 /// needs a trailing '\'.
888 unsigned
889 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
890 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
891 unsigned Limit) {
892 if (I[0]->InPPDirective && I + 1 != E &&
893 !I[1]->First->HasUnescapedNewline && I[1]->First->isNot(tok::eof)) {
894 return Limit < 2 ? 0 : Limit - 2;
896 return Limit;
899 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
900 unsigned Limit) {
901 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
902 return false;
903 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
906 bool containsMustBreak(const AnnotatedLine *Line) {
907 assert(Line->First);
908 // Ignore the first token, because in this situation, it applies more to the
909 // last token of the previous line.
910 for (const FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next)
911 if (Tok->MustBreakBefore)
912 return true;
913 return false;
916 void join(AnnotatedLine &A, const AnnotatedLine &B) {
917 assert(!A.Last->Next);
918 assert(!B.First->Previous);
919 if (B.Affected)
920 A.Affected = true;
921 A.Last->Next = B.First;
922 B.First->Previous = A.Last;
923 B.First->CanBreakBefore = true;
924 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
925 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
926 Tok->TotalLength += LengthA;
927 A.Last = Tok;
931 const FormatStyle &Style;
932 const AdditionalKeywords &Keywords;
933 const SmallVectorImpl<AnnotatedLine *>::const_iterator End;
935 SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
936 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
939 static void markFinalized(FormatToken *Tok) {
940 for (; Tok; Tok = Tok->Next) {
941 if (Tok->MacroCtx && Tok->MacroCtx->Role == MR_ExpandedArg) {
942 // In the first pass we format all macro arguments in the expanded token
943 // stream. Instead of finalizing the macro arguments, we mark that they
944 // will be modified as unexpanded arguments (as part of the macro call
945 // formatting) in the next pass.
946 Tok->MacroCtx->Role = MR_UnexpandedArg;
947 // Reset whether spaces are required before this token, as that is context
948 // dependent, and that context may change when formatting the macro call.
949 // For example, given M(x) -> 2 * x, and the macro call M(var),
950 // the token 'var' will have SpacesRequiredBefore = 1 after being
951 // formatted as part of the expanded macro, but SpacesRequiredBefore = 0
952 // for its position within the macro call.
953 Tok->SpacesRequiredBefore = 0;
954 } else {
955 Tok->Finalized = true;
960 #ifndef NDEBUG
961 static void printLineState(const LineState &State) {
962 llvm::dbgs() << "State: ";
963 for (const ParenState &P : State.Stack) {
964 llvm::dbgs() << (P.Tok ? P.Tok->TokenText : "F") << "|" << P.Indent << "|"
965 << P.LastSpace << "|" << P.NestedBlockIndent << " ";
967 llvm::dbgs() << State.NextToken->TokenText << "\n";
969 #endif
971 /// Base class for classes that format one \c AnnotatedLine.
972 class LineFormatter {
973 public:
974 LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
975 const FormatStyle &Style,
976 UnwrappedLineFormatter *BlockFormatter)
977 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
978 BlockFormatter(BlockFormatter) {}
979 virtual ~LineFormatter() {}
981 /// Formats an \c AnnotatedLine and returns the penalty.
983 /// If \p DryRun is \c false, directly applies the changes.
984 virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
985 unsigned FirstStartColumn, bool DryRun) = 0;
987 protected:
988 /// If the \p State's next token is an r_brace closing a nested block,
989 /// format the nested block before it.
991 /// Returns \c true if all children could be placed successfully and adapts
992 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
993 /// creates changes using \c Whitespaces.
995 /// The crucial idea here is that children always get formatted upon
996 /// encountering the closing brace right after the nested block. Now, if we
997 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
998 /// \c false), the entire block has to be kept on the same line (which is only
999 /// possible if it fits on the line, only contains a single statement, etc.
1001 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1002 /// break after the "{", format all lines with correct indentation and the put
1003 /// the closing "}" on yet another new line.
1005 /// This enables us to keep the simple structure of the
1006 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1007 /// break or don't break.
1008 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1009 unsigned &Penalty) {
1010 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1011 bool HasLBrace = LBrace && LBrace->is(tok::l_brace) && LBrace->is(BK_Block);
1012 FormatToken &Previous = *State.NextToken->Previous;
1013 if (Previous.Children.size() == 0 || (!HasLBrace && !LBrace->MacroParent)) {
1014 // The previous token does not open a block. Nothing to do. We don't
1015 // assert so that we can simply call this function for all tokens.
1016 return true;
1019 if (NewLine || Previous.MacroParent) {
1020 const ParenState &P = State.Stack.back();
1022 int AdditionalIndent =
1023 P.Indent - Previous.Children[0]->Level * Style.IndentWidth;
1024 Penalty +=
1025 BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
1026 /*FixBadIndentation=*/true);
1027 return true;
1030 if (Previous.Children[0]->First->MustBreakBefore)
1031 return false;
1033 // Cannot merge into one line if this line ends on a comment.
1034 if (Previous.is(tok::comment))
1035 return false;
1037 // Cannot merge multiple statements into a single line.
1038 if (Previous.Children.size() > 1)
1039 return false;
1041 const AnnotatedLine *Child = Previous.Children[0];
1042 // We can't put the closing "}" on a line with a trailing comment.
1043 if (Child->Last->isTrailingComment())
1044 return false;
1046 // If the child line exceeds the column limit, we wouldn't want to merge it.
1047 // We add +2 for the trailing " }".
1048 if (Style.ColumnLimit > 0 &&
1049 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit) {
1050 return false;
1053 if (!DryRun) {
1054 Whitespaces->replaceWhitespace(
1055 *Child->First, /*Newlines=*/0, /*Spaces=*/1,
1056 /*StartOfTokenColumn=*/State.Column, /*IsAligned=*/false,
1057 State.Line->InPPDirective);
1059 Penalty +=
1060 formatLine(*Child, State.Column + 1, /*FirstStartColumn=*/0, DryRun);
1062 State.Column += 1 + Child->Last->TotalLength;
1063 return true;
1066 ContinuationIndenter *Indenter;
1068 private:
1069 WhitespaceManager *Whitespaces;
1070 const FormatStyle &Style;
1071 UnwrappedLineFormatter *BlockFormatter;
1074 /// Formatter that keeps the existing line breaks.
1075 class NoColumnLimitLineFormatter : public LineFormatter {
1076 public:
1077 NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
1078 WhitespaceManager *Whitespaces,
1079 const FormatStyle &Style,
1080 UnwrappedLineFormatter *BlockFormatter)
1081 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1083 /// Formats the line, simply keeping all of the input's line breaking
1084 /// decisions.
1085 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1086 unsigned FirstStartColumn, bool DryRun) override {
1087 assert(!DryRun);
1088 LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
1089 &Line, /*DryRun=*/false);
1090 while (State.NextToken) {
1091 bool Newline =
1092 Indenter->mustBreak(State) ||
1093 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
1094 unsigned Penalty = 0;
1095 formatChildren(State, Newline, /*DryRun=*/false, Penalty);
1096 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
1098 return 0;
1102 /// Formatter that puts all tokens into a single line without breaks.
1103 class NoLineBreakFormatter : public LineFormatter {
1104 public:
1105 NoLineBreakFormatter(ContinuationIndenter *Indenter,
1106 WhitespaceManager *Whitespaces, const FormatStyle &Style,
1107 UnwrappedLineFormatter *BlockFormatter)
1108 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1110 /// Puts all tokens into a single line.
1111 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1112 unsigned FirstStartColumn, bool DryRun) override {
1113 unsigned Penalty = 0;
1114 LineState State =
1115 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
1116 while (State.NextToken) {
1117 formatChildren(State, /*NewLine=*/false, DryRun, Penalty);
1118 Indenter->addTokenToState(
1119 State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun);
1121 return Penalty;
1125 /// Finds the best way to break lines.
1126 class OptimizingLineFormatter : public LineFormatter {
1127 public:
1128 OptimizingLineFormatter(ContinuationIndenter *Indenter,
1129 WhitespaceManager *Whitespaces,
1130 const FormatStyle &Style,
1131 UnwrappedLineFormatter *BlockFormatter)
1132 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1134 /// Formats the line by finding the best line breaks with line lengths
1135 /// below the column limit.
1136 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1137 unsigned FirstStartColumn, bool DryRun) override {
1138 LineState State =
1139 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
1141 // If the ObjC method declaration does not fit on a line, we should format
1142 // it with one arg per line.
1143 if (State.Line->Type == LT_ObjCMethodDecl)
1144 State.Stack.back().BreakBeforeParameter = true;
1146 // Find best solution in solution space.
1147 return analyzeSolutionSpace(State, DryRun);
1150 private:
1151 struct CompareLineStatePointers {
1152 bool operator()(LineState *obj1, LineState *obj2) const {
1153 return *obj1 < *obj2;
1157 /// A pair of <penalty, count> that is used to prioritize the BFS on.
1159 /// In case of equal penalties, we want to prefer states that were inserted
1160 /// first. During state generation we make sure that we insert states first
1161 /// that break the line as late as possible.
1162 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1164 /// An edge in the solution space from \c Previous->State to \c State,
1165 /// inserting a newline dependent on the \c NewLine.
1166 struct StateNode {
1167 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
1168 : State(State), NewLine(NewLine), Previous(Previous) {}
1169 LineState State;
1170 bool NewLine;
1171 StateNode *Previous;
1174 /// An item in the prioritized BFS search queue. The \c StateNode's
1175 /// \c State has the given \c OrderedPenalty.
1176 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1178 /// The BFS queue type.
1179 typedef std::priority_queue<QueueItem, SmallVector<QueueItem>,
1180 std::greater<QueueItem>>
1181 QueueType;
1183 /// Analyze the entire solution space starting from \p InitialState.
1185 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1186 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1187 /// find the shortest path (the one with lowest penalty) from \p InitialState
1188 /// to a state where all tokens are placed. Returns the penalty.
1190 /// If \p DryRun is \c false, directly applies the changes.
1191 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
1192 std::set<LineState *, CompareLineStatePointers> Seen;
1194 // Increasing count of \c StateNode items we have created. This is used to
1195 // create a deterministic order independent of the container.
1196 unsigned Count = 0;
1197 QueueType Queue;
1199 // Insert start element into queue.
1200 StateNode *RootNode =
1201 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
1202 Queue.push(QueueItem(OrderedPenalty(0, Count), RootNode));
1203 ++Count;
1205 unsigned Penalty = 0;
1207 // While not empty, take first element and follow edges.
1208 while (!Queue.empty()) {
1209 // Quit if we still haven't found a solution by now.
1210 if (Count > 25000000)
1211 return 0;
1213 Penalty = Queue.top().first.first;
1214 StateNode *Node = Queue.top().second;
1215 if (!Node->State.NextToken) {
1216 LLVM_DEBUG(llvm::dbgs()
1217 << "\n---\nPenalty for line: " << Penalty << "\n");
1218 break;
1220 Queue.pop();
1222 // Cut off the analysis of certain solutions if the analysis gets too
1223 // complex. See description of IgnoreStackForComparison.
1224 if (Count > 50000)
1225 Node->State.IgnoreStackForComparison = true;
1227 if (!Seen.insert(&Node->State).second) {
1228 // State already examined with lower penalty.
1229 continue;
1232 FormatDecision LastFormat = Node->State.NextToken->getDecision();
1233 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
1234 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
1235 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
1236 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
1239 if (Queue.empty()) {
1240 // We were unable to find a solution, do nothing.
1241 // FIXME: Add diagnostic?
1242 LLVM_DEBUG(llvm::dbgs() << "Could not find a solution.\n");
1243 return 0;
1246 // Reconstruct the solution.
1247 if (!DryRun)
1248 reconstructPath(InitialState, Queue.top().second);
1250 LLVM_DEBUG(llvm::dbgs()
1251 << "Total number of analyzed states: " << Count << "\n");
1252 LLVM_DEBUG(llvm::dbgs() << "---\n");
1254 return Penalty;
1257 /// Add the following state to the analysis queue \c Queue.
1259 /// Assume the current state is \p PreviousNode and has been reached with a
1260 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
1261 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1262 bool NewLine, unsigned *Count, QueueType *Queue) {
1263 if (NewLine && !Indenter->canBreak(PreviousNode->State))
1264 return;
1265 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
1266 return;
1268 StateNode *Node = new (Allocator.Allocate())
1269 StateNode(PreviousNode->State, NewLine, PreviousNode);
1270 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1271 return;
1273 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
1275 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1276 ++(*Count);
1279 /// Applies the best formatting by reconstructing the path in the
1280 /// solution space that leads to \c Best.
1281 void reconstructPath(LineState &State, StateNode *Best) {
1282 llvm::SmallVector<StateNode *> Path;
1283 // We do not need a break before the initial token.
1284 while (Best->Previous) {
1285 Path.push_back(Best);
1286 Best = Best->Previous;
1288 for (const auto &Node : llvm::reverse(Path)) {
1289 unsigned Penalty = 0;
1290 formatChildren(State, Node->NewLine, /*DryRun=*/false, Penalty);
1291 Penalty += Indenter->addTokenToState(State, Node->NewLine, false);
1293 LLVM_DEBUG({
1294 printLineState(Node->Previous->State);
1295 if (Node->NewLine) {
1296 llvm::dbgs() << "Penalty for placing "
1297 << Node->Previous->State.NextToken->Tok.getName()
1298 << " on a new line: " << Penalty << "\n";
1304 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1307 } // anonymous namespace
1309 unsigned UnwrappedLineFormatter::format(
1310 const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
1311 int AdditionalIndent, bool FixBadIndentation, unsigned FirstStartColumn,
1312 unsigned NextStartColumn, unsigned LastStartColumn) {
1313 LineJoiner Joiner(Style, Keywords, Lines);
1315 // Try to look up already computed penalty in DryRun-mode.
1316 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
1317 &Lines, AdditionalIndent);
1318 auto CacheIt = PenaltyCache.find(CacheKey);
1319 if (DryRun && CacheIt != PenaltyCache.end())
1320 return CacheIt->second;
1322 assert(!Lines.empty());
1323 unsigned Penalty = 0;
1324 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
1325 AdditionalIndent);
1326 const AnnotatedLine *PrevPrevLine = nullptr;
1327 const AnnotatedLine *PreviousLine = nullptr;
1328 const AnnotatedLine *NextLine = nullptr;
1330 // The minimum level of consecutive lines that have been formatted.
1331 unsigned RangeMinLevel = UINT_MAX;
1333 bool FirstLine = true;
1334 for (const AnnotatedLine *Line =
1335 Joiner.getNextMergedLine(DryRun, IndentTracker);
1336 Line; PrevPrevLine = PreviousLine, PreviousLine = Line, Line = NextLine,
1337 FirstLine = false) {
1338 assert(Line->First);
1339 const AnnotatedLine &TheLine = *Line;
1340 unsigned Indent = IndentTracker.getIndent();
1342 // We continue formatting unchanged lines to adjust their indent, e.g. if a
1343 // scope was added. However, we need to carefully stop doing this when we
1344 // exit the scope of affected lines to prevent indenting the entire
1345 // remaining file if it currently missing a closing brace.
1346 bool PreviousRBrace =
1347 PreviousLine && PreviousLine->startsWith(tok::r_brace);
1348 bool ContinueFormatting =
1349 TheLine.Level > RangeMinLevel ||
1350 (TheLine.Level == RangeMinLevel && !PreviousRBrace &&
1351 !TheLine.startsWith(tok::r_brace));
1353 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
1354 Indent != TheLine.First->OriginalColumn;
1355 bool ShouldFormat = TheLine.Affected || FixIndentation;
1356 // We cannot format this line; if the reason is that the line had a
1357 // parsing error, remember that.
1358 if (ShouldFormat && TheLine.Type == LT_Invalid && Status) {
1359 Status->FormatComplete = false;
1360 Status->Line =
1361 SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation());
1364 if (ShouldFormat && TheLine.Type != LT_Invalid) {
1365 if (!DryRun) {
1366 bool LastLine = TheLine.First->is(tok::eof);
1367 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines, Indent,
1368 LastLine ? LastStartColumn : NextStartColumn + Indent);
1371 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1372 unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
1373 bool FitsIntoOneLine =
1374 !TheLine.ContainsMacroCall &&
1375 (TheLine.Last->TotalLength + Indent <= ColumnLimit ||
1376 (TheLine.Type == LT_ImportStatement &&
1377 (!Style.isJavaScript() || !Style.JavaScriptWrapImports)) ||
1378 (Style.isCSharp() &&
1379 TheLine.InPPDirective)); // don't split #regions in C#
1380 if (Style.ColumnLimit == 0) {
1381 NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
1382 .formatLine(TheLine, NextStartColumn + Indent,
1383 FirstLine ? FirstStartColumn : 0, DryRun);
1384 } else if (FitsIntoOneLine) {
1385 Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
1386 .formatLine(TheLine, NextStartColumn + Indent,
1387 FirstLine ? FirstStartColumn : 0, DryRun);
1388 } else {
1389 Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
1390 .formatLine(TheLine, NextStartColumn + Indent,
1391 FirstLine ? FirstStartColumn : 0, DryRun);
1393 RangeMinLevel = std::min(RangeMinLevel, TheLine.Level);
1394 } else {
1395 // If no token in the current line is affected, we still need to format
1396 // affected children.
1397 if (TheLine.ChildrenAffected) {
1398 for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next)
1399 if (!Tok->Children.empty())
1400 format(Tok->Children, DryRun);
1403 // Adapt following lines on the current indent level to the same level
1404 // unless the current \c AnnotatedLine is not at the beginning of a line.
1405 bool StartsNewLine =
1406 TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
1407 if (StartsNewLine)
1408 IndentTracker.adjustToUnmodifiedLine(TheLine);
1409 if (!DryRun) {
1410 bool ReformatLeadingWhitespace =
1411 StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
1412 TheLine.LeadingEmptyLinesAffected);
1413 // Format the first token.
1414 if (ReformatLeadingWhitespace) {
1415 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines,
1416 TheLine.First->OriginalColumn,
1417 TheLine.First->OriginalColumn);
1418 } else {
1419 Whitespaces->addUntouchableToken(*TheLine.First,
1420 TheLine.InPPDirective);
1423 // Notify the WhitespaceManager about the unchanged whitespace.
1424 for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
1425 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
1427 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1428 RangeMinLevel = UINT_MAX;
1430 if (!DryRun) {
1431 auto *Tok = TheLine.First;
1432 if (Tok->is(tok::hash) && !Tok->Previous && Tok->Next &&
1433 Tok->Next->isOneOf(tok::pp_if, tok::pp_ifdef, tok::pp_ifndef,
1434 tok::pp_elif, tok::pp_elifdef, tok::pp_elifndef,
1435 tok::pp_else, tok::pp_endif)) {
1436 Tok = Tok->Next;
1438 markFinalized(Tok);
1441 PenaltyCache[CacheKey] = Penalty;
1442 return Penalty;
1445 static auto computeNewlines(const AnnotatedLine &Line,
1446 const AnnotatedLine *PreviousLine,
1447 const AnnotatedLine *PrevPrevLine,
1448 const SmallVectorImpl<AnnotatedLine *> &Lines,
1449 const FormatStyle &Style) {
1450 const auto &RootToken = *Line.First;
1451 auto Newlines =
1452 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1453 // Remove empty lines before "}" where applicable.
1454 if (RootToken.is(tok::r_brace) &&
1455 (!RootToken.Next ||
1456 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)) &&
1457 // Do not remove empty lines before namespace closing "}".
1458 !getNamespaceToken(&Line, Lines)) {
1459 Newlines = std::min(Newlines, 1u);
1461 // Remove empty lines at the start of nested blocks (lambdas/arrow functions)
1462 if (!PreviousLine && Line.Level > 0)
1463 Newlines = std::min(Newlines, 1u);
1464 if (Newlines == 0 && !RootToken.IsFirst)
1465 Newlines = 1;
1466 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1467 Newlines = 0;
1469 // Remove empty lines after "{".
1470 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1471 PreviousLine->Last->is(tok::l_brace) &&
1472 !PreviousLine->startsWithNamespace() &&
1473 !(PrevPrevLine && PrevPrevLine->startsWithNamespace() &&
1474 PreviousLine->startsWith(tok::l_brace)) &&
1475 !startsExternCBlock(*PreviousLine)) {
1476 Newlines = 1;
1479 // Insert or remove empty line before access specifiers.
1480 if (PreviousLine && RootToken.isAccessSpecifier()) {
1481 switch (Style.EmptyLineBeforeAccessModifier) {
1482 case FormatStyle::ELBAMS_Never:
1483 if (Newlines > 1)
1484 Newlines = 1;
1485 break;
1486 case FormatStyle::ELBAMS_Leave:
1487 Newlines = std::max(RootToken.NewlinesBefore, 1u);
1488 break;
1489 case FormatStyle::ELBAMS_LogicalBlock:
1490 if (PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) && Newlines <= 1)
1491 Newlines = 2;
1492 if (PreviousLine->First->isAccessSpecifier())
1493 Newlines = 1; // Previous is an access modifier remove all new lines.
1494 break;
1495 case FormatStyle::ELBAMS_Always: {
1496 const FormatToken *previousToken;
1497 if (PreviousLine->Last->is(tok::comment))
1498 previousToken = PreviousLine->Last->getPreviousNonComment();
1499 else
1500 previousToken = PreviousLine->Last;
1501 if ((!previousToken || previousToken->isNot(tok::l_brace)) &&
1502 Newlines <= 1) {
1503 Newlines = 2;
1505 } break;
1509 // Insert or remove empty line after access specifiers.
1510 if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
1511 (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline)) {
1512 // EmptyLineBeforeAccessModifier is handling the case when two access
1513 // modifiers follow each other.
1514 if (!RootToken.isAccessSpecifier()) {
1515 switch (Style.EmptyLineAfterAccessModifier) {
1516 case FormatStyle::ELAAMS_Never:
1517 Newlines = 1;
1518 break;
1519 case FormatStyle::ELAAMS_Leave:
1520 Newlines = std::max(Newlines, 1u);
1521 break;
1522 case FormatStyle::ELAAMS_Always:
1523 if (RootToken.is(tok::r_brace)) // Do not add at end of class.
1524 Newlines = 1u;
1525 else
1526 Newlines = std::max(Newlines, 2u);
1527 break;
1532 return Newlines;
1535 void UnwrappedLineFormatter::formatFirstToken(
1536 const AnnotatedLine &Line, const AnnotatedLine *PreviousLine,
1537 const AnnotatedLine *PrevPrevLine,
1538 const SmallVectorImpl<AnnotatedLine *> &Lines, unsigned Indent,
1539 unsigned NewlineIndent) {
1540 FormatToken &RootToken = *Line.First;
1541 if (RootToken.is(tok::eof)) {
1542 unsigned Newlines =
1543 std::min(RootToken.NewlinesBefore,
1544 Style.KeepEmptyLinesAtEOF ? Style.MaxEmptyLinesToKeep + 1 : 1);
1545 unsigned TokenIndent = Newlines ? NewlineIndent : 0;
1546 Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
1547 TokenIndent);
1548 return;
1551 if (RootToken.Newlines < 0) {
1552 RootToken.Newlines =
1553 computeNewlines(Line, PreviousLine, PrevPrevLine, Lines, Style);
1554 assert(RootToken.Newlines >= 0);
1557 if (RootToken.Newlines > 0)
1558 Indent = NewlineIndent;
1560 // Preprocessor directives get indented before the hash only if specified. In
1561 // Javascript import statements are indented like normal statements.
1562 if (!Style.isJavaScript() &&
1563 Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
1564 (Line.Type == LT_PreprocessorDirective ||
1565 Line.Type == LT_ImportStatement)) {
1566 Indent = 0;
1569 Whitespaces->replaceWhitespace(RootToken, RootToken.Newlines, Indent, Indent,
1570 /*IsAligned=*/false,
1571 Line.InPPDirective &&
1572 !RootToken.HasUnescapedNewline);
1575 unsigned
1576 UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
1577 const AnnotatedLine *NextLine) const {
1578 // In preprocessor directives reserve two chars for trailing " \" if the
1579 // next line continues the preprocessor directive.
1580 bool ContinuesPPDirective =
1581 InPPDirective &&
1582 // If there is no next line, this is likely a child line and the parent
1583 // continues the preprocessor directive.
1584 (!NextLine ||
1585 (NextLine->InPPDirective &&
1586 // If there is an unescaped newline between this line and the next, the
1587 // next line starts a new preprocessor directive.
1588 !NextLine->First->HasUnescapedNewline));
1589 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
1592 } // namespace format
1593 } // namespace clang