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