Coverage Report

Created: 2024-01-17 10:31

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