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