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