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