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