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 (TheLine->Last->is(TT: TT_RecordLBrace) && Style.isJava())) {
524 return tryMergeRecord(I, E, Limit);
525 } else if (TheLine->InPPDirective ||
526 TheLine->First->isNoneOf(Ks: tok::kw_class, Ks: tok::kw_enum,
527 Ks: tok::kw_struct, Ks: tok::kw_union)) {
528 // Try to merge a block with left brace unwrapped that wasn't yet
529 // covered.
530 ShouldMerge = !Style.BraceWrapping.AfterFunction ||
531 (NextLine.First->is(Kind: tok::r_brace) &&
532 !Style.BraceWrapping.SplitEmptyFunction);
533 }
534 return ShouldMerge ? tryMergeSimpleBlock(I, E, Limit) : 0;
535 }
536
537 // Try to merge a function block with left brace wrapped.
538 if (NextLine.First->is(TT: TT_FunctionLBrace) &&
539 Style.BraceWrapping.AfterFunction) {
540 if (NextLine.Last->is(TT: TT_LineComment))
541 return 0;
542
543 // Check for Limit <= 2 to account for the " {".
544 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(Line: TheLine)))
545 return 0;
546 Limit -= 2;
547
548 unsigned MergedLines = 0;
549 if (MergeShortFunctions ||
550 (Style.AllowShortFunctionsOnASingleLine.Empty &&
551 NextLine.First == NextLine.Last && I + 2 != E &&
552 I[2]->First->is(Kind: tok::r_brace))) {
553 MergedLines = tryMergeSimpleBlock(I: I + 1, E, Limit);
554 // If we managed to merge the block, count the function header, which is
555 // on a separate line.
556 if (MergedLines > 0)
557 ++MergedLines;
558 }
559 return MergedLines;
560 }
561 auto IsElseLine = [&TheLine]() -> bool {
562 const FormatToken *First = TheLine->First;
563 if (First->is(Kind: tok::kw_else))
564 return true;
565
566 return First->is(Kind: tok::r_brace) && First->Next &&
567 First->Next->is(Kind: tok::kw_else);
568 };
569 if (TheLine->First->is(Kind: tok::kw_if) ||
570 (IsElseLine() && (Style.AllowShortIfStatementsOnASingleLine ==
571 FormatStyle::SIS_AllIfsAndElse))) {
572 return Style.AllowShortIfStatementsOnASingleLine
573 ? tryMergeSimpleControlStatement(I, E, Limit)
574 : 0;
575 }
576 if (TheLine->First->isOneOf(K1: tok::kw_for, K2: tok::kw_while, Ks: tok::kw_do,
577 Ks: TT_ForEachMacro)) {
578 return Style.AllowShortLoopsOnASingleLine
579 ? tryMergeSimpleControlStatement(I, E, Limit)
580 : 0;
581 }
582 if (TheLine->First->isOneOf(K1: tok::kw_case, K2: tok::kw_default)) {
583 return Style.AllowShortCaseLabelsOnASingleLine
584 ? tryMergeShortCaseLabels(I, E, Limit)
585 : 0;
586 }
587 if (TheLine->InPPDirective &&
588 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
589 return tryMergeSimplePPDirective(I, E, Limit);
590 }
591 return 0;
592 }
593
594 unsigned tryMergeRecord(ArrayRef<AnnotatedLine *>::const_iterator I,
595 ArrayRef<AnnotatedLine *>::const_iterator E,
596 unsigned Limit) {
597 const auto *Line = I[0];
598 const auto *NextLine = I[1];
599
600 // Current line begins both record and block, brace was not wrapped.
601 if (Line->Last->isOneOf(K1: TT_ClassLBrace, K2: TT_StructLBrace, Ks: TT_UnionLBrace)) {
602 auto ShouldWrapLBrace = [&](TokenType LBraceType) {
603 switch (LBraceType) {
604 case TT_ClassLBrace:
605 return Style.BraceWrapping.AfterClass;
606 case TT_StructLBrace:
607 return Style.BraceWrapping.AfterStruct;
608 case TT_UnionLBrace:
609 return Style.BraceWrapping.AfterUnion;
610 default:
611 return false;
612 }
613 };
614
615 auto TryMergeShortRecord = [&] {
616 switch (Style.AllowShortRecordOnASingleLine) {
617 case FormatStyle::SRS_Never:
618 return false;
619 case FormatStyle::SRS_Always:
620 return true;
621 default:
622 return NextLine->First->is(Kind: tok::r_brace);
623 }
624 };
625
626 if (Style.AllowShortRecordOnASingleLine != FormatStyle::SRS_Never &&
627 (!ShouldWrapLBrace(Line->Last->getType()) ||
628 (!Style.BraceWrapping.SplitEmptyRecord && TryMergeShortRecord()))) {
629 return tryMergeSimpleBlock(I, E, Limit);
630 }
631 }
632
633 // Cases where the l_brace was wrapped.
634 // Current line begins record, next line block.
635 if (NextLine->First->isOneOf(K1: TT_ClassLBrace, K2: TT_StructLBrace,
636 Ks: TT_UnionLBrace)) {
637 if (I + 2 == E || I[2]->First->is(Kind: tok::r_brace) ||
638 Style.AllowShortRecordOnASingleLine != FormatStyle::SRS_Always) {
639 return 0;
640 }
641
642 return tryMergeSimpleBlock(I, E, Limit);
643 }
644
645 // Previous line begins record, current line block.
646 if (I != AnnotatedLines.begin() &&
647 I[-1]->First->isOneOf(K1: tok::kw_class, K2: tok::kw_struct, Ks: tok::kw_union)) {
648 const bool IsEmptyBlock =
649 Line->Last->is(Kind: tok::l_brace) && NextLine->First->is(Kind: tok::r_brace);
650
651 if ((IsEmptyBlock && !Style.BraceWrapping.SplitEmptyRecord) ||
652 (!IsEmptyBlock &&
653 Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Always)) {
654 return tryMergeSimpleBlock(I, E, Limit);
655 }
656 }
657
658 return 0;
659 }
660
661 unsigned
662 tryMergeSimplePPDirective(ArrayRef<AnnotatedLine *>::const_iterator I,
663 ArrayRef<AnnotatedLine *>::const_iterator E,
664 unsigned Limit) {
665 if (Limit == 0)
666 return 0;
667 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
668 return 0;
669 if (1 + I[1]->Last->TotalLength > Limit)
670 return 0;
671 return 1;
672 }
673
674 unsigned tryMergeNamespace(ArrayRef<AnnotatedLine *>::const_iterator I,
675 ArrayRef<AnnotatedLine *>::const_iterator E,
676 unsigned Limit) {
677 if (Limit == 0)
678 return 0;
679
680 // The merging code is relative to the opening namespace brace, which could
681 // be either on the first or second line due to the brace wrapping rules.
682 const bool OpenBraceWrapped = Style.BraceWrapping.AfterNamespace;
683 const auto *BraceOpenLine = I + OpenBraceWrapped;
684
685 assert(*BraceOpenLine);
686 if (BraceOpenLine[0]->Last->isNot(Kind: TT_NamespaceLBrace))
687 return 0;
688
689 if (std::distance(first: BraceOpenLine, last: E) <= 2)
690 return 0;
691
692 if (BraceOpenLine[0]->Last->is(Kind: tok::comment))
693 return 0;
694
695 assert(BraceOpenLine[1]);
696 const auto &L1 = *BraceOpenLine[1];
697 if (L1.InPPDirective != (*I)->InPPDirective ||
698 (L1.InPPDirective && L1.First->HasUnescapedNewline)) {
699 return 0;
700 }
701
702 assert(BraceOpenLine[2]);
703 const auto &L2 = *BraceOpenLine[2];
704 if (L2.Type == LT_Invalid)
705 return 0;
706
707 Limit = limitConsideringMacros(I: I + 1, E, Limit);
708
709 const auto LinesToBeMerged = OpenBraceWrapped + 2;
710
711 // Check if it's a namespace inside a namespace, and call recursively if so.
712 // '3' is the sizes of the whitespace and closing brace for " _inner_ }".
713 if (L1.First->is(Kind: tok::kw_namespace)) {
714 if (L1.Last->is(Kind: tok::comment) || !Style.CompactNamespaces)
715 return 0;
716 if (Limit < L1.Last->TotalLength + 3)
717 return 0;
718 const auto InnerLimit = Limit - L1.Last->TotalLength - 3;
719 const auto MergedLines =
720 tryMergeNamespace(I: BraceOpenLine + 1, E, Limit: InnerLimit);
721 if (MergedLines == 0)
722 return 0;
723 const auto N = MergedLines + LinesToBeMerged;
724 // Check if there is even a line after the inner result.
725 if (auto Distance = std::distance(first: I, last: E);
726 static_cast<std::remove_const_t<decltype(N)>>(Distance) <= N) {
727 return 0;
728 }
729 // Check that the line after the inner result starts with a closing brace
730 // which we are permitted to merge into one line.
731 if (I[N]->First->is(TT: TT_NamespaceRBrace) &&
732 !I[N]->First->MustBreakBefore &&
733 BraceOpenLine[MergedLines + 1]->Last->isNot(Kind: tok::comment) &&
734 nextNLinesFitInto(I, E: I + N + 1, Limit)) {
735 return N;
736 }
737 return 0;
738 }
739
740 // There's no inner namespace, so we are considering to merge at most one
741 // line.
742
743 // The line which is in the namespace should end with semicolon.
744 if (L1.Last->isNot(Kind: tok::semi))
745 return 0;
746
747 // Last, check that the third line starts with a closing brace.
748 if (L2.First->isNot(Kind: TT_NamespaceRBrace) || L2.First->MustBreakBefore)
749 return 0;
750
751 if (!nextTwoLinesFitInto(I, Limit))
752 return 0;
753
754 return LinesToBeMerged;
755 }
756
757 unsigned
758 tryMergeSimpleControlStatement(ArrayRef<AnnotatedLine *>::const_iterator I,
759 ArrayRef<AnnotatedLine *>::const_iterator E,
760 unsigned Limit) {
761 if (Limit == 0)
762 return 0;
763 if (Style.BraceWrapping.AfterControlStatement ==
764 FormatStyle::BWACS_Always &&
765 I[1]->First->is(Kind: tok::l_brace) &&
766 Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) {
767 return 0;
768 }
769 if (I[1]->InPPDirective != (*I)->InPPDirective ||
770 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) {
771 return 0;
772 }
773 Limit = limitConsideringMacros(I: I + 1, E, Limit);
774 AnnotatedLine &Line = **I;
775 if (Line.First->isNoneOf(Ks: tok::kw_do, Ks: tok::kw_else) &&
776 Line.Last->isNoneOf(Ks: tok::kw_else, Ks: tok::r_paren)) {
777 return 0;
778 }
779 // Only merge `do while` if `do` is the only statement on the line.
780 if (Line.First->is(Kind: tok::kw_do) && Line.Last->isNot(Kind: tok::kw_do))
781 return 0;
782 if (1 + I[1]->Last->TotalLength > Limit)
783 return 0;
784 // Don't merge with loops, ifs, a single semicolon or a line comment.
785 if (I[1]->First->isOneOf(K1: tok::semi, K2: tok::kw_if, Ks: tok::kw_for, Ks: tok::kw_while,
786 Ks: TT_ForEachMacro, Ks: TT_LineComment)) {
787 return 0;
788 }
789 // Only inline simple if's (no nested if or else), unless specified
790 if (Style.AllowShortIfStatementsOnASingleLine ==
791 FormatStyle::SIS_WithoutElse) {
792 if (I + 2 != E && Line.startsWith(Tokens: tok::kw_if) &&
793 I[2]->First->is(Kind: tok::kw_else)) {
794 return 0;
795 }
796 }
797 return 1;
798 }
799
800 unsigned tryMergeShortCaseLabels(ArrayRef<AnnotatedLine *>::const_iterator I,
801 ArrayRef<AnnotatedLine *>::const_iterator E,
802 unsigned Limit) {
803 if (Limit == 0 || I + 1 == E ||
804 I[1]->First->isOneOf(K1: tok::kw_case, K2: tok::kw_default)) {
805 return 0;
806 }
807 if (I[0]->Last->is(Kind: tok::l_brace) || I[1]->First->is(Kind: tok::l_brace))
808 return 0;
809 unsigned NumStmts = 0;
810 unsigned Length = 0;
811 bool EndsWithComment = false;
812 bool InPPDirective = I[0]->InPPDirective;
813 bool InMacroBody = I[0]->InMacroBody;
814 const unsigned Level = I[0]->Level;
815 for (; NumStmts < 3; ++NumStmts) {
816 if (I + 1 + NumStmts == E)
817 break;
818 const AnnotatedLine *Line = I[1 + NumStmts];
819 if (Line->InPPDirective != InPPDirective)
820 break;
821 if (Line->InMacroBody != InMacroBody)
822 break;
823 if (Line->First->isOneOf(K1: tok::kw_case, K2: tok::kw_default, Ks: tok::r_brace))
824 break;
825 if (Line->First->isOneOf(K1: tok::kw_if, K2: tok::kw_for, Ks: tok::kw_switch,
826 Ks: tok::kw_while) ||
827 EndsWithComment) {
828 return 0;
829 }
830 if (Line->First->is(Kind: tok::comment)) {
831 if (Level != Line->Level)
832 return 0;
833 const auto *J = I + 2 + NumStmts;
834 for (; J != E; ++J) {
835 Line = *J;
836 if (Line->InPPDirective != InPPDirective)
837 break;
838 if (Line->First->isOneOf(K1: tok::kw_case, K2: tok::kw_default, Ks: tok::r_brace))
839 break;
840 if (Line->First->isNot(Kind: tok::comment) || Level != Line->Level)
841 return 0;
842 }
843 break;
844 }
845 if (Line->Last->is(Kind: tok::comment))
846 EndsWithComment = true;
847 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
848 }
849 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
850 return 0;
851 return NumStmts;
852 }
853
854 unsigned tryMergeSimpleBlock(ArrayRef<AnnotatedLine *>::const_iterator I,
855 ArrayRef<AnnotatedLine *>::const_iterator E,
856 unsigned Limit) {
857 // Don't merge with a preprocessor directive.
858 if (I[1]->Type == LT_PreprocessorDirective)
859 return 0;
860
861 AnnotatedLine &Line = **I;
862
863 // Don't merge ObjC @ keywords and methods.
864 // FIXME: If an option to allow short exception handling clauses on a single
865 // line is added, change this to not return for @try and friends.
866 if (!Style.isJava() && Line.First->isOneOf(K1: tok::at, K2: tok::minus, Ks: tok::plus))
867 return 0;
868
869 // Check that the current line allows merging. This depends on whether we
870 // are in a control flow statements as well as several style flags.
871 if (Line.First->is(Kind: tok::kw_case) ||
872 (Line.First->Next && Line.First->Next->is(Kind: tok::kw_else))) {
873 return 0;
874 }
875 // default: in switch statement
876 if (Line.First->is(Kind: tok::kw_default)) {
877 const FormatToken *Tok = Line.First->getNextNonComment();
878 if (Tok && Tok->is(Kind: tok::colon))
879 return 0;
880 }
881
882 auto IsCtrlStmt = [](const auto &Line) {
883 return Line.First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
884 tok::kw_do, tok::kw_for, TT_ForEachMacro);
885 };
886
887 const bool IsSplitBlock =
888 Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never ||
889 (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Empty &&
890 I[1]->First->isNot(Kind: tok::r_brace));
891
892 if (IsCtrlStmt(Line) ||
893 Line.First->isOneOf(K1: tok::kw_try, K2: tok::kw___try, Ks: tok::kw_catch,
894 Ks: tok::kw___finally, Ks: tok::r_brace,
895 Ks: Keywords.kw___except) ||
896 Line.Last->is(TT: TT_ExportLBrace)) {
897 if (IsSplitBlock)
898 return 0;
899 // Don't merge when we can't except the case when
900 // the control statement block is empty
901 if (!Style.AllowShortIfStatementsOnASingleLine &&
902 Line.First->isOneOf(K1: tok::kw_if, K2: tok::kw_else) &&
903 !Style.BraceWrapping.AfterControlStatement &&
904 I[1]->First->isNot(Kind: tok::r_brace)) {
905 return 0;
906 }
907 if (!Style.AllowShortIfStatementsOnASingleLine &&
908 Line.First->isOneOf(K1: tok::kw_if, K2: tok::kw_else) &&
909 Style.BraceWrapping.AfterControlStatement ==
910 FormatStyle::BWACS_Always &&
911 I + 2 != E && I[2]->First->isNot(Kind: tok::r_brace)) {
912 return 0;
913 }
914 if (!Style.AllowShortLoopsOnASingleLine &&
915 Line.First->isOneOf(K1: tok::kw_while, K2: tok::kw_do, Ks: tok::kw_for,
916 Ks: TT_ForEachMacro) &&
917 !Style.BraceWrapping.AfterControlStatement &&
918 I[1]->First->isNot(Kind: tok::r_brace)) {
919 return 0;
920 }
921 if (!Style.AllowShortLoopsOnASingleLine &&
922 Line.First->isOneOf(K1: tok::kw_while, K2: tok::kw_do, Ks: tok::kw_for,
923 Ks: TT_ForEachMacro) &&
924 Style.BraceWrapping.AfterControlStatement ==
925 FormatStyle::BWACS_Always &&
926 I + 2 != E && I[2]->First->isNot(Kind: tok::r_brace)) {
927 return 0;
928 }
929 // FIXME: Consider an option to allow short exception handling clauses on
930 // a single line.
931 // FIXME: This isn't covered by tests.
932 // FIXME: For catch, __except, __finally the first token on the line
933 // is '}', so this isn't correct here.
934 if (Line.First->isOneOf(K1: tok::kw_try, K2: tok::kw___try, Ks: tok::kw_catch,
935 Ks: Keywords.kw___except, Ks: tok::kw___finally)) {
936 return 0;
937 }
938 }
939
940 if (Line.endsWith(Tokens: tok::l_brace)) {
941 if (Style.BraceWrapping.AfterExportBlock &&
942 Line.First->is(TT: TT_ExportLBrace)) {
943 return 0;
944 }
945
946 if (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never &&
947 Line.First->is(TT: TT_BlockLBrace)) {
948 return 0;
949 }
950
951 if (IsSplitBlock && Line.First == Line.Last &&
952 I > AnnotatedLines.begin() &&
953 (I[-1]->endsWith(Tokens: tok::kw_else) || IsCtrlStmt(*I[-1]))) {
954 return 0;
955 }
956 FormatToken *Tok = I[1]->First;
957 auto ShouldMerge = [Tok]() {
958 if (Tok->isNot(Kind: tok::r_brace) || Tok->MustBreakBefore)
959 return false;
960 const FormatToken *Next = Tok->getNextNonComment();
961 return !Next || Next->is(Kind: tok::semi);
962 };
963
964 if (ShouldMerge()) {
965 // We merge empty blocks even if the line exceeds the column limit.
966 Tok->SpacesRequiredBefore =
967 Style.SpaceInEmptyBraces != FormatStyle::SIEB_Never ||
968 Line.Last->is(Kind: tok::comment);
969 Tok->CanBreakBefore = true;
970 return 1;
971 } else if (Limit != 0 && !Line.startsWithNamespace() &&
972 !startsExternCBlock(Line)) {
973 // Merge short records only when requested.
974 if (Line.Last->isOneOf(K1: TT_EnumLBrace, K2: TT_RecordLBrace))
975 return 0;
976
977 if (Line.Last->isOneOf(K1: TT_ClassLBrace, K2: TT_StructLBrace,
978 Ks: TT_UnionLBrace) &&
979 Line.Last != Line.First &&
980 Style.AllowShortRecordOnASingleLine != FormatStyle::SRS_Always) {
981 return 0;
982 }
983
984 // Check that we still have three lines and they fit into the limit.
985 if (I + 2 == E || I[2]->Type == LT_Invalid)
986 return 0;
987 Limit = limitConsideringMacros(I: I + 2, E, Limit);
988
989 if (!nextTwoLinesFitInto(I, Limit))
990 return 0;
991
992 // Second, check that the next line does not contain non-braced-init
993 // braces - if it does, readability declines when putting it into a
994 // single line.
995 if (I[1]->Last->is(TT: TT_LineComment))
996 return 0;
997 do {
998 if (Tok->is(Kind: tok::l_brace) && Tok->isNot(Kind: BK_BracedInit))
999 return 0;
1000 if (Tok->is(Kind: tok::r_brace) &&
1001 (!Tok->MatchingParen ||
1002 Tok->MatchingParen->isNot(Kind: BK_BracedInit))) {
1003 return 0;
1004 }
1005 Tok = Tok->Next;
1006 } while (Tok);
1007
1008 // Last, check that the third line starts with a closing brace.
1009 Tok = I[2]->First;
1010 if (Tok->isNot(Kind: tok::r_brace))
1011 return 0;
1012
1013 // Don't merge "if (a) { .. } else {".
1014 if (Tok->Next && Tok->Next->is(Kind: tok::kw_else))
1015 return 0;
1016
1017 // Don't merge a trailing multi-line control statement block like:
1018 // } else if (foo &&
1019 // bar)
1020 // { <-- current Line
1021 // baz();
1022 // }
1023 if (Line.First == Line.Last &&
1024 Line.First->is(TT: TT_ControlStatementLBrace) &&
1025 Style.BraceWrapping.AfterControlStatement ==
1026 FormatStyle::BWACS_MultiLine) {
1027 return 0;
1028 }
1029
1030 return 2;
1031 }
1032 } else if (I[1]->First->is(Kind: tok::l_brace)) {
1033 if (I[1]->Last->is(TT: TT_LineComment))
1034 return 0;
1035
1036 // Check for Limit <= 2 to account for the " {".
1037 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(Line: *I)))
1038 return 0;
1039 Limit -= 2;
1040 unsigned MergedLines = 0;
1041
1042 auto TryMergeBlock = [&] {
1043 if (Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never ||
1044 Style.AllowShortRecordOnASingleLine == FormatStyle::SRS_Always) {
1045 return true;
1046 }
1047 return I[1]->First == I[1]->Last && I + 2 != E &&
1048 I[2]->First->is(Kind: tok::r_brace);
1049 };
1050
1051 if (TryMergeBlock()) {
1052 MergedLines = tryMergeSimpleBlock(I: I + 1, E, Limit);
1053 // If we managed to merge the block, count the statement header, which
1054 // is on a separate line.
1055 if (MergedLines > 0)
1056 ++MergedLines;
1057 }
1058 return MergedLines;
1059 }
1060 return 0;
1061 }
1062
1063 /// Returns the modified column limit for \p I if it is inside a macro and
1064 /// needs a trailing '\'.
1065 unsigned limitConsideringMacros(ArrayRef<AnnotatedLine *>::const_iterator I,
1066 ArrayRef<AnnotatedLine *>::const_iterator E,
1067 unsigned Limit) {
1068 if (I[0]->InPPDirective && I + 1 != E &&
1069 !I[1]->First->HasUnescapedNewline && I[1]->First->isNot(Kind: tok::eof)) {
1070 return Limit < 2 ? 0 : Limit - 2;
1071 }
1072 return Limit;
1073 }
1074
1075 bool nextTwoLinesFitInto(ArrayRef<AnnotatedLine *>::const_iterator I,
1076 unsigned Limit) {
1077 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
1078 return false;
1079 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
1080 }
1081
1082 bool nextNLinesFitInto(ArrayRef<AnnotatedLine *>::const_iterator I,
1083 ArrayRef<AnnotatedLine *>::const_iterator E,
1084 unsigned Limit) {
1085 unsigned JoinedLength = 0;
1086 for (const auto *J = I + 1; J != E; ++J) {
1087 if ((*J)->First->MustBreakBefore)
1088 return false;
1089
1090 JoinedLength += 1 + (*J)->Last->TotalLength;
1091 if (JoinedLength > Limit)
1092 return false;
1093 }
1094 return true;
1095 }
1096
1097 bool containsMustBreak(const AnnotatedLine *Line) {
1098 assert(Line->First);
1099 // Ignore the first token, because in this situation, it applies more to the
1100 // last token of the previous line.
1101 for (const FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next)
1102 if (Tok->MustBreakBefore)
1103 return true;
1104 return false;
1105 }
1106
1107 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1108 assert(!A.Last->Next);
1109 assert(!B.First->Previous);
1110 if (B.Affected || B.LeadingEmptyLinesAffected) {
1111 assert(B.Affected || A.Last->Children.empty());
1112 A.Affected = true;
1113 }
1114 A.Last->Next = B.First;
1115 B.First->Previous = A.Last;
1116 B.First->CanBreakBefore = true;
1117 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1118 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1119 Tok->TotalLength += LengthA;
1120 A.Last = Tok;
1121 }
1122 }
1123
1124 const FormatStyle &Style;
1125 const AdditionalKeywords &Keywords;
1126 const ArrayRef<AnnotatedLine *>::const_iterator End;
1127
1128 ArrayRef<AnnotatedLine *>::const_iterator Next;
1129 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
1130};
1131
1132static void markFinalized(FormatToken *Tok) {
1133 if (Tok->is(Kind: tok::hash) && !Tok->Previous && Tok->Next &&
1134 Tok->Next->isOneOf(K1: tok::pp_if, K2: tok::pp_ifdef, Ks: tok::pp_ifndef,
1135 Ks: tok::pp_elif, Ks: tok::pp_elifdef, Ks: tok::pp_elifndef,
1136 Ks: tok::pp_else, Ks: tok::pp_endif)) {
1137 Tok = Tok->Next;
1138 }
1139 for (; Tok; Tok = Tok->Next) {
1140 if (Tok->MacroCtx && Tok->MacroCtx->Role == MR_ExpandedArg) {
1141 // In the first pass we format all macro arguments in the expanded token
1142 // stream. Instead of finalizing the macro arguments, we mark that they
1143 // will be modified as unexpanded arguments (as part of the macro call
1144 // formatting) in the next pass.
1145 Tok->MacroCtx->Role = MR_UnexpandedArg;
1146 // Reset whether spaces or a line break are required before this token, as
1147 // that is context dependent, and that context may change when formatting
1148 // the macro call. For example, given M(x) -> 2 * x, and the macro call
1149 // M(var), the token 'var' will have SpacesRequiredBefore = 1 after being
1150 // formatted as part of the expanded macro, but SpacesRequiredBefore = 0
1151 // for its position within the macro call.
1152 Tok->SpacesRequiredBefore = 0;
1153 if (!Tok->MustBreakBeforeFinalized)
1154 Tok->MustBreakBefore = 0;
1155 } else {
1156 Tok->Finalized = true;
1157 }
1158 }
1159}
1160
1161#ifndef NDEBUG
1162static void printLineState(const LineState &State) {
1163 llvm::dbgs() << "State: ";
1164 for (const ParenState &P : State.Stack) {
1165 llvm::dbgs() << (P.Tok ? P.Tok->TokenText : "F") << "|" << P.Indent.Total
1166 << "|" << P.LastSpace << "|" << P.NestedBlockIndent << " ";
1167 }
1168 llvm::dbgs() << State.NextToken->TokenText << "\n";
1169}
1170#endif
1171
1172/// Base class for classes that format one \c AnnotatedLine.
1173class LineFormatter {
1174public:
1175 LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
1176 const FormatStyle &Style,
1177 UnwrappedLineFormatter *BlockFormatter)
1178 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
1179 BlockFormatter(BlockFormatter) {}
1180 virtual ~LineFormatter() {}
1181
1182 /// Formats an \c AnnotatedLine and returns the penalty.
1183 ///
1184 /// If \p DryRun is \c false, directly applies the changes.
1185 virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1186 unsigned FirstStartColumn, bool DryRun) = 0;
1187
1188protected:
1189 /// If the \p State's next token is an r_brace closing a nested block,
1190 /// format the nested block before it.
1191 ///
1192 /// Returns \c true if all children could be placed successfully and adapts
1193 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1194 /// creates changes using \c Whitespaces.
1195 ///
1196 /// The crucial idea here is that children always get formatted upon
1197 /// encountering the closing brace right after the nested block. Now, if we
1198 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1199 /// \c false), the entire block has to be kept on the same line (which is only
1200 /// possible if it fits on the line, only contains a single statement, etc.
1201 ///
1202 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1203 /// break after the "{", format all lines with correct indentation and the put
1204 /// the closing "}" on yet another new line.
1205 ///
1206 /// This enables us to keep the simple structure of the
1207 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1208 /// break or don't break.
1209 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1210 unsigned &Penalty) {
1211 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1212 bool HasLBrace = LBrace && LBrace->is(Kind: tok::l_brace) && LBrace->is(BBK: BK_Block);
1213 FormatToken &Previous = *State.NextToken->Previous;
1214 if (Previous.Children.empty() || (!HasLBrace && !LBrace->MacroParent)) {
1215 // The previous token does not open a block. Nothing to do. We don't
1216 // assert so that we can simply call this function for all tokens.
1217 return true;
1218 }
1219
1220 if (NewLine || Previous.MacroParent) {
1221 const ParenState &P = State.Stack.back();
1222
1223 int AdditionalIndent =
1224 P.Indent.Total - Previous.Children[0]->Level * Style.IndentWidth;
1225 Penalty +=
1226 BlockFormatter->format(Lines: Previous.Children, DryRun, AdditionalIndent,
1227 /*FixBadIndentation=*/true);
1228 return true;
1229 }
1230
1231 if (Previous.Children[0]->First->MustBreakBefore)
1232 return false;
1233
1234 // Cannot merge into one line if this line ends on a comment.
1235 if (Previous.is(Kind: tok::comment))
1236 return false;
1237
1238 // Cannot merge multiple statements into a single line.
1239 if (Previous.Children.size() > 1)
1240 return false;
1241
1242 const AnnotatedLine *Child = Previous.Children[0];
1243 // We can't put the closing "}" on a line with a trailing comment.
1244 if (Child->Last->isTrailingComment())
1245 return false;
1246
1247 // If the child line exceeds the column limit, we wouldn't want to merge it.
1248 // We add +2 for the trailing " }".
1249 if (Style.ColumnLimit > 0 &&
1250 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit) {
1251 return false;
1252 }
1253
1254 if (!DryRun) {
1255 Whitespaces->replaceWhitespace(
1256 Tok&: *Child->First, /*Newlines=*/0, /*Spaces=*/1,
1257 /*StartOfTokenColumn=*/State.Column, /*AlignedTo=*/nullptr,
1258 InPPDirective: State.Line->InPPDirective);
1259 }
1260 Penalty +=
1261 formatLine(Line: *Child, FirstIndent: State.Column + 1, /*FirstStartColumn=*/0, DryRun);
1262 if (!DryRun)
1263 markFinalized(Tok: Child->First);
1264
1265 State.Column += 1 + Child->Last->TotalLength;
1266 return true;
1267 }
1268
1269 ContinuationIndenter *Indenter;
1270
1271private:
1272 WhitespaceManager *Whitespaces;
1273 const FormatStyle &Style;
1274 UnwrappedLineFormatter *BlockFormatter;
1275};
1276
1277/// Formatter that keeps the existing line breaks.
1278class NoColumnLimitLineFormatter : public LineFormatter {
1279public:
1280 NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
1281 WhitespaceManager *Whitespaces,
1282 const FormatStyle &Style,
1283 UnwrappedLineFormatter *BlockFormatter)
1284 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1285
1286 /// Formats the line, simply keeping all of the input's line breaking
1287 /// decisions.
1288 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1289 unsigned FirstStartColumn, bool DryRun) override {
1290 assert(!DryRun);
1291 LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
1292 Line: &Line, /*DryRun=*/false);
1293 while (State.NextToken) {
1294 bool Newline =
1295 Indenter->mustBreak(State) ||
1296 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
1297 unsigned Penalty = 0;
1298 formatChildren(State, NewLine: Newline, /*DryRun=*/false, Penalty);
1299 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
1300 }
1301 return 0;
1302 }
1303};
1304
1305/// Formatter that puts all tokens into a single line without breaks.
1306class NoLineBreakFormatter : public LineFormatter {
1307public:
1308 NoLineBreakFormatter(ContinuationIndenter *Indenter,
1309 WhitespaceManager *Whitespaces, const FormatStyle &Style,
1310 UnwrappedLineFormatter *BlockFormatter)
1311 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1312
1313 /// Puts all tokens into a single line.
1314 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1315 unsigned FirstStartColumn, bool DryRun) override {
1316 unsigned Penalty = 0;
1317 LineState State =
1318 Indenter->getInitialState(FirstIndent, FirstStartColumn, Line: &Line, DryRun);
1319 while (State.NextToken) {
1320 formatChildren(State, /*NewLine=*/false, DryRun, Penalty);
1321 Indenter->addTokenToState(
1322 State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun);
1323 }
1324 return Penalty;
1325 }
1326};
1327
1328/// Finds the best way to break lines.
1329class OptimizingLineFormatter : public LineFormatter {
1330public:
1331 OptimizingLineFormatter(ContinuationIndenter *Indenter,
1332 WhitespaceManager *Whitespaces,
1333 const FormatStyle &Style,
1334 UnwrappedLineFormatter *BlockFormatter)
1335 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1336
1337 /// Formats the line by finding the best line breaks with line lengths
1338 /// below the column limit.
1339 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1340 unsigned FirstStartColumn, bool DryRun) override {
1341 LineState State =
1342 Indenter->getInitialState(FirstIndent, FirstStartColumn, Line: &Line, DryRun);
1343
1344 // If the ObjC method declaration does not fit on a line, we should format
1345 // it with one arg per line.
1346 if (State.Line->Type == LT_ObjCMethodDecl)
1347 State.Stack.back().BreakBeforeParameter = true;
1348
1349 // Find best solution in solution space.
1350 return analyzeSolutionSpace(InitialState&: State, DryRun);
1351 }
1352
1353private:
1354 struct CompareLineStatePointers {
1355 bool operator()(LineState *obj1, LineState *obj2) const {
1356 return *obj1 < *obj2;
1357 }
1358 };
1359
1360 /// A pair of <penalty, count> that is used to prioritize the BFS on.
1361 ///
1362 /// In case of equal penalties, we want to prefer states that were inserted
1363 /// first. During state generation we make sure that we insert states first
1364 /// that break the line as late as possible.
1365 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1366
1367 /// An edge in the solution space from \c Previous->State to \c State,
1368 /// inserting a newline dependent on the \c NewLine.
1369 struct StateNode {
1370 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
1371 : State(State), NewLine(NewLine), Previous(Previous) {}
1372 LineState State;
1373 bool NewLine;
1374 StateNode *Previous;
1375 };
1376
1377 /// An item in the prioritized BFS search queue. The \c StateNode's
1378 /// \c State has the given \c OrderedPenalty.
1379 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1380
1381 /// The BFS queue type.
1382 typedef std::priority_queue<QueueItem, SmallVector<QueueItem>,
1383 std::greater<QueueItem>>
1384 QueueType;
1385
1386 /// Analyze the entire solution space starting from \p InitialState.
1387 ///
1388 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1389 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1390 /// find the shortest path (the one with lowest penalty) from \p InitialState
1391 /// to a state where all tokens are placed. Returns the penalty.
1392 ///
1393 /// If \p DryRun is \c false, directly applies the changes.
1394 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
1395 std::set<LineState *, CompareLineStatePointers> Seen;
1396
1397 // Increasing count of \c StateNode items we have created. This is used to
1398 // create a deterministic order independent of the container.
1399 unsigned Count = 0;
1400 QueueType Queue;
1401
1402 // Insert start element into queue.
1403 StateNode *RootNode =
1404 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
1405 Queue.push(x: QueueItem(OrderedPenalty(0, Count), RootNode));
1406 ++Count;
1407
1408 unsigned Penalty = 0;
1409
1410 // While not empty, take first element and follow edges.
1411 while (!Queue.empty()) {
1412 // Quit if we still haven't found a solution by now.
1413 if (Count > 25'000'000)
1414 return 0;
1415
1416 Penalty = Queue.top().first.first;
1417 StateNode *Node = Queue.top().second;
1418 if (!Node->State.NextToken) {
1419 LLVM_DEBUG(llvm::dbgs()
1420 << "\n---\nPenalty for line: " << Penalty << "\n");
1421 break;
1422 }
1423 Queue.pop();
1424
1425 // Cut off the analysis of certain solutions if the analysis gets too
1426 // complex. See description of IgnoreStackForComparison.
1427 if (Count > 50'000)
1428 Node->State.IgnoreStackForComparison = true;
1429
1430 if (!Seen.insert(x: &Node->State).second) {
1431 // State already examined with lower penalty.
1432 continue;
1433 }
1434
1435 FormatDecision LastFormat = Node->State.NextToken->getDecision();
1436 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
1437 addNextStateToQueue(Penalty, PreviousNode: Node, /*NewLine=*/false, Count: &Count, Queue: &Queue);
1438 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
1439 addNextStateToQueue(Penalty, PreviousNode: Node, /*NewLine=*/true, Count: &Count, Queue: &Queue);
1440 }
1441
1442 if (Queue.empty()) {
1443 // We were unable to find a solution, do nothing.
1444 // FIXME: Add diagnostic?
1445 LLVM_DEBUG(llvm::dbgs() << "Could not find a solution.\n");
1446 return 0;
1447 }
1448
1449 // Reconstruct the solution.
1450 if (!DryRun)
1451 reconstructPath(State&: InitialState, Best: Queue.top().second);
1452
1453 LLVM_DEBUG(llvm::dbgs()
1454 << "Total number of analyzed states: " << Count << "\n");
1455 LLVM_DEBUG(llvm::dbgs() << "---\n");
1456
1457 return Penalty;
1458 }
1459
1460 /// Add the following state to the analysis queue \c Queue.
1461 ///
1462 /// Assume the current state is \p PreviousNode and has been reached with a
1463 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
1464 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1465 bool NewLine, unsigned *Count, QueueType *Queue) {
1466 if (NewLine && !Indenter->canBreak(State: PreviousNode->State))
1467 return;
1468 if (!NewLine && Indenter->mustBreak(State: PreviousNode->State))
1469 return;
1470
1471 StateNode *Node = new (Allocator.Allocate())
1472 StateNode(PreviousNode->State, NewLine, PreviousNode);
1473 if (!formatChildren(State&: Node->State, NewLine, /*DryRun=*/true, Penalty))
1474 return;
1475
1476 Penalty += Indenter->addTokenToState(State&: Node->State, Newline: NewLine, DryRun: true);
1477
1478 Queue->push(x: QueueItem(OrderedPenalty(Penalty, *Count), Node));
1479 ++(*Count);
1480 }
1481
1482 /// Applies the best formatting by reconstructing the path in the
1483 /// solution space that leads to \c Best.
1484 void reconstructPath(LineState &State, StateNode *Best) {
1485 llvm::SmallVector<StateNode *> Path;
1486 // We do not need a break before the initial token.
1487 while (Best->Previous) {
1488 Path.push_back(Elt: Best);
1489 Best = Best->Previous;
1490 }
1491 for (const auto &Node : llvm::reverse(C&: Path)) {
1492 unsigned Penalty = 0;
1493 formatChildren(State, NewLine: Node->NewLine, /*DryRun=*/false, Penalty);
1494 Penalty += Indenter->addTokenToState(State, Newline: Node->NewLine, DryRun: false);
1495
1496 LLVM_DEBUG({
1497 printLineState(Node->Previous->State);
1498 if (Node->NewLine) {
1499 llvm::dbgs() << "Penalty for placing "
1500 << Node->Previous->State.NextToken->Tok.getName()
1501 << " on a new line: " << Penalty << "\n";
1502 }
1503 });
1504 }
1505 }
1506
1507 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1508};
1509
1510} // anonymous namespace
1511
1512unsigned UnwrappedLineFormatter::format(
1513 const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
1514 int AdditionalIndent, bool FixBadIndentation, unsigned FirstStartColumn,
1515 unsigned NextStartColumn, unsigned LastStartColumn) {
1516 LineJoiner Joiner(Style, Keywords, Lines);
1517
1518 // Try to look up already computed penalty in DryRun-mode.
1519 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
1520 &Lines, AdditionalIndent);
1521 auto CacheIt = PenaltyCache.find(x: CacheKey);
1522 if (DryRun && CacheIt != PenaltyCache.end())
1523 return CacheIt->second;
1524
1525 assert(!Lines.empty());
1526 unsigned Penalty = 0;
1527 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
1528 AdditionalIndent);
1529 const AnnotatedLine *PrevPrevLine = nullptr;
1530 const AnnotatedLine *PreviousLine = nullptr;
1531 const AnnotatedLine *NextLine = nullptr;
1532
1533 // The minimum level of consecutive lines that have been formatted.
1534 unsigned RangeMinLevel = UINT_MAX;
1535
1536 bool FirstLine = true;
1537 for (const AnnotatedLine *Line =
1538 Joiner.getNextMergedLine(DryRun, IndentTracker);
1539 Line; PrevPrevLine = PreviousLine, PreviousLine = Line, Line = NextLine,
1540 FirstLine = false) {
1541 assert(Line->First);
1542 const AnnotatedLine &TheLine = *Line;
1543 unsigned Indent = IndentTracker.getIndent();
1544
1545 // We continue formatting unchanged lines to adjust their indent, e.g. if a
1546 // scope was added. However, we need to carefully stop doing this when we
1547 // exit the scope of affected lines to prevent indenting the entire
1548 // remaining file if it currently missing a closing brace.
1549 bool PreviousRBrace =
1550 PreviousLine && PreviousLine->startsWith(Tokens: tok::r_brace);
1551 bool ContinueFormatting =
1552 TheLine.Level > RangeMinLevel ||
1553 (TheLine.Level == RangeMinLevel && !PreviousRBrace &&
1554 !TheLine.startsWith(Tokens: TT_NamespaceRBrace));
1555
1556 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
1557 Indent != TheLine.First->OriginalColumn;
1558 bool ShouldFormat = TheLine.Affected || FixIndentation;
1559 // We cannot format this line; if the reason is that the line had a
1560 // parsing error, remember that.
1561 if (ShouldFormat && TheLine.Type == LT_Invalid && Status) {
1562 Status->FormatComplete = false;
1563 Status->Line =
1564 SourceMgr.getSpellingLineNumber(Loc: TheLine.First->Tok.getLocation());
1565 }
1566
1567 if (ShouldFormat && TheLine.Type != LT_Invalid) {
1568 if (!DryRun) {
1569 bool LastLine = TheLine.First->is(Kind: tok::eof);
1570 formatFirstToken(Line: TheLine, PreviousLine, PrevPrevLine, Lines, Indent,
1571 NewlineIndent: LastLine ? LastStartColumn : NextStartColumn + Indent);
1572 }
1573
1574 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1575 unsigned ColumnLimit = getColumnLimit(InPPDirective: TheLine.InPPDirective, NextLine);
1576 bool FitsIntoOneLine =
1577 !TheLine.ContainsMacroCall &&
1578 (TheLine.Last->TotalLength + Indent <= ColumnLimit ||
1579 (TheLine.Type == LT_ImportStatement &&
1580 (!Style.isJavaScript() || !Style.JavaScriptWrapImports)) ||
1581 (Style.isCSharp() &&
1582 TheLine.InPPDirective)); // don't split #regions in C#
1583 if (Style.ColumnLimit == 0) {
1584 NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
1585 .formatLine(Line: TheLine, FirstIndent: NextStartColumn + Indent,
1586 FirstStartColumn: FirstLine ? FirstStartColumn : 0, DryRun);
1587 } else if (FitsIntoOneLine) {
1588 Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
1589 .formatLine(Line: TheLine, FirstIndent: NextStartColumn + Indent,
1590 FirstStartColumn: FirstLine ? FirstStartColumn : 0, DryRun);
1591 } else {
1592 Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
1593 .formatLine(Line: TheLine, FirstIndent: NextStartColumn + Indent,
1594 FirstStartColumn: FirstLine ? FirstStartColumn : 0, DryRun);
1595 }
1596 RangeMinLevel = std::min(a: RangeMinLevel, b: TheLine.Level);
1597 } else {
1598 // If no token in the current line is affected, we still need to format
1599 // affected children.
1600 if (TheLine.ChildrenAffected) {
1601 for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next)
1602 if (!Tok->Children.empty())
1603 format(Lines: Tok->Children, DryRun);
1604 }
1605
1606 // Adapt following lines on the current indent level to the same level
1607 // unless the current \c AnnotatedLine is not at the beginning of a line.
1608 bool StartsNewLine =
1609 TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
1610 if (StartsNewLine)
1611 IndentTracker.adjustToUnmodifiedLine(Line: TheLine);
1612 if (!DryRun) {
1613 bool ReformatLeadingWhitespace =
1614 StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
1615 TheLine.LeadingEmptyLinesAffected);
1616 // Format the first token.
1617 if (ReformatLeadingWhitespace) {
1618 formatFirstToken(Line: TheLine, PreviousLine, PrevPrevLine, Lines,
1619 Indent: TheLine.First->OriginalColumn,
1620 NewlineIndent: TheLine.First->OriginalColumn);
1621 } else {
1622 Whitespaces->addUntouchableToken(Tok: *TheLine.First,
1623 InPPDirective: TheLine.InPPDirective);
1624 }
1625
1626 // Notify the WhitespaceManager about the unchanged whitespace.
1627 for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
1628 Whitespaces->addUntouchableToken(Tok: *Tok, InPPDirective: TheLine.InPPDirective);
1629 }
1630 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1631 RangeMinLevel = UINT_MAX;
1632 }
1633 if (!DryRun)
1634 markFinalized(Tok: TheLine.First);
1635 }
1636 PenaltyCache[CacheKey] = Penalty;
1637 return Penalty;
1638}
1639
1640static auto computeNewlines(const AnnotatedLine &Line,
1641 const AnnotatedLine *PreviousLine,
1642 const AnnotatedLine *PrevPrevLine,
1643 const SmallVectorImpl<AnnotatedLine *> &Lines,
1644 const FormatStyle &Style) {
1645 const auto &RootToken = *Line.First;
1646 if (isClangFormatOn(Comment: RootToken.TokenText))
1647 return RootToken.NewlinesBefore;
1648 auto Newlines =
1649 std::min(a: RootToken.NewlinesBefore, b: Style.MaxEmptyLinesToKeep + 1);
1650 // Remove empty lines before "}" where applicable.
1651 if (RootToken.is(Kind: tok::r_brace) &&
1652 (!RootToken.Next ||
1653 (RootToken.Next->is(Kind: tok::semi) && !RootToken.Next->Next)) &&
1654 // Do not remove empty lines before namespace closing "}".
1655 !getNamespaceToken(Line: &Line, AnnotatedLines: Lines)) {
1656 Newlines = std::min(a: Newlines, b: 1u);
1657 }
1658 // Remove empty lines at the start of nested blocks (lambdas/arrow functions)
1659 if (!PreviousLine && Line.Level > 0)
1660 Newlines = std::min(a: Newlines, b: 1u);
1661 if (Newlines == 0 && !RootToken.IsFirst)
1662 Newlines = 1;
1663 if (RootToken.IsFirst &&
1664 (!Style.KeepEmptyLines.AtStartOfFile || !RootToken.HasUnescapedNewline)) {
1665 Newlines = 0;
1666 }
1667
1668 // Remove empty lines after "{".
1669 if (!Style.KeepEmptyLines.AtStartOfBlock && PreviousLine &&
1670 PreviousLine->Last->is(Kind: tok::l_brace) &&
1671 !PreviousLine->startsWithNamespace() &&
1672 !(PrevPrevLine && PrevPrevLine->startsWithNamespace() &&
1673 PreviousLine->startsWith(Tokens: tok::l_brace)) &&
1674 !startsExternCBlock(Line: *PreviousLine)) {
1675 Newlines = 1;
1676 }
1677
1678 if (Style.WrapNamespaceBodyWithEmptyLines != FormatStyle::WNBWELS_Leave) {
1679 // Modify empty lines after TT_NamespaceLBrace.
1680 if (PreviousLine && PreviousLine->endsWith(Tokens: TT_NamespaceLBrace)) {
1681 if (Style.WrapNamespaceBodyWithEmptyLines == FormatStyle::WNBWELS_Never)
1682 Newlines = 1;
1683 else if (!Line.startsWithNamespace())
1684 Newlines = std::max(a: Newlines, b: 2u);
1685 }
1686 // Modify empty lines before TT_NamespaceRBrace.
1687 if (Line.startsWith(Tokens: TT_NamespaceRBrace)) {
1688 if (Style.WrapNamespaceBodyWithEmptyLines == FormatStyle::WNBWELS_Never)
1689 Newlines = 1;
1690 else if (!PreviousLine->startsWith(Tokens: TT_NamespaceRBrace))
1691 Newlines = std::max(a: Newlines, b: 2u);
1692 }
1693 }
1694
1695 // Insert or remove empty line before access specifiers.
1696 if (PreviousLine && RootToken.isAccessSpecifier()) {
1697 switch (Style.EmptyLineBeforeAccessModifier) {
1698 case FormatStyle::ELBAMS_Never:
1699 if (Newlines > 1)
1700 Newlines = 1;
1701 break;
1702 case FormatStyle::ELBAMS_Leave:
1703 Newlines = std::max(a: RootToken.NewlinesBefore, b: 1u);
1704 break;
1705 case FormatStyle::ELBAMS_LogicalBlock:
1706 if (PreviousLine->Last->isOneOf(K1: tok::semi, K2: tok::r_brace) && Newlines <= 1)
1707 Newlines = 2;
1708 if (PreviousLine->First->isAccessSpecifier())
1709 Newlines = 1; // Previous is an access modifier remove all new lines.
1710 break;
1711 case FormatStyle::ELBAMS_Always: {
1712 const FormatToken *previousToken;
1713 if (PreviousLine->Last->is(Kind: tok::comment))
1714 previousToken = PreviousLine->Last->getPreviousNonComment();
1715 else
1716 previousToken = PreviousLine->Last;
1717 if ((!previousToken || previousToken->isNot(Kind: tok::l_brace)) &&
1718 Newlines <= 1) {
1719 Newlines = 2;
1720 }
1721 } break;
1722 }
1723 }
1724
1725 // Insert or remove empty line after access specifiers.
1726 if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
1727 (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline)) {
1728 // EmptyLineBeforeAccessModifier is handling the case when two access
1729 // modifiers follow each other.
1730 if (!RootToken.isAccessSpecifier()) {
1731 switch (Style.EmptyLineAfterAccessModifier) {
1732 case FormatStyle::ELAAMS_Never:
1733 Newlines = 1;
1734 break;
1735 case FormatStyle::ELAAMS_Leave:
1736 Newlines = std::max(a: Newlines, b: 1u);
1737 break;
1738 case FormatStyle::ELAAMS_Always:
1739 if (RootToken.is(Kind: tok::r_brace)) // Do not add at end of class.
1740 Newlines = 1u;
1741 else
1742 Newlines = std::max(a: Newlines, b: 2u);
1743 break;
1744 }
1745 }
1746 }
1747
1748 return Newlines;
1749}
1750
1751void UnwrappedLineFormatter::formatFirstToken(
1752 const AnnotatedLine &Line, const AnnotatedLine *PreviousLine,
1753 const AnnotatedLine *PrevPrevLine,
1754 const SmallVectorImpl<AnnotatedLine *> &Lines, unsigned Indent,
1755 unsigned NewlineIndent) {
1756 FormatToken &RootToken = *Line.First;
1757 if (RootToken.is(Kind: tok::eof)) {
1758 unsigned Newlines = std::min(
1759 a: RootToken.NewlinesBefore,
1760 b: Style.KeepEmptyLines.AtEndOfFile ? Style.MaxEmptyLinesToKeep + 1 : 1);
1761 unsigned TokenIndent = Newlines ? NewlineIndent : 0;
1762 Whitespaces->replaceWhitespace(Tok&: RootToken, Newlines, Spaces: TokenIndent,
1763 StartOfTokenColumn: TokenIndent);
1764 return;
1765 }
1766
1767 if (RootToken.Newlines < 0) {
1768 RootToken.Newlines =
1769 computeNewlines(Line, PreviousLine, PrevPrevLine, Lines, Style);
1770 assert(RootToken.Newlines >= 0);
1771 }
1772
1773 if (RootToken.Newlines > 0)
1774 Indent = NewlineIndent;
1775
1776 // Preprocessor directives get indented before the hash only if specified. In
1777 // Javascript import statements are indented like normal statements.
1778 if (!Style.isJavaScript() &&
1779 Style.IndentPPDirectives < FormatStyle::PPDIS_BeforeHash &&
1780 (Line.Type == LT_PreprocessorDirective ||
1781 Line.Type == LT_ImportStatement)) {
1782 Indent = 0;
1783 }
1784
1785 Whitespaces->replaceWhitespace(Tok&: RootToken, Newlines: RootToken.Newlines, Spaces: Indent, StartOfTokenColumn: Indent,
1786 /*AlignedTo=*/nullptr,
1787 InPPDirective: Line.InPPDirective &&
1788 !RootToken.HasUnescapedNewline);
1789}
1790
1791unsigned
1792UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
1793 const AnnotatedLine *NextLine) const {
1794 // In preprocessor directives reserve two chars for trailing " \" if the
1795 // next line continues the preprocessor directive.
1796 bool ContinuesPPDirective =
1797 InPPDirective &&
1798 // If there is no next line, this is likely a child line and the parent
1799 // continues the preprocessor directive.
1800 (!NextLine ||
1801 (NextLine->InPPDirective &&
1802 // If there is an unescaped newline between this line and the next, the
1803 // next line starts a new preprocessor directive.
1804 !NextLine->First->HasUnescapedNewline));
1805 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
1806}
1807
1808} // namespace format
1809} // namespace clang
1810