clang  16.0.0git
WhitespaceManager.cpp
Go to the documentation of this file.
1 //===--- WhitespaceManager.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 ///
9 /// \file
10 /// This file implements WhitespaceManager class.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "WhitespaceManager.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include <algorithm>
18 
19 namespace clang {
20 namespace format {
21 
23  const Change &C1, const Change &C2) const {
24  return SourceMgr.isBeforeInTranslationUnit(
27 }
28 
30  bool CreateReplacement,
32  int Spaces, unsigned StartOfTokenColumn,
33  unsigned NewlinesBefore,
34  StringRef PreviousLinePostfix,
35  StringRef CurrentLinePrefix, bool IsAligned,
46 }
47 
49  unsigned Spaces,
50  unsigned StartOfTokenColumn,
51  bool IsAligned, bool InPPDirective) {
52  if (Tok.Finalized)
53  return;
54  Tok.setDecision((Newlines > 0) ? FD_Break : FD_Continue);
55  Changes.push_back(Change(Tok, /*CreateReplacement=*/true, Tok.WhitespaceRange,
56  Spaces, StartOfTokenColumn, Newlines, "", "",
57  IsAligned, InPPDirective && !Tok.IsFirst,
58  /*IsInsideToken=*/false));
59 }
60 
62  bool InPPDirective) {
63  if (Tok.Finalized)
64  return;
65  Changes.push_back(Change(Tok, /*CreateReplacement=*/false,
66  Tok.WhitespaceRange, /*Spaces=*/0,
67  Tok.OriginalColumn, Tok.NewlinesBefore, "", "",
68  /*IsAligned=*/false, InPPDirective && !Tok.IsFirst,
69  /*IsInsideToken=*/false));
70 }
71 
72 llvm::Error
74  return Replaces.add(Replacement);
75 }
76 
77 bool WhitespaceManager::inputUsesCRLF(StringRef Text, bool DefaultToCRLF) {
78  size_t LF = Text.count('\n');
79  size_t CR = Text.count('\r') * 2;
80  return LF == CR ? DefaultToCRLF : CR > LF;
81 }
82 
84  const FormatToken &Tok, unsigned Offset, unsigned ReplaceChars,
85  StringRef PreviousPostfix, StringRef CurrentPrefix, bool InPPDirective,
86  unsigned Newlines, int Spaces) {
87  if (Tok.Finalized)
88  return;
90  Changes.push_back(
91  Change(Tok, /*CreateReplacement=*/true,
92  SourceRange(Start, Start.getLocWithOffset(ReplaceChars)), Spaces,
93  std::max(0, Spaces), Newlines, PreviousPostfix, CurrentPrefix,
94  /*IsAligned=*/true, InPPDirective && !Tok.IsFirst,
95  /*IsInsideToken=*/true));
96 }
97 
99  if (Changes.empty())
100  return Replaces;
101 
102  llvm::sort(Changes, Change::IsBeforeInFile(SourceMgr));
103  calculateLineBreakInformation();
104  alignConsecutiveMacros();
105  alignConsecutiveDeclarations();
106  alignConsecutiveBitFields();
107  alignConsecutiveAssignments();
108  alignChainedConditionals();
109  alignTrailingComments();
110  alignEscapedNewlines();
111  alignArrayInitializers();
112  generateChanges();
113 
114  return Replaces;
115 }
116 
117 void WhitespaceManager::calculateLineBreakInformation() {
118  Changes[0].PreviousEndOfTokenColumn = 0;
119  Change *LastOutsideTokenChange = &Changes[0];
120  for (unsigned i = 1, e = Changes.size(); i != e; ++i) {
121  SourceLocation OriginalWhitespaceStart =
122  Changes[i].OriginalWhitespaceRange.getBegin();
123  SourceLocation PreviousOriginalWhitespaceEnd =
124  Changes[i - 1].OriginalWhitespaceRange.getEnd();
125  unsigned OriginalWhitespaceStartOffset =
126  SourceMgr.getFileOffset(OriginalWhitespaceStart);
127  unsigned PreviousOriginalWhitespaceEndOffset =
128  SourceMgr.getFileOffset(PreviousOriginalWhitespaceEnd);
129  assert(PreviousOriginalWhitespaceEndOffset <=
130  OriginalWhitespaceStartOffset);
131  const char *const PreviousOriginalWhitespaceEndData =
132  SourceMgr.getCharacterData(PreviousOriginalWhitespaceEnd);
133  StringRef Text(PreviousOriginalWhitespaceEndData,
134  SourceMgr.getCharacterData(OriginalWhitespaceStart) -
135  PreviousOriginalWhitespaceEndData);
136  // Usually consecutive changes would occur in consecutive tokens. This is
137  // not the case however when analyzing some preprocessor runs of the
138  // annotated lines. For example, in this code:
139  //
140  // #if A // line 1
141  // int i = 1;
142  // #else B // line 2
143  // int i = 2;
144  // #endif // line 3
145  //
146  // one of the runs will produce the sequence of lines marked with line 1, 2
147  // and 3. So the two consecutive whitespace changes just before '// line 2'
148  // and before '#endif // line 3' span multiple lines and tokens:
149  //
150  // #else B{change X}[// line 2
151  // int i = 2;
152  // ]{change Y}#endif // line 3
153  //
154  // For this reason, if the text between consecutive changes spans multiple
155  // newlines, the token length must be adjusted to the end of the original
156  // line of the token.
157  auto NewlinePos = Text.find_first_of('\n');
158  if (NewlinePos == StringRef::npos) {
159  Changes[i - 1].TokenLength = OriginalWhitespaceStartOffset -
160  PreviousOriginalWhitespaceEndOffset +
161  Changes[i].PreviousLinePostfix.size() +
162  Changes[i - 1].CurrentLinePrefix.size();
163  } else {
164  Changes[i - 1].TokenLength =
165  NewlinePos + Changes[i - 1].CurrentLinePrefix.size();
166  }
167 
168  // If there are multiple changes in this token, sum up all the changes until
169  // the end of the line.
170  if (Changes[i - 1].IsInsideToken && Changes[i - 1].NewlinesBefore == 0) {
171  LastOutsideTokenChange->TokenLength +=
172  Changes[i - 1].TokenLength + Changes[i - 1].Spaces;
173  } else {
174  LastOutsideTokenChange = &Changes[i - 1];
175  }
176 
177  Changes[i].PreviousEndOfTokenColumn =
178  Changes[i - 1].StartOfTokenColumn + Changes[i - 1].TokenLength;
179 
180  Changes[i - 1].IsTrailingComment =
181  (Changes[i].NewlinesBefore > 0 || Changes[i].Tok->is(tok::eof) ||
182  (Changes[i].IsInsideToken && Changes[i].Tok->is(tok::comment))) &&
183  Changes[i - 1].Tok->is(tok::comment) &&
184  // FIXME: This is a dirty hack. The problem is that
185  // BreakableLineCommentSection does comment reflow changes and here is
186  // the aligning of trailing comments. Consider the case where we reflow
187  // the second line up in this example:
188  //
189  // // line 1
190  // // line 2
191  //
192  // That amounts to 2 changes by BreakableLineCommentSection:
193  // - the first, delimited by (), for the whitespace between the tokens,
194  // - and second, delimited by [], for the whitespace at the beginning
195  // of the second token:
196  //
197  // // line 1(
198  // )[// ]line 2
199  //
200  // So in the end we have two changes like this:
201  //
202  // // line1()[ ]line 2
203  //
204  // Note that the OriginalWhitespaceStart of the second change is the
205  // same as the PreviousOriginalWhitespaceEnd of the first change.
206  // In this case, the below check ensures that the second change doesn't
207  // get treated as a trailing comment change here, since this might
208  // trigger additional whitespace to be wrongly inserted before "line 2"
209  // by the comment aligner here.
210  //
211  // For a proper solution we need a mechanism to say to WhitespaceManager
212  // that a particular change breaks the current sequence of trailing
213  // comments.
214  OriginalWhitespaceStart != PreviousOriginalWhitespaceEnd;
215  }
216  // FIXME: The last token is currently not always an eof token; in those
217  // cases, setting TokenLength of the last token to 0 is wrong.
218  Changes.back().TokenLength = 0;
219  Changes.back().IsTrailingComment = Changes.back().Tok->is(tok::comment);
220 
221  const WhitespaceManager::Change *LastBlockComment = nullptr;
222  for (auto &Change : Changes) {
223  // Reset the IsTrailingComment flag for changes inside of trailing comments
224  // so they don't get realigned later. Comment line breaks however still need
225  // to be aligned.
226  if (Change.IsInsideToken && Change.NewlinesBefore == 0)
227  Change.IsTrailingComment = false;
228  Change.StartOfBlockComment = nullptr;
229  Change.IndentationOffset = 0;
230  if (Change.Tok->is(tok::comment)) {
231  if (Change.Tok->is(TT_LineComment) || !Change.IsInsideToken) {
232  LastBlockComment = &Change;
233  } else if ((Change.StartOfBlockComment = LastBlockComment)) {
234  Change.IndentationOffset =
235  Change.StartOfTokenColumn -
236  Change.StartOfBlockComment->StartOfTokenColumn;
237  }
238  } else {
239  LastBlockComment = nullptr;
240  }
241  }
242 
243  // Compute conditional nesting level
244  // Level is increased for each conditional, unless this conditional continues
245  // a chain of conditional, i.e. starts immediately after the colon of another
246  // conditional.
247  SmallVector<bool, 16> ScopeStack;
248  int ConditionalsLevel = 0;
249  for (auto &Change : Changes) {
250  for (unsigned i = 0, e = Change.Tok->FakeLParens.size(); i != e; ++i) {
251  bool isNestedConditional =
252  Change.Tok->FakeLParens[e - 1 - i] == prec::Conditional &&
253  !(i == 0 && Change.Tok->Previous &&
254  Change.Tok->Previous->is(TT_ConditionalExpr) &&
255  Change.Tok->Previous->is(tok::colon));
256  if (isNestedConditional)
257  ++ConditionalsLevel;
258  ScopeStack.push_back(isNestedConditional);
259  }
260 
261  Change.ConditionalsLevel = ConditionalsLevel;
262 
263  for (unsigned i = Change.Tok->FakeRParens; i > 0 && ScopeStack.size(); --i)
264  if (ScopeStack.pop_back_val())
265  --ConditionalsLevel;
266  }
267 }
268 
269 // Align a single sequence of tokens, see AlignTokens below.
270 // Column - The token for which Matches returns true is moved to this column.
271 // RightJustify - Whether it is the token's right end or left end that gets
272 // moved to that column.
273 template <typename F>
274 static void
275 AlignTokenSequence(const FormatStyle &Style, unsigned Start, unsigned End,
276  unsigned Column, bool RightJustify, F &&Matches,
278  bool FoundMatchOnLine = false;
279  int Shift = 0;
280 
281  // ScopeStack keeps track of the current scope depth. It contains indices of
282  // the first token on each scope.
283  // We only run the "Matches" function on tokens from the outer-most scope.
284  // However, we do need to pay special attention to one class of tokens
285  // that are not in the outer-most scope, and that is function parameters
286  // which are split across multiple lines, as illustrated by this example:
287  // double a(int x);
288  // int b(int y,
289  // double z);
290  // In the above example, we need to take special care to ensure that
291  // 'double z' is indented along with it's owning function 'b'.
292  // The same holds for calling a function:
293  // double a = foo(x);
294  // int b = bar(foo(y),
295  // foor(z));
296  // Similar for broken string literals:
297  // double x = 3.14;
298  // auto s = "Hello"
299  // "World";
300  // Special handling is required for 'nested' ternary operators.
301  SmallVector<unsigned, 16> ScopeStack;
302 
303  for (unsigned i = Start; i != End; ++i) {
304  if (ScopeStack.size() != 0 &&
305  Changes[i].indentAndNestingLevel() <
306  Changes[ScopeStack.back()].indentAndNestingLevel()) {
307  ScopeStack.pop_back();
308  }
309 
310  // Compare current token to previous non-comment token to ensure whether
311  // it is in a deeper scope or not.
312  unsigned PreviousNonComment = i - 1;
313  while (PreviousNonComment > Start &&
314  Changes[PreviousNonComment].Tok->is(tok::comment)) {
315  --PreviousNonComment;
316  }
317  if (i != Start && Changes[i].indentAndNestingLevel() >
318  Changes[PreviousNonComment].indentAndNestingLevel()) {
319  ScopeStack.push_back(i);
320  }
321 
322  bool InsideNestedScope = ScopeStack.size() != 0;
323  bool ContinuedStringLiteral = i > Start &&
324  Changes[i].Tok->is(tok::string_literal) &&
325  Changes[i - 1].Tok->is(tok::string_literal);
326  bool SkipMatchCheck = InsideNestedScope || ContinuedStringLiteral;
327 
328  if (Changes[i].NewlinesBefore > 0 && !SkipMatchCheck) {
329  Shift = 0;
330  FoundMatchOnLine = false;
331  }
332 
333  // If this is the first matching token to be aligned, remember by how many
334  // spaces it has to be shifted, so the rest of the changes on the line are
335  // shifted by the same amount
336  if (!FoundMatchOnLine && !SkipMatchCheck && Matches(Changes[i])) {
337  FoundMatchOnLine = true;
338  Shift = Column - (RightJustify ? Changes[i].TokenLength : 0) -
339  Changes[i].StartOfTokenColumn;
340  Changes[i].Spaces += Shift;
341  // FIXME: This is a workaround that should be removed when we fix
342  // http://llvm.org/PR53699. An assertion later below verifies this.
343  if (Changes[i].NewlinesBefore == 0) {
344  Changes[i].Spaces =
345  std::max(Changes[i].Spaces,
346  static_cast<int>(Changes[i].Tok->SpacesRequiredBefore));
347  }
348  }
349 
350  // This is for function parameters that are split across multiple lines,
351  // as mentioned in the ScopeStack comment.
352  if (InsideNestedScope && Changes[i].NewlinesBefore > 0) {
353  unsigned ScopeStart = ScopeStack.back();
354  auto ShouldShiftBeAdded = [&] {
355  // Function declaration
356  if (Changes[ScopeStart - 1].Tok->is(TT_FunctionDeclarationName))
357  return true;
358 
359  // Lambda.
360  if (Changes[ScopeStart - 1].Tok->is(TT_LambdaLBrace))
361  return false;
362 
363  // Continued function declaration
364  if (ScopeStart > Start + 1 &&
365  Changes[ScopeStart - 2].Tok->is(TT_FunctionDeclarationName)) {
366  return true;
367  }
368 
369  // Continued function call
370  if (ScopeStart > Start + 1 &&
371  Changes[ScopeStart - 2].Tok->is(tok::identifier) &&
372  Changes[ScopeStart - 1].Tok->is(tok::l_paren) &&
373  Changes[ScopeStart].Tok->isNot(TT_LambdaLSquare)) {
374  if (Changes[i].Tok->MatchingParen &&
375  Changes[i].Tok->MatchingParen->is(TT_LambdaLBrace)) {
376  return false;
377  }
378  if (Changes[ScopeStart].NewlinesBefore > 0)
379  return false;
380  if (Changes[i].Tok->is(tok::l_brace) &&
381  Changes[i].Tok->is(BK_BracedInit)) {
382  return true;
383  }
384  return Style.BinPackArguments;
385  }
386 
387  // Ternary operator
388  if (Changes[i].Tok->is(TT_ConditionalExpr))
389  return true;
390 
391  // Period Initializer .XXX = 1.
392  if (Changes[i].Tok->is(TT_DesignatedInitializerPeriod))
393  return true;
394 
395  // Continued ternary operator
396  if (Changes[i].Tok->Previous &&
397  Changes[i].Tok->Previous->is(TT_ConditionalExpr)) {
398  return true;
399  }
400 
401  // Continued direct-list-initialization using braced list.
402  if (ScopeStart > Start + 1 &&
403  Changes[ScopeStart - 2].Tok->is(tok::identifier) &&
404  Changes[ScopeStart - 1].Tok->is(tok::l_brace) &&
405  Changes[i].Tok->is(tok::l_brace) &&
406  Changes[i].Tok->is(BK_BracedInit)) {
407  return true;
408  }
409 
410  // Continued braced list.
411  if (ScopeStart > Start + 1 &&
412  Changes[ScopeStart - 2].Tok->isNot(tok::identifier) &&
413  Changes[ScopeStart - 1].Tok->is(tok::l_brace) &&
414  Changes[i].Tok->isNot(tok::r_brace)) {
415  for (unsigned OuterScopeStart : llvm::reverse(ScopeStack)) {
416  // Lambda.
417  if (OuterScopeStart > Start &&
418  Changes[OuterScopeStart - 1].Tok->is(TT_LambdaLBrace)) {
419  return false;
420  }
421  }
422  if (Changes[ScopeStart].NewlinesBefore > 0)
423  return false;
424  return true;
425  }
426 
427  return false;
428  };
429 
430  if (ShouldShiftBeAdded())
431  Changes[i].Spaces += Shift;
432  }
433 
434  if (ContinuedStringLiteral)
435  Changes[i].Spaces += Shift;
436 
437  // We should not remove required spaces unless we break the line before.
438  assert(Shift >= 0 || Changes[i].NewlinesBefore > 0 ||
439  Changes[i].Spaces >=
440  static_cast<int>(Changes[i].Tok->SpacesRequiredBefore) ||
441  Changes[i].Tok->is(tok::eof));
442 
443  Changes[i].StartOfTokenColumn += Shift;
444  if (i + 1 != Changes.size())
445  Changes[i + 1].PreviousEndOfTokenColumn += Shift;
446 
447  // If PointerAlignment is PAS_Right, keep *s or &s next to the token
448  if (Style.PointerAlignment == FormatStyle::PAS_Right &&
449  Changes[i].Spaces != 0) {
450  for (int Previous = i - 1;
451  Previous >= 0 &&
452  Changes[Previous].Tok->getType() == TT_PointerOrReference;
453  --Previous) {
454  Changes[Previous + 1].Spaces -= Shift;
455  Changes[Previous].Spaces += Shift;
456  Changes[Previous].StartOfTokenColumn += Shift;
457  }
458  }
459  }
460 }
461 
462 // Walk through a subset of the changes, starting at StartAt, and find
463 // sequences of matching tokens to align. To do so, keep track of the lines and
464 // whether or not a matching token was found on a line. If a matching token is
465 // found, extend the current sequence. If the current line cannot be part of a
466 // sequence, e.g. because there is an empty line before it or it contains only
467 // non-matching tokens, finalize the previous sequence.
468 // The value returned is the token on which we stopped, either because we
469 // exhausted all items inside Changes, or because we hit a scope level higher
470 // than our initial scope.
471 // This function is recursive. Each invocation processes only the scope level
472 // equal to the initial level, which is the level of Changes[StartAt].
473 // If we encounter a scope level greater than the initial level, then we call
474 // ourselves recursively, thereby avoiding the pollution of the current state
475 // with the alignment requirements of the nested sub-level. This recursive
476 // behavior is necessary for aligning function prototypes that have one or more
477 // arguments.
478 // If this function encounters a scope level less than the initial level,
479 // it returns the current position.
480 // There is a non-obvious subtlety in the recursive behavior: Even though we
481 // defer processing of nested levels to recursive invocations of this
482 // function, when it comes time to align a sequence of tokens, we run the
483 // alignment on the entire sequence, including the nested levels.
484 // When doing so, most of the nested tokens are skipped, because their
485 // alignment was already handled by the recursive invocations of this function.
486 // However, the special exception is that we do NOT skip function parameters
487 // that are split across multiple lines. See the test case in FormatTest.cpp
488 // that mentions "split function parameter alignment" for an example of this.
489 // When the parameter RightJustify is true, the operator will be
490 // right-justified. It is used to align compound assignments like `+=` and `=`.
491 // When RightJustify and ACS.PadOperators are true, operators in each block to
492 // be aligned will be padded on the left to the same length before aligning.
493 template <typename F>
494 static unsigned AlignTokens(const FormatStyle &Style, F &&Matches,
496  unsigned StartAt,
497  const FormatStyle::AlignConsecutiveStyle &ACS = {},
498  bool RightJustify = false) {
499  // We arrange each line in 3 parts. The operator to be aligned (the anchor),
500  // and text to its left and right. In the aligned text the width of each part
501  // will be the maximum of that over the block that has been aligned. Maximum
502  // widths of each part so far. When RightJustify is true and ACS.PadOperators
503  // is false, the part from start of line to the right end of the anchor.
504  // Otherwise, only the part to the left of the anchor. Including the space
505  // that exists on its left from the start. Not including the padding added on
506  // the left to right-justify the anchor.
507  unsigned WidthLeft = 0;
508  // The operator to be aligned when RightJustify is true and ACS.PadOperators
509  // is false. 0 otherwise.
510  unsigned WidthAnchor = 0;
511  // Width to the right of the anchor. Plus width of the anchor when
512  // RightJustify is false.
513  unsigned WidthRight = 0;
514 
515  // Line number of the start and the end of the current token sequence.
516  unsigned StartOfSequence = 0;
517  unsigned EndOfSequence = 0;
518 
519  // Measure the scope level (i.e. depth of (), [], {}) of the first token, and
520  // abort when we hit any token in a higher scope than the starting one.
521  auto IndentAndNestingLevel = StartAt < Changes.size()
522  ? Changes[StartAt].indentAndNestingLevel()
523  : std::tuple<unsigned, unsigned, unsigned>();
524 
525  // Keep track if the first token has a non-zero indent and nesting level.
526  // This can happen when aligning the contents of "#else" preprocessor blocks,
527  // which is done separately.
528  bool HasInitialIndentAndNesting =
529  StartAt == 0 &&
530  IndentAndNestingLevel > std::tuple<unsigned, unsigned, unsigned>();
531 
532  // Keep track of the number of commas before the matching tokens, we will only
533  // align a sequence of matching tokens if they are preceded by the same number
534  // of commas.
535  unsigned CommasBeforeLastMatch = 0;
536  unsigned CommasBeforeMatch = 0;
537 
538  // Whether a matching token has been found on the current line.
539  bool FoundMatchOnLine = false;
540 
541  // Whether the current line consists purely of comments.
542  bool LineIsComment = true;
543 
544  // Aligns a sequence of matching tokens, on the MinColumn column.
545  //
546  // Sequences start from the first matching token to align, and end at the
547  // first token of the first line that doesn't need to be aligned.
548  //
549  // We need to adjust the StartOfTokenColumn of each Change that is on a line
550  // containing any matching token to be aligned and located after such token.
551  auto AlignCurrentSequence = [&] {
552  if (StartOfSequence > 0 && StartOfSequence < EndOfSequence) {
553  AlignTokenSequence(Style, StartOfSequence, EndOfSequence,
554  WidthLeft + WidthAnchor, RightJustify, Matches,
555  Changes);
556  }
557  WidthLeft = 0;
558  WidthAnchor = 0;
559  WidthRight = 0;
560  StartOfSequence = 0;
561  EndOfSequence = 0;
562  };
563 
564  unsigned i = StartAt;
565  for (unsigned e = Changes.size(); i != e; ++i) {
566  if (Changes[i].indentAndNestingLevel() < IndentAndNestingLevel) {
567  if (!HasInitialIndentAndNesting)
568  break;
569  // The contents of preprocessor blocks are aligned separately.
570  // If the initial preprocessor block is indented or nested (e.g. it's in
571  // a function), do not align and exit after finishing this scope block.
572  // Instead, align, and then lower the baseline indent and nesting level
573  // in order to continue aligning subsequent blocks.
574  EndOfSequence = i;
575  AlignCurrentSequence();
576  IndentAndNestingLevel =
577  Changes[i].indentAndNestingLevel(); // new baseline
578  }
579 
580  if (Changes[i].NewlinesBefore != 0) {
581  CommasBeforeMatch = 0;
582  EndOfSequence = i;
583 
584  // Whether to break the alignment sequence because of an empty line.
585  bool EmptyLineBreak =
586  (Changes[i].NewlinesBefore > 1) && !ACS.AcrossEmptyLines;
587 
588  // Whether to break the alignment sequence because of a line without a
589  // match.
590  bool NoMatchBreak =
591  !FoundMatchOnLine && !(LineIsComment && ACS.AcrossComments);
592 
593  if (EmptyLineBreak || NoMatchBreak)
594  AlignCurrentSequence();
595 
596  // A new line starts, re-initialize line status tracking bools.
597  // Keep the match state if a string literal is continued on this line.
598  if (i == 0 || !Changes[i].Tok->is(tok::string_literal) ||
599  !Changes[i - 1].Tok->is(tok::string_literal)) {
600  FoundMatchOnLine = false;
601  }
602  LineIsComment = true;
603  }
604 
605  if (!Changes[i].Tok->is(tok::comment))
606  LineIsComment = false;
607 
608  if (Changes[i].Tok->is(tok::comma)) {
609  ++CommasBeforeMatch;
610  } else if (Changes[i].indentAndNestingLevel() > IndentAndNestingLevel) {
611  // Call AlignTokens recursively, skipping over this scope block.
612  unsigned StoppedAt = AlignTokens(Style, Matches, Changes, i, ACS);
613  i = StoppedAt - 1;
614  continue;
615  }
616 
617  if (!Matches(Changes[i]))
618  continue;
619 
620  // If there is more than one matching token per line, or if the number of
621  // preceding commas, do not match anymore, end the sequence.
622  if (FoundMatchOnLine || CommasBeforeMatch != CommasBeforeLastMatch)
623  AlignCurrentSequence();
624 
625  CommasBeforeLastMatch = CommasBeforeMatch;
626  FoundMatchOnLine = true;
627 
628  if (StartOfSequence == 0)
629  StartOfSequence = i;
630 
631  unsigned ChangeWidthLeft = Changes[i].StartOfTokenColumn;
632  unsigned ChangeWidthAnchor = 0;
633  unsigned ChangeWidthRight = 0;
634  if (RightJustify)
635  if (ACS.PadOperators)
636  ChangeWidthAnchor = Changes[i].TokenLength;
637  else
638  ChangeWidthLeft += Changes[i].TokenLength;
639  else
640  ChangeWidthRight = Changes[i].TokenLength;
641  for (unsigned j = i + 1; j != e && Changes[j].NewlinesBefore == 0; ++j) {
642  ChangeWidthRight += Changes[j].Spaces;
643  // Changes are generally 1:1 with the tokens, but a change could also be
644  // inside of a token, in which case it's counted more than once: once for
645  // the whitespace surrounding the token (!IsInsideToken) and once for
646  // each whitespace change within it (IsInsideToken).
647  // Therefore, changes inside of a token should only count the space.
648  if (!Changes[j].IsInsideToken)
649  ChangeWidthRight += Changes[j].TokenLength;
650  }
651 
652  // If we are restricted by the maximum column width, end the sequence.
653  unsigned NewLeft = std::max(ChangeWidthLeft, WidthLeft);
654  unsigned NewAnchor = std::max(ChangeWidthAnchor, WidthAnchor);
655  unsigned NewRight = std::max(ChangeWidthRight, WidthRight);
656  // `ColumnLimit == 0` means there is no column limit.
657  if (Style.ColumnLimit != 0 &&
658  Style.ColumnLimit < NewLeft + NewAnchor + NewRight) {
659  AlignCurrentSequence();
660  StartOfSequence = i;
661  WidthLeft = ChangeWidthLeft;
662  WidthAnchor = ChangeWidthAnchor;
663  WidthRight = ChangeWidthRight;
664  } else {
665  WidthLeft = NewLeft;
666  WidthAnchor = NewAnchor;
667  WidthRight = NewRight;
668  }
669  }
670 
671  EndOfSequence = i;
672  AlignCurrentSequence();
673  return i;
674 }
675 
676 // Aligns a sequence of matching tokens, on the MinColumn column.
677 //
678 // Sequences start from the first matching token to align, and end at the
679 // first token of the first line that doesn't need to be aligned.
680 //
681 // We need to adjust the StartOfTokenColumn of each Change that is on a line
682 // containing any matching token to be aligned and located after such token.
683 static void AlignMacroSequence(
684  unsigned &StartOfSequence, unsigned &EndOfSequence, unsigned &MinColumn,
685  unsigned &MaxColumn, bool &FoundMatchOnLine,
686  std::function<bool(const WhitespaceManager::Change &C)> AlignMacrosMatches,
688  if (StartOfSequence > 0 && StartOfSequence < EndOfSequence) {
689 
690  FoundMatchOnLine = false;
691  int Shift = 0;
692 
693  for (unsigned I = StartOfSequence; I != EndOfSequence; ++I) {
694  if (Changes[I].NewlinesBefore > 0) {
695  Shift = 0;
696  FoundMatchOnLine = false;
697  }
698 
699  // If this is the first matching token to be aligned, remember by how many
700  // spaces it has to be shifted, so the rest of the changes on the line are
701  // shifted by the same amount
702  if (!FoundMatchOnLine && AlignMacrosMatches(Changes[I])) {
703  FoundMatchOnLine = true;
704  Shift = MinColumn - Changes[I].StartOfTokenColumn;
705  Changes[I].Spaces += Shift;
706  }
707 
708  assert(Shift >= 0);
709  Changes[I].StartOfTokenColumn += Shift;
710  if (I + 1 != Changes.size())
711  Changes[I + 1].PreviousEndOfTokenColumn += Shift;
712  }
713  }
714 
715  MinColumn = 0;
716  MaxColumn = UINT_MAX;
717  StartOfSequence = 0;
718  EndOfSequence = 0;
719 }
720 
721 void WhitespaceManager::alignConsecutiveMacros() {
722  if (!Style.AlignConsecutiveMacros.Enabled)
723  return;
724 
725  auto AlignMacrosMatches = [](const Change &C) {
726  const FormatToken *Current = C.Tok;
727  unsigned SpacesRequiredBefore = 1;
728 
729  if (Current->SpacesRequiredBefore == 0 || !Current->Previous)
730  return false;
731 
732  Current = Current->Previous;
733 
734  // If token is a ")", skip over the parameter list, to the
735  // token that precedes the "("
736  if (Current->is(tok::r_paren) && Current->MatchingParen) {
737  Current = Current->MatchingParen->Previous;
738  SpacesRequiredBefore = 0;
739  }
740 
741  if (!Current || !Current->is(tok::identifier))
742  return false;
743 
744  if (!Current->Previous || !Current->Previous->is(tok::pp_define))
745  return false;
746 
747  // For a macro function, 0 spaces are required between the
748  // identifier and the lparen that opens the parameter list.
749  // For a simple macro, 1 space is required between the
750  // identifier and the first token of the defined value.
751  return Current->Next->SpacesRequiredBefore == SpacesRequiredBefore;
752  };
753 
754  unsigned MinColumn = 0;
755  unsigned MaxColumn = UINT_MAX;
756 
757  // Start and end of the token sequence we're processing.
758  unsigned StartOfSequence = 0;
759  unsigned EndOfSequence = 0;
760 
761  // Whether a matching token has been found on the current line.
762  bool FoundMatchOnLine = false;
763 
764  // Whether the current line consists only of comments
765  bool LineIsComment = true;
766 
767  unsigned I = 0;
768  for (unsigned E = Changes.size(); I != E; ++I) {
769  if (Changes[I].NewlinesBefore != 0) {
770  EndOfSequence = I;
771 
772  // Whether to break the alignment sequence because of an empty line.
773  bool EmptyLineBreak = (Changes[I].NewlinesBefore > 1) &&
774  !Style.AlignConsecutiveMacros.AcrossEmptyLines;
775 
776  // Whether to break the alignment sequence because of a line without a
777  // match.
778  bool NoMatchBreak =
779  !FoundMatchOnLine &&
780  !(LineIsComment && Style.AlignConsecutiveMacros.AcrossComments);
781 
782  if (EmptyLineBreak || NoMatchBreak) {
783  AlignMacroSequence(StartOfSequence, EndOfSequence, MinColumn, MaxColumn,
784  FoundMatchOnLine, AlignMacrosMatches, Changes);
785  }
786 
787  // A new line starts, re-initialize line status tracking bools.
788  FoundMatchOnLine = false;
789  LineIsComment = true;
790  }
791 
792  if (!Changes[I].Tok->is(tok::comment))
793  LineIsComment = false;
794 
795  if (!AlignMacrosMatches(Changes[I]))
796  continue;
797 
798  FoundMatchOnLine = true;
799 
800  if (StartOfSequence == 0)
801  StartOfSequence = I;
802 
803  unsigned ChangeMinColumn = Changes[I].StartOfTokenColumn;
804  int LineLengthAfter = -Changes[I].Spaces;
805  for (unsigned j = I; j != E && Changes[j].NewlinesBefore == 0; ++j)
806  LineLengthAfter += Changes[j].Spaces + Changes[j].TokenLength;
807  unsigned ChangeMaxColumn = Style.ColumnLimit - LineLengthAfter;
808 
809  MinColumn = std::max(MinColumn, ChangeMinColumn);
810  MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
811  }
812 
813  EndOfSequence = I;
814  AlignMacroSequence(StartOfSequence, EndOfSequence, MinColumn, MaxColumn,
815  FoundMatchOnLine, AlignMacrosMatches, Changes);
816 }
817 
818 void WhitespaceManager::alignConsecutiveAssignments() {
819  if (!Style.AlignConsecutiveAssignments.Enabled)
820  return;
821 
822  AlignTokens(
823  Style,
824  [&](const Change &C) {
825  // Do not align on equal signs that are first on a line.
826  if (C.NewlinesBefore > 0)
827  return false;
828 
829  // Do not align on equal signs that are last on a line.
830  if (&C != &Changes.back() && (&C + 1)->NewlinesBefore > 0)
831  return false;
832 
833  // Do not align operator= overloads.
834  FormatToken *Previous = C.Tok->getPreviousNonComment();
835  if (Previous && Previous->is(tok::kw_operator))
836  return false;
837 
838  return Style.AlignConsecutiveAssignments.AlignCompound
839  ? C.Tok->getPrecedence() == prec::Assignment
840  : C.Tok->is(tok::equal);
841  },
842  Changes, /*StartAt=*/0, Style.AlignConsecutiveAssignments,
843  /*RightJustify=*/true);
844 }
845 
846 void WhitespaceManager::alignConsecutiveBitFields() {
847  if (!Style.AlignConsecutiveBitFields.Enabled)
848  return;
849 
850  AlignTokens(
851  Style,
852  [&](Change const &C) {
853  // Do not align on ':' that is first on a line.
854  if (C.NewlinesBefore > 0)
855  return false;
856 
857  // Do not align on ':' that is last on a line.
858  if (&C != &Changes.back() && (&C + 1)->NewlinesBefore > 0)
859  return false;
860 
861  return C.Tok->is(TT_BitFieldColon);
862  },
863  Changes, /*StartAt=*/0, Style.AlignConsecutiveBitFields);
864 }
865 
866 void WhitespaceManager::alignConsecutiveDeclarations() {
867  if (!Style.AlignConsecutiveDeclarations.Enabled)
868  return;
869 
870  AlignTokens(
871  Style,
872  [](Change const &C) {
873  if (C.Tok->is(TT_FunctionDeclarationName))
874  return true;
875  if (C.Tok->isNot(TT_StartOfName))
876  return false;
877  if (C.Tok->Previous &&
878  C.Tok->Previous->is(TT_StatementAttributeLikeMacro))
879  return false;
880  // Check if there is a subsequent name that starts the same declaration.
881  for (FormatToken *Next = C.Tok->Next; Next; Next = Next->Next) {
882  if (Next->is(tok::comment))
883  continue;
884  if (Next->is(TT_PointerOrReference))
885  return false;
886  if (!Next->Tok.getIdentifierInfo())
887  break;
888  if (Next->isOneOf(TT_StartOfName, TT_FunctionDeclarationName,
889  tok::kw_operator)) {
890  return false;
891  }
892  }
893  return true;
894  },
895  Changes, /*StartAt=*/0, Style.AlignConsecutiveDeclarations);
896 }
897 
898 void WhitespaceManager::alignChainedConditionals() {
899  if (Style.BreakBeforeTernaryOperators) {
900  AlignTokens(
901  Style,
902  [](Change const &C) {
903  // Align question operators and last colon
904  return C.Tok->is(TT_ConditionalExpr) &&
905  ((C.Tok->is(tok::question) && !C.NewlinesBefore) ||
906  (C.Tok->is(tok::colon) && C.Tok->Next &&
907  (C.Tok->Next->FakeLParens.size() == 0 ||
908  C.Tok->Next->FakeLParens.back() != prec::Conditional)));
909  },
910  Changes, /*StartAt=*/0);
911  } else {
912  static auto AlignWrappedOperand = [](Change const &C) {
913  FormatToken *Previous = C.Tok->getPreviousNonComment();
914  return C.NewlinesBefore && Previous && Previous->is(TT_ConditionalExpr) &&
915  (Previous->is(tok::colon) &&
916  (C.Tok->FakeLParens.size() == 0 ||
917  C.Tok->FakeLParens.back() != prec::Conditional));
918  };
919  // Ensure we keep alignment of wrapped operands with non-wrapped operands
920  // Since we actually align the operators, the wrapped operands need the
921  // extra offset to be properly aligned.
922  for (Change &C : Changes)
923  if (AlignWrappedOperand(C))
924  C.StartOfTokenColumn -= 2;
925  AlignTokens(
926  Style,
927  [this](Change const &C) {
928  // Align question operators if next operand is not wrapped, as
929  // well as wrapped operands after question operator or last
930  // colon in conditional sequence
931  return (C.Tok->is(TT_ConditionalExpr) && C.Tok->is(tok::question) &&
932  &C != &Changes.back() && (&C + 1)->NewlinesBefore == 0 &&
933  !(&C + 1)->IsTrailingComment) ||
934  AlignWrappedOperand(C);
935  },
936  Changes, /*StartAt=*/0);
937  }
938 }
939 
940 void WhitespaceManager::alignTrailingComments() {
941  unsigned MinColumn = 0;
942  unsigned MaxColumn = UINT_MAX;
943  unsigned StartOfSequence = 0;
944  bool BreakBeforeNext = false;
945  unsigned Newlines = 0;
946  unsigned int NewLineThreshold = 1;
947  if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Always)
948  NewLineThreshold = Style.AlignTrailingComments.OverEmptyLines + 1;
949 
950  for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
951  if (Changes[i].StartOfBlockComment)
952  continue;
953  Newlines += Changes[i].NewlinesBefore;
954  if (!Changes[i].IsTrailingComment)
955  continue;
956 
957  if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Leave) {
958  auto OriginalSpaces =
959  Changes[i].OriginalWhitespaceRange.getEnd().getRawEncoding() -
960  Changes[i].OriginalWhitespaceRange.getBegin().getRawEncoding() -
961  Changes[i].Tok->NewlinesBefore;
962  unsigned RestoredLineLength = Changes[i].StartOfTokenColumn +
963  Changes[i].TokenLength + OriginalSpaces;
964  // If leaving comments makes the line exceed the column limit, give up to
965  // leave the comments.
966  if (RestoredLineLength >= Style.ColumnLimit && Style.ColumnLimit != 0)
967  break;
968  Changes[i].Spaces = OriginalSpaces;
969  continue;
970  }
971 
972  unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
973  unsigned ChangeMaxColumn;
974 
975  if (Style.ColumnLimit == 0)
976  ChangeMaxColumn = UINT_MAX;
977  else if (Style.ColumnLimit >= Changes[i].TokenLength)
978  ChangeMaxColumn = Style.ColumnLimit - Changes[i].TokenLength;
979  else
980  ChangeMaxColumn = ChangeMinColumn;
981 
982  // If we don't create a replacement for this change, we have to consider
983  // it to be immovable.
984  if (!Changes[i].CreateReplacement)
985  ChangeMaxColumn = ChangeMinColumn;
986 
987  if (i + 1 != e && Changes[i + 1].ContinuesPPDirective)
988  ChangeMaxColumn -= 2;
989  // If this comment follows an } in column 0, it probably documents the
990  // closing of a namespace and we don't want to align it.
991  bool FollowsRBraceInColumn0 = i > 0 && Changes[i].NewlinesBefore == 0 &&
992  Changes[i - 1].Tok->is(tok::r_brace) &&
993  Changes[i - 1].StartOfTokenColumn == 0;
994  bool WasAlignedWithStartOfNextLine = false;
995  if (Changes[i].NewlinesBefore >= 1) { // A comment on its own line.
996  unsigned CommentColumn = SourceMgr.getSpellingColumnNumber(
997  Changes[i].OriginalWhitespaceRange.getEnd());
998  for (unsigned j = i + 1; j != e; ++j) {
999  if (Changes[j].Tok->is(tok::comment))
1000  continue;
1001 
1002  unsigned NextColumn = SourceMgr.getSpellingColumnNumber(
1003  Changes[j].OriginalWhitespaceRange.getEnd());
1004  // The start of the next token was previously aligned with the
1005  // start of this comment.
1006  WasAlignedWithStartOfNextLine =
1007  CommentColumn == NextColumn ||
1008  CommentColumn == NextColumn + Style.IndentWidth;
1009  break;
1010  }
1011  }
1012  if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never ||
1013  FollowsRBraceInColumn0) {
1014  alignTrailingComments(StartOfSequence, i, MinColumn);
1015  MinColumn = ChangeMinColumn;
1016  MaxColumn = ChangeMinColumn;
1017  StartOfSequence = i;
1018  } else if (BreakBeforeNext || Newlines > NewLineThreshold ||
1019  (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) ||
1020  // Break the comment sequence if the previous line did not end
1021  // in a trailing comment.
1022  (Changes[i].NewlinesBefore == 1 && i > 0 &&
1023  !Changes[i - 1].IsTrailingComment) ||
1024  WasAlignedWithStartOfNextLine) {
1025  alignTrailingComments(StartOfSequence, i, MinColumn);
1026  MinColumn = ChangeMinColumn;
1027  MaxColumn = ChangeMaxColumn;
1028  StartOfSequence = i;
1029  } else {
1030  MinColumn = std::max(MinColumn, ChangeMinColumn);
1031  MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
1032  }
1033  BreakBeforeNext = (i == 0) || (Changes[i].NewlinesBefore > 1) ||
1034  // Never start a sequence with a comment at the beginning
1035  // of the line.
1036  (Changes[i].NewlinesBefore == 1 && StartOfSequence == i);
1037  Newlines = 0;
1038  }
1039  alignTrailingComments(StartOfSequence, Changes.size(), MinColumn);
1040 }
1041 
1042 void WhitespaceManager::alignTrailingComments(unsigned Start, unsigned End,
1043  unsigned Column) {
1044  for (unsigned i = Start; i != End; ++i) {
1045  int Shift = 0;
1046  if (Changes[i].IsTrailingComment)
1047  Shift = Column - Changes[i].StartOfTokenColumn;
1048  if (Changes[i].StartOfBlockComment) {
1049  Shift = Changes[i].IndentationOffset +
1050  Changes[i].StartOfBlockComment->StartOfTokenColumn -
1051  Changes[i].StartOfTokenColumn;
1052  }
1053  if (Shift <= 0)
1054  continue;
1055  Changes[i].Spaces += Shift;
1056  if (i + 1 != Changes.size())
1057  Changes[i + 1].PreviousEndOfTokenColumn += Shift;
1058  Changes[i].StartOfTokenColumn += Shift;
1059  }
1060 }
1061 
1062 void WhitespaceManager::alignEscapedNewlines() {
1063  if (Style.AlignEscapedNewlines == FormatStyle::ENAS_DontAlign)
1064  return;
1065 
1066  bool AlignLeft = Style.AlignEscapedNewlines == FormatStyle::ENAS_Left;
1067  unsigned MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit;
1068  unsigned StartOfMacro = 0;
1069  for (unsigned i = 1, e = Changes.size(); i < e; ++i) {
1070  Change &C = Changes[i];
1071  if (C.NewlinesBefore > 0) {
1072  if (C.ContinuesPPDirective) {
1073  MaxEndOfLine = std::max(C.PreviousEndOfTokenColumn + 2, MaxEndOfLine);
1074  } else {
1075  alignEscapedNewlines(StartOfMacro + 1, i, MaxEndOfLine);
1076  MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit;
1077  StartOfMacro = i;
1078  }
1079  }
1080  }
1081  alignEscapedNewlines(StartOfMacro + 1, Changes.size(), MaxEndOfLine);
1082 }
1083 
1084 void WhitespaceManager::alignEscapedNewlines(unsigned Start, unsigned End,
1085  unsigned Column) {
1086  for (unsigned i = Start; i < End; ++i) {
1087  Change &C = Changes[i];
1088  if (C.NewlinesBefore > 0) {
1089  assert(C.ContinuesPPDirective);
1090  if (C.PreviousEndOfTokenColumn + 1 > Column)
1091  C.EscapedNewlineColumn = 0;
1092  else
1093  C.EscapedNewlineColumn = Column;
1094  }
1095  }
1096 }
1097 
1098 void WhitespaceManager::alignArrayInitializers() {
1099  if (Style.AlignArrayOfStructures == FormatStyle::AIAS_None)
1100  return;
1101 
1102  for (unsigned ChangeIndex = 1U, ChangeEnd = Changes.size();
1103  ChangeIndex < ChangeEnd; ++ChangeIndex) {
1104  auto &C = Changes[ChangeIndex];
1105  if (C.Tok->IsArrayInitializer) {
1106  bool FoundComplete = false;
1107  for (unsigned InsideIndex = ChangeIndex + 1; InsideIndex < ChangeEnd;
1108  ++InsideIndex) {
1109  if (Changes[InsideIndex].Tok == C.Tok->MatchingParen) {
1110  alignArrayInitializers(ChangeIndex, InsideIndex + 1);
1111  ChangeIndex = InsideIndex + 1;
1112  FoundComplete = true;
1113  break;
1114  }
1115  }
1116  if (!FoundComplete)
1117  ChangeIndex = ChangeEnd;
1118  }
1119  }
1120 }
1121 
1122 void WhitespaceManager::alignArrayInitializers(unsigned Start, unsigned End) {
1123 
1124  if (Style.AlignArrayOfStructures == FormatStyle::AIAS_Right)
1125  alignArrayInitializersRightJustified(getCells(Start, End));
1126  else if (Style.AlignArrayOfStructures == FormatStyle::AIAS_Left)
1127  alignArrayInitializersLeftJustified(getCells(Start, End));
1128 }
1129 
1130 void WhitespaceManager::alignArrayInitializersRightJustified(
1131  CellDescriptions &&CellDescs) {
1132  if (!CellDescs.isRectangular())
1133  return;
1134 
1135  auto &Cells = CellDescs.Cells;
1136  // Now go through and fixup the spaces.
1137  auto *CellIter = Cells.begin();
1138  for (auto i = 0U; i < CellDescs.CellCounts[0]; ++i, ++CellIter) {
1139  unsigned NetWidth = 0U;
1140  if (isSplitCell(*CellIter))
1141  NetWidth = getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1142  auto CellWidth = getMaximumCellWidth(CellIter, NetWidth);
1143 
1144  if (Changes[CellIter->Index].Tok->is(tok::r_brace)) {
1145  // So in here we want to see if there is a brace that falls
1146  // on a line that was split. If so on that line we make sure that
1147  // the spaces in front of the brace are enough.
1148  const auto *Next = CellIter;
1149  do {
1150  const FormatToken *Previous = Changes[Next->Index].Tok->Previous;
1151  if (Previous && Previous->isNot(TT_LineComment)) {
1152  Changes[Next->Index].Spaces = 0;
1153  Changes[Next->Index].NewlinesBefore = 0;
1154  }
1155  Next = Next->NextColumnElement;
1156  } while (Next);
1157  // Unless the array is empty, we need the position of all the
1158  // immediately adjacent cells
1159  if (CellIter != Cells.begin()) {
1160  auto ThisNetWidth =
1161  getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1162  auto MaxNetWidth = getMaximumNetWidth(
1163  Cells.begin(), CellIter, CellDescs.InitialSpaces,
1164  CellDescs.CellCounts[0], CellDescs.CellCounts.size());
1165  if (ThisNetWidth < MaxNetWidth)
1166  Changes[CellIter->Index].Spaces = (MaxNetWidth - ThisNetWidth);
1167  auto RowCount = 1U;
1168  auto Offset = std::distance(Cells.begin(), CellIter);
1169  for (const auto *Next = CellIter->NextColumnElement; Next != nullptr;
1170  Next = Next->NextColumnElement) {
1171  auto *Start = (Cells.begin() + RowCount * CellDescs.CellCounts[0]);
1172  auto *End = Start + Offset;
1173  ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces);
1174  if (ThisNetWidth < MaxNetWidth)
1175  Changes[Next->Index].Spaces = (MaxNetWidth - ThisNetWidth);
1176  ++RowCount;
1177  }
1178  }
1179  } else {
1180  auto ThisWidth =
1181  calculateCellWidth(CellIter->Index, CellIter->EndIndex, true) +
1182  NetWidth;
1183  if (Changes[CellIter->Index].NewlinesBefore == 0) {
1184  Changes[CellIter->Index].Spaces = (CellWidth - (ThisWidth + NetWidth));
1185  Changes[CellIter->Index].Spaces += (i > 0) ? 1 : 0;
1186  }
1187  alignToStartOfCell(CellIter->Index, CellIter->EndIndex);
1188  for (const auto *Next = CellIter->NextColumnElement; Next != nullptr;
1189  Next = Next->NextColumnElement) {
1190  ThisWidth =
1191  calculateCellWidth(Next->Index, Next->EndIndex, true) + NetWidth;
1192  if (Changes[Next->Index].NewlinesBefore == 0) {
1193  Changes[Next->Index].Spaces = (CellWidth - ThisWidth);
1194  Changes[Next->Index].Spaces += (i > 0) ? 1 : 0;
1195  }
1196  alignToStartOfCell(Next->Index, Next->EndIndex);
1197  }
1198  }
1199  }
1200 }
1201 
1202 void WhitespaceManager::alignArrayInitializersLeftJustified(
1203  CellDescriptions &&CellDescs) {
1204 
1205  if (!CellDescs.isRectangular())
1206  return;
1207 
1208  auto &Cells = CellDescs.Cells;
1209  // Now go through and fixup the spaces.
1210  auto *CellIter = Cells.begin();
1211  // The first cell needs to be against the left brace.
1212  if (Changes[CellIter->Index].NewlinesBefore == 0)
1213  Changes[CellIter->Index].Spaces = 0;
1214  else
1215  Changes[CellIter->Index].Spaces = CellDescs.InitialSpaces;
1216  ++CellIter;
1217  for (auto i = 1U; i < CellDescs.CellCounts[0]; i++, ++CellIter) {
1218  auto MaxNetWidth = getMaximumNetWidth(
1219  Cells.begin(), CellIter, CellDescs.InitialSpaces,
1220  CellDescs.CellCounts[0], CellDescs.CellCounts.size());
1221  auto ThisNetWidth =
1222  getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1223  if (Changes[CellIter->Index].NewlinesBefore == 0) {
1224  Changes[CellIter->Index].Spaces =
1225  MaxNetWidth - ThisNetWidth +
1226  (Changes[CellIter->Index].Tok->isNot(tok::r_brace) ? 1 : 0);
1227  }
1228  auto RowCount = 1U;
1229  auto Offset = std::distance(Cells.begin(), CellIter);
1230  for (const auto *Next = CellIter->NextColumnElement; Next != nullptr;
1231  Next = Next->NextColumnElement) {
1232  if (RowCount > CellDescs.CellCounts.size())
1233  break;
1234  auto *Start = (Cells.begin() + RowCount * CellDescs.CellCounts[0]);
1235  auto *End = Start + Offset;
1236  auto ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces);
1237  if (Changes[Next->Index].NewlinesBefore == 0) {
1238  Changes[Next->Index].Spaces =
1239  MaxNetWidth - ThisNetWidth +
1240  (Changes[Next->Index].Tok->isNot(tok::r_brace) ? 1 : 0);
1241  }
1242  ++RowCount;
1243  }
1244  }
1245 }
1246 
1247 bool WhitespaceManager::isSplitCell(const CellDescription &Cell) {
1248  if (Cell.HasSplit)
1249  return true;
1250  for (const auto *Next = Cell.NextColumnElement; Next != nullptr;
1251  Next = Next->NextColumnElement) {
1252  if (Next->HasSplit)
1253  return true;
1254  }
1255  return false;
1256 }
1257 
1258 WhitespaceManager::CellDescriptions WhitespaceManager::getCells(unsigned Start,
1259  unsigned End) {
1260 
1261  unsigned Depth = 0;
1262  unsigned Cell = 0;
1263  SmallVector<unsigned> CellCounts;
1264  unsigned InitialSpaces = 0;
1265  unsigned InitialTokenLength = 0;
1266  unsigned EndSpaces = 0;
1267  SmallVector<CellDescription> Cells;
1268  const FormatToken *MatchingParen = nullptr;
1269  for (unsigned i = Start; i < End; ++i) {
1270  auto &C = Changes[i];
1271  if (C.Tok->is(tok::l_brace))
1272  ++Depth;
1273  else if (C.Tok->is(tok::r_brace))
1274  --Depth;
1275  if (Depth == 2) {
1276  if (C.Tok->is(tok::l_brace)) {
1277  Cell = 0;
1278  MatchingParen = C.Tok->MatchingParen;
1279  if (InitialSpaces == 0) {
1280  InitialSpaces = C.Spaces + C.TokenLength;
1281  InitialTokenLength = C.TokenLength;
1282  auto j = i - 1;
1283  for (; Changes[j].NewlinesBefore == 0 && j > Start; --j) {
1284  InitialSpaces += Changes[j].Spaces + Changes[j].TokenLength;
1285  InitialTokenLength += Changes[j].TokenLength;
1286  }
1287  if (C.NewlinesBefore == 0) {
1288  InitialSpaces += Changes[j].Spaces + Changes[j].TokenLength;
1289  InitialTokenLength += Changes[j].TokenLength;
1290  }
1291  }
1292  } else if (C.Tok->is(tok::comma)) {
1293  if (!Cells.empty())
1294  Cells.back().EndIndex = i;
1295  if (C.Tok->getNextNonComment()->isNot(tok::r_brace)) // dangling comma
1296  ++Cell;
1297  }
1298  } else if (Depth == 1) {
1299  if (C.Tok == MatchingParen) {
1300  if (!Cells.empty())
1301  Cells.back().EndIndex = i;
1302  Cells.push_back(CellDescription{i, ++Cell, i + 1, false, nullptr});
1303  CellCounts.push_back(C.Tok->Previous->isNot(tok::comma) ? Cell + 1
1304  : Cell);
1305  // Go to the next non-comment and ensure there is a break in front
1306  const auto *NextNonComment = C.Tok->getNextNonComment();
1307  while (NextNonComment->is(tok::comma))
1308  NextNonComment = NextNonComment->getNextNonComment();
1309  auto j = i;
1310  while (Changes[j].Tok != NextNonComment && j < End)
1311  ++j;
1312  if (j < End && Changes[j].NewlinesBefore == 0 &&
1313  Changes[j].Tok->isNot(tok::r_brace)) {
1314  Changes[j].NewlinesBefore = 1;
1315  // Account for the added token lengths
1316  Changes[j].Spaces = InitialSpaces - InitialTokenLength;
1317  }
1318  } else if (C.Tok->is(tok::comment)) {
1319  // Trailing comments stay at a space past the last token
1320  C.Spaces = Changes[i - 1].Tok->is(tok::comma) ? 1 : 2;
1321  } else if (C.Tok->is(tok::l_brace)) {
1322  // We need to make sure that the ending braces is aligned to the
1323  // start of our initializer
1324  auto j = i - 1;
1325  for (; j > 0 && !Changes[j].Tok->ArrayInitializerLineStart; --j)
1326  ; // Nothing the loop does the work
1327  EndSpaces = Changes[j].Spaces;
1328  }
1329  } else if (Depth == 0 && C.Tok->is(tok::r_brace)) {
1330  C.NewlinesBefore = 1;
1331  C.Spaces = EndSpaces;
1332  }
1333  if (C.Tok->StartsColumn) {
1334  // This gets us past tokens that have been split over multiple
1335  // lines
1336  bool HasSplit = false;
1337  if (Changes[i].NewlinesBefore > 0) {
1338  // So if we split a line previously and the tail line + this token is
1339  // less then the column limit we remove the split here and just put
1340  // the column start at a space past the comma
1341  //
1342  // FIXME This if branch covers the cases where the column is not
1343  // the first column. This leads to weird pathologies like the formatting
1344  // auto foo = Items{
1345  // Section{
1346  // 0, bar(),
1347  // }
1348  // };
1349  // Well if it doesn't lead to that it's indicative that the line
1350  // breaking should be revisited. Unfortunately alot of other options
1351  // interact with this
1352  auto j = i - 1;
1353  if ((j - 1) > Start && Changes[j].Tok->is(tok::comma) &&
1354  Changes[j - 1].NewlinesBefore > 0) {
1355  --j;
1356  auto LineLimit = Changes[j].Spaces + Changes[j].TokenLength;
1357  if (LineLimit < Style.ColumnLimit) {
1358  Changes[i].NewlinesBefore = 0;
1359  Changes[i].Spaces = 1;
1360  }
1361  }
1362  }
1363  while (Changes[i].NewlinesBefore > 0 && Changes[i].Tok == C.Tok) {
1364  Changes[i].Spaces = InitialSpaces;
1365  ++i;
1366  HasSplit = true;
1367  }
1368  if (Changes[i].Tok != C.Tok)
1369  --i;
1370  Cells.push_back(CellDescription{i, Cell, i, HasSplit, nullptr});
1371  }
1372  }
1373 
1374  return linkCells({Cells, CellCounts, InitialSpaces});
1375 }
1376 
1377 unsigned WhitespaceManager::calculateCellWidth(unsigned Start, unsigned End,
1378  bool WithSpaces) const {
1379  unsigned CellWidth = 0;
1380  for (auto i = Start; i < End; i++) {
1381  if (Changes[i].NewlinesBefore > 0)
1382  CellWidth = 0;
1383  CellWidth += Changes[i].TokenLength;
1384  CellWidth += (WithSpaces ? Changes[i].Spaces : 0);
1385  }
1386  return CellWidth;
1387 }
1388 
1389 void WhitespaceManager::alignToStartOfCell(unsigned Start, unsigned End) {
1390  if ((End - Start) <= 1)
1391  return;
1392  // If the line is broken anywhere in there make sure everything
1393  // is aligned to the parent
1394  for (auto i = Start + 1; i < End; i++)
1395  if (Changes[i].NewlinesBefore > 0)
1396  Changes[i].Spaces = Changes[Start].Spaces;
1397 }
1398 
1399 WhitespaceManager::CellDescriptions
1400 WhitespaceManager::linkCells(CellDescriptions &&CellDesc) {
1401  auto &Cells = CellDesc.Cells;
1402  for (auto *CellIter = Cells.begin(); CellIter != Cells.end(); ++CellIter) {
1403  if (CellIter->NextColumnElement == nullptr &&
1404  ((CellIter + 1) != Cells.end())) {
1405  for (auto *NextIter = CellIter + 1; NextIter != Cells.end(); ++NextIter) {
1406  if (NextIter->Cell == CellIter->Cell) {
1407  CellIter->NextColumnElement = &(*NextIter);
1408  break;
1409  }
1410  }
1411  }
1412  }
1413  return std::move(CellDesc);
1414 }
1415 
1416 void WhitespaceManager::generateChanges() {
1417  for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
1418  const Change &C = Changes[i];
1419  if (i > 0 && Changes[i - 1].OriginalWhitespaceRange.getBegin() ==
1420  C.OriginalWhitespaceRange.getBegin()) {
1421  // Do not generate two replacements for the same location.
1422  continue;
1423  }
1424  if (C.CreateReplacement) {
1425  std::string ReplacementText = C.PreviousLinePostfix;
1426  if (C.ContinuesPPDirective) {
1427  appendEscapedNewlineText(ReplacementText, C.NewlinesBefore,
1428  C.PreviousEndOfTokenColumn,
1429  C.EscapedNewlineColumn);
1430  } else {
1431  appendNewlineText(ReplacementText, C.NewlinesBefore);
1432  }
1433  // FIXME: This assert should hold if we computed the column correctly.
1434  // assert((int)C.StartOfTokenColumn >= C.Spaces);
1435  appendIndentText(
1436  ReplacementText, C.Tok->IndentLevel, std::max(0, C.Spaces),
1437  std::max((int)C.StartOfTokenColumn, C.Spaces) - std::max(0, C.Spaces),
1438  C.IsAligned);
1439  ReplacementText.append(C.CurrentLinePrefix);
1440  storeReplacement(C.OriginalWhitespaceRange, ReplacementText);
1441  }
1442  }
1443 }
1444 
1445 void WhitespaceManager::storeReplacement(SourceRange Range, StringRef Text) {
1446  unsigned WhitespaceLength = SourceMgr.getFileOffset(Range.getEnd()) -
1447  SourceMgr.getFileOffset(Range.getBegin());
1448  // Don't create a replacement, if it does not change anything.
1449  if (StringRef(SourceMgr.getCharacterData(Range.getBegin()),
1450  WhitespaceLength) == Text) {
1451  return;
1452  }
1453  auto Err = Replaces.add(tooling::Replacement(
1454  SourceMgr, CharSourceRange::getCharRange(Range), Text));
1455  // FIXME: better error handling. For now, just print an error message in the
1456  // release version.
1457  if (Err) {
1458  llvm::errs() << llvm::toString(std::move(Err)) << "\n";
1459  assert(false);
1460  }
1461 }
1462 
1463 void WhitespaceManager::appendNewlineText(std::string &Text,
1464  unsigned Newlines) {
1465  if (UseCRLF) {
1466  Text.reserve(Text.size() + 2 * Newlines);
1467  for (unsigned i = 0; i < Newlines; ++i)
1468  Text.append("\r\n");
1469  } else {
1470  Text.append(Newlines, '\n');
1471  }
1472 }
1473 
1474 void WhitespaceManager::appendEscapedNewlineText(
1475  std::string &Text, unsigned Newlines, unsigned PreviousEndOfTokenColumn,
1476  unsigned EscapedNewlineColumn) {
1477  if (Newlines > 0) {
1478  unsigned Spaces =
1479  std::max<int>(1, EscapedNewlineColumn - PreviousEndOfTokenColumn - 1);
1480  for (unsigned i = 0; i < Newlines; ++i) {
1481  Text.append(Spaces, ' ');
1482  Text.append(UseCRLF ? "\\\r\n" : "\\\n");
1483  Spaces = std::max<int>(0, EscapedNewlineColumn - 1);
1484  }
1485  }
1486 }
1487 
1488 void WhitespaceManager::appendIndentText(std::string &Text,
1489  unsigned IndentLevel, unsigned Spaces,
1490  unsigned WhitespaceStartColumn,
1491  bool IsAligned) {
1492  switch (Style.UseTab) {
1493  case FormatStyle::UT_Never:
1494  Text.append(Spaces, ' ');
1495  break;
1496  case FormatStyle::UT_Always: {
1497  if (Style.TabWidth) {
1498  unsigned FirstTabWidth =
1499  Style.TabWidth - WhitespaceStartColumn % Style.TabWidth;
1500 
1501  // Insert only spaces when we want to end up before the next tab.
1502  if (Spaces < FirstTabWidth || Spaces == 1) {
1503  Text.append(Spaces, ' ');
1504  break;
1505  }
1506  // Align to the next tab.
1507  Spaces -= FirstTabWidth;
1508  Text.append("\t");
1509 
1510  Text.append(Spaces / Style.TabWidth, '\t');
1511  Text.append(Spaces % Style.TabWidth, ' ');
1512  } else if (Spaces == 1) {
1513  Text.append(Spaces, ' ');
1514  }
1515  break;
1516  }
1518  if (WhitespaceStartColumn == 0) {
1519  unsigned Indentation = IndentLevel * Style.IndentWidth;
1520  Spaces = appendTabIndent(Text, Spaces, Indentation);
1521  }
1522  Text.append(Spaces, ' ');
1523  break;
1525  if (WhitespaceStartColumn == 0)
1526  Spaces = appendTabIndent(Text, Spaces, Spaces);
1527  Text.append(Spaces, ' ');
1528  break;
1530  if (WhitespaceStartColumn == 0) {
1531  unsigned Indentation =
1532  IsAligned ? IndentLevel * Style.IndentWidth : Spaces;
1533  Spaces = appendTabIndent(Text, Spaces, Indentation);
1534  }
1535  Text.append(Spaces, ' ');
1536  break;
1537  }
1538 }
1539 
1540 unsigned WhitespaceManager::appendTabIndent(std::string &Text, unsigned Spaces,
1541  unsigned Indentation) {
1542  // This happens, e.g. when a line in a block comment is indented less than the
1543  // first one.
1544  if (Indentation > Spaces)
1545  Indentation = Spaces;
1546  if (Style.TabWidth) {
1547  unsigned Tabs = Indentation / Style.TabWidth;
1548  Text.append(Tabs, '\t');
1549  Spaces -= Tabs * Style.TabWidth;
1550  }
1551  return Spaces;
1552 }
1553 
1554 } // namespace format
1555 } // namespace clang
clang::format::WhitespaceManager::Change::Spaces
int Spaces
Definition: WhitespaceManager.h:142
clang::format::WhitespaceManager::Change::ConditionalsLevel
int ConditionalsLevel
Definition: WhitespaceManager.h:169
clang::format::AlignTokenSequence
static void AlignTokenSequence(const FormatStyle &Style, unsigned Start, unsigned End, unsigned Column, bool RightJustify, F &&Matches, SmallVector< WhitespaceManager::Change, 16 > &Changes)
Definition: WhitespaceManager.cpp:275
clang::prec::Conditional
@ Conditional
Definition: OperatorPrecedence.h:30
max
__DEVICE__ int max(int __a, int __b)
Definition: __clang_cuda_math.h:196
clang::format::FormatStyle::AlignConsecutiveStyle
Alignment options.
Definition: Format.h:160
clang::format::AlignTokens
static unsigned AlignTokens(const FormatStyle &Style, F &&Matches, SmallVector< WhitespaceManager::Change, 16 > &Changes, unsigned StartAt, const FormatStyle::AlignConsecutiveStyle &ACS={}, bool RightJustify=false)
Definition: WhitespaceManager.cpp:494
clang::for
for(unsigned I=0, E=TL.getNumArgs();I !=E;++I)
Definition: RecursiveASTVisitor.h:1384
clang::SourceRange
A trivial tuple used to represent a source range.
Definition: SourceLocation.h:210
clang::format::AlignMacroSequence
static void AlignMacroSequence(unsigned &StartOfSequence, unsigned &EndOfSequence, unsigned &MinColumn, unsigned &MaxColumn, bool &FoundMatchOnLine, std::function< bool(const WhitespaceManager::Change &C)> AlignMacrosMatches, SmallVector< WhitespaceManager::Change, 16 > &Changes)
Definition: WhitespaceManager.cpp:683
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::format::WhitespaceManager::Change::StartOfTokenColumn
unsigned StartOfTokenColumn
Definition: WhitespaceManager.h:130
clang::SourceManager::getFileOffset
unsigned getFileOffset(SourceLocation SpellingLoc) const
Returns the offset from the start of the file that the specified SourceLocation represents.
Definition: SourceManager.h:1294
llvm::SmallVector
Definition: LLVM.h:38
clang::if
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
Definition: RecursiveASTVisitor.h:1081
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
clang::SourceLocation::getLocWithOffset
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
Definition: SourceLocation.h:134
clang::SourceRange::getBegin
SourceLocation getBegin() const
Definition: SourceLocation.h:219
clang::format::WhitespaceManager::generateReplacements
const tooling::Replacements & generateReplacements()
Returns all the Replacements created during formatting.
Definition: WhitespaceManager.cpp:98
clang::format::FormatStyle::TCAS_Leave
@ TCAS_Leave
Leave trailing comments as they are.
Definition: Format.h:382
clang::format::WhitespaceManager::inputUsesCRLF
static bool inputUsesCRLF(StringRef Text, bool DefaultToCRLF)
Infers whether the input is using CRLF.
Definition: WhitespaceManager.cpp:77
AttributeLangSupport::C
@ C
Definition: SemaDeclAttr.cpp:56
clang::format::FormatStyle::PAS_Right
@ PAS_Right
Align pointer to the right.
Definition: Format.h:2894
clang::tooling::Replacements
Maintains a set of replacements that are conflict-free.
Definition: Replacement.h:209
clang::format::WhitespaceManager::Change::PreviousLinePostfix
std::string PreviousLinePostfix
Definition: WhitespaceManager.h:132
clang::format::WhitespaceManager::addUntouchableToken
void addUntouchableToken(const FormatToken &Tok, bool InPPDirective)
Adds information about an unchangeable token's whitespace.
Definition: WhitespaceManager.cpp:61
clang::format::WhitespaceManager::Change::CreateReplacement
bool CreateReplacement
Definition: WhitespaceManager.h:126
clang::format::FormatStyle
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition: Format.h:54
clang::format::FormatToken
A wrapper around a Token storing information about the whitespace characters preceding it.
Definition: FormatToken.h:240
clang::prec::Assignment
@ Assignment
Definition: OperatorPrecedence.h:29
clang::format::FormatToken::OriginalColumn
unsigned OriginalColumn
The original 0-based column of this token, including expanded tabs.
Definition: FormatToken.h:426
clang::format::WhitespaceManager::Change::Tok
const FormatToken * Tok
Definition: WhitespaceManager.h:124
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::WhitespaceManager::addReplacement
llvm::Error addReplacement(const tooling::Replacement &Replacement)
Definition: WhitespaceManager.cpp:73
clang::format::WhitespaceManager::Change::IndentationOffset
int IndentationOffset
Definition: WhitespaceManager.h:165
clang::SourceManager::getSpellingColumnNumber
unsigned getSpellingColumnNumber(SourceLocation Loc, bool *Invalid=nullptr) const
Definition: SourceManager.cpp:1240
clang::format::WhitespaceManager::Change
Represents a change before a token, a break inside a token, or the layout of an unchanged token (or w...
Definition: WhitespaceManager.h:94
clang::format::FormatToken::NewlinesBefore
unsigned NewlinesBefore
The number of newlines immediately before the Token.
Definition: FormatToken.h:391
Offset
unsigned Offset
Definition: Format.cpp:2717
clang::format::FormatStyle::ENAS_DontAlign
@ ENAS_DontAlign
Don't align escaped newlines.
Definition: Format.h:307
U
clang::CharSourceRange::getCharRange
static CharSourceRange getCharRange(SourceRange R)
Definition: SourceLocation.h:265
clang::format::FormatStyle::UT_Always
@ UT_Always
Use tabs whenever we need to fill whitespace that spans at least from one tab stop to the next one.
Definition: Format.h:3993
clang::format::WhitespaceManager::Change::OriginalWhitespaceRange
SourceRange OriginalWhitespaceRange
Definition: WhitespaceManager.h:129
clang::format::WhitespaceManager::Change::IsTrailingComment
bool IsTrailingComment
Definition: WhitespaceManager.h:151
min
__DEVICE__ int min(int __a, int __b)
Definition: __clang_cuda_math.h:197
clang::format::FormatStyle::TCAS_Never
@ TCAS_Never
Don't align trailing comments but other formatter applies.
Definition: Format.h:400
clang::format::WhitespaceManager::Change::IsInsideToken
bool IsInsideToken
Definition: WhitespaceManager.h:146
clang::threadSafety::sx::toString
std::string toString(const til::SExpr *E)
Definition: ThreadSafetyCommon.h:91
clang::format::FormatStyle::ENAS_Left
@ ENAS_Left
Align escaped newlines as far left as possible.
Definition: Format.h:318
clang::format::WhitespaceManager::Change::IsAligned
bool IsAligned
Definition: WhitespaceManager.h:134
clang::dependency_directives_scan::pp_define
@ pp_define
Definition: DependencyDirectivesScanner.h:63
Depth
int Depth
Definition: ASTDiff.cpp:189
clang::format::FormatStyle::AIAS_None
@ AIAS_None
Don't align array initializer columns.
Definition: Format.h:130
clang::format::FD_Break
@ FD_Break
Definition: FormatToken.h:171
WhitespaceManager.h
clang::format::WhitespaceManager::Change::Change
Change(const FormatToken &Tok, bool CreateReplacement, SourceRange OriginalWhitespaceRange, int Spaces, unsigned StartOfTokenColumn, unsigned NewlinesBefore, StringRef PreviousLinePostfix, StringRef CurrentLinePrefix, bool IsAligned, bool ContinuesPPDirective, bool IsInsideToken)
Creates a Change.
Definition: WhitespaceManager.cpp:29
clang::format::WhitespaceManager::Change::NewlinesBefore
unsigned NewlinesBefore
Definition: WhitespaceManager.h:131
clang::SourceManager::isBeforeInTranslationUnit
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
Definition: SourceManager.cpp:2026
clang::format::FormatStyle::AIAS_Left
@ AIAS_Left
Align array column and left justify the columns e.g.
Definition: Format.h:118
clang::format::FormatStyle::UT_Never
@ UT_Never
Never use tab.
Definition: Format.h:3982
clang::format::WhitespaceManager::Change::TokenLength
unsigned TokenLength
Definition: WhitespaceManager.h:152
clang::transformer::EditKind::Range
@ Range
clang::format::WhitespaceManager::Change::ContinuesPPDirective
bool ContinuesPPDirective
Definition: WhitespaceManager.h:135
false
#define false
Definition: stdbool.h:22
clang::format::FormatToken::Finalized
unsigned Finalized
If true, this token has been fully formatted (indented and potentially re-formatted inside),...
Definition: FormatToken.h:313
UINT_MAX
#define UINT_MAX
Definition: limits.h:56
clang::format::WhitespaceManager::Change::CurrentLinePrefix
std::string CurrentLinePrefix
Definition: WhitespaceManager.h:133
clang::SourceManager::getCharacterData
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
Definition: SourceManager.cpp:1160
clang::tooling::Replacement
A text replacement.
Definition: Replacement.h:83
clang::format::WhitespaceManager::Change::PreviousEndOfTokenColumn
unsigned PreviousEndOfTokenColumn
Definition: WhitespaceManager.h:153
clang::format::FormatToken::getStartOfNonWhitespace
SourceLocation getStartOfNonWhitespace() const
Returns actual token start location without leading escaped newlines and whitespace.
Definition: FormatToken.h:710
clang::format::FD_Continue
@ FD_Continue
Definition: FormatToken.h:171
clang::format::WhitespaceManager::Change::StartOfBlockComment
const Change * StartOfBlockComment
Definition: WhitespaceManager.h:164
clang::format::WhitespaceManager::Change::IsBeforeInFile::operator()
bool operator()(const Change &C1, const Change &C2) const
Definition: WhitespaceManager.cpp:22
clang
Definition: CalledOnceCheck.h:17
Text
StringRef Text
Definition: Format.cpp:2716
distance
float __ovld __cnfn distance(float, float)
Returns the distance between p0 and p1.
clang::format::WhitespaceManager::Change::EscapedNewlineColumn
unsigned EscapedNewlineColumn
Definition: WhitespaceManager.h:154
clang::format::FormatStyle::AIAS_Right
@ AIAS_Right
Align array column and right justify the columns e.g.
Definition: Format.h:128
clang::format::WhitespaceManager::Change::IsBeforeInFile
Functor to sort changes in original source order.
Definition: WhitespaceManager.h:96
clang::tooling::Replacements::add
llvm::Error add(const Replacement &R)
Adds a new replacement R to the current set of replacements.
Definition: Replacement.cpp:245
clang::format::FormatStyle::UT_ForContinuationAndIndentation
@ UT_ForContinuationAndIndentation
Fill all leading whitespace with tabs, and use spaces for alignment that appears within a line (e....
Definition: Format.h:3987
clang::comments::tok::eof
@ eof
Definition: CommentLexer.h:33
Previous
StateNode * Previous
Definition: UnwrappedLineFormatter.cpp:1149
clang::format::FormatToken::WhitespaceRange
SourceRange WhitespaceRange
The range of the whitespace immediately preceding the Token.
Definition: FormatToken.h:267
clang::format::WhitespaceManager::replaceWhitespaceInToken
void replaceWhitespaceInToken(const FormatToken &Tok, unsigned Offset, unsigned ReplaceChars, StringRef PreviousPostfix, StringRef CurrentPrefix, bool InPPDirective, unsigned Newlines, int Spaces)
Inserts or replaces whitespace in the middle of a token.
Definition: WhitespaceManager.cpp:83
clang::prec::Shift
@ Shift
Definition: OperatorPrecedence.h:39
clang::format::WhitespaceManager::replaceWhitespace
void replaceWhitespace(FormatToken &Tok, unsigned Newlines, unsigned Spaces, unsigned StartOfTokenColumn, bool isAligned=false, bool InPPDirective=false)
Replaces the whitespace in front of Tok.
Definition: WhitespaceManager.cpp:48
clang::format::FormatStyle::TCAS_Always
@ TCAS_Always
Align trailing comments.
Definition: Format.h:391
clang::format::FormatStyle::UT_ForIndentation
@ UT_ForIndentation
Use tabs only for indentation.
Definition: Format.h:3984
clang::format::FormatStyle::UT_AlignWithSpaces
@ UT_AlignWithSpaces
Use tabs for line continuation and indentation, and spaces for alignment.
Definition: Format.h:3990
clang::format::FormatToken::setDecision
void setDecision(FormatDecision D)
Definition: FormatToken.h:339