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