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