clang 23.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 = [this, &I, &NextLine, PreviousLine,
318 TheLine]() {
319 if (Style.AllowShortFunctionsOnASingleLine.isAll())
320 return true;
321
322 if (Style.AllowShortFunctionsOnASingleLine.Empty &&
323 NextLine.First->is(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_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(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(*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 ==
458 FormatStyle::BWACS_Always
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 ==
570 FormatStyle::SIS_AllIfsAndElse))) {
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) {
616 case FormatStyle::SRS_Never:
617 return false;
618 case FormatStyle::SRS_Always:
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 ==
763 FormatStyle::BWACS_Always &&
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 ==
790 FormatStyle::SIS_WithoutElse) {
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 ==
909 FormatStyle::BWACS_Always &&
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 ==
924 FormatStyle::BWACS_Always &&
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 any braces - if it
987 // does, readability declines when putting it into a single line.
988 if (I[1]->Last->is(TT_LineComment))
989 return 0;
990 do {
991 if (Tok->isOneOf(tok::l_brace, tok::r_brace) &&
992 Tok->isNot(BK_BracedInit)) {
993 return 0;
994 }
995 Tok = Tok->Next;
996 } while (Tok);
997
998 // Last, check that the third line starts with a closing brace.
999 Tok = I[2]->First;
1000 if (Tok->isNot(tok::r_brace))
1001 return 0;
1002
1003 // Don't merge "if (a) { .. } else {".
1004 if (Tok->Next && Tok->Next->is(tok::kw_else))
1005 return 0;
1006
1007 // Don't merge a trailing multi-line control statement block like:
1008 // } else if (foo &&
1009 // bar)
1010 // { <-- current Line
1011 // baz();
1012 // }
1013 if (Line.First == Line.Last &&
1014 Line.First->is(TT_ControlStatementLBrace) &&
1015 Style.BraceWrapping.AfterControlStatement ==
1016 FormatStyle::BWACS_MultiLine) {
1017 return 0;
1018 }
1019
1020 return 2;
1021 }
1022 } else if (I[1]->First->is(tok::l_brace)) {
1023 if (I[1]->Last->is(TT_LineComment))
1024 return 0;
1025
1026 // Check for Limit <= 2 to account for the " {".
1027 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
1028 return 0;
1029 Limit -= 2;
1030 unsigned MergedLines = 0;
1031
1032 auto TryMergeBlock = [&] {
1033 if (Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never ||
1034 Style.AllowShortRecordOnASingleLine == FormatStyle::SRS_Always) {
1035 return true;
1036 }
1037 return I[1]->First == I[1]->Last && I + 2 != E &&
1038 I[2]->First->is(tok::r_brace);
1039 };
1040
1041 if (TryMergeBlock()) {
1042 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
1043 // If we managed to merge the block, count the statement header, which
1044 // is on a separate line.
1045 if (MergedLines > 0)
1046 ++MergedLines;
1047 }
1048 return MergedLines;
1049 }
1050 return 0;
1051 }
1052
1053 /// Returns the modified column limit for \p I if it is inside a macro and
1054 /// needs a trailing '\'.
1055 unsigned limitConsideringMacros(ArrayRef<AnnotatedLine *>::const_iterator I,
1057 unsigned Limit) {
1058 if (I[0]->InPPDirective && I + 1 != E &&
1059 !I[1]->First->HasUnescapedNewline && I[1]->First->isNot(tok::eof)) {
1060 return Limit < 2 ? 0 : Limit - 2;
1061 }
1062 return Limit;
1063 }
1064
1065 bool nextTwoLinesFitInto(ArrayRef<AnnotatedLine *>::const_iterator I,
1066 unsigned Limit) {
1067 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
1068 return false;
1069 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
1070 }
1071
1072 bool nextNLinesFitInto(ArrayRef<AnnotatedLine *>::const_iterator I,
1074 unsigned Limit) {
1075 unsigned JoinedLength = 0;
1076 for (const auto *J = I + 1; J != E; ++J) {
1077 if ((*J)->First->MustBreakBefore)
1078 return false;
1079
1080 JoinedLength += 1 + (*J)->Last->TotalLength;
1081 if (JoinedLength > Limit)
1082 return false;
1083 }
1084 return true;
1085 }
1086
1087 bool containsMustBreak(const AnnotatedLine *Line) {
1088 assert(Line->First);
1089 // Ignore the first token, because in this situation, it applies more to the
1090 // last token of the previous line.
1091 for (const FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next)
1092 if (Tok->MustBreakBefore)
1093 return true;
1094 return false;
1095 }
1096
1097 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1098 assert(!A.Last->Next);
1099 assert(!B.First->Previous);
1100 if (B.Affected || B.LeadingEmptyLinesAffected) {
1101 assert(B.Affected || A.Last->Children.empty());
1102 A.Affected = true;
1103 }
1104 A.Last->Next = B.First;
1105 B.First->Previous = A.Last;
1106 B.First->CanBreakBefore = true;
1107 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1108 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1109 Tok->TotalLength += LengthA;
1110 A.Last = Tok;
1111 }
1112 }
1113
1114 const FormatStyle &Style;
1115 const AdditionalKeywords &Keywords;
1117
1119 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
1120};
1121
1122static void markFinalized(FormatToken *Tok) {
1123 if (Tok->is(tok::hash) && !Tok->Previous && Tok->Next &&
1124 Tok->Next->isOneOf(tok::pp_if, tok::pp_ifdef, tok::pp_ifndef,
1125 tok::pp_elif, tok::pp_elifdef, tok::pp_elifndef,
1126 tok::pp_else, tok::pp_endif)) {
1127 Tok = Tok->Next;
1128 }
1129 for (; Tok; Tok = Tok->Next) {
1130 if (Tok->MacroCtx && Tok->MacroCtx->Role == MR_ExpandedArg) {
1131 // In the first pass we format all macro arguments in the expanded token
1132 // stream. Instead of finalizing the macro arguments, we mark that they
1133 // will be modified as unexpanded arguments (as part of the macro call
1134 // formatting) in the next pass.
1135 Tok->MacroCtx->Role = MR_UnexpandedArg;
1136 // Reset whether spaces or a line break are required before this token, as
1137 // that is context dependent, and that context may change when formatting
1138 // the macro call. For example, given M(x) -> 2 * x, and the macro call
1139 // M(var), the token 'var' will have SpacesRequiredBefore = 1 after being
1140 // formatted as part of the expanded macro, but SpacesRequiredBefore = 0
1141 // for its position within the macro call.
1142 Tok->SpacesRequiredBefore = 0;
1143 if (!Tok->MustBreakBeforeFinalized)
1144 Tok->MustBreakBefore = 0;
1145 } else {
1146 Tok->Finalized = true;
1147 }
1148 }
1149}
1150
1151#ifndef NDEBUG
1152static void printLineState(const LineState &State) {
1153 llvm::dbgs() << "State: ";
1154 for (const ParenState &P : State.Stack) {
1155 llvm::dbgs() << (P.Tok ? P.Tok->TokenText : "F") << "|" << P.Indent.Total
1156 << "|" << P.LastSpace << "|" << P.NestedBlockIndent << " ";
1157 }
1158 llvm::dbgs() << State.NextToken->TokenText << "\n";
1159}
1160#endif
1161
1162/// Base class for classes that format one \c AnnotatedLine.
1163class LineFormatter {
1164public:
1165 LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
1166 const FormatStyle &Style,
1167 UnwrappedLineFormatter *BlockFormatter)
1168 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
1169 BlockFormatter(BlockFormatter) {}
1170 virtual ~LineFormatter() {}
1171
1172 /// Formats an \c AnnotatedLine and returns the penalty.
1173 ///
1174 /// If \p DryRun is \c false, directly applies the changes.
1175 virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1176 unsigned FirstStartColumn, bool DryRun) = 0;
1177
1178protected:
1179 /// If the \p State's next token is an r_brace closing a nested block,
1180 /// format the nested block before it.
1181 ///
1182 /// Returns \c true if all children could be placed successfully and adapts
1183 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1184 /// creates changes using \c Whitespaces.
1185 ///
1186 /// The crucial idea here is that children always get formatted upon
1187 /// encountering the closing brace right after the nested block. Now, if we
1188 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1189 /// \c false), the entire block has to be kept on the same line (which is only
1190 /// possible if it fits on the line, only contains a single statement, etc.
1191 ///
1192 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1193 /// break after the "{", format all lines with correct indentation and the put
1194 /// the closing "}" on yet another new line.
1195 ///
1196 /// This enables us to keep the simple structure of the
1197 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1198 /// break or don't break.
1199 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1200 unsigned &Penalty) {
1201 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1202 bool HasLBrace = LBrace && LBrace->is(tok::l_brace) && LBrace->is(BK_Block);
1203 FormatToken &Previous = *State.NextToken->Previous;
1204 if (Previous.Children.empty() || (!HasLBrace && !LBrace->MacroParent)) {
1205 // The previous token does not open a block. Nothing to do. We don't
1206 // assert so that we can simply call this function for all tokens.
1207 return true;
1208 }
1209
1210 if (NewLine || Previous.MacroParent) {
1211 const ParenState &P = State.Stack.back();
1212
1213 int AdditionalIndent =
1214 P.Indent.Total - Previous.Children[0]->Level * Style.IndentWidth;
1215 Penalty +=
1216 BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
1217 /*FixBadIndentation=*/true);
1218 return true;
1219 }
1220
1221 if (Previous.Children[0]->First->MustBreakBefore)
1222 return false;
1223
1224 // Cannot merge into one line if this line ends on a comment.
1225 if (Previous.is(tok::comment))
1226 return false;
1227
1228 // Cannot merge multiple statements into a single line.
1229 if (Previous.Children.size() > 1)
1230 return false;
1231
1232 const AnnotatedLine *Child = Previous.Children[0];
1233 // We can't put the closing "}" on a line with a trailing comment.
1234 if (Child->Last->isTrailingComment())
1235 return false;
1236
1237 // If the child line exceeds the column limit, we wouldn't want to merge it.
1238 // We add +2 for the trailing " }".
1239 if (Style.ColumnLimit > 0 &&
1240 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit) {
1241 return false;
1242 }
1243
1244 if (!DryRun) {
1245 Whitespaces->replaceWhitespace(
1246 *Child->First, /*Newlines=*/0, /*Spaces=*/1,
1247 /*StartOfTokenColumn=*/State.Column, /*IsAligned=*/false,
1248 State.Line->InPPDirective);
1249 }
1250 Penalty +=
1251 formatLine(*Child, State.Column + 1, /*FirstStartColumn=*/0, DryRun);
1252 if (!DryRun)
1253 markFinalized(Child->First);
1254
1255 State.Column += 1 + Child->Last->TotalLength;
1256 return true;
1257 }
1258
1259 ContinuationIndenter *Indenter;
1260
1261private:
1262 WhitespaceManager *Whitespaces;
1263 const FormatStyle &Style;
1264 UnwrappedLineFormatter *BlockFormatter;
1265};
1266
1267/// Formatter that keeps the existing line breaks.
1268class NoColumnLimitLineFormatter : public LineFormatter {
1269public:
1270 NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
1271 WhitespaceManager *Whitespaces,
1272 const FormatStyle &Style,
1273 UnwrappedLineFormatter *BlockFormatter)
1274 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1275
1276 /// Formats the line, simply keeping all of the input's line breaking
1277 /// decisions.
1278 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1279 unsigned FirstStartColumn, bool DryRun) override {
1280 assert(!DryRun);
1281 LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
1282 &Line, /*DryRun=*/false);
1283 while (State.NextToken) {
1284 bool Newline =
1285 Indenter->mustBreak(State) ||
1286 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
1287 unsigned Penalty = 0;
1288 formatChildren(State, Newline, /*DryRun=*/false, Penalty);
1289 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
1290 }
1291 return 0;
1292 }
1293};
1294
1295/// Formatter that puts all tokens into a single line without breaks.
1296class NoLineBreakFormatter : public LineFormatter {
1297public:
1298 NoLineBreakFormatter(ContinuationIndenter *Indenter,
1299 WhitespaceManager *Whitespaces, const FormatStyle &Style,
1300 UnwrappedLineFormatter *BlockFormatter)
1301 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1302
1303 /// Puts all tokens into a single line.
1304 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1305 unsigned FirstStartColumn, bool DryRun) override {
1306 unsigned Penalty = 0;
1307 LineState State =
1308 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
1309 while (State.NextToken) {
1310 formatChildren(State, /*NewLine=*/false, DryRun, Penalty);
1311 Indenter->addTokenToState(
1312 State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun);
1313 }
1314 return Penalty;
1315 }
1316};
1317
1318/// Finds the best way to break lines.
1319class OptimizingLineFormatter : public LineFormatter {
1320public:
1321 OptimizingLineFormatter(ContinuationIndenter *Indenter,
1322 WhitespaceManager *Whitespaces,
1323 const FormatStyle &Style,
1324 UnwrappedLineFormatter *BlockFormatter)
1325 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1326
1327 /// Formats the line by finding the best line breaks with line lengths
1328 /// below the column limit.
1329 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1330 unsigned FirstStartColumn, bool DryRun) override {
1331 LineState State =
1332 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
1333
1334 // If the ObjC method declaration does not fit on a line, we should format
1335 // it with one arg per line.
1336 if (State.Line->Type == LT_ObjCMethodDecl)
1337 State.Stack.back().BreakBeforeParameter = true;
1338
1339 // Find best solution in solution space.
1340 return analyzeSolutionSpace(State, DryRun);
1341 }
1342
1343private:
1344 struct CompareLineStatePointers {
1345 bool operator()(LineState *obj1, LineState *obj2) const {
1346 return *obj1 < *obj2;
1347 }
1348 };
1349
1350 /// A pair of <penalty, count> that is used to prioritize the BFS on.
1351 ///
1352 /// In case of equal penalties, we want to prefer states that were inserted
1353 /// first. During state generation we make sure that we insert states first
1354 /// that break the line as late as possible.
1355 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1356
1357 /// An edge in the solution space from \c Previous->State to \c State,
1358 /// inserting a newline dependent on the \c NewLine.
1359 struct StateNode {
1360 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
1361 : State(State), NewLine(NewLine), Previous(Previous) {}
1362 LineState State;
1363 bool NewLine;
1364 StateNode *Previous;
1365 };
1366
1367 /// An item in the prioritized BFS search queue. The \c StateNode's
1368 /// \c State has the given \c OrderedPenalty.
1369 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1370
1371 /// The BFS queue type.
1372 typedef std::priority_queue<QueueItem, SmallVector<QueueItem>,
1373 std::greater<QueueItem>>
1374 QueueType;
1375
1376 /// Analyze the entire solution space starting from \p InitialState.
1377 ///
1378 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1379 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1380 /// find the shortest path (the one with lowest penalty) from \p InitialState
1381 /// to a state where all tokens are placed. Returns the penalty.
1382 ///
1383 /// If \p DryRun is \c false, directly applies the changes.
1384 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
1385 std::set<LineState *, CompareLineStatePointers> Seen;
1386
1387 // Increasing count of \c StateNode items we have created. This is used to
1388 // create a deterministic order independent of the container.
1389 unsigned Count = 0;
1390 QueueType Queue;
1391
1392 // Insert start element into queue.
1393 StateNode *RootNode =
1394 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
1395 Queue.push(QueueItem(OrderedPenalty(0, Count), RootNode));
1396 ++Count;
1397
1398 unsigned Penalty = 0;
1399
1400 // While not empty, take first element and follow edges.
1401 while (!Queue.empty()) {
1402 // Quit if we still haven't found a solution by now.
1403 if (Count > 25'000'000)
1404 return 0;
1405
1406 Penalty = Queue.top().first.first;
1407 StateNode *Node = Queue.top().second;
1408 if (!Node->State.NextToken) {
1409 LLVM_DEBUG(llvm::dbgs()
1410 << "\n---\nPenalty for line: " << Penalty << "\n");
1411 break;
1412 }
1413 Queue.pop();
1414
1415 // Cut off the analysis of certain solutions if the analysis gets too
1416 // complex. See description of IgnoreStackForComparison.
1417 if (Count > 50'000)
1418 Node->State.IgnoreStackForComparison = true;
1419
1420 if (!Seen.insert(&Node->State).second) {
1421 // State already examined with lower penalty.
1422 continue;
1423 }
1424
1425 FormatDecision LastFormat = Node->State.NextToken->getDecision();
1426 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
1427 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
1428 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
1429 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
1430 }
1431
1432 if (Queue.empty()) {
1433 // We were unable to find a solution, do nothing.
1434 // FIXME: Add diagnostic?
1435 LLVM_DEBUG(llvm::dbgs() << "Could not find a solution.\n");
1436 return 0;
1437 }
1438
1439 // Reconstruct the solution.
1440 if (!DryRun)
1441 reconstructPath(InitialState, Queue.top().second);
1442
1443 LLVM_DEBUG(llvm::dbgs()
1444 << "Total number of analyzed states: " << Count << "\n");
1445 LLVM_DEBUG(llvm::dbgs() << "---\n");
1446
1447 return Penalty;
1448 }
1449
1450 /// Add the following state to the analysis queue \c Queue.
1451 ///
1452 /// Assume the current state is \p PreviousNode and has been reached with a
1453 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
1454 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1455 bool NewLine, unsigned *Count, QueueType *Queue) {
1456 if (NewLine && !Indenter->canBreak(PreviousNode->State))
1457 return;
1458 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
1459 return;
1460
1461 StateNode *Node = new (Allocator.Allocate())
1462 StateNode(PreviousNode->State, NewLine, PreviousNode);
1463 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1464 return;
1465
1466 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
1467
1468 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1469 ++(*Count);
1470 }
1471
1472 /// Applies the best formatting by reconstructing the path in the
1473 /// solution space that leads to \c Best.
1474 void reconstructPath(LineState &State, StateNode *Best) {
1476 // We do not need a break before the initial token.
1477 while (Best->Previous) {
1478 Path.push_back(Best);
1479 Best = Best->Previous;
1480 }
1481 for (const auto &Node : llvm::reverse(Path)) {
1482 unsigned Penalty = 0;
1483 formatChildren(State, Node->NewLine, /*DryRun=*/false, Penalty);
1484 Penalty += Indenter->addTokenToState(State, Node->NewLine, false);
1485
1486 LLVM_DEBUG({
1487 printLineState(Node->Previous->State);
1488 if (Node->NewLine) {
1489 llvm::dbgs() << "Penalty for placing "
1490 << Node->Previous->State.NextToken->Tok.getName()
1491 << " on a new line: " << Penalty << "\n";
1492 }
1493 });
1494 }
1495 }
1496
1497 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1498};
1499
1500} // anonymous namespace
1501
1503 const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
1504 int AdditionalIndent, bool FixBadIndentation, unsigned FirstStartColumn,
1505 unsigned NextStartColumn, unsigned LastStartColumn) {
1506 LineJoiner Joiner(Style, Keywords, Lines);
1507
1508 // Try to look up already computed penalty in DryRun-mode.
1509 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
1510 &Lines, AdditionalIndent);
1511 auto CacheIt = PenaltyCache.find(CacheKey);
1512 if (DryRun && CacheIt != PenaltyCache.end())
1513 return CacheIt->second;
1514
1515 assert(!Lines.empty());
1516 unsigned Penalty = 0;
1517 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
1518 AdditionalIndent);
1519 const AnnotatedLine *PrevPrevLine = nullptr;
1520 const AnnotatedLine *PreviousLine = nullptr;
1521 const AnnotatedLine *NextLine = nullptr;
1522
1523 // The minimum level of consecutive lines that have been formatted.
1524 unsigned RangeMinLevel = UINT_MAX;
1525
1526 bool FirstLine = true;
1527 for (const AnnotatedLine *Line =
1528 Joiner.getNextMergedLine(DryRun, IndentTracker);
1529 Line; PrevPrevLine = PreviousLine, PreviousLine = Line, Line = NextLine,
1530 FirstLine = false) {
1531 assert(Line->First);
1532 const AnnotatedLine &TheLine = *Line;
1533 unsigned Indent = IndentTracker.getIndent();
1534
1535 // We continue formatting unchanged lines to adjust their indent, e.g. if a
1536 // scope was added. However, we need to carefully stop doing this when we
1537 // exit the scope of affected lines to prevent indenting the entire
1538 // remaining file if it currently missing a closing brace.
1539 bool PreviousRBrace =
1540 PreviousLine && PreviousLine->startsWith(tok::r_brace);
1541 bool ContinueFormatting =
1542 TheLine.Level > RangeMinLevel ||
1543 (TheLine.Level == RangeMinLevel && !PreviousRBrace &&
1544 !TheLine.startsWith(TT_NamespaceRBrace));
1545
1546 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
1547 Indent != TheLine.First->OriginalColumn;
1548 bool ShouldFormat = TheLine.Affected || FixIndentation;
1549 // We cannot format this line; if the reason is that the line had a
1550 // parsing error, remember that.
1551 if (ShouldFormat && TheLine.Type == LT_Invalid && Status) {
1552 Status->FormatComplete = false;
1553 Status->Line =
1554 SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation());
1555 }
1556
1557 if (ShouldFormat && TheLine.Type != LT_Invalid) {
1558 if (!DryRun) {
1559 bool LastLine = TheLine.First->is(tok::eof);
1560 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines, Indent,
1561 LastLine ? LastStartColumn : NextStartColumn + Indent);
1562 }
1563
1564 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1565 unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
1566 bool FitsIntoOneLine =
1567 !TheLine.ContainsMacroCall &&
1568 (TheLine.Last->TotalLength + Indent <= ColumnLimit ||
1569 (TheLine.Type == LT_ImportStatement &&
1570 (!Style.isJavaScript() || !Style.JavaScriptWrapImports)) ||
1571 (Style.isCSharp() &&
1572 TheLine.InPPDirective)); // don't split #regions in C#
1573 if (Style.ColumnLimit == 0) {
1574 NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
1575 .formatLine(TheLine, NextStartColumn + Indent,
1576 FirstLine ? FirstStartColumn : 0, DryRun);
1577 } else if (FitsIntoOneLine) {
1578 Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
1579 .formatLine(TheLine, NextStartColumn + Indent,
1580 FirstLine ? FirstStartColumn : 0, DryRun);
1581 } else {
1582 Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
1583 .formatLine(TheLine, NextStartColumn + Indent,
1584 FirstLine ? FirstStartColumn : 0, DryRun);
1585 }
1586 RangeMinLevel = std::min(RangeMinLevel, TheLine.Level);
1587 } else {
1588 // If no token in the current line is affected, we still need to format
1589 // affected children.
1590 if (TheLine.ChildrenAffected) {
1591 for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next)
1592 if (!Tok->Children.empty())
1593 format(Tok->Children, DryRun);
1594 }
1595
1596 // Adapt following lines on the current indent level to the same level
1597 // unless the current \c AnnotatedLine is not at the beginning of a line.
1598 bool StartsNewLine =
1599 TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
1600 if (StartsNewLine)
1601 IndentTracker.adjustToUnmodifiedLine(TheLine);
1602 if (!DryRun) {
1603 bool ReformatLeadingWhitespace =
1604 StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
1606 // Format the first token.
1607 if (ReformatLeadingWhitespace) {
1608 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines,
1609 TheLine.First->OriginalColumn,
1610 TheLine.First->OriginalColumn);
1611 } else {
1612 Whitespaces->addUntouchableToken(*TheLine.First,
1613 TheLine.InPPDirective);
1614 }
1615
1616 // Notify the WhitespaceManager about the unchanged whitespace.
1617 for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
1618 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
1619 }
1620 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1621 RangeMinLevel = UINT_MAX;
1622 }
1623 if (!DryRun)
1624 markFinalized(TheLine.First);
1625 }
1626 PenaltyCache[CacheKey] = Penalty;
1627 return Penalty;
1628}
1629
1631 const AnnotatedLine *PreviousLine,
1632 const AnnotatedLine *PrevPrevLine,
1634 const FormatStyle &Style) {
1635 const auto &RootToken = *Line.First;
1636 auto Newlines =
1637 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1638 // Remove empty lines before "}" where applicable.
1639 if (RootToken.is(tok::r_brace) &&
1640 (!RootToken.Next ||
1641 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)) &&
1642 // Do not remove empty lines before namespace closing "}".
1643 !getNamespaceToken(&Line, Lines)) {
1644 Newlines = std::min(Newlines, 1u);
1645 }
1646 // Remove empty lines at the start of nested blocks (lambdas/arrow functions)
1647 if (!PreviousLine && Line.Level > 0)
1648 Newlines = std::min(Newlines, 1u);
1649 if (Newlines == 0 && !RootToken.IsFirst)
1650 Newlines = 1;
1651 if (RootToken.IsFirst &&
1652 (!Style.KeepEmptyLines.AtStartOfFile || !RootToken.HasUnescapedNewline)) {
1653 Newlines = 0;
1654 }
1655
1656 // Remove empty lines after "{".
1657 if (!Style.KeepEmptyLines.AtStartOfBlock && PreviousLine &&
1658 PreviousLine->Last->is(tok::l_brace) &&
1659 !PreviousLine->startsWithNamespace() &&
1660 !(PrevPrevLine && PrevPrevLine->startsWithNamespace() &&
1661 PreviousLine->startsWith(tok::l_brace)) &&
1662 !startsExternCBlock(*PreviousLine)) {
1663 Newlines = 1;
1664 }
1665
1666 if (Style.WrapNamespaceBodyWithEmptyLines != FormatStyle::WNBWELS_Leave) {
1667 // Modify empty lines after TT_NamespaceLBrace.
1668 if (PreviousLine && PreviousLine->endsWith(TT_NamespaceLBrace)) {
1669 if (Style.WrapNamespaceBodyWithEmptyLines == FormatStyle::WNBWELS_Never)
1670 Newlines = 1;
1671 else if (!Line.startsWithNamespace())
1672 Newlines = std::max(Newlines, 2u);
1673 }
1674 // Modify empty lines before TT_NamespaceRBrace.
1675 if (Line.startsWith(TT_NamespaceRBrace)) {
1676 if (Style.WrapNamespaceBodyWithEmptyLines == FormatStyle::WNBWELS_Never)
1677 Newlines = 1;
1678 else if (!PreviousLine->startsWith(TT_NamespaceRBrace))
1679 Newlines = std::max(Newlines, 2u);
1680 }
1681 }
1682
1683 // Insert or remove empty line before access specifiers.
1684 if (PreviousLine && RootToken.isAccessSpecifier()) {
1685 switch (Style.EmptyLineBeforeAccessModifier) {
1686 case FormatStyle::ELBAMS_Never:
1687 if (Newlines > 1)
1688 Newlines = 1;
1689 break;
1690 case FormatStyle::ELBAMS_Leave:
1691 Newlines = std::max(RootToken.NewlinesBefore, 1u);
1692 break;
1693 case FormatStyle::ELBAMS_LogicalBlock:
1694 if (PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) && Newlines <= 1)
1695 Newlines = 2;
1696 if (PreviousLine->First->isAccessSpecifier())
1697 Newlines = 1; // Previous is an access modifier remove all new lines.
1698 break;
1699 case FormatStyle::ELBAMS_Always: {
1700 const FormatToken *previousToken;
1701 if (PreviousLine->Last->is(tok::comment))
1702 previousToken = PreviousLine->Last->getPreviousNonComment();
1703 else
1704 previousToken = PreviousLine->Last;
1705 if ((!previousToken || previousToken->isNot(tok::l_brace)) &&
1706 Newlines <= 1) {
1707 Newlines = 2;
1708 }
1709 } break;
1710 }
1711 }
1712
1713 // Insert or remove empty line after access specifiers.
1714 if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
1715 (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline)) {
1716 // EmptyLineBeforeAccessModifier is handling the case when two access
1717 // modifiers follow each other.
1718 if (!RootToken.isAccessSpecifier()) {
1719 switch (Style.EmptyLineAfterAccessModifier) {
1720 case FormatStyle::ELAAMS_Never:
1721 Newlines = 1;
1722 break;
1723 case FormatStyle::ELAAMS_Leave:
1724 Newlines = std::max(Newlines, 1u);
1725 break;
1726 case FormatStyle::ELAAMS_Always:
1727 if (RootToken.is(tok::r_brace)) // Do not add at end of class.
1728 Newlines = 1u;
1729 else
1730 Newlines = std::max(Newlines, 2u);
1731 break;
1732 }
1733 }
1734 }
1735
1736 return Newlines;
1737}
1738
1739void UnwrappedLineFormatter::formatFirstToken(
1740 const AnnotatedLine &Line, const AnnotatedLine *PreviousLine,
1741 const AnnotatedLine *PrevPrevLine,
1742 const SmallVectorImpl<AnnotatedLine *> &Lines, unsigned Indent,
1743 unsigned NewlineIndent) {
1744 FormatToken &RootToken = *Line.First;
1745 if (RootToken.is(tok::eof)) {
1746 unsigned Newlines = std::min(
1747 RootToken.NewlinesBefore,
1748 Style.KeepEmptyLines.AtEndOfFile ? Style.MaxEmptyLinesToKeep + 1 : 1);
1749 unsigned TokenIndent = Newlines ? NewlineIndent : 0;
1750 Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
1751 TokenIndent);
1752 return;
1753 }
1754
1755 if (RootToken.Newlines < 0) {
1756 RootToken.Newlines =
1757 computeNewlines(Line, PreviousLine, PrevPrevLine, Lines, Style);
1758 assert(RootToken.Newlines >= 0);
1759 }
1760
1761 if (RootToken.Newlines > 0)
1762 Indent = NewlineIndent;
1763
1764 // Preprocessor directives get indented before the hash only if specified. In
1765 // Javascript import statements are indented like normal statements.
1766 if (!Style.isJavaScript() &&
1767 Style.IndentPPDirectives < FormatStyle::PPDIS_BeforeHash &&
1768 (Line.Type == LT_PreprocessorDirective ||
1769 Line.Type == LT_ImportStatement)) {
1770 Indent = 0;
1771 }
1772
1773 Whitespaces->replaceWhitespace(RootToken, RootToken.Newlines, Indent, Indent,
1774 /*IsAligned=*/false,
1775 Line.InPPDirective &&
1776 !RootToken.HasUnescapedNewline);
1777}
1778
1779unsigned
1780UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
1781 const AnnotatedLine *NextLine) const {
1782 // In preprocessor directives reserve two chars for trailing " \" if the
1783 // next line continues the preprocessor directive.
1784 bool ContinuesPPDirective =
1785 InPPDirective &&
1786 // If there is no next line, this is likely a child line and the parent
1787 // continues the preprocessor directive.
1788 (!NextLine ||
1789 (NextLine->InPPDirective &&
1790 // If there is an unescaped newline between this line and the next, the
1791 // next line starts a new preprocessor directive.
1792 !NextLine->First->HasUnescapedNewline));
1793 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
1794}
1795
1796} // namespace format
1797} // 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, bool IsAligned=false, 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)
The JSON file list parser is used to communicate input to InstallAPI.
int PPIndentWidth
The number of columns to use for indentation of preprocessor statements. When set to -1 (default) Ind...
Definition Format.h:4371
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition JsonSupport.h:21
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.