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