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