Coverage Report

Created: 2022-07-16 07:03

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