clang  6.0.0svn
UnwrappedLineFormatter.cpp
Go to the documentation of this file.
1 //===--- UnwrappedLineFormatter.cpp - Format C++ code ---------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "UnwrappedLineFormatter.h"
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 /// \brief Tracks the indent level of \c AnnotatedLines across levels.
30 ///
31 /// \c nextLine must be called for each \c AnnotatedLine, after which \c
32 /// getIndent() will return the indent for the last line \c nextLine was called
33 /// with.
34 /// If the line is not formatted (and thus the indent does not change), calling
35 /// \c adjustToUnmodifiedLine after the call to \c nextLine will cause
36 /// subsequent lines on the same level to be indented at the same level as the
37 /// given line.
38 class LevelIndentTracker {
39 public:
40  LevelIndentTracker(const FormatStyle &Style,
41  const AdditionalKeywords &Keywords, unsigned StartLevel,
42  int AdditionalIndent)
43  : Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) {
44  for (unsigned i = 0; i != StartLevel; ++i)
45  IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
46  }
47 
48  /// \brief Returns the indent for the current line.
49  unsigned getIndent() const { return Indent; }
50 
51  /// \brief Update the indent state given that \p Line is going to be formatted
52  /// next.
53  void nextLine(const AnnotatedLine &Line) {
54  Offset = getIndentOffset(*Line.First);
55  // Update the indent level cache size so that we can rely on it
56  // having the right size in adjustToUnmodifiedline.
57  while (IndentForLevel.size() <= Line.Level)
58  IndentForLevel.push_back(-1);
59  if (Line.InPPDirective) {
60  Indent = Line.Level * Style.IndentWidth + AdditionalIndent;
61  } else {
62  IndentForLevel.resize(Line.Level + 1);
63  Indent = getIndent(IndentForLevel, Line.Level);
64  }
65  if (static_cast<int>(Indent) + Offset >= 0)
66  Indent += Offset;
67  }
68 
69  /// \brief Update the indent state given that \p Line indent should be
70  /// skipped.
71  void skipLine(const AnnotatedLine &Line) {
72  while (IndentForLevel.size() <= Line.Level)
73  IndentForLevel.push_back(Indent);
74  }
75 
76  /// \brief Update the level indent to adapt to the given \p Line.
77  ///
78  /// When a line is not formatted, we move the subsequent lines on the same
79  /// level to the same indent.
80  /// Note that \c nextLine must have been called before this method.
81  void adjustToUnmodifiedLine(const AnnotatedLine &Line) {
82  unsigned LevelIndent = Line.First->OriginalColumn;
83  if (static_cast<int>(LevelIndent) - Offset >= 0)
84  LevelIndent -= Offset;
85  if ((!Line.First->is(tok::comment) || IndentForLevel[Line.Level] == -1) &&
86  !Line.InPPDirective)
87  IndentForLevel[Line.Level] = LevelIndent;
88  }
89 
90 private:
91  /// \brief Get the offset of the line relatively to the level.
92  ///
93  /// For example, 'public:' labels in classes are offset by 1 or 2
94  /// characters to the left from their level.
95  int getIndentOffset(const FormatToken &RootToken) {
96  if (Style.Language == FormatStyle::LK_Java ||
97  Style.Language == FormatStyle::LK_JavaScript)
98  return 0;
99  if (RootToken.isAccessSpecifier(false) ||
100  RootToken.isObjCAccessSpecifier() ||
101  (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
102  RootToken.Next && RootToken.Next->is(tok::colon)))
103  return Style.AccessModifierOffset;
104  return 0;
105  }
106 
107  /// \brief Get the indent of \p Level from \p IndentForLevel.
108  ///
109  /// \p IndentForLevel must contain the indent for the level \c l
110  /// at \p IndentForLevel[l], or a value < 0 if the indent for
111  /// that level is unknown.
112  unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
113  if (IndentForLevel[Level] != -1)
114  return IndentForLevel[Level];
115  if (Level == 0)
116  return 0;
117  return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
118  }
119 
120  const FormatStyle &Style;
121  const AdditionalKeywords &Keywords;
122  const unsigned AdditionalIndent;
123 
124  /// \brief The indent in characters for each level.
125  std::vector<int> IndentForLevel;
126 
127  /// \brief Offset of the current line relative to the indent level.
128  ///
129  /// For example, the 'public' keywords is often indented with a negative
130  /// offset.
131  int Offset = 0;
132 
133  /// \brief The current line's indent.
134  unsigned Indent = 0;
135 };
136 
137 bool isNamespaceDeclaration(const AnnotatedLine *Line) {
138  const FormatToken *NamespaceTok = Line->First;
139  return NamespaceTok && NamespaceTok->getNamespaceToken();
140 }
141 
142 bool isEndOfNamespace(const AnnotatedLine *Line,
143  const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
144  if (!Line->startsWith(tok::r_brace))
145  return false;
146  size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex;
147  if (StartLineIndex == UnwrappedLine::kInvalidIndex)
148  return false;
149  assert(StartLineIndex < AnnotatedLines.size());
150  return isNamespaceDeclaration(AnnotatedLines[StartLineIndex]);
151 }
152 
153 class LineJoiner {
154 public:
155  LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords,
156  const SmallVectorImpl<AnnotatedLine *> &Lines)
157  : Style(Style), Keywords(Keywords), End(Lines.end()), Next(Lines.begin()),
158  AnnotatedLines(Lines) {}
159 
160  /// \brief Returns the next line, merging multiple lines into one if possible.
161  const AnnotatedLine *getNextMergedLine(bool DryRun,
162  LevelIndentTracker &IndentTracker) {
163  if (Next == End)
164  return nullptr;
165  const AnnotatedLine *Current = *Next;
166  IndentTracker.nextLine(*Current);
167  unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next, End);
168  if (MergedLines > 0 && Style.ColumnLimit == 0)
169  // Disallow line merging if there is a break at the start of one of the
170  // input lines.
171  for (unsigned i = 0; i < MergedLines; ++i)
172  if (Next[i + 1]->First->NewlinesBefore > 0)
173  MergedLines = 0;
174  if (!DryRun)
175  for (unsigned i = 0; i < MergedLines; ++i)
176  join(*Next[0], *Next[i + 1]);
177  Next = Next + MergedLines + 1;
178  return Current;
179  }
180 
181 private:
182  /// \brief Calculates how many lines can be merged into 1 starting at \p I.
183  unsigned
184  tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker,
185  SmallVectorImpl<AnnotatedLine *>::const_iterator I,
186  SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
187  const unsigned Indent = IndentTracker.getIndent();
188 
189  // Can't join the last line with anything.
190  if (I + 1 == E)
191  return 0;
192  // We can never merge stuff if there are trailing line comments.
193  const AnnotatedLine *TheLine = *I;
194  if (TheLine->Last->is(TT_LineComment))
195  return 0;
196  if (I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
197  return 0;
198  if (TheLine->InPPDirective &&
199  (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline))
200  return 0;
201 
202  if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
203  return 0;
204 
205  unsigned Limit =
206  Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
207  // If we already exceed the column limit, we set 'Limit' to 0. The different
208  // tryMerge..() functions can then decide whether to still do merging.
209  Limit = TheLine->Last->TotalLength > Limit
210  ? 0
211  : Limit - TheLine->Last->TotalLength;
212 
213  if (TheLine->Last->is(TT_FunctionLBrace) &&
214  TheLine->First == TheLine->Last &&
215  !Style.BraceWrapping.SplitEmptyFunction &&
216  I[1]->First->is(tok::r_brace))
217  return tryMergeSimpleBlock(I, E, Limit);
218 
219  // Handle empty record blocks where the brace has already been wrapped
220  if (TheLine->Last->is(tok::l_brace) && TheLine->First == TheLine->Last &&
221  I != AnnotatedLines.begin()) {
222  bool EmptyBlock = I[1]->First->is(tok::r_brace);
223 
224  const FormatToken *Tok = I[-1]->First;
225  if (Tok && Tok->is(tok::comment))
226  Tok = Tok->getNextNonComment();
227 
228  if (Tok && Tok->getNamespaceToken())
229  return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock
230  ? tryMergeSimpleBlock(I, E, Limit)
231  : 0;
232 
233  if (Tok && Tok->is(tok::kw_typedef))
234  Tok = Tok->getNextNonComment();
235  if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union,
236  tok::kw_extern, Keywords.kw_interface))
237  return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock
238  ? tryMergeSimpleBlock(I, E, Limit)
239  : 0;
240  }
241 
242  // FIXME: TheLine->Level != 0 might or might not be the right check to do.
243  // If necessary, change to something smarter.
244  bool MergeShortFunctions =
245  Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
246  (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
247  I[1]->First->is(tok::r_brace)) ||
248  (Style.AllowShortFunctionsOnASingleLine & FormatStyle::SFS_InlineOnly &&
249  TheLine->Level != 0);
250 
251  if (Style.CompactNamespaces) {
252  if (isNamespaceDeclaration(TheLine)) {
253  int i = 0;
254  unsigned closingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
255  for (; I + 1 + i != E && isNamespaceDeclaration(I[i + 1]) &&
256  closingLine == I[i + 1]->MatchingOpeningBlockLineIndex &&
257  I[i + 1]->Last->TotalLength < Limit;
258  i++, closingLine--) {
259  // No extra indent for compacted namespaces
260  IndentTracker.skipLine(*I[i + 1]);
261 
262  Limit -= I[i + 1]->Last->TotalLength;
263  }
264  return i;
265  }
266 
267  if (isEndOfNamespace(TheLine, AnnotatedLines)) {
268  int i = 0;
269  unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
270  for (; I + 1 + i != E && isEndOfNamespace(I[i + 1], AnnotatedLines) &&
271  openingLine == I[i + 1]->MatchingOpeningBlockLineIndex;
272  i++, openingLine--) {
273  // No space between consecutive braces
274  I[i + 1]->First->SpacesRequiredBefore = !I[i]->Last->is(tok::r_brace);
275 
276  // Indent like the outer-most namespace
277  IndentTracker.nextLine(*I[i + 1]);
278  }
279  return i;
280  }
281  }
282 
283  // Try to merge a function block with left brace unwrapped
284  if (TheLine->Last->is(TT_FunctionLBrace) &&
285  TheLine->First != TheLine->Last) {
286  return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
287  }
288  // Try to merge a control statement block with left brace unwrapped
289  if (TheLine->Last->is(tok::l_brace) && TheLine->First != TheLine->Last &&
290  TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
291  return Style.AllowShortBlocksOnASingleLine
292  ? tryMergeSimpleBlock(I, E, Limit)
293  : 0;
294  }
295  // Try to merge a control statement block with left brace wrapped
296  if (I[1]->First->is(tok::l_brace) &&
297  TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
298  return Style.BraceWrapping.AfterControlStatement
299  ? tryMergeSimpleBlock(I, E, Limit)
300  : 0;
301  }
302  // Try to merge either empty or one-line block if is precedeed by control
303  // statement token
304  if (TheLine->First->is(tok::l_brace) && TheLine->First == TheLine->Last &&
305  I != AnnotatedLines.begin() &&
306  I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
307  return Style.AllowShortBlocksOnASingleLine
308  ? tryMergeSimpleBlock(I - 1, E, Limit)
309  : 0;
310  }
311  // Try to merge a block with left brace wrapped that wasn't yet covered
312  if (TheLine->Last->is(tok::l_brace)) {
313  return !Style.BraceWrapping.AfterFunction ||
314  (I[1]->First->is(tok::r_brace) &&
315  !Style.BraceWrapping.SplitEmptyRecord)
316  ? tryMergeSimpleBlock(I, E, Limit)
317  : 0;
318  }
319  // Try to merge a function block with left brace wrapped
320  if (I[1]->First->is(TT_FunctionLBrace) &&
321  Style.BraceWrapping.AfterFunction) {
322  if (I[1]->Last->is(TT_LineComment))
323  return 0;
324 
325  // Check for Limit <= 2 to account for the " {".
326  if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
327  return 0;
328  Limit -= 2;
329 
330  unsigned MergedLines = 0;
331  if (MergeShortFunctions ||
332  (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
333  I[1]->First == I[1]->Last && I + 2 != E &&
334  I[2]->First->is(tok::r_brace))) {
335  MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
336  // If we managed to merge the block, count the function header, which is
337  // on a separate line.
338  if (MergedLines > 0)
339  ++MergedLines;
340  }
341  return MergedLines;
342  }
343  if (TheLine->First->is(tok::kw_if)) {
344  return Style.AllowShortIfStatementsOnASingleLine
345  ? tryMergeSimpleControlStatement(I, E, Limit)
346  : 0;
347  }
348  if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
349  return Style.AllowShortLoopsOnASingleLine
350  ? tryMergeSimpleControlStatement(I, E, Limit)
351  : 0;
352  }
353  if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
354  return Style.AllowShortCaseLabelsOnASingleLine
355  ? tryMergeShortCaseLabels(I, E, Limit)
356  : 0;
357  }
358  if (TheLine->InPPDirective &&
359  (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
360  return tryMergeSimplePPDirective(I, E, Limit);
361  }
362  return 0;
363  }
364 
365  unsigned
366  tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
367  SmallVectorImpl<AnnotatedLine *>::const_iterator E,
368  unsigned Limit) {
369  if (Limit == 0)
370  return 0;
371  if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
372  return 0;
373  if (1 + I[1]->Last->TotalLength > Limit)
374  return 0;
375  return 1;
376  }
377 
378  unsigned tryMergeSimpleControlStatement(
379  SmallVectorImpl<AnnotatedLine *>::const_iterator I,
380  SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
381  if (Limit == 0)
382  return 0;
383  if (Style.BraceWrapping.AfterControlStatement &&
384  (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
385  return 0;
386  if (I[1]->InPPDirective != (*I)->InPPDirective ||
387  (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
388  return 0;
389  Limit = limitConsideringMacros(I + 1, E, Limit);
390  AnnotatedLine &Line = **I;
391  if (Line.Last->isNot(tok::r_paren))
392  return 0;
393  if (1 + I[1]->Last->TotalLength > Limit)
394  return 0;
395  if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
396  TT_LineComment))
397  return 0;
398  // Only inline simple if's (no nested if or else).
399  if (I + 2 != E && Line.startsWith(tok::kw_if) &&
400  I[2]->First->is(tok::kw_else))
401  return 0;
402  return 1;
403  }
404 
405  unsigned
406  tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
407  SmallVectorImpl<AnnotatedLine *>::const_iterator E,
408  unsigned Limit) {
409  if (Limit == 0 || I + 1 == E ||
410  I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
411  return 0;
412  unsigned NumStmts = 0;
413  unsigned Length = 0;
414  bool EndsWithComment = false;
415  bool InPPDirective = I[0]->InPPDirective;
416  const unsigned Level = I[0]->Level;
417  for (; NumStmts < 3; ++NumStmts) {
418  if (I + 1 + NumStmts == E)
419  break;
420  const AnnotatedLine *Line = I[1 + NumStmts];
421  if (Line->InPPDirective != InPPDirective)
422  break;
423  if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
424  break;
425  if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
426  tok::kw_while) ||
427  EndsWithComment)
428  return 0;
429  if (Line->First->is(tok::comment)) {
430  if (Level != Line->Level)
431  return 0;
432  SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts;
433  for (; J != E; ++J) {
434  Line = *J;
435  if (Line->InPPDirective != InPPDirective)
436  break;
437  if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
438  break;
439  if (Line->First->isNot(tok::comment) || Level != Line->Level)
440  return 0;
441  }
442  break;
443  }
444  if (Line->Last->is(tok::comment))
445  EndsWithComment = true;
446  Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
447  }
448  if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
449  return 0;
450  return NumStmts;
451  }
452 
453  unsigned
454  tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
455  SmallVectorImpl<AnnotatedLine *>::const_iterator E,
456  unsigned Limit) {
457  AnnotatedLine &Line = **I;
458 
459  // Don't merge ObjC @ keywords and methods.
460  // FIXME: If an option to allow short exception handling clauses on a single
461  // line is added, change this to not return for @try and friends.
462  if (Style.Language != FormatStyle::LK_Java &&
463  Line.First->isOneOf(tok::at, tok::minus, tok::plus))
464  return 0;
465 
466  // Check that the current line allows merging. This depends on whether we
467  // are in a control flow statements as well as several style flags.
468  if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
469  (Line.First->Next && Line.First->Next->is(tok::kw_else)))
470  return 0;
471  if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
472  tok::kw___try, tok::kw_catch, tok::kw___finally,
473  tok::kw_for, tok::r_brace, Keywords.kw___except)) {
474  if (!Style.AllowShortBlocksOnASingleLine)
475  return 0;
476  // Don't merge when we can't except the case when
477  // the control statement block is empty
478  if (!Style.AllowShortIfStatementsOnASingleLine &&
479  Line.startsWith(tok::kw_if) &&
480  !Style.BraceWrapping.AfterControlStatement &&
481  !I[1]->First->is(tok::r_brace))
482  return 0;
483  if (!Style.AllowShortIfStatementsOnASingleLine &&
484  Line.startsWith(tok::kw_if) &&
485  Style.BraceWrapping.AfterControlStatement && I + 2 != E &&
486  !I[2]->First->is(tok::r_brace))
487  return 0;
488  if (!Style.AllowShortLoopsOnASingleLine &&
489  Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
490  !Style.BraceWrapping.AfterControlStatement &&
491  !I[1]->First->is(tok::r_brace))
492  return 0;
493  if (!Style.AllowShortLoopsOnASingleLine &&
494  Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
495  Style.BraceWrapping.AfterControlStatement && I + 2 != E &&
496  !I[2]->First->is(tok::r_brace))
497  return 0;
498  // FIXME: Consider an option to allow short exception handling clauses on
499  // a single line.
500  // FIXME: This isn't covered by tests.
501  // FIXME: For catch, __except, __finally the first token on the line
502  // is '}', so this isn't correct here.
503  if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
504  Keywords.kw___except, tok::kw___finally))
505  return 0;
506  }
507 
508  if (Line.Last->is(tok::l_brace)) {
509  FormatToken *Tok = I[1]->First;
510  if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
511  (Tok->getNextNonComment() == nullptr ||
512  Tok->getNextNonComment()->is(tok::semi))) {
513  // We merge empty blocks even if the line exceeds the column limit.
514  Tok->SpacesRequiredBefore = 0;
515  Tok->CanBreakBefore = true;
516  return 1;
517  } else if (Limit != 0 && !Line.startsWith(tok::kw_namespace) &&
518  !startsExternCBlock(Line)) {
519  // We don't merge short records.
520  FormatToken *RecordTok =
521  Line.First->is(tok::kw_typedef) ? Line.First->Next : Line.First;
522  if (RecordTok &&
523  RecordTok->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
524  Keywords.kw_interface))
525  return 0;
526 
527  // Check that we still have three lines and they fit into the limit.
528  if (I + 2 == E || I[2]->Type == LT_Invalid)
529  return 0;
530  Limit = limitConsideringMacros(I + 2, E, Limit);
531 
532  if (!nextTwoLinesFitInto(I, Limit))
533  return 0;
534 
535  // Second, check that the next line does not contain any braces - if it
536  // does, readability declines when putting it into a single line.
537  if (I[1]->Last->is(TT_LineComment))
538  return 0;
539  do {
540  if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
541  return 0;
542  Tok = Tok->Next;
543  } while (Tok);
544 
545  // Last, check that the third line starts with a closing brace.
546  Tok = I[2]->First;
547  if (Tok->isNot(tok::r_brace))
548  return 0;
549 
550  // Don't merge "if (a) { .. } else {".
551  if (Tok->Next && Tok->Next->is(tok::kw_else))
552  return 0;
553 
554  return 2;
555  }
556  } else if (I[1]->First->is(tok::l_brace)) {
557  if (I[1]->Last->is(TT_LineComment))
558  return 0;
559 
560  // Check for Limit <= 2 to account for the " {".
561  if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
562  return 0;
563  Limit -= 2;
564  unsigned MergedLines = 0;
565  if (Style.AllowShortBlocksOnASingleLine ||
566  (I[1]->First == I[1]->Last && I + 2 != E &&
567  I[2]->First->is(tok::r_brace))) {
568  MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
569  // If we managed to merge the block, count the statement header, which
570  // is on a separate line.
571  if (MergedLines > 0)
572  ++MergedLines;
573  }
574  return MergedLines;
575  }
576  return 0;
577  }
578 
579  /// Returns the modified column limit for \p I if it is inside a macro and
580  /// needs a trailing '\'.
581  unsigned
582  limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
583  SmallVectorImpl<AnnotatedLine *>::const_iterator E,
584  unsigned Limit) {
585  if (I[0]->InPPDirective && I + 1 != E &&
586  !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
587  return Limit < 2 ? 0 : Limit - 2;
588  }
589  return Limit;
590  }
591 
592  bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
593  unsigned Limit) {
594  if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
595  return false;
596  return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
597  }
598 
599  bool containsMustBreak(const AnnotatedLine *Line) {
600  for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
601  if (Tok->MustBreakBefore)
602  return true;
603  }
604  return false;
605  }
606 
607  void join(AnnotatedLine &A, const AnnotatedLine &B) {
608  assert(!A.Last->Next);
609  assert(!B.First->Previous);
610  if (B.Affected)
611  A.Affected = true;
612  A.Last->Next = B.First;
613  B.First->Previous = A.Last;
614  B.First->CanBreakBefore = true;
615  unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
616  for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
617  Tok->TotalLength += LengthA;
618  A.Last = Tok;
619  }
620  }
621 
622  const FormatStyle &Style;
623  const AdditionalKeywords &Keywords;
624  const SmallVectorImpl<AnnotatedLine *>::const_iterator End;
625 
626  SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
627  const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
628 };
629 
630 static void markFinalized(FormatToken *Tok) {
631  for (; Tok; Tok = Tok->Next) {
632  Tok->Finalized = true;
633  for (AnnotatedLine *Child : Tok->Children)
634  markFinalized(Child->First);
635  }
636 }
637 
638 #ifndef NDEBUG
639 static void printLineState(const LineState &State) {
640  llvm::dbgs() << "State: ";
641  for (const ParenState &P : State.Stack) {
642  llvm::dbgs() << P.Indent << "|" << P.LastSpace << "|" << P.NestedBlockIndent
643  << " ";
644  }
645  llvm::dbgs() << State.NextToken->TokenText << "\n";
646 }
647 #endif
648 
649 /// \brief Base class for classes that format one \c AnnotatedLine.
650 class LineFormatter {
651 public:
652  LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
653  const FormatStyle &Style,
654  UnwrappedLineFormatter *BlockFormatter)
655  : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
656  BlockFormatter(BlockFormatter) {}
657  virtual ~LineFormatter() {}
658 
659  /// \brief Formats an \c AnnotatedLine and returns the penalty.
660  ///
661  /// If \p DryRun is \c false, directly applies the changes.
662  virtual unsigned formatLine(const AnnotatedLine &Line,
663  unsigned FirstIndent,
664  unsigned FirstStartColumn,
665  bool DryRun) = 0;
666 
667 protected:
668  /// \brief If the \p State's next token is an r_brace closing a nested block,
669  /// format the nested block before it.
670  ///
671  /// Returns \c true if all children could be placed successfully and adapts
672  /// \p Penalty as well as \p State. If \p DryRun is false, also directly
673  /// creates changes using \c Whitespaces.
674  ///
675  /// The crucial idea here is that children always get formatted upon
676  /// encountering the closing brace right after the nested block. Now, if we
677  /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
678  /// \c false), the entire block has to be kept on the same line (which is only
679  /// possible if it fits on the line, only contains a single statement, etc.
680  ///
681  /// If \p NewLine is true, we format the nested block on separate lines, i.e.
682  /// break after the "{", format all lines with correct indentation and the put
683  /// the closing "}" on yet another new line.
684  ///
685  /// This enables us to keep the simple structure of the
686  /// \c UnwrappedLineFormatter, where we only have two options for each token:
687  /// break or don't break.
688  bool formatChildren(LineState &State, bool NewLine, bool DryRun,
689  unsigned &Penalty) {
690  const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
691  FormatToken &Previous = *State.NextToken->Previous;
692  if (!LBrace || LBrace->isNot(tok::l_brace) ||
693  LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
694  // The previous token does not open a block. Nothing to do. We don't
695  // assert so that we can simply call this function for all tokens.
696  return true;
697 
698  if (NewLine) {
699  int AdditionalIndent = State.Stack.back().Indent -
700  Previous.Children[0]->Level * Style.IndentWidth;
701 
702  Penalty +=
703  BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
704  /*FixBadIndentation=*/true);
705  return true;
706  }
707 
708  if (Previous.Children[0]->First->MustBreakBefore)
709  return false;
710 
711  // Cannot merge into one line if this line ends on a comment.
712  if (Previous.is(tok::comment))
713  return false;
714 
715  // Cannot merge multiple statements into a single line.
716  if (Previous.Children.size() > 1)
717  return false;
718 
719  const AnnotatedLine *Child = Previous.Children[0];
720  // We can't put the closing "}" on a line with a trailing comment.
721  if (Child->Last->isTrailingComment())
722  return false;
723 
724  // If the child line exceeds the column limit, we wouldn't want to merge it.
725  // We add +2 for the trailing " }".
726  if (Style.ColumnLimit > 0 &&
727  Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit)
728  return false;
729 
730  if (!DryRun) {
731  Whitespaces->replaceWhitespace(
732  *Child->First, /*Newlines=*/0, /*Spaces=*/1,
733  /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
734  }
735  Penalty +=
736  formatLine(*Child, State.Column + 1, /*FirstStartColumn=*/0, DryRun);
737 
738  State.Column += 1 + Child->Last->TotalLength;
739  return true;
740  }
741 
742  ContinuationIndenter *Indenter;
743 
744 private:
745  WhitespaceManager *Whitespaces;
746  const FormatStyle &Style;
747  UnwrappedLineFormatter *BlockFormatter;
748 };
749 
750 /// \brief Formatter that keeps the existing line breaks.
751 class NoColumnLimitLineFormatter : public LineFormatter {
752 public:
753  NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
754  WhitespaceManager *Whitespaces,
755  const FormatStyle &Style,
756  UnwrappedLineFormatter *BlockFormatter)
757  : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
758 
759  /// \brief Formats the line, simply keeping all of the input's line breaking
760  /// decisions.
761  unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
762  unsigned FirstStartColumn, bool DryRun) override {
763  assert(!DryRun);
764  LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
765  &Line, /*DryRun=*/false);
766  while (State.NextToken) {
767  bool Newline =
768  Indenter->mustBreak(State) ||
769  (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
770  unsigned Penalty = 0;
771  formatChildren(State, Newline, /*DryRun=*/false, Penalty);
772  Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
773  }
774  return 0;
775  }
776 };
777 
778 /// \brief Formatter that puts all tokens into a single line without breaks.
779 class NoLineBreakFormatter : public LineFormatter {
780 public:
781  NoLineBreakFormatter(ContinuationIndenter *Indenter,
782  WhitespaceManager *Whitespaces, const FormatStyle &Style,
783  UnwrappedLineFormatter *BlockFormatter)
784  : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
785 
786  /// \brief Puts all tokens into a single line.
787  unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
788  unsigned FirstStartColumn, bool DryRun) override {
789  unsigned Penalty = 0;
790  LineState State =
791  Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
792  while (State.NextToken) {
793  formatChildren(State, /*Newline=*/false, DryRun, Penalty);
794  Indenter->addTokenToState(
795  State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun);
796  }
797  return Penalty;
798  }
799 };
800 
801 /// \brief Finds the best way to break lines.
802 class OptimizingLineFormatter : public LineFormatter {
803 public:
804  OptimizingLineFormatter(ContinuationIndenter *Indenter,
805  WhitespaceManager *Whitespaces,
806  const FormatStyle &Style,
807  UnwrappedLineFormatter *BlockFormatter)
808  : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
809 
810  /// \brief Formats the line by finding the best line breaks with line lengths
811  /// below the column limit.
812  unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
813  unsigned FirstStartColumn, bool DryRun) override {
814  LineState State =
815  Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
816 
817  // If the ObjC method declaration does not fit on a line, we should format
818  // it with one arg per line.
819  if (State.Line->Type == LT_ObjCMethodDecl)
820  State.Stack.back().BreakBeforeParameter = true;
821 
822  // Find best solution in solution space.
823  return analyzeSolutionSpace(State, DryRun);
824  }
825 
826 private:
827  struct CompareLineStatePointers {
828  bool operator()(LineState *obj1, LineState *obj2) const {
829  return *obj1 < *obj2;
830  }
831  };
832 
833  /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
834  ///
835  /// In case of equal penalties, we want to prefer states that were inserted
836  /// first. During state generation we make sure that we insert states first
837  /// that break the line as late as possible.
838  typedef std::pair<unsigned, unsigned> OrderedPenalty;
839 
840  /// \brief An edge in the solution space from \c Previous->State to \c State,
841  /// inserting a newline dependent on the \c NewLine.
842  struct StateNode {
843  StateNode(const LineState &State, bool NewLine, StateNode *Previous)
844  : State(State), NewLine(NewLine), Previous(Previous) {}
845  LineState State;
846  bool NewLine;
847  StateNode *Previous;
848  };
849 
850  /// \brief An item in the prioritized BFS search queue. The \c StateNode's
851  /// \c State has the given \c OrderedPenalty.
852  typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
853 
854  /// \brief The BFS queue type.
855  typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
856  std::greater<QueueItem>>
857  QueueType;
858 
859  /// \brief Analyze the entire solution space starting from \p InitialState.
860  ///
861  /// This implements a variant of Dijkstra's algorithm on the graph that spans
862  /// the solution space (\c LineStates are the nodes). The algorithm tries to
863  /// find the shortest path (the one with lowest penalty) from \p InitialState
864  /// to a state where all tokens are placed. Returns the penalty.
865  ///
866  /// If \p DryRun is \c false, directly applies the changes.
867  unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
868  std::set<LineState *, CompareLineStatePointers> Seen;
869 
870  // Increasing count of \c StateNode items we have created. This is used to
871  // create a deterministic order independent of the container.
872  unsigned Count = 0;
873  QueueType Queue;
874 
875  // Insert start element into queue.
876  StateNode *Node =
877  new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
878  Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
879  ++Count;
880 
881  unsigned Penalty = 0;
882 
883  // While not empty, take first element and follow edges.
884  while (!Queue.empty()) {
885  Penalty = Queue.top().first.first;
886  StateNode *Node = Queue.top().second;
887  if (!Node->State.NextToken) {
888  DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
889  break;
890  }
891  Queue.pop();
892 
893  // Cut off the analysis of certain solutions if the analysis gets too
894  // complex. See description of IgnoreStackForComparison.
895  if (Count > 50000)
896  Node->State.IgnoreStackForComparison = true;
897 
898  if (!Seen.insert(&Node->State).second)
899  // State already examined with lower penalty.
900  continue;
901 
902  FormatDecision LastFormat = Node->State.NextToken->Decision;
903  if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
904  addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
905  if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
906  addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
907  }
908 
909  if (Queue.empty()) {
910  // We were unable to find a solution, do nothing.
911  // FIXME: Add diagnostic?
912  DEBUG(llvm::dbgs() << "Could not find a solution.\n");
913  return 0;
914  }
915 
916  // Reconstruct the solution.
917  if (!DryRun)
918  reconstructPath(InitialState, Queue.top().second);
919 
920  DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
921  DEBUG(llvm::dbgs() << "---\n");
922 
923  return Penalty;
924  }
925 
926  /// \brief Add the following state to the analysis queue \c Queue.
927  ///
928  /// Assume the current state is \p PreviousNode and has been reached with a
929  /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
930  void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
931  bool NewLine, unsigned *Count, QueueType *Queue) {
932  if (NewLine && !Indenter->canBreak(PreviousNode->State))
933  return;
934  if (!NewLine && Indenter->mustBreak(PreviousNode->State))
935  return;
936 
937  StateNode *Node = new (Allocator.Allocate())
938  StateNode(PreviousNode->State, NewLine, PreviousNode);
939  if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
940  return;
941 
942  Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
943 
944  Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
945  ++(*Count);
946  }
947 
948  /// \brief Applies the best formatting by reconstructing the path in the
949  /// solution space that leads to \c Best.
950  void reconstructPath(LineState &State, StateNode *Best) {
951  std::deque<StateNode *> Path;
952  // We do not need a break before the initial token.
953  while (Best->Previous) {
954  Path.push_front(Best);
955  Best = Best->Previous;
956  }
957  for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
958  I != E; ++I) {
959  unsigned Penalty = 0;
960  formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
961  Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
962 
963  DEBUG({
964  printLineState((*I)->Previous->State);
965  if ((*I)->NewLine) {
966  llvm::dbgs() << "Penalty for placing "
967  << (*I)->Previous->State.NextToken->Tok.getName() << ": "
968  << Penalty << "\n";
969  }
970  });
971  }
972  }
973 
974  llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
975 };
976 
977 } // anonymous namespace
978 
979 unsigned
981  bool DryRun, int AdditionalIndent,
982  bool FixBadIndentation,
983  unsigned FirstStartColumn,
984  unsigned NextStartColumn,
985  unsigned LastStartColumn) {
986  LineJoiner Joiner(Style, Keywords, Lines);
987 
988  // Try to look up already computed penalty in DryRun-mode.
989  std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
990  &Lines, AdditionalIndent);
991  auto CacheIt = PenaltyCache.find(CacheKey);
992  if (DryRun && CacheIt != PenaltyCache.end())
993  return CacheIt->second;
994 
995  assert(!Lines.empty());
996  unsigned Penalty = 0;
997  LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
998  AdditionalIndent);
999  const AnnotatedLine *PreviousLine = nullptr;
1000  const AnnotatedLine *NextLine = nullptr;
1001 
1002  // The minimum level of consecutive lines that have been formatted.
1003  unsigned RangeMinLevel = UINT_MAX;
1004 
1005  bool FirstLine = true;
1006  for (const AnnotatedLine *Line =
1007  Joiner.getNextMergedLine(DryRun, IndentTracker);
1008  Line; Line = NextLine, FirstLine = false) {
1009  const AnnotatedLine &TheLine = *Line;
1010  unsigned Indent = IndentTracker.getIndent();
1011 
1012  // We continue formatting unchanged lines to adjust their indent, e.g. if a
1013  // scope was added. However, we need to carefully stop doing this when we
1014  // exit the scope of affected lines to prevent indenting a the entire
1015  // remaining file if it currently missing a closing brace.
1016  bool ContinueFormatting =
1017  TheLine.Level > RangeMinLevel ||
1018  (TheLine.Level == RangeMinLevel && !TheLine.startsWith(tok::r_brace));
1019 
1020  bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
1021  Indent != TheLine.First->OriginalColumn;
1022  bool ShouldFormat = TheLine.Affected || FixIndentation;
1023  // We cannot format this line; if the reason is that the line had a
1024  // parsing error, remember that.
1025  if (ShouldFormat && TheLine.Type == LT_Invalid && Status) {
1026  Status->FormatComplete = false;
1027  Status->Line =
1028  SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation());
1029  }
1030 
1031  if (ShouldFormat && TheLine.Type != LT_Invalid) {
1032  if (!DryRun) {
1033  bool LastLine = Line->First->is(tok::eof);
1034  formatFirstToken(TheLine, PreviousLine,
1035  Indent,
1036  LastLine ? LastStartColumn : NextStartColumn + Indent);
1037  }
1038 
1039  NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1040  unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
1041  bool FitsIntoOneLine =
1042  TheLine.Last->TotalLength + Indent <= ColumnLimit ||
1043  (TheLine.Type == LT_ImportStatement &&
1046  if (Style.ColumnLimit == 0)
1047  NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
1048  .formatLine(TheLine, NextStartColumn + Indent,
1049  FirstLine ? FirstStartColumn : 0, DryRun);
1050  else if (FitsIntoOneLine)
1051  Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
1052  .formatLine(TheLine, NextStartColumn + Indent,
1053  FirstLine ? FirstStartColumn : 0, DryRun);
1054  else
1055  Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
1056  .formatLine(TheLine, NextStartColumn + Indent,
1057  FirstLine ? FirstStartColumn : 0, DryRun);
1058  RangeMinLevel = std::min(RangeMinLevel, TheLine.Level);
1059  } else {
1060  // If no token in the current line is affected, we still need to format
1061  // affected children.
1062  if (TheLine.ChildrenAffected)
1063  for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next)
1064  if (!Tok->Children.empty())
1065  format(Tok->Children, DryRun);
1066 
1067  // Adapt following lines on the current indent level to the same level
1068  // unless the current \c AnnotatedLine is not at the beginning of a line.
1069  bool StartsNewLine =
1070  TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
1071  if (StartsNewLine)
1072  IndentTracker.adjustToUnmodifiedLine(TheLine);
1073  if (!DryRun) {
1074  bool ReformatLeadingWhitespace =
1075  StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
1076  TheLine.LeadingEmptyLinesAffected);
1077  // Format the first token.
1078  if (ReformatLeadingWhitespace)
1079  formatFirstToken(TheLine, PreviousLine,
1080  TheLine.First->OriginalColumn,
1081  TheLine.First->OriginalColumn);
1082  else
1083  Whitespaces->addUntouchableToken(*TheLine.First,
1084  TheLine.InPPDirective);
1085 
1086  // Notify the WhitespaceManager about the unchanged whitespace.
1087  for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
1088  Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
1089  }
1090  NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1091  RangeMinLevel = UINT_MAX;
1092  }
1093  if (!DryRun)
1094  markFinalized(TheLine.First);
1095  PreviousLine = &TheLine;
1096  }
1097  PenaltyCache[CacheKey] = Penalty;
1098  return Penalty;
1099 }
1100 
1101 void UnwrappedLineFormatter::formatFirstToken(const AnnotatedLine &Line,
1102  const AnnotatedLine *PreviousLine,
1103  unsigned Indent,
1104  unsigned NewlineIndent) {
1105  FormatToken &RootToken = *Line.First;
1106  if (RootToken.is(tok::eof)) {
1107  unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u);
1108  unsigned TokenIndent = Newlines ? NewlineIndent : 0;
1109  Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
1110  TokenIndent);
1111  return;
1112  }
1113  unsigned Newlines =
1115  // Remove empty lines before "}" where applicable.
1116  if (RootToken.is(tok::r_brace) &&
1117  (!RootToken.Next ||
1118  (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1119  Newlines = std::min(Newlines, 1u);
1120  // Remove empty lines at the start of nested blocks (lambdas/arrow functions)
1121  if (PreviousLine == nullptr && Line.Level > 0)
1122  Newlines = std::min(Newlines, 1u);
1123  if (Newlines == 0 && !RootToken.IsFirst)
1124  Newlines = 1;
1125  if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1126  Newlines = 0;
1127 
1128  // Remove empty lines after "{".
1129  if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1130  PreviousLine->Last->is(tok::l_brace) &&
1131  PreviousLine->First->isNot(tok::kw_namespace) &&
1132  !startsExternCBlock(*PreviousLine))
1133  Newlines = 1;
1134 
1135  // Insert extra new line before access specifiers.
1136  if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1137  RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1138  ++Newlines;
1139 
1140  // Remove empty lines after access specifiers.
1141  if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
1142  (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline))
1143  Newlines = std::min(1u, Newlines);
1144 
1145  if (Newlines)
1146  Indent = NewlineIndent;
1147 
1148  // Preprocessor directives get indented after the hash, if indented.
1149  if (Line.Type == LT_PreprocessorDirective || Line.Type == LT_ImportStatement)
1150  Indent = 0;
1151 
1152  Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent,
1153  Line.InPPDirective &&
1154  !RootToken.HasUnescapedNewline);
1155 }
1156 
1157 unsigned
1158 UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
1159  const AnnotatedLine *NextLine) const {
1160  // In preprocessor directives reserve two chars for trailing " \" if the
1161  // next line continues the preprocessor directive.
1162  bool ContinuesPPDirective =
1163  InPPDirective &&
1164  // If there is no next line, this is likely a child line and the parent
1165  // continues the preprocessor directive.
1166  (!NextLine ||
1167  (NextLine->InPPDirective &&
1168  // If there is an unescaped newline between this line and the next, the
1169  // next line starts a new preprocessor directive.
1170  !NextLine->First->HasUnescapedNewline));
1171  return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
1172 }
1173 
1174 } // namespace format
1175 } // namespace clang
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.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
Token Tok
The Token.
Definition: FormatToken.h:124
unsigned OriginalColumn
The original 0-based column of this token, including expanded tabs.
Definition: FormatToken.h:215
StringRef P
const FormatToken * getNextNonComment() const
Returns the next token ignoring comments.
Definition: FormatToken.h:456
bool LeadingEmptyLinesAffected
True if the leading empty lines of this line intersect with one of the input ranges.
bool IsFirst
Indicates that this is the first token of the file.
Definition: FormatToken.h:156
bool isAccessSpecifier(bool ColonRequired=true) const
Definition: FormatToken.h:335
unsigned TotalLength
The total length of the unwrapped line up to and including this token.
Definition: FormatToken.h:211
unsigned NewlinesBefore
The number of newlines immediately before the Token.
Definition: FormatToken.h:130
FormatToken * Next
The next token in the unwrapped line.
Definition: FormatToken.h:283
bool JavaScriptWrapImports
Whether to wrap JavaScript import/export statements.
Definition: Format.h:1145
LineState State
Should be used for Java.
Definition: Format.h:1168
Only merge functions defined inside a class.
Definition: Format.h:207
unsigned SpacesRequiredBefore
The number of spaces that should be inserted before this token.
Definition: FormatToken.h:179
bool isNot(T Kind) const
Definition: FormatToken.h:313
uint32_t Offset
Definition: CacheTokens.cpp:43
const FormatToken & Tok
bool ChildrenAffected
True if one of this line&#39;s children intersects with an input range.
#define UINT_MAX
Definition: limits.h:72
unsigned ColumnLimit
The column limit.
Definition: Format.h:840
bool KeepEmptyLinesAtTheStartOfBlocks
If true, the empty line at the start of blocks is kept.
Definition: Format.h:1155
bool isOneOf(A K1, B K2) const
Definition: FormatToken.h:306
WhitespaceManager class manages whitespace around tokens and their replacements.
Only merge empty functions.
Definition: Format.h:215
SourceLocation End
Should be used for JavaScript.
Definition: Format.h:1170
ContinuationIndenter * Indenter
const AnnotatedLine * Line
StateNode * Previous
static const size_t kInvalidIndex
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
Definition: Token.h:124
A wrapper around a Token storing information about the whitespace characters preceding it...
Definition: FormatToken.h:120
char __ovld __cnfn min(char x, char y)
Returns y if y < x, otherwise it returns x.
Implements a combinartorial exploration of all the different linebreaks unwrapped lines can be format...
bool Affected
True if this line should be formatted, i.e.
bool is(tok::TokenKind Kind) const
Definition: FormatToken.h:297
const bool InPPDirective
bool startsWith(Ts... Tokens) const
true if this line starts with the given tokens in order, ignoring comments.
LanguageKind Language
Language, this format style is targeted at.
Definition: Format.h:1185
ast_type_traits::DynTypedNode Node
Dataflow Directional Tag Classes.
Merge all functions fitting on a single line.
Definition: Format.h:234
SmallVector< AnnotatedLine *, 1 > Children
If this token starts a block, this contains all the unwrapped lines in it.
Definition: FormatToken.h:287
bool MustBreakBefore
Whether there must be a line break before this token.
Definition: FormatToken.h:162
unsigned MaxEmptyLinesToKeep
The maximum number of consecutive empty lines to keep.
Definition: Format.h:1229
bool HasUnescapedNewline
Whether there is at least one unescaped newline before the Token.
Definition: FormatToken.h:134
const FormatStyle & Style