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