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