clang 24.0.0git
UnwrappedLineFormatter.cpp
Go to the documentation of this file.
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
10#include "FormatToken.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(tok::kw_extern) && Next && Next->isStringLiteral() &&
27 NextNext && NextNext->is(tok::l_brace);
28}
29
30bool isRecordLBrace(const FormatToken &Tok) {
31 return Tok.isOneOf(TT_ClassLBrace, TT_EnumLBrace, TT_RecordLBrace,
32 TT_StructLBrace, 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(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(Line.Level + 1, -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 &&
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(Line.Level + 1);
89 }
90 Indent = getIndent(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(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_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(Keywords.kw_signals, Keywords.kw_qsignals) &&
135 RootToken.Next && RootToken.Next->is(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 - 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(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(*Current);
218 unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next, 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(*Next[0], *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,
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_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_FunctionLBrace) &&
267 TheLine->First == TheLine->Last) {
268 const bool EmptyFunctionBody = NextLine.First->is(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(TT_ClassLBrace, TT_StructLBrace,
279 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(tok::l_brace) &&
288 TheLine->First == TheLine->Last) {
289 const bool EmptyBlock = NextLine.First->is(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(tok::kw_typedef))
300 Tok = Tok->getNextNonComment();
301
302 if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union))
303 return tryMergeRecord(I, E, Limit);
304
305 if (Tok && Tok->isOneOf(tok::kw_extern, Keywords.kw_interface)) {
306 return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock
307 ? tryMergeSimpleBlock(I, E, Limit)
308 : 0;
309 }
310
311 if (Tok && Tok->is(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(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_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(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(*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(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(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(Level - OutdentBy, 0);
407 }
408 }
409 }
410 return J - 1;
411 }
412
413 if (auto nsToken = getMatchingNamespaceToken(TheLine, AnnotatedLines)) {
414 int i = 0;
415 unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
416 for (; I + 1 + i != E &&
417 nsToken->TokenText ==
418 getMatchingNamespaceTokenText(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(tok::r_brace);
424
425 // Indent like the outer-most namespace.
426 IndentTracker.nextLine(*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_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(tok::l_brace) && FirstNonComment != TheLine->Last &&
445 (FirstNonComment->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for,
446 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_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 ==
459 ? tryMergeSimpleBlock(I, E, Limit)
460 : 0;
461 }
462 if (PreviousLine && TheLine->First->is(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(tok::objc_autoreleasepool,
468 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(tok::l_brace) && PreviousLine->Last) {
487 const FormatToken *Previous = PreviousLine->Last;
488 if (Previous) {
489 if (Previous->is(tok::comment))
490 Previous = Previous->getPreviousNonComment();
491 if (Previous) {
492 if (Previous->is(tok::greater) && !PreviousLine->InPPDirective)
493 return 0;
494 if (Previous->is(tok::identifier)) {
495 const FormatToken *PreviousPrevious =
496 Previous->getPreviousNonComment();
497 if (PreviousPrevious &&
498 PreviousPrevious->isOneOf(tok::kw_class, tok::kw_struct,
499 tok::kw_union)) {
500 return 0;
501 }
502 }
503 }
504 }
505 }
506
507 if (TheLine->First->is(TT_SwitchExpressionLabel)) {
508 return Style.AllowShortCaseExpressionOnASingleLine
509 ? tryMergeShortCaseLabels(I, E, Limit)
510 : 0;
511 }
512
513 if (TheLine->Last->is(tok::l_brace)) {
514 bool ShouldMerge = false;
515 // Try to merge records.
516 if (TheLine->Last->is(TT_EnumLBrace)) {
517 ShouldMerge = Style.AllowShortEnumsOnASingleLine;
518 } else if (TheLine->Last->is(TT_CompoundRequirementLBrace)) {
519 ShouldMerge = Style.AllowShortCompoundRequirementOnASingleLine;
520 } else if (TheLine->Last->isOneOf(TT_ClassLBrace, TT_StructLBrace,
521 TT_UnionLBrace) ||
522 (TheLine->Last->is(TT_RecordLBrace) && Style.isJava())) {
523 return tryMergeRecord(I, E, Limit);
524 } else if (TheLine->InPPDirective ||
525 TheLine->First->isNoneOf(tok::kw_class, tok::kw_enum,
526 tok::kw_struct, 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(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_FunctionLBrace) &&
538 Style.BraceWrapping.AfterFunction) {
539 if (NextLine.Last->is(TT_LineComment))
540 return 0;
541
542 // Check for Limit <= 2 to account for the " {".
543 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(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(tok::r_brace))) {
552 MergedLines = tryMergeSimpleBlock(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(tok::kw_else))
563 return true;
564
565 return First->is(tok::r_brace) && First->Next &&
566 First->Next->is(tok::kw_else);
567 };
568 if (TheLine->First->is(tok::kw_if) ||
569 (IsElseLine() && (Style.AllowShortIfStatementsOnASingleLine ==
571 return Style.AllowShortIfStatementsOnASingleLine
572 ? tryMergeSimpleControlStatement(I, E, Limit)
573 : 0;
574 }
575 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while, tok::kw_do,
576 TT_ForEachMacro)) {
577 return Style.AllowShortLoopsOnASingleLine
578 ? tryMergeSimpleControlStatement(I, E, Limit)
579 : 0;
580 }
581 if (TheLine->First->isOneOf(tok::kw_case, 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,
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(TT_ClassLBrace, TT_StructLBrace, 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) {
617 return false;
619 return true;
620 default:
621 return NextLine->First->is(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(TT_ClassLBrace, TT_StructLBrace,
635 TT_UnionLBrace)) {
636 if (I + 2 == E || I[2]->First->is(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(tok::kw_class, tok::kw_struct, tok::kw_union)) {
647 const bool IsEmptyBlock =
648 Line->Last->is(tok::l_brace) && NextLine->First->is(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,
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,
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(TT_NamespaceLBrace))
686 return 0;
687
688 if (std::distance(BraceOpenLine, E) <= 2)
689 return 0;
690
691 if (BraceOpenLine[0]->Last->is(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 + 1, E, Limit);
707
708 const auto LinesToBeMerged = OpenBraceWrapped + 2;
709
710 // Check if it's a namespace inside a namespace, and call recursively if so.
711 // '3' is the sizes of the whitespace and closing brace for " _inner_ }".
712 if (L1.First->is(tok::kw_namespace)) {
713 if (L1.Last->is(tok::comment) || !Style.CompactNamespaces)
714 return 0;
715 if (Limit < L1.Last->TotalLength + 3)
716 return 0;
717 const auto InnerLimit = Limit - L1.Last->TotalLength - 3;
718 const auto MergedLines =
719 tryMergeNamespace(BraceOpenLine + 1, E, InnerLimit);
720 if (MergedLines == 0)
721 return 0;
722 const auto N = MergedLines + LinesToBeMerged;
723 // Check if there is even a line after the inner result.
724 if (auto Distance = std::distance(I, E);
725 static_cast<std::remove_const_t<decltype(N)>>(Distance) <= N) {
726 return 0;
727 }
728 // Check that the line after the inner result starts with a closing brace
729 // which we are permitted to merge into one line.
730 if (I[N]->First->is(TT_NamespaceRBrace) &&
731 !I[N]->First->MustBreakBefore &&
732 BraceOpenLine[MergedLines + 1]->Last->isNot(tok::comment) &&
733 nextNLinesFitInto(I, I + N + 1, Limit)) {
734 return N;
735 }
736 return 0;
737 }
738
739 // There's no inner namespace, so we are considering to merge at most one
740 // line.
741
742 // The line which is in the namespace should end with semicolon.
743 if (L1.Last->isNot(tok::semi))
744 return 0;
745
746 // Last, check that the third line starts with a closing brace.
747 if (L2.First->isNot(TT_NamespaceRBrace) || L2.First->MustBreakBefore)
748 return 0;
749
750 if (!nextTwoLinesFitInto(I, Limit))
751 return 0;
752
753 return LinesToBeMerged;
754 }
755
756 unsigned
757 tryMergeSimpleControlStatement(ArrayRef<AnnotatedLine *>::const_iterator I,
759 unsigned Limit) {
760 if (Limit == 0)
761 return 0;
762 if (Style.BraceWrapping.AfterControlStatement ==
764 I[1]->First->is(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 + 1, E, Limit);
773 AnnotatedLine &Line = **I;
774 if (Line.First->isNoneOf(tok::kw_do, tok::kw_else) &&
775 Line.Last->isNoneOf(tok::kw_else, 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(tok::kw_do) && Line.Last->isNot(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(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
785 TT_ForEachMacro, TT_LineComment)) {
786 return 0;
787 }
788 // Only inline simple if's (no nested if or else), unless specified
789 if (Style.AllowShortIfStatementsOnASingleLine ==
791 if (I + 2 != E && Line.startsWith(tok::kw_if) &&
792 I[2]->First->is(tok::kw_else)) {
793 return 0;
794 }
795 }
796 return 1;
797 }
798
799 unsigned tryMergeShortCaseLabels(ArrayRef<AnnotatedLine *>::const_iterator I,
801 unsigned Limit) {
802 if (Limit == 0 || I + 1 == E ||
803 I[1]->First->isOneOf(tok::kw_case, tok::kw_default)) {
804 return 0;
805 }
806 if (I[0]->Last->is(tok::l_brace) || I[1]->First->is(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(tok::kw_case, tok::kw_default, tok::r_brace))
823 break;
824 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
825 tok::kw_while) ||
826 EndsWithComment) {
827 return 0;
828 }
829 if (Line->First->is(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(tok::kw_case, tok::kw_default, tok::r_brace))
838 break;
839 if (Line->First->isNot(tok::comment) || Level != Line->Level)
840 return 0;
841 }
842 break;
843 }
844 if (Line->Last->is(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,
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(tok::at, tok::minus, 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(tok::kw_case) ||
871 (Line.First->Next && Line.First->Next->is(tok::kw_else))) {
872 return 0;
873 }
874 // default: in switch statement
875 if (Line.First->is(tok::kw_default)) {
876 const FormatToken *Tok = Line.First->getNextNonComment();
877 if (Tok && Tok->is(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(tok::r_brace));
890
891 if (IsCtrlStmt(Line) ||
892 Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
893 tok::kw___finally, tok::r_brace,
894 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(tok::kw_if, tok::kw_else) &&
902 !Style.BraceWrapping.AfterControlStatement &&
903 I[1]->First->isNot(tok::r_brace)) {
904 return 0;
905 }
906 if (!Style.AllowShortIfStatementsOnASingleLine &&
907 Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
908 Style.BraceWrapping.AfterControlStatement ==
910 I + 2 != E && I[2]->First->isNot(tok::r_brace)) {
911 return 0;
912 }
913 if (!Style.AllowShortLoopsOnASingleLine &&
914 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
915 TT_ForEachMacro) &&
916 !Style.BraceWrapping.AfterControlStatement &&
917 I[1]->First->isNot(tok::r_brace)) {
918 return 0;
919 }
920 if (!Style.AllowShortLoopsOnASingleLine &&
921 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
922 TT_ForEachMacro) &&
923 Style.BraceWrapping.AfterControlStatement ==
925 I + 2 != E && I[2]->First->isNot(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(tok::kw_try, tok::kw___try, tok::kw_catch,
934 Keywords.kw___except, tok::kw___finally)) {
935 return 0;
936 }
937 }
938
939 if (Line.endsWith(tok::l_brace)) {
940 if (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never &&
941 Line.First->is(TT_BlockLBrace)) {
942 return 0;
943 }
944
945 if (IsSplitBlock && Line.First == Line.Last &&
946 I > AnnotatedLines.begin() &&
947 (I[-1]->endsWith(tok::kw_else) || IsCtrlStmt(*I[-1]))) {
948 return 0;
949 }
950 FormatToken *Tok = I[1]->First;
951 auto ShouldMerge = [Tok]() {
952 if (Tok->isNot(tok::r_brace) || Tok->MustBreakBefore)
953 return false;
954 const FormatToken *Next = Tok->getNextNonComment();
955 return !Next || Next->is(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(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(TT_EnumLBrace, TT_RecordLBrace))
969 return 0;
970
971 if (Line.Last->isOneOf(TT_ClassLBrace, TT_StructLBrace,
972 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 + 2, E, Limit);
982
983 if (!nextTwoLinesFitInto(I, Limit))
984 return 0;
985
986 // Second, check that the next line does not contain non-braced-init
987 // braces - if it does, readability declines when putting it into a
988 // single line.
989 if (I[1]->Last->is(TT_LineComment))
990 return 0;
991 do {
992 if (Tok->is(tok::l_brace) && Tok->isNot(BK_BracedInit))
993 return 0;
994 if (Tok->is(tok::r_brace) &&
995 (!Tok->MatchingParen ||
996 Tok->MatchingParen->isNot(BK_BracedInit))) {
997 return 0;
998 }
999 Tok = Tok->Next;
1000 } while (Tok);
1001
1002 // Last, check that the third line starts with a closing brace.
1003 Tok = I[2]->First;
1004 if (Tok->isNot(tok::r_brace))
1005 return 0;
1006
1007 // Don't merge "if (a) { .. } else {".
1008 if (Tok->Next && Tok->Next->is(tok::kw_else))
1009 return 0;
1010
1011 // Don't merge a trailing multi-line control statement block like:
1012 // } else if (foo &&
1013 // bar)
1014 // { <-- current Line
1015 // baz();
1016 // }
1017 if (Line.First == Line.Last &&
1018 Line.First->is(TT_ControlStatementLBrace) &&
1019 Style.BraceWrapping.AfterControlStatement ==
1021 return 0;
1022 }
1023
1024 return 2;
1025 }
1026 } else if (I[1]->First->is(tok::l_brace)) {
1027 if (I[1]->Last->is(TT_LineComment))
1028 return 0;
1029
1030 // Check for Limit <= 2 to account for the " {".
1031 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
1032 return 0;
1033 Limit -= 2;
1034 unsigned MergedLines = 0;
1035
1036 auto TryMergeBlock = [&] {
1037 if (Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never ||
1038 Style.AllowShortRecordOnASingleLine == FormatStyle::SRS_Always) {
1039 return true;
1040 }
1041 return I[1]->First == I[1]->Last && I + 2 != E &&
1042 I[2]->First->is(tok::r_brace);
1043 };
1044
1045 if (TryMergeBlock()) {
1046 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
1047 // If we managed to merge the block, count the statement header, which
1048 // is on a separate line.
1049 if (MergedLines > 0)
1050 ++MergedLines;
1051 }
1052 return MergedLines;
1053 }
1054 return 0;
1055 }
1056
1057 /// Returns the modified column limit for \p I if it is inside a macro and
1058 /// needs a trailing '\'.
1059 unsigned limitConsideringMacros(ArrayRef<AnnotatedLine *>::const_iterator I,
1061 unsigned Limit) {
1062 if (I[0]->InPPDirective && I + 1 != E &&
1063 !I[1]->First->HasUnescapedNewline && I[1]->First->isNot(tok::eof)) {
1064 return Limit < 2 ? 0 : Limit - 2;
1065 }
1066 return Limit;
1067 }
1068
1069 bool nextTwoLinesFitInto(ArrayRef<AnnotatedLine *>::const_iterator I,
1070 unsigned Limit) {
1071 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
1072 return false;
1073 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
1074 }
1075
1076 bool nextNLinesFitInto(ArrayRef<AnnotatedLine *>::const_iterator I,
1078 unsigned Limit) {
1079 unsigned JoinedLength = 0;
1080 for (const auto *J = I + 1; J != E; ++J) {
1081 if ((*J)->First->MustBreakBefore)
1082 return false;
1083
1084 JoinedLength += 1 + (*J)->Last->TotalLength;
1085 if (JoinedLength > Limit)
1086 return false;
1087 }
1088 return true;
1089 }
1090
1091 bool containsMustBreak(const AnnotatedLine *Line) {
1092 assert(Line->First);
1093 // Ignore the first token, because in this situation, it applies more to the
1094 // last token of the previous line.
1095 for (const FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next)
1096 if (Tok->MustBreakBefore)
1097 return true;
1098 return false;
1099 }
1100
1101 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1102 assert(!A.Last->Next);
1103 assert(!B.First->Previous);
1104 if (B.Affected || B.LeadingEmptyLinesAffected) {
1105 assert(B.Affected || A.Last->Children.empty());
1106 A.Affected = true;
1107 }
1108 A.Last->Next = B.First;
1109 B.First->Previous = A.Last;
1110 B.First->CanBreakBefore = true;
1111 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1112 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1113 Tok->TotalLength += LengthA;
1114 A.Last = Tok;
1115 }
1116 }
1117
1118 const FormatStyle &Style;
1119 const AdditionalKeywords &Keywords;
1121
1123 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
1124};
1125
1126static void markFinalized(FormatToken *Tok) {
1127 if (Tok->is(tok::hash) && !Tok->Previous && Tok->Next &&
1128 Tok->Next->isOneOf(tok::pp_if, tok::pp_ifdef, tok::pp_ifndef,
1129 tok::pp_elif, tok::pp_elifdef, tok::pp_elifndef,
1130 tok::pp_else, tok::pp_endif)) {
1131 Tok = Tok->Next;
1132 }
1133 for (; Tok; Tok = Tok->Next) {
1134 if (Tok->MacroCtx && Tok->MacroCtx->Role == MR_ExpandedArg) {
1135 // In the first pass we format all macro arguments in the expanded token
1136 // stream. Instead of finalizing the macro arguments, we mark that they
1137 // will be modified as unexpanded arguments (as part of the macro call
1138 // formatting) in the next pass.
1139 Tok->MacroCtx->Role = MR_UnexpandedArg;
1140 // Reset whether spaces or a line break are required before this token, as
1141 // that is context dependent, and that context may change when formatting
1142 // the macro call. For example, given M(x) -> 2 * x, and the macro call
1143 // M(var), the token 'var' will have SpacesRequiredBefore = 1 after being
1144 // formatted as part of the expanded macro, but SpacesRequiredBefore = 0
1145 // for its position within the macro call.
1146 Tok->SpacesRequiredBefore = 0;
1147 if (!Tok->MustBreakBeforeFinalized)
1148 Tok->MustBreakBefore = 0;
1149 } else {
1150 Tok->Finalized = true;
1151 }
1152 }
1153}
1154
1155#ifndef NDEBUG
1156static void printLineState(const LineState &State) {
1157 llvm::dbgs() << "State: ";
1158 for (const ParenState &P : State.Stack) {
1159 llvm::dbgs() << (P.Tok ? P.Tok->TokenText : "F") << "|" << P.Indent.Total
1160 << "|" << P.LastSpace << "|" << P.NestedBlockIndent << " ";
1161 }
1162 llvm::dbgs() << State.NextToken->TokenText << "\n";
1163}
1164#endif
1165
1166/// Base class for classes that format one \c AnnotatedLine.
1167class LineFormatter {
1168public:
1169 LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
1170 const FormatStyle &Style,
1171 UnwrappedLineFormatter *BlockFormatter)
1172 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
1173 BlockFormatter(BlockFormatter) {}
1174 virtual ~LineFormatter() {}
1175
1176 /// Formats an \c AnnotatedLine and returns the penalty.
1177 ///
1178 /// If \p DryRun is \c false, directly applies the changes.
1179 virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1180 unsigned FirstStartColumn, bool DryRun) = 0;
1181
1182protected:
1183 /// If the \p State's next token is an r_brace closing a nested block,
1184 /// format the nested block before it.
1185 ///
1186 /// Returns \c true if all children could be placed successfully and adapts
1187 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1188 /// creates changes using \c Whitespaces.
1189 ///
1190 /// The crucial idea here is that children always get formatted upon
1191 /// encountering the closing brace right after the nested block. Now, if we
1192 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1193 /// \c false), the entire block has to be kept on the same line (which is only
1194 /// possible if it fits on the line, only contains a single statement, etc.
1195 ///
1196 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1197 /// break after the "{", format all lines with correct indentation and the put
1198 /// the closing "}" on yet another new line.
1199 ///
1200 /// This enables us to keep the simple structure of the
1201 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1202 /// break or don't break.
1203 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1204 unsigned &Penalty) {
1205 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1206 bool HasLBrace = LBrace && LBrace->is(tok::l_brace) && LBrace->is(BK_Block);
1207 FormatToken &Previous = *State.NextToken->Previous;
1208 if (Previous.Children.empty() || (!HasLBrace && !LBrace->MacroParent)) {
1209 // The previous token does not open a block. Nothing to do. We don't
1210 // assert so that we can simply call this function for all tokens.
1211 return true;
1212 }
1213
1214 if (NewLine || Previous.MacroParent) {
1215 const ParenState &P = State.Stack.back();
1216
1217 int AdditionalIndent =
1218 P.Indent.Total - Previous.Children[0]->Level * Style.IndentWidth;
1219 Penalty +=
1220 BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
1221 /*FixBadIndentation=*/true);
1222 return true;
1223 }
1224
1225 if (Previous.Children[0]->First->MustBreakBefore)
1226 return false;
1227
1228 // Cannot merge into one line if this line ends on a comment.
1229 if (Previous.is(tok::comment))
1230 return false;
1231
1232 // Cannot merge multiple statements into a single line.
1233 if (Previous.Children.size() > 1)
1234 return false;
1235
1236 const AnnotatedLine *Child = Previous.Children[0];
1237 // We can't put the closing "}" on a line with a trailing comment.
1238 if (Child->Last->isTrailingComment())
1239 return false;
1240
1241 // If the child line exceeds the column limit, we wouldn't want to merge it.
1242 // We add +2 for the trailing " }".
1243 if (Style.ColumnLimit > 0 &&
1244 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit) {
1245 return false;
1246 }
1247
1248 if (!DryRun) {
1249 Whitespaces->replaceWhitespace(
1250 *Child->First, /*Newlines=*/0, /*Spaces=*/1,
1251 /*StartOfTokenColumn=*/State.Column, /*AlignedTo=*/nullptr,
1252 State.Line->InPPDirective);
1253 }
1254 Penalty +=
1255 formatLine(*Child, State.Column + 1, /*FirstStartColumn=*/0, DryRun);
1256 if (!DryRun)
1257 markFinalized(Child->First);
1258
1259 State.Column += 1 + Child->Last->TotalLength;
1260 return true;
1261 }
1262
1263 ContinuationIndenter *Indenter;
1264
1265private:
1266 WhitespaceManager *Whitespaces;
1267 const FormatStyle &Style;
1268 UnwrappedLineFormatter *BlockFormatter;
1269};
1270
1271/// Formatter that keeps the existing line breaks.
1272class NoColumnLimitLineFormatter : public LineFormatter {
1273public:
1274 NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
1275 WhitespaceManager *Whitespaces,
1276 const FormatStyle &Style,
1277 UnwrappedLineFormatter *BlockFormatter)
1278 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1279
1280 /// Formats the line, simply keeping all of the input's line breaking
1281 /// decisions.
1282 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1283 unsigned FirstStartColumn, bool DryRun) override {
1284 assert(!DryRun);
1285 LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
1286 &Line, /*DryRun=*/false);
1287 while (State.NextToken) {
1288 bool Newline =
1289 Indenter->mustBreak(State) ||
1290 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
1291 unsigned Penalty = 0;
1292 formatChildren(State, Newline, /*DryRun=*/false, Penalty);
1293 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
1294 }
1295 return 0;
1296 }
1297};
1298
1299/// Formatter that puts all tokens into a single line without breaks.
1300class NoLineBreakFormatter : public LineFormatter {
1301public:
1302 NoLineBreakFormatter(ContinuationIndenter *Indenter,
1303 WhitespaceManager *Whitespaces, const FormatStyle &Style,
1304 UnwrappedLineFormatter *BlockFormatter)
1305 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1306
1307 /// Puts all tokens into a single line.
1308 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1309 unsigned FirstStartColumn, bool DryRun) override {
1310 unsigned Penalty = 0;
1311 LineState State =
1312 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
1313 while (State.NextToken) {
1314 formatChildren(State, /*NewLine=*/false, DryRun, Penalty);
1315 Indenter->addTokenToState(
1316 State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun);
1317 }
1318 return Penalty;
1319 }
1320};
1321
1322/// Finds the best way to break lines.
1323class OptimizingLineFormatter : public LineFormatter {
1324public:
1325 OptimizingLineFormatter(ContinuationIndenter *Indenter,
1326 WhitespaceManager *Whitespaces,
1327 const FormatStyle &Style,
1328 UnwrappedLineFormatter *BlockFormatter)
1329 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1330
1331 /// Formats the line by finding the best line breaks with line lengths
1332 /// below the column limit.
1333 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1334 unsigned FirstStartColumn, bool DryRun) override {
1335 LineState State =
1336 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
1337
1338 // If the ObjC method declaration does not fit on a line, we should format
1339 // it with one arg per line.
1340 if (State.Line->Type == LT_ObjCMethodDecl)
1341 State.Stack.back().BreakBeforeParameter = true;
1342
1343 // Find best solution in solution space.
1344 return analyzeSolutionSpace(State, DryRun);
1345 }
1346
1347private:
1348 struct CompareLineStatePointers {
1349 bool operator()(LineState *obj1, LineState *obj2) const {
1350 return *obj1 < *obj2;
1351 }
1352 };
1353
1354 /// A pair of <penalty, count> that is used to prioritize the BFS on.
1355 ///
1356 /// In case of equal penalties, we want to prefer states that were inserted
1357 /// first. During state generation we make sure that we insert states first
1358 /// that break the line as late as possible.
1359 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1360
1361 /// An edge in the solution space from \c Previous->State to \c State,
1362 /// inserting a newline dependent on the \c NewLine.
1363 struct StateNode {
1364 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
1365 : State(State), NewLine(NewLine), Previous(Previous) {}
1366 LineState State;
1367 bool NewLine;
1368 StateNode *Previous;
1369 };
1370
1371 /// An item in the prioritized BFS search queue. The \c StateNode's
1372 /// \c State has the given \c OrderedPenalty.
1373 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1374
1375 /// The BFS queue type.
1376 typedef std::priority_queue<QueueItem, SmallVector<QueueItem>,
1377 std::greater<QueueItem>>
1378 QueueType;
1379
1380 /// Analyze the entire solution space starting from \p InitialState.
1381 ///
1382 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1383 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1384 /// find the shortest path (the one with lowest penalty) from \p InitialState
1385 /// to a state where all tokens are placed. Returns the penalty.
1386 ///
1387 /// If \p DryRun is \c false, directly applies the changes.
1388 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
1389 std::set<LineState *, CompareLineStatePointers> Seen;
1390
1391 // Increasing count of \c StateNode items we have created. This is used to
1392 // create a deterministic order independent of the container.
1393 unsigned Count = 0;
1394 QueueType Queue;
1395
1396 // Insert start element into queue.
1397 StateNode *RootNode =
1398 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
1399 Queue.push(QueueItem(OrderedPenalty(0, Count), RootNode));
1400 ++Count;
1401
1402 unsigned Penalty = 0;
1403
1404 // While not empty, take first element and follow edges.
1405 while (!Queue.empty()) {
1406 // Quit if we still haven't found a solution by now.
1407 if (Count > 25'000'000)
1408 return 0;
1409
1410 Penalty = Queue.top().first.first;
1411 StateNode *Node = Queue.top().second;
1412 if (!Node->State.NextToken) {
1413 LLVM_DEBUG(llvm::dbgs()
1414 << "\n---\nPenalty for line: " << Penalty << "\n");
1415 break;
1416 }
1417 Queue.pop();
1418
1419 // Cut off the analysis of certain solutions if the analysis gets too
1420 // complex. See description of IgnoreStackForComparison.
1421 if (Count > 50'000)
1422 Node->State.IgnoreStackForComparison = true;
1423
1424 if (!Seen.insert(&Node->State).second) {
1425 // State already examined with lower penalty.
1426 continue;
1427 }
1428
1429 FormatDecision LastFormat = Node->State.NextToken->getDecision();
1430 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
1431 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
1432 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
1433 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
1434 }
1435
1436 if (Queue.empty()) {
1437 // We were unable to find a solution, do nothing.
1438 // FIXME: Add diagnostic?
1439 LLVM_DEBUG(llvm::dbgs() << "Could not find a solution.\n");
1440 return 0;
1441 }
1442
1443 // Reconstruct the solution.
1444 if (!DryRun)
1445 reconstructPath(InitialState, Queue.top().second);
1446
1447 LLVM_DEBUG(llvm::dbgs()
1448 << "Total number of analyzed states: " << Count << "\n");
1449 LLVM_DEBUG(llvm::dbgs() << "---\n");
1450
1451 return Penalty;
1452 }
1453
1454 /// Add the following state to the analysis queue \c Queue.
1455 ///
1456 /// Assume the current state is \p PreviousNode and has been reached with a
1457 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
1458 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1459 bool NewLine, unsigned *Count, QueueType *Queue) {
1460 if (NewLine && !Indenter->canBreak(PreviousNode->State))
1461 return;
1462 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
1463 return;
1464
1465 StateNode *Node = new (Allocator.Allocate())
1466 StateNode(PreviousNode->State, NewLine, PreviousNode);
1467 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1468 return;
1469
1470 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
1471
1472 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1473 ++(*Count);
1474 }
1475
1476 /// Applies the best formatting by reconstructing the path in the
1477 /// solution space that leads to \c Best.
1478 void reconstructPath(LineState &State, StateNode *Best) {
1480 // We do not need a break before the initial token.
1481 while (Best->Previous) {
1482 Path.push_back(Best);
1483 Best = Best->Previous;
1484 }
1485 for (const auto &Node : llvm::reverse(Path)) {
1486 unsigned Penalty = 0;
1487 formatChildren(State, Node->NewLine, /*DryRun=*/false, Penalty);
1488 Penalty += Indenter->addTokenToState(State, Node->NewLine, false);
1489
1490 LLVM_DEBUG({
1491 printLineState(Node->Previous->State);
1492 if (Node->NewLine) {
1493 llvm::dbgs() << "Penalty for placing "
1494 << Node->Previous->State.NextToken->Tok.getName()
1495 << " on a new line: " << Penalty << "\n";
1496 }
1497 });
1498 }
1499 }
1500
1501 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1502};
1503
1504} // anonymous namespace
1505
1507 const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
1508 int AdditionalIndent, bool FixBadIndentation, unsigned FirstStartColumn,
1509 unsigned NextStartColumn, unsigned LastStartColumn) {
1510 LineJoiner Joiner(Style, Keywords, Lines);
1511
1512 // Try to look up already computed penalty in DryRun-mode.
1513 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
1514 &Lines, AdditionalIndent);
1515 auto CacheIt = PenaltyCache.find(CacheKey);
1516 if (DryRun && CacheIt != PenaltyCache.end())
1517 return CacheIt->second;
1518
1519 assert(!Lines.empty());
1520 unsigned Penalty = 0;
1521 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
1522 AdditionalIndent);
1523 const AnnotatedLine *PrevPrevLine = nullptr;
1524 const AnnotatedLine *PreviousLine = nullptr;
1525 const AnnotatedLine *NextLine = nullptr;
1526
1527 // The minimum level of consecutive lines that have been formatted.
1528 unsigned RangeMinLevel = UINT_MAX;
1529
1530 bool FirstLine = true;
1531 for (const AnnotatedLine *Line =
1532 Joiner.getNextMergedLine(DryRun, IndentTracker);
1533 Line; PrevPrevLine = PreviousLine, PreviousLine = Line, Line = NextLine,
1534 FirstLine = false) {
1535 assert(Line->First);
1536 const AnnotatedLine &TheLine = *Line;
1537 unsigned Indent = IndentTracker.getIndent();
1538
1539 // We continue formatting unchanged lines to adjust their indent, e.g. if a
1540 // scope was added. However, we need to carefully stop doing this when we
1541 // exit the scope of affected lines to prevent indenting the entire
1542 // remaining file if it currently missing a closing brace.
1543 bool PreviousRBrace =
1544 PreviousLine && PreviousLine->startsWith(tok::r_brace);
1545 bool ContinueFormatting =
1546 TheLine.Level > RangeMinLevel ||
1547 (TheLine.Level == RangeMinLevel && !PreviousRBrace &&
1548 !TheLine.startsWith(TT_NamespaceRBrace));
1549
1550 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
1551 Indent != TheLine.First->OriginalColumn;
1552 bool ShouldFormat = TheLine.Affected || FixIndentation;
1553 // We cannot format this line; if the reason is that the line had a
1554 // parsing error, remember that.
1555 if (ShouldFormat && TheLine.Type == LT_Invalid && Status) {
1556 Status->FormatComplete = false;
1557 Status->Line =
1558 SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation());
1559 }
1560
1561 if (ShouldFormat && TheLine.Type != LT_Invalid) {
1562 if (!DryRun) {
1563 bool LastLine = TheLine.First->is(tok::eof);
1564 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines, Indent,
1565 LastLine ? LastStartColumn : NextStartColumn + Indent);
1566 }
1567
1568 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1569 unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
1570 bool FitsIntoOneLine =
1571 !TheLine.ContainsMacroCall &&
1572 (TheLine.Last->TotalLength + Indent <= ColumnLimit ||
1573 (TheLine.Type == LT_ImportStatement &&
1574 (!Style.isJavaScript() || !Style.JavaScriptWrapImports)) ||
1575 (Style.isCSharp() &&
1576 TheLine.InPPDirective)); // don't split #regions in C#
1577 if (Style.ColumnLimit == 0) {
1578 NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
1579 .formatLine(TheLine, NextStartColumn + Indent,
1580 FirstLine ? FirstStartColumn : 0, DryRun);
1581 } else if (FitsIntoOneLine) {
1582 Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
1583 .formatLine(TheLine, NextStartColumn + Indent,
1584 FirstLine ? FirstStartColumn : 0, DryRun);
1585 } else {
1586 Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
1587 .formatLine(TheLine, NextStartColumn + Indent,
1588 FirstLine ? FirstStartColumn : 0, DryRun);
1589 }
1590 RangeMinLevel = std::min(RangeMinLevel, TheLine.Level);
1591 } else {
1592 // If no token in the current line is affected, we still need to format
1593 // affected children.
1594 if (TheLine.ChildrenAffected) {
1595 for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next)
1596 if (!Tok->Children.empty())
1597 format(Tok->Children, DryRun);
1598 }
1599
1600 // Adapt following lines on the current indent level to the same level
1601 // unless the current \c AnnotatedLine is not at the beginning of a line.
1602 bool StartsNewLine =
1603 TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
1604 if (StartsNewLine)
1605 IndentTracker.adjustToUnmodifiedLine(TheLine);
1606 if (!DryRun) {
1607 bool ReformatLeadingWhitespace =
1608 StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
1610 // Format the first token.
1611 if (ReformatLeadingWhitespace) {
1612 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines,
1613 TheLine.First->OriginalColumn,
1614 TheLine.First->OriginalColumn);
1615 } else {
1616 Whitespaces->addUntouchableToken(*TheLine.First,
1617 TheLine.InPPDirective);
1618 }
1619
1620 // Notify the WhitespaceManager about the unchanged whitespace.
1621 for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
1622 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
1623 }
1624 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1625 RangeMinLevel = UINT_MAX;
1626 }
1627 if (!DryRun)
1628 markFinalized(TheLine.First);
1629 }
1630 PenaltyCache[CacheKey] = Penalty;
1631 return Penalty;
1632}
1633
1635 const AnnotatedLine *PreviousLine,
1636 const AnnotatedLine *PrevPrevLine,
1638 const FormatStyle &Style) {
1639 const auto &RootToken = *Line.First;
1640 auto Newlines =
1641 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1642 // Remove empty lines before "}" where applicable.
1643 if (RootToken.is(tok::r_brace) &&
1644 (!RootToken.Next ||
1645 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)) &&
1646 // Do not remove empty lines before namespace closing "}".
1647 !getNamespaceToken(&Line, Lines)) {
1648 Newlines = std::min(Newlines, 1u);
1649 }
1650 // Remove empty lines at the start of nested blocks (lambdas/arrow functions)
1651 if (!PreviousLine && Line.Level > 0)
1652 Newlines = std::min(Newlines, 1u);
1653 if (Newlines == 0 && !RootToken.IsFirst)
1654 Newlines = 1;
1655 if (RootToken.IsFirst &&
1656 (!Style.KeepEmptyLines.AtStartOfFile || !RootToken.HasUnescapedNewline)) {
1657 Newlines = 0;
1658 }
1659
1660 // Remove empty lines after "{".
1661 if (!Style.KeepEmptyLines.AtStartOfBlock && PreviousLine &&
1662 PreviousLine->Last->is(tok::l_brace) &&
1663 !PreviousLine->startsWithNamespace() &&
1664 !(PrevPrevLine && PrevPrevLine->startsWithNamespace() &&
1665 PreviousLine->startsWith(tok::l_brace)) &&
1666 !startsExternCBlock(*PreviousLine)) {
1667 Newlines = 1;
1668 }
1669
1670 if (Style.WrapNamespaceBodyWithEmptyLines != FormatStyle::WNBWELS_Leave) {
1671 // Modify empty lines after TT_NamespaceLBrace.
1672 if (PreviousLine && PreviousLine->endsWith(TT_NamespaceLBrace)) {
1673 if (Style.WrapNamespaceBodyWithEmptyLines == FormatStyle::WNBWELS_Never)
1674 Newlines = 1;
1675 else if (!Line.startsWithNamespace())
1676 Newlines = std::max(Newlines, 2u);
1677 }
1678 // Modify empty lines before TT_NamespaceRBrace.
1679 if (Line.startsWith(TT_NamespaceRBrace)) {
1680 if (Style.WrapNamespaceBodyWithEmptyLines == FormatStyle::WNBWELS_Never)
1681 Newlines = 1;
1682 else if (!PreviousLine->startsWith(TT_NamespaceRBrace))
1683 Newlines = std::max(Newlines, 2u);
1684 }
1685 }
1686
1687 // Insert or remove empty line before access specifiers.
1688 if (PreviousLine && RootToken.isAccessSpecifier()) {
1689 switch (Style.EmptyLineBeforeAccessModifier) {
1691 if (Newlines > 1)
1692 Newlines = 1;
1693 break;
1695 Newlines = std::max(RootToken.NewlinesBefore, 1u);
1696 break;
1698 if (PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) && Newlines <= 1)
1699 Newlines = 2;
1700 if (PreviousLine->First->isAccessSpecifier())
1701 Newlines = 1; // Previous is an access modifier remove all new lines.
1702 break;
1704 const FormatToken *previousToken;
1705 if (PreviousLine->Last->is(tok::comment))
1706 previousToken = PreviousLine->Last->getPreviousNonComment();
1707 else
1708 previousToken = PreviousLine->Last;
1709 if ((!previousToken || previousToken->isNot(tok::l_brace)) &&
1710 Newlines <= 1) {
1711 Newlines = 2;
1712 }
1713 } break;
1714 }
1715 }
1716
1717 // Insert or remove empty line after access specifiers.
1718 if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
1719 (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline)) {
1720 // EmptyLineBeforeAccessModifier is handling the case when two access
1721 // modifiers follow each other.
1722 if (!RootToken.isAccessSpecifier()) {
1723 switch (Style.EmptyLineAfterAccessModifier) {
1725 Newlines = 1;
1726 break;
1728 Newlines = std::max(Newlines, 1u);
1729 break;
1731 if (RootToken.is(tok::r_brace)) // Do not add at end of class.
1732 Newlines = 1u;
1733 else
1734 Newlines = std::max(Newlines, 2u);
1735 break;
1736 }
1737 }
1738 }
1739
1740 return Newlines;
1741}
1742
1743void UnwrappedLineFormatter::formatFirstToken(
1744 const AnnotatedLine &Line, const AnnotatedLine *PreviousLine,
1745 const AnnotatedLine *PrevPrevLine,
1746 const SmallVectorImpl<AnnotatedLine *> &Lines, unsigned Indent,
1747 unsigned NewlineIndent) {
1748 FormatToken &RootToken = *Line.First;
1749 if (RootToken.is(tok::eof)) {
1750 unsigned Newlines = std::min(
1751 RootToken.NewlinesBefore,
1752 Style.KeepEmptyLines.AtEndOfFile ? Style.MaxEmptyLinesToKeep + 1 : 1);
1753 unsigned TokenIndent = Newlines ? NewlineIndent : 0;
1754 Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
1755 TokenIndent);
1756 return;
1757 }
1758
1759 if (RootToken.Newlines < 0) {
1760 RootToken.Newlines =
1761 computeNewlines(Line, PreviousLine, PrevPrevLine, Lines, Style);
1762 assert(RootToken.Newlines >= 0);
1763 }
1764
1765 if (RootToken.Newlines > 0)
1766 Indent = NewlineIndent;
1767
1768 // Preprocessor directives get indented before the hash only if specified. In
1769 // Javascript import statements are indented like normal statements.
1770 if (!Style.isJavaScript() &&
1771 Style.IndentPPDirectives < FormatStyle::PPDIS_BeforeHash &&
1772 (Line.Type == LT_PreprocessorDirective ||
1773 Line.Type == LT_ImportStatement)) {
1774 Indent = 0;
1775 }
1776
1777 Whitespaces->replaceWhitespace(RootToken, RootToken.Newlines, Indent, Indent,
1778 /*AlignedTo=*/nullptr,
1779 Line.InPPDirective &&
1780 !RootToken.HasUnescapedNewline);
1781}
1782
1783unsigned
1784UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
1785 const AnnotatedLine *NextLine) const {
1786 // In preprocessor directives reserve two chars for trailing " \" if the
1787 // next line continues the preprocessor directive.
1788 bool ContinuesPPDirective =
1789 InPPDirective &&
1790 // If there is no next line, this is likely a child line and the parent
1791 // continues the preprocessor directive.
1792 (!NextLine ||
1793 (NextLine->InPPDirective &&
1794 // If there is an unescaped newline between this line and the next, the
1795 // next line starts a new preprocessor directive.
1796 !NextLine->First->HasUnescapedNewline));
1797 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
1798}
1799
1800} // namespace format
1801} // namespace clang
This file contains the declaration of the FormatToken, a wrapper around Token with additional informa...
int Newlines
The number of newlines immediately before the Token after formatting.
FormatToken()
Token Tok
The Token.
unsigned TotalLength
The total length of the unwrapped line up to and including this token.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
This file declares NamespaceEndCommentsFixer, a TokenAnalyzer that fixes namespace end comments.
Implements a combinatorial exploration of all the different linebreaks unwrapped lines can be formatt...
WhitespaceManager class manages whitespace around tokens and their replacements.
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition Token.h:142
bool LeadingEmptyLinesAffected
True if the leading empty lines of this line intersect with one of the input ranges.
bool Affected
True if this line should be formatted, i.e.
bool ContainsMacroCall
True if this line contains a macro call for which an expansion exists.
bool ChildrenAffected
True if one of this line's children intersects with an input range.
bool startsWithNamespace() const
true if this line starts a namespace definition.
bool endsWith(Ts... Tokens) const
true if this line ends with the given tokens in reversed order, ignoring comments.
bool startsWith(Ts... Tokens) const
true if this line starts with the given tokens in order, ignoring comments.
unsigned format(const SmallVectorImpl< AnnotatedLine * > &Lines, bool DryRun=false, int AdditionalIndent=0, bool FixBadIndentation=false, unsigned FirstStartColumn=0, unsigned NextStartColumn=0, unsigned LastStartColumn=0)
Format the current block and return the penalty.
void replaceWhitespace(FormatToken &Tok, unsigned Newlines, unsigned Spaces, unsigned StartOfTokenColumn, const FormatToken *AlignedTo=nullptr, bool InPPDirective=false, unsigned IndentedFromColumn=0)
Replaces the whitespace in front of Tok.
#define UINT_MAX
Definition limits.h:64
const FormatToken * getNamespaceToken() const
Return the actual namespace token, if this token starts a namespace block.
@ MR_UnexpandedArg
The token is part of a macro argument that was previously formatted as expansion when formatting the ...
@ MR_ExpandedArg
The token was expanded from a macro argument when formatting the expanded token sequence.
static auto computeNewlines(const AnnotatedLine &Line, const AnnotatedLine *PreviousLine, const AnnotatedLine *PrevPrevLine, const SmallVectorImpl< AnnotatedLine * > &Lines, const FormatStyle &Style)
StringRef getNamespaceTokenText(const AnnotatedLine *Line, const SmallVectorImpl< AnnotatedLine * > &AnnotatedLines)
Top level wrappers for InstallAPI frontend operations.
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition JsonSupport.h:21
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition Format.h:56
@ SRS_Always
Merge all records that fit on a single line.
Definition Format.h:1094
@ SRS_Never
Never merge records into a single line.
Definition Format.h:1076
@ PPDIS_Leave
Leaves indentation of directives as-is.
Definition Format.h:3384
@ PPDIS_BeforeHash
Indents directives before the hash.
Definition Format.h:3372
@ PPDIS_None
Does not indent any directives.
Definition Format.h:3354
@ SBS_Always
Always merge short blocks into a single line.
Definition Format.h:765
@ SBS_Empty
Only merge empty blocks.
Definition Format.h:759
@ SBS_Never
Never merge blocks into a single line.
Definition Format.h:751
@ SIS_WithoutElse
Put short ifs on the same line only if there is no else statement.
Definition Format.h:992
@ SIS_AllIfsAndElse
Always put short ifs, else ifs and else statements on the same line.
Definition Format.h:1022
@ BWACS_Always
Always wrap braces after a control statement.
Definition Format.h:1420
@ BWACS_MultiLine
Only wrap braces after a multi-line control statement.
Definition Format.h:1410
@ BS_Whitesmiths
Like Allman but always indent braces and line up code with braces.
Definition Format.h:2230
@ SIEB_Never
Never insert a space in empty braces.
Definition Format.h:5552
@ IGLS_HalfIndent
Indent goto labels to half the indentation of the surrounding code.
Definition Format.h:3337
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition Format.h:56
@ ELBAMS_LogicalBlock
Add empty line only when access modifier starts a new logical block.
Definition Format.h:3032
@ ELBAMS_Never
Remove all empty lines before access modifiers.
Definition Format.h:3012
@ ELBAMS_Always
Always add empty line before access modifiers unless access modifier is at the start of struct or cla...
Definition Format.h:3052
@ ELBAMS_Leave
Keep existing empty lines before access modifiers.
Definition Format.h:3014
@ PPDIS_BeforeHash
Indents directives before the hash.
Definition Format.h:3372
@ WNBWELS_Leave
Keep existing newlines at the beginning and the end of namespace body.
Definition Format.h:6086
@ WNBWELS_Never
Remove all empty lines at the beginning and the end of namespace body.
Definition Format.h:6070
@ ELAAMS_Always
Always add empty line after access modifiers if there are none.
Definition Format.h:2987
@ ELAAMS_Never
Remove all empty lines after access modifiers.
Definition Format.h:2963
@ ELAAMS_Leave
Keep existing empty lines after access modifiers.
Definition Format.h:2966
A wrapper around a Token storing information about the whitespace characters preceding it.
unsigned OriginalColumn
The original 0-based column of this token, including expanded tabs.
bool isNot(T Kind) const
FormatToken * Next
The next token in the unwrapped line.
unsigned NewlinesBefore
The number of newlines immediately before the Token.
bool is(tok::TokenKind Kind) const
unsigned TotalLength
The total length of the unwrapped line up to and including this token.
bool isOneOf(A K1, B K2) const
unsigned IsFirst
Indicates that this is the first token of the file.