clang  15.0.0git
ContinuationIndenter.cpp
Go to the documentation of this file.
1 //===--- ContinuationIndenter.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 the continuation indenter.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "ContinuationIndenter.h"
15 #include "BreakableToken.h"
16 #include "FormatInternal.h"
17 #include "FormatToken.h"
18 #include "WhitespaceManager.h"
21 #include "clang/Format/Format.h"
22 #include "llvm/ADT/StringSet.h"
23 #include "llvm/Support/Debug.h"
24 
25 #define DEBUG_TYPE "format-indenter"
26 
27 namespace clang {
28 namespace format {
29 
30 // Returns true if a TT_SelectorName should be indented when wrapped,
31 // false otherwise.
35 }
36 
37 // Returns the length of everything up to the first possible line break after
38 // the ), ], } or > matching \c Tok.
39 static unsigned getLengthToMatchingParen(const FormatToken &Tok,
40  const std::vector<ParenState> &Stack) {
41  // Normally whether or not a break before T is possible is calculated and
42  // stored in T.CanBreakBefore. Braces, array initializers and text proto
43  // messages like `key: < ... >` are an exception: a break is possible
44  // before a closing brace R if a break was inserted after the corresponding
45  // opening brace. The information about whether or not a break is needed
46  // before a closing brace R is stored in the ParenState field
47  // S.BreakBeforeClosingBrace where S is the state that R closes.
48  //
49  // In order to decide whether there can be a break before encountered right
50  // braces, this implementation iterates over the sequence of tokens and over
51  // the paren stack in lockstep, keeping track of the stack level which visited
52  // right braces correspond to in MatchingStackIndex.
53  //
54  // For example, consider:
55  // L. <- line number
56  // 1. {
57  // 2. {1},
58  // 3. {2},
59  // 4. {{3}}}
60  // ^ where we call this method with this token.
61  // The paren stack at this point contains 3 brace levels:
62  // 0. { at line 1, BreakBeforeClosingBrace: true
63  // 1. first { at line 4, BreakBeforeClosingBrace: false
64  // 2. second { at line 4, BreakBeforeClosingBrace: false,
65  // where there might be fake parens levels in-between these levels.
66  // The algorithm will start at the first } on line 4, which is the matching
67  // brace of the initial left brace and at level 2 of the stack. Then,
68  // examining BreakBeforeClosingBrace: false at level 2, it will continue to
69  // the second } on line 4, and will traverse the stack downwards until it
70  // finds the matching { on level 1. Then, examining BreakBeforeClosingBrace:
71  // false at level 1, it will continue to the third } on line 4 and will
72  // traverse the stack downwards until it finds the matching { on level 0.
73  // Then, examining BreakBeforeClosingBrace: true at level 0, the algorithm
74  // will stop and will use the second } on line 4 to determine the length to
75  // return, as in this example the range will include the tokens: {3}}
76  //
77  // The algorithm will only traverse the stack if it encounters braces, array
78  // initializer squares or text proto angle brackets.
79  if (!Tok.MatchingParen)
80  return 0;
82  // Maintains a stack level corresponding to the current End token.
83  int MatchingStackIndex = Stack.size() - 1;
84  // Traverses the stack downwards, looking for the level to which LBrace
85  // corresponds. Returns either a pointer to the matching level or nullptr if
86  // LParen is not found in the initial portion of the stack up to
87  // MatchingStackIndex.
88  auto FindParenState = [&](const FormatToken *LBrace) -> const ParenState * {
89  while (MatchingStackIndex >= 0 && Stack[MatchingStackIndex].Tok != LBrace)
90  --MatchingStackIndex;
91  return MatchingStackIndex >= 0 ? &Stack[MatchingStackIndex] : nullptr;
92  };
93  for (; End->Next; End = End->Next) {
94  if (End->Next->CanBreakBefore)
95  break;
96  if (!End->Next->closesScope())
97  continue;
98  if (End->Next->MatchingParen &&
99  End->Next->MatchingParen->isOneOf(
100  tok::l_brace, TT_ArrayInitializerLSquare, tok::less)) {
101  const ParenState *State = FindParenState(End->Next->MatchingParen);
102  if (State && State->BreakBeforeClosingBrace)
103  break;
104  }
105  }
106  return End->TotalLength - Tok.TotalLength + 1;
107 }
108 
109 static unsigned getLengthToNextOperator(const FormatToken &Tok) {
110  if (!Tok.NextOperator)
111  return 0;
112  return Tok.NextOperator->TotalLength - Tok.TotalLength;
113 }
114 
115 // Returns \c true if \c Tok is the "." or "->" of a call and starts the next
116 // segment of a builder type call.
118  return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
119 }
120 
121 // Returns \c true if \c Current starts a new parameter.
122 static bool startsNextParameter(const FormatToken &Current,
123  const FormatStyle &Style) {
124  const FormatToken &Previous = *Current.Previous;
125  if (Current.is(TT_CtorInitializerComma) &&
127  return true;
128  }
129  if (Style.Language == FormatStyle::LK_Proto && Current.is(TT_SelectorName))
130  return true;
131  return Previous.is(tok::comma) && !Current.isTrailingComment() &&
132  ((Previous.isNot(TT_CtorInitializerComma) ||
135  (Previous.isNot(TT_InheritanceComma) ||
137 }
138 
139 static bool opensProtoMessageField(const FormatToken &LessTok,
140  const FormatStyle &Style) {
141  if (LessTok.isNot(tok::less))
142  return false;
143  return Style.Language == FormatStyle::LK_TextProto ||
144  (Style.Language == FormatStyle::LK_Proto &&
145  (LessTok.NestingLevel > 0 ||
146  (LessTok.Previous && LessTok.Previous->is(tok::equal))));
147 }
148 
149 // Returns the delimiter of a raw string literal, or None if TokenText is not
150 // the text of a raw string literal. The delimiter could be the empty string.
151 // For example, the delimiter of R"deli(cont)deli" is deli.
153  if (TokenText.size() < 5 // The smallest raw string possible is 'R"()"'.
154  || !TokenText.startswith("R\"") || !TokenText.endswith("\"")) {
155  return None;
156  }
157 
158  // A raw string starts with 'R"<delimiter>(' and delimiter is ascii and has
159  // size at most 16 by the standard, so the first '(' must be among the first
160  // 19 bytes.
161  size_t LParenPos = TokenText.substr(0, 19).find_first_of('(');
162  if (LParenPos == StringRef::npos)
163  return None;
164  StringRef Delimiter = TokenText.substr(2, LParenPos - 2);
165 
166  // Check that the string ends in ')Delimiter"'.
167  size_t RParenPos = TokenText.size() - Delimiter.size() - 2;
168  if (TokenText[RParenPos] != ')')
169  return None;
170  if (!TokenText.substr(RParenPos + 1).startswith(Delimiter))
171  return None;
172  return Delimiter;
173 }
174 
175 // Returns the canonical delimiter for \p Language, or the empty string if no
176 // canonical delimiter is specified.
177 static StringRef
180  for (const auto &Format : Style.RawStringFormats)
181  if (Format.Language == Language)
182  return StringRef(Format.CanonicalDelimiter);
183  return "";
184 }
185 
187  const FormatStyle &CodeStyle) {
188  for (const auto &RawStringFormat : CodeStyle.RawStringFormats) {
189  llvm::Optional<FormatStyle> LanguageStyle =
190  CodeStyle.GetLanguageStyle(RawStringFormat.Language);
191  if (!LanguageStyle) {
192  FormatStyle PredefinedStyle;
193  if (!getPredefinedStyle(RawStringFormat.BasedOnStyle,
194  RawStringFormat.Language, &PredefinedStyle)) {
195  PredefinedStyle = getLLVMStyle();
196  PredefinedStyle.Language = RawStringFormat.Language;
197  }
198  LanguageStyle = PredefinedStyle;
199  }
200  LanguageStyle->ColumnLimit = CodeStyle.ColumnLimit;
201  for (StringRef Delimiter : RawStringFormat.Delimiters)
202  DelimiterStyle.insert({Delimiter, *LanguageStyle});
203  for (StringRef EnclosingFunction : RawStringFormat.EnclosingFunctions)
204  EnclosingFunctionStyle.insert({EnclosingFunction, *LanguageStyle});
205  }
206 }
207 
210  auto It = DelimiterStyle.find(Delimiter);
211  if (It == DelimiterStyle.end())
212  return None;
213  return It->second;
214 }
215 
218  StringRef EnclosingFunction) const {
219  auto It = EnclosingFunctionStyle.find(EnclosingFunction);
220  if (It == EnclosingFunctionStyle.end())
221  return None;
222  return It->second;
223 }
224 
226  const AdditionalKeywords &Keywords,
227  const SourceManager &SourceMgr,
228  WhitespaceManager &Whitespaces,
230  bool BinPackInconclusiveFunctions)
231  : Style(Style), Keywords(Keywords), SourceMgr(SourceMgr),
232  Whitespaces(Whitespaces), Encoding(Encoding),
233  BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
234  CommentPragmasRegex(Style.CommentPragmas), RawStringFormats(Style) {}
235 
237  unsigned FirstStartColumn,
238  const AnnotatedLine *Line,
239  bool DryRun) {
241  State.FirstIndent = FirstIndent;
242  if (FirstStartColumn && Line->First->NewlinesBefore == 0)
243  State.Column = FirstStartColumn;
244  else
245  State.Column = FirstIndent;
246  // With preprocessor directive indentation, the line starts on column 0
247  // since it's indented after the hash, but FirstIndent is set to the
248  // preprocessor indent.
250  (Line->Type == LT_PreprocessorDirective ||
251  Line->Type == LT_ImportStatement)) {
252  State.Column = 0;
253  }
254  State.Line = Line;
255  State.NextToken = Line->First;
256  State.Stack.push_back(ParenState(/*Tok=*/nullptr, FirstIndent, FirstIndent,
257  /*AvoidBinPacking=*/false,
258  /*NoLineBreak=*/false));
259  State.NoContinuation = false;
260  State.StartOfStringLiteral = 0;
261  State.StartOfLineLevel = 0;
262  State.LowestLevelOnLine = 0;
263  State.IgnoreStackForComparison = false;
264 
265  if (Style.Language == FormatStyle::LK_TextProto) {
266  // We need this in order to deal with the bin packing of text fields at
267  // global scope.
268  auto &CurrentState = State.Stack.back();
269  CurrentState.AvoidBinPacking = true;
270  CurrentState.BreakBeforeParameter = true;
271  CurrentState.AlignColons = false;
272  }
273 
274  // The first token has already been indented and thus consumed.
275  moveStateToNextToken(State, DryRun, /*Newline=*/false);
276  return State;
277 }
278 
280  const FormatToken &Current = *State.NextToken;
281  const FormatToken &Previous = *Current.Previous;
282  const auto &CurrentState = State.Stack.back();
283  assert(&Previous == Current.Previous);
284  if (!Current.CanBreakBefore && !(CurrentState.BreakBeforeClosingBrace &&
285  Current.closesBlockOrBlockTypeList(Style))) {
286  return false;
287  }
288  // The opening "{" of a braced list has to be on the same line as the first
289  // element if it is nested in another braced init list or function call.
290  if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
291  Previous.isNot(TT_DictLiteral) && Previous.is(BK_BracedInit) &&
292  Previous.Previous &&
293  Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma)) {
294  return false;
295  }
296  // This prevents breaks like:
297  // ...
298  // SomeParameter, OtherParameter).DoSomething(
299  // ...
300  // As they hide "DoSomething" and are generally bad for readability.
301  if (Previous.opensScope() && Previous.isNot(tok::l_brace) &&
302  State.LowestLevelOnLine < State.StartOfLineLevel &&
303  State.LowestLevelOnLine < Current.NestingLevel) {
304  return false;
305  }
306  if (Current.isMemberAccess() && CurrentState.ContainsUnwrappedBuilder)
307  return false;
308 
309  // Don't create a 'hanging' indent if there are multiple blocks in a single
310  // statement.
311  if (Previous.is(tok::l_brace) && State.Stack.size() > 1 &&
312  State.Stack[State.Stack.size() - 2].NestedBlockInlined &&
313  State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks) {
314  return false;
315  }
316 
317  // Don't break after very short return types (e.g. "void") as that is often
318  // unexpected.
319  if (Current.is(TT_FunctionDeclarationName) && State.Column < 6) {
321  return false;
322  }
323 
324  // If binary operators are moved to the next line (including commas for some
325  // styles of constructor initializers), that's always ok.
326  if (!Current.isOneOf(TT_BinaryOperator, tok::comma) &&
327  CurrentState.NoLineBreakInOperand) {
328  return false;
329  }
330 
331  if (Previous.is(tok::l_square) && Previous.is(TT_ObjCMethodExpr))
332  return false;
333 
334  return !CurrentState.NoLineBreak;
335 }
336 
338  const FormatToken &Current = *State.NextToken;
339  const FormatToken &Previous = *Current.Previous;
340  const auto &CurrentState = State.Stack.back();
341  if (Style.BraceWrapping.BeforeLambdaBody && Current.CanBreakBefore &&
342  Current.is(TT_LambdaLBrace) && Previous.isNot(TT_LineComment)) {
343  auto LambdaBodyLength = getLengthToMatchingParen(Current, State.Stack);
344  return LambdaBodyLength > getColumnLimit(State);
345  }
346  if (Current.MustBreakBefore || Current.is(TT_InlineASMColon))
347  return true;
348  if (CurrentState.BreakBeforeClosingBrace &&
349  Current.closesBlockOrBlockTypeList(Style)) {
350  return true;
351  }
352  if (CurrentState.BreakBeforeClosingParen && Current.is(tok::r_paren))
353  return true;
354  if (Style.Language == FormatStyle::LK_ObjC &&
356  Current.ObjCSelectorNameParts > 1 &&
357  Current.startsSequence(TT_SelectorName, tok::colon, tok::caret)) {
358  return true;
359  }
360  // Avoid producing inconsistent states by requiring breaks where they are not
361  // permitted for C# generic type constraints.
362  if (CurrentState.IsCSharpGenericTypeConstraint &&
363  Previous.isNot(TT_CSharpGenericTypeConstraintComma)) {
364  return false;
365  }
366  if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
367  (Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&
368  Style.isCpp() &&
369  // FIXME: This is a temporary workaround for the case where clang-format
370  // sets BreakBeforeParameter to avoid bin packing and this creates a
371  // completely unnecessary line break after a template type that isn't
372  // line-wrapped.
373  (Previous.NestingLevel == 1 || Style.BinPackParameters)) ||
374  (Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
375  Previous.isNot(tok::question)) ||
376  (!Style.BreakBeforeTernaryOperators &&
377  Previous.is(TT_ConditionalExpr))) &&
378  CurrentState.BreakBeforeParameter && !Current.isTrailingComment() &&
379  !Current.isOneOf(tok::r_paren, tok::r_brace)) {
380  return true;
381  }
382  if (CurrentState.IsChainedConditional &&
383  ((Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
384  Current.is(tok::colon)) ||
385  (!Style.BreakBeforeTernaryOperators && Previous.is(TT_ConditionalExpr) &&
386  Previous.is(tok::colon)))) {
387  return true;
388  }
389  if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) ||
390  (Previous.is(TT_ArrayInitializerLSquare) &&
391  Previous.ParameterCount > 1) ||
392  opensProtoMessageField(Previous, Style)) &&
393  Style.ColumnLimit > 0 &&
394  getLengthToMatchingParen(Previous, State.Stack) + State.Column - 1 >
396  return true;
397  }
398 
399  const FormatToken &BreakConstructorInitializersToken =
401  ? Previous
402  : Current;
403  if (BreakConstructorInitializersToken.is(TT_CtorInitializerColon) &&
404  (State.Column + State.Line->Last->TotalLength - Previous.TotalLength >
406  CurrentState.BreakBeforeParameter) &&
409  Style.ColumnLimit != 0)) {
410  return true;
411  }
412 
413  if (Current.is(TT_ObjCMethodExpr) && !Previous.is(TT_SelectorName) &&
414  State.Line->startsWith(TT_ObjCMethodSpecifier)) {
415  return true;
416  }
417  if (Current.is(TT_SelectorName) && !Previous.is(tok::at) &&
418  CurrentState.ObjCSelectorNameFound && CurrentState.BreakBeforeParameter &&
420  !Current.startsSequence(TT_SelectorName, tok::colon, tok::caret))) {
421  return true;
422  }
423 
424  unsigned NewLineColumn = getNewLineColumn(State);
425  if (Current.isMemberAccess() && Style.ColumnLimit != 0 &&
426  State.Column + getLengthToNextOperator(Current) > Style.ColumnLimit &&
427  (State.Column > NewLineColumn ||
428  Current.NestingLevel < State.StartOfLineLevel)) {
429  return true;
430  }
431 
432  if (startsSegmentOfBuilderTypeCall(Current) &&
433  (CurrentState.CallContinuation != 0 ||
434  CurrentState.BreakBeforeParameter) &&
435  // JavaScript is treated different here as there is a frequent pattern:
436  // SomeFunction(function() {
437  // ...
438  // }.bind(...));
439  // FIXME: We should find a more generic solution to this problem.
440  !(State.Column <= NewLineColumn && Style.isJavaScript()) &&
441  !(Previous.closesScopeAfterBlock() && State.Column <= NewLineColumn)) {
442  return true;
443  }
444 
445  // If the template declaration spans multiple lines, force wrap before the
446  // function/class declaration
447  if (Previous.ClosesTemplateDeclaration && CurrentState.BreakBeforeParameter &&
448  Current.CanBreakBefore) {
449  return true;
450  }
451 
452  if (!State.Line->First->is(tok::kw_enum) && State.Column <= NewLineColumn)
453  return false;
454 
456  (NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth ||
457  Previous.is(tok::comma) || Current.NestingLevel < 2) &&
458  !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at,
459  Keywords.kw_dollar) &&
460  !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) &&
461  nextIsMultilineString(State)) {
462  return true;
463  }
464 
465  // Using CanBreakBefore here and below takes care of the decision whether the
466  // current style uses wrapping before or after operators for the given
467  // operator.
468  if (Previous.is(TT_BinaryOperator) && Current.CanBreakBefore) {
469  const auto PreviousPrecedence = Previous.getPrecedence();
470  if (PreviousPrecedence != prec::Assignment &&
471  CurrentState.BreakBeforeParameter && !Current.isTrailingComment()) {
472  const bool LHSIsBinaryExpr =
473  Previous.Previous && Previous.Previous->EndsBinaryExpression;
474  if (LHSIsBinaryExpr)
475  return true;
476  // If we need to break somewhere inside the LHS of a binary expression, we
477  // should also break after the operator. Otherwise, the formatting would
478  // hide the operator precedence, e.g. in:
479  // if (aaaaaaaaaaaaaa ==
480  // bbbbbbbbbbbbbb && c) {..
481  // For comparisons, we only apply this rule, if the LHS is a binary
482  // expression itself as otherwise, the line breaks seem superfluous.
483  // We need special cases for ">>" which we have split into two ">" while
484  // lexing in order to make template parsing easier.
485  const bool IsComparison =
486  (PreviousPrecedence == prec::Relational ||
487  PreviousPrecedence == prec::Equality ||
488  PreviousPrecedence == prec::Spaceship) &&
489  Previous.Previous &&
490  Previous.Previous->isNot(TT_BinaryOperator); // For >>.
491  if (!IsComparison)
492  return true;
493  }
494  } else if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore &&
495  CurrentState.BreakBeforeParameter) {
496  return true;
497  }
498 
499  // Same as above, but for the first "<<" operator.
500  if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) &&
501  CurrentState.BreakBeforeParameter && CurrentState.FirstLessLess == 0) {
502  return true;
503  }
504 
505  if (Current.NestingLevel == 0 && !Current.isTrailingComment()) {
506  // Always break after "template <...>"(*) and leading annotations. This is
507  // only for cases where the entire line does not fit on a single line as a
508  // different LineFormatter would be used otherwise.
509  // *: Except when another option interferes with that, like concepts.
510  if (Previous.ClosesTemplateDeclaration) {
511  if (Current.is(tok::kw_concept)) {
512  switch (Style.BreakBeforeConceptDeclarations) {
514  break;
516  return true;
518  return false;
519  }
520  }
521  if (Current.is(TT_RequiresClause)) {
522  switch (Style.RequiresClausePosition) {
525  return false;
526  default:
527  return true;
528  }
529  }
531  }
532  if (Previous.is(TT_FunctionAnnotationRParen) &&
533  State.Line->Type != LT_PreprocessorDirective) {
534  return true;
535  }
536  if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) &&
537  Current.isNot(TT_LeadingJavaAnnotation)) {
538  return true;
539  }
540  }
541 
542  if (Style.isJavaScript() && Previous.is(tok::r_paren) &&
543  Previous.is(TT_JavaAnnotation)) {
544  // Break after the closing parenthesis of TypeScript decorators before
545  // functions, getters and setters.
546  static const llvm::StringSet<> BreakBeforeDecoratedTokens = {"get", "set",
547  "function"};
548  if (BreakBeforeDecoratedTokens.contains(Current.TokenText))
549  return true;
550  }
551 
552  // If the return type spans multiple lines, wrap before the function name.
553  if (((Current.is(TT_FunctionDeclarationName) &&
554  // Don't break before a C# function when no break after return type
555  (!Style.isCSharp() ||
557  // Don't always break between a JavaScript `function` and the function
558  // name.
559  !Style.isJavaScript()) ||
560  (Current.is(tok::kw_operator) && !Previous.is(tok::coloncolon))) &&
561  !Previous.is(tok::kw_template) && CurrentState.BreakBeforeParameter) {
562  return true;
563  }
564 
565  // The following could be precomputed as they do not depend on the state.
566  // However, as they should take effect only if the UnwrappedLine does not fit
567  // into the ColumnLimit, they are checked here in the ContinuationIndenter.
568  if (Style.ColumnLimit != 0 && Previous.is(BK_Block) &&
569  Previous.is(tok::l_brace) &&
570  !Current.isOneOf(tok::r_brace, tok::comment)) {
571  return true;
572  }
573 
574  if (Current.is(tok::lessless) &&
575  ((Previous.is(tok::identifier) && Previous.TokenText == "endl") ||
576  (Previous.Tok.isLiteral() && (Previous.TokenText.endswith("\\n\"") ||
577  Previous.TokenText == "\'\\n\'")))) {
578  return true;
579  }
580 
581  if (Previous.is(TT_BlockComment) && Previous.IsMultiline)
582  return true;
583 
584  if (State.NoContinuation)
585  return true;
586 
587  return false;
588 }
589 
591  bool DryRun,
592  unsigned ExtraSpaces) {
593  const FormatToken &Current = *State.NextToken;
594  assert(State.NextToken->Previous);
595  const FormatToken &Previous = *State.NextToken->Previous;
596 
597  assert(!State.Stack.empty());
598  State.NoContinuation = false;
599 
600  if ((Current.is(TT_ImplicitStringLiteral) &&
601  (Previous.Tok.getIdentifierInfo() == nullptr ||
602  Previous.Tok.getIdentifierInfo()->getPPKeywordID() ==
603  tok::pp_not_keyword))) {
604  unsigned EndColumn =
605  SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getEnd());
606  if (Current.LastNewlineOffset != 0) {
607  // If there is a newline within this token, the final column will solely
608  // determined by the current end column.
609  State.Column = EndColumn;
610  } else {
611  unsigned StartColumn =
612  SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getBegin());
613  assert(EndColumn >= StartColumn);
614  State.Column += EndColumn - StartColumn;
615  }
616  moveStateToNextToken(State, DryRun, /*Newline=*/false);
617  return 0;
618  }
619 
620  unsigned Penalty = 0;
621  if (Newline)
622  Penalty = addTokenOnNewLine(State, DryRun);
623  else
624  addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
625 
626  return moveStateToNextToken(State, DryRun, Newline) + Penalty;
627 }
628 
629 void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
630  unsigned ExtraSpaces) {
631  FormatToken &Current = *State.NextToken;
632  assert(State.NextToken->Previous);
633  const FormatToken &Previous = *State.NextToken->Previous;
634  auto &CurrentState = State.Stack.back();
635 
636  if (Current.is(tok::equal) &&
637  (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&
638  CurrentState.VariablePos == 0) {
639  CurrentState.VariablePos = State.Column;
640  // Move over * and & if they are bound to the variable name.
641  const FormatToken *Tok = &Previous;
642  while (Tok && CurrentState.VariablePos >= Tok->ColumnWidth) {
643  CurrentState.VariablePos -= Tok->ColumnWidth;
644  if (Tok->SpacesRequiredBefore != 0)
645  break;
646  Tok = Tok->Previous;
647  }
648  if (Previous.PartOfMultiVariableDeclStmt)
649  CurrentState.LastSpace = CurrentState.VariablePos;
650  }
651 
652  unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
653 
654  // Indent preprocessor directives after the hash if required.
655  int PPColumnCorrection = 0;
657  Previous.is(tok::hash) && State.FirstIndent > 0 &&
658  (State.Line->Type == LT_PreprocessorDirective ||
659  State.Line->Type == LT_ImportStatement)) {
660  Spaces += State.FirstIndent;
661 
662  // For preprocessor indent with tabs, State.Column will be 1 because of the
663  // hash. This causes second-level indents onward to have an extra space
664  // after the tabs. We avoid this misalignment by subtracting 1 from the
665  // column value passed to replaceWhitespace().
666  if (Style.UseTab != FormatStyle::UT_Never)
667  PPColumnCorrection = -1;
668  }
669 
670  if (!DryRun) {
671  Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, Spaces,
672  State.Column + Spaces + PPColumnCorrection);
673  }
674 
675  // If "BreakBeforeInheritanceComma" mode, don't break within the inheritance
676  // declaration unless there is multiple inheritance.
678  Current.is(TT_InheritanceColon)) {
679  CurrentState.NoLineBreak = true;
680  }
682  Previous.is(TT_InheritanceColon)) {
683  CurrentState.NoLineBreak = true;
684  }
685 
686  if (Current.is(TT_SelectorName) && !CurrentState.ObjCSelectorNameFound) {
687  unsigned MinIndent = std::max(
688  State.FirstIndent + Style.ContinuationIndentWidth, CurrentState.Indent);
689  unsigned FirstColonPos = State.Column + Spaces + Current.ColumnWidth;
690  if (Current.LongestObjCSelectorName == 0)
691  CurrentState.AlignColons = false;
692  else if (MinIndent + Current.LongestObjCSelectorName > FirstColonPos)
693  CurrentState.ColonPos = MinIndent + Current.LongestObjCSelectorName;
694  else
695  CurrentState.ColonPos = FirstColonPos;
696  }
697 
698  // In "AlwaysBreak" or "BlockIndent" mode, enforce wrapping directly after the
699  // parenthesis by disallowing any further line breaks if there is no line
700  // break after the opening parenthesis. Don't break if it doesn't conserve
701  // columns.
704  (Previous.isOneOf(tok::l_paren, TT_TemplateOpener, tok::l_square) ||
705  (Previous.is(tok::l_brace) && Previous.isNot(BK_Block) &&
706  Style.Cpp11BracedListStyle)) &&
707  State.Column > getNewLineColumn(State) &&
708  (!Previous.Previous || !Previous.Previous->isOneOf(
709  tok::kw_for, tok::kw_while, tok::kw_switch)) &&
710  // Don't do this for simple (no expressions) one-argument function calls
711  // as that feels like needlessly wasting whitespace, e.g.:
712  //
713  // caaaaaaaaaaaall(
714  // caaaaaaaaaaaall(
715  // caaaaaaaaaaaall(
716  // caaaaaaaaaaaaaaaaaaaaaaall(aaaaaaaaaaaaaa, aaaaaaaaa))));
717  Current.FakeLParens.size() > 0 &&
718  Current.FakeLParens.back() > prec::Unknown) {
719  CurrentState.NoLineBreak = true;
720  }
721  if (Previous.is(TT_TemplateString) && Previous.opensScope())
722  CurrentState.NoLineBreak = true;
723 
725  !CurrentState.IsCSharpGenericTypeConstraint && Previous.opensScope() &&
726  Previous.isNot(TT_ObjCMethodExpr) && Previous.isNot(TT_RequiresClause) &&
727  (Current.isNot(TT_LineComment) || Previous.is(BK_BracedInit))) {
728  CurrentState.Indent = State.Column + Spaces;
729  CurrentState.IsAligned = true;
730  }
731  if (CurrentState.AvoidBinPacking && startsNextParameter(Current, Style))
732  CurrentState.NoLineBreak = true;
733  if (startsSegmentOfBuilderTypeCall(Current) &&
734  State.Column > getNewLineColumn(State)) {
735  CurrentState.ContainsUnwrappedBuilder = true;
736  }
737 
738  if (Current.is(TT_LambdaArrow) && Style.Language == FormatStyle::LK_Java)
739  CurrentState.NoLineBreak = true;
740  if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
741  (Previous.MatchingParen &&
742  (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) {
743  // If there is a function call with long parameters, break before trailing
744  // calls. This prevents things like:
745  // EXPECT_CALL(SomeLongParameter).Times(
746  // 2);
747  // We don't want to do this for short parameters as they can just be
748  // indexes.
749  CurrentState.NoLineBreak = true;
750  }
751 
752  // Don't allow the RHS of an operator to be split over multiple lines unless
753  // there is a line-break right after the operator.
754  // Exclude relational operators, as there, it is always more desirable to
755  // have the LHS 'left' of the RHS.
756  const FormatToken *P = Current.getPreviousNonComment();
757  if (!Current.is(tok::comment) && P &&
758  (P->isOneOf(TT_BinaryOperator, tok::comma) ||
759  (P->is(TT_ConditionalExpr) && P->is(tok::colon))) &&
760  !P->isOneOf(TT_OverloadedOperator, TT_CtorInitializerComma) &&
761  P->getPrecedence() != prec::Assignment &&
762  P->getPrecedence() != prec::Relational &&
763  P->getPrecedence() != prec::Spaceship) {
764  bool BreakBeforeOperator =
765  P->MustBreakBefore || P->is(tok::lessless) ||
766  (P->is(TT_BinaryOperator) &&
768  (P->is(TT_ConditionalExpr) && Style.BreakBeforeTernaryOperators);
769  // Don't do this if there are only two operands. In these cases, there is
770  // always a nice vertical separation between them and the extra line break
771  // does not help.
772  bool HasTwoOperands =
773  P->OperatorIndex == 0 && !P->NextOperator && !P->is(TT_ConditionalExpr);
774  if ((!BreakBeforeOperator &&
775  !(HasTwoOperands &&
777  (!CurrentState.LastOperatorWrapped && BreakBeforeOperator)) {
778  CurrentState.NoLineBreakInOperand = true;
779  }
780  }
781 
782  State.Column += Spaces;
783  if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
784  Previous.Previous &&
785  (Previous.Previous->is(tok::kw_for) || Previous.Previous->isIf())) {
786  // Treat the condition inside an if as if it was a second function
787  // parameter, i.e. let nested calls have a continuation indent.
788  CurrentState.LastSpace = State.Column;
789  CurrentState.NestedBlockIndent = State.Column;
790  } else if (!Current.isOneOf(tok::comment, tok::caret) &&
791  ((Previous.is(tok::comma) &&
792  !Previous.is(TT_OverloadedOperator)) ||
793  (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) {
794  CurrentState.LastSpace = State.Column;
795  } else if (Previous.is(TT_CtorInitializerColon) &&
798  CurrentState.Indent = State.Column;
799  CurrentState.LastSpace = State.Column;
800  } else if ((Previous.isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
801  TT_CtorInitializerColon)) &&
802  ((Previous.getPrecedence() != prec::Assignment &&
803  (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
804  Previous.NextOperator)) ||
805  Current.StartsBinaryExpression)) {
806  // Indent relative to the RHS of the expression unless this is a simple
807  // assignment without binary expression on the RHS. Also indent relative to
808  // unary operators and the colons of constructor initializers.
810  CurrentState.LastSpace = State.Column;
811  } else if (Previous.is(TT_InheritanceColon)) {
812  CurrentState.Indent = State.Column;
813  CurrentState.LastSpace = State.Column;
814  } else if (Current.is(TT_CSharpGenericTypeConstraintColon)) {
815  CurrentState.ColonPos = State.Column;
816  } else if (Previous.opensScope()) {
817  // If a function has a trailing call, indent all parameters from the
818  // opening parenthesis. This avoids confusing indents like:
819  // OuterFunction(InnerFunctionCall( // break
820  // ParameterToInnerFunction)) // break
821  // .SecondInnerFunctionCall();
822  if (Previous.MatchingParen) {
823  const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
824  if (Next && Next->isMemberAccess() && State.Stack.size() > 1 &&
825  State.Stack[State.Stack.size() - 2].CallContinuation == 0) {
826  CurrentState.LastSpace = State.Column;
827  }
828  }
829  }
830 }
831 
832 unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
833  bool DryRun) {
834  FormatToken &Current = *State.NextToken;
835  assert(State.NextToken->Previous);
836  const FormatToken &Previous = *State.NextToken->Previous;
837  auto &CurrentState = State.Stack.back();
838 
839  // Extra penalty that needs to be added because of the way certain line
840  // breaks are chosen.
841  unsigned Penalty = 0;
842 
843  const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
844  const FormatToken *NextNonComment = Previous.getNextNonComment();
845  if (!NextNonComment)
846  NextNonComment = &Current;
847  // The first line break on any NestingLevel causes an extra penalty in order
848  // prefer similar line breaks.
849  if (!CurrentState.ContainsLineBreak)
850  Penalty += 15;
851  CurrentState.ContainsLineBreak = true;
852 
853  Penalty += State.NextToken->SplitPenalty;
854 
855  // Breaking before the first "<<" is generally not desirable if the LHS is
856  // short. Also always add the penalty if the LHS is split over multiple lines
857  // to avoid unnecessary line breaks that just work around this penalty.
858  if (NextNonComment->is(tok::lessless) && CurrentState.FirstLessLess == 0 &&
859  (State.Column <= Style.ColumnLimit / 3 ||
860  CurrentState.BreakBeforeParameter)) {
861  Penalty += Style.PenaltyBreakFirstLessLess;
862  }
863 
864  State.Column = getNewLineColumn(State);
865 
866  // Add Penalty proportional to amount of whitespace away from FirstColumn
867  // This tends to penalize several lines that are far-right indented,
868  // and prefers a line-break prior to such a block, e.g:
869  //
870  // Constructor() :
871  // member(value), looooooooooooooooong_member(
872  // looooooooooong_call(param_1, param_2, param_3))
873  // would then become
874  // Constructor() :
875  // member(value),
876  // looooooooooooooooong_member(
877  // looooooooooong_call(param_1, param_2, param_3))
878  if (State.Column > State.FirstIndent) {
879  Penalty +=
880  Style.PenaltyIndentedWhitespace * (State.Column - State.FirstIndent);
881  }
882 
883  // Indent nested blocks relative to this column, unless in a very specific
884  // JavaScript special case where:
885  //
886  // var loooooong_name =
887  // function() {
888  // // code
889  // }
890  //
891  // is common and should be formatted like a free-standing function. The same
892  // goes for wrapping before the lambda return type arrow.
893  if (!Current.is(TT_LambdaArrow) &&
894  (!Style.isJavaScript() || Current.NestingLevel != 0 ||
895  !PreviousNonComment || !PreviousNonComment->is(tok::equal) ||
896  !Current.isOneOf(Keywords.kw_async, Keywords.kw_function))) {
897  CurrentState.NestedBlockIndent = State.Column;
898  }
899 
900  if (NextNonComment->isMemberAccess()) {
901  if (CurrentState.CallContinuation == 0)
902  CurrentState.CallContinuation = State.Column;
903  } else if (NextNonComment->is(TT_SelectorName)) {
904  if (!CurrentState.ObjCSelectorNameFound) {
905  if (NextNonComment->LongestObjCSelectorName == 0) {
906  CurrentState.AlignColons = false;
907  } else {
908  CurrentState.ColonPos =
909  (shouldIndentWrappedSelectorName(Style, State.Line->Type)
910  ? std::max(CurrentState.Indent,
911  State.FirstIndent + Style.ContinuationIndentWidth)
912  : CurrentState.Indent) +
913  std::max(NextNonComment->LongestObjCSelectorName,
914  NextNonComment->ColumnWidth);
915  }
916  } else if (CurrentState.AlignColons &&
917  CurrentState.ColonPos <= NextNonComment->ColumnWidth) {
918  CurrentState.ColonPos = State.Column + NextNonComment->ColumnWidth;
919  }
920  } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
921  PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
922  // FIXME: This is hacky, find a better way. The problem is that in an ObjC
923  // method expression, the block should be aligned to the line starting it,
924  // e.g.:
925  // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
926  // ^(int *i) {
927  // // ...
928  // }];
929  // Thus, we set LastSpace of the next higher NestingLevel, to which we move
930  // when we consume all of the "}"'s FakeRParens at the "{".
931  if (State.Stack.size() > 1) {
932  State.Stack[State.Stack.size() - 2].LastSpace =
933  std::max(CurrentState.LastSpace, CurrentState.Indent) +
935  }
936  }
937 
938  if ((PreviousNonComment &&
939  PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
940  !CurrentState.AvoidBinPacking) ||
941  Previous.is(TT_BinaryOperator)) {
942  CurrentState.BreakBeforeParameter = false;
943  }
944  if (PreviousNonComment &&
945  (PreviousNonComment->isOneOf(TT_TemplateCloser, TT_JavaAnnotation) ||
946  PreviousNonComment->ClosesRequiresClause) &&
947  Current.NestingLevel == 0) {
948  CurrentState.BreakBeforeParameter = false;
949  }
950  if (NextNonComment->is(tok::question) ||
951  (PreviousNonComment && PreviousNonComment->is(tok::question))) {
952  CurrentState.BreakBeforeParameter = true;
953  }
954  if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore)
955  CurrentState.BreakBeforeParameter = false;
956 
957  if (!DryRun) {
958  unsigned MaxEmptyLinesToKeep = Style.MaxEmptyLinesToKeep + 1;
959  if (Current.is(tok::r_brace) && Current.MatchingParen &&
960  // Only strip trailing empty lines for l_braces that have children, i.e.
961  // for function expressions (lambdas, arrows, etc).
962  !Current.MatchingParen->Children.empty()) {
963  // lambdas and arrow functions are expressions, thus their r_brace is not
964  // on its own line, and thus not covered by UnwrappedLineFormatter's logic
965  // about removing empty lines on closing blocks. Special case them here.
966  MaxEmptyLinesToKeep = 1;
967  }
968  unsigned Newlines =
969  std::max(1u, std::min(Current.NewlinesBefore, MaxEmptyLinesToKeep));
970  bool ContinuePPDirective =
971  State.Line->InPPDirective && State.Line->Type != LT_ImportStatement;
972  Whitespaces.replaceWhitespace(Current, Newlines, State.Column, State.Column,
973  CurrentState.IsAligned, ContinuePPDirective);
974  }
975 
976  if (!Current.isTrailingComment())
977  CurrentState.LastSpace = State.Column;
978  if (Current.is(tok::lessless)) {
979  // If we are breaking before a "<<", we always want to indent relative to
980  // RHS. This is necessary only for "<<", as we special-case it and don't
981  // always indent relative to the RHS.
982  CurrentState.LastSpace += 3; // 3 -> width of "<< ".
983  }
984 
985  State.StartOfLineLevel = Current.NestingLevel;
986  State.LowestLevelOnLine = Current.NestingLevel;
987 
988  // Any break on this level means that the parent level has been broken
989  // and we need to avoid bin packing there.
990  bool NestedBlockSpecialCase =
991  (!Style.isCpp() && Current.is(tok::r_brace) && State.Stack.size() > 1 &&
992  State.Stack[State.Stack.size() - 2].NestedBlockInlined) ||
993  (Style.Language == FormatStyle::LK_ObjC && Current.is(tok::r_brace) &&
994  State.Stack.size() > 1 && !Style.ObjCBreakBeforeNestedBlockParam);
995  // Do not force parameter break for statements with requires expressions.
996  NestedBlockSpecialCase =
997  NestedBlockSpecialCase ||
998  (Current.MatchingParen &&
999  Current.MatchingParen->is(TT_RequiresExpressionLBrace));
1000  if (!NestedBlockSpecialCase)
1001  for (ParenState &PState : llvm::drop_end(State.Stack))
1002  PState.BreakBeforeParameter = true;
1003 
1004  if (PreviousNonComment &&
1005  !PreviousNonComment->isOneOf(tok::comma, tok::colon, tok::semi) &&
1006  ((PreviousNonComment->isNot(TT_TemplateCloser) &&
1007  !PreviousNonComment->ClosesRequiresClause) ||
1008  Current.NestingLevel != 0) &&
1009  !PreviousNonComment->isOneOf(
1010  TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
1011  TT_LeadingJavaAnnotation) &&
1012  Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope()) {
1013  CurrentState.BreakBeforeParameter = true;
1014  }
1015 
1016  // If we break after { or the [ of an array initializer, we should also break
1017  // before the corresponding } or ].
1018  if (PreviousNonComment &&
1019  (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
1020  opensProtoMessageField(*PreviousNonComment, Style))) {
1021  CurrentState.BreakBeforeClosingBrace = true;
1022  }
1023 
1024  if (PreviousNonComment && PreviousNonComment->is(tok::l_paren)) {
1025  CurrentState.BreakBeforeClosingParen =
1027  }
1028 
1029  if (CurrentState.AvoidBinPacking) {
1030  // If we are breaking after '(', '{', '<', or this is the break after a ':'
1031  // to start a member initializater list in a constructor, this should not
1032  // be considered bin packing unless the relevant AllowAll option is false or
1033  // this is a dict/object literal.
1034  bool PreviousIsBreakingCtorInitializerColon =
1035  Previous.is(TT_CtorInitializerColon) &&
1037  if (!(Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) ||
1038  PreviousIsBreakingCtorInitializerColon) ||
1040  State.Line->MustBeDeclaration) ||
1041  (!Style.AllowAllArgumentsOnNextLine &&
1042  !State.Line->MustBeDeclaration) ||
1044  PreviousIsBreakingCtorInitializerColon) ||
1045  Previous.is(TT_DictLiteral)) {
1046  CurrentState.BreakBeforeParameter = true;
1047  }
1048 
1049  // If we are breaking after a ':' to start a member initializer list,
1050  // and we allow all arguments on the next line, we should not break
1051  // before the next parameter.
1052  if (PreviousIsBreakingCtorInitializerColon &&
1054  CurrentState.BreakBeforeParameter = false;
1055  }
1056  }
1057 
1058  return Penalty;
1059 }
1060 
1061 unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
1062  if (!State.NextToken || !State.NextToken->Previous)
1063  return 0;
1064 
1065  FormatToken &Current = *State.NextToken;
1066  const auto &CurrentState = State.Stack.back();
1067 
1068  if (CurrentState.IsCSharpGenericTypeConstraint &&
1069  Current.isNot(TT_CSharpGenericTypeConstraint)) {
1070  return CurrentState.ColonPos + 2;
1071  }
1072 
1073  const FormatToken &Previous = *Current.Previous;
1074  // If we are continuing an expression, we want to use the continuation indent.
1075  unsigned ContinuationIndent =
1076  std::max(CurrentState.LastSpace, CurrentState.Indent) +
1078  const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
1079  const FormatToken *NextNonComment = Previous.getNextNonComment();
1080  if (!NextNonComment)
1081  NextNonComment = &Current;
1082 
1083  // Java specific bits.
1084  if (Style.Language == FormatStyle::LK_Java &&
1085  Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends)) {
1086  return std::max(CurrentState.LastSpace,
1087  CurrentState.Indent + Style.ContinuationIndentWidth);
1088  }
1089 
1091  State.Line->First->is(tok::kw_enum)) {
1092  return (Style.IndentWidth * State.Line->First->IndentLevel) +
1093  Style.IndentWidth;
1094  }
1095 
1096  if (NextNonComment->is(tok::l_brace) && NextNonComment->is(BK_Block))
1097  return Current.NestingLevel == 0 ? State.FirstIndent : CurrentState.Indent;
1098  if ((Current.isOneOf(tok::r_brace, tok::r_square) ||
1099  (Current.is(tok::greater) &&
1100  (Style.Language == FormatStyle::LK_Proto ||
1101  Style.Language == FormatStyle::LK_TextProto))) &&
1102  State.Stack.size() > 1) {
1103  if (Current.closesBlockOrBlockTypeList(Style))
1104  return State.Stack[State.Stack.size() - 2].NestedBlockIndent;
1105  if (Current.MatchingParen && Current.MatchingParen->is(BK_BracedInit))
1106  return State.Stack[State.Stack.size() - 2].LastSpace;
1107  return State.FirstIndent;
1108  }
1109  // Indent a closing parenthesis at the previous level if followed by a semi,
1110  // const, or opening brace. This allows indentations such as:
1111  // foo(
1112  // a,
1113  // );
1114  // int Foo::getter(
1115  // //
1116  // ) const {
1117  // return foo;
1118  // }
1119  // function foo(
1120  // a,
1121  // ) {
1122  // code(); //
1123  // }
1124  if (Current.is(tok::r_paren) && State.Stack.size() > 1 &&
1125  (!Current.Next ||
1126  Current.Next->isOneOf(tok::semi, tok::kw_const, tok::l_brace))) {
1127  return State.Stack[State.Stack.size() - 2].LastSpace;
1128  }
1130  Current.is(tok::r_paren) && State.Stack.size() > 1) {
1131  return State.Stack[State.Stack.size() - 2].LastSpace;
1132  }
1133  if (NextNonComment->is(TT_TemplateString) && NextNonComment->closesScope())
1134  return State.Stack[State.Stack.size() - 2].LastSpace;
1135  if (Current.is(tok::identifier) && Current.Next &&
1136  (Current.Next->is(TT_DictLiteral) ||
1137  ((Style.Language == FormatStyle::LK_Proto ||
1138  Style.Language == FormatStyle::LK_TextProto) &&
1139  Current.Next->isOneOf(tok::less, tok::l_brace)))) {
1140  return CurrentState.Indent;
1141  }
1142  if (NextNonComment->is(TT_ObjCStringLiteral) &&
1143  State.StartOfStringLiteral != 0) {
1144  return State.StartOfStringLiteral - 1;
1145  }
1146  if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
1147  return State.StartOfStringLiteral;
1148  if (NextNonComment->is(tok::lessless) && CurrentState.FirstLessLess != 0)
1149  return CurrentState.FirstLessLess;
1150  if (NextNonComment->isMemberAccess()) {
1151  if (CurrentState.CallContinuation == 0)
1152  return ContinuationIndent;
1153  return CurrentState.CallContinuation;
1154  }
1155  if (CurrentState.QuestionColumn != 0 &&
1156  ((NextNonComment->is(tok::colon) &&
1157  NextNonComment->is(TT_ConditionalExpr)) ||
1158  Previous.is(TT_ConditionalExpr))) {
1159  if (((NextNonComment->is(tok::colon) && NextNonComment->Next &&
1160  !NextNonComment->Next->FakeLParens.empty() &&
1161  NextNonComment->Next->FakeLParens.back() == prec::Conditional) ||
1162  (Previous.is(tok::colon) && !Current.FakeLParens.empty() &&
1163  Current.FakeLParens.back() == prec::Conditional)) &&
1164  !CurrentState.IsWrappedConditional) {
1165  // NOTE: we may tweak this slightly:
1166  // * not remove the 'lead' ContinuationIndentWidth
1167  // * always un-indent by the operator when
1168  // BreakBeforeTernaryOperators=true
1169  unsigned Indent = CurrentState.Indent;
1172  if (Style.BreakBeforeTernaryOperators && CurrentState.UnindentOperator)
1173  Indent -= 2;
1174  return Indent;
1175  }
1176  return CurrentState.QuestionColumn;
1177  }
1178  if (Previous.is(tok::comma) && CurrentState.VariablePos != 0)
1179  return CurrentState.VariablePos;
1180  if (Current.is(TT_RequiresClause)) {
1181  if (Style.IndentRequiresClause)
1182  return CurrentState.Indent + Style.IndentWidth;
1183  switch (Style.RequiresClausePosition) {
1186  return CurrentState.Indent;
1187  default:
1188  break;
1189  }
1190  }
1191  if ((PreviousNonComment &&
1192  (PreviousNonComment->ClosesTemplateDeclaration ||
1193  PreviousNonComment->ClosesRequiresClause ||
1194  PreviousNonComment->isOneOf(
1195  TT_AttributeParen, TT_AttributeSquare, TT_FunctionAnnotationRParen,
1196  TT_JavaAnnotation, TT_LeadingJavaAnnotation))) ||
1197  (!Style.IndentWrappedFunctionNames &&
1198  NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName))) {
1199  return std::max(CurrentState.LastSpace, CurrentState.Indent);
1200  }
1201  if (NextNonComment->is(TT_SelectorName)) {
1202  if (!CurrentState.ObjCSelectorNameFound) {
1203  unsigned MinIndent = CurrentState.Indent;
1204  if (shouldIndentWrappedSelectorName(Style, State.Line->Type)) {
1205  MinIndent = std::max(MinIndent,
1206  State.FirstIndent + Style.ContinuationIndentWidth);
1207  }
1208  // If LongestObjCSelectorName is 0, we are indenting the first
1209  // part of an ObjC selector (or a selector component which is
1210  // not colon-aligned due to block formatting).
1211  //
1212  // Otherwise, we are indenting a subsequent part of an ObjC
1213  // selector which should be colon-aligned to the longest
1214  // component of the ObjC selector.
1215  //
1216  // In either case, we want to respect Style.IndentWrappedFunctionNames.
1217  return MinIndent +
1218  std::max(NextNonComment->LongestObjCSelectorName,
1219  NextNonComment->ColumnWidth) -
1220  NextNonComment->ColumnWidth;
1221  }
1222  if (!CurrentState.AlignColons)
1223  return CurrentState.Indent;
1224  if (CurrentState.ColonPos > NextNonComment->ColumnWidth)
1225  return CurrentState.ColonPos - NextNonComment->ColumnWidth;
1226  return CurrentState.Indent;
1227  }
1228  if (NextNonComment->is(tok::colon) && NextNonComment->is(TT_ObjCMethodExpr))
1229  return CurrentState.ColonPos;
1230  if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
1231  if (CurrentState.StartOfArraySubscripts != 0) {
1232  return CurrentState.StartOfArraySubscripts;
1233  } else if (Style.isCSharp()) { // C# allows `["key"] = value` inside object
1234  // initializers.
1235  return CurrentState.Indent;
1236  }
1237  return ContinuationIndent;
1238  }
1239 
1240  // This ensure that we correctly format ObjC methods calls without inputs,
1241  // i.e. where the last element isn't selector like: [callee method];
1242  if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 &&
1243  NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr)) {
1244  return CurrentState.Indent;
1245  }
1246 
1247  if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) ||
1248  Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon)) {
1249  return ContinuationIndent;
1250  }
1251  if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
1252  PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
1253  return ContinuationIndent;
1254  }
1255  if (NextNonComment->is(TT_CtorInitializerComma))
1256  return CurrentState.Indent;
1257  if (PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) &&
1259  return CurrentState.Indent;
1260  }
1261  if (PreviousNonComment && PreviousNonComment->is(TT_InheritanceColon) &&
1263  return CurrentState.Indent;
1264  }
1265  if (NextNonComment->isOneOf(TT_CtorInitializerColon, TT_InheritanceColon,
1266  TT_InheritanceComma)) {
1267  return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1268  }
1269  if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() &&
1270  !Current.isOneOf(tok::colon, tok::comment)) {
1271  return ContinuationIndent;
1272  }
1273  if (Current.is(TT_ProtoExtensionLSquare))
1274  return CurrentState.Indent;
1275  if (Current.isBinaryOperator() && CurrentState.UnindentOperator) {
1276  return CurrentState.Indent - Current.Tok.getLength() -
1277  Current.SpacesRequiredBefore;
1278  }
1279  if (Current.isOneOf(tok::comment, TT_BlockComment, TT_LineComment) &&
1280  NextNonComment->isBinaryOperator() && CurrentState.UnindentOperator) {
1281  return CurrentState.Indent - NextNonComment->Tok.getLength() -
1282  NextNonComment->SpacesRequiredBefore;
1283  }
1284  if (CurrentState.Indent == State.FirstIndent && PreviousNonComment &&
1285  !PreviousNonComment->isOneOf(tok::r_brace, TT_CtorInitializerComma)) {
1286  // Ensure that we fall back to the continuation indent width instead of
1287  // just flushing continuations left.
1288  return CurrentState.Indent + Style.ContinuationIndentWidth;
1289  }
1290  return CurrentState.Indent;
1291 }
1292 
1294  const FormatToken &Current,
1295  const FormatStyle &Style) {
1296  if (Previous->isNot(tok::l_paren))
1297  return true;
1298  if (Previous->ParameterCount > 1)
1299  return true;
1300 
1301  // Also a nested block if contains a lambda inside function with 1 parameter
1302  return Style.BraceWrapping.BeforeLambdaBody && Current.is(TT_LambdaLSquare);
1303 }
1304 
1305 unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
1306  bool DryRun, bool Newline) {
1307  assert(State.Stack.size());
1308  const FormatToken &Current = *State.NextToken;
1309  auto &CurrentState = State.Stack.back();
1310 
1311  if (Current.is(TT_CSharpGenericTypeConstraint))
1312  CurrentState.IsCSharpGenericTypeConstraint = true;
1313  if (Current.isOneOf(tok::comma, TT_BinaryOperator))
1314  CurrentState.NoLineBreakInOperand = false;
1315  if (Current.isOneOf(TT_InheritanceColon, TT_CSharpGenericTypeConstraintColon))
1316  CurrentState.AvoidBinPacking = true;
1317  if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
1318  if (CurrentState.FirstLessLess == 0)
1319  CurrentState.FirstLessLess = State.Column;
1320  else
1321  CurrentState.LastOperatorWrapped = Newline;
1322  }
1323  if (Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless))
1324  CurrentState.LastOperatorWrapped = Newline;
1325  if (Current.is(TT_ConditionalExpr) && Current.Previous &&
1326  !Current.Previous->is(TT_ConditionalExpr)) {
1327  CurrentState.LastOperatorWrapped = Newline;
1328  }
1329  if (Current.is(TT_ArraySubscriptLSquare) &&
1330  CurrentState.StartOfArraySubscripts == 0) {
1331  CurrentState.StartOfArraySubscripts = State.Column;
1332  }
1333 
1334  auto IsWrappedConditional = [](const FormatToken &Tok) {
1335  if (!(Tok.is(TT_ConditionalExpr) && Tok.is(tok::question)))
1336  return false;
1337  if (Tok.MustBreakBefore)
1338  return true;
1339 
1340  const FormatToken *Next = Tok.getNextNonComment();
1341  return Next && Next->MustBreakBefore;
1342  };
1343  if (IsWrappedConditional(Current))
1344  CurrentState.IsWrappedConditional = true;
1345  if (Style.BreakBeforeTernaryOperators && Current.is(tok::question))
1346  CurrentState.QuestionColumn = State.Column;
1347  if (!Style.BreakBeforeTernaryOperators && Current.isNot(tok::colon)) {
1348  const FormatToken *Previous = Current.Previous;
1349  while (Previous && Previous->isTrailingComment())
1350  Previous = Previous->Previous;
1351  if (Previous && Previous->is(tok::question))
1352  CurrentState.QuestionColumn = State.Column;
1353  }
1354  if (!Current.opensScope() && !Current.closesScope() &&
1355  !Current.is(TT_PointerOrReference)) {
1356  State.LowestLevelOnLine =
1357  std::min(State.LowestLevelOnLine, Current.NestingLevel);
1358  }
1359  if (Current.isMemberAccess())
1360  CurrentState.StartOfFunctionCall = !Current.NextOperator ? 0 : State.Column;
1361  if (Current.is(TT_SelectorName))
1362  CurrentState.ObjCSelectorNameFound = true;
1363  if (Current.is(TT_CtorInitializerColon) &&
1365  // Indent 2 from the column, so:
1366  // SomeClass::SomeClass()
1367  // : First(...), ...
1368  // Next(...)
1369  // ^ line up here.
1370  CurrentState.Indent = State.Column + (Style.BreakConstructorInitializers ==
1372  ? 0
1373  : 2);
1374  CurrentState.NestedBlockIndent = CurrentState.Indent;
1376  CurrentState.AvoidBinPacking = true;
1377  CurrentState.BreakBeforeParameter =
1379  } else {
1380  CurrentState.BreakBeforeParameter = false;
1381  }
1382  }
1383  if (Current.is(TT_CtorInitializerColon) &&
1385  CurrentState.Indent =
1386  State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1387  CurrentState.NestedBlockIndent = CurrentState.Indent;
1389  CurrentState.AvoidBinPacking = true;
1390  }
1391  if (Current.is(TT_InheritanceColon)) {
1392  CurrentState.Indent =
1393  State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1394  }
1395  if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline)
1396  CurrentState.NestedBlockIndent = State.Column + Current.ColumnWidth + 1;
1397  if (Current.isOneOf(TT_LambdaLSquare, TT_LambdaArrow))
1398  CurrentState.LastSpace = State.Column;
1399  if (Current.is(TT_RequiresExpression))
1400  CurrentState.NestedBlockIndent = State.Column;
1401 
1402  // Insert scopes created by fake parenthesis.
1403  const FormatToken *Previous = Current.getPreviousNonComment();
1404 
1405  // Add special behavior to support a format commonly used for JavaScript
1406  // closures:
1407  // SomeFunction(function() {
1408  // foo();
1409  // bar();
1410  // }, a, b, c);
1411  if (Current.isNot(tok::comment) && !Current.ClosesRequiresClause &&
1412  Previous && Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
1413  !Previous->is(TT_DictLiteral) && State.Stack.size() > 1 &&
1414  !CurrentState.HasMultipleNestedBlocks) {
1415  if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)
1416  for (ParenState &PState : llvm::drop_end(State.Stack))
1417  PState.NoLineBreak = true;
1418  State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
1419  }
1420  if (Previous && (Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr) ||
1421  (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) &&
1422  !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))) {
1423  CurrentState.NestedBlockInlined =
1424  !Newline && hasNestedBlockInlined(Previous, Current, Style);
1425  }
1426 
1427  moveStatePastFakeLParens(State, Newline);
1428  moveStatePastScopeCloser(State);
1429  // Do not use CurrentState here, since the two functions before may change the
1430  // Stack.
1431  bool AllowBreak = !State.Stack.back().NoLineBreak &&
1432  !State.Stack.back().NoLineBreakInOperand;
1433  moveStatePastScopeOpener(State, Newline);
1434  moveStatePastFakeRParens(State);
1435 
1436  if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0)
1437  State.StartOfStringLiteral = State.Column + 1;
1438  if (Current.is(TT_CSharpStringLiteral) && State.StartOfStringLiteral == 0) {
1439  State.StartOfStringLiteral = State.Column + 1;
1440  } else if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {
1441  State.StartOfStringLiteral = State.Column;
1442  } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
1443  !Current.isStringLiteral()) {
1444  State.StartOfStringLiteral = 0;
1445  }
1446 
1447  State.Column += Current.ColumnWidth;
1448  State.NextToken = State.NextToken->Next;
1449 
1450  unsigned Penalty =
1451  handleEndOfLine(Current, State, DryRun, AllowBreak, Newline);
1452 
1453  if (Current.Role)
1454  Current.Role->formatFromToken(State, this, DryRun);
1455  // If the previous has a special role, let it consume tokens as appropriate.
1456  // It is necessary to start at the previous token for the only implemented
1457  // role (comma separated list). That way, the decision whether or not to break
1458  // after the "{" is already done and both options are tried and evaluated.
1459  // FIXME: This is ugly, find a better way.
1460  if (Previous && Previous->Role)
1461  Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
1462 
1463  return Penalty;
1464 }
1465 
1466 void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
1467  bool Newline) {
1468  const FormatToken &Current = *State.NextToken;
1469  if (Current.FakeLParens.empty())
1470  return;
1471 
1472  const FormatToken *Previous = Current.getPreviousNonComment();
1473 
1474  // Don't add extra indentation for the first fake parenthesis after
1475  // 'return', assignments, opening <({[, or requires clauses. The indentation
1476  // for these cases is special cased.
1477  bool SkipFirstExtraIndent =
1478  Previous &&
1479  (Previous->opensScope() ||
1480  Previous->isOneOf(tok::semi, tok::kw_return, TT_RequiresClause) ||
1481  (Previous->getPrecedence() == prec::Assignment &&
1483  Previous->is(TT_ObjCMethodExpr));
1484  for (const auto &PrecedenceLevel : llvm::reverse(Current.FakeLParens)) {
1485  const auto &CurrentState = State.Stack.back();
1486  ParenState NewParenState = CurrentState;
1487  NewParenState.Tok = nullptr;
1488  NewParenState.ContainsLineBreak = false;
1489  NewParenState.LastOperatorWrapped = true;
1490  NewParenState.IsChainedConditional = false;
1491  NewParenState.IsWrappedConditional = false;
1492  NewParenState.UnindentOperator = false;
1493  NewParenState.NoLineBreak =
1494  NewParenState.NoLineBreak || CurrentState.NoLineBreakInOperand;
1495 
1496  // Don't propagate AvoidBinPacking into subexpressions of arg/param lists.
1497  if (PrecedenceLevel > prec::Comma)
1498  NewParenState.AvoidBinPacking = false;
1499 
1500  // Indent from 'LastSpace' unless these are fake parentheses encapsulating
1501  // a builder type call after 'return' or, if the alignment after opening
1502  // brackets is disabled.
1503  if (!Current.isTrailingComment() &&
1505  PrecedenceLevel < prec::Assignment) &&
1506  (!Previous || Previous->isNot(tok::kw_return) ||
1507  (Style.Language != FormatStyle::LK_Java && PrecedenceLevel > 0)) &&
1509  PrecedenceLevel != prec::Comma || Current.NestingLevel == 0)) {
1510  NewParenState.Indent = std::max(
1511  std::max(State.Column, NewParenState.Indent), CurrentState.LastSpace);
1512  }
1513 
1514  if (Previous &&
1515  (Previous->getPrecedence() == prec::Assignment ||
1516  Previous->isOneOf(tok::kw_return, TT_RequiresClause) ||
1517  (PrecedenceLevel == prec::Conditional && Previous->is(tok::question) &&
1518  Previous->is(TT_ConditionalExpr))) &&
1519  !Newline) {
1520  // If BreakBeforeBinaryOperators is set, un-indent a bit to account for
1521  // the operator and keep the operands aligned
1523  NewParenState.UnindentOperator = true;
1524  // Mark indentation as alignment if the expression is aligned.
1526  NewParenState.IsAligned = true;
1527  }
1528 
1529  // Do not indent relative to the fake parentheses inserted for "." or "->".
1530  // This is a special case to make the following to statements consistent:
1531  // OuterFunction(InnerFunctionCall( // break
1532  // ParameterToInnerFunction));
1533  // OuterFunction(SomeObject.InnerFunctionCall( // break
1534  // ParameterToInnerFunction));
1535  if (PrecedenceLevel > prec::Unknown)
1536  NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
1537  if (PrecedenceLevel != prec::Conditional && !Current.is(TT_UnaryOperator) &&
1539  NewParenState.StartOfFunctionCall = State.Column;
1540  }
1541 
1542  // Indent conditional expressions, unless they are chained "else-if"
1543  // conditionals. Never indent expression where the 'operator' is ',', ';' or
1544  // an assignment (i.e. *I <= prec::Assignment) as those have different
1545  // indentation rules. Indent other expression, unless the indentation needs
1546  // to be skipped.
1547  if (PrecedenceLevel == prec::Conditional && Previous &&
1548  Previous->is(tok::colon) && Previous->is(TT_ConditionalExpr) &&
1549  &PrecedenceLevel == &Current.FakeLParens.back() &&
1550  !CurrentState.IsWrappedConditional) {
1551  NewParenState.IsChainedConditional = true;
1552  NewParenState.UnindentOperator = State.Stack.back().UnindentOperator;
1553  } else if (PrecedenceLevel == prec::Conditional ||
1554  (!SkipFirstExtraIndent && PrecedenceLevel > prec::Assignment &&
1555  !Current.isTrailingComment())) {
1556  NewParenState.Indent += Style.ContinuationIndentWidth;
1557  }
1558  if ((Previous && !Previous->opensScope()) || PrecedenceLevel != prec::Comma)
1559  NewParenState.BreakBeforeParameter = false;
1560  State.Stack.push_back(NewParenState);
1561  SkipFirstExtraIndent = false;
1562  }
1563 }
1564 
1565 void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
1566  for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {
1567  unsigned VariablePos = State.Stack.back().VariablePos;
1568  if (State.Stack.size() == 1) {
1569  // Do not pop the last element.
1570  break;
1571  }
1572  State.Stack.pop_back();
1573  State.Stack.back().VariablePos = VariablePos;
1574  }
1575 
1576  if (State.NextToken->ClosesRequiresClause && Style.IndentRequiresClause) {
1577  // Remove the indentation of the requires clauses (which is not in Indent,
1578  // but in LastSpace).
1579  State.Stack.back().LastSpace -= Style.IndentWidth;
1580  }
1581 }
1582 
1583 void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
1584  bool Newline) {
1585  const FormatToken &Current = *State.NextToken;
1586  if (!Current.opensScope())
1587  return;
1588 
1589  const auto &CurrentState = State.Stack.back();
1590 
1591  // Don't allow '<' or '(' in C# generic type constraints to start new scopes.
1592  if (Current.isOneOf(tok::less, tok::l_paren) &&
1593  CurrentState.IsCSharpGenericTypeConstraint) {
1594  return;
1595  }
1596 
1597  if (Current.MatchingParen && Current.is(BK_Block)) {
1598  moveStateToNewBlock(State);
1599  return;
1600  }
1601 
1602  unsigned NewIndent;
1603  unsigned LastSpace = CurrentState.LastSpace;
1604  bool AvoidBinPacking;
1605  bool BreakBeforeParameter = false;
1606  unsigned NestedBlockIndent = std::max(CurrentState.StartOfFunctionCall,
1607  CurrentState.NestedBlockIndent);
1608  if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
1609  opensProtoMessageField(Current, Style)) {
1610  if (Current.opensBlockOrBlockTypeList(Style)) {
1611  NewIndent = Style.IndentWidth +
1612  std::min(State.Column, CurrentState.NestedBlockIndent);
1613  } else {
1614  NewIndent = CurrentState.LastSpace + Style.ContinuationIndentWidth;
1615  }
1616  const FormatToken *NextNoComment = Current.getNextNonComment();
1617  bool EndsInComma = Current.MatchingParen &&
1618  Current.MatchingParen->Previous &&
1619  Current.MatchingParen->Previous->is(tok::comma);
1620  AvoidBinPacking = EndsInComma || Current.is(TT_DictLiteral) ||
1621  Style.Language == FormatStyle::LK_Proto ||
1623  !Style.BinPackArguments ||
1624  (NextNoComment &&
1625  NextNoComment->isOneOf(TT_DesignatedInitializerPeriod,
1626  TT_DesignatedInitializerLSquare));
1627  BreakBeforeParameter = EndsInComma;
1628  if (Current.ParameterCount > 1)
1629  NestedBlockIndent = std::max(NestedBlockIndent, State.Column + 1);
1630  } else {
1631  NewIndent =
1632  Style.ContinuationIndentWidth +
1633  std::max(CurrentState.LastSpace, CurrentState.StartOfFunctionCall);
1634 
1635  // Ensure that different different brackets force relative alignment, e.g.:
1636  // void SomeFunction(vector< // break
1637  // int> v);
1638  // FIXME: We likely want to do this for more combinations of brackets.
1639  if (Current.is(tok::less) && Current.ParentBracket == tok::l_paren) {
1640  NewIndent = std::max(NewIndent, CurrentState.Indent);
1641  LastSpace = std::max(LastSpace, CurrentState.Indent);
1642  }
1643 
1644  bool EndsInComma =
1645  Current.MatchingParen &&
1646  Current.MatchingParen->getPreviousNonComment() &&
1647  Current.MatchingParen->getPreviousNonComment()->is(tok::comma);
1648 
1649  // If ObjCBinPackProtocolList is unspecified, fall back to BinPackParameters
1650  // for backwards compatibility.
1651  bool ObjCBinPackProtocolList =
1653  Style.BinPackParameters) ||
1655 
1656  bool BinPackDeclaration =
1657  (State.Line->Type != LT_ObjCDecl && Style.BinPackParameters) ||
1658  (State.Line->Type == LT_ObjCDecl && ObjCBinPackProtocolList);
1659 
1660  AvoidBinPacking =
1661  (CurrentState.IsCSharpGenericTypeConstraint) ||
1662  (Style.isJavaScript() && EndsInComma) ||
1663  (State.Line->MustBeDeclaration && !BinPackDeclaration) ||
1664  (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
1666  (Current.is(PPK_OnePerLine) ||
1667  (!BinPackInconclusiveFunctions && Current.is(PPK_Inconclusive))));
1668 
1669  if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen &&
1671  if (Style.ColumnLimit) {
1672  // If this '[' opens an ObjC call, determine whether all parameters fit
1673  // into one line and put one per line if they don't.
1674  if (getLengthToMatchingParen(Current, State.Stack) + State.Column >
1675  getColumnLimit(State)) {
1676  BreakBeforeParameter = true;
1677  }
1678  } else {
1679  // For ColumnLimit = 0, we have to figure out whether there is or has to
1680  // be a line break within this call.
1681  for (const FormatToken *Tok = &Current;
1682  Tok && Tok != Current.MatchingParen; Tok = Tok->Next) {
1683  if (Tok->MustBreakBefore ||
1684  (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) {
1685  BreakBeforeParameter = true;
1686  break;
1687  }
1688  }
1689  }
1690  }
1691 
1692  if (Style.isJavaScript() && EndsInComma)
1693  BreakBeforeParameter = true;
1694  }
1695  // Generally inherit NoLineBreak from the current scope to nested scope.
1696  // However, don't do this for non-empty nested blocks, dict literals and
1697  // array literals as these follow different indentation rules.
1698  bool NoLineBreak =
1699  Current.Children.empty() &&
1700  !Current.isOneOf(TT_DictLiteral, TT_ArrayInitializerLSquare) &&
1701  (CurrentState.NoLineBreak || CurrentState.NoLineBreakInOperand ||
1702  (Current.is(TT_TemplateOpener) &&
1703  CurrentState.ContainsUnwrappedBuilder));
1704  State.Stack.push_back(
1705  ParenState(&Current, NewIndent, LastSpace, AvoidBinPacking, NoLineBreak));
1706  auto &NewState = State.Stack.back();
1707  NewState.NestedBlockIndent = NestedBlockIndent;
1708  NewState.BreakBeforeParameter = BreakBeforeParameter;
1709  NewState.HasMultipleNestedBlocks = (Current.BlockParameterCount > 1);
1710 
1711  if (Style.BraceWrapping.BeforeLambdaBody && Current.Next != nullptr &&
1712  Current.is(tok::l_paren)) {
1713  // Search for any parameter that is a lambda
1714  FormatToken const *next = Current.Next;
1715  while (next != nullptr) {
1716  if (next->is(TT_LambdaLSquare)) {
1717  NewState.HasMultipleNestedBlocks = true;
1718  break;
1719  }
1720  next = next->Next;
1721  }
1722  }
1723 
1724  NewState.IsInsideObjCArrayLiteral = Current.is(TT_ArrayInitializerLSquare) &&
1725  Current.Previous &&
1726  Current.Previous->is(tok::at);
1727 }
1728 
1729 void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
1730  const FormatToken &Current = *State.NextToken;
1731  if (!Current.closesScope())
1732  return;
1733 
1734  // If we encounter a closing ), ], } or >, we can remove a level from our
1735  // stacks.
1736  if (State.Stack.size() > 1 &&
1737  (Current.isOneOf(tok::r_paren, tok::r_square, TT_TemplateString) ||
1738  (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
1739  State.NextToken->is(TT_TemplateCloser) ||
1740  (Current.is(tok::greater) && Current.is(TT_DictLiteral)))) {
1741  State.Stack.pop_back();
1742  }
1743 
1744  auto &CurrentState = State.Stack.back();
1745 
1746  // Reevaluate whether ObjC message arguments fit into one line.
1747  // If a receiver spans multiple lines, e.g.:
1748  // [[object block:^{
1749  // return 42;
1750  // }] a:42 b:42];
1751  // BreakBeforeParameter is calculated based on an incorrect assumption
1752  // (it is checked whether the whole expression fits into one line without
1753  // considering a line break inside a message receiver).
1754  // We check whether arguments fit after receiver scope closer (into the same
1755  // line).
1756  if (CurrentState.BreakBeforeParameter && Current.MatchingParen &&
1757  Current.MatchingParen->Previous) {
1758  const FormatToken &CurrentScopeOpener = *Current.MatchingParen->Previous;
1759  if (CurrentScopeOpener.is(TT_ObjCMethodExpr) &&
1760  CurrentScopeOpener.MatchingParen) {
1761  int NecessarySpaceInLine =
1762  getLengthToMatchingParen(CurrentScopeOpener, State.Stack) +
1763  CurrentScopeOpener.TotalLength - Current.TotalLength - 1;
1764  if (State.Column + Current.ColumnWidth + NecessarySpaceInLine <=
1765  Style.ColumnLimit) {
1766  CurrentState.BreakBeforeParameter = false;
1767  }
1768  }
1769  }
1770 
1771  if (Current.is(tok::r_square)) {
1772  // If this ends the array subscript expr, reset the corresponding value.
1773  const FormatToken *NextNonComment = Current.getNextNonComment();
1774  if (NextNonComment && NextNonComment->isNot(tok::l_square))
1775  CurrentState.StartOfArraySubscripts = 0;
1776  }
1777 }
1778 
1779 void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
1780  unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
1781  // ObjC block sometimes follow special indentation rules.
1782  unsigned NewIndent =
1783  NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace)
1784  ? Style.ObjCBlockIndentWidth
1785  : Style.IndentWidth);
1786  State.Stack.push_back(ParenState(State.NextToken, NewIndent,
1787  State.Stack.back().LastSpace,
1788  /*AvoidBinPacking=*/true,
1789  /*NoLineBreak=*/false));
1790  State.Stack.back().NestedBlockIndent = NestedBlockIndent;
1791  State.Stack.back().BreakBeforeParameter = true;
1792 }
1793 
1794 static unsigned getLastLineEndColumn(StringRef Text, unsigned StartColumn,
1795  unsigned TabWidth,
1797  size_t LastNewlinePos = Text.find_last_of("\n");
1798  if (LastNewlinePos == StringRef::npos) {
1799  return StartColumn +
1800  encoding::columnWidthWithTabs(Text, StartColumn, TabWidth, Encoding);
1801  } else {
1802  return encoding::columnWidthWithTabs(Text.substr(LastNewlinePos),
1803  /*StartColumn=*/0, TabWidth, Encoding);
1804  }
1805 }
1806 
1807 unsigned ContinuationIndenter::reformatRawStringLiteral(
1808  const FormatToken &Current, LineState &State,
1809  const FormatStyle &RawStringStyle, bool DryRun, bool Newline) {
1810  unsigned StartColumn = State.Column - Current.ColumnWidth;
1811  StringRef OldDelimiter = *getRawStringDelimiter(Current.TokenText);
1812  StringRef NewDelimiter =
1813  getCanonicalRawStringDelimiter(Style, RawStringStyle.Language);
1814  if (NewDelimiter.empty())
1815  NewDelimiter = OldDelimiter;
1816  // The text of a raw string is between the leading 'R"delimiter(' and the
1817  // trailing 'delimiter)"'.
1818  unsigned OldPrefixSize = 3 + OldDelimiter.size();
1819  unsigned OldSuffixSize = 2 + OldDelimiter.size();
1820  // We create a virtual text environment which expects a null-terminated
1821  // string, so we cannot use StringRef.
1822  std::string RawText = std::string(
1823  Current.TokenText.substr(OldPrefixSize).drop_back(OldSuffixSize));
1824  if (NewDelimiter != OldDelimiter) {
1825  // Don't update to the canonical delimiter 'deli' if ')deli"' occurs in the
1826  // raw string.
1827  std::string CanonicalDelimiterSuffix = (")" + NewDelimiter + "\"").str();
1828  if (StringRef(RawText).contains(CanonicalDelimiterSuffix))
1829  NewDelimiter = OldDelimiter;
1830  }
1831 
1832  unsigned NewPrefixSize = 3 + NewDelimiter.size();
1833  unsigned NewSuffixSize = 2 + NewDelimiter.size();
1834 
1835  // The first start column is the column the raw text starts after formatting.
1836  unsigned FirstStartColumn = StartColumn + NewPrefixSize;
1837 
1838  // The next start column is the intended indentation a line break inside
1839  // the raw string at level 0. It is determined by the following rules:
1840  // - if the content starts on newline, it is one level more than the current
1841  // indent, and
1842  // - if the content does not start on a newline, it is the first start
1843  // column.
1844  // These rules have the advantage that the formatted content both does not
1845  // violate the rectangle rule and visually flows within the surrounding
1846  // source.
1847  bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n';
1848  // If this token is the last parameter (checked by looking if it's followed by
1849  // `)` and is not on a newline, the base the indent off the line's nested
1850  // block indent. Otherwise, base the indent off the arguments indent, so we
1851  // can achieve:
1852  //
1853  // fffffffffff(1, 2, 3, R"pb(
1854  // key1: 1 #
1855  // key2: 2)pb");
1856  //
1857  // fffffffffff(1, 2, 3,
1858  // R"pb(
1859  // key1: 1 #
1860  // key2: 2
1861  // )pb");
1862  //
1863  // fffffffffff(1, 2, 3,
1864  // R"pb(
1865  // key1: 1 #
1866  // key2: 2
1867  // )pb",
1868  // 5);
1869  unsigned CurrentIndent =
1870  (!Newline && Current.Next && Current.Next->is(tok::r_paren))
1871  ? State.Stack.back().NestedBlockIndent
1872  : State.Stack.back().Indent;
1873  unsigned NextStartColumn = ContentStartsOnNewline
1874  ? CurrentIndent + Style.IndentWidth
1875  : FirstStartColumn;
1876 
1877  // The last start column is the column the raw string suffix starts if it is
1878  // put on a newline.
1879  // The last start column is the intended indentation of the raw string postfix
1880  // if it is put on a newline. It is determined by the following rules:
1881  // - if the raw string prefix starts on a newline, it is the column where
1882  // that raw string prefix starts, and
1883  // - if the raw string prefix does not start on a newline, it is the current
1884  // indent.
1885  unsigned LastStartColumn =
1886  Current.NewlinesBefore ? FirstStartColumn - NewPrefixSize : CurrentIndent;
1887 
1888  std::pair<tooling::Replacements, unsigned> Fixes = internal::reformat(
1889  RawStringStyle, RawText, {tooling::Range(0, RawText.size())},
1890  FirstStartColumn, NextStartColumn, LastStartColumn, "<stdin>",
1891  /*Status=*/nullptr);
1892 
1893  auto NewCode = applyAllReplacements(RawText, Fixes.first);
1894  tooling::Replacements NoFixes;
1895  if (!NewCode)
1896  return addMultilineToken(Current, State);
1897  if (!DryRun) {
1898  if (NewDelimiter != OldDelimiter) {
1899  // In 'R"delimiter(...', the delimiter starts 2 characters after the start
1900  // of the token.
1901  SourceLocation PrefixDelimiterStart =
1902  Current.Tok.getLocation().getLocWithOffset(2);
1903  auto PrefixErr = Whitespaces.addReplacement(tooling::Replacement(
1904  SourceMgr, PrefixDelimiterStart, OldDelimiter.size(), NewDelimiter));
1905  if (PrefixErr) {
1906  llvm::errs()
1907  << "Failed to update the prefix delimiter of a raw string: "
1908  << llvm::toString(std::move(PrefixErr)) << "\n";
1909  }
1910  // In 'R"delimiter(...)delimiter"', the suffix delimiter starts at
1911  // position length - 1 - |delimiter|.
1912  SourceLocation SuffixDelimiterStart =
1913  Current.Tok.getLocation().getLocWithOffset(Current.TokenText.size() -
1914  1 - OldDelimiter.size());
1915  auto SuffixErr = Whitespaces.addReplacement(tooling::Replacement(
1916  SourceMgr, SuffixDelimiterStart, OldDelimiter.size(), NewDelimiter));
1917  if (SuffixErr) {
1918  llvm::errs()
1919  << "Failed to update the suffix delimiter of a raw string: "
1920  << llvm::toString(std::move(SuffixErr)) << "\n";
1921  }
1922  }
1923  SourceLocation OriginLoc =
1924  Current.Tok.getLocation().getLocWithOffset(OldPrefixSize);
1925  for (const tooling::Replacement &Fix : Fixes.first) {
1926  auto Err = Whitespaces.addReplacement(tooling::Replacement(
1927  SourceMgr, OriginLoc.getLocWithOffset(Fix.getOffset()),
1928  Fix.getLength(), Fix.getReplacementText()));
1929  if (Err) {
1930  llvm::errs() << "Failed to reformat raw string: "
1931  << llvm::toString(std::move(Err)) << "\n";
1932  }
1933  }
1934  }
1935  unsigned RawLastLineEndColumn = getLastLineEndColumn(
1936  *NewCode, FirstStartColumn, Style.TabWidth, Encoding);
1937  State.Column = RawLastLineEndColumn + NewSuffixSize;
1938  // Since we're updating the column to after the raw string literal here, we
1939  // have to manually add the penalty for the prefix R"delim( over the column
1940  // limit.
1941  unsigned PrefixExcessCharacters =
1942  StartColumn + NewPrefixSize > Style.ColumnLimit
1943  ? StartColumn + NewPrefixSize - Style.ColumnLimit
1944  : 0;
1945  bool IsMultiline =
1946  ContentStartsOnNewline || (NewCode->find('\n') != std::string::npos);
1947  if (IsMultiline) {
1948  // Break before further function parameters on all levels.
1949  for (ParenState &Paren : State.Stack)
1950  Paren.BreakBeforeParameter = true;
1951  }
1952  return Fixes.second + PrefixExcessCharacters * Style.PenaltyExcessCharacter;
1953 }
1954 
1955 unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
1956  LineState &State) {
1957  // Break before further function parameters on all levels.
1958  for (ParenState &Paren : State.Stack)
1959  Paren.BreakBeforeParameter = true;
1960 
1961  unsigned ColumnsUsed = State.Column;
1962  // We can only affect layout of the first and the last line, so the penalty
1963  // for all other lines is constant, and we ignore it.
1964  State.Column = Current.LastLineColumnWidth;
1965 
1966  if (ColumnsUsed > getColumnLimit(State))
1967  return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
1968  return 0;
1969 }
1970 
1971 unsigned ContinuationIndenter::handleEndOfLine(const FormatToken &Current,
1972  LineState &State, bool DryRun,
1973  bool AllowBreak, bool Newline) {
1974  unsigned Penalty = 0;
1975  // Compute the raw string style to use in case this is a raw string literal
1976  // that can be reformatted.
1977  auto RawStringStyle = getRawStringStyle(Current, State);
1978  if (RawStringStyle && !Current.Finalized) {
1979  Penalty = reformatRawStringLiteral(Current, State, *RawStringStyle, DryRun,
1980  Newline);
1981  } else if (Current.IsMultiline && Current.isNot(TT_BlockComment)) {
1982  // Don't break multi-line tokens other than block comments and raw string
1983  // literals. Instead, just update the state.
1984  Penalty = addMultilineToken(Current, State);
1985  } else if (State.Line->Type != LT_ImportStatement) {
1986  // We generally don't break import statements.
1987  LineState OriginalState = State;
1988 
1989  // Whether we force the reflowing algorithm to stay strictly within the
1990  // column limit.
1991  bool Strict = false;
1992  // Whether the first non-strict attempt at reflowing did intentionally
1993  // exceed the column limit.
1994  bool Exceeded = false;
1995  std::tie(Penalty, Exceeded) = breakProtrudingToken(
1996  Current, State, AllowBreak, /*DryRun=*/true, Strict);
1997  if (Exceeded) {
1998  // If non-strict reflowing exceeds the column limit, try whether strict
1999  // reflowing leads to an overall lower penalty.
2000  LineState StrictState = OriginalState;
2001  unsigned StrictPenalty =
2002  breakProtrudingToken(Current, StrictState, AllowBreak,
2003  /*DryRun=*/true, /*Strict=*/true)
2004  .first;
2005  Strict = StrictPenalty <= Penalty;
2006  if (Strict) {
2007  Penalty = StrictPenalty;
2008  State = StrictState;
2009  }
2010  }
2011  if (!DryRun) {
2012  // If we're not in dry-run mode, apply the changes with the decision on
2013  // strictness made above.
2014  breakProtrudingToken(Current, OriginalState, AllowBreak, /*DryRun=*/false,
2015  Strict);
2016  }
2017  }
2018  if (State.Column > getColumnLimit(State)) {
2019  unsigned ExcessCharacters = State.Column - getColumnLimit(State);
2020  Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
2021  }
2022  return Penalty;
2023 }
2024 
2025 // Returns the enclosing function name of a token, or the empty string if not
2026 // found.
2027 static StringRef getEnclosingFunctionName(const FormatToken &Current) {
2028  // Look for: 'function(' or 'function<templates>(' before Current.
2029  auto Tok = Current.getPreviousNonComment();
2030  if (!Tok || !Tok->is(tok::l_paren))
2031  return "";
2032  Tok = Tok->getPreviousNonComment();
2033  if (!Tok)
2034  return "";
2035  if (Tok->is(TT_TemplateCloser)) {
2036  Tok = Tok->MatchingParen;
2037  if (Tok)
2038  Tok = Tok->getPreviousNonComment();
2039  }
2040  if (!Tok || !Tok->is(tok::identifier))
2041  return "";
2042  return Tok->TokenText;
2043 }
2044 
2046 ContinuationIndenter::getRawStringStyle(const FormatToken &Current,
2047  const LineState &State) {
2048  if (!Current.isStringLiteral())
2049  return None;
2050  auto Delimiter = getRawStringDelimiter(Current.TokenText);
2051  if (!Delimiter)
2052  return None;
2053  auto RawStringStyle = RawStringFormats.getDelimiterStyle(*Delimiter);
2054  if (!RawStringStyle && Delimiter->empty()) {
2055  RawStringStyle = RawStringFormats.getEnclosingFunctionStyle(
2056  getEnclosingFunctionName(Current));
2057  }
2058  if (!RawStringStyle)
2059  return None;
2060  RawStringStyle->ColumnLimit = getColumnLimit(State);
2061  return RawStringStyle;
2062 }
2063 
2064 std::unique_ptr<BreakableToken>
2065 ContinuationIndenter::createBreakableToken(const FormatToken &Current,
2066  LineState &State, bool AllowBreak) {
2067  unsigned StartColumn = State.Column - Current.ColumnWidth;
2068  if (Current.isStringLiteral()) {
2069  // FIXME: String literal breaking is currently disabled for C#, Java, Json
2070  // and JavaScript, as it requires strings to be merged using "+" which we
2071  // don't support.
2072  if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
2073  Style.isCSharp() || Style.isJson() || !Style.BreakStringLiterals ||
2074  !AllowBreak) {
2075  return nullptr;
2076  }
2077 
2078  // Don't break string literals inside preprocessor directives (except for
2079  // #define directives, as their contents are stored in separate lines and
2080  // are not affected by this check).
2081  // This way we avoid breaking code with line directives and unknown
2082  // preprocessor directives that contain long string literals.
2083  if (State.Line->Type == LT_PreprocessorDirective)
2084  return nullptr;
2085  // Exempts unterminated string literals from line breaking. The user will
2086  // likely want to terminate the string before any line breaking is done.
2087  if (Current.IsUnterminatedLiteral)
2088  return nullptr;
2089  // Don't break string literals inside Objective-C array literals (doing so
2090  // raises the warning -Wobjc-string-concatenation).
2091  if (State.Stack.back().IsInsideObjCArrayLiteral)
2092  return nullptr;
2093 
2094  StringRef Text = Current.TokenText;
2095  StringRef Prefix;
2096  StringRef Postfix;
2097  // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
2098  // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
2099  // reduce the overhead) for each FormatToken, which is a string, so that we
2100  // don't run multiple checks here on the hot path.
2101  if ((Text.endswith(Postfix = "\"") &&
2102  (Text.startswith(Prefix = "@\"") || Text.startswith(Prefix = "\"") ||
2103  Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
2104  Text.startswith(Prefix = "u8\"") ||
2105  Text.startswith(Prefix = "L\""))) ||
2106  (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) {
2107  // We need this to address the case where there is an unbreakable tail
2108  // only if certain other formatting decisions have been taken. The
2109  // UnbreakableTailLength of Current is an overapproximation is that case
2110  // and we need to be correct here.
2111  unsigned UnbreakableTailLength = (State.NextToken && canBreak(State))
2112  ? 0
2113  : Current.UnbreakableTailLength;
2114  return std::make_unique<BreakableStringLiteral>(
2115  Current, StartColumn, Prefix, Postfix, UnbreakableTailLength,
2116  State.Line->InPPDirective, Encoding, Style);
2117  }
2118  } else if (Current.is(TT_BlockComment)) {
2119  if (!Style.ReflowComments ||
2120  // If a comment token switches formatting, like
2121  // /* clang-format on */, we don't want to break it further,
2122  // but we may still want to adjust its indentation.
2123  switchesFormatting(Current)) {
2124  return nullptr;
2125  }
2126  return std::make_unique<BreakableBlockComment>(
2127  Current, StartColumn, Current.OriginalColumn, !Current.Previous,
2128  State.Line->InPPDirective, Encoding, Style, Whitespaces.useCRLF());
2129  } else if (Current.is(TT_LineComment) &&
2130  (Current.Previous == nullptr ||
2131  Current.Previous->isNot(TT_ImplicitStringLiteral))) {
2132  bool RegularComments = [&]() {
2133  for (const FormatToken *T = &Current; T && T->is(TT_LineComment);
2134  T = T->Next) {
2135  if (!(T->TokenText.startswith("//") || T->TokenText.startswith("#")))
2136  return false;
2137  }
2138  return true;
2139  }();
2140  if (!Style.ReflowComments ||
2141  CommentPragmasRegex.match(Current.TokenText.substr(2)) ||
2142  switchesFormatting(Current) || !RegularComments) {
2143  return nullptr;
2144  }
2145  return std::make_unique<BreakableLineCommentSection>(
2146  Current, StartColumn, /*InPPDirective=*/false, Encoding, Style);
2147  }
2148  return nullptr;
2149 }
2150 
2151 std::pair<unsigned, bool>
2152 ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
2153  LineState &State, bool AllowBreak,
2154  bool DryRun, bool Strict) {
2155  std::unique_ptr<const BreakableToken> Token =
2156  createBreakableToken(Current, State, AllowBreak);
2157  if (!Token)
2158  return {0, false};
2159  assert(Token->getLineCount() > 0);
2160  unsigned ColumnLimit = getColumnLimit(State);
2161  if (Current.is(TT_LineComment)) {
2162  // We don't insert backslashes when breaking line comments.
2163  ColumnLimit = Style.ColumnLimit;
2164  }
2165  if (ColumnLimit == 0) {
2166  // To make the rest of the function easier set the column limit to the
2167  // maximum, if there should be no limit.
2168  ColumnLimit = std::numeric_limits<decltype(ColumnLimit)>::max();
2169  }
2170  if (Current.UnbreakableTailLength >= ColumnLimit)
2171  return {0, false};
2172  // ColumnWidth was already accounted into State.Column before calling
2173  // breakProtrudingToken.
2174  unsigned StartColumn = State.Column - Current.ColumnWidth;
2175  unsigned NewBreakPenalty = Current.isStringLiteral()
2176  ? Style.PenaltyBreakString
2177  : Style.PenaltyBreakComment;
2178  // Stores whether we intentionally decide to let a line exceed the column
2179  // limit.
2180  bool Exceeded = false;
2181  // Stores whether we introduce a break anywhere in the token.
2182  bool BreakInserted = Token->introducesBreakBeforeToken();
2183  // Store whether we inserted a new line break at the end of the previous
2184  // logical line.
2185  bool NewBreakBefore = false;
2186  // We use a conservative reflowing strategy. Reflow starts after a line is
2187  // broken or the corresponding whitespace compressed. Reflow ends as soon as a
2188  // line that doesn't get reflown with the previous line is reached.
2189  bool Reflow = false;
2190  // Keep track of where we are in the token:
2191  // Where we are in the content of the current logical line.
2192  unsigned TailOffset = 0;
2193  // The column number we're currently at.
2194  unsigned ContentStartColumn =
2195  Token->getContentStartColumn(0, /*Break=*/false);
2196  // The number of columns left in the current logical line after TailOffset.
2197  unsigned RemainingTokenColumns =
2198  Token->getRemainingLength(0, TailOffset, ContentStartColumn);
2199  // Adapt the start of the token, for example indent.
2200  if (!DryRun)
2201  Token->adaptStartOfLine(0, Whitespaces);
2202 
2203  unsigned ContentIndent = 0;
2204  unsigned Penalty = 0;
2205  LLVM_DEBUG(llvm::dbgs() << "Breaking protruding token at column "
2206  << StartColumn << ".\n");
2207  for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
2208  LineIndex != EndIndex; ++LineIndex) {
2209  LLVM_DEBUG(llvm::dbgs()
2210  << " Line: " << LineIndex << " (Reflow: " << Reflow << ")\n");
2211  NewBreakBefore = false;
2212  // If we did reflow the previous line, we'll try reflowing again. Otherwise
2213  // we'll start reflowing if the current line is broken or whitespace is
2214  // compressed.
2215  bool TryReflow = Reflow;
2216  // Break the current token until we can fit the rest of the line.
2217  while (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
2218  LLVM_DEBUG(llvm::dbgs() << " Over limit, need: "
2219  << (ContentStartColumn + RemainingTokenColumns)
2220  << ", space: " << ColumnLimit
2221  << ", reflown prefix: " << ContentStartColumn
2222  << ", offset in line: " << TailOffset << "\n");
2223  // If the current token doesn't fit, find the latest possible split in the
2224  // current line so that breaking at it will be under the column limit.
2225  // FIXME: Use the earliest possible split while reflowing to correctly
2226  // compress whitespace within a line.
2228  Token->getSplit(LineIndex, TailOffset, ColumnLimit,
2229  ContentStartColumn, CommentPragmasRegex);
2230  if (Split.first == StringRef::npos) {
2231  // No break opportunity - update the penalty and continue with the next
2232  // logical line.
2233  if (LineIndex < EndIndex - 1) {
2234  // The last line's penalty is handled in addNextStateToQueue() or when
2235  // calling replaceWhitespaceAfterLastLine below.
2236  Penalty += Style.PenaltyExcessCharacter *
2237  (ContentStartColumn + RemainingTokenColumns - ColumnLimit);
2238  }
2239  LLVM_DEBUG(llvm::dbgs() << " No break opportunity.\n");
2240  break;
2241  }
2242  assert(Split.first != 0);
2243 
2244  if (Token->supportsReflow()) {
2245  // Check whether the next natural split point after the current one can
2246  // still fit the line, either because we can compress away whitespace,
2247  // or because the penalty the excess characters introduce is lower than
2248  // the break penalty.
2249  // We only do this for tokens that support reflowing, and thus allow us
2250  // to change the whitespace arbitrarily (e.g. comments).
2251  // Other tokens, like string literals, can be broken on arbitrary
2252  // positions.
2253 
2254  // First, compute the columns from TailOffset to the next possible split
2255  // position.
2256  // For example:
2257  // ColumnLimit: |
2258  // // Some text that breaks
2259  // ^ tail offset
2260  // ^-- split
2261  // ^-------- to split columns
2262  // ^--- next split
2263  // ^--------------- to next split columns
2264  unsigned ToSplitColumns = Token->getRangeLength(
2265  LineIndex, TailOffset, Split.first, ContentStartColumn);
2266  LLVM_DEBUG(llvm::dbgs() << " ToSplit: " << ToSplitColumns << "\n");
2267 
2268  BreakableToken::Split NextSplit = Token->getSplit(
2269  LineIndex, TailOffset + Split.first + Split.second, ColumnLimit,
2270  ContentStartColumn + ToSplitColumns + 1, CommentPragmasRegex);
2271  // Compute the columns necessary to fit the next non-breakable sequence
2272  // into the current line.
2273  unsigned ToNextSplitColumns = 0;
2274  if (NextSplit.first == StringRef::npos) {
2275  ToNextSplitColumns = Token->getRemainingLength(LineIndex, TailOffset,
2276  ContentStartColumn);
2277  } else {
2278  ToNextSplitColumns = Token->getRangeLength(
2279  LineIndex, TailOffset,
2280  Split.first + Split.second + NextSplit.first, ContentStartColumn);
2281  }
2282  // Compress the whitespace between the break and the start of the next
2283  // unbreakable sequence.
2284  ToNextSplitColumns =
2285  Token->getLengthAfterCompression(ToNextSplitColumns, Split);
2286  LLVM_DEBUG(llvm::dbgs()
2287  << " ContentStartColumn: " << ContentStartColumn << "\n");
2288  LLVM_DEBUG(llvm::dbgs()
2289  << " ToNextSplit: " << ToNextSplitColumns << "\n");
2290  // If the whitespace compression makes us fit, continue on the current
2291  // line.
2292  bool ContinueOnLine =
2293  ContentStartColumn + ToNextSplitColumns <= ColumnLimit;
2294  unsigned ExcessCharactersPenalty = 0;
2295  if (!ContinueOnLine && !Strict) {
2296  // Similarly, if the excess characters' penalty is lower than the
2297  // penalty of introducing a new break, continue on the current line.
2298  ExcessCharactersPenalty =
2299  (ContentStartColumn + ToNextSplitColumns - ColumnLimit) *
2300  Style.PenaltyExcessCharacter;
2301  LLVM_DEBUG(llvm::dbgs()
2302  << " Penalty excess: " << ExcessCharactersPenalty
2303  << "\n break : " << NewBreakPenalty << "\n");
2304  if (ExcessCharactersPenalty < NewBreakPenalty) {
2305  Exceeded = true;
2306  ContinueOnLine = true;
2307  }
2308  }
2309  if (ContinueOnLine) {
2310  LLVM_DEBUG(llvm::dbgs() << " Continuing on line...\n");
2311  // The current line fits after compressing the whitespace - reflow
2312  // the next line into it if possible.
2313  TryReflow = true;
2314  if (!DryRun) {
2315  Token->compressWhitespace(LineIndex, TailOffset, Split,
2316  Whitespaces);
2317  }
2318  // When we continue on the same line, leave one space between content.
2319  ContentStartColumn += ToSplitColumns + 1;
2320  Penalty += ExcessCharactersPenalty;
2321  TailOffset += Split.first + Split.second;
2322  RemainingTokenColumns = Token->getRemainingLength(
2323  LineIndex, TailOffset, ContentStartColumn);
2324  continue;
2325  }
2326  }
2327  LLVM_DEBUG(llvm::dbgs() << " Breaking...\n");
2328  // Update the ContentIndent only if the current line was not reflown with
2329  // the previous line, since in that case the previous line should still
2330  // determine the ContentIndent. Also never intent the last line.
2331  if (!Reflow)
2332  ContentIndent = Token->getContentIndent(LineIndex);
2333  LLVM_DEBUG(llvm::dbgs()
2334  << " ContentIndent: " << ContentIndent << "\n");
2335  ContentStartColumn = ContentIndent + Token->getContentStartColumn(
2336  LineIndex, /*Break=*/true);
2337 
2338  unsigned NewRemainingTokenColumns = Token->getRemainingLength(
2339  LineIndex, TailOffset + Split.first + Split.second,
2340  ContentStartColumn);
2341  if (NewRemainingTokenColumns == 0) {
2342  // No content to indent.
2343  ContentIndent = 0;
2344  ContentStartColumn =
2345  Token->getContentStartColumn(LineIndex, /*Break=*/true);
2346  NewRemainingTokenColumns = Token->getRemainingLength(
2347  LineIndex, TailOffset + Split.first + Split.second,
2348  ContentStartColumn);
2349  }
2350 
2351  // When breaking before a tab character, it may be moved by a few columns,
2352  // but will still be expanded to the next tab stop, so we don't save any
2353  // columns.
2354  if (NewRemainingTokenColumns >= RemainingTokenColumns) {
2355  // FIXME: Do we need to adjust the penalty?
2356  break;
2357  }
2358 
2359  LLVM_DEBUG(llvm::dbgs() << " Breaking at: " << TailOffset + Split.first
2360  << ", " << Split.second << "\n");
2361  if (!DryRun) {
2362  Token->insertBreak(LineIndex, TailOffset, Split, ContentIndent,
2363  Whitespaces);
2364  }
2365 
2366  Penalty += NewBreakPenalty;
2367  TailOffset += Split.first + Split.second;
2368  RemainingTokenColumns = NewRemainingTokenColumns;
2369  BreakInserted = true;
2370  NewBreakBefore = true;
2371  }
2372  // In case there's another line, prepare the state for the start of the next
2373  // line.
2374  if (LineIndex + 1 != EndIndex) {
2375  unsigned NextLineIndex = LineIndex + 1;
2376  if (NewBreakBefore) {
2377  // After breaking a line, try to reflow the next line into the current
2378  // one once RemainingTokenColumns fits.
2379  TryReflow = true;
2380  }
2381  if (TryReflow) {
2382  // We decided that we want to try reflowing the next line into the
2383  // current one.
2384  // We will now adjust the state as if the reflow is successful (in
2385  // preparation for the next line), and see whether that works. If we
2386  // decide that we cannot reflow, we will later reset the state to the
2387  // start of the next line.
2388  Reflow = false;
2389  // As we did not continue breaking the line, RemainingTokenColumns is
2390  // known to fit after ContentStartColumn. Adapt ContentStartColumn to
2391  // the position at which we want to format the next line if we do
2392  // actually reflow.
2393  // When we reflow, we need to add a space between the end of the current
2394  // line and the next line's start column.
2395  ContentStartColumn += RemainingTokenColumns + 1;
2396  // Get the split that we need to reflow next logical line into the end
2397  // of the current one; the split will include any leading whitespace of
2398  // the next logical line.
2399  BreakableToken::Split SplitBeforeNext =
2400  Token->getReflowSplit(NextLineIndex, CommentPragmasRegex);
2401  LLVM_DEBUG(llvm::dbgs()
2402  << " Size of reflown text: " << ContentStartColumn
2403  << "\n Potential reflow split: ");
2404  if (SplitBeforeNext.first != StringRef::npos) {
2405  LLVM_DEBUG(llvm::dbgs() << SplitBeforeNext.first << ", "
2406  << SplitBeforeNext.second << "\n");
2407  TailOffset = SplitBeforeNext.first + SplitBeforeNext.second;
2408  // If the rest of the next line fits into the current line below the
2409  // column limit, we can safely reflow.
2410  RemainingTokenColumns = Token->getRemainingLength(
2411  NextLineIndex, TailOffset, ContentStartColumn);
2412  Reflow = true;
2413  if (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
2414  LLVM_DEBUG(llvm::dbgs()
2415  << " Over limit after reflow, need: "
2416  << (ContentStartColumn + RemainingTokenColumns)
2417  << ", space: " << ColumnLimit
2418  << ", reflown prefix: " << ContentStartColumn
2419  << ", offset in line: " << TailOffset << "\n");
2420  // If the whole next line does not fit, try to find a point in
2421  // the next line at which we can break so that attaching the part
2422  // of the next line to that break point onto the current line is
2423  // below the column limit.
2425  Token->getSplit(NextLineIndex, TailOffset, ColumnLimit,
2426  ContentStartColumn, CommentPragmasRegex);
2427  if (Split.first == StringRef::npos) {
2428  LLVM_DEBUG(llvm::dbgs() << " Did not find later break\n");
2429  Reflow = false;
2430  } else {
2431  // Check whether the first split point gets us below the column
2432  // limit. Note that we will execute this split below as part of
2433  // the normal token breaking and reflow logic within the line.
2434  unsigned ToSplitColumns = Token->getRangeLength(
2435  NextLineIndex, TailOffset, Split.first, ContentStartColumn);
2436  if (ContentStartColumn + ToSplitColumns > ColumnLimit) {
2437  LLVM_DEBUG(llvm::dbgs() << " Next split protrudes, need: "
2438  << (ContentStartColumn + ToSplitColumns)
2439  << ", space: " << ColumnLimit);
2440  unsigned ExcessCharactersPenalty =
2441  (ContentStartColumn + ToSplitColumns - ColumnLimit) *
2442  Style.PenaltyExcessCharacter;
2443  if (NewBreakPenalty < ExcessCharactersPenalty)
2444  Reflow = false;
2445  }
2446  }
2447  }
2448  } else {
2449  LLVM_DEBUG(llvm::dbgs() << "not found.\n");
2450  }
2451  }
2452  if (!Reflow) {
2453  // If we didn't reflow into the next line, the only space to consider is
2454  // the next logical line. Reset our state to match the start of the next
2455  // line.
2456  TailOffset = 0;
2457  ContentStartColumn =
2458  Token->getContentStartColumn(NextLineIndex, /*Break=*/false);
2459  RemainingTokenColumns = Token->getRemainingLength(
2460  NextLineIndex, TailOffset, ContentStartColumn);
2461  // Adapt the start of the token, for example indent.
2462  if (!DryRun)
2463  Token->adaptStartOfLine(NextLineIndex, Whitespaces);
2464  } else {
2465  // If we found a reflow split and have added a new break before the next
2466  // line, we are going to remove the line break at the start of the next
2467  // logical line. For example, here we'll add a new line break after
2468  // 'text', and subsequently delete the line break between 'that' and
2469  // 'reflows'.
2470  // // some text that
2471  // // reflows
2472  // ->
2473  // // some text
2474  // // that reflows
2475  // When adding the line break, we also added the penalty for it, so we
2476  // need to subtract that penalty again when we remove the line break due
2477  // to reflowing.
2478  if (NewBreakBefore) {
2479  assert(Penalty >= NewBreakPenalty);
2480  Penalty -= NewBreakPenalty;
2481  }
2482  if (!DryRun)
2483  Token->reflow(NextLineIndex, Whitespaces);
2484  }
2485  }
2486  }
2487 
2488  BreakableToken::Split SplitAfterLastLine =
2489  Token->getSplitAfterLastLine(TailOffset);
2490  if (SplitAfterLastLine.first != StringRef::npos) {
2491  LLVM_DEBUG(llvm::dbgs() << "Replacing whitespace after last line.\n");
2492 
2493  // We add the last line's penalty here, since that line is going to be split
2494  // now.
2495  Penalty += Style.PenaltyExcessCharacter *
2496  (ContentStartColumn + RemainingTokenColumns - ColumnLimit);
2497 
2498  if (!DryRun) {
2499  Token->replaceWhitespaceAfterLastLine(TailOffset, SplitAfterLastLine,
2500  Whitespaces);
2501  }
2502  ContentStartColumn =
2503  Token->getContentStartColumn(Token->getLineCount() - 1, /*Break=*/true);
2504  RemainingTokenColumns = Token->getRemainingLength(
2505  Token->getLineCount() - 1,
2506  TailOffset + SplitAfterLastLine.first + SplitAfterLastLine.second,
2507  ContentStartColumn);
2508  }
2509 
2510  State.Column = ContentStartColumn + RemainingTokenColumns -
2511  Current.UnbreakableTailLength;
2512 
2513  if (BreakInserted) {
2514  // If we break the token inside a parameter list, we need to break before
2515  // the next parameter on all levels, so that the next parameter is clearly
2516  // visible. Line comments already introduce a break.
2517  if (Current.isNot(TT_LineComment))
2518  for (ParenState &Paren : State.Stack)
2519  Paren.BreakBeforeParameter = true;
2520 
2521  if (Current.is(TT_BlockComment))
2522  State.NoContinuation = true;
2523 
2524  State.Stack.back().LastSpace = StartColumn;
2525  }
2526 
2527  Token->updateNextToken(State);
2528 
2529  return {Penalty, Exceeded};
2530 }
2531 
2533  // In preprocessor directives reserve two chars for trailing " \"
2534  return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
2535 }
2536 
2537 bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
2538  const FormatToken &Current = *State.NextToken;
2539  if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral))
2540  return false;
2541  // We never consider raw string literals "multiline" for the purpose of
2542  // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
2543  // (see TokenAnnotator::mustBreakBefore().
2544  if (Current.TokenText.startswith("R\""))
2545  return false;
2546  if (Current.IsMultiline)
2547  return true;
2548  if (Current.getNextNonComment() &&
2549  Current.getNextNonComment()->isStringLiteral()) {
2550  return true; // Implicit concatenation.
2551  }
2552  if (Style.ColumnLimit != 0 && Style.BreakStringLiterals &&
2553  State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
2554  Style.ColumnLimit) {
2555  return true; // String will be split.
2556  }
2557  return false;
2558 }
2559 
2560 } // namespace format
2561 } // namespace clang
clang::format::FormatToken::MustBreakBefore
unsigned MustBreakBefore
Whether there must be a line break before this token.
Definition: FormatToken.h:270
clang::format::FormatStyle::BTDS_No
@ BTDS_No
Do not force break before declaration.
Definition: Format.h:763
clang::prec::Comma
@ Comma
Definition: OperatorPrecedence.h:28
clang::format::FormatStyle::BBCDS_Never
@ BBCDS_Never
Keep the template declaration line together with concept.
Definition: Format.h:1649
clang::prec::Conditional
@ Conditional
Definition: OperatorPrecedence.h:30
clang::format::FormatStyle::RCPS_WithPreceding
@ RCPS_WithPreceding
Try to put the clause together with the preceding part of a declaration.
Definition: Format.h:3077
max
__DEVICE__ int max(int __a, int __b)
Definition: __clang_cuda_math.h:196
clang::format::FormatStyle::BILS_BeforeComma
@ BILS_BeforeComma
Break inheritance list before the colon and commas, and align the commas with the colon.
Definition: Format.h:1840
clang::format::AdditionalKeywords::kw_implements
IdentifierInfo * kw_implements
Definition: FormatToken.h:1309
clang::format::hasNestedBlockInlined
static bool hasNestedBlockInlined(const FormatToken *Previous, const FormatToken &Current, const FormatStyle &Style)
Definition: ContinuationIndenter.cpp:1293
clang::format::FormatStyle::BCIS_BeforeColon
@ BCIS_BeforeColon
Break constructor initializers before the colon and after the commas.
Definition: Format.h:1690
clang::format::FormatStyle::BreakStringLiterals
bool BreakStringLiterals
Allow breaking string literals when formatting.
Definition: Format.h:1734
clang::format::FormatStyle::MaxEmptyLinesToKeep
unsigned MaxEmptyLinesToKeep
The maximum number of consecutive empty lines to keep.
Definition: Format.h:2686
clang::format::FormatToken::getNextNonComment
const LLVM_NODISCARD FormatToken * getNextNonComment() const
Returns the next token ignoring comments.
Definition: FormatToken.h:704
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::format::FormatStyle::RequiresClausePosition
RequiresClausePositionStyle RequiresClausePosition
The position of the requires clause.
Definition: Format.h:3120
clang::format::FormatStyle::PenaltyBreakString
unsigned PenaltyBreakString
The penalty for each line break introduced inside a string literal.
Definition: Format.h:2826
clang::format::FormatStyle::ObjCBinPackProtocolList
BinPackStyle ObjCBinPackProtocolList
Controls bin-packing Objective-C protocol conformance list items into as few lines as possible when t...
Definition: Format.h:2757
clang::format::FormatStyle::BOS_None
@ BOS_None
Break after operators.
Definition: Format.h:899
FormatInternal.h
clang::if
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
Definition: RecursiveASTVisitor.h:1098
clang::format::FormatStyle::AlwaysBreakBeforeMultilineStrings
bool AlwaysBreakBeforeMultilineStrings
If true, always break before multiline string literals.
Definition: Format.h:750
clang::format::ContinuationIndenter::ContinuationIndenter
ContinuationIndenter(const FormatStyle &Style, const AdditionalKeywords &Keywords, const SourceManager &SourceMgr, WhitespaceManager &Whitespaces, encoding::Encoding Encoding, bool BinPackInconclusiveFunctions)
Constructs a ContinuationIndenter to format Line starting in column FirstIndent.
Definition: ContinuationIndenter.cpp:225
clang::format::FormatStyle::BraceWrappingFlags::BeforeLambdaBody
bool BeforeLambdaBody
Wrap lambda block.
Definition: Format.h:1572
clang::format::FormatStyle::AlwaysBreakTemplateDeclarations
BreakTemplateDeclarationsStyle AlwaysBreakTemplateDeclarations
The template declaration breaking style to use.
Definition: Format.h:790
clang::format::FormatStyle::BreakBeforeBinaryOperators
BinaryOperatorStyle BreakBeforeBinaryOperators
The way to wrap binary operators.
Definition: Format.h:928
clang::format::FormatStyle
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition: Format.h:54
clang::format::FormatToken::TokenText
StringRef TokenText
The raw text of the token.
Definition: FormatToken.h:245
clang::format::FormatToken
A wrapper around a Token storing information about the whitespace characters preceding it.
Definition: FormatToken.h:227
clang::format::AdditionalKeywords
Encapsulates keywords that are context sensitive or for languages not properly supported by Clang's l...
Definition: FormatToken.h:885
llvm::Optional
Definition: LLVM.h:40
clang::format::FormatStyle::AlwaysBreakAfterReturnType
ReturnTypeBreakingStyle AlwaysBreakAfterReturnType
The function declaration return type breaking style to use.
Definition: Format.h:735
clang::format::FormatToken::isNot
bool isNot(T Kind) const
Definition: FormatToken.h:519
clang::format::FormatToken::SpacesRequiredBefore
unsigned SpacesRequiredBefore
The number of spaces that should be inserted before this token.
Definition: FormatToken.h:391
clang::prec::Assignment
@ Assignment
Definition: OperatorPrecedence.h:29
SourceManager.h
clang::format::getPredefinedStyle
bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language, FormatStyle *Style)
Gets a predefined style for the specified language by name.
Definition: Format.cpp:1660
clang::format::FormatStyle::BBCDS_Allowed
@ BBCDS_Allowed
Breaking between template declaration and concept is allowed.
Definition: Format.h:1653
clang::format::FormatStyle::IndentWrappedFunctionNames
bool IndentWrappedFunctionNames
Indent if a function definition or declaration is wrapped after the type.
Definition: Format.h:2442
Format.h
clang::format::BK_BracedInit
@ BK_BracedInit
Definition: FormatToken.h:153
End
SourceLocation End
Definition: USRLocFinder.cpp:167
clang::format::WhitespaceManager::addReplacement
llvm::Error addReplacement(const tooling::Replacement &Replacement)
Definition: WhitespaceManager.cpp:73
BreakableToken.h
clang::SourceManager
This class handles loading and caching of source files into memory.
Definition: SourceManager.h:627
Paren
@ Paren
Definition: PPMacroExpansion.cpp:632
clang::SourceManager::getSpellingColumnNumber
unsigned getSpellingColumnNumber(SourceLocation Loc, bool *Invalid=nullptr) const
Definition: SourceManager.cpp:1232
clang::format::FormatToken::NewlinesBefore
unsigned NewlinesBefore
The number of newlines immediately before the Token.
Definition: FormatToken.h:375
clang::format::FormatStyle::BAS_BlockIndent
@ BAS_BlockIndent
Always break after an open bracket, if the parameters don't fit on a single line.
Definition: Format.h:97
clang::format::FormatToken::CanBreakBefore
unsigned CanBreakBefore
true if it is allowed to break before this token.
Definition: FormatToken.h:276
clang::format::FormatStyle::Cpp11BracedListStyle
bool Cpp11BracedListStyle
If true, format braced lists as best suited for C++11 braced lists.
Definition: Format.h:1928
clang::format::LT_PreprocessorDirective
@ LT_PreprocessorDirective
Definition: TokenAnnotator.h:31
clang::format::FormatToken::closesScope
bool closesScope() const
Returns whether Tok is )]} or a closing > of a template or in protos.
Definition: FormatToken.h:595
clang::format::FormatToken::NestingLevel
unsigned NestingLevel
The nesting level of this token, i.e.
Definition: FormatToken.h:423
clang::format::AdditionalKeywords::kw_extends
IdentifierInfo * kw_extends
Definition: FormatToken.h:1308
clang::format::AdditionalKeywords::kw_async
IdentifierInfo * kw_async
Definition: FormatToken.h:1286
clang::format::FormatToken::Previous
FormatToken * Previous
The previous token in the unwrapped line.
Definition: FormatToken.h:469
clang::format::LineState
The current state when indenting a unwrapped line.
Definition: ContinuationIndenter.h:415
clang::prec::Unknown
@ Unknown
Definition: OperatorPrecedence.h:27
clang::format::FormatStyle::AllowAllParametersOfDeclarationOnNextLine
bool AllowAllParametersOfDeclarationOnNextLine
This option is deprecated.
Definition: Format.h:419
min
__DEVICE__ int min(int __a, int __b)
Definition: __clang_cuda_math.h:197
clang::format::FormatStyle::OAS_DontAlign
@ OAS_DontAlign
Do not align operands of binary and ternary expressions.
Definition: Format.h:338
clang::format::FormatStyle::ReflowComments
bool ReflowComments
If true, clang-format will attempt to re-flow comments.
Definition: Format.h:2984
clang::format::FormatStyle::ExperimentalAutoDetectBinPacking
bool ExperimentalAutoDetectBinPacking
If true, clang-format detects whether function calls and definitions are formatted with one parameter...
Definition: Format.h:2072
clang::format::FormatStyle::PCIS_NextLine
@ PCIS_NextLine
Same as PCIS_CurrentLine except that if all constructor initializers do not fit on the current line,...
Definition: Format.h:2114
clang::format::FormatStyle::BCIS_BeforeComma
@ BCIS_BeforeComma
Break constructor initializers before the colon and commas, and align the commas with the colon.
Definition: Format.h:1698
clang::format::FormatStyle::IndentWidth
unsigned IndentWidth
The number of columns to use for indentation.
Definition: Format.h:2428
clang::format::FormatToken::isMemberAccess
bool isMemberAccess() const
Returns true if this is a "." or "->" accessing a member.
Definition: FormatToken.h:605
clang::format::encoding::Encoding
Encoding
Definition: Encoding.h:27
clang::format::FormatStyle::PPDIS_AfterHash
@ PPDIS_AfterHash
Indents directives after the hash.
Definition: Format.h:2338
clang::format::FormatStyle::LK_TextProto
@ LK_TextProto
Should be used for Protocol Buffer messages in text format (https://developers.google....
Definition: Format.h:2592
clang::threadSafety::sx::toString
std::string toString(const til::SExpr *E)
Definition: ThreadSafetyCommon.h:90
clang::format::FormatStyle::LK_Proto
@ LK_Proto
Should be used for Protocol Buffers (https://developers.google.com/protocol-buffers/).
Definition: Format.h:2587
clang::format::WhitespaceManager
Manages the whitespaces around tokens and their replacements.
Definition: WhitespaceManager.h:40
clang::format::AnnotatedLine
Definition: TokenAnnotator.h:36
clang::format::FormatStyle::AlignOperands
OperandAlignmentStyle AlignOperands
If true, horizontally align operands of binary and ternary expressions.
Definition: Format.h:370
clang::format::startsSegmentOfBuilderTypeCall
static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok)
Definition: ContinuationIndenter.cpp:117
clang::format::LT_ImportStatement
@ LT_ImportStatement
Definition: TokenAnnotator.h:26
clang::format::FormatStyle::BinPackArguments
bool BinPackArguments
If false, a function call's arguments will either be all on the same line or will have one line each.
Definition: Format.h:828
clang::format::FormatStyle::ObjCBlockIndentWidth
unsigned ObjCBlockIndentWidth
The number of characters to use for indentation of ObjC blocks.
Definition: Format.h:2768
clang::format::ContinuationIndenter::getInitialState
LineState getInitialState(unsigned FirstIndent, unsigned FirstStartColumn, const AnnotatedLine *Line, bool DryRun)
Get the initial state, i.e.
Definition: ContinuationIndenter.cpp:236
clang::format::FormatToken::getPreviousNonComment
LLVM_NODISCARD FormatToken * getPreviousNonComment() const
Returns the previous token ignoring comments.
Definition: FormatToken.h:696
clang::format::FormatToken::isTrailingComment
bool isTrailingComment() const
Definition: FormatToken.h:632
clang::format::RawStringFormatStyleManager::RawStringFormatStyleManager
RawStringFormatStyleManager(const FormatStyle &CodeStyle)
Definition: ContinuationIndenter.cpp:186
clang::format::FormatStyle::PenaltyBreakFirstLessLess
unsigned PenaltyBreakFirstLessLess
The penalty for breaking before the first <<.
Definition: Format.h:2818
clang::format::getEnclosingFunctionName
static StringRef getEnclosingFunctionName(const FormatToken &Current)
Definition: ContinuationIndenter.cpp:2027
clang::format::ContinuationIndenter::getColumnLimit
unsigned getColumnLimit(const LineState &State) const
Get the column limit for this line.
Definition: ContinuationIndenter.cpp:2532
clang::format::FormatStyle::BreakBeforeBraces
BraceBreakingStyle BreakBeforeBraces
The brace breaking style to use.
Definition: Format.h:1363
clang::format::getLLVMStyle
FormatStyle getLLVMStyle(FormatStyle::LanguageKind Language=FormatStyle::LanguageKind::LK_Cpp)
Returns a format style complying with the LLVM coding standards: http://llvm.org/docs/CodingStandards...
Definition: Format.cpp:1175
clang::format::FormatStyle::ColumnLimit
unsigned ColumnLimit
The column limit.
Definition: Format.h:1742
clang::format::FormatStyle::isJson
bool isJson() const
Definition: Format.h:2600
clang::format::FormatStyle::PenaltyExcessCharacter
unsigned PenaltyExcessCharacter
The penalty for each character outside of the column limit.
Definition: Format.h:2834
clang::format::FormatStyle::BAS_AlwaysBreak
@ BAS_AlwaysBreak
Always break after an open bracket, if the parameters don't fit on a single line, e....
Definition: Format.h:84
clang::format::BK_Block
@ BK_Block
Definition: FormatToken.h:153
WhitespaceManager.h
clang::format::ParenState
Definition: ContinuationIndenter.h:201
Line
const AnnotatedLine * Line
Definition: UsingDeclarationsSorter.cpp:68
clang::format::FormatStyle::TabWidth
unsigned TabWidth
The number of columns used for tab stops.
Definition: Format.h:3821
clang::format::FormatStyle::BILS_AfterColon
@ BILS_AfterColon
Break inheritance list after the colon and commas.
Definition: Format.h:1848
clang::format::PPK_OnePerLine
@ PPK_OnePerLine
Definition: FormatToken.h:156
clang::format::FormatStyle::isJavaScript
bool isJavaScript() const
Definition: Format.h:2601
clang::format::FormatStyle::BraceWrapping
BraceWrappingFlags BraceWrapping
Control of individual brace wrapping cases.
Definition: Format.h:1641
clang::format::FormatStyle::UT_Never
@ UT_Never
Never use tab.
Definition: Format.h:3826
clang::format::FormatStyle::BreakConstructorInitializers
BreakConstructorInitializersStyle BreakConstructorInitializers
The break constructor initializers style to use.
Definition: Format.h:1710
clang::format::FormatStyle::ContinuationIndentWidth
unsigned ContinuationIndentWidth
Indent width for line continuations.
Definition: Format.h:1905
clang::Indent
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition: JsonSupport.h:21
clang::format::FormatStyle::isCSharp
bool isCSharp() const
Definition: Format.h:2599
P
StringRef P
Definition: ASTMatchersInternal.cpp:563
clang::format::RawStringFormatStyleManager::getDelimiterStyle
llvm::Optional< FormatStyle > getDelimiterStyle(StringRef Delimiter) const
Definition: ContinuationIndenter.cpp:209
clang::format::FormatStyle::BCIS_AfterColon
@ BCIS_AfterColon
Break constructor initializers after the colon and commas.
Definition: Format.h:1705
clang::format::LineType
LineType
Definition: TokenAnnotator.h:24
clang::format::FormatStyle::RCPS_SingleLine
@ RCPS_SingleLine
Try to put everything in the same line if possible.
Definition: Format.h:3115
clang::Language
Language
The language for the input, used to select and validate the language standard and possible actions.
Definition: LangStandard.h:23
clang::format::FormatStyle::Language
LanguageKind Language
Language, this format style is targeted at.
Definition: Format.h:2606
clang::format::FormatStyle::LK_Java
@ LK_Java
Should be used for Java.
Definition: Format.h:2578
LongestObjCSelectorName
unsigned LongestObjCSelectorName
Definition: TokenAnnotator.cpp:1548
clang::format::LT_ObjCDecl
@ LT_ObjCDecl
Definition: TokenAnnotator.h:27
clang::format::RawStringFormatStyleManager::getEnclosingFunctionStyle
llvm::Optional< FormatStyle > getEnclosingFunctionStyle(StringRef EnclosingFunction) const
Definition: ContinuationIndenter.cpp:217
clang::format::getLengthToMatchingParen
static unsigned getLengthToMatchingParen(const FormatToken &Tok, const std::vector< ParenState > &Stack)
Definition: ContinuationIndenter.cpp:39
clang::format::internal::reformat
std::pair< tooling::Replacements, unsigned > reformat(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, unsigned FirstStartColumn, unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName, FormattingAttemptStatus *Status)
Reformats the given Ranges in the code fragment Code.
Definition: Format.cpp:3206
clang::format::AdditionalKeywords::kw_dollar
IdentifierInfo * kw_dollar
Definition: FormatToken.h:1339
clang::format::FormatToken::is
bool is(tok::TokenKind Kind) const
Definition: FormatToken.h:500
clang::format::FormatStyle::AlignAfterOpenBracket
BracketAlignmentStyle AlignAfterOpenBracket
If true, horizontally aligns arguments after an open bracket.
Definition: Format.h:105
clang::format::FormatStyle::BBCDS_Always
@ BBCDS_Always
Always break before concept, putting it in the line after the template declaration.
Definition: Format.h:1660
clang::format::RawStringFormatStyleManager::EnclosingFunctionStyle
llvm::StringMap< FormatStyle > EnclosingFunctionStyle
Definition: ContinuationIndenter.h:40
State
LineState State
Definition: UnwrappedLineFormatter.cpp:1126
DwarfFissionKind::Split
@ Split
clang::format::FormatStyle::ObjCBreakBeforeNestedBlockParam
bool ObjCBreakBeforeNestedBlockParam
Break parameters list into lines when there is nested block parameters in a function call.
Definition: Format.h:2797
clang::format::FormatStyle::BinPackParameters
bool BinPackParameters
If false, a function declaration's or function definition's parameters will either all be on the same...
Definition: Format.h:873
clang::format::opensProtoMessageField
static bool opensProtoMessageField(const FormatToken &LessTok, const FormatStyle &Style)
Definition: ContinuationIndenter.cpp:139
clang::format::FormatStyle::RTBS_None
@ RTBS_None
Break after return type automatically.
Definition: Format.h:669
clang::format::FormatStyle::RCPS_OwnLine
@ RCPS_OwnLine
Always put the requires clause on its own line.
Definition: Format.h:3060
clang::format::AdditionalKeywords::kw_function
IdentifierInfo * kw_function
Definition: FormatToken.h:1291
clang::format::FormatStyle::AllowAllArgumentsOnNextLine
bool AllowAllArgumentsOnNextLine
If a function call or braced initializer list doesn't fit on a line, allow putting all arguments onto...
Definition: Format.h:396
clang::format::ContinuationIndenter::canBreak
bool canBreak(const LineState &State)
Returns true, if a line break after State is allowed.
Definition: ContinuationIndenter.cpp:279
clang::prec::Relational
@ Relational
Definition: OperatorPrecedence.h:37
clang::format::FormatStyle::OAS_AlignAfterOperator
@ OAS_AlignAfterOperator
Horizontally align operands of binary and ternary expressions.
Definition: Format.h:364
clang::format::WhitespaceManager::useCRLF
bool useCRLF() const
Definition: WhitespaceManager.h:46
std
Definition: Format.h:4303
clang::format::FormatToken::NextOperator
FormatToken * NextOperator
If this is an operator (or "."/"->") in a sequence of operators with the same precedence,...
Definition: FormatToken.h:463
clang::format::FormatStyle::ConstructorInitializerIndentWidth
unsigned ConstructorInitializerIndentWidth
This option is deprecated.
Definition: Format.h:1894
clang::format::FormatStyle::GetLanguageStyle
llvm::Optional< FormatStyle > GetLanguageStyle(LanguageKind Language) const
Definition: Format.cpp:1827
clang
Definition: CalledOnceCheck.h:17
Text
StringRef Text
Definition: Format.cpp:2573
clang::format::FormatStyle::RawStringFormats
std::vector< RawStringFormat > RawStringFormats
Defines hints for detecting supported languages code blocks in raw strings.
Definition: Format.h:2942
clang::format::RawStringFormatStyleManager::DelimiterStyle
llvm::StringMap< FormatStyle > DelimiterStyle
Definition: ContinuationIndenter.h:39
clang::format::FormatStyle::AllowShortFunctionsOnASingleLine
ShortFunctionStyle AllowShortFunctionsOnASingleLine
Dependent on the value, int f() { return 0; } can be put on a single line.
Definition: Format.h:533
clang::format::FormatStyle::BPS_Always
@ BPS_Always
Always bin-pack parameters.
Definition: Format.h:881
clang::format::ContinuationIndenter::addTokenToState
unsigned addTokenToState(LineState &State, bool Newline, bool DryRun, unsigned ExtraSpaces=0)
Appends the next token to State and updates information necessary for indentation.
Definition: ContinuationIndenter.cpp:590
clang::format::FormatStyle::BS_Whitesmiths
@ BS_Whitesmiths
Like Allman but always indent braces and line up code with braces.
Definition: Format.h:1246
clang::format::switchesFormatting
bool switchesFormatting(const FormatToken &Token)
Checks if Token switches formatting, like /* clang-format off *‍/.
Definition: BreakableToken.cpp:219
clang::format::FormatStyle::BreakInheritanceList
BreakInheritanceListStyle BreakInheritanceList
The inheritance list style to use.
Definition: Format.h:1860
clang::format::FormatStyle::LanguageKind
LanguageKind
Supported languages.
Definition: Format.h:2570
clang::format::FormatStyle::isCpp
bool isCpp() const
Definition: Format.h:2598
clang::prec::Equality
@ Equality
Definition: OperatorPrecedence.h:36
clang::format::FormatToken::ColumnWidth
unsigned ColumnWidth
The width of the non-whitespace parts of the token (or its first line for multi-line tokens) in colum...
Definition: FormatToken.h:384
clang::format::ContinuationIndenter::mustBreak
bool mustBreak(const LineState &State)
Returns true, if a line break after State is mandatory.
Definition: ContinuationIndenter.cpp:337
clang::format::FormatStyle::PCIS_BinPack
@ PCIS_BinPack
Bin-pack constructor initializers.
Definition: Format.h:2089
clang::format::encoding::columnWidthWithTabs
unsigned columnWidthWithTabs(StringRef Text, unsigned StartColumn, unsigned TabWidth, Encoding Encoding)
Returns the number of columns required to display the Text, starting from the StartColumn on a termin...
Definition: Encoding.h:61
clang::format::shouldIndentWrappedSelectorName
static bool shouldIndentWrappedSelectorName(const FormatStyle &Style, LineType LineType)
Definition: ContinuationIndenter.cpp:32
FormatToken.h
clang::format::FormatStyle::BAS_DontAlign
@ BAS_DontAlign
Don't align, instead use ContinuationIndentWidth, e.g.
Definition: Format.h:77
OperatorPrecedence.h
clang::format::FormatStyle::IndentRequiresClause
bool IndentRequiresClause
Indent the requires clause in a template.
Definition: Format.h:2414
clang::format::getLastLineEndColumn
static unsigned getLastLineEndColumn(StringRef Text, unsigned StartColumn, unsigned TabWidth, encoding::Encoding Encoding)
Definition: ContinuationIndenter.cpp:1794
ContinuationIndenter.h
clang::format::FormatStyle::PackConstructorInitializers
PackConstructorInitializersStyle PackConstructorInitializers
The pack constructor initializers style to use.
Definition: Format.h:2119
clang::format::FormatToken::TotalLength
unsigned TotalLength
The total length of the unwrapped line up to and including this token.
Definition: FormatToken.h:406
clang::format::FormatStyle::UseTab
UseTabStyle UseTab
The way to use tab characters in the resulting file.
Definition: Format.h:3847
clang::format::FormatStyle::IndentPPDirectives
PPDirectiveIndentStyle IndentPPDirectives
The preprocessor directive indenting style to use.
Definition: Format.h:2352
Previous
StateNode * Previous
Definition: UnwrappedLineFormatter.cpp:1128
clang::format::PPK_Inconclusive
@ PPK_Inconclusive
Definition: FormatToken.h:156
clang::format::FormatToken::Next
FormatToken * Next
The next token in the unwrapped line.
Definition: FormatToken.h:472
clang::tooling::applyAllReplacements
bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite)
Apply all replacements in Replaces to the Rewriter Rewrite.
Definition: Replacement.cpp:567
clang::format::LT_ObjCMethodDecl
@ LT_ObjCMethodDecl
Definition: TokenAnnotator.h:28
clang::format::FormatStyle::BreakBeforeTernaryOperators
bool BreakBeforeTernaryOperators
If true, ternary operators will be placed after line breaks.
Definition: Format.h:1680
clang::format::FormatStyle::PenaltyIndentedWhitespace
unsigned PenaltyIndentedWhitespace
Penalty for each character of whitespace indentation (counted relative to leading non-whitespace colu...
Definition: Format.h:2844
clang::format::getRawStringDelimiter
static llvm::Optional< StringRef > getRawStringDelimiter(StringRef TokenText)
Definition: ContinuationIndenter.cpp:152
clang::format::BreakableToken::Split
std::pair< StringRef::size_type, unsigned > Split
Contains starting character index and length of split.
Definition: BreakableToken.h:92
clang::format::FormatStyle::RCPS_WithFollowing
@ RCPS_WithFollowing
Try to put the requires clause together with the class or function declaration.
Definition: Format.h:3091
clang::format::startsNextParameter
static bool startsNextParameter(const FormatToken &Current, const FormatStyle &Style)
Definition: ContinuationIndenter.cpp:122
clang::format::FormatToken::MatchingParen
FormatToken * MatchingParen
If this is a bracket, this points to the matching one.
Definition: FormatToken.h:466
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::LK_ObjC
@ LK_ObjC
Should be used for Objective-C, Objective-C++.
Definition: Format.h:2584
clang::format::FormatStyle::BPS_Auto
@ BPS_Auto
Automatically determine parameter bin-packing behavior.
Definition: Format.h:879
clang::format::FormatStyle::BreakBeforeConceptDeclarations
BreakBeforeConceptDeclarationsStyle BreakBeforeConceptDeclarations
The concept declaration style to use.
Definition: Format.h:1665
clang::format::FormatStyle::SFS_All
@ SFS_All
Merge all functions fitting on a single line.
Definition: Format.h:527
clang::prec::Spaceship
@ Spaceship
Definition: OperatorPrecedence.h:38
clang::format::getLengthToNextOperator
static unsigned getLengthToNextOperator(const FormatToken &Tok)
Definition: ContinuationIndenter.cpp:109
clang::format::FormatStyle::PenaltyBreakComment
unsigned PenaltyBreakComment
The penalty for each line break introduced inside a comment.
Definition: Format.h:2814
clang::format::getCanonicalRawStringDelimiter
static StringRef getCanonicalRawStringDelimiter(const FormatStyle &Style, FormatStyle::LanguageKind Language)
Definition: ContinuationIndenter.cpp:178