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//===----------------------------------------------------------------------===//
8
9#include "UnwrappedLineFormatter.h"
10#include "FormatToken.h"
11#include "WhitespaceManager.h"
12#include "llvm/Support/Debug.h"
13#include <queue>
14
15#define DEBUG_TYPE "format-formatter"
16
17namespace clang {
18namespace format {
19
20namespace {
21
22bool startsExternCBlock(const AnnotatedLine &Line) {
23 const FormatToken *Next = Line.First->getNextNonComment();
24 const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
25 return Line.startsWith(Tokens: tok::kw_extern) && Next && Next->isStringLiteral() &&
26 NextNext && NextNext->is(Kind: tok::l_brace);
27}
28
29bool isRecordLBrace(const FormatToken &Tok) {
30 return Tok.isOneOf(K1: TT_ClassLBrace, K2: TT_EnumLBrace, Ks: TT_RecordLBrace,
31 Ks: TT_StructLBrace, Ks: TT_UnionLBrace);
32}
33
34/// Tracks the indent level of \c AnnotatedLines across levels.
35///
36/// \c nextLine must be called for each \c AnnotatedLine, after which \c
37/// getIndent() will return the indent for the last line \c nextLine was called
38/// with.
39/// If the line is not formatted (and thus the indent does not change), calling
40/// \c adjustToUnmodifiedLine after the call to \c nextLine will cause
41/// subsequent lines on the same level to be indented at the same level as the
42/// given line.
43class LevelIndentTracker {
44public:
45 LevelIndentTracker(const FormatStyle &Style,
46 const AdditionalKeywords &Keywords, unsigned StartLevel,
47 int AdditionalIndent)
48 : Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) {
49 for (unsigned i = 0; i != StartLevel; ++i)
50 IndentForLevel.push_back(Elt: Style.IndentWidth * i + AdditionalIndent);
51 }
52
53 /// Returns the indent for the current line.
54 unsigned getIndent() const { return Indent; }
55
56 /// Update the indent state given that \p Line is going to be formatted
57 /// next.
58 void nextLine(const AnnotatedLine &Line) {
59 Offset = getIndentOffset(Line);
60 // Update the indent level cache size so that we can rely on it
61 // having the right size in adjustToUnmodifiedline.
62 if (Line.Level >= IndentForLevel.size())
63 IndentForLevel.resize(N: Line.Level + 1, NV: -1);
64 if (Style.IndentPPDirectives == FormatStyle::PPDIS_Leave &&
65 (Line.InPPDirective || Line.Type == LT_CommentAbovePPDirective)) {
66 Indent = Line.InMacroBody
67 ? (Line.Level - Line.PPLevel) * Style.IndentWidth +
68 AdditionalIndent
69 : Line.First->OriginalColumn;
70 } else if (Style.IndentPPDirectives != FormatStyle::PPDIS_None &&
71 (Line.InPPDirective ||
72 (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash &&
73 Line.Type == LT_CommentAbovePPDirective))) {
74 unsigned PPIndentWidth =
75 (Style.PPIndentWidth >= 0) ? Style.PPIndentWidth : Style.IndentWidth;
76 Indent = Line.InMacroBody
77 ? Line.PPLevel * PPIndentWidth +
78 (Line.Level - Line.PPLevel) * Style.IndentWidth
79 : Line.Level * PPIndentWidth;
80 Indent += AdditionalIndent;
81 } else {
82 // When going to lower levels, forget previous higher levels so that we
83 // recompute future higher levels. But don't forget them if we enter a PP
84 // directive, since these do not terminate a C++ code block.
85 if (!Line.InPPDirective) {
86 assert(Line.Level <= IndentForLevel.size());
87 IndentForLevel.resize(N: Line.Level + 1);
88 }
89 Indent = getIndent(Level: Line.Level);
90 }
91 if (static_cast<int>(Indent) + Offset >= 0)
92 Indent += Offset;
93 if (Line.IsContinuation)
94 Indent = Line.Level * Style.IndentWidth + Style.ContinuationIndentWidth;
95 }
96
97 /// Update the level indent to adapt to the given \p Line.
98 ///
99 /// When a line is not formatted, we move the subsequent lines on the same
100 /// level to the same indent.
101 /// Note that \c nextLine must have been called before this method.
102 void adjustToUnmodifiedLine(const AnnotatedLine &Line) {
103 if (Line.InPPDirective || Line.IsContinuation)
104 return;
105 assert(Line.Level < IndentForLevel.size());
106 if (Line.First->is(Kind: tok::comment) && IndentForLevel[Line.Level] != -1)
107 return;
108 unsigned LevelIndent = Line.First->OriginalColumn;
109 if (static_cast<int>(LevelIndent) - Offset >= 0)
110 LevelIndent -= Offset;
111 IndentForLevel[Line.Level] = LevelIndent;
112 }
113
114private:
115 /// Get the offset of the line relatively to the level.
116 ///
117 /// For example, 'public:' labels in classes are offset by 1 or 2
118 /// characters to the left from their level.
119 int getIndentOffset(const AnnotatedLine &Line) {
120 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp())
121 return 0;
122
123 const auto &RootToken = *Line.First;
124
125 if (Style.IndentGotoLabels == FormatStyle::IGLS_HalfIndent &&
126 RootToken.Next && RootToken.Next->is(TT: TT_GotoLabelColon)) {
127 return -static_cast<int>(Style.IndentWidth / 2);
128 }
129
130 if (Line.Type == LT_AccessModifier ||
131 RootToken.isAccessSpecifier(/*ColonRequired=*/false) ||
132 RootToken.isObjCAccessSpecifier() ||
133 (RootToken.isOneOf(K1: Keywords.kw_signals, K2: Keywords.kw_qsignals) &&
134 RootToken.Next && RootToken.Next->is(Kind: tok::colon))) {
135 // The AccessModifierOffset may be overridden by IndentAccessModifiers,
136 // in which case we take a negative value of the IndentWidth to simulate
137 // the upper indent level.
138 return Style.IndentAccessModifiers != FormatStyle::IAMS_Never
139 ? -Style.IndentWidth
140 : Style.AccessModifierOffset;
141 }
142 return 0;
143 }
144
145 /// Get the indent of \p Level from \p IndentForLevel.
146 ///
147 /// \p IndentForLevel must contain the indent for the level \c l
148 /// at \p IndentForLevel[l], or a value < 0 if the indent for
149 /// that level is unknown.
150 unsigned getIndent(unsigned Level) const {
151 assert(Level < IndentForLevel.size());
152 if (IndentForLevel[Level] != -1)
153 return IndentForLevel[Level];
154 if (Level == 0)
155 return 0;
156 return getIndent(Level: Level - 1) + Style.IndentWidth;
157 }
158
159 const FormatStyle &Style;
160 const AdditionalKeywords &Keywords;
161 const unsigned AdditionalIndent;
162
163 /// The indent in characters for each level. It remembers the indent of
164 /// previous lines (that are not PP directives) of equal or lower levels. This
165 /// is used to align formatted lines to the indent of previous non-formatted
166 /// lines. Think about the --lines parameter of clang-format.
167 SmallVector<int> IndentForLevel;
168
169 /// Offset of the current line relative to the indent level.
170 ///
171 /// For example, the 'public' keywords is often indented with a negative
172 /// offset.
173 int Offset = 0;
174
175 /// The current line's indent.
176 unsigned Indent = 0;
177};
178
179const FormatToken *
180getMatchingNamespaceToken(const AnnotatedLine *Line,
181 const ArrayRef<AnnotatedLine *> &AnnotatedLines) {
182 if (!Line->startsWith(Tokens: tok::r_brace))
183 return nullptr;
184 size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex;
185 if (StartLineIndex == UnwrappedLine::kInvalidIndex)
186 return nullptr;
187 assert(StartLineIndex < AnnotatedLines.size());
188 return AnnotatedLines[StartLineIndex]->First->getNamespaceToken();
189}
190
191StringRef getNamespaceTokenText(const AnnotatedLine *Line) {
192 const FormatToken *NamespaceToken = Line->First->getNamespaceToken();
193 return NamespaceToken ? NamespaceToken->TokenText : StringRef();
194}
195
196StringRef
197getMatchingNamespaceTokenText(const AnnotatedLine *Line,
198 const ArrayRef<AnnotatedLine *> &AnnotatedLines) {
199 const FormatToken *NamespaceToken =
200 getMatchingNamespaceToken(Line, AnnotatedLines);
201 return NamespaceToken ? NamespaceToken->TokenText : StringRef();
202}
203
204class LineJoiner {
205public:
206 LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords,
207 const SmallVectorImpl<AnnotatedLine *> &Lines)
208 : Style(Style), Keywords(Keywords), End(Lines.end()), Next(Lines.begin()),
209 AnnotatedLines(Lines) {}
210
211 /// Returns the next line, merging multiple lines into one if possible.
212 const AnnotatedLine *getNextMergedLine(bool DryRun,
213 LevelIndentTracker &IndentTracker) {
214 if (Next == End)
215 return nullptr;
216 const AnnotatedLine *Current = *Next;
217 IndentTracker.nextLine(Line: *Current);
218 unsigned MergedLines =
219 Current->InMacroExpansion
220 ? 0
221 : tryFitMultipleLinesInOne(IndentTracker, I: Next, E: End);
222 if (MergedLines > 0 && Style.ColumnLimit == 0) {
223 // Disallow line merging if there is a break at the start of one of the
224 // input lines.
225 for (unsigned i = 0; i < MergedLines; ++i)
226 if (Next[i + 1]->First->NewlinesBefore > 0)
227 MergedLines = 0;
228 }
229 if (MergedLines > 0) {
230 bool MergingEmptyBlock = MergedLines == 1 &&
231 Next[0]->endsWith(Tokens: tok::l_brace) &&
232 Next[1]->startsWith(Tokens: tok::r_brace);
233 for (unsigned i = 0; i <= MergedLines; ++i) {
234 if (cannotMergeMacroLine(Line: Next[i],
235 /*AllowMultiLine=*/i == 0 &&
236 MergingEmptyBlock)) {
237 MergedLines = 0;
238 break;
239 }
240 }
241 }
242 if (!DryRun)
243 for (unsigned i = 0; i < MergedLines; ++i)
244 join(A&: *Next[0], B: *Next[i + 1]);
245 Next = Next + MergedLines + 1;
246 return Current;
247 }
248
249private:
250 /// Calculates how many lines can be merged into 1 starting at \p I.
251 unsigned
252 tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker,
253 ArrayRef<AnnotatedLine *>::const_iterator I,
254 ArrayRef<AnnotatedLine *>::const_iterator E) {
255 // Can't join the last line with anything.
256 if (I + 1 == E)
257 return 0;
258 // We can never merge stuff if there are trailing line comments.
259 const AnnotatedLine *TheLine = *I;
260 if (TheLine->Last->is(TT: TT_LineComment))
261 return 0;
262 const auto &NextLine = *I[1];
263 if (NextLine.Type == LT_Invalid || NextLine.First->MustBreakBefore)
264 return 0;
265 if (TheLine->InPPDirective &&
266 (!NextLine.InPPDirective || NextLine.First->HasUnescapedNewline)) {
267 return 0;
268 }
269
270 const auto Indent = IndentTracker.getIndent();
271 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
272 return 0;
273
274 unsigned Limit =
275 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
276 // If we already exceed the column limit, we set 'Limit' to 0. The different
277 // tryMerge..() functions can then decide whether to still do merging.
278 Limit = TheLine->Last->TotalLength > Limit
279 ? 0
280 : Limit - TheLine->Last->TotalLength;
281
282 if (TheLine->Last->is(TT: TT_FunctionLBrace) &&
283 TheLine->First == TheLine->Last) {
284 const bool EmptyFunctionBody = NextLine.First->is(Kind: tok::r_brace);
285 if ((EmptyFunctionBody && !Style.BraceWrapping.SplitEmptyFunction) ||
286 (!EmptyFunctionBody &&
287 Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Always)) {
288 return tryMergeSimpleBlock(I, E, Limit);
289 }
290 }
291
292 // Try merging record blocks that have had their left brace wrapped into
293 // a single line.
294 if (NextLine.First->isOneOf(K1: TT_ClassLBrace, K2: TT_StructLBrace,
295 Ks: TT_UnionLBrace)) {
296 if (unsigned MergedLines = tryMergeRecord(I, E, Limit))
297 return MergedLines;
298 }
299
300 // Optionally merge preceding `break` or `[[fallthrough]]` with case label
301 // when at compatible levels, preserving label's indent.
302 if (Style.CompactCaseLabels &&
303 NextLine.First->isOneOf(K1: tok::kw_case, K2: tok::kw_default) &&
304 TheLine->Level <= NextLine.Level + 1 &&
305 canJoinWithCaseLabel(Line: TheLine, LabelTok: *NextLine.First)) {
306 IndentTracker.nextLine(Line: NextLine);
307 unsigned MergedLinesInCaseBody =
308 Style.AllowShortCaseLabelsOnASingleLine
309 ? tryMergeShortCaseLabels(I: I + 1, E, Limit)
310 : 0;
311 return 1 + MergedLinesInCaseBody;
312 }
313
314 const auto *PreviousLine = I != AnnotatedLines.begin() ? I[-1] : nullptr;
315
316 // Handle blocks where the brace has already been wrapped.
317 if (PreviousLine && TheLine->Last->is(Kind: tok::l_brace) &&
318 TheLine->First == TheLine->Last) {
319 const bool EmptyBlock = NextLine.First->is(Kind: tok::r_brace);
320
321 const FormatToken *Tok = PreviousLine->getFirstNonComment();
322
323 if (Tok && Tok->getNamespaceToken()) {
324 return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock
325 ? tryMergeSimpleBlock(I, E, Limit)
326 : 0;
327 }
328
329 if (Tok && Tok->is(Kind: tok::kw_typedef))
330 Tok = Tok->getNextNonComment();
331
332 if (Tok && Tok->isOneOf(K1: tok::kw_class, K2: tok::kw_struct, Ks: tok::kw_union))
333 return tryMergeRecord(I, E, Limit);
334
335 if (Tok && Tok->isOneOf(K1: tok::kw_extern, K2: Keywords.kw_interface)) {
336 return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock
337 ? tryMergeSimpleBlock(I, E, Limit)
338 : 0;
339 }
340
341 if (Tok && Tok->is(Kind: tok::kw_template) &&
342 Style.BraceWrapping.SplitEmptyRecord && EmptyBlock) {
343 return 0;
344 }
345 }
346
347 auto ShouldMergeShortFunctions = [&] {
348 if (Style.AllowShortFunctionsOnASingleLine.isAll())
349 return true;
350
351 if (Style.AllowShortFunctionsOnASingleLine.Empty &&
352 NextLine.First->is(Kind: tok::r_brace)) {
353 return true;
354 }
355
356 if (Style.AllowShortFunctionsOnASingleLine.Inline &&
357 !Style.AllowShortFunctionsOnASingleLine.Other) {
358 if (Style.isJavaScript() && TheLine->Last->is(TT: TT_FunctionLBrace))
359 return true;
360
361 // Just checking `TheLine->Level > 0` is not enough because it would
362 // cause functions inside indented namespaces to be treated as short.
363 if (const auto Level = TheLine->Level; Level > 0) {
364 if (!PreviousLine)
365 return false;
366
367 // TODO: Use IndentTracker to avoid loop?
368 // Find the last line with lower level.
369 const AnnotatedLine *Line = nullptr;
370 for (auto J = I - 1; J >= AnnotatedLines.begin(); --J) {
371 const auto *L = *J;
372 assert(L);
373 if (TheLine->InMacroBody && !L->InMacroBody)
374 break;
375 if (L->isComment() || (!TheLine->InPPDirective && L->InPPDirective))
376 continue;
377 if (L->Level < Level ||
378 (L->Level == Level && L->First->is(Kind: tok::l_brace) &&
379 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)) {
380 Line = L;
381 break;
382 }
383 }
384
385 if (!Line)
386 return false;
387
388 // Check if the found line starts a record.
389 const auto *LastNonComment = Line->getLastNonComment();
390 // There must be another token (usually `{`), because we chose a
391 // non-PPDirective and non-comment line that has a smaller level.
392 assert(LastNonComment);
393 return isRecordLBrace(Tok: *LastNonComment);
394 }
395 }
396
397 return false;
398 };
399
400 bool MergeShortFunctions = ShouldMergeShortFunctions();
401
402 const auto *FirstNonComment = TheLine->getFirstNonComment();
403 if (!FirstNonComment)
404 return 0;
405
406 // FIXME: There are probably cases where we should use FirstNonComment
407 // instead of TheLine->First.
408
409 if (Style.AllowShortNamespacesOnASingleLine &&
410 TheLine->First->is(Kind: tok::kw_namespace)) {
411 const auto result = tryMergeNamespace(I, E, Limit);
412 if (result > 0)
413 return result;
414 }
415
416 if (Style.CompactNamespaces) {
417 if (const auto *NSToken = TheLine->First->getNamespaceToken()) {
418 int J = 1;
419 assert(TheLine->MatchingClosingBlockLineIndex > 0);
420 for (auto ClosingLineIndex = TheLine->MatchingClosingBlockLineIndex - 1;
421 I + J != E && NSToken->TokenText == getNamespaceTokenText(Line: I[J]) &&
422 ClosingLineIndex == I[J]->MatchingClosingBlockLineIndex &&
423 I[J]->Last->TotalLength < Limit;
424 ++J, --ClosingLineIndex) {
425 Limit -= I[J]->Last->TotalLength + 1;
426
427 // Reduce indent level for bodies of namespaces which were compacted,
428 // but only if their content was indented in the first place.
429 auto *ClosingLine = AnnotatedLines.begin() + ClosingLineIndex + 1;
430 const int OutdentBy = I[J]->Level - TheLine->Level;
431 assert(OutdentBy >= 0);
432 for (auto *CompactedLine = I + J; CompactedLine <= ClosingLine;
433 ++CompactedLine) {
434 if (!(*CompactedLine)->InPPDirective) {
435 const int Level = (*CompactedLine)->Level;
436 (*CompactedLine)->Level = std::max(a: Level - OutdentBy, b: 0);
437 }
438 }
439 }
440 return J - 1;
441 }
442
443 if (auto nsToken = getMatchingNamespaceToken(Line: TheLine, AnnotatedLines)) {
444 int i = 0;
445 unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
446 for (; I + 1 + i != E &&
447 nsToken->TokenText ==
448 getMatchingNamespaceTokenText(Line: I[i + 1], AnnotatedLines) &&
449 openingLine == I[i + 1]->MatchingOpeningBlockLineIndex;
450 i++, --openingLine) {
451 // No space between consecutive braces.
452 I[i + 1]->First->SpacesRequiredBefore =
453 I[i]->Last->isNot(Kind: tok::r_brace);
454
455 // Indent like the outer-most namespace.
456 IndentTracker.nextLine(Line: *I[i + 1]);
457 }
458 return i;
459 }
460 }
461
462 const auto *LastNonComment = TheLine->getLastNonComment();
463 assert(LastNonComment);
464 // FIXME: There are probably cases where we should use LastNonComment
465 // instead of TheLine->Last.
466
467 // Try to merge a function block with left brace unwrapped.
468 if (LastNonComment->is(TT: TT_FunctionLBrace) &&
469 TheLine->First != LastNonComment) {
470 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
471 }
472
473 // Try to merge a control statement block with left brace unwrapped.
474 if (TheLine->Last->is(Kind: tok::l_brace) && FirstNonComment != TheLine->Last &&
475 (FirstNonComment->isOneOf(K1: tok::kw_if, K2: tok::kw_while, Ks: tok::kw_for,
476 Ks: TT_ForEachMacro) ||
477 (TheLine->Last->is(TT: TT_ExportLBrace) &&
478 !Style.BraceWrapping.AfterExportBlock))) {
479 return Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never
480 ? tryMergeSimpleBlock(I, E, Limit)
481 : 0;
482 }
483 // Try to merge a control statement block with left brace wrapped.
484 if (NextLine.First->is(TT: TT_ControlStatementLBrace)) {
485 // If possible, merge the next line's wrapped left brace with the
486 // current line. Otherwise, leave it on the next line, as this is a
487 // multi-line control statement.
488 return Style.BraceWrapping.AfterControlStatement ==
489 FormatStyle::BWACS_Always
490 ? tryMergeSimpleBlock(I, E, Limit)
491 : 0;
492 }
493 if (PreviousLine && TheLine->First->is(Kind: tok::l_brace)) {
494 switch (PreviousLine->First->Tok.getKind()) {
495 case tok::at:
496 // Don't merge block with left brace wrapped after ObjC special blocks.
497 if (PreviousLine->First->Next &&
498 PreviousLine->First->Next->isOneOf(K1: tok::objc_autoreleasepool,
499 K2: tok::objc_synchronized)) {
500 return 0;
501 }
502 break;
503
504 case tok::kw_case:
505 case tok::kw_default:
506 // Don't merge block with left brace wrapped after case labels.
507 return 0;
508
509 default:
510 break;
511 }
512 }
513
514 // Don't merge an empty template class or struct if SplitEmptyRecords
515 // is defined.
516 if (PreviousLine && Style.BraceWrapping.SplitEmptyRecord &&
517 TheLine->Last->is(Kind: tok::l_brace) && PreviousLine->Last) {
518 const FormatToken *Previous = PreviousLine->Last;
519 if (Previous) {
520 if (Previous->is(Kind: tok::comment))
521 Previous = Previous->getPreviousNonComment();
522 if (Previous) {
523 if (Previous->is(Kind: tok::greater) && !PreviousLine->InPPDirective)
524 return 0;
525 if (Previous->is(Kind: tok::identifier)) {
526 const FormatToken *PreviousPrevious =
527 Previous->getPreviousNonComment();
528 if (PreviousPrevious &&
529 PreviousPrevious->isOneOf(K1: tok::kw_class, K2: tok::kw_struct,
530 Ks: tok::kw_union)) {
531 return 0;
532 }
533 }
534 }
535 }
536 }
537
538 if (TheLine->First->is(TT: TT_SwitchExpressionLabel)) {
539 return Style.AllowShortCaseExpressionOnASingleLine
540 ? tryMergeShortCaseLabels(I, E, Limit)
541 : 0;
542 }
543
544 if (TheLine->Last->is(Kind: tok::l_brace)) {
545 bool ShouldMerge = false;
546 // Try to merge records.
547 if (TheLine->Last->is(TT: TT_EnumLBrace)) {
548 ShouldMerge = Style.AllowShortEnumsOnASingleLine;
549 } else if (TheLine->Last->is(TT: TT_CompoundRequirementLBrace)) {
550 ShouldMerge = Style.AllowShortCompoundRequirementOnASingleLine;
551 } else if (TheLine->Last->isOneOf(K1: TT_ClassLBrace, K2: TT_StructLBrace,
552 Ks: TT_UnionLBrace)) {
553 return tryMergeRecord(I, E, Limit);
554 } else if (TheLine->Last->is(TT: TT_RecordLBrace) && Style.isJava()) {
555 // Java `interface` and `record` have no dedicated `BraceWrapping.After`
556 // option and are not governed by `AllowShortRecordOnASingleLine`.
557 ShouldMerge = !Style.BraceWrapping.AfterClass ||
558 (NextLine.First->is(Kind: tok::r_brace) &&
559 !Style.BraceWrapping.SplitEmptyRecord);
560 } else if (TheLine->InPPDirective ||
561 TheLine->First->isNoneOf(Ks: tok::kw_class, Ks: tok::kw_enum,
562 Ks: tok::kw_struct, Ks: tok::kw_union)) {
563 // Try to merge a block with left brace unwrapped that wasn't yet
564 // covered.
565 ShouldMerge = !Style.BraceWrapping.AfterFunction ||
566 (NextLine.First->is(Kind: tok::r_brace) &&
567 !Style.BraceWrapping.SplitEmptyFunction);
568 }
569 return ShouldMerge ? tryMergeSimpleBlock(I, E, Limit) : 0;
570 }
571
572 // Try to merge a function block with left brace wrapped.
573 if (NextLine.First->is(TT: TT_FunctionLBrace) &&
574 Style.BraceWrapping.AfterFunction) {
575 if (NextLine.Last->is(TT: TT_LineComment))
576 return 0;
577
578 // Check for Limit <= 2 to account for the " {".
579 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(Line: TheLine)))
580 return 0;
581 Limit -= 2;
582
583 unsigned MergedLines = 0;
584 if (MergeShortFunctions ||
585 (Style.AllowShortFunctionsOnASingleLine.Empty &&
586 NextLine.First == NextLine.Last && I + 2 != E &&
587 I[2]->First->is(Kind: tok::r_brace))) {
588 MergedLines = tryMergeSimpleBlock(I: I + 1, E, Limit);
589 // If we managed to merge the block, count the function header, which is
590 // on a separate line.
591 if (MergedLines > 0)
592 ++MergedLines;
593 }
594 return MergedLines;
595 }
596 auto IsElseLine = [&TheLine]() -> bool {
597 const FormatToken *First = TheLine->First;
598 if (First->is(Kind: tok::kw_else))
599 return true;
600
601 return First->is(Kind: tok::r_brace) && First->Next &&
602 First->Next->is(Kind: tok::kw_else);
603 };
604 if (TheLine->First->is(Kind: tok::kw_if) ||
605 (IsElseLine() && (Style.AllowShortIfStatementsOnASingleLine ==
606 FormatStyle::SIS_AllIfsAndElse))) {
607 return Style.AllowShortIfStatementsOnASingleLine
608 ? tryMergeSimpleControlStatement(I, E, Limit)
609 : 0;
610 }
611 if (TheLine->First->isOneOf(K1: tok::kw_for, K2: tok::kw_while, Ks: tok::kw_do,
612 Ks: TT_ForEachMacro)) {
613 return Style.AllowShortLoopsOnASingleLine
614 ? tryMergeSimpleControlStatement(I, E, Limit)
615 : 0;
616 }
617 if (TheLine->First->isOneOf(K1: tok::kw_case, K2: tok::kw_default)) {
618 return Style.AllowShortCaseLabelsOnASingleLine
619 ? tryMergeShortCaseLabels(I, E, Limit)
620 : 0;
621 }
622 if (TheLine->InPPDirective &&
623 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
624 return tryMergeSimplePPDirective(I, E, Limit);
625 }
626 return 0;
627 }
628
629 unsigned tryMergeRecord(ArrayRef<AnnotatedLine *>::const_iterator I,
630 ArrayRef<AnnotatedLine *>::const_iterator E,
631 unsigned Limit) {
632 const auto *Line = I[0];
633 const auto *NextLine = I[1];
634
635 // Current line begins both record and block, brace was not wrapped.
636 if (Line->Last->isOneOf(K1: TT_ClassLBrace, K2: TT_StructLBrace, Ks: TT_UnionLBrace)) {
637 auto ShouldWrapLBrace = [&](TokenType LBraceType) {
638 switch (LBraceType) {
639 case TT_ClassLBrace:
640 return Style.BraceWrapping.AfterClass;
641 case TT_StructLBrace:
642 return Style.BraceWrapping.AfterStruct;
643 case TT_UnionLBrace:
644 return Style.BraceWrapping.AfterUnion;
645 default:
646 return false;
647 }
648 };
649
650 auto TryMergeShortRecord = [&] {
651 switch (Style.AllowShortRecordOnASingleLine) {
652 case FormatStyle::SRS_Never:
653 return false;
654 case FormatStyle::SRS_Always:
655 return true;
656 default:
657 return NextLine->First->is(Kind: tok::r_brace);
658 }
659 };
660
661 if (Style.AllowShortRecordOnASingleLine != FormatStyle::SRS_Never &&
662 (!ShouldWrapLBrace(Line->Last->getType()) ||
663 (!Style.BraceWrapping.SplitEmptyRecord && TryMergeShortRecord()))) {
664 return tryMergeSimpleBlock(I, E, Limit);
665 }
666 }
667
668 // Cases where the l_brace was wrapped.
669 // Current line begins record, next line block.
670 if (NextLine->First->isOneOf(K1: TT_ClassLBrace, K2: TT_StructLBrace,
671 Ks: TT_UnionLBrace)) {
672 if (I + 2 == E || I[2]->First->is(Kind: tok::r_brace) ||
673 Style.AllowShortRecordOnASingleLine != FormatStyle::SRS_Always) {
674 return 0;
675 }
676
677 return tryMergeSimpleBlock(I, E, Limit);
678 }
679
680 // Previous line begins record, current line block.
681 if (I != AnnotatedLines.begin() &&
682 I[-1]->First->isOneOf(K1: tok::kw_class, K2: tok::kw_struct, Ks: tok::kw_union)) {
683 const bool IsEmptyBlock =
684 Line->Last->is(Kind: tok::l_brace) && NextLine->First->is(Kind: tok::r_brace);
685
686 if ((IsEmptyBlock && !Style.BraceWrapping.SplitEmptyRecord) ||
687 (!IsEmptyBlock &&
688 Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Always)) {
689 return tryMergeSimpleBlock(I, E, Limit);
690 }
691 }
692
693 return 0;
694 }
695
696 bool canJoinWithCaseLabel(const AnnotatedLine *Line,
697 const FormatToken &LabelTok) {
698 if (Line->endsWith(Tokens: tok::semi, Tokens: tok::kw_break))
699 return true;
700
701 if (Line->startsWith(Tokens: TT_AttributeLSquare) &&
702 Line->endsWith(Tokens: tok::semi, Tokens: TT_AttributeRSquare)) {
703 return !LabelTok.mustBreakAfterAttributes(Style);
704 }
705
706 return false;
707 }
708
709 unsigned
710 tryMergeSimplePPDirective(ArrayRef<AnnotatedLine *>::const_iterator I,
711 ArrayRef<AnnotatedLine *>::const_iterator E,
712 unsigned Limit) {
713 if (Limit == 0)
714 return 0;
715 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
716 return 0;
717 if (1 + I[1]->Last->TotalLength > Limit)
718 return 0;
719 return 1;
720 }
721
722 unsigned tryMergeNamespace(ArrayRef<AnnotatedLine *>::const_iterator I,
723 ArrayRef<AnnotatedLine *>::const_iterator E,
724 unsigned Limit) {
725 if (Limit == 0)
726 return 0;
727
728 // The merging code is relative to the opening namespace brace, which could
729 // be either on the first or second line due to the brace wrapping rules.
730 const bool OpenBraceWrapped = Style.BraceWrapping.AfterNamespace;
731 const auto *BraceOpenLine = I + OpenBraceWrapped;
732
733 assert(*BraceOpenLine);
734 if (BraceOpenLine[0]->Last->isNot(Kind: TT_NamespaceLBrace))
735 return 0;
736
737 if (std::distance(first: BraceOpenLine, last: E) <= 2)
738 return 0;
739
740 if (BraceOpenLine[0]->Last->is(Kind: tok::comment))
741 return 0;
742
743 assert(BraceOpenLine[1]);
744 const auto &L1 = *BraceOpenLine[1];
745 if (L1.InPPDirective != (*I)->InPPDirective ||
746 (L1.InPPDirective && L1.First->HasUnescapedNewline)) {
747 return 0;
748 }
749
750 assert(BraceOpenLine[2]);
751 const auto &L2 = *BraceOpenLine[2];
752 if (L2.Type == LT_Invalid)
753 return 0;
754
755 Limit = limitConsideringMacros(I: I + 1, E, Limit);
756
757 const auto LinesToBeMerged = OpenBraceWrapped + 2;
758
759 // Check if it's a namespace inside a namespace, and call recursively if so.
760 // '3' is the sizes of the whitespace and closing brace for " _inner_ }".
761 if (L1.First->is(Kind: tok::kw_namespace)) {
762 if (L1.Last->is(Kind: tok::comment) || !Style.CompactNamespaces)
763 return 0;
764 if (Limit < L1.Last->TotalLength + 3)
765 return 0;
766 const auto InnerLimit = Limit - L1.Last->TotalLength - 3;
767 const auto MergedLines =
768 tryMergeNamespace(I: BraceOpenLine + 1, E, Limit: InnerLimit);
769 if (MergedLines == 0)
770 return 0;
771 const auto N = MergedLines + LinesToBeMerged;
772 // Check if there is even a line after the inner result.
773 if (auto Distance = std::distance(first: I, last: E);
774 static_cast<std::remove_const_t<decltype(N)>>(Distance) <= N) {
775 return 0;
776 }
777 // Check that the line after the inner result starts with a closing brace
778 // which we are permitted to merge into one line.
779 if (I[N]->First->is(TT: TT_NamespaceRBrace) &&
780 !I[N]->First->MustBreakBefore &&
781 BraceOpenLine[MergedLines + 1]->Last->isNot(Kind: tok::comment) &&
782 nextNLinesFitInto(I, E: I + N + 1, Limit)) {
783 return N;
784 }
785 return 0;
786 }
787
788 // There's no inner namespace, so we are considering to merge at most one
789 // line.
790
791 // The line which is in the namespace should end with semicolon.
792 if (L1.Last->isNot(Kind: tok::semi))
793 return 0;
794
795 // Last, check that the third line starts with a closing brace.
796 if (L2.First->isNot(Kind: TT_NamespaceRBrace) || L2.First->MustBreakBefore)
797 return 0;
798
799 if (!nextTwoLinesFitInto(I, Limit))
800 return 0;
801
802 return LinesToBeMerged;
803 }
804
805 unsigned
806 tryMergeSimpleControlStatement(ArrayRef<AnnotatedLine *>::const_iterator I,
807 ArrayRef<AnnotatedLine *>::const_iterator E,
808 unsigned Limit) {
809 if (Limit == 0)
810 return 0;
811 if (Style.BraceWrapping.AfterControlStatement ==
812 FormatStyle::BWACS_Always &&
813 I[1]->First->is(Kind: tok::l_brace) &&
814 Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) {
815 return 0;
816 }
817 if (I[1]->InPPDirective != (*I)->InPPDirective ||
818 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) {
819 return 0;
820 }
821 Limit = limitConsideringMacros(I: I + 1, E, Limit);
822 AnnotatedLine &Line = **I;
823 if (Line.First->isNoneOf(Ks: tok::kw_do, Ks: tok::kw_else) &&
824 Line.Last->isNoneOf(Ks: tok::kw_else, Ks: tok::r_paren)) {
825 return 0;
826 }
827 // Only merge `do while` if `do` is the only statement on the line.
828 if (Line.First->is(Kind: tok::kw_do) && Line.Last->isNot(Kind: tok::kw_do))
829 return 0;
830 if (1 + I[1]->Last->TotalLength > Limit)
831 return 0;
832 // Don't merge with loops, ifs, a single semicolon or a line comment.
833 if (I[1]->First->isOneOf(K1: tok::semi, K2: tok::kw_if, Ks: tok::kw_for, Ks: tok::kw_while,
834 Ks: TT_ForEachMacro, Ks: TT_LineComment)) {
835 return 0;
836 }
837 // Only inline simple if's (no nested if or else), unless specified
838 if (Style.AllowShortIfStatementsOnASingleLine ==
839 FormatStyle::SIS_WithoutElse) {
840 if (I + 2 != E && Line.startsWith(Tokens: tok::kw_if) &&
841 I[2]->First->is(Kind: tok::kw_else)) {
842 return 0;
843 }
844 }
845 return 1;
846 }
847
848 unsigned tryMergeShortCaseLabels(ArrayRef<AnnotatedLine *>::const_iterator I,
849 ArrayRef<AnnotatedLine *>::const_iterator E,
850 unsigned Limit) {
851 if (Limit == 0 || I + 1 == E ||
852 I[1]->First->isOneOf(K1: tok::kw_case, K2: tok::kw_default)) {
853 return 0;
854 }
855 if (I[0]->Last->is(Kind: tok::l_brace) || I[1]->First->is(Kind: tok::l_brace))
856 return 0;
857 unsigned NumStmts = 0;
858 unsigned Length = 0;
859 bool EndsWithComment = false;
860 bool InPPDirective = I[0]->InPPDirective;
861 bool InMacroBody = I[0]->InMacroBody;
862 const unsigned Level = I[0]->Level;
863 for (; NumStmts < 3; ++NumStmts) {
864 if (I + 1 + NumStmts == E)
865 break;
866 const AnnotatedLine *Line = I[1 + NumStmts];
867 if (Line->InPPDirective != InPPDirective)
868 break;
869 if (Line->InMacroBody != InMacroBody)
870 break;
871 if (Line->First->isOneOf(K1: tok::kw_case, K2: tok::kw_default, Ks: tok::r_brace))
872 break;
873 if (Line->First->isOneOf(K1: tok::kw_if, K2: tok::kw_for, Ks: tok::kw_switch,
874 Ks: tok::kw_while) ||
875 EndsWithComment) {
876 return 0;
877 }
878 const auto *J = I + 2 + NumStmts;
879 if (Style.CompactCaseLabels && J != E &&
880 (*J)->First->isOneOf(K1: tok::kw_case, K2: tok::kw_default) &&
881 canJoinWithCaseLabel(Line, LabelTok: *(*J)->First)) {
882 break;
883 }
884
885 if (Line->First->is(Kind: tok::comment)) {
886 if (Level != Line->Level)
887 return 0;
888 for (; J != E; ++J) {
889 Line = *J;
890 if (Line->InPPDirective != InPPDirective)
891 break;
892 if (Line->First->isOneOf(K1: tok::kw_case, K2: tok::kw_default, Ks: tok::r_brace))
893 break;
894 if (Line->First->isNot(Kind: tok::comment) || Level != Line->Level)
895 return 0;
896 }
897 break;
898 }
899 if (Line->Last->is(Kind: tok::comment))
900 EndsWithComment = true;
901 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
902 }
903 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
904 return 0;
905 return NumStmts;
906 }
907
908 unsigned tryMergeSimpleBlock(ArrayRef<AnnotatedLine *>::const_iterator I,
909 ArrayRef<AnnotatedLine *>::const_iterator E,
910 unsigned Limit) {
911 // Don't merge with a preprocessor directive.
912 if (I[1]->Type == LT_PreprocessorDirective)
913 return 0;
914
915 AnnotatedLine &Line = **I;
916
917 // Don't merge ObjC @ keywords and methods.
918 // FIXME: If an option to allow short exception handling clauses on a single
919 // line is added, change this to not return for @try and friends.
920 if (!Style.isJava() && Line.First->isOneOf(K1: tok::at, K2: tok::minus, Ks: tok::plus))
921 return 0;
922
923 // Check that the current line allows merging. This depends on whether we
924 // are in a control flow statements as well as several style flags.
925 if (Line.First->is(Kind: tok::kw_case) ||
926 (Line.First->Next && Line.First->Next->is(Kind: tok::kw_else))) {
927 return 0;
928 }
929 // default: in switch statement
930 if (Line.First->is(Kind: tok::kw_default)) {
931 const FormatToken *Tok = Line.First->getNextNonComment();
932 if (Tok && Tok->is(Kind: tok::colon))
933 return 0;
934 }
935
936 auto IsCtrlStmt = [](const auto &Line) {
937 return Line.First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
938 tok::kw_do, tok::kw_for, TT_ForEachMacro);
939 };
940
941 const bool IsSplitBlock =
942 Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never ||
943 (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Empty &&
944 I[1]->First->isNot(Kind: tok::r_brace));
945
946 if (IsCtrlStmt(Line) ||
947 Line.First->isOneOf(K1: tok::kw_try, K2: tok::kw___try, Ks: tok::kw_catch,
948 Ks: tok::kw___finally, Ks: tok::r_brace,
949 Ks: Keywords.kw___except) ||
950 Line.Last->is(TT: TT_ExportLBrace)) {
951 if (IsSplitBlock)
952 return 0;
953 // Don't merge when we can't except the case when
954 // the control statement block is empty
955 if (!Style.AllowShortIfStatementsOnASingleLine &&
956 Line.First->isOneOf(K1: tok::kw_if, K2: tok::kw_else) &&
957 !Style.BraceWrapping.AfterControlStatement &&
958 I[1]->First->isNot(Kind: tok::r_brace)) {
959 return 0;
960 }
961 if (!Style.AllowShortIfStatementsOnASingleLine &&
962 Line.First->isOneOf(K1: tok::kw_if, K2: tok::kw_else) &&
963 Style.BraceWrapping.AfterControlStatement ==
964 FormatStyle::BWACS_Always &&
965 I + 2 != E && I[2]->First->isNot(Kind: tok::r_brace)) {
966 return 0;
967 }
968 if (!Style.AllowShortLoopsOnASingleLine &&
969 Line.First->isOneOf(K1: tok::kw_while, K2: tok::kw_do, Ks: tok::kw_for,
970 Ks: TT_ForEachMacro) &&
971 !Style.BraceWrapping.AfterControlStatement &&
972 I[1]->First->isNot(Kind: tok::r_brace)) {
973 return 0;
974 }
975 if (!Style.AllowShortLoopsOnASingleLine &&
976 Line.First->isOneOf(K1: tok::kw_while, K2: tok::kw_do, Ks: tok::kw_for,
977 Ks: TT_ForEachMacro) &&
978 Style.BraceWrapping.AfterControlStatement ==
979 FormatStyle::BWACS_Always &&
980 I + 2 != E && I[2]->First->isNot(Kind: tok::r_brace)) {
981 return 0;
982 }
983 // FIXME: Consider an option to allow short exception handling clauses on
984 // a single line.
985 // FIXME: This isn't covered by tests.
986 // FIXME: For catch, __except, __finally the first token on the line
987 // is '}', so this isn't correct here.
988 if (Line.First->isOneOf(K1: tok::kw_try, K2: tok::kw___try, Ks: tok::kw_catch,
989 Ks: Keywords.kw___except, Ks: tok::kw___finally)) {
990 return 0;
991 }
992 }
993
994 if (Line.endsWith(Tokens: tok::l_brace)) {
995 if (Style.BraceWrapping.AfterExportBlock &&
996 Line.First->is(TT: TT_ExportLBrace)) {
997 return 0;
998 }
999
1000 if (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never &&
1001 Line.First->is(TT: TT_BlockLBrace)) {
1002 return 0;
1003 }
1004
1005 if (IsSplitBlock && Line.First == Line.Last &&
1006 I > AnnotatedLines.begin() &&
1007 (I[-1]->endsWith(Tokens: tok::kw_else) || IsCtrlStmt(*I[-1]))) {
1008 return 0;
1009 }
1010 FormatToken *Tok = I[1]->First;
1011 auto ShouldMerge = [Tok]() {
1012 if (Tok->isNot(Kind: tok::r_brace) || Tok->MustBreakBefore)
1013 return false;
1014 const FormatToken *Next = Tok->getNextNonComment();
1015 return !Next || Next->is(Kind: tok::semi);
1016 };
1017
1018 if (ShouldMerge()) {
1019 // We merge empty blocks even if the line exceeds the column limit.
1020 Tok->SpacesRequiredBefore =
1021 Style.SpaceInEmptyBraces != FormatStyle::SIEB_Never ||
1022 Line.Last->is(Kind: tok::comment);
1023 Tok->CanBreakBefore = true;
1024 return 1;
1025 } else if (Limit != 0 && !Line.startsWithNamespace() &&
1026 !startsExternCBlock(Line)) {
1027 // Merge short records only when requested.
1028 if (Line.Last->isOneOf(K1: TT_EnumLBrace, K2: TT_RecordLBrace))
1029 return 0;
1030
1031 if (Line.Last->isOneOf(K1: TT_ClassLBrace, K2: TT_StructLBrace,
1032 Ks: TT_UnionLBrace) &&
1033 Line.Last != Line.First &&
1034 Style.AllowShortRecordOnASingleLine != FormatStyle::SRS_Always) {
1035 return 0;
1036 }
1037
1038 // Check that we still have three lines and they fit into the limit.
1039 if (I + 2 == E || I[2]->Type == LT_Invalid)
1040 return 0;
1041 Limit = limitConsideringMacros(I: I + 2, E, Limit);
1042
1043 if (!nextTwoLinesFitInto(I, Limit))
1044 return 0;
1045
1046 // Second, check that the next line does not contain non-braced-init
1047 // braces - if it does, readability declines when putting it into a
1048 // single line.
1049 if (I[1]->Last->is(TT: TT_LineComment))
1050 return 0;
1051 do {
1052 if (Tok->is(Kind: tok::l_brace) && Tok->isNot(Kind: BK_BracedInit))
1053 return 0;
1054 if (Tok->is(Kind: tok::r_brace) &&
1055 (!Tok->MatchingParen ||
1056 Tok->MatchingParen->isNot(Kind: BK_BracedInit))) {
1057 return 0;
1058 }
1059 Tok = Tok->Next;
1060 } while (Tok);
1061
1062 // Last, check that the third line starts with a closing brace at the
1063 // same level as the opening line.
1064 Tok = I[2]->First;
1065 if (Tok->isNot(Kind: tok::r_brace) || I[2]->Level != Line.Level)
1066 return 0;
1067
1068 // Don't merge "if (a) { .. } else {".
1069 if (Tok->Next && Tok->Next->is(Kind: tok::kw_else))
1070 return 0;
1071
1072 // Don't merge a trailing multi-line control statement block like:
1073 // } else if (foo &&
1074 // bar)
1075 // { <-- current Line
1076 // baz();
1077 // }
1078 if (Line.First == Line.Last &&
1079 Line.First->is(TT: TT_ControlStatementLBrace) &&
1080 Style.BraceWrapping.AfterControlStatement ==
1081 FormatStyle::BWACS_MultiLine) {
1082 return 0;
1083 }
1084
1085 return 2;
1086 }
1087 } else if (I[1]->First->is(Kind: tok::l_brace)) {
1088 if (I[1]->Last->is(TT: TT_LineComment))
1089 return 0;
1090
1091 // Check for Limit <= 2 to account for the " {".
1092 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(Line: *I)))
1093 return 0;
1094 Limit -= 2;
1095 unsigned MergedLines = 0;
1096
1097 auto TryMergeBlock = [&] {
1098 if (Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never ||
1099 Style.AllowShortRecordOnASingleLine == FormatStyle::SRS_Always) {
1100 return true;
1101 }
1102 return I[1]->First == I[1]->Last && I + 2 != E &&
1103 I[2]->First->is(Kind: tok::r_brace);
1104 };
1105
1106 if (TryMergeBlock()) {
1107 MergedLines = tryMergeSimpleBlock(I: I + 1, E, Limit);
1108 // If we managed to merge the block, count the statement header, which
1109 // is on a separate line.
1110 if (MergedLines > 0)
1111 ++MergedLines;
1112 }
1113 return MergedLines;
1114 }
1115 return 0;
1116 }
1117
1118 /// Returns the modified column limit for \p I if it is inside a macro and
1119 /// needs a trailing '\'.
1120 unsigned limitConsideringMacros(ArrayRef<AnnotatedLine *>::const_iterator I,
1121 ArrayRef<AnnotatedLine *>::const_iterator E,
1122 unsigned Limit) {
1123 if (I[0]->InPPDirective && I + 1 != E &&
1124 !I[1]->First->HasUnescapedNewline && I[1]->First->isNot(Kind: tok::eof)) {
1125 return Limit < 2 ? 0 : Limit - 2;
1126 }
1127 return Limit;
1128 }
1129
1130 bool nextTwoLinesFitInto(ArrayRef<AnnotatedLine *>::const_iterator I,
1131 unsigned Limit) {
1132 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
1133 return false;
1134 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
1135 }
1136
1137 bool nextNLinesFitInto(ArrayRef<AnnotatedLine *>::const_iterator I,
1138 ArrayRef<AnnotatedLine *>::const_iterator E,
1139 unsigned Limit) {
1140 unsigned JoinedLength = 0;
1141 for (const auto *J = I + 1; J != E; ++J) {
1142 if ((*J)->First->MustBreakBefore)
1143 return false;
1144
1145 JoinedLength += 1 + (*J)->Last->TotalLength;
1146 if (JoinedLength > Limit)
1147 return false;
1148 }
1149 return true;
1150 }
1151
1152 bool containsMustBreak(const AnnotatedLine *Line) {
1153 assert(Line->First);
1154 // Ignore the first token, because in this situation, it applies more to the
1155 // last token of the previous line.
1156 for (const FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next)
1157 if (Tok->MustBreakBefore)
1158 return true;
1159 return false;
1160 }
1161
1162 bool cannotMergeMacroLine(const AnnotatedLine *Line, bool AllowMultiLine) {
1163 assert(Line->First);
1164 if (Line->Last->MacroParent)
1165 return true;
1166 if (AllowMultiLine)
1167 return false;
1168 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1169 if (Tok->MacroParent && !Tok->Children.empty())
1170 return true;
1171 if (Tok != Line->First && Tok->getDecision() == FD_Break)
1172 return true;
1173 }
1174 return false;
1175 }
1176
1177 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1178 assert(!A.Last->Next);
1179 assert(!B.First->Previous);
1180 if (B.Affected || B.LeadingEmptyLinesAffected) {
1181 assert(B.Affected || A.Last->Children.empty());
1182 A.Affected = true;
1183 }
1184 A.Last->Next = B.First;
1185 B.First->Previous = A.Last;
1186 B.First->CanBreakBefore = true;
1187 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1188 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1189 Tok->TotalLength += LengthA;
1190 A.Last = Tok;
1191 }
1192 }
1193
1194 const FormatStyle &Style;
1195 const AdditionalKeywords &Keywords;
1196 const ArrayRef<AnnotatedLine *>::const_iterator End;
1197
1198 ArrayRef<AnnotatedLine *>::const_iterator Next;
1199 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
1200};
1201
1202static void markFinalized(FormatToken *Tok, bool SkipFirst = false) {
1203 if (Tok->is(Kind: tok::hash) && !Tok->Previous && Tok->Next &&
1204 Tok->Next->isOneOf(K1: tok::pp_if, K2: tok::pp_ifdef, Ks: tok::pp_ifndef,
1205 Ks: tok::pp_elif, Ks: tok::pp_elifdef, Ks: tok::pp_elifndef,
1206 Ks: tok::pp_else, Ks: tok::pp_endif)) {
1207 Tok = Tok->Next;
1208 SkipFirst = false;
1209 }
1210 for (bool First = true; Tok; Tok = Tok->Next, First = false) {
1211 if (Tok->MacroCtx && Tok->MacroCtx->Role == MR_ExpandedArg) {
1212 // In the first pass we format all macro arguments in the expanded token
1213 // stream. Instead of finalizing the macro arguments, we mark that they
1214 // will be modified as unexpanded arguments (as part of the macro call
1215 // formatting) in the next pass.
1216 Tok->MacroCtx->Role = MR_UnexpandedArg;
1217 // Reset whether spaces or a line break are required before this token, as
1218 // that is context dependent, and that context may change when formatting
1219 // the macro call. For example, given M(x) -> 2 * x, and the macro call
1220 // M(var), the token 'var' will have SpacesRequiredBefore = 1 after being
1221 // formatted as part of the expanded macro, but SpacesRequiredBefore = 0
1222 // for its position within the macro call.
1223 Tok->SpacesRequiredBefore = 0;
1224 if (!Tok->MustBreakBeforeFinalized)
1225 Tok->MustBreakBefore = 0;
1226 } else if (!First || !SkipFirst) {
1227 Tok->Finalized = true;
1228 }
1229 }
1230}
1231
1232#ifndef NDEBUG
1233static void printLineState(const LineState &State) {
1234 llvm::dbgs() << "State: ";
1235 for (const ParenState &P : State.Stack) {
1236 llvm::dbgs() << (P.Tok ? P.Tok->TokenText : "F") << "|" << P.Indent.Total
1237 << "|" << P.LastSpace << "|" << P.NestedBlockIndent << " ";
1238 }
1239 llvm::dbgs() << State.NextToken->TokenText << "\n";
1240}
1241#endif
1242
1243/// Base class for classes that format one \c AnnotatedLine.
1244class LineFormatter {
1245public:
1246 LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
1247 const FormatStyle &Style,
1248 UnwrappedLineFormatter *BlockFormatter)
1249 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
1250 BlockFormatter(BlockFormatter) {}
1251 virtual ~LineFormatter() {}
1252
1253 /// Formats an \c AnnotatedLine and returns the penalty.
1254 ///
1255 /// If \p DryRun is \c false, directly applies the changes.
1256 virtual uint64_t formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1257 unsigned FirstStartColumn, bool DryRun) = 0;
1258
1259protected:
1260 /// If the \p State's next token is an r_brace closing a nested block,
1261 /// format the nested block before it.
1262 ///
1263 /// Returns \c true if all children could be placed successfully and adapts
1264 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1265 /// creates changes using \c Whitespaces.
1266 ///
1267 /// The crucial idea here is that children always get formatted upon
1268 /// encountering the closing brace right after the nested block. Now, if we
1269 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1270 /// \c false), the entire block has to be kept on the same line (which is only
1271 /// possible if it fits on the line, only contains a single statement, etc.
1272 ///
1273 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1274 /// break after the "{", format all lines with correct indentation and the put
1275 /// the closing "}" on yet another new line.
1276 ///
1277 /// This enables us to keep the simple structure of the
1278 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1279 /// break or don't break.
1280 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1281 uint64_t &Penalty) {
1282 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1283 bool HasLBrace = LBrace && LBrace->is(Kind: tok::l_brace) && LBrace->is(BBK: BK_Block);
1284 FormatToken &Previous = *State.NextToken->Previous;
1285 if (Previous.Children.empty() || (!HasLBrace && !LBrace->MacroParent)) {
1286 // The previous token does not open a block. Nothing to do. We don't
1287 // assert so that we can simply call this function for all tokens.
1288 return true;
1289 }
1290
1291 if (NewLine || Previous.MacroParent) {
1292 ParenState &P = State.Stack.back();
1293
1294 int AdditionalIndent =
1295 P.Indent.Total - Previous.Children[0]->Level * Style.IndentWidth;
1296 Penalty +=
1297 BlockFormatter->format(Lines: Previous.Children, DryRun, AdditionalIndent,
1298 /*FixBadIndentation=*/true);
1299 if (Previous.MacroParent)
1300 P.NestedBlockIndent = P.Indent.Total;
1301 return true;
1302 }
1303
1304 if (Previous.Children[0]->First->MustBreakBefore)
1305 return false;
1306
1307 // Cannot merge into one line if this line ends on a comment.
1308 if (Previous.is(Kind: tok::comment))
1309 return false;
1310
1311 // Cannot merge multiple statements into a single line.
1312 if (Previous.Children.size() > 1)
1313 return false;
1314
1315 const AnnotatedLine *Child = Previous.Children[0];
1316 // We can't put the closing "}" on a line with a trailing comment.
1317 if (Child->Last->isTrailingComment())
1318 return false;
1319
1320 // If the child line exceeds the column limit, we wouldn't want to merge it.
1321 // We add +2 for the trailing " }".
1322 if (Style.ColumnLimit > 0 &&
1323 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit) {
1324 return false;
1325 }
1326
1327 if (!DryRun) {
1328 Whitespaces->replaceWhitespace(
1329 Tok&: *Child->First, /*Newlines=*/0, /*Spaces=*/1,
1330 /*StartOfTokenColumn=*/State.Column, /*AlignedTo=*/nullptr,
1331 InPPDirective: State.Line->InPPDirective);
1332 }
1333 Penalty +=
1334 formatLine(Line: *Child, FirstIndent: State.Column + 1, /*FirstStartColumn=*/0, DryRun);
1335 if (!DryRun)
1336 markFinalized(Tok: Child->First);
1337
1338 State.Column += 1 + Child->Last->TotalLength;
1339 return true;
1340 }
1341
1342 ContinuationIndenter *Indenter;
1343
1344private:
1345 WhitespaceManager *Whitespaces;
1346 const FormatStyle &Style;
1347 UnwrappedLineFormatter *BlockFormatter;
1348};
1349
1350/// Formatter that keeps the existing line breaks.
1351class NoColumnLimitLineFormatter : public LineFormatter {
1352public:
1353 NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
1354 WhitespaceManager *Whitespaces,
1355 const FormatStyle &Style,
1356 UnwrappedLineFormatter *BlockFormatter)
1357 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1358
1359 /// Formats the line, simply keeping all of the input's line breaking
1360 /// decisions.
1361 uint64_t formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1362 unsigned FirstStartColumn, bool DryRun) override {
1363 assert(!DryRun);
1364 LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
1365 Line: &Line, /*DryRun=*/false);
1366 while (State.NextToken) {
1367 bool Newline =
1368 Indenter->mustBreak(State) ||
1369 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
1370 uint64_t Penalty = 0;
1371 formatChildren(State, NewLine: Newline, /*DryRun=*/false, Penalty);
1372 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
1373 }
1374 return 0;
1375 }
1376};
1377
1378/// Formatter that puts all tokens into a single line without breaks.
1379class NoLineBreakFormatter : public LineFormatter {
1380public:
1381 NoLineBreakFormatter(ContinuationIndenter *Indenter,
1382 WhitespaceManager *Whitespaces, const FormatStyle &Style,
1383 UnwrappedLineFormatter *BlockFormatter)
1384 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1385
1386 /// Puts all tokens into a single line.
1387 uint64_t formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1388 unsigned FirstStartColumn, bool DryRun) override {
1389 uint64_t Penalty = 0;
1390 LineState State =
1391 Indenter->getInitialState(FirstIndent, FirstStartColumn, Line: &Line, DryRun);
1392 while (State.NextToken) {
1393 formatChildren(State, /*NewLine=*/false, DryRun, Penalty);
1394 Indenter->addTokenToState(
1395 State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun);
1396 }
1397 return Penalty;
1398 }
1399};
1400
1401/// Finds the best way to break lines.
1402class OptimizingLineFormatter : public LineFormatter {
1403public:
1404 OptimizingLineFormatter(ContinuationIndenter *Indenter,
1405 WhitespaceManager *Whitespaces,
1406 const FormatStyle &Style,
1407 UnwrappedLineFormatter *BlockFormatter)
1408 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1409
1410 /// Formats the line by finding the best line breaks with line lengths
1411 /// below the column limit.
1412 uint64_t formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1413 unsigned FirstStartColumn, bool DryRun) override {
1414 LineState State =
1415 Indenter->getInitialState(FirstIndent, FirstStartColumn, Line: &Line, DryRun);
1416
1417 // If the ObjC method declaration does not fit on a line, we should format
1418 // it with one arg per line.
1419 if (State.Line->Type == LT_ObjCMethodDecl)
1420 State.Stack.back().BreakBeforeParameter = true;
1421
1422 // Find best solution in solution space.
1423 return analyzeSolutionSpace(InitialState&: State, DryRun);
1424 }
1425
1426private:
1427 struct CompareLineStatePointers {
1428 bool operator()(LineState *obj1, LineState *obj2) const {
1429 return *obj1 < *obj2;
1430 }
1431 };
1432
1433 /// A pair of <penalty, count> that is used to prioritize the BFS on.
1434 ///
1435 /// In case of equal penalties, we want to prefer states that were inserted
1436 /// first. During state generation we make sure that we insert states first
1437 /// that break the line as late as possible.
1438 typedef std::pair<uint64_t, unsigned> OrderedPenalty;
1439
1440 /// An edge in the solution space from \c Previous->State to \c State,
1441 /// inserting a newline dependent on the \c NewLine.
1442 struct StateNode {
1443 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
1444 : State(State), NewLine(NewLine), Previous(Previous) {}
1445 LineState State;
1446 bool NewLine;
1447 StateNode *Previous;
1448 };
1449
1450 /// An item in the prioritized BFS search queue. The \c StateNode's
1451 /// \c State has the given \c OrderedPenalty.
1452 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1453
1454 /// The BFS queue type.
1455 typedef std::priority_queue<QueueItem, SmallVector<QueueItem>,
1456 std::greater<QueueItem>>
1457 QueueType;
1458
1459 /// Analyze the entire solution space starting from \p InitialState.
1460 ///
1461 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1462 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1463 /// find the shortest path (the one with lowest penalty) from \p InitialState
1464 /// to a state where all tokens are placed. Returns the penalty.
1465 ///
1466 /// If \p DryRun is \c false, directly applies the changes.
1467 uint64_t analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
1468 std::set<LineState *, CompareLineStatePointers> Seen;
1469
1470 // Increasing count of \c StateNode items we have created. This is used to
1471 // create a deterministic order independent of the container.
1472 unsigned Count = 0;
1473 QueueType Queue;
1474
1475 // Insert start element into queue.
1476 StateNode *RootNode =
1477 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
1478 Queue.push(x: QueueItem(OrderedPenalty(0, Count), RootNode));
1479 ++Count;
1480
1481 uint64_t Penalty = 0;
1482
1483 // While not empty, take first element and follow edges.
1484 while (!Queue.empty()) {
1485 // Quit if we still haven't found a solution by now.
1486 if (Count > 25'000'000)
1487 return 0;
1488
1489 Penalty = Queue.top().first.first;
1490 StateNode *Node = Queue.top().second;
1491 if (!Node->State.NextToken) {
1492 LLVM_DEBUG(llvm::dbgs()
1493 << "\n---\nPenalty for line: " << Penalty << "\n");
1494 break;
1495 }
1496 Queue.pop();
1497
1498 // Cut off the analysis of certain solutions if the analysis gets too
1499 // complex. See description of IgnoreStackForComparison.
1500 if (Count > 50'000)
1501 Node->State.IgnoreStackForComparison = true;
1502
1503 if (!Seen.insert(x: &Node->State).second) {
1504 // State already examined with lower penalty.
1505 continue;
1506 }
1507
1508 FormatDecision LastFormat = Node->State.NextToken->getDecision();
1509 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
1510 addNextStateToQueue(Penalty, PreviousNode: Node, /*NewLine=*/false, Count: &Count, Queue: &Queue);
1511 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
1512 addNextStateToQueue(Penalty, PreviousNode: Node, /*NewLine=*/true, Count: &Count, Queue: &Queue);
1513 }
1514
1515 if (Queue.empty()) {
1516 // We were unable to find a solution, do nothing.
1517 // FIXME: Add diagnostic?
1518 LLVM_DEBUG(llvm::dbgs() << "Could not find a solution.\n");
1519 return 0;
1520 }
1521
1522 // Reconstruct the solution.
1523 if (!DryRun)
1524 reconstructPath(State&: InitialState, Best: Queue.top().second);
1525
1526 LLVM_DEBUG(llvm::dbgs()
1527 << "Total number of analyzed states: " << Count << "\n");
1528 LLVM_DEBUG(llvm::dbgs() << "---\n");
1529
1530 return Penalty;
1531 }
1532
1533 /// Add the following state to the analysis queue \c Queue.
1534 ///
1535 /// Assume the current state is \p PreviousNode and has been reached with a
1536 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
1537 void addNextStateToQueue(uint64_t Penalty, StateNode *PreviousNode,
1538 bool NewLine, unsigned *Count, QueueType *Queue) {
1539 if (NewLine && !Indenter->canBreak(State: PreviousNode->State))
1540 return;
1541 if (!NewLine && Indenter->mustBreak(State: PreviousNode->State))
1542 return;
1543
1544 StateNode *Node = new (Allocator.Allocate())
1545 StateNode(PreviousNode->State, NewLine, PreviousNode);
1546 if (!formatChildren(State&: Node->State, NewLine, /*DryRun=*/true, Penalty))
1547 return;
1548
1549 Penalty += Indenter->addTokenToState(State&: Node->State, Newline: NewLine, DryRun: true);
1550
1551 Queue->push(x: QueueItem(OrderedPenalty(Penalty, *Count), Node));
1552 ++(*Count);
1553 }
1554
1555 /// Applies the best formatting by reconstructing the path in the
1556 /// solution space that leads to \c Best.
1557 void reconstructPath(LineState &State, StateNode *Best) {
1558 llvm::SmallVector<StateNode *> Path;
1559 // We do not need a break before the initial token.
1560 while (Best->Previous) {
1561 Path.push_back(Elt: Best);
1562 Best = Best->Previous;
1563 }
1564 for (const auto &Node : llvm::reverse(C&: Path)) {
1565 uint64_t Penalty = 0;
1566 formatChildren(State, NewLine: Node->NewLine, /*DryRun=*/false, Penalty);
1567 Penalty += Indenter->addTokenToState(State, Newline: Node->NewLine, DryRun: false);
1568
1569 LLVM_DEBUG({
1570 printLineState(Node->Previous->State);
1571 if (Node->NewLine) {
1572 llvm::dbgs() << "Penalty for placing "
1573 << Node->Previous->State.NextToken->Tok.getName()
1574 << " on a new line: " << Penalty << "\n";
1575 }
1576 });
1577 }
1578 }
1579
1580 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1581};
1582
1583} // anonymous namespace
1584
1585uint64_t UnwrappedLineFormatter::format(
1586 const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
1587 int AdditionalIndent, bool FixBadIndentation, unsigned FirstStartColumn,
1588 unsigned NextStartColumn, unsigned LastStartColumn) {
1589 LineJoiner Joiner(Style, Keywords, Lines);
1590
1591 // Try to look up already computed penalty in DryRun-mode.
1592 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
1593 &Lines, AdditionalIndent);
1594 auto CacheIt = PenaltyCache.find(x: CacheKey);
1595 if (DryRun && CacheIt != PenaltyCache.end())
1596 return CacheIt->second;
1597
1598 assert(!Lines.empty());
1599 uint64_t Penalty = 0;
1600 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
1601 AdditionalIndent);
1602 const AnnotatedLine *PrevPrevLine = nullptr;
1603 const AnnotatedLine *PreviousLine = nullptr;
1604 const AnnotatedLine *NextLine = nullptr;
1605
1606 // The minimum level of consecutive lines that have been formatted.
1607 unsigned RangeMinLevel = UINT_MAX;
1608
1609 bool FirstLine = true;
1610 for (const AnnotatedLine *Line =
1611 Joiner.getNextMergedLine(DryRun, IndentTracker);
1612 Line; PrevPrevLine = PreviousLine, PreviousLine = Line, Line = NextLine,
1613 FirstLine = false) {
1614 assert(Line->First);
1615 const AnnotatedLine &TheLine = *Line;
1616 unsigned Indent = IndentTracker.getIndent();
1617
1618 // We continue formatting unchanged lines to adjust their indent, e.g. if a
1619 // scope was added. However, we need to carefully stop doing this when we
1620 // exit the scope of affected lines to prevent indenting the entire
1621 // remaining file if it currently missing a closing brace.
1622 bool PreviousRBrace =
1623 PreviousLine && PreviousLine->startsWith(Tokens: tok::r_brace);
1624 bool ContinueFormatting =
1625 TheLine.Level > RangeMinLevel ||
1626 (TheLine.Level == RangeMinLevel && !PreviousRBrace &&
1627 !TheLine.startsWith(Tokens: TT_NamespaceRBrace));
1628
1629 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
1630 Indent != TheLine.First->OriginalColumn;
1631 bool ShouldFormat = TheLine.Affected || FixIndentation;
1632 // We cannot format this line; if the reason is that the line had a
1633 // parsing error, remember that.
1634 if (ShouldFormat && TheLine.Type == LT_Invalid && Status) {
1635 Status->FormatComplete = false;
1636 Status->Line =
1637 SourceMgr.getSpellingLineNumber(Loc: TheLine.First->Tok.getLocation());
1638 }
1639
1640 if (ShouldFormat && TheLine.Type != LT_Invalid) {
1641 if (!DryRun) {
1642 bool LastLine = TheLine.First->is(Kind: tok::eof);
1643 formatFirstToken(Line: TheLine, PreviousLine, PrevPrevLine, Indent,
1644 NewlineIndent: LastLine ? LastStartColumn : NextStartColumn + Indent);
1645 }
1646
1647 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1648 unsigned ColumnLimit = getColumnLimit(InPPDirective: TheLine.InPPDirective, NextLine);
1649 bool FitsIntoOneLine =
1650 !TheLine.ContainsMacroCall &&
1651 (TheLine.Last->TotalLength + Indent <= ColumnLimit ||
1652 (TheLine.Type == LT_ImportStatement &&
1653 (!Style.isJavaScript() || !Style.JavaScriptWrapImports)) ||
1654 (Style.isCSharp() &&
1655 TheLine.InPPDirective)); // don't split #regions in C#
1656 if (Style.ColumnLimit == 0) {
1657 NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
1658 .formatLine(Line: TheLine, FirstIndent: NextStartColumn + Indent,
1659 FirstStartColumn: FirstLine ? FirstStartColumn : 0, DryRun);
1660 } else if (FitsIntoOneLine) {
1661 Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
1662 .formatLine(Line: TheLine, FirstIndent: NextStartColumn + Indent,
1663 FirstStartColumn: FirstLine ? FirstStartColumn : 0, DryRun);
1664 } else {
1665 Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
1666 .formatLine(Line: TheLine, FirstIndent: NextStartColumn + Indent,
1667 FirstStartColumn: FirstLine ? FirstStartColumn : 0, DryRun);
1668 }
1669 RangeMinLevel = std::min(a: RangeMinLevel, b: TheLine.Level);
1670 } else {
1671 // If no token in the current line is affected, we still need to format
1672 // affected children.
1673 if (TheLine.ChildrenAffected) {
1674 for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next)
1675 if (!Tok->Children.empty())
1676 format(Lines: Tok->Children, DryRun);
1677 }
1678
1679 // Adapt following lines on the current indent level to the same level
1680 // unless the current \c AnnotatedLine is not at the beginning of a line.
1681 bool StartsNewLine =
1682 TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
1683 if (StartsNewLine)
1684 IndentTracker.adjustToUnmodifiedLine(Line: TheLine);
1685 if (!DryRun) {
1686 bool ReformatLeadingWhitespace =
1687 StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
1688 TheLine.LeadingEmptyLinesAffected);
1689 // Format the first token.
1690 if (ReformatLeadingWhitespace) {
1691 formatFirstToken(Line: TheLine, PreviousLine, PrevPrevLine,
1692 Indent: TheLine.First->OriginalColumn,
1693 NewlineIndent: TheLine.First->OriginalColumn);
1694 } else {
1695 Whitespaces->addUntouchableToken(Tok: *TheLine.First,
1696 InPPDirective: TheLine.InPPDirective);
1697 }
1698
1699 // Notify the WhitespaceManager about the unchanged whitespace.
1700 for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
1701 Whitespaces->addUntouchableToken(Tok: *Tok, InPPDirective: TheLine.InPPDirective);
1702 }
1703 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1704 RangeMinLevel = UINT_MAX;
1705 }
1706 if (!DryRun)
1707 markFinalized(Tok: TheLine.First, /*SkipFirst=*/TheLine.InMacroExpansion);
1708 }
1709 PenaltyCache[CacheKey] = Penalty;
1710 return Penalty;
1711}
1712
1713static auto computeNewlines(const AnnotatedLine &Line,
1714 const AnnotatedLine *PreviousLine,
1715 const AnnotatedLine *PrevPrevLine,
1716 const FormatStyle &Style) {
1717 const auto &RootToken = *Line.First;
1718 if (isClangFormatOn(Comment: RootToken.TokenText))
1719 return RootToken.NewlinesBefore;
1720 auto Newlines =
1721 std::min(a: RootToken.NewlinesBefore, b: Style.MaxEmptyLinesToKeep + 1);
1722 // Remove empty lines before "}" where applicable.
1723 if (RootToken.is(Kind: tok::r_brace) &&
1724 (!RootToken.Next ||
1725 (RootToken.Next->is(Kind: tok::semi) && !RootToken.Next->Next)) &&
1726 // Do not remove empty lines before namespace closing "}".
1727 (Line.InPPDirective || !Line.startsWith(Tokens: TT_NamespaceRBrace)) &&
1728 !Style.KeepEmptyLines.AtEndOfBlock) {
1729 Newlines = std::min(a: Newlines, b: 1u);
1730 }
1731 // Remove empty lines at the start of nested blocks (lambdas/arrow functions)
1732 if (!PreviousLine && Line.Level > 0)
1733 Newlines = std::min(a: Newlines, b: 1u);
1734 if (Newlines == 0 && !RootToken.IsFirst)
1735 Newlines = 1;
1736 if (RootToken.IsFirst &&
1737 (!Style.KeepEmptyLines.AtStartOfFile || !RootToken.HasUnescapedNewline)) {
1738 Newlines = 0;
1739 }
1740
1741 // Remove empty lines after "{".
1742 if (!Style.KeepEmptyLines.AtStartOfBlock && PreviousLine &&
1743 PreviousLine->Last->is(Kind: tok::l_brace) &&
1744 !PreviousLine->startsWithNamespace() &&
1745 !(PrevPrevLine && PrevPrevLine->startsWithNamespace() &&
1746 PreviousLine->startsWith(Tokens: tok::l_brace)) &&
1747 !startsExternCBlock(Line: *PreviousLine)) {
1748 Newlines = 1;
1749 }
1750
1751 if (Style.WrapNamespaceBodyWithEmptyLines != FormatStyle::WNBWELS_Leave) {
1752 // Modify empty lines after TT_NamespaceLBrace.
1753 if (PreviousLine && PreviousLine->endsWith(Tokens: TT_NamespaceLBrace)) {
1754 if (Style.WrapNamespaceBodyWithEmptyLines == FormatStyle::WNBWELS_Never)
1755 Newlines = 1;
1756 else if (!Line.startsWithNamespace())
1757 Newlines = std::max(a: Newlines, b: 2u);
1758 }
1759 // Modify empty lines before TT_NamespaceRBrace.
1760 if (Line.startsWith(Tokens: TT_NamespaceRBrace)) {
1761 if (Style.WrapNamespaceBodyWithEmptyLines == FormatStyle::WNBWELS_Never)
1762 Newlines = 1;
1763 else if (!PreviousLine->startsWith(Tokens: TT_NamespaceRBrace))
1764 Newlines = std::max(a: Newlines, b: 2u);
1765 }
1766 }
1767
1768 // Insert or remove empty line before access specifiers.
1769 if (PreviousLine && RootToken.isAccessSpecifier()) {
1770 switch (Style.EmptyLineBeforeAccessModifier) {
1771 case FormatStyle::ELBAMS_Never:
1772 if (Newlines > 1)
1773 Newlines = 1;
1774 break;
1775 case FormatStyle::ELBAMS_Leave:
1776 Newlines = std::max(a: RootToken.NewlinesBefore, b: 1u);
1777 break;
1778 case FormatStyle::ELBAMS_LogicalBlock:
1779 if (PreviousLine->Last->isOneOf(K1: tok::semi, K2: tok::r_brace) && Newlines <= 1)
1780 Newlines = 2;
1781 if (PreviousLine->First->isAccessSpecifier())
1782 Newlines = 1; // Previous is an access modifier remove all new lines.
1783 break;
1784 case FormatStyle::ELBAMS_Always: {
1785 const FormatToken *previousToken;
1786 if (PreviousLine->Last->is(Kind: tok::comment))
1787 previousToken = PreviousLine->Last->getPreviousNonComment();
1788 else
1789 previousToken = PreviousLine->Last;
1790 if ((!previousToken || previousToken->isNot(Kind: tok::l_brace)) &&
1791 Newlines <= 1) {
1792 Newlines = 2;
1793 }
1794 } break;
1795 }
1796 }
1797
1798 // Insert or remove empty line after access specifiers.
1799 if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
1800 (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline)) {
1801 // EmptyLineBeforeAccessModifier is handling the case when two access
1802 // modifiers follow each other.
1803 if (!RootToken.isAccessSpecifier()) {
1804 switch (Style.EmptyLineAfterAccessModifier) {
1805 case FormatStyle::ELAAMS_Never:
1806 Newlines = 1;
1807 break;
1808 case FormatStyle::ELAAMS_Leave:
1809 Newlines = std::max(a: Newlines, b: 1u);
1810 break;
1811 case FormatStyle::ELAAMS_Always:
1812 if (RootToken.is(Kind: tok::r_brace)) // Do not add at end of class.
1813 Newlines = 1u;
1814 else
1815 Newlines = std::max(a: Newlines, b: 2u);
1816 break;
1817 }
1818 }
1819 }
1820
1821 return Newlines;
1822}
1823
1824void UnwrappedLineFormatter::formatFirstToken(const AnnotatedLine &Line,
1825 const AnnotatedLine *PreviousLine,
1826 const AnnotatedLine *PrevPrevLine,
1827 unsigned Indent,
1828 unsigned NewlineIndent) {
1829 FormatToken &RootToken = *Line.First;
1830 if (RootToken.is(Kind: tok::eof)) {
1831 unsigned Newlines = std::min(
1832 a: RootToken.NewlinesBefore,
1833 b: Style.KeepEmptyLines.AtEndOfFile ? Style.MaxEmptyLinesToKeep + 1 : 1);
1834 unsigned TokenIndent = Newlines ? NewlineIndent : 0;
1835 Whitespaces->replaceWhitespace(
1836 Tok&: RootToken, Newlines, Spaces: TokenIndent, StartOfTokenColumn: TokenIndent, /*AlignedTo=*/nullptr,
1837 /*InPPDirective=*/false,
1838 /*IndentedFromColumn=*/0,
1839 /*CreateReplacement=*/!Line.InMacroExpansion);
1840 return;
1841 }
1842
1843 if (RootToken.Newlines < 0) {
1844 RootToken.Newlines =
1845 computeNewlines(Line, PreviousLine, PrevPrevLine, Style);
1846 assert(RootToken.Newlines >= 0);
1847 }
1848
1849 if (RootToken.Newlines > 0)
1850 Indent = NewlineIndent;
1851
1852 // Preprocessor directives get indented before the hash only if specified. In
1853 // Javascript import statements are indented like normal statements.
1854 if (!Style.isJavaScript() &&
1855 Style.IndentPPDirectives < FormatStyle::PPDIS_BeforeHash &&
1856 (Line.Type == LT_PreprocessorDirective ||
1857 Line.Type == LT_ImportStatement)) {
1858 Indent = 0;
1859 }
1860
1861 Whitespaces->replaceWhitespace(
1862 Tok&: RootToken, Newlines: RootToken.Newlines, Spaces: Indent, StartOfTokenColumn: Indent, /*AlignedTo=*/nullptr,
1863 InPPDirective: Line.InPPDirective && !RootToken.HasUnescapedNewline,
1864 /*IndentedFromColumn=*/0, /*CreateReplacement=*/!Line.InMacroExpansion);
1865}
1866
1867unsigned
1868UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
1869 const AnnotatedLine *NextLine) const {
1870 // In preprocessor directives reserve two chars for trailing " \" if the
1871 // next line continues the preprocessor directive.
1872 bool ContinuesPPDirective =
1873 InPPDirective &&
1874 // If there is no next line, this is likely a child line and the parent
1875 // continues the preprocessor directive.
1876 (!NextLine ||
1877 (NextLine->InPPDirective &&
1878 // If there is an unescaped newline between this line and the next, the
1879 // next line starts a new preprocessor directive.
1880 !NextLine->First->HasUnescapedNewline));
1881 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
1882}
1883
1884} // namespace format
1885} // namespace clang
1886