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 *getMatchingNamespaceToken(
187 const AnnotatedLine *Line,
188 const SmallVectorImpl<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 getMatchingNamespaceTokenText(
204 const AnnotatedLine *Line,
205 const SmallVectorImpl<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 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
245 SmallVectorImpl<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_RequiresExpressionLBrace)) {
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(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
618 SmallVectorImpl<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(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
630 SmallVectorImpl<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 tryMergeSimpleControlStatement(
696 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
697 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
698 if (Limit == 0)
699 return 0;
700 if (Style.BraceWrapping.AfterControlStatement ==
702 I[1]->First->is(tok::l_brace) &&
703 Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) {
704 return 0;
705 }
706 if (I[1]->InPPDirective != (*I)->InPPDirective ||
707 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) {
708 return 0;
709 }
710 Limit = limitConsideringMacros(I + 1, E, Limit);
711 AnnotatedLine &Line = **I;
712 if (Line.First->isNot(tok::kw_do) && Line.First->isNot(tok::kw_else) &&
713 Line.Last->isNot(tok::kw_else) && Line.Last->isNot(tok::r_paren)) {
714 return 0;
715 }
716 // Only merge `do while` if `do` is the only statement on the line.
717 if (Line.First->is(tok::kw_do) && Line.Last->isNot(tok::kw_do))
718 return 0;
719 if (1 + I[1]->Last->TotalLength > Limit)
720 return 0;
721 // Don't merge with loops, ifs, a single semicolon or a line comment.
722 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
723 TT_ForEachMacro, TT_LineComment)) {
724 return 0;
725 }
726 // Only inline simple if's (no nested if or else), unless specified
727 if (Style.AllowShortIfStatementsOnASingleLine ==
729 if (I + 2 != E && Line.startsWith(tok::kw_if) &&
730 I[2]->First->is(tok::kw_else)) {
731 return 0;
732 }
733 }
734 return 1;
735 }
736
737 unsigned
738 tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
739 SmallVectorImpl<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 SmallVectorImpl<AnnotatedLine *>::const_iterator 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
793 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
794 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
795 unsigned Limit) {
796 // Don't merge with a preprocessor directive.
797 if (I[1]->Type == LT_PreprocessorDirective)
798 return 0;
799
800 AnnotatedLine &Line = **I;
801
802 // Don't merge ObjC @ keywords and methods.
803 // FIXME: If an option to allow short exception handling clauses on a single
804 // line is added, change this to not return for @try and friends.
805 if (Style.Language != FormatStyle::LK_Java &&
806 Line.First->isOneOf(tok::at, tok::minus, tok::plus)) {
807 return 0;
808 }
809
810 // Check that the current line allows merging. This depends on whether we
811 // are in a control flow statements as well as several style flags.
812 if (Line.First->is(tok::kw_case) ||
813 (Line.First->Next && Line.First->Next->is(tok::kw_else))) {
814 return 0;
815 }
816 // default: in switch statement
817 if (Line.First->is(tok::kw_default)) {
818 const FormatToken *Tok = Line.First->getNextNonComment();
819 if (Tok && Tok->is(tok::colon))
820 return 0;
821 }
822
823 auto IsCtrlStmt = [](const auto &Line) {
824 return Line.First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
825 tok::kw_do, tok::kw_for, TT_ForEachMacro);
826 };
827
828 const bool IsSplitBlock =
829 Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never ||
830 (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Empty &&
831 I[1]->First->isNot(tok::r_brace));
832
833 if (IsCtrlStmt(Line) ||
834 Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
835 tok::kw___finally, tok::r_brace,
836 Keywords.kw___except)) {
837 if (IsSplitBlock)
838 return 0;
839 // Don't merge when we can't except the case when
840 // the control statement block is empty
841 if (!Style.AllowShortIfStatementsOnASingleLine &&
842 Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
843 !Style.BraceWrapping.AfterControlStatement &&
844 I[1]->First->isNot(tok::r_brace)) {
845 return 0;
846 }
847 if (!Style.AllowShortIfStatementsOnASingleLine &&
848 Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
849 Style.BraceWrapping.AfterControlStatement ==
851 I + 2 != E && I[2]->First->isNot(tok::r_brace)) {
852 return 0;
853 }
854 if (!Style.AllowShortLoopsOnASingleLine &&
855 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
856 TT_ForEachMacro) &&
857 !Style.BraceWrapping.AfterControlStatement &&
858 I[1]->First->isNot(tok::r_brace)) {
859 return 0;
860 }
861 if (!Style.AllowShortLoopsOnASingleLine &&
862 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
863 TT_ForEachMacro) &&
864 Style.BraceWrapping.AfterControlStatement ==
866 I + 2 != E && I[2]->First->isNot(tok::r_brace)) {
867 return 0;
868 }
869 // FIXME: Consider an option to allow short exception handling clauses on
870 // a single line.
871 // FIXME: This isn't covered by tests.
872 // FIXME: For catch, __except, __finally the first token on the line
873 // is '}', so this isn't correct here.
874 if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
875 Keywords.kw___except, tok::kw___finally)) {
876 return 0;
877 }
878 }
879
880 if (Line.endsWith(tok::l_brace)) {
881 if (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never &&
882 Line.First->is(TT_BlockLBrace)) {
883 return 0;
884 }
885
886 if (IsSplitBlock && Line.First == Line.Last &&
887 I > AnnotatedLines.begin() &&
888 (I[-1]->endsWith(tok::kw_else) || IsCtrlStmt(*I[-1]))) {
889 return 0;
890 }
891 FormatToken *Tok = I[1]->First;
892 auto ShouldMerge = [Tok]() {
893 if (Tok->isNot(tok::r_brace) || Tok->MustBreakBefore)
894 return false;
895 const FormatToken *Next = Tok->getNextNonComment();
896 return !Next || Next->is(tok::semi);
897 };
898
899 if (ShouldMerge()) {
900 // We merge empty blocks even if the line exceeds the column limit.
901 Tok->SpacesRequiredBefore =
902 (Style.SpaceInEmptyBlock || Line.Last->is(tok::comment)) ? 1 : 0;
903 Tok->CanBreakBefore = true;
904 return 1;
905 } else if (Limit != 0 && !Line.startsWithNamespace() &&
906 !startsExternCBlock(Line)) {
907 // We don't merge short records.
908 if (isRecordLBrace(*Line.Last))
909 return 0;
910
911 // Check that we still have three lines and they fit into the limit.
912 if (I + 2 == E || I[2]->Type == LT_Invalid)
913 return 0;
914 Limit = limitConsideringMacros(I + 2, E, Limit);
915
916 if (!nextTwoLinesFitInto(I, Limit))
917 return 0;
918
919 // Second, check that the next line does not contain any braces - if it
920 // does, readability declines when putting it into a single line.
921 if (I[1]->Last->is(TT_LineComment))
922 return 0;
923 do {
924 if (Tok->is(tok::l_brace) && Tok->isNot(BK_BracedInit))
925 return 0;
926 Tok = Tok->Next;
927 } while (Tok);
928
929 // Last, check that the third line starts with a closing brace.
930 Tok = I[2]->First;
931 if (Tok->isNot(tok::r_brace))
932 return 0;
933
934 // Don't merge "if (a) { .. } else {".
935 if (Tok->Next && Tok->Next->is(tok::kw_else))
936 return 0;
937
938 // Don't merge a trailing multi-line control statement block like:
939 // } else if (foo &&
940 // bar)
941 // { <-- current Line
942 // baz();
943 // }
944 if (Line.First == Line.Last && Line.First->isNot(TT_FunctionLBrace) &&
945 Style.BraceWrapping.AfterControlStatement ==
947 return 0;
948 }
949
950 return 2;
951 }
952 } else if (I[1]->First->is(tok::l_brace)) {
953 if (I[1]->Last->is(TT_LineComment))
954 return 0;
955
956 // Check for Limit <= 2 to account for the " {".
957 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
958 return 0;
959 Limit -= 2;
960 unsigned MergedLines = 0;
961 if (Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never ||
962 (I[1]->First == I[1]->Last && I + 2 != E &&
963 I[2]->First->is(tok::r_brace))) {
964 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
965 // If we managed to merge the block, count the statement header, which
966 // is on a separate line.
967 if (MergedLines > 0)
968 ++MergedLines;
969 }
970 return MergedLines;
971 }
972 return 0;
973 }
974
975 /// Returns the modified column limit for \p I if it is inside a macro and
976 /// needs a trailing '\'.
977 unsigned
978 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
979 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
980 unsigned Limit) {
981 if (I[0]->InPPDirective && I + 1 != E &&
982 !I[1]->First->HasUnescapedNewline && I[1]->First->isNot(tok::eof)) {
983 return Limit < 2 ? 0 : Limit - 2;
984 }
985 return Limit;
986 }
987
988 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
989 unsigned Limit) {
990 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
991 return false;
992 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
993 }
994
995 bool nextNLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
996 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
997 unsigned Limit) {
998 unsigned JoinedLength = 0;
999 for (const auto *J = I + 1; J != E; ++J) {
1000 if ((*J)->First->MustBreakBefore)
1001 return false;
1002
1003 JoinedLength += 1 + (*J)->Last->TotalLength;
1004 if (JoinedLength > Limit)
1005 return false;
1006 }
1007 return true;
1008 }
1009
1010 bool containsMustBreak(const AnnotatedLine *Line) {
1011 assert(Line->First);
1012 // Ignore the first token, because in this situation, it applies more to the
1013 // last token of the previous line.
1014 for (const FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next)
1015 if (Tok->MustBreakBefore)
1016 return true;
1017 return false;
1018 }
1019
1020 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1021 assert(!A.Last->Next);
1022 assert(!B.First->Previous);
1023 if (B.Affected)
1024 A.Affected = true;
1025 A.Last->Next = B.First;
1026 B.First->Previous = A.Last;
1027 B.First->CanBreakBefore = true;
1028 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1029 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1030 Tok->TotalLength += LengthA;
1031 A.Last = Tok;
1032 }
1033 }
1034
1035 const FormatStyle &Style;
1036 const AdditionalKeywords &Keywords;
1037 const SmallVectorImpl<AnnotatedLine *>::const_iterator End;
1038
1039 SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
1040 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
1041};
1042
1043static void markFinalized(FormatToken *Tok) {
1044 if (Tok->is(tok::hash) && !Tok->Previous && Tok->Next &&
1045 Tok->Next->isOneOf(tok::pp_if, tok::pp_ifdef, tok::pp_ifndef,
1046 tok::pp_elif, tok::pp_elifdef, tok::pp_elifndef,
1047 tok::pp_else, tok::pp_endif)) {
1048 Tok = Tok->Next;
1049 }
1050 for (; Tok; Tok = Tok->Next) {
1051 if (Tok->MacroCtx && Tok->MacroCtx->Role == MR_ExpandedArg) {
1052 // In the first pass we format all macro arguments in the expanded token
1053 // stream. Instead of finalizing the macro arguments, we mark that they
1054 // will be modified as unexpanded arguments (as part of the macro call
1055 // formatting) in the next pass.
1056 Tok->MacroCtx->Role = MR_UnexpandedArg;
1057 // Reset whether spaces or a line break are required before this token, as
1058 // that is context dependent, and that context may change when formatting
1059 // the macro call. For example, given M(x) -> 2 * x, and the macro call
1060 // M(var), the token 'var' will have SpacesRequiredBefore = 1 after being
1061 // formatted as part of the expanded macro, but SpacesRequiredBefore = 0
1062 // for its position within the macro call.
1063 Tok->SpacesRequiredBefore = 0;
1064 if (!Tok->MustBreakBeforeFinalized)
1065 Tok->MustBreakBefore = 0;
1066 } else {
1067 Tok->Finalized = true;
1068 }
1069 }
1070}
1071
1072#ifndef NDEBUG
1073static void printLineState(const LineState &State) {
1074 llvm::dbgs() << "State: ";
1075 for (const ParenState &P : State.Stack) {
1076 llvm::dbgs() << (P.Tok ? P.Tok->TokenText : "F") << "|" << P.Indent << "|"
1077 << P.LastSpace << "|" << P.NestedBlockIndent << " ";
1078 }
1079 llvm::dbgs() << State.NextToken->TokenText << "\n";
1080}
1081#endif
1082
1083/// Base class for classes that format one \c AnnotatedLine.
1084class LineFormatter {
1085public:
1086 LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
1087 const FormatStyle &Style,
1088 UnwrappedLineFormatter *BlockFormatter)
1089 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
1090 BlockFormatter(BlockFormatter) {}
1091 virtual ~LineFormatter() {}
1092
1093 /// Formats an \c AnnotatedLine and returns the penalty.
1094 ///
1095 /// If \p DryRun is \c false, directly applies the changes.
1096 virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1097 unsigned FirstStartColumn, bool DryRun) = 0;
1098
1099protected:
1100 /// If the \p State's next token is an r_brace closing a nested block,
1101 /// format the nested block before it.
1102 ///
1103 /// Returns \c true if all children could be placed successfully and adapts
1104 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1105 /// creates changes using \c Whitespaces.
1106 ///
1107 /// The crucial idea here is that children always get formatted upon
1108 /// encountering the closing brace right after the nested block. Now, if we
1109 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1110 /// \c false), the entire block has to be kept on the same line (which is only
1111 /// possible if it fits on the line, only contains a single statement, etc.
1112 ///
1113 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1114 /// break after the "{", format all lines with correct indentation and the put
1115 /// the closing "}" on yet another new line.
1116 ///
1117 /// This enables us to keep the simple structure of the
1118 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1119 /// break or don't break.
1120 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1121 unsigned &Penalty) {
1122 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1123 bool HasLBrace = LBrace && LBrace->is(tok::l_brace) && LBrace->is(BK_Block);
1124 FormatToken &Previous = *State.NextToken->Previous;
1125 if (Previous.Children.size() == 0 || (!HasLBrace && !LBrace->MacroParent)) {
1126 // The previous token does not open a block. Nothing to do. We don't
1127 // assert so that we can simply call this function for all tokens.
1128 return true;
1129 }
1130
1131 if (NewLine || Previous.MacroParent) {
1132 const ParenState &P = State.Stack.back();
1133
1134 int AdditionalIndent =
1135 P.Indent - Previous.Children[0]->Level * Style.IndentWidth;
1136 Penalty +=
1137 BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
1138 /*FixBadIndentation=*/true);
1139 return true;
1140 }
1141
1142 if (Previous.Children[0]->First->MustBreakBefore)
1143 return false;
1144
1145 // Cannot merge into one line if this line ends on a comment.
1146 if (Previous.is(tok::comment))
1147 return false;
1148
1149 // Cannot merge multiple statements into a single line.
1150 if (Previous.Children.size() > 1)
1151 return false;
1152
1153 const AnnotatedLine *Child = Previous.Children[0];
1154 // We can't put the closing "}" on a line with a trailing comment.
1155 if (Child->Last->isTrailingComment())
1156 return false;
1157
1158 // If the child line exceeds the column limit, we wouldn't want to merge it.
1159 // We add +2 for the trailing " }".
1160 if (Style.ColumnLimit > 0 &&
1161 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit) {
1162 return false;
1163 }
1164
1165 if (!DryRun) {
1166 Whitespaces->replaceWhitespace(
1167 *Child->First, /*Newlines=*/0, /*Spaces=*/1,
1168 /*StartOfTokenColumn=*/State.Column, /*IsAligned=*/false,
1169 State.Line->InPPDirective);
1170 }
1171 Penalty +=
1172 formatLine(*Child, State.Column + 1, /*FirstStartColumn=*/0, DryRun);
1173 if (!DryRun)
1174 markFinalized(Child->First);
1175
1176 State.Column += 1 + Child->Last->TotalLength;
1177 return true;
1178 }
1179
1180 ContinuationIndenter *Indenter;
1181
1182private:
1183 WhitespaceManager *Whitespaces;
1184 const FormatStyle &Style;
1185 UnwrappedLineFormatter *BlockFormatter;
1186};
1187
1188/// Formatter that keeps the existing line breaks.
1189class NoColumnLimitLineFormatter : public LineFormatter {
1190public:
1191 NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
1192 WhitespaceManager *Whitespaces,
1193 const FormatStyle &Style,
1194 UnwrappedLineFormatter *BlockFormatter)
1195 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1196
1197 /// Formats the line, simply keeping all of the input's line breaking
1198 /// decisions.
1199 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1200 unsigned FirstStartColumn, bool DryRun) override {
1201 assert(!DryRun);
1202 LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
1203 &Line, /*DryRun=*/false);
1204 while (State.NextToken) {
1205 bool Newline =
1206 Indenter->mustBreak(State) ||
1207 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
1208 unsigned Penalty = 0;
1209 formatChildren(State, Newline, /*DryRun=*/false, Penalty);
1210 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
1211 }
1212 return 0;
1213 }
1214};
1215
1216/// Formatter that puts all tokens into a single line without breaks.
1217class NoLineBreakFormatter : public LineFormatter {
1218public:
1219 NoLineBreakFormatter(ContinuationIndenter *Indenter,
1220 WhitespaceManager *Whitespaces, const FormatStyle &Style,
1221 UnwrappedLineFormatter *BlockFormatter)
1222 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1223
1224 /// Puts all tokens into a single line.
1225 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1226 unsigned FirstStartColumn, bool DryRun) override {
1227 unsigned Penalty = 0;
1228 LineState State =
1229 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
1230 while (State.NextToken) {
1231 formatChildren(State, /*NewLine=*/false, DryRun, Penalty);
1232 Indenter->addTokenToState(
1233 State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun);
1234 }
1235 return Penalty;
1236 }
1237};
1238
1239/// Finds the best way to break lines.
1240class OptimizingLineFormatter : public LineFormatter {
1241public:
1242 OptimizingLineFormatter(ContinuationIndenter *Indenter,
1243 WhitespaceManager *Whitespaces,
1244 const FormatStyle &Style,
1245 UnwrappedLineFormatter *BlockFormatter)
1246 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1247
1248 /// Formats the line by finding the best line breaks with line lengths
1249 /// below the column limit.
1250 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1251 unsigned FirstStartColumn, bool DryRun) override {
1252 LineState State =
1253 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
1254
1255 // If the ObjC method declaration does not fit on a line, we should format
1256 // it with one arg per line.
1257 if (State.Line->Type == LT_ObjCMethodDecl)
1258 State.Stack.back().BreakBeforeParameter = true;
1259
1260 // Find best solution in solution space.
1261 return analyzeSolutionSpace(State, DryRun);
1262 }
1263
1264private:
1265 struct CompareLineStatePointers {
1266 bool operator()(LineState *obj1, LineState *obj2) const {
1267 return *obj1 < *obj2;
1268 }
1269 };
1270
1271 /// A pair of <penalty, count> that is used to prioritize the BFS on.
1272 ///
1273 /// In case of equal penalties, we want to prefer states that were inserted
1274 /// first. During state generation we make sure that we insert states first
1275 /// that break the line as late as possible.
1276 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1277
1278 /// An edge in the solution space from \c Previous->State to \c State,
1279 /// inserting a newline dependent on the \c NewLine.
1280 struct StateNode {
1281 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
1282 : State(State), NewLine(NewLine), Previous(Previous) {}
1283 LineState State;
1285 StateNode *Previous;
1286 };
1287
1288 /// An item in the prioritized BFS search queue. The \c StateNode's
1289 /// \c State has the given \c OrderedPenalty.
1290 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1291
1292 /// The BFS queue type.
1293 typedef std::priority_queue<QueueItem, SmallVector<QueueItem>,
1294 std::greater<QueueItem>>
1295 QueueType;
1296
1297 /// Analyze the entire solution space starting from \p InitialState.
1298 ///
1299 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1300 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1301 /// find the shortest path (the one with lowest penalty) from \p InitialState
1302 /// to a state where all tokens are placed. Returns the penalty.
1303 ///
1304 /// If \p DryRun is \c false, directly applies the changes.
1305 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
1306 std::set<LineState *, CompareLineStatePointers> Seen;
1307
1308 // Increasing count of \c StateNode items we have created. This is used to
1309 // create a deterministic order independent of the container.
1310 unsigned Count = 0;
1311 QueueType Queue;
1312
1313 // Insert start element into queue.
1314 StateNode *RootNode =
1315 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
1316 Queue.push(QueueItem(OrderedPenalty(0, Count), RootNode));
1317 ++Count;
1318
1319 unsigned Penalty = 0;
1320
1321 // While not empty, take first element and follow edges.
1322 while (!Queue.empty()) {
1323 // Quit if we still haven't found a solution by now.
1324 if (Count > 25'000'000)
1325 return 0;
1326
1327 Penalty = Queue.top().first.first;
1328 StateNode *Node = Queue.top().second;
1329 if (!Node->State.NextToken) {
1330 LLVM_DEBUG(llvm::dbgs()
1331 << "\n---\nPenalty for line: " << Penalty << "\n");
1332 break;
1333 }
1334 Queue.pop();
1335
1336 // Cut off the analysis of certain solutions if the analysis gets too
1337 // complex. See description of IgnoreStackForComparison.
1338 if (Count > 50'000)
1339 Node->State.IgnoreStackForComparison = true;
1340
1341 if (!Seen.insert(&Node->State).second) {
1342 // State already examined with lower penalty.
1343 continue;
1344 }
1345
1346 FormatDecision LastFormat = Node->State.NextToken->getDecision();
1347 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
1348 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
1349 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
1350 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
1351 }
1352
1353 if (Queue.empty()) {
1354 // We were unable to find a solution, do nothing.
1355 // FIXME: Add diagnostic?
1356 LLVM_DEBUG(llvm::dbgs() << "Could not find a solution.\n");
1357 return 0;
1358 }
1359
1360 // Reconstruct the solution.
1361 if (!DryRun)
1362 reconstructPath(InitialState, Queue.top().second);
1363
1364 LLVM_DEBUG(llvm::dbgs()
1365 << "Total number of analyzed states: " << Count << "\n");
1366 LLVM_DEBUG(llvm::dbgs() << "---\n");
1367
1368 return Penalty;
1369 }
1370
1371 /// Add the following state to the analysis queue \c Queue.
1372 ///
1373 /// Assume the current state is \p PreviousNode and has been reached with a
1374 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
1375 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1376 bool NewLine, unsigned *Count, QueueType *Queue) {
1377 if (NewLine && !Indenter->canBreak(PreviousNode->State))
1378 return;
1379 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
1380 return;
1381
1382 StateNode *Node = new (Allocator.Allocate())
1383 StateNode(PreviousNode->State, NewLine, PreviousNode);
1384 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1385 return;
1386
1387 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
1388
1389 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1390 ++(*Count);
1391 }
1392
1393 /// Applies the best formatting by reconstructing the path in the
1394 /// solution space that leads to \c Best.
1395 void reconstructPath(LineState &State, StateNode *Best) {
1397 // We do not need a break before the initial token.
1398 while (Best->Previous) {
1399 Path.push_back(Best);
1400 Best = Best->Previous;
1401 }
1402 for (const auto &Node : llvm::reverse(Path)) {
1403 unsigned Penalty = 0;
1404 formatChildren(State, Node->NewLine, /*DryRun=*/false, Penalty);
1405 Penalty += Indenter->addTokenToState(State, Node->NewLine, false);
1406
1407 LLVM_DEBUG({
1408 printLineState(Node->Previous->State);
1409 if (Node->NewLine) {
1410 llvm::dbgs() << "Penalty for placing "
1411 << Node->Previous->State.NextToken->Tok.getName()
1412 << " on a new line: " << Penalty << "\n";
1413 }
1414 });
1415 }
1416 }
1417
1418 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1419};
1420
1421} // anonymous namespace
1422
1424 const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
1425 int AdditionalIndent, bool FixBadIndentation, unsigned FirstStartColumn,
1426 unsigned NextStartColumn, unsigned LastStartColumn) {
1427 LineJoiner Joiner(Style, Keywords, Lines);
1428
1429 // Try to look up already computed penalty in DryRun-mode.
1430 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
1431 &Lines, AdditionalIndent);
1432 auto CacheIt = PenaltyCache.find(CacheKey);
1433 if (DryRun && CacheIt != PenaltyCache.end())
1434 return CacheIt->second;
1435
1436 assert(!Lines.empty());
1437 unsigned Penalty = 0;
1438 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
1439 AdditionalIndent);
1440 const AnnotatedLine *PrevPrevLine = nullptr;
1441 const AnnotatedLine *PreviousLine = nullptr;
1442 const AnnotatedLine *NextLine = nullptr;
1443
1444 // The minimum level of consecutive lines that have been formatted.
1445 unsigned RangeMinLevel = UINT_MAX;
1446
1447 bool FirstLine = true;
1448 for (const AnnotatedLine *Line =
1449 Joiner.getNextMergedLine(DryRun, IndentTracker);
1450 Line; PrevPrevLine = PreviousLine, PreviousLine = Line, Line = NextLine,
1451 FirstLine = false) {
1452 assert(Line->First);
1453 const AnnotatedLine &TheLine = *Line;
1454 unsigned Indent = IndentTracker.getIndent();
1455
1456 // We continue formatting unchanged lines to adjust their indent, e.g. if a
1457 // scope was added. However, we need to carefully stop doing this when we
1458 // exit the scope of affected lines to prevent indenting the entire
1459 // remaining file if it currently missing a closing brace.
1460 bool PreviousRBrace =
1461 PreviousLine && PreviousLine->startsWith(tok::r_brace);
1462 bool ContinueFormatting =
1463 TheLine.Level > RangeMinLevel ||
1464 (TheLine.Level == RangeMinLevel && !PreviousRBrace &&
1465 !TheLine.startsWith(tok::r_brace));
1466
1467 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
1468 Indent != TheLine.First->OriginalColumn;
1469 bool ShouldFormat = TheLine.Affected || FixIndentation;
1470 // We cannot format this line; if the reason is that the line had a
1471 // parsing error, remember that.
1472 if (ShouldFormat && TheLine.Type == LT_Invalid && Status) {
1473 Status->FormatComplete = false;
1474 Status->Line =
1475 SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation());
1476 }
1477
1478 if (ShouldFormat && TheLine.Type != LT_Invalid) {
1479 if (!DryRun) {
1480 bool LastLine = TheLine.First->is(tok::eof);
1481 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines, Indent,
1482 LastLine ? LastStartColumn : NextStartColumn + Indent);
1483 }
1484
1485 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1486 unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
1487 bool FitsIntoOneLine =
1488 !TheLine.ContainsMacroCall &&
1489 (TheLine.Last->TotalLength + Indent <= ColumnLimit ||
1490 (TheLine.Type == LT_ImportStatement &&
1491 (!Style.isJavaScript() || !Style.JavaScriptWrapImports)) ||
1492 (Style.isCSharp() &&
1493 TheLine.InPPDirective)); // don't split #regions in C#
1494 if (Style.ColumnLimit == 0) {
1495 NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
1496 .formatLine(TheLine, NextStartColumn + Indent,
1497 FirstLine ? FirstStartColumn : 0, DryRun);
1498 } else if (FitsIntoOneLine) {
1499 Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
1500 .formatLine(TheLine, NextStartColumn + Indent,
1501 FirstLine ? FirstStartColumn : 0, DryRun);
1502 } else {
1503 Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
1504 .formatLine(TheLine, NextStartColumn + Indent,
1505 FirstLine ? FirstStartColumn : 0, DryRun);
1506 }
1507 RangeMinLevel = std::min(RangeMinLevel, TheLine.Level);
1508 } else {
1509 // If no token in the current line is affected, we still need to format
1510 // affected children.
1511 if (TheLine.ChildrenAffected) {
1512 for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next)
1513 if (!Tok->Children.empty())
1514 format(Tok->Children, DryRun);
1515 }
1516
1517 // Adapt following lines on the current indent level to the same level
1518 // unless the current \c AnnotatedLine is not at the beginning of a line.
1519 bool StartsNewLine =
1520 TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
1521 if (StartsNewLine)
1522 IndentTracker.adjustToUnmodifiedLine(TheLine);
1523 if (!DryRun) {
1524 bool ReformatLeadingWhitespace =
1525 StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
1527 // Format the first token.
1528 if (ReformatLeadingWhitespace) {
1529 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines,
1530 TheLine.First->OriginalColumn,
1531 TheLine.First->OriginalColumn);
1532 } else {
1533 Whitespaces->addUntouchableToken(*TheLine.First,
1534 TheLine.InPPDirective);
1535 }
1536
1537 // Notify the WhitespaceManager about the unchanged whitespace.
1538 for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
1539 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
1540 }
1541 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1542 RangeMinLevel = UINT_MAX;
1543 }
1544 if (!DryRun)
1545 markFinalized(TheLine.First);
1546 }
1547 PenaltyCache[CacheKey] = Penalty;
1548 return Penalty;
1549}
1550
1552 const AnnotatedLine *PreviousLine,
1553 const AnnotatedLine *PrevPrevLine,
1555 const FormatStyle &Style) {
1556 const auto &RootToken = *Line.First;
1557 auto Newlines =
1558 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1559 // Remove empty lines before "}" where applicable.
1560 if (RootToken.is(tok::r_brace) &&
1561 (!RootToken.Next ||
1562 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)) &&
1563 // Do not remove empty lines before namespace closing "}".
1564 !getNamespaceToken(&Line, Lines)) {
1565 Newlines = std::min(Newlines, 1u);
1566 }
1567 // Remove empty lines at the start of nested blocks (lambdas/arrow functions)
1568 if (!PreviousLine && Line.Level > 0)
1569 Newlines = std::min(Newlines, 1u);
1570 if (Newlines == 0 && !RootToken.IsFirst)
1571 Newlines = 1;
1572 if (RootToken.IsFirst &&
1573 (!Style.KeepEmptyLines.AtStartOfFile || !RootToken.HasUnescapedNewline)) {
1574 Newlines = 0;
1575 }
1576
1577 // Remove empty lines after "{".
1578 if (!Style.KeepEmptyLines.AtStartOfBlock && PreviousLine &&
1579 PreviousLine->Last->is(tok::l_brace) &&
1580 !PreviousLine->startsWithNamespace() &&
1581 !(PrevPrevLine && PrevPrevLine->startsWithNamespace() &&
1582 PreviousLine->startsWith(tok::l_brace)) &&
1583 !startsExternCBlock(*PreviousLine)) {
1584 Newlines = 1;
1585 }
1586
1587 // Insert or remove empty line before access specifiers.
1588 if (PreviousLine && RootToken.isAccessSpecifier()) {
1589 switch (Style.EmptyLineBeforeAccessModifier) {
1591 if (Newlines > 1)
1592 Newlines = 1;
1593 break;
1595 Newlines = std::max(RootToken.NewlinesBefore, 1u);
1596 break;
1598 if (PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) && Newlines <= 1)
1599 Newlines = 2;
1600 if (PreviousLine->First->isAccessSpecifier())
1601 Newlines = 1; // Previous is an access modifier remove all new lines.
1602 break;
1604 const FormatToken *previousToken;
1605 if (PreviousLine->Last->is(tok::comment))
1606 previousToken = PreviousLine->Last->getPreviousNonComment();
1607 else
1608 previousToken = PreviousLine->Last;
1609 if ((!previousToken || previousToken->isNot(tok::l_brace)) &&
1610 Newlines <= 1) {
1611 Newlines = 2;
1612 }
1613 } break;
1614 }
1615 }
1616
1617 // Insert or remove empty line after access specifiers.
1618 if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
1619 (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline)) {
1620 // EmptyLineBeforeAccessModifier is handling the case when two access
1621 // modifiers follow each other.
1622 if (!RootToken.isAccessSpecifier()) {
1623 switch (Style.EmptyLineAfterAccessModifier) {
1625 Newlines = 1;
1626 break;
1628 Newlines = std::max(Newlines, 1u);
1629 break;
1631 if (RootToken.is(tok::r_brace)) // Do not add at end of class.
1632 Newlines = 1u;
1633 else
1634 Newlines = std::max(Newlines, 2u);
1635 break;
1636 }
1637 }
1638 }
1639
1640 return Newlines;
1641}
1642
1643void UnwrappedLineFormatter::formatFirstToken(
1644 const AnnotatedLine &Line, const AnnotatedLine *PreviousLine,
1645 const AnnotatedLine *PrevPrevLine,
1646 const SmallVectorImpl<AnnotatedLine *> &Lines, unsigned Indent,
1647 unsigned NewlineIndent) {
1648 FormatToken &RootToken = *Line.First;
1649 if (RootToken.is(tok::eof)) {
1650 unsigned Newlines = std::min(
1651 RootToken.NewlinesBefore,
1652 Style.KeepEmptyLines.AtEndOfFile ? Style.MaxEmptyLinesToKeep + 1 : 1);
1653 unsigned TokenIndent = Newlines ? NewlineIndent : 0;
1654 Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
1655 TokenIndent);
1656 return;
1657 }
1658
1659 if (RootToken.Newlines < 0) {
1660 RootToken.Newlines =
1661 computeNewlines(Line, PreviousLine, PrevPrevLine, Lines, Style);
1662 assert(RootToken.Newlines >= 0);
1663 }
1664
1665 if (RootToken.Newlines > 0)
1666 Indent = NewlineIndent;
1667
1668 // Preprocessor directives get indented before the hash only if specified. In
1669 // Javascript import statements are indented like normal statements.
1670 if (!Style.isJavaScript() &&
1671 Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
1672 (Line.Type == LT_PreprocessorDirective ||
1673 Line.Type == LT_ImportStatement)) {
1674 Indent = 0;
1675 }
1676
1677 Whitespaces->replaceWhitespace(RootToken, RootToken.Newlines, Indent, Indent,
1678 /*IsAligned=*/false,
1679 Line.InPPDirective &&
1680 !RootToken.HasUnescapedNewline);
1681}
1682
1683unsigned
1684UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
1685 const AnnotatedLine *NextLine) const {
1686 // In preprocessor directives reserve two chars for trailing " \" if the
1687 // next line continues the preprocessor directive.
1688 bool ContinuesPPDirective =
1689 InPPDirective &&
1690 // If there is no next line, this is likely a child line and the parent
1691 // continues the preprocessor directive.
1692 (!NextLine ||
1693 (NextLine->InPPDirective &&
1694 // If there is an unescaped newline between this line and the next, the
1695 // next line starts a new preprocessor directive.
1696 !NextLine->First->HasUnescapedNewline));
1697 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
1698}
1699
1700} // namespace format
1701} // 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 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:235
@ MR_ExpandedArg
The token was expanded from a macro argument when formatting the expanded token sequence.
Definition: FormatToken.h:232
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:3268
@ 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
@ 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
@ 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:3403
@ 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:295
unsigned OriginalColumn
The original 0-based column of this token, including expanded tabs.
Definition: FormatToken.h:505
bool isNot(T Kind) const
Definition: FormatToken.h:629
FormatToken * getPreviousNonComment() const
Returns the previous token ignoring comments.
Definition: FormatToken.h:838
FormatToken * Next
The next token in the unwrapped line.
Definition: FormatToken.h:567
unsigned NewlinesBefore
The number of newlines immediately before the Token.
Definition: FormatToken.h:464
bool is(tok::TokenKind Kind) const
Definition: FormatToken.h:610
unsigned TotalLength
The total length of the unwrapped line up to and including this token.
Definition: FormatToken.h:501
bool isOneOf(A K1, B K2) const
Definition: FormatToken.h:622
unsigned IsFirst
Indicates that this is the first token of the file.
Definition: FormatToken.h:334
bool isAccessSpecifier(bool ColonRequired=true) const
Definition: FormatToken.h:676
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:5484
unsigned Line
If FormatComplete is false, Line records a one-based original line number at which a syntax error mig...
Definition: Format.h:5489
static const size_t kInvalidIndex