llvm-project

Форк
0
/
ContinuationIndenter.cpp 
2848 строк · 122.3 Кб
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
                                            LineType LineType) {
36
  return Style.IndentWrappedFunctionNames || LineType == LT_ObjCMethodDecl;
37
}
38

39
// Returns true if a binary operator following \p Tok should be unindented when
40
// the style permits it.
41
static bool shouldUnindentNextOperator(const FormatToken &Tok) {
42
  const FormatToken *Previous = Tok.getPreviousNonComment();
43
  return Previous && (Previous->getPrecedence() == prec::Assignment ||
44
                      Previous->isOneOf(tok::kw_return, TT_RequiresClause));
45
}
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
                                         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
  if (!Tok.MatchingParen)
90
    return 0;
91
  FormatToken *End = Tok.MatchingParen;
92
  // Maintains a stack level corresponding to the current End token.
93
  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
  auto FindParenState = [&](const FormatToken *LBrace) -> const ParenState * {
99
    while (MatchingStackIndex >= 0 && Stack[MatchingStackIndex].Tok != LBrace)
100
      --MatchingStackIndex;
101
    return MatchingStackIndex >= 0 ? &Stack[MatchingStackIndex] : nullptr;
102
  };
103
  for (; End->Next; End = End->Next) {
104
    if (End->Next->CanBreakBefore)
105
      break;
106
    if (!End->Next->closesScope())
107
      continue;
108
    if (End->Next->MatchingParen &&
109
        End->Next->MatchingParen->isOneOf(
110
            tok::l_brace, TT_ArrayInitializerLSquare, tok::less)) {
111
      const ParenState *State = FindParenState(End->Next->MatchingParen);
112
      if (State && State->BreakBeforeClosingBrace)
113
        break;
114
    }
115
  }
116
  return End->TotalLength - Tok.TotalLength + 1;
117
}
118

119
static unsigned getLengthToNextOperator(const FormatToken &Tok) {
120
  if (!Tok.NextOperator)
121
    return 0;
122
  return Tok.NextOperator->TotalLength - Tok.TotalLength;
123
}
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
static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) {
128
  return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
129
}
130

131
// Returns \c true if \c Current starts a new parameter.
132
static bool startsNextParameter(const FormatToken &Current,
133
                                const FormatStyle &Style) {
134
  const FormatToken &Previous = *Current.Previous;
135
  if (Current.is(TT_CtorInitializerComma) &&
136
      Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) {
137
    return true;
138
  }
139
  if (Style.Language == FormatStyle::LK_Proto && Current.is(TT_SelectorName))
140
    return true;
141
  return Previous.is(tok::comma) && !Current.isTrailingComment() &&
142
         ((Previous.isNot(TT_CtorInitializerComma) ||
143
           Style.BreakConstructorInitializers !=
144
               FormatStyle::BCIS_BeforeComma) &&
145
          (Previous.isNot(TT_InheritanceComma) ||
146
           Style.BreakInheritanceList != FormatStyle::BILS_BeforeComma));
147
}
148

149
static bool opensProtoMessageField(const FormatToken &LessTok,
150
                                   const FormatStyle &Style) {
151
  if (LessTok.isNot(tok::less))
152
    return false;
153
  return Style.Language == FormatStyle::LK_TextProto ||
154
         (Style.Language == FormatStyle::LK_Proto &&
155
          (LessTok.NestingLevel > 0 ||
156
           (LessTok.Previous && LessTok.Previous->is(tok::equal))));
157
}
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
static std::optional<StringRef> getRawStringDelimiter(StringRef TokenText) {
163
  if (TokenText.size() < 5 // The smallest raw string possible is 'R"()"'.
164
      || !TokenText.starts_with("R\"") || !TokenText.ends_with("\"")) {
165
    return std::nullopt;
166
  }
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
  size_t LParenPos = TokenText.substr(0, 19).find_first_of('(');
172
  if (LParenPos == StringRef::npos)
173
    return std::nullopt;
174
  StringRef Delimiter = TokenText.substr(2, LParenPos - 2);
175

176
  // Check that the string ends in ')Delimiter"'.
177
  size_t RParenPos = TokenText.size() - Delimiter.size() - 2;
178
  if (TokenText[RParenPos] != ')')
179
    return std::nullopt;
180
  if (!TokenText.substr(RParenPos + 1).starts_with(Delimiter))
181
    return std::nullopt;
182
  return Delimiter;
183
}
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
                               FormatStyle::LanguageKind Language) {
190
  for (const auto &Format : Style.RawStringFormats)
191
    if (Format.Language == Language)
192
      return StringRef(Format.CanonicalDelimiter);
193
  return "";
194
}
195

196
RawStringFormatStyleManager::RawStringFormatStyleManager(
197
    const FormatStyle &CodeStyle) {
198
  for (const auto &RawStringFormat : CodeStyle.RawStringFormats) {
199
    std::optional<FormatStyle> LanguageStyle =
200
        CodeStyle.GetLanguageStyle(RawStringFormat.Language);
201
    if (!LanguageStyle) {
202
      FormatStyle PredefinedStyle;
203
      if (!getPredefinedStyle(RawStringFormat.BasedOnStyle,
204
                              RawStringFormat.Language, &PredefinedStyle)) {
205
        PredefinedStyle = getLLVMStyle();
206
        PredefinedStyle.Language = RawStringFormat.Language;
207
      }
208
      LanguageStyle = PredefinedStyle;
209
    }
210
    LanguageStyle->ColumnLimit = CodeStyle.ColumnLimit;
211
    for (StringRef Delimiter : RawStringFormat.Delimiters)
212
      DelimiterStyle.insert({Delimiter, *LanguageStyle});
213
    for (StringRef EnclosingFunction : RawStringFormat.EnclosingFunctions)
214
      EnclosingFunctionStyle.insert({EnclosingFunction, *LanguageStyle});
215
  }
216
}
217

218
std::optional<FormatStyle>
219
RawStringFormatStyleManager::getDelimiterStyle(StringRef Delimiter) const {
220
  auto It = DelimiterStyle.find(Delimiter);
221
  if (It == DelimiterStyle.end())
222
    return std::nullopt;
223
  return It->second;
224
}
225

226
std::optional<FormatStyle>
227
RawStringFormatStyleManager::getEnclosingFunctionStyle(
228
    StringRef EnclosingFunction) const {
229
  auto It = EnclosingFunctionStyle.find(EnclosingFunction);
230
  if (It == EnclosingFunctionStyle.end())
231
    return std::nullopt;
232
  return It->second;
233
}
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
      CommentPragmasRegex(Style.CommentPragmas), RawStringFormats(Style) {}
245

246
LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
247
                                                unsigned FirstStartColumn,
248
                                                const AnnotatedLine *Line,
249
                                                bool DryRun) {
250
  LineState State;
251
  State.FirstIndent = FirstIndent;
252
  if (FirstStartColumn && Line->First->NewlinesBefore == 0)
253
    State.Column = FirstStartColumn;
254
  else
255
    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
  if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash &&
260
      (Line->Type == LT_PreprocessorDirective ||
261
       Line->Type == LT_ImportStatement)) {
262
    State.Column = 0;
263
  }
264
  State.Line = Line;
265
  State.NextToken = Line->First;
266
  State.Stack.push_back(ParenState(/*Tok=*/nullptr, FirstIndent, FirstIndent,
267
                                   /*AvoidBinPacking=*/false,
268
                                   /*NoLineBreak=*/false));
269
  State.NoContinuation = false;
270
  State.StartOfStringLiteral = 0;
271
  State.NoLineBreak = false;
272
  State.StartOfLineLevel = 0;
273
  State.LowestLevelOnLine = 0;
274
  State.IgnoreStackForComparison = false;
275

276
  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
    auto &CurrentState = State.Stack.back();
280
    CurrentState.AvoidBinPacking = true;
281
    CurrentState.BreakBeforeParameter = true;
282
    CurrentState.AlignColons = false;
283
  }
284

285
  // The first token has already been indented and thus consumed.
286
  moveStateToNextToken(State, DryRun, /*Newline=*/false);
287
  return State;
288
}
289

290
bool ContinuationIndenter::canBreak(const LineState &State) {
291
  const FormatToken &Current = *State.NextToken;
292
  const FormatToken &Previous = *Current.Previous;
293
  const auto &CurrentState = State.Stack.back();
294
  assert(&Previous == Current.Previous);
295
  if (!Current.CanBreakBefore && !(CurrentState.BreakBeforeClosingBrace &&
296
                                   Current.closesBlockOrBlockTypeList(Style))) {
297
    return false;
298
  }
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
  if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
302
      Previous.isNot(TT_DictLiteral) && Previous.is(BK_BracedInit) &&
303
      Previous.Previous &&
304
      Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma)) {
305
    return false;
306
  }
307
  // This prevents breaks like:
308
  //   ...
309
  //   SomeParameter, OtherParameter).DoSomething(
310
  //   ...
311
  // As they hide "DoSomething" and are generally bad for readability.
312
  if (Previous.opensScope() && Previous.isNot(tok::l_brace) &&
313
      State.LowestLevelOnLine < State.StartOfLineLevel &&
314
      State.LowestLevelOnLine < Current.NestingLevel) {
315
    return false;
316
  }
317
  if (Current.isMemberAccess() && CurrentState.ContainsUnwrappedBuilder)
318
    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
  if (Previous.is(tok::l_brace) && State.Stack.size() > 1 &&
323
      State.Stack[State.Stack.size() - 2].NestedBlockInlined &&
324
      State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks &&
325
      Style.LambdaBodyIndentation == FormatStyle::LBI_Signature) {
326
    return false;
327
  }
328

329
  // Don't break after very short return types (e.g. "void") as that is often
330
  // unexpected.
331
  if (Current.is(TT_FunctionDeclarationName)) {
332
    if (Style.BreakAfterReturnType == FormatStyle::RTBS_None &&
333
        State.Column < 6) {
334
      return false;
335
    }
336

337
    if (Style.BreakAfterReturnType == FormatStyle::RTBS_ExceptShortType) {
338
      assert(State.Column >= State.FirstIndent);
339
      if (State.Column - State.FirstIndent < 6)
340
        return false;
341
    }
342
  }
343

344
  // If binary operators are moved to the next line (including commas for some
345
  // styles of constructor initializers), that's always ok.
346
  if (!Current.isOneOf(TT_BinaryOperator, tok::comma) &&
347
      // Allow breaking opening brace of lambdas (when passed as function
348
      // arguments) to a new line when BeforeLambdaBody brace wrapping is
349
      // enabled.
350
      (!Style.BraceWrapping.BeforeLambdaBody ||
351
       Current.isNot(TT_LambdaLBrace)) &&
352
      CurrentState.NoLineBreakInOperand) {
353
    return false;
354
  }
355

356
  if (Previous.is(tok::l_square) && Previous.is(TT_ObjCMethodExpr))
357
    return false;
358

359
  if (Current.is(TT_ConditionalExpr) && Previous.is(tok::r_paren) &&
360
      Previous.MatchingParen && Previous.MatchingParen->Previous &&
361
      Previous.MatchingParen->Previous->MatchingParen &&
362
      Previous.MatchingParen->Previous->MatchingParen->is(TT_LambdaLBrace)) {
363
    // We have a lambda within a conditional expression, allow breaking here.
364
    assert(Previous.MatchingParen->Previous->is(tok::r_brace));
365
    return true;
366
  }
367

368
  return !State.NoLineBreak && !CurrentState.NoLineBreak;
369
}
370

371
bool ContinuationIndenter::mustBreak(const LineState &State) {
372
  const FormatToken &Current = *State.NextToken;
373
  const FormatToken &Previous = *Current.Previous;
374
  const auto &CurrentState = State.Stack.back();
375
  if (Style.BraceWrapping.BeforeLambdaBody && Current.CanBreakBefore &&
376
      Current.is(TT_LambdaLBrace) && Previous.isNot(TT_LineComment)) {
377
    auto LambdaBodyLength = getLengthToMatchingParen(Current, State.Stack);
378
    return LambdaBodyLength > getColumnLimit(State);
379
  }
380
  if (Current.MustBreakBefore ||
381
      (Current.is(TT_InlineASMColon) &&
382
       (Style.BreakBeforeInlineASMColon == FormatStyle::BBIAS_Always ||
383
        (Style.BreakBeforeInlineASMColon == FormatStyle::BBIAS_OnlyMultiline &&
384
         Style.ColumnLimit > 0)))) {
385
    return true;
386
  }
387
  if (CurrentState.BreakBeforeClosingBrace &&
388
      (Current.closesBlockOrBlockTypeList(Style) ||
389
       (Current.is(tok::r_brace) &&
390
        Current.isBlockIndentedInitRBrace(Style)))) {
391
    return true;
392
  }
393
  if (CurrentState.BreakBeforeClosingParen && Current.is(tok::r_paren))
394
    return true;
395
  if (Style.Language == FormatStyle::LK_ObjC &&
396
      Style.ObjCBreakBeforeNestedBlockParam &&
397
      Current.ObjCSelectorNameParts > 1 &&
398
      Current.startsSequence(TT_SelectorName, tok::colon, tok::caret)) {
399
    return true;
400
  }
401
  // Avoid producing inconsistent states by requiring breaks where they are not
402
  // permitted for C# generic type constraints.
403
  if (CurrentState.IsCSharpGenericTypeConstraint &&
404
      Previous.isNot(TT_CSharpGenericTypeConstraintComma)) {
405
    return false;
406
  }
407
  if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
408
       (Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&
409
        State.Line->First->isNot(TT_AttributeSquare) && Style.isCpp() &&
410
        // FIXME: This is a temporary workaround for the case where clang-format
411
        // sets BreakBeforeParameter to avoid bin packing and this creates a
412
        // completely unnecessary line break after a template type that isn't
413
        // line-wrapped.
414
        (Previous.NestingLevel == 1 || Style.BinPackParameters)) ||
415
       (Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
416
        Previous.isNot(tok::question)) ||
417
       (!Style.BreakBeforeTernaryOperators &&
418
        Previous.is(TT_ConditionalExpr))) &&
419
      CurrentState.BreakBeforeParameter && !Current.isTrailingComment() &&
420
      !Current.isOneOf(tok::r_paren, tok::r_brace)) {
421
    return true;
422
  }
423
  if (CurrentState.IsChainedConditional &&
424
      ((Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
425
        Current.is(tok::colon)) ||
426
       (!Style.BreakBeforeTernaryOperators && Previous.is(TT_ConditionalExpr) &&
427
        Previous.is(tok::colon)))) {
428
    return true;
429
  }
430
  if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) ||
431
       (Previous.is(TT_ArrayInitializerLSquare) &&
432
        Previous.ParameterCount > 1) ||
433
       opensProtoMessageField(Previous, Style)) &&
434
      Style.ColumnLimit > 0 &&
435
      getLengthToMatchingParen(Previous, State.Stack) + State.Column - 1 >
436
          getColumnLimit(State)) {
437
    return true;
438
  }
439

440
  const FormatToken &BreakConstructorInitializersToken =
441
      Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon
442
          ? Previous
443
          : Current;
444
  if (BreakConstructorInitializersToken.is(TT_CtorInitializerColon) &&
445
      (State.Column + State.Line->Last->TotalLength - Previous.TotalLength >
446
           getColumnLimit(State) ||
447
       CurrentState.BreakBeforeParameter) &&
448
      (!Current.isTrailingComment() || Current.NewlinesBefore > 0) &&
449
      (Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All ||
450
       Style.BreakConstructorInitializers != FormatStyle::BCIS_BeforeColon ||
451
       Style.ColumnLimit != 0)) {
452
    return true;
453
  }
454

455
  if (Current.is(TT_ObjCMethodExpr) && Previous.isNot(TT_SelectorName) &&
456
      State.Line->startsWith(TT_ObjCMethodSpecifier)) {
457
    return true;
458
  }
459
  if (Current.is(TT_SelectorName) && Previous.isNot(tok::at) &&
460
      CurrentState.ObjCSelectorNameFound && CurrentState.BreakBeforeParameter &&
461
      (Style.ObjCBreakBeforeNestedBlockParam ||
462
       !Current.startsSequence(TT_SelectorName, tok::colon, tok::caret))) {
463
    return true;
464
  }
465

466
  unsigned NewLineColumn = getNewLineColumn(State);
467
  if (Current.isMemberAccess() && Style.ColumnLimit != 0 &&
468
      State.Column + getLengthToNextOperator(Current) > Style.ColumnLimit &&
469
      (State.Column > NewLineColumn ||
470
       Current.NestingLevel < State.StartOfLineLevel)) {
471
    return true;
472
  }
473

474
  if (startsSegmentOfBuilderTypeCall(Current) &&
475
      (CurrentState.CallContinuation != 0 ||
476
       CurrentState.BreakBeforeParameter) &&
477
      // JavaScript is treated different here as there is a frequent pattern:
478
      //   SomeFunction(function() {
479
      //     ...
480
      //   }.bind(...));
481
      // FIXME: We should find a more generic solution to this problem.
482
      !(State.Column <= NewLineColumn && Style.isJavaScript()) &&
483
      !(Previous.closesScopeAfterBlock() && State.Column <= NewLineColumn)) {
484
    return true;
485
  }
486

487
  // If the template declaration spans multiple lines, force wrap before the
488
  // function/class declaration.
489
  if (Previous.ClosesTemplateDeclaration && CurrentState.BreakBeforeParameter &&
490
      Current.CanBreakBefore) {
491
    return true;
492
  }
493

494
  if (State.Line->First->isNot(tok::kw_enum) && State.Column <= NewLineColumn)
495
    return false;
496

497
  if (Style.AlwaysBreakBeforeMultilineStrings &&
498
      (NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth ||
499
       Previous.is(tok::comma) || Current.NestingLevel < 2) &&
500
      !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at,
501
                        Keywords.kw_dollar) &&
502
      !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) &&
503
      nextIsMultilineString(State)) {
504
    return true;
505
  }
506

507
  // Using CanBreakBefore here and below takes care of the decision whether the
508
  // current style uses wrapping before or after operators for the given
509
  // operator.
510
  if (Previous.is(TT_BinaryOperator) && Current.CanBreakBefore) {
511
    const auto PreviousPrecedence = Previous.getPrecedence();
512
    if (PreviousPrecedence != prec::Assignment &&
513
        CurrentState.BreakBeforeParameter && !Current.isTrailingComment()) {
514
      const bool LHSIsBinaryExpr =
515
          Previous.Previous && Previous.Previous->EndsBinaryExpression;
516
      if (LHSIsBinaryExpr)
517
        return true;
518
      // If we need to break somewhere inside the LHS of a binary expression, we
519
      // should also break after the operator. Otherwise, the formatting would
520
      // hide the operator precedence, e.g. in:
521
      //   if (aaaaaaaaaaaaaa ==
522
      //           bbbbbbbbbbbbbb && c) {..
523
      // For comparisons, we only apply this rule, if the LHS is a binary
524
      // expression itself as otherwise, the line breaks seem superfluous.
525
      // We need special cases for ">>" which we have split into two ">" while
526
      // lexing in order to make template parsing easier.
527
      const bool IsComparison =
528
          (PreviousPrecedence == prec::Relational ||
529
           PreviousPrecedence == prec::Equality ||
530
           PreviousPrecedence == prec::Spaceship) &&
531
          Previous.Previous &&
532
          Previous.Previous->isNot(TT_BinaryOperator); // For >>.
533
      if (!IsComparison)
534
        return true;
535
    }
536
  } else if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore &&
537
             CurrentState.BreakBeforeParameter) {
538
    return true;
539
  }
540

541
  // Same as above, but for the first "<<" operator.
542
  if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) &&
543
      CurrentState.BreakBeforeParameter && CurrentState.FirstLessLess == 0) {
544
    return true;
545
  }
546

547
  if (Current.NestingLevel == 0 && !Current.isTrailingComment()) {
548
    // Always break after "template <...>"(*) and leading annotations. This is
549
    // only for cases where the entire line does not fit on a single line as a
550
    // different LineFormatter would be used otherwise.
551
    // *: Except when another option interferes with that, like concepts.
552
    if (Previous.ClosesTemplateDeclaration) {
553
      if (Current.is(tok::kw_concept)) {
554
        switch (Style.BreakBeforeConceptDeclarations) {
555
        case FormatStyle::BBCDS_Allowed:
556
          break;
557
        case FormatStyle::BBCDS_Always:
558
          return true;
559
        case FormatStyle::BBCDS_Never:
560
          return false;
561
        }
562
      }
563
      if (Current.is(TT_RequiresClause)) {
564
        switch (Style.RequiresClausePosition) {
565
        case FormatStyle::RCPS_SingleLine:
566
        case FormatStyle::RCPS_WithPreceding:
567
          return false;
568
        default:
569
          return true;
570
        }
571
      }
572
      return Style.BreakTemplateDeclarations != FormatStyle::BTDS_No &&
573
             (Style.BreakTemplateDeclarations != FormatStyle::BTDS_Leave ||
574
              Current.NewlinesBefore > 0);
575
    }
576
    if (Previous.is(TT_FunctionAnnotationRParen) &&
577
        State.Line->Type != LT_PreprocessorDirective) {
578
      return true;
579
    }
580
    if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) &&
581
        Current.isNot(TT_LeadingJavaAnnotation)) {
582
      return true;
583
    }
584
  }
585

586
  if (Style.isJavaScript() && Previous.is(tok::r_paren) &&
587
      Previous.is(TT_JavaAnnotation)) {
588
    // Break after the closing parenthesis of TypeScript decorators before
589
    // functions, getters and setters.
590
    static const llvm::StringSet<> BreakBeforeDecoratedTokens = {"get", "set",
591
                                                                 "function"};
592
    if (BreakBeforeDecoratedTokens.contains(Current.TokenText))
593
      return true;
594
  }
595

596
  if (Current.is(TT_FunctionDeclarationName) &&
597
      !State.Line->ReturnTypeWrapped &&
598
      // Don't break before a C# function when no break after return type.
599
      (!Style.isCSharp() ||
600
       Style.BreakAfterReturnType > FormatStyle::RTBS_ExceptShortType) &&
601
      // Don't always break between a JavaScript `function` and the function
602
      // name.
603
      !Style.isJavaScript() && Previous.isNot(tok::kw_template) &&
604
      CurrentState.BreakBeforeParameter) {
605
    return true;
606
  }
607

608
  // The following could be precomputed as they do not depend on the state.
609
  // However, as they should take effect only if the UnwrappedLine does not fit
610
  // into the ColumnLimit, they are checked here in the ContinuationIndenter.
611
  if (Style.ColumnLimit != 0 && Previous.is(BK_Block) &&
612
      Previous.is(tok::l_brace) &&
613
      !Current.isOneOf(tok::r_brace, tok::comment)) {
614
    return true;
615
  }
616

617
  if (Current.is(tok::lessless) &&
618
      ((Previous.is(tok::identifier) && Previous.TokenText == "endl") ||
619
       (Previous.Tok.isLiteral() && (Previous.TokenText.ends_with("\\n\"") ||
620
                                     Previous.TokenText == "\'\\n\'")))) {
621
    return true;
622
  }
623

624
  if (Previous.is(TT_BlockComment) && Previous.IsMultiline)
625
    return true;
626

627
  if (State.NoContinuation)
628
    return true;
629

630
  return false;
631
}
632

633
unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
634
                                               bool DryRun,
635
                                               unsigned ExtraSpaces) {
636
  const FormatToken &Current = *State.NextToken;
637
  assert(State.NextToken->Previous);
638
  const FormatToken &Previous = *State.NextToken->Previous;
639

640
  assert(!State.Stack.empty());
641
  State.NoContinuation = false;
642

643
  if (Current.is(TT_ImplicitStringLiteral) &&
644
      (!Previous.Tok.getIdentifierInfo() ||
645
       Previous.Tok.getIdentifierInfo()->getPPKeywordID() ==
646
           tok::pp_not_keyword)) {
647
    unsigned EndColumn =
648
        SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getEnd());
649
    if (Current.LastNewlineOffset != 0) {
650
      // If there is a newline within this token, the final column will solely
651
      // determined by the current end column.
652
      State.Column = EndColumn;
653
    } else {
654
      unsigned StartColumn =
655
          SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getBegin());
656
      assert(EndColumn >= StartColumn);
657
      State.Column += EndColumn - StartColumn;
658
    }
659
    moveStateToNextToken(State, DryRun, /*Newline=*/false);
660
    return 0;
661
  }
662

663
  unsigned Penalty = 0;
664
  if (Newline)
665
    Penalty = addTokenOnNewLine(State, DryRun);
666
  else
667
    addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
668

669
  return moveStateToNextToken(State, DryRun, Newline) + Penalty;
670
}
671

672
void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
673
                                                 unsigned ExtraSpaces) {
674
  FormatToken &Current = *State.NextToken;
675
  assert(State.NextToken->Previous);
676
  const FormatToken &Previous = *State.NextToken->Previous;
677
  auto &CurrentState = State.Stack.back();
678

679
  bool DisallowLineBreaksOnThisLine =
680
      Style.LambdaBodyIndentation == FormatStyle::LBI_Signature &&
681
      Style.isCpp() && [&Current] {
682
        // Deal with lambda arguments in C++. The aim here is to ensure that we
683
        // don't over-indent lambda function bodies when lambdas are passed as
684
        // arguments to function calls. We do this by ensuring that either all
685
        // arguments (including any lambdas) go on the same line as the function
686
        // call, or we break before the first argument.
687
        const auto *Prev = Current.Previous;
688
        if (!Prev)
689
          return false;
690
        // For example, `/*Newline=*/false`.
691
        if (Prev->is(TT_BlockComment) && Current.SpacesRequiredBefore == 0)
692
          return false;
693
        const auto *PrevNonComment = Current.getPreviousNonComment();
694
        if (!PrevNonComment || PrevNonComment->isNot(tok::l_paren))
695
          return false;
696
        if (Current.isOneOf(tok::comment, tok::l_paren, TT_LambdaLSquare))
697
          return false;
698
        auto BlockParameterCount = PrevNonComment->BlockParameterCount;
699
        if (BlockParameterCount == 0)
700
          return false;
701

702
        // Multiple lambdas in the same function call.
703
        if (BlockParameterCount > 1)
704
          return true;
705

706
        // A lambda followed by another arg.
707
        if (!PrevNonComment->Role)
708
          return false;
709
        auto Comma = PrevNonComment->Role->lastComma();
710
        if (!Comma)
711
          return false;
712
        auto Next = Comma->getNextNonComment();
713
        return Next &&
714
               !Next->isOneOf(TT_LambdaLSquare, tok::l_brace, tok::caret);
715
      }();
716

717
  if (DisallowLineBreaksOnThisLine)
718
    State.NoLineBreak = true;
719

720
  if (Current.is(tok::equal) &&
721
      (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&
722
      CurrentState.VariablePos == 0 &&
723
      (!Previous.Previous ||
724
       Previous.Previous->isNot(TT_DesignatedInitializerPeriod))) {
725
    CurrentState.VariablePos = State.Column;
726
    // Move over * and & if they are bound to the variable name.
727
    const FormatToken *Tok = &Previous;
728
    while (Tok && CurrentState.VariablePos >= Tok->ColumnWidth) {
729
      CurrentState.VariablePos -= Tok->ColumnWidth;
730
      if (Tok->SpacesRequiredBefore != 0)
731
        break;
732
      Tok = Tok->Previous;
733
    }
734
    if (Previous.PartOfMultiVariableDeclStmt)
735
      CurrentState.LastSpace = CurrentState.VariablePos;
736
  }
737

738
  unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
739

740
  // Indent preprocessor directives after the hash if required.
741
  int PPColumnCorrection = 0;
742
  if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash &&
743
      Previous.is(tok::hash) && State.FirstIndent > 0 &&
744
      &Previous == State.Line->First &&
745
      (State.Line->Type == LT_PreprocessorDirective ||
746
       State.Line->Type == LT_ImportStatement)) {
747
    Spaces += State.FirstIndent;
748

749
    // For preprocessor indent with tabs, State.Column will be 1 because of the
750
    // hash. This causes second-level indents onward to have an extra space
751
    // after the tabs. We avoid this misalignment by subtracting 1 from the
752
    // column value passed to replaceWhitespace().
753
    if (Style.UseTab != FormatStyle::UT_Never)
754
      PPColumnCorrection = -1;
755
  }
756

757
  if (!DryRun) {
758
    Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, Spaces,
759
                                  State.Column + Spaces + PPColumnCorrection,
760
                                  /*IsAligned=*/false, State.Line->InMacroBody);
761
  }
762

763
  // If "BreakBeforeInheritanceComma" mode, don't break within the inheritance
764
  // declaration unless there is multiple inheritance.
765
  if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
766
      Current.is(TT_InheritanceColon)) {
767
    CurrentState.NoLineBreak = true;
768
  }
769
  if (Style.BreakInheritanceList == FormatStyle::BILS_AfterColon &&
770
      Previous.is(TT_InheritanceColon)) {
771
    CurrentState.NoLineBreak = true;
772
  }
773

774
  if (Current.is(TT_SelectorName) && !CurrentState.ObjCSelectorNameFound) {
775
    unsigned MinIndent = std::max(
776
        State.FirstIndent + Style.ContinuationIndentWidth, CurrentState.Indent);
777
    unsigned FirstColonPos = State.Column + Spaces + Current.ColumnWidth;
778
    if (Current.LongestObjCSelectorName == 0)
779
      CurrentState.AlignColons = false;
780
    else if (MinIndent + Current.LongestObjCSelectorName > FirstColonPos)
781
      CurrentState.ColonPos = MinIndent + Current.LongestObjCSelectorName;
782
    else
783
      CurrentState.ColonPos = FirstColonPos;
784
  }
785

786
  // In "AlwaysBreak" or "BlockIndent" mode, enforce wrapping directly after the
787
  // parenthesis by disallowing any further line breaks if there is no line
788
  // break after the opening parenthesis. Don't break if it doesn't conserve
789
  // columns.
790
  auto IsOpeningBracket = [&](const FormatToken &Tok) {
791
    auto IsStartOfBracedList = [&]() {
792
      return Tok.is(tok::l_brace) && Tok.isNot(BK_Block) &&
793
             Style.Cpp11BracedListStyle;
794
    };
795
    if (!Tok.isOneOf(tok::l_paren, TT_TemplateOpener, tok::l_square) &&
796
        !IsStartOfBracedList()) {
797
      return false;
798
    }
799
    if (!Tok.Previous)
800
      return true;
801
    if (Tok.Previous->isIf())
802
      return Style.AlignAfterOpenBracket == FormatStyle::BAS_AlwaysBreak;
803
    return !Tok.Previous->isOneOf(TT_CastRParen, tok::kw_for, tok::kw_while,
804
                                  tok::kw_switch);
805
  };
806
  if ((Style.AlignAfterOpenBracket == FormatStyle::BAS_AlwaysBreak ||
807
       Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent) &&
808
      IsOpeningBracket(Previous) && State.Column > getNewLineColumn(State) &&
809
      // Don't do this for simple (no expressions) one-argument function calls
810
      // as that feels like needlessly wasting whitespace, e.g.:
811
      //
812
      //   caaaaaaaaaaaall(
813
      //       caaaaaaaaaaaall(
814
      //           caaaaaaaaaaaall(
815
      //               caaaaaaaaaaaaaaaaaaaaaaall(aaaaaaaaaaaaaa, aaaaaaaaa))));
816
      Current.FakeLParens.size() > 0 &&
817
      Current.FakeLParens.back() > prec::Unknown) {
818
    CurrentState.NoLineBreak = true;
819
  }
820
  if (Previous.is(TT_TemplateString) && Previous.opensScope())
821
    CurrentState.NoLineBreak = true;
822

823
  // Align following lines within parentheses / brackets if configured.
824
  // Note: This doesn't apply to macro expansion lines, which are MACRO( , , )
825
  // with args as children of the '(' and ',' tokens. It does not make sense to
826
  // align the commas with the opening paren.
827
  if (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign &&
828
      !CurrentState.IsCSharpGenericTypeConstraint && Previous.opensScope() &&
829
      Previous.isNot(TT_ObjCMethodExpr) && Previous.isNot(TT_RequiresClause) &&
830
      Previous.isNot(TT_TableGenDAGArgOpener) &&
831
      Previous.isNot(TT_TableGenDAGArgOpenerToBreak) &&
832
      !(Current.MacroParent && Previous.MacroParent) &&
833
      (Current.isNot(TT_LineComment) ||
834
       Previous.isOneOf(BK_BracedInit, TT_VerilogMultiLineListLParen))) {
835
    CurrentState.Indent = State.Column + Spaces;
836
    CurrentState.IsAligned = true;
837
  }
838
  if (CurrentState.AvoidBinPacking && startsNextParameter(Current, Style))
839
    CurrentState.NoLineBreak = true;
840
  if (startsSegmentOfBuilderTypeCall(Current) &&
841
      State.Column > getNewLineColumn(State)) {
842
    CurrentState.ContainsUnwrappedBuilder = true;
843
  }
844

845
  if (Current.is(TT_TrailingReturnArrow) &&
846
      Style.Language == FormatStyle::LK_Java) {
847
    CurrentState.NoLineBreak = true;
848
  }
849
  if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
850
      (Previous.MatchingParen &&
851
       (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) {
852
    // If there is a function call with long parameters, break before trailing
853
    // calls. This prevents things like:
854
    //   EXPECT_CALL(SomeLongParameter).Times(
855
    //       2);
856
    // We don't want to do this for short parameters as they can just be
857
    // indexes.
858
    CurrentState.NoLineBreak = true;
859
  }
860

861
  // Don't allow the RHS of an operator to be split over multiple lines unless
862
  // there is a line-break right after the operator.
863
  // Exclude relational operators, as there, it is always more desirable to
864
  // have the LHS 'left' of the RHS.
865
  const FormatToken *P = Current.getPreviousNonComment();
866
  if (Current.isNot(tok::comment) && P &&
867
      (P->isOneOf(TT_BinaryOperator, tok::comma) ||
868
       (P->is(TT_ConditionalExpr) && P->is(tok::colon))) &&
869
      !P->isOneOf(TT_OverloadedOperator, TT_CtorInitializerComma) &&
870
      P->getPrecedence() != prec::Assignment &&
871
      P->getPrecedence() != prec::Relational &&
872
      P->getPrecedence() != prec::Spaceship) {
873
    bool BreakBeforeOperator =
874
        P->MustBreakBefore || P->is(tok::lessless) ||
875
        (P->is(TT_BinaryOperator) &&
876
         Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) ||
877
        (P->is(TT_ConditionalExpr) && Style.BreakBeforeTernaryOperators);
878
    // Don't do this if there are only two operands. In these cases, there is
879
    // always a nice vertical separation between them and the extra line break
880
    // does not help.
881
    bool HasTwoOperands = P->OperatorIndex == 0 && !P->NextOperator &&
882
                          P->isNot(TT_ConditionalExpr);
883
    if ((!BreakBeforeOperator &&
884
         !(HasTwoOperands &&
885
           Style.AlignOperands != FormatStyle::OAS_DontAlign)) ||
886
        (!CurrentState.LastOperatorWrapped && BreakBeforeOperator)) {
887
      CurrentState.NoLineBreakInOperand = true;
888
    }
889
  }
890

891
  State.Column += Spaces;
892
  if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
893
      Previous.Previous &&
894
      (Previous.Previous->is(tok::kw_for) || Previous.Previous->isIf())) {
895
    // Treat the condition inside an if as if it was a second function
896
    // parameter, i.e. let nested calls have a continuation indent.
897
    CurrentState.LastSpace = State.Column;
898
    CurrentState.NestedBlockIndent = State.Column;
899
  } else if (!Current.isOneOf(tok::comment, tok::caret) &&
900
             ((Previous.is(tok::comma) &&
901
               Previous.isNot(TT_OverloadedOperator)) ||
902
              (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) {
903
    CurrentState.LastSpace = State.Column;
904
  } else if (Previous.is(TT_CtorInitializerColon) &&
905
             (!Current.isTrailingComment() || Current.NewlinesBefore > 0) &&
906
             Style.BreakConstructorInitializers ==
907
                 FormatStyle::BCIS_AfterColon) {
908
    CurrentState.Indent = State.Column;
909
    CurrentState.LastSpace = State.Column;
910
  } else if (Previous.isOneOf(TT_ConditionalExpr, TT_CtorInitializerColon)) {
911
    CurrentState.LastSpace = State.Column;
912
  } else if (Previous.is(TT_BinaryOperator) &&
913
             ((Previous.getPrecedence() != prec::Assignment &&
914
               (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
915
                Previous.NextOperator)) ||
916
              Current.StartsBinaryExpression)) {
917
    // Indent relative to the RHS of the expression unless this is a simple
918
    // assignment without binary expression on the RHS.
919
    if (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None)
920
      CurrentState.LastSpace = State.Column;
921
  } else if (Previous.is(TT_InheritanceColon)) {
922
    CurrentState.Indent = State.Column;
923
    CurrentState.LastSpace = State.Column;
924
  } else if (Current.is(TT_CSharpGenericTypeConstraintColon)) {
925
    CurrentState.ColonPos = State.Column;
926
  } else if (Previous.opensScope()) {
927
    // If a function has a trailing call, indent all parameters from the
928
    // opening parenthesis. This avoids confusing indents like:
929
    //   OuterFunction(InnerFunctionCall( // break
930
    //       ParameterToInnerFunction))   // break
931
    //       .SecondInnerFunctionCall();
932
    if (Previous.MatchingParen) {
933
      const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
934
      if (Next && Next->isMemberAccess() && State.Stack.size() > 1 &&
935
          State.Stack[State.Stack.size() - 2].CallContinuation == 0) {
936
        CurrentState.LastSpace = State.Column;
937
      }
938
    }
939
  }
940
}
941

942
unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
943
                                                 bool DryRun) {
944
  FormatToken &Current = *State.NextToken;
945
  assert(State.NextToken->Previous);
946
  const FormatToken &Previous = *State.NextToken->Previous;
947
  auto &CurrentState = State.Stack.back();
948

949
  // Extra penalty that needs to be added because of the way certain line
950
  // breaks are chosen.
951
  unsigned Penalty = 0;
952

953
  const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
954
  const FormatToken *NextNonComment = Previous.getNextNonComment();
955
  if (!NextNonComment)
956
    NextNonComment = &Current;
957
  // The first line break on any NestingLevel causes an extra penalty in order
958
  // prefer similar line breaks.
959
  if (!CurrentState.ContainsLineBreak)
960
    Penalty += 15;
961
  CurrentState.ContainsLineBreak = true;
962

963
  Penalty += State.NextToken->SplitPenalty;
964

965
  // Breaking before the first "<<" is generally not desirable if the LHS is
966
  // short. Also always add the penalty if the LHS is split over multiple lines
967
  // to avoid unnecessary line breaks that just work around this penalty.
968
  if (NextNonComment->is(tok::lessless) && CurrentState.FirstLessLess == 0 &&
969
      (State.Column <= Style.ColumnLimit / 3 ||
970
       CurrentState.BreakBeforeParameter)) {
971
    Penalty += Style.PenaltyBreakFirstLessLess;
972
  }
973

974
  State.Column = getNewLineColumn(State);
975

976
  // Add Penalty proportional to amount of whitespace away from FirstColumn
977
  // This tends to penalize several lines that are far-right indented,
978
  // and prefers a line-break prior to such a block, e.g:
979
  //
980
  // Constructor() :
981
  //   member(value), looooooooooooooooong_member(
982
  //                      looooooooooong_call(param_1, param_2, param_3))
983
  // would then become
984
  // Constructor() :
985
  //   member(value),
986
  //   looooooooooooooooong_member(
987
  //       looooooooooong_call(param_1, param_2, param_3))
988
  if (State.Column > State.FirstIndent) {
989
    Penalty +=
990
        Style.PenaltyIndentedWhitespace * (State.Column - State.FirstIndent);
991
  }
992

993
  // Indent nested blocks relative to this column, unless in a very specific
994
  // JavaScript special case where:
995
  //
996
  //   var loooooong_name =
997
  //       function() {
998
  //     // code
999
  //   }
1000
  //
1001
  // is common and should be formatted like a free-standing function. The same
1002
  // goes for wrapping before the lambda return type arrow.
1003
  if (Current.isNot(TT_TrailingReturnArrow) &&
1004
      (!Style.isJavaScript() || Current.NestingLevel != 0 ||
1005
       !PreviousNonComment || PreviousNonComment->isNot(tok::equal) ||
1006
       !Current.isOneOf(Keywords.kw_async, Keywords.kw_function))) {
1007
    CurrentState.NestedBlockIndent = State.Column;
1008
  }
1009

1010
  if (NextNonComment->isMemberAccess()) {
1011
    if (CurrentState.CallContinuation == 0)
1012
      CurrentState.CallContinuation = State.Column;
1013
  } else if (NextNonComment->is(TT_SelectorName)) {
1014
    if (!CurrentState.ObjCSelectorNameFound) {
1015
      if (NextNonComment->LongestObjCSelectorName == 0) {
1016
        CurrentState.AlignColons = false;
1017
      } else {
1018
        CurrentState.ColonPos =
1019
            (shouldIndentWrappedSelectorName(Style, State.Line->Type)
1020
                 ? std::max(CurrentState.Indent,
1021
                            State.FirstIndent + Style.ContinuationIndentWidth)
1022
                 : CurrentState.Indent) +
1023
            std::max(NextNonComment->LongestObjCSelectorName,
1024
                     NextNonComment->ColumnWidth);
1025
      }
1026
    } else if (CurrentState.AlignColons &&
1027
               CurrentState.ColonPos <= NextNonComment->ColumnWidth) {
1028
      CurrentState.ColonPos = State.Column + NextNonComment->ColumnWidth;
1029
    }
1030
  } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
1031
             PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
1032
    // FIXME: This is hacky, find a better way. The problem is that in an ObjC
1033
    // method expression, the block should be aligned to the line starting it,
1034
    // e.g.:
1035
    //   [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
1036
    //                        ^(int *i) {
1037
    //                            // ...
1038
    //                        }];
1039
    // Thus, we set LastSpace of the next higher NestingLevel, to which we move
1040
    // when we consume all of the "}"'s FakeRParens at the "{".
1041
    if (State.Stack.size() > 1) {
1042
      State.Stack[State.Stack.size() - 2].LastSpace =
1043
          std::max(CurrentState.LastSpace, CurrentState.Indent) +
1044
          Style.ContinuationIndentWidth;
1045
    }
1046
  }
1047

1048
  if ((PreviousNonComment &&
1049
       PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
1050
       !CurrentState.AvoidBinPacking) ||
1051
      Previous.is(TT_BinaryOperator)) {
1052
    CurrentState.BreakBeforeParameter = false;
1053
  }
1054
  if (PreviousNonComment &&
1055
      (PreviousNonComment->isOneOf(TT_TemplateCloser, TT_JavaAnnotation) ||
1056
       PreviousNonComment->ClosesRequiresClause) &&
1057
      Current.NestingLevel == 0) {
1058
    CurrentState.BreakBeforeParameter = false;
1059
  }
1060
  if (NextNonComment->is(tok::question) ||
1061
      (PreviousNonComment && PreviousNonComment->is(tok::question))) {
1062
    CurrentState.BreakBeforeParameter = true;
1063
  }
1064
  if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore)
1065
    CurrentState.BreakBeforeParameter = false;
1066

1067
  if (!DryRun) {
1068
    unsigned MaxEmptyLinesToKeep = Style.MaxEmptyLinesToKeep + 1;
1069
    if (Current.is(tok::r_brace) && Current.MatchingParen &&
1070
        // Only strip trailing empty lines for l_braces that have children, i.e.
1071
        // for function expressions (lambdas, arrows, etc).
1072
        !Current.MatchingParen->Children.empty()) {
1073
      // lambdas and arrow functions are expressions, thus their r_brace is not
1074
      // on its own line, and thus not covered by UnwrappedLineFormatter's logic
1075
      // about removing empty lines on closing blocks. Special case them here.
1076
      MaxEmptyLinesToKeep = 1;
1077
    }
1078
    unsigned Newlines =
1079
        std::max(1u, std::min(Current.NewlinesBefore, MaxEmptyLinesToKeep));
1080
    bool ContinuePPDirective =
1081
        State.Line->InPPDirective && State.Line->Type != LT_ImportStatement;
1082
    Whitespaces.replaceWhitespace(Current, Newlines, State.Column, State.Column,
1083
                                  CurrentState.IsAligned, ContinuePPDirective);
1084
  }
1085

1086
  if (!Current.isTrailingComment())
1087
    CurrentState.LastSpace = State.Column;
1088
  if (Current.is(tok::lessless)) {
1089
    // If we are breaking before a "<<", we always want to indent relative to
1090
    // RHS. This is necessary only for "<<", as we special-case it and don't
1091
    // always indent relative to the RHS.
1092
    CurrentState.LastSpace += 3; // 3 -> width of "<< ".
1093
  }
1094

1095
  State.StartOfLineLevel = Current.NestingLevel;
1096
  State.LowestLevelOnLine = Current.NestingLevel;
1097

1098
  // Any break on this level means that the parent level has been broken
1099
  // and we need to avoid bin packing there.
1100
  bool NestedBlockSpecialCase =
1101
      (!Style.isCpp() && Current.is(tok::r_brace) && State.Stack.size() > 1 &&
1102
       State.Stack[State.Stack.size() - 2].NestedBlockInlined) ||
1103
      (Style.Language == FormatStyle::LK_ObjC && Current.is(tok::r_brace) &&
1104
       State.Stack.size() > 1 && !Style.ObjCBreakBeforeNestedBlockParam);
1105
  // Do not force parameter break for statements with requires expressions.
1106
  NestedBlockSpecialCase =
1107
      NestedBlockSpecialCase ||
1108
      (Current.MatchingParen &&
1109
       Current.MatchingParen->is(TT_RequiresExpressionLBrace));
1110
  if (!NestedBlockSpecialCase) {
1111
    auto ParentLevelIt = std::next(State.Stack.rbegin());
1112
    if (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&
1113
        Current.MatchingParen && Current.MatchingParen->is(TT_LambdaLBrace)) {
1114
      // If the first character on the new line is a lambda's closing brace, the
1115
      // stack still contains that lambda's parenthesis. As such, we need to
1116
      // recurse further down the stack than usual to find the parenthesis level
1117
      // containing the lambda, which is where we want to set
1118
      // BreakBeforeParameter.
1119
      //
1120
      // We specifically special case "OuterScope"-formatted lambdas here
1121
      // because, when using that setting, breaking before the parameter
1122
      // directly following the lambda is particularly unsightly. However, when
1123
      // "OuterScope" is not set, the logic to find the parent parenthesis level
1124
      // still appears to be sometimes incorrect. It has not been fixed yet
1125
      // because it would lead to significant changes in existing behaviour.
1126
      //
1127
      // TODO: fix the non-"OuterScope" case too.
1128
      auto FindCurrentLevel = [&](const auto &It) {
1129
        return std::find_if(It, State.Stack.rend(), [](const auto &PState) {
1130
          return PState.Tok != nullptr; // Ignore fake parens.
1131
        });
1132
      };
1133
      auto MaybeIncrement = [&](const auto &It) {
1134
        return It != State.Stack.rend() ? std::next(It) : It;
1135
      };
1136
      auto LambdaLevelIt = FindCurrentLevel(State.Stack.rbegin());
1137
      auto LevelContainingLambdaIt =
1138
          FindCurrentLevel(MaybeIncrement(LambdaLevelIt));
1139
      ParentLevelIt = MaybeIncrement(LevelContainingLambdaIt);
1140
    }
1141
    for (auto I = ParentLevelIt, E = State.Stack.rend(); I != E; ++I)
1142
      I->BreakBeforeParameter = true;
1143
  }
1144

1145
  if (PreviousNonComment &&
1146
      !PreviousNonComment->isOneOf(tok::comma, tok::colon, tok::semi) &&
1147
      ((PreviousNonComment->isNot(TT_TemplateCloser) &&
1148
        !PreviousNonComment->ClosesRequiresClause) ||
1149
       Current.NestingLevel != 0) &&
1150
      !PreviousNonComment->isOneOf(
1151
          TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
1152
          TT_LeadingJavaAnnotation) &&
1153
      Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope() &&
1154
      // We don't want to enforce line breaks for subsequent arguments just
1155
      // because we have been forced to break before a lambda body.
1156
      (!Style.BraceWrapping.BeforeLambdaBody ||
1157
       Current.isNot(TT_LambdaLBrace))) {
1158
    CurrentState.BreakBeforeParameter = true;
1159
  }
1160

1161
  // If we break after { or the [ of an array initializer, we should also break
1162
  // before the corresponding } or ].
1163
  if (PreviousNonComment &&
1164
      (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
1165
       opensProtoMessageField(*PreviousNonComment, Style))) {
1166
    CurrentState.BreakBeforeClosingBrace = true;
1167
  }
1168

1169
  if (PreviousNonComment && PreviousNonComment->is(tok::l_paren)) {
1170
    CurrentState.BreakBeforeClosingParen =
1171
        Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent;
1172
  }
1173

1174
  if (CurrentState.AvoidBinPacking) {
1175
    // If we are breaking after '(', '{', '<', or this is the break after a ':'
1176
    // to start a member initializer list in a constructor, this should not
1177
    // be considered bin packing unless the relevant AllowAll option is false or
1178
    // this is a dict/object literal.
1179
    bool PreviousIsBreakingCtorInitializerColon =
1180
        PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) &&
1181
        Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon;
1182
    bool AllowAllConstructorInitializersOnNextLine =
1183
        Style.PackConstructorInitializers == FormatStyle::PCIS_NextLine ||
1184
        Style.PackConstructorInitializers == FormatStyle::PCIS_NextLineOnly;
1185
    if (!(Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) ||
1186
          PreviousIsBreakingCtorInitializerColon) ||
1187
        (!Style.AllowAllParametersOfDeclarationOnNextLine &&
1188
         State.Line->MustBeDeclaration) ||
1189
        (!Style.AllowAllArgumentsOnNextLine &&
1190
         !State.Line->MustBeDeclaration) ||
1191
        (!AllowAllConstructorInitializersOnNextLine &&
1192
         PreviousIsBreakingCtorInitializerColon) ||
1193
        Previous.is(TT_DictLiteral)) {
1194
      CurrentState.BreakBeforeParameter = true;
1195
    }
1196

1197
    // If we are breaking after a ':' to start a member initializer list,
1198
    // and we allow all arguments on the next line, we should not break
1199
    // before the next parameter.
1200
    if (PreviousIsBreakingCtorInitializerColon &&
1201
        AllowAllConstructorInitializersOnNextLine) {
1202
      CurrentState.BreakBeforeParameter = false;
1203
    }
1204
  }
1205

1206
  return Penalty;
1207
}
1208

1209
unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
1210
  if (!State.NextToken || !State.NextToken->Previous)
1211
    return 0;
1212

1213
  FormatToken &Current = *State.NextToken;
1214
  const auto &CurrentState = State.Stack.back();
1215

1216
  if (CurrentState.IsCSharpGenericTypeConstraint &&
1217
      Current.isNot(TT_CSharpGenericTypeConstraint)) {
1218
    return CurrentState.ColonPos + 2;
1219
  }
1220

1221
  const FormatToken &Previous = *Current.Previous;
1222
  // If we are continuing an expression, we want to use the continuation indent.
1223
  unsigned ContinuationIndent =
1224
      std::max(CurrentState.LastSpace, CurrentState.Indent) +
1225
      Style.ContinuationIndentWidth;
1226
  const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
1227
  const FormatToken *NextNonComment = Previous.getNextNonComment();
1228
  if (!NextNonComment)
1229
    NextNonComment = &Current;
1230

1231
  // Java specific bits.
1232
  if (Style.Language == FormatStyle::LK_Java &&
1233
      Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends)) {
1234
    return std::max(CurrentState.LastSpace,
1235
                    CurrentState.Indent + Style.ContinuationIndentWidth);
1236
  }
1237

1238
  // Indentation of the statement following a Verilog case label is taken care
1239
  // of in moveStateToNextToken.
1240
  if (Style.isVerilog() && PreviousNonComment &&
1241
      Keywords.isVerilogEndOfLabel(*PreviousNonComment)) {
1242
    return State.FirstIndent;
1243
  }
1244

1245
  if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths &&
1246
      State.Line->First->is(tok::kw_enum)) {
1247
    return (Style.IndentWidth * State.Line->First->IndentLevel) +
1248
           Style.IndentWidth;
1249
  }
1250

1251
  if ((NextNonComment->is(tok::l_brace) && NextNonComment->is(BK_Block)) ||
1252
      (Style.isVerilog() && Keywords.isVerilogBegin(*NextNonComment))) {
1253
    if (Current.NestingLevel == 0 ||
1254
        (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&
1255
         State.NextToken->is(TT_LambdaLBrace))) {
1256
      return State.FirstIndent;
1257
    }
1258
    return CurrentState.Indent;
1259
  }
1260
  if (Current.is(TT_TrailingReturnArrow) &&
1261
      Previous.isOneOf(tok::kw_noexcept, tok::kw_mutable, tok::kw_constexpr,
1262
                       tok::kw_consteval, tok::kw_static, TT_AttributeSquare)) {
1263
    return ContinuationIndent;
1264
  }
1265
  if ((Current.isOneOf(tok::r_brace, tok::r_square) ||
1266
       (Current.is(tok::greater) && (Style.isProto() || Style.isTableGen()))) &&
1267
      State.Stack.size() > 1) {
1268
    if (Current.closesBlockOrBlockTypeList(Style))
1269
      return State.Stack[State.Stack.size() - 2].NestedBlockIndent;
1270
    if (Current.MatchingParen && Current.MatchingParen->is(BK_BracedInit))
1271
      return State.Stack[State.Stack.size() - 2].LastSpace;
1272
    return State.FirstIndent;
1273
  }
1274
  // Indent a closing parenthesis at the previous level if followed by a semi,
1275
  // const, or opening brace. This allows indentations such as:
1276
  //     foo(
1277
  //       a,
1278
  //     );
1279
  //     int Foo::getter(
1280
  //         //
1281
  //     ) const {
1282
  //       return foo;
1283
  //     }
1284
  //     function foo(
1285
  //       a,
1286
  //     ) {
1287
  //       code(); //
1288
  //     }
1289
  if (Current.is(tok::r_paren) && State.Stack.size() > 1 &&
1290
      (!Current.Next ||
1291
       Current.Next->isOneOf(tok::semi, tok::kw_const, tok::l_brace))) {
1292
    return State.Stack[State.Stack.size() - 2].LastSpace;
1293
  }
1294
  // When DAGArg closer exists top of line, it should be aligned in the similar
1295
  // way as function call above.
1296
  if (Style.isTableGen() && Current.is(TT_TableGenDAGArgCloser) &&
1297
      State.Stack.size() > 1) {
1298
    return State.Stack[State.Stack.size() - 2].LastSpace;
1299
  }
1300
  if (Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent &&
1301
      (Current.is(tok::r_paren) ||
1302
       (Current.is(tok::r_brace) && Current.MatchingParen &&
1303
        Current.MatchingParen->is(BK_BracedInit))) &&
1304
      State.Stack.size() > 1) {
1305
    return State.Stack[State.Stack.size() - 2].LastSpace;
1306
  }
1307
  if (NextNonComment->is(TT_TemplateString) && NextNonComment->closesScope())
1308
    return State.Stack[State.Stack.size() - 2].LastSpace;
1309
  // Field labels in a nested type should be aligned to the brace. For example
1310
  // in ProtoBuf:
1311
  //   optional int32 b = 2 [(foo_options) = {aaaaaaaaaaaaaaaaaaa: 123,
1312
  //                                          bbbbbbbbbbbbbbbbbbbbbbbb:"baz"}];
1313
  // For Verilog, a quote following a brace is treated as an identifier.  And
1314
  // Both braces and colons get annotated as TT_DictLiteral.  So we have to
1315
  // check.
1316
  if (Current.is(tok::identifier) && Current.Next &&
1317
      (!Style.isVerilog() || Current.Next->is(tok::colon)) &&
1318
      (Current.Next->is(TT_DictLiteral) ||
1319
       (Style.isProto() && Current.Next->isOneOf(tok::less, tok::l_brace)))) {
1320
    return CurrentState.Indent;
1321
  }
1322
  if (NextNonComment->is(TT_ObjCStringLiteral) &&
1323
      State.StartOfStringLiteral != 0) {
1324
    return State.StartOfStringLiteral - 1;
1325
  }
1326
  if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
1327
    return State.StartOfStringLiteral;
1328
  if (NextNonComment->is(tok::lessless) && CurrentState.FirstLessLess != 0)
1329
    return CurrentState.FirstLessLess;
1330
  if (NextNonComment->isMemberAccess()) {
1331
    if (CurrentState.CallContinuation == 0)
1332
      return ContinuationIndent;
1333
    return CurrentState.CallContinuation;
1334
  }
1335
  if (CurrentState.QuestionColumn != 0 &&
1336
      ((NextNonComment->is(tok::colon) &&
1337
        NextNonComment->is(TT_ConditionalExpr)) ||
1338
       Previous.is(TT_ConditionalExpr))) {
1339
    if (((NextNonComment->is(tok::colon) && NextNonComment->Next &&
1340
          !NextNonComment->Next->FakeLParens.empty() &&
1341
          NextNonComment->Next->FakeLParens.back() == prec::Conditional) ||
1342
         (Previous.is(tok::colon) && !Current.FakeLParens.empty() &&
1343
          Current.FakeLParens.back() == prec::Conditional)) &&
1344
        !CurrentState.IsWrappedConditional) {
1345
      // NOTE: we may tweak this slightly:
1346
      //    * not remove the 'lead' ContinuationIndentWidth
1347
      //    * always un-indent by the operator when
1348
      //    BreakBeforeTernaryOperators=true
1349
      unsigned Indent = CurrentState.Indent;
1350
      if (Style.AlignOperands != FormatStyle::OAS_DontAlign)
1351
        Indent -= Style.ContinuationIndentWidth;
1352
      if (Style.BreakBeforeTernaryOperators && CurrentState.UnindentOperator)
1353
        Indent -= 2;
1354
      return Indent;
1355
    }
1356
    return CurrentState.QuestionColumn;
1357
  }
1358
  if (Previous.is(tok::comma) && CurrentState.VariablePos != 0)
1359
    return CurrentState.VariablePos;
1360
  if (Current.is(TT_RequiresClause)) {
1361
    if (Style.IndentRequiresClause)
1362
      return CurrentState.Indent + Style.IndentWidth;
1363
    switch (Style.RequiresClausePosition) {
1364
    case FormatStyle::RCPS_OwnLine:
1365
    case FormatStyle::RCPS_WithFollowing:
1366
      return CurrentState.Indent;
1367
    default:
1368
      break;
1369
    }
1370
  }
1371
  if (NextNonComment->isOneOf(TT_CtorInitializerColon, TT_InheritanceColon,
1372
                              TT_InheritanceComma)) {
1373
    return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1374
  }
1375
  if ((PreviousNonComment &&
1376
       (PreviousNonComment->ClosesTemplateDeclaration ||
1377
        PreviousNonComment->ClosesRequiresClause ||
1378
        (PreviousNonComment->is(TT_AttributeMacro) &&
1379
         Current.isNot(tok::l_paren)) ||
1380
        PreviousNonComment->isOneOf(
1381
            TT_AttributeRParen, TT_AttributeSquare, TT_FunctionAnnotationRParen,
1382
            TT_JavaAnnotation, TT_LeadingJavaAnnotation))) ||
1383
      (!Style.IndentWrappedFunctionNames &&
1384
       NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName))) {
1385
    return std::max(CurrentState.LastSpace, CurrentState.Indent);
1386
  }
1387
  if (NextNonComment->is(TT_SelectorName)) {
1388
    if (!CurrentState.ObjCSelectorNameFound) {
1389
      unsigned MinIndent = CurrentState.Indent;
1390
      if (shouldIndentWrappedSelectorName(Style, State.Line->Type)) {
1391
        MinIndent = std::max(MinIndent,
1392
                             State.FirstIndent + Style.ContinuationIndentWidth);
1393
      }
1394
      // If LongestObjCSelectorName is 0, we are indenting the first
1395
      // part of an ObjC selector (or a selector component which is
1396
      // not colon-aligned due to block formatting).
1397
      //
1398
      // Otherwise, we are indenting a subsequent part of an ObjC
1399
      // selector which should be colon-aligned to the longest
1400
      // component of the ObjC selector.
1401
      //
1402
      // In either case, we want to respect Style.IndentWrappedFunctionNames.
1403
      return MinIndent +
1404
             std::max(NextNonComment->LongestObjCSelectorName,
1405
                      NextNonComment->ColumnWidth) -
1406
             NextNonComment->ColumnWidth;
1407
    }
1408
    if (!CurrentState.AlignColons)
1409
      return CurrentState.Indent;
1410
    if (CurrentState.ColonPos > NextNonComment->ColumnWidth)
1411
      return CurrentState.ColonPos - NextNonComment->ColumnWidth;
1412
    return CurrentState.Indent;
1413
  }
1414
  if (NextNonComment->is(tok::colon) && NextNonComment->is(TT_ObjCMethodExpr))
1415
    return CurrentState.ColonPos;
1416
  if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
1417
    if (CurrentState.StartOfArraySubscripts != 0) {
1418
      return CurrentState.StartOfArraySubscripts;
1419
    } else if (Style.isCSharp()) { // C# allows `["key"] = value` inside object
1420
                                   // initializers.
1421
      return CurrentState.Indent;
1422
    }
1423
    return ContinuationIndent;
1424
  }
1425

1426
  // OpenMP clauses want to get additional indentation when they are pushed onto
1427
  // the next line.
1428
  if (State.Line->InPragmaDirective) {
1429
    FormatToken *PragmaType = State.Line->First->Next->Next;
1430
    if (PragmaType && PragmaType->TokenText == "omp")
1431
      return CurrentState.Indent + Style.ContinuationIndentWidth;
1432
  }
1433

1434
  // This ensure that we correctly format ObjC methods calls without inputs,
1435
  // i.e. where the last element isn't selector like: [callee method];
1436
  if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 &&
1437
      NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr)) {
1438
    return CurrentState.Indent;
1439
  }
1440

1441
  if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) ||
1442
      Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon)) {
1443
    return ContinuationIndent;
1444
  }
1445
  if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
1446
      PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
1447
    return ContinuationIndent;
1448
  }
1449
  if (NextNonComment->is(TT_CtorInitializerComma))
1450
    return CurrentState.Indent;
1451
  if (PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) &&
1452
      Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) {
1453
    return CurrentState.Indent;
1454
  }
1455
  if (PreviousNonComment && PreviousNonComment->is(TT_InheritanceColon) &&
1456
      Style.BreakInheritanceList == FormatStyle::BILS_AfterColon) {
1457
    return CurrentState.Indent;
1458
  }
1459
  if (Previous.is(tok::r_paren) &&
1460
      Previous.isNot(TT_TableGenDAGArgOperatorToBreak) &&
1461
      !Current.isBinaryOperator() &&
1462
      !Current.isOneOf(tok::colon, tok::comment)) {
1463
    return ContinuationIndent;
1464
  }
1465
  if (Current.is(TT_ProtoExtensionLSquare))
1466
    return CurrentState.Indent;
1467
  if (Current.isBinaryOperator() && CurrentState.UnindentOperator) {
1468
    return CurrentState.Indent - Current.Tok.getLength() -
1469
           Current.SpacesRequiredBefore;
1470
  }
1471
  if (Current.is(tok::comment) && NextNonComment->isBinaryOperator() &&
1472
      CurrentState.UnindentOperator) {
1473
    return CurrentState.Indent - NextNonComment->Tok.getLength() -
1474
           NextNonComment->SpacesRequiredBefore;
1475
  }
1476
  if (CurrentState.Indent == State.FirstIndent && PreviousNonComment &&
1477
      !PreviousNonComment->isOneOf(tok::r_brace, TT_CtorInitializerComma)) {
1478
    // Ensure that we fall back to the continuation indent width instead of
1479
    // just flushing continuations left.
1480
    return CurrentState.Indent + Style.ContinuationIndentWidth;
1481
  }
1482
  return CurrentState.Indent;
1483
}
1484

1485
static bool hasNestedBlockInlined(const FormatToken *Previous,
1486
                                  const FormatToken &Current,
1487
                                  const FormatStyle &Style) {
1488
  if (Previous->isNot(tok::l_paren))
1489
    return true;
1490
  if (Previous->ParameterCount > 1)
1491
    return true;
1492

1493
  // Also a nested block if contains a lambda inside function with 1 parameter.
1494
  return Style.BraceWrapping.BeforeLambdaBody && Current.is(TT_LambdaLSquare);
1495
}
1496

1497
unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
1498
                                                    bool DryRun, bool Newline) {
1499
  assert(State.Stack.size());
1500
  const FormatToken &Current = *State.NextToken;
1501
  auto &CurrentState = State.Stack.back();
1502

1503
  if (Current.is(TT_CSharpGenericTypeConstraint))
1504
    CurrentState.IsCSharpGenericTypeConstraint = true;
1505
  if (Current.isOneOf(tok::comma, TT_BinaryOperator))
1506
    CurrentState.NoLineBreakInOperand = false;
1507
  if (Current.isOneOf(TT_InheritanceColon, TT_CSharpGenericTypeConstraintColon))
1508
    CurrentState.AvoidBinPacking = true;
1509
  if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
1510
    if (CurrentState.FirstLessLess == 0)
1511
      CurrentState.FirstLessLess = State.Column;
1512
    else
1513
      CurrentState.LastOperatorWrapped = Newline;
1514
  }
1515
  if (Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless))
1516
    CurrentState.LastOperatorWrapped = Newline;
1517
  if (Current.is(TT_ConditionalExpr) && Current.Previous &&
1518
      Current.Previous->isNot(TT_ConditionalExpr)) {
1519
    CurrentState.LastOperatorWrapped = Newline;
1520
  }
1521
  if (Current.is(TT_ArraySubscriptLSquare) &&
1522
      CurrentState.StartOfArraySubscripts == 0) {
1523
    CurrentState.StartOfArraySubscripts = State.Column;
1524
  }
1525

1526
  auto IsWrappedConditional = [](const FormatToken &Tok) {
1527
    if (!(Tok.is(TT_ConditionalExpr) && Tok.is(tok::question)))
1528
      return false;
1529
    if (Tok.MustBreakBefore)
1530
      return true;
1531

1532
    const FormatToken *Next = Tok.getNextNonComment();
1533
    return Next && Next->MustBreakBefore;
1534
  };
1535
  if (IsWrappedConditional(Current))
1536
    CurrentState.IsWrappedConditional = true;
1537
  if (Style.BreakBeforeTernaryOperators && Current.is(tok::question))
1538
    CurrentState.QuestionColumn = State.Column;
1539
  if (!Style.BreakBeforeTernaryOperators && Current.isNot(tok::colon)) {
1540
    const FormatToken *Previous = Current.Previous;
1541
    while (Previous && Previous->isTrailingComment())
1542
      Previous = Previous->Previous;
1543
    if (Previous && Previous->is(tok::question))
1544
      CurrentState.QuestionColumn = State.Column;
1545
  }
1546
  if (!Current.opensScope() && !Current.closesScope() &&
1547
      Current.isNot(TT_PointerOrReference)) {
1548
    State.LowestLevelOnLine =
1549
        std::min(State.LowestLevelOnLine, Current.NestingLevel);
1550
  }
1551
  if (Current.isMemberAccess())
1552
    CurrentState.StartOfFunctionCall = !Current.NextOperator ? 0 : State.Column;
1553
  if (Current.is(TT_SelectorName))
1554
    CurrentState.ObjCSelectorNameFound = true;
1555
  if (Current.is(TT_CtorInitializerColon) &&
1556
      Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon) {
1557
    // Indent 2 from the column, so:
1558
    // SomeClass::SomeClass()
1559
    //     : First(...), ...
1560
    //       Next(...)
1561
    //       ^ line up here.
1562
    CurrentState.Indent = State.Column + (Style.BreakConstructorInitializers ==
1563
                                                  FormatStyle::BCIS_BeforeComma
1564
                                              ? 0
1565
                                              : 2);
1566
    CurrentState.NestedBlockIndent = CurrentState.Indent;
1567
    if (Style.PackConstructorInitializers > FormatStyle::PCIS_BinPack) {
1568
      CurrentState.AvoidBinPacking = true;
1569
      CurrentState.BreakBeforeParameter =
1570
          Style.ColumnLimit > 0 &&
1571
          Style.PackConstructorInitializers != FormatStyle::PCIS_NextLine &&
1572
          Style.PackConstructorInitializers != FormatStyle::PCIS_NextLineOnly;
1573
    } else {
1574
      CurrentState.BreakBeforeParameter = false;
1575
    }
1576
  }
1577
  if (Current.is(TT_CtorInitializerColon) &&
1578
      Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) {
1579
    CurrentState.Indent =
1580
        State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1581
    CurrentState.NestedBlockIndent = CurrentState.Indent;
1582
    if (Style.PackConstructorInitializers > FormatStyle::PCIS_BinPack)
1583
      CurrentState.AvoidBinPacking = true;
1584
    else
1585
      CurrentState.BreakBeforeParameter = false;
1586
  }
1587
  if (Current.is(TT_InheritanceColon)) {
1588
    CurrentState.Indent =
1589
        State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1590
  }
1591
  if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline)
1592
    CurrentState.NestedBlockIndent = State.Column + Current.ColumnWidth + 1;
1593
  if (Current.isOneOf(TT_LambdaLSquare, TT_TrailingReturnArrow))
1594
    CurrentState.LastSpace = State.Column;
1595
  if (Current.is(TT_RequiresExpression) &&
1596
      Style.RequiresExpressionIndentation == FormatStyle::REI_Keyword) {
1597
    CurrentState.NestedBlockIndent = State.Column;
1598
  }
1599

1600
  // Insert scopes created by fake parenthesis.
1601
  const FormatToken *Previous = Current.getPreviousNonComment();
1602

1603
  // Add special behavior to support a format commonly used for JavaScript
1604
  // closures:
1605
  //   SomeFunction(function() {
1606
  //     foo();
1607
  //     bar();
1608
  //   }, a, b, c);
1609
  if (Current.isNot(tok::comment) && !Current.ClosesRequiresClause &&
1610
      Previous && Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
1611
      Previous->isNot(TT_DictLiteral) && State.Stack.size() > 1 &&
1612
      !CurrentState.HasMultipleNestedBlocks) {
1613
    if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)
1614
      for (ParenState &PState : llvm::drop_end(State.Stack))
1615
        PState.NoLineBreak = true;
1616
    State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
1617
  }
1618
  if (Previous && (Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr) ||
1619
                   (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) &&
1620
                    !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))) {
1621
    CurrentState.NestedBlockInlined =
1622
        !Newline && hasNestedBlockInlined(Previous, Current, Style);
1623
  }
1624

1625
  moveStatePastFakeLParens(State, Newline);
1626
  moveStatePastScopeCloser(State);
1627
  // Do not use CurrentState here, since the two functions before may change the
1628
  // Stack.
1629
  bool AllowBreak = !State.Stack.back().NoLineBreak &&
1630
                    !State.Stack.back().NoLineBreakInOperand;
1631
  moveStatePastScopeOpener(State, Newline);
1632
  moveStatePastFakeRParens(State);
1633

1634
  if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0)
1635
    State.StartOfStringLiteral = State.Column + 1;
1636
  if (Current.is(TT_CSharpStringLiteral) && State.StartOfStringLiteral == 0) {
1637
    State.StartOfStringLiteral = State.Column + 1;
1638
  } else if (Current.is(TT_TableGenMultiLineString) &&
1639
             State.StartOfStringLiteral == 0) {
1640
    State.StartOfStringLiteral = State.Column + 1;
1641
  } else if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {
1642
    State.StartOfStringLiteral = State.Column;
1643
  } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
1644
             !Current.isStringLiteral()) {
1645
    State.StartOfStringLiteral = 0;
1646
  }
1647

1648
  State.Column += Current.ColumnWidth;
1649
  State.NextToken = State.NextToken->Next;
1650
  // Verilog case labels are on the same unwrapped lines as the statements that
1651
  // follow. TokenAnnotator identifies them and sets MustBreakBefore.
1652
  // Indentation is taken care of here. A case label can only have 1 statement
1653
  // in Verilog, so we don't have to worry about lines that follow.
1654
  if (Style.isVerilog() && State.NextToken &&
1655
      State.NextToken->MustBreakBefore &&
1656
      Keywords.isVerilogEndOfLabel(Current)) {
1657
    State.FirstIndent += Style.IndentWidth;
1658
    CurrentState.Indent = State.FirstIndent;
1659
  }
1660

1661
  unsigned Penalty =
1662
      handleEndOfLine(Current, State, DryRun, AllowBreak, Newline);
1663

1664
  if (Current.Role)
1665
    Current.Role->formatFromToken(State, this, DryRun);
1666
  // If the previous has a special role, let it consume tokens as appropriate.
1667
  // It is necessary to start at the previous token for the only implemented
1668
  // role (comma separated list). That way, the decision whether or not to break
1669
  // after the "{" is already done and both options are tried and evaluated.
1670
  // FIXME: This is ugly, find a better way.
1671
  if (Previous && Previous->Role)
1672
    Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
1673

1674
  return Penalty;
1675
}
1676

1677
void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
1678
                                                    bool Newline) {
1679
  const FormatToken &Current = *State.NextToken;
1680
  if (Current.FakeLParens.empty())
1681
    return;
1682

1683
  const FormatToken *Previous = Current.getPreviousNonComment();
1684

1685
  // Don't add extra indentation for the first fake parenthesis after
1686
  // 'return', assignments, opening <({[, or requires clauses. The indentation
1687
  // for these cases is special cased.
1688
  bool SkipFirstExtraIndent =
1689
      Previous &&
1690
      (Previous->opensScope() ||
1691
       Previous->isOneOf(tok::semi, tok::kw_return, TT_RequiresClause) ||
1692
       (Previous->getPrecedence() == prec::Assignment &&
1693
        Style.AlignOperands != FormatStyle::OAS_DontAlign) ||
1694
       Previous->is(TT_ObjCMethodExpr));
1695
  for (const auto &PrecedenceLevel : llvm::reverse(Current.FakeLParens)) {
1696
    const auto &CurrentState = State.Stack.back();
1697
    ParenState NewParenState = CurrentState;
1698
    NewParenState.Tok = nullptr;
1699
    NewParenState.ContainsLineBreak = false;
1700
    NewParenState.LastOperatorWrapped = true;
1701
    NewParenState.IsChainedConditional = false;
1702
    NewParenState.IsWrappedConditional = false;
1703
    NewParenState.UnindentOperator = false;
1704
    NewParenState.NoLineBreak =
1705
        NewParenState.NoLineBreak || CurrentState.NoLineBreakInOperand;
1706

1707
    // Don't propagate AvoidBinPacking into subexpressions of arg/param lists.
1708
    if (PrecedenceLevel > prec::Comma)
1709
      NewParenState.AvoidBinPacking = false;
1710

1711
    // Indent from 'LastSpace' unless these are fake parentheses encapsulating
1712
    // a builder type call after 'return' or, if the alignment after opening
1713
    // brackets is disabled.
1714
    if (!Current.isTrailingComment() &&
1715
        (Style.AlignOperands != FormatStyle::OAS_DontAlign ||
1716
         PrecedenceLevel < prec::Assignment) &&
1717
        (!Previous || Previous->isNot(tok::kw_return) ||
1718
         (Style.Language != FormatStyle::LK_Java && PrecedenceLevel > 0)) &&
1719
        (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign ||
1720
         PrecedenceLevel > prec::Comma || Current.NestingLevel == 0) &&
1721
        (!Style.isTableGen() ||
1722
         (Previous && Previous->isOneOf(TT_TableGenDAGArgListComma,
1723
                                        TT_TableGenDAGArgListCommaToBreak)))) {
1724
      NewParenState.Indent = std::max(
1725
          std::max(State.Column, NewParenState.Indent), CurrentState.LastSpace);
1726
    }
1727

1728
    // Special case for generic selection expressions, its comma-separated
1729
    // expressions are not aligned to the opening paren like regular calls, but
1730
    // rather continuation-indented relative to the _Generic keyword.
1731
    if (Previous && Previous->endsSequence(tok::l_paren, tok::kw__Generic) &&
1732
        State.Stack.size() > 1) {
1733
      NewParenState.Indent = State.Stack[State.Stack.size() - 2].Indent +
1734
                             Style.ContinuationIndentWidth;
1735
    }
1736

1737
    if ((shouldUnindentNextOperator(Current) ||
1738
         (Previous &&
1739
          (PrecedenceLevel == prec::Conditional &&
1740
           Previous->is(tok::question) && Previous->is(TT_ConditionalExpr)))) &&
1741
        !Newline) {
1742
      // If BreakBeforeBinaryOperators is set, un-indent a bit to account for
1743
      // the operator and keep the operands aligned.
1744
      if (Style.AlignOperands == FormatStyle::OAS_AlignAfterOperator)
1745
        NewParenState.UnindentOperator = true;
1746
      // Mark indentation as alignment if the expression is aligned.
1747
      if (Style.AlignOperands != FormatStyle::OAS_DontAlign)
1748
        NewParenState.IsAligned = true;
1749
    }
1750

1751
    // Do not indent relative to the fake parentheses inserted for "." or "->".
1752
    // This is a special case to make the following to statements consistent:
1753
    //   OuterFunction(InnerFunctionCall( // break
1754
    //       ParameterToInnerFunction));
1755
    //   OuterFunction(SomeObject.InnerFunctionCall( // break
1756
    //       ParameterToInnerFunction));
1757
    if (PrecedenceLevel > prec::Unknown)
1758
      NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
1759
    if (PrecedenceLevel != prec::Conditional &&
1760
        Current.isNot(TT_UnaryOperator) &&
1761
        Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign) {
1762
      NewParenState.StartOfFunctionCall = State.Column;
1763
    }
1764

1765
    // Indent conditional expressions, unless they are chained "else-if"
1766
    // conditionals. Never indent expression where the 'operator' is ',', ';' or
1767
    // an assignment (i.e. *I <= prec::Assignment) as those have different
1768
    // indentation rules. Indent other expression, unless the indentation needs
1769
    // to be skipped.
1770
    if (PrecedenceLevel == prec::Conditional && Previous &&
1771
        Previous->is(tok::colon) && Previous->is(TT_ConditionalExpr) &&
1772
        &PrecedenceLevel == &Current.FakeLParens.back() &&
1773
        !CurrentState.IsWrappedConditional) {
1774
      NewParenState.IsChainedConditional = true;
1775
      NewParenState.UnindentOperator = State.Stack.back().UnindentOperator;
1776
    } else if (PrecedenceLevel == prec::Conditional ||
1777
               (!SkipFirstExtraIndent && PrecedenceLevel > prec::Assignment &&
1778
                !Current.isTrailingComment())) {
1779
      NewParenState.Indent += Style.ContinuationIndentWidth;
1780
    }
1781
    if ((Previous && !Previous->opensScope()) || PrecedenceLevel != prec::Comma)
1782
      NewParenState.BreakBeforeParameter = false;
1783
    State.Stack.push_back(NewParenState);
1784
    SkipFirstExtraIndent = false;
1785
  }
1786
}
1787

1788
void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
1789
  for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {
1790
    unsigned VariablePos = State.Stack.back().VariablePos;
1791
    if (State.Stack.size() == 1) {
1792
      // Do not pop the last element.
1793
      break;
1794
    }
1795
    State.Stack.pop_back();
1796
    State.Stack.back().VariablePos = VariablePos;
1797
  }
1798

1799
  if (State.NextToken->ClosesRequiresClause && Style.IndentRequiresClause) {
1800
    // Remove the indentation of the requires clauses (which is not in Indent,
1801
    // but in LastSpace).
1802
    State.Stack.back().LastSpace -= Style.IndentWidth;
1803
  }
1804
}
1805

1806
void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
1807
                                                    bool Newline) {
1808
  const FormatToken &Current = *State.NextToken;
1809
  if (!Current.opensScope())
1810
    return;
1811

1812
  const auto &CurrentState = State.Stack.back();
1813

1814
  // Don't allow '<' or '(' in C# generic type constraints to start new scopes.
1815
  if (Current.isOneOf(tok::less, tok::l_paren) &&
1816
      CurrentState.IsCSharpGenericTypeConstraint) {
1817
    return;
1818
  }
1819

1820
  if (Current.MatchingParen && Current.is(BK_Block)) {
1821
    moveStateToNewBlock(State, Newline);
1822
    return;
1823
  }
1824

1825
  unsigned NewIndent;
1826
  unsigned LastSpace = CurrentState.LastSpace;
1827
  bool AvoidBinPacking;
1828
  bool BreakBeforeParameter = false;
1829
  unsigned NestedBlockIndent = std::max(CurrentState.StartOfFunctionCall,
1830
                                        CurrentState.NestedBlockIndent);
1831
  if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
1832
      opensProtoMessageField(Current, Style)) {
1833
    if (Current.opensBlockOrBlockTypeList(Style)) {
1834
      NewIndent = Style.IndentWidth +
1835
                  std::min(State.Column, CurrentState.NestedBlockIndent);
1836
    } else if (Current.is(tok::l_brace)) {
1837
      NewIndent =
1838
          CurrentState.LastSpace + Style.BracedInitializerIndentWidth.value_or(
1839
                                       Style.ContinuationIndentWidth);
1840
    } else {
1841
      NewIndent = CurrentState.LastSpace + Style.ContinuationIndentWidth;
1842
    }
1843
    const FormatToken *NextNonComment = Current.getNextNonComment();
1844
    bool EndsInComma = Current.MatchingParen &&
1845
                       Current.MatchingParen->Previous &&
1846
                       Current.MatchingParen->Previous->is(tok::comma);
1847
    AvoidBinPacking = EndsInComma || Current.is(TT_DictLiteral) ||
1848
                      Style.isProto() || !Style.BinPackArguments ||
1849
                      (NextNonComment && NextNonComment->isOneOf(
1850
                                             TT_DesignatedInitializerPeriod,
1851
                                             TT_DesignatedInitializerLSquare));
1852
    BreakBeforeParameter = EndsInComma;
1853
    if (Current.ParameterCount > 1)
1854
      NestedBlockIndent = std::max(NestedBlockIndent, State.Column + 1);
1855
  } else {
1856
    NewIndent =
1857
        Style.ContinuationIndentWidth +
1858
        std::max(CurrentState.LastSpace, CurrentState.StartOfFunctionCall);
1859

1860
    if (Style.isTableGen() && Current.is(TT_TableGenDAGArgOpenerToBreak) &&
1861
        Style.TableGenBreakInsideDAGArg == FormatStyle::DAS_BreakElements) {
1862
      // For the case the next token is a TableGen DAGArg operator identifier
1863
      // that is not marked to have a line break after it.
1864
      // In this case the option DAS_BreakElements requires to align the
1865
      // DAGArg elements to the operator.
1866
      const FormatToken *Next = Current.Next;
1867
      if (Next && Next->is(TT_TableGenDAGArgOperatorID))
1868
        NewIndent = State.Column + Next->TokenText.size() + 2;
1869
    }
1870

1871
    // Ensure that different different brackets force relative alignment, e.g.:
1872
    // void SomeFunction(vector<  // break
1873
    //                       int> v);
1874
    // FIXME: We likely want to do this for more combinations of brackets.
1875
    if (Current.is(tok::less) && Current.ParentBracket == tok::l_paren) {
1876
      NewIndent = std::max(NewIndent, CurrentState.Indent);
1877
      LastSpace = std::max(LastSpace, CurrentState.Indent);
1878
    }
1879

1880
    bool EndsInComma =
1881
        Current.MatchingParen &&
1882
        Current.MatchingParen->getPreviousNonComment() &&
1883
        Current.MatchingParen->getPreviousNonComment()->is(tok::comma);
1884

1885
    // If ObjCBinPackProtocolList is unspecified, fall back to BinPackParameters
1886
    // for backwards compatibility.
1887
    bool ObjCBinPackProtocolList =
1888
        (Style.ObjCBinPackProtocolList == FormatStyle::BPS_Auto &&
1889
         Style.BinPackParameters) ||
1890
        Style.ObjCBinPackProtocolList == FormatStyle::BPS_Always;
1891

1892
    bool BinPackDeclaration =
1893
        (State.Line->Type != LT_ObjCDecl && Style.BinPackParameters) ||
1894
        (State.Line->Type == LT_ObjCDecl && ObjCBinPackProtocolList);
1895

1896
    bool GenericSelection =
1897
        Current.getPreviousNonComment() &&
1898
        Current.getPreviousNonComment()->is(tok::kw__Generic);
1899

1900
    AvoidBinPacking =
1901
        (CurrentState.IsCSharpGenericTypeConstraint) || GenericSelection ||
1902
        (Style.isJavaScript() && EndsInComma) ||
1903
        (State.Line->MustBeDeclaration && !BinPackDeclaration) ||
1904
        (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
1905
        (Style.ExperimentalAutoDetectBinPacking &&
1906
         (Current.is(PPK_OnePerLine) ||
1907
          (!BinPackInconclusiveFunctions && Current.is(PPK_Inconclusive))));
1908

1909
    if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen &&
1910
        Style.ObjCBreakBeforeNestedBlockParam) {
1911
      if (Style.ColumnLimit) {
1912
        // If this '[' opens an ObjC call, determine whether all parameters fit
1913
        // into one line and put one per line if they don't.
1914
        if (getLengthToMatchingParen(Current, State.Stack) + State.Column >
1915
            getColumnLimit(State)) {
1916
          BreakBeforeParameter = true;
1917
        }
1918
      } else {
1919
        // For ColumnLimit = 0, we have to figure out whether there is or has to
1920
        // be a line break within this call.
1921
        for (const FormatToken *Tok = &Current;
1922
             Tok && Tok != Current.MatchingParen; Tok = Tok->Next) {
1923
          if (Tok->MustBreakBefore ||
1924
              (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) {
1925
            BreakBeforeParameter = true;
1926
            break;
1927
          }
1928
        }
1929
      }
1930
    }
1931

1932
    if (Style.isJavaScript() && EndsInComma)
1933
      BreakBeforeParameter = true;
1934
  }
1935
  // Generally inherit NoLineBreak from the current scope to nested scope.
1936
  // However, don't do this for non-empty nested blocks, dict literals and
1937
  // array literals as these follow different indentation rules.
1938
  bool NoLineBreak =
1939
      Current.Children.empty() &&
1940
      !Current.isOneOf(TT_DictLiteral, TT_ArrayInitializerLSquare) &&
1941
      (CurrentState.NoLineBreak || CurrentState.NoLineBreakInOperand ||
1942
       (Current.is(TT_TemplateOpener) &&
1943
        CurrentState.ContainsUnwrappedBuilder));
1944
  State.Stack.push_back(
1945
      ParenState(&Current, NewIndent, LastSpace, AvoidBinPacking, NoLineBreak));
1946
  auto &NewState = State.Stack.back();
1947
  NewState.NestedBlockIndent = NestedBlockIndent;
1948
  NewState.BreakBeforeParameter = BreakBeforeParameter;
1949
  NewState.HasMultipleNestedBlocks = (Current.BlockParameterCount > 1);
1950

1951
  if (Style.BraceWrapping.BeforeLambdaBody && Current.Next &&
1952
      Current.is(tok::l_paren)) {
1953
    // Search for any parameter that is a lambda.
1954
    FormatToken const *next = Current.Next;
1955
    while (next) {
1956
      if (next->is(TT_LambdaLSquare)) {
1957
        NewState.HasMultipleNestedBlocks = true;
1958
        break;
1959
      }
1960
      next = next->Next;
1961
    }
1962
  }
1963

1964
  NewState.IsInsideObjCArrayLiteral = Current.is(TT_ArrayInitializerLSquare) &&
1965
                                      Current.Previous &&
1966
                                      Current.Previous->is(tok::at);
1967
}
1968

1969
void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
1970
  const FormatToken &Current = *State.NextToken;
1971
  if (!Current.closesScope())
1972
    return;
1973

1974
  // If we encounter a closing ), ], } or >, we can remove a level from our
1975
  // stacks.
1976
  if (State.Stack.size() > 1 &&
1977
      (Current.isOneOf(tok::r_paren, tok::r_square, TT_TemplateString) ||
1978
       (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
1979
       State.NextToken->is(TT_TemplateCloser) ||
1980
       State.NextToken->is(TT_TableGenListCloser) ||
1981
       (Current.is(tok::greater) && Current.is(TT_DictLiteral)))) {
1982
    State.Stack.pop_back();
1983
  }
1984

1985
  auto &CurrentState = State.Stack.back();
1986

1987
  // Reevaluate whether ObjC message arguments fit into one line.
1988
  // If a receiver spans multiple lines, e.g.:
1989
  //   [[object block:^{
1990
  //     return 42;
1991
  //   }] a:42 b:42];
1992
  // BreakBeforeParameter is calculated based on an incorrect assumption
1993
  // (it is checked whether the whole expression fits into one line without
1994
  // considering a line break inside a message receiver).
1995
  // We check whether arguments fit after receiver scope closer (into the same
1996
  // line).
1997
  if (CurrentState.BreakBeforeParameter && Current.MatchingParen &&
1998
      Current.MatchingParen->Previous) {
1999
    const FormatToken &CurrentScopeOpener = *Current.MatchingParen->Previous;
2000
    if (CurrentScopeOpener.is(TT_ObjCMethodExpr) &&
2001
        CurrentScopeOpener.MatchingParen) {
2002
      int NecessarySpaceInLine =
2003
          getLengthToMatchingParen(CurrentScopeOpener, State.Stack) +
2004
          CurrentScopeOpener.TotalLength - Current.TotalLength - 1;
2005
      if (State.Column + Current.ColumnWidth + NecessarySpaceInLine <=
2006
          Style.ColumnLimit) {
2007
        CurrentState.BreakBeforeParameter = false;
2008
      }
2009
    }
2010
  }
2011

2012
  if (Current.is(tok::r_square)) {
2013
    // If this ends the array subscript expr, reset the corresponding value.
2014
    const FormatToken *NextNonComment = Current.getNextNonComment();
2015
    if (NextNonComment && NextNonComment->isNot(tok::l_square))
2016
      CurrentState.StartOfArraySubscripts = 0;
2017
  }
2018
}
2019

2020
void ContinuationIndenter::moveStateToNewBlock(LineState &State, bool NewLine) {
2021
  if (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&
2022
      State.NextToken->is(TT_LambdaLBrace) &&
2023
      !State.Line->MightBeFunctionDecl) {
2024
    State.Stack.back().NestedBlockIndent = State.FirstIndent;
2025
  }
2026
  unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
2027
  // ObjC block sometimes follow special indentation rules.
2028
  unsigned NewIndent =
2029
      NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace)
2030
                               ? Style.ObjCBlockIndentWidth
2031
                               : Style.IndentWidth);
2032

2033
  // Even when wrapping before lambda body, the left brace can still be added to
2034
  // the same line. This occurs when checking whether the whole lambda body can
2035
  // go on a single line. In this case we have to make sure there are no line
2036
  // breaks in the body, otherwise we could just end up with a regular lambda
2037
  // body without the brace wrapped.
2038
  bool NoLineBreak = Style.BraceWrapping.BeforeLambdaBody && !NewLine &&
2039
                     State.NextToken->is(TT_LambdaLBrace);
2040

2041
  State.Stack.push_back(ParenState(State.NextToken, NewIndent,
2042
                                   State.Stack.back().LastSpace,
2043
                                   /*AvoidBinPacking=*/true, NoLineBreak));
2044
  State.Stack.back().NestedBlockIndent = NestedBlockIndent;
2045
  State.Stack.back().BreakBeforeParameter = true;
2046
}
2047

2048
static unsigned getLastLineEndColumn(StringRef Text, unsigned StartColumn,
2049
                                     unsigned TabWidth,
2050
                                     encoding::Encoding Encoding) {
2051
  size_t LastNewlinePos = Text.find_last_of("\n");
2052
  if (LastNewlinePos == StringRef::npos) {
2053
    return StartColumn +
2054
           encoding::columnWidthWithTabs(Text, StartColumn, TabWidth, Encoding);
2055
  } else {
2056
    return encoding::columnWidthWithTabs(Text.substr(LastNewlinePos),
2057
                                         /*StartColumn=*/0, TabWidth, Encoding);
2058
  }
2059
}
2060

2061
unsigned ContinuationIndenter::reformatRawStringLiteral(
2062
    const FormatToken &Current, LineState &State,
2063
    const FormatStyle &RawStringStyle, bool DryRun, bool Newline) {
2064
  unsigned StartColumn = State.Column - Current.ColumnWidth;
2065
  StringRef OldDelimiter = *getRawStringDelimiter(Current.TokenText);
2066
  StringRef NewDelimiter =
2067
      getCanonicalRawStringDelimiter(Style, RawStringStyle.Language);
2068
  if (NewDelimiter.empty())
2069
    NewDelimiter = OldDelimiter;
2070
  // The text of a raw string is between the leading 'R"delimiter(' and the
2071
  // trailing 'delimiter)"'.
2072
  unsigned OldPrefixSize = 3 + OldDelimiter.size();
2073
  unsigned OldSuffixSize = 2 + OldDelimiter.size();
2074
  // We create a virtual text environment which expects a null-terminated
2075
  // string, so we cannot use StringRef.
2076
  std::string RawText = std::string(
2077
      Current.TokenText.substr(OldPrefixSize).drop_back(OldSuffixSize));
2078
  if (NewDelimiter != OldDelimiter) {
2079
    // Don't update to the canonical delimiter 'deli' if ')deli"' occurs in the
2080
    // raw string.
2081
    std::string CanonicalDelimiterSuffix = (")" + NewDelimiter + "\"").str();
2082
    if (StringRef(RawText).contains(CanonicalDelimiterSuffix))
2083
      NewDelimiter = OldDelimiter;
2084
  }
2085

2086
  unsigned NewPrefixSize = 3 + NewDelimiter.size();
2087
  unsigned NewSuffixSize = 2 + NewDelimiter.size();
2088

2089
  // The first start column is the column the raw text starts after formatting.
2090
  unsigned FirstStartColumn = StartColumn + NewPrefixSize;
2091

2092
  // The next start column is the intended indentation a line break inside
2093
  // the raw string at level 0. It is determined by the following rules:
2094
  //   - if the content starts on newline, it is one level more than the current
2095
  //     indent, and
2096
  //   - if the content does not start on a newline, it is the first start
2097
  //     column.
2098
  // These rules have the advantage that the formatted content both does not
2099
  // violate the rectangle rule and visually flows within the surrounding
2100
  // source.
2101
  bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n';
2102
  // If this token is the last parameter (checked by looking if it's followed by
2103
  // `)` and is not on a newline, the base the indent off the line's nested
2104
  // block indent. Otherwise, base the indent off the arguments indent, so we
2105
  // can achieve:
2106
  //
2107
  // fffffffffff(1, 2, 3, R"pb(
2108
  //     key1: 1  #
2109
  //     key2: 2)pb");
2110
  //
2111
  // fffffffffff(1, 2, 3,
2112
  //             R"pb(
2113
  //               key1: 1  #
2114
  //               key2: 2
2115
  //             )pb");
2116
  //
2117
  // fffffffffff(1, 2, 3,
2118
  //             R"pb(
2119
  //               key1: 1  #
2120
  //               key2: 2
2121
  //             )pb",
2122
  //             5);
2123
  unsigned CurrentIndent =
2124
      (!Newline && Current.Next && Current.Next->is(tok::r_paren))
2125
          ? State.Stack.back().NestedBlockIndent
2126
          : State.Stack.back().Indent;
2127
  unsigned NextStartColumn = ContentStartsOnNewline
2128
                                 ? CurrentIndent + Style.IndentWidth
2129
                                 : FirstStartColumn;
2130

2131
  // The last start column is the column the raw string suffix starts if it is
2132
  // put on a newline.
2133
  // The last start column is the intended indentation of the raw string postfix
2134
  // if it is put on a newline. It is determined by the following rules:
2135
  //   - if the raw string prefix starts on a newline, it is the column where
2136
  //     that raw string prefix starts, and
2137
  //   - if the raw string prefix does not start on a newline, it is the current
2138
  //     indent.
2139
  unsigned LastStartColumn =
2140
      Current.NewlinesBefore ? FirstStartColumn - NewPrefixSize : CurrentIndent;
2141

2142
  std::pair<tooling::Replacements, unsigned> Fixes = internal::reformat(
2143
      RawStringStyle, RawText, {tooling::Range(0, RawText.size())},
2144
      FirstStartColumn, NextStartColumn, LastStartColumn, "<stdin>",
2145
      /*Status=*/nullptr);
2146

2147
  auto NewCode = applyAllReplacements(RawText, Fixes.first);
2148
  tooling::Replacements NoFixes;
2149
  if (!NewCode)
2150
    return addMultilineToken(Current, State);
2151
  if (!DryRun) {
2152
    if (NewDelimiter != OldDelimiter) {
2153
      // In 'R"delimiter(...', the delimiter starts 2 characters after the start
2154
      // of the token.
2155
      SourceLocation PrefixDelimiterStart =
2156
          Current.Tok.getLocation().getLocWithOffset(2);
2157
      auto PrefixErr = Whitespaces.addReplacement(tooling::Replacement(
2158
          SourceMgr, PrefixDelimiterStart, OldDelimiter.size(), NewDelimiter));
2159
      if (PrefixErr) {
2160
        llvm::errs()
2161
            << "Failed to update the prefix delimiter of a raw string: "
2162
            << llvm::toString(std::move(PrefixErr)) << "\n";
2163
      }
2164
      // In 'R"delimiter(...)delimiter"', the suffix delimiter starts at
2165
      // position length - 1 - |delimiter|.
2166
      SourceLocation SuffixDelimiterStart =
2167
          Current.Tok.getLocation().getLocWithOffset(Current.TokenText.size() -
2168
                                                     1 - OldDelimiter.size());
2169
      auto SuffixErr = Whitespaces.addReplacement(tooling::Replacement(
2170
          SourceMgr, SuffixDelimiterStart, OldDelimiter.size(), NewDelimiter));
2171
      if (SuffixErr) {
2172
        llvm::errs()
2173
            << "Failed to update the suffix delimiter of a raw string: "
2174
            << llvm::toString(std::move(SuffixErr)) << "\n";
2175
      }
2176
    }
2177
    SourceLocation OriginLoc =
2178
        Current.Tok.getLocation().getLocWithOffset(OldPrefixSize);
2179
    for (const tooling::Replacement &Fix : Fixes.first) {
2180
      auto Err = Whitespaces.addReplacement(tooling::Replacement(
2181
          SourceMgr, OriginLoc.getLocWithOffset(Fix.getOffset()),
2182
          Fix.getLength(), Fix.getReplacementText()));
2183
      if (Err) {
2184
        llvm::errs() << "Failed to reformat raw string: "
2185
                     << llvm::toString(std::move(Err)) << "\n";
2186
      }
2187
    }
2188
  }
2189
  unsigned RawLastLineEndColumn = getLastLineEndColumn(
2190
      *NewCode, FirstStartColumn, Style.TabWidth, Encoding);
2191
  State.Column = RawLastLineEndColumn + NewSuffixSize;
2192
  // Since we're updating the column to after the raw string literal here, we
2193
  // have to manually add the penalty for the prefix R"delim( over the column
2194
  // limit.
2195
  unsigned PrefixExcessCharacters =
2196
      StartColumn + NewPrefixSize > Style.ColumnLimit
2197
          ? StartColumn + NewPrefixSize - Style.ColumnLimit
2198
          : 0;
2199
  bool IsMultiline =
2200
      ContentStartsOnNewline || (NewCode->find('\n') != std::string::npos);
2201
  if (IsMultiline) {
2202
    // Break before further function parameters on all levels.
2203
    for (ParenState &Paren : State.Stack)
2204
      Paren.BreakBeforeParameter = true;
2205
  }
2206
  return Fixes.second + PrefixExcessCharacters * Style.PenaltyExcessCharacter;
2207
}
2208

2209
unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
2210
                                                 LineState &State) {
2211
  // Break before further function parameters on all levels.
2212
  for (ParenState &Paren : State.Stack)
2213
    Paren.BreakBeforeParameter = true;
2214

2215
  unsigned ColumnsUsed = State.Column;
2216
  // We can only affect layout of the first and the last line, so the penalty
2217
  // for all other lines is constant, and we ignore it.
2218
  State.Column = Current.LastLineColumnWidth;
2219

2220
  if (ColumnsUsed > getColumnLimit(State))
2221
    return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
2222
  return 0;
2223
}
2224

2225
unsigned ContinuationIndenter::handleEndOfLine(const FormatToken &Current,
2226
                                               LineState &State, bool DryRun,
2227
                                               bool AllowBreak, bool Newline) {
2228
  unsigned Penalty = 0;
2229
  // Compute the raw string style to use in case this is a raw string literal
2230
  // that can be reformatted.
2231
  auto RawStringStyle = getRawStringStyle(Current, State);
2232
  if (RawStringStyle && !Current.Finalized) {
2233
    Penalty = reformatRawStringLiteral(Current, State, *RawStringStyle, DryRun,
2234
                                       Newline);
2235
  } else if (Current.IsMultiline && Current.isNot(TT_BlockComment)) {
2236
    // Don't break multi-line tokens other than block comments and raw string
2237
    // literals. Instead, just update the state.
2238
    Penalty = addMultilineToken(Current, State);
2239
  } else if (State.Line->Type != LT_ImportStatement) {
2240
    // We generally don't break import statements.
2241
    LineState OriginalState = State;
2242

2243
    // Whether we force the reflowing algorithm to stay strictly within the
2244
    // column limit.
2245
    bool Strict = false;
2246
    // Whether the first non-strict attempt at reflowing did intentionally
2247
    // exceed the column limit.
2248
    bool Exceeded = false;
2249
    std::tie(Penalty, Exceeded) = breakProtrudingToken(
2250
        Current, State, AllowBreak, /*DryRun=*/true, Strict);
2251
    if (Exceeded) {
2252
      // If non-strict reflowing exceeds the column limit, try whether strict
2253
      // reflowing leads to an overall lower penalty.
2254
      LineState StrictState = OriginalState;
2255
      unsigned StrictPenalty =
2256
          breakProtrudingToken(Current, StrictState, AllowBreak,
2257
                               /*DryRun=*/true, /*Strict=*/true)
2258
              .first;
2259
      Strict = StrictPenalty <= Penalty;
2260
      if (Strict) {
2261
        Penalty = StrictPenalty;
2262
        State = StrictState;
2263
      }
2264
    }
2265
    if (!DryRun) {
2266
      // If we're not in dry-run mode, apply the changes with the decision on
2267
      // strictness made above.
2268
      breakProtrudingToken(Current, OriginalState, AllowBreak, /*DryRun=*/false,
2269
                           Strict);
2270
    }
2271
  }
2272
  if (State.Column > getColumnLimit(State)) {
2273
    unsigned ExcessCharacters = State.Column - getColumnLimit(State);
2274
    Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
2275
  }
2276
  return Penalty;
2277
}
2278

2279
// Returns the enclosing function name of a token, or the empty string if not
2280
// found.
2281
static StringRef getEnclosingFunctionName(const FormatToken &Current) {
2282
  // Look for: 'function(' or 'function<templates>(' before Current.
2283
  auto Tok = Current.getPreviousNonComment();
2284
  if (!Tok || Tok->isNot(tok::l_paren))
2285
    return "";
2286
  Tok = Tok->getPreviousNonComment();
2287
  if (!Tok)
2288
    return "";
2289
  if (Tok->is(TT_TemplateCloser)) {
2290
    Tok = Tok->MatchingParen;
2291
    if (Tok)
2292
      Tok = Tok->getPreviousNonComment();
2293
  }
2294
  if (!Tok || Tok->isNot(tok::identifier))
2295
    return "";
2296
  return Tok->TokenText;
2297
}
2298

2299
std::optional<FormatStyle>
2300
ContinuationIndenter::getRawStringStyle(const FormatToken &Current,
2301
                                        const LineState &State) {
2302
  if (!Current.isStringLiteral())
2303
    return std::nullopt;
2304
  auto Delimiter = getRawStringDelimiter(Current.TokenText);
2305
  if (!Delimiter)
2306
    return std::nullopt;
2307
  auto RawStringStyle = RawStringFormats.getDelimiterStyle(*Delimiter);
2308
  if (!RawStringStyle && Delimiter->empty()) {
2309
    RawStringStyle = RawStringFormats.getEnclosingFunctionStyle(
2310
        getEnclosingFunctionName(Current));
2311
  }
2312
  if (!RawStringStyle)
2313
    return std::nullopt;
2314
  RawStringStyle->ColumnLimit = getColumnLimit(State);
2315
  return RawStringStyle;
2316
}
2317

2318
std::unique_ptr<BreakableToken>
2319
ContinuationIndenter::createBreakableToken(const FormatToken &Current,
2320
                                           LineState &State, bool AllowBreak) {
2321
  unsigned StartColumn = State.Column - Current.ColumnWidth;
2322
  if (Current.isStringLiteral()) {
2323
    // Strings in JSON cannot be broken. Breaking strings in JavaScript is
2324
    // disabled for now.
2325
    if (Style.isJson() || Style.isJavaScript() || !Style.BreakStringLiterals ||
2326
        !AllowBreak) {
2327
      return nullptr;
2328
    }
2329

2330
    // Don't break string literals inside preprocessor directives (except for
2331
    // #define directives, as their contents are stored in separate lines and
2332
    // are not affected by this check).
2333
    // This way we avoid breaking code with line directives and unknown
2334
    // preprocessor directives that contain long string literals.
2335
    if (State.Line->Type == LT_PreprocessorDirective)
2336
      return nullptr;
2337
    // Exempts unterminated string literals from line breaking. The user will
2338
    // likely want to terminate the string before any line breaking is done.
2339
    if (Current.IsUnterminatedLiteral)
2340
      return nullptr;
2341
    // Don't break string literals inside Objective-C array literals (doing so
2342
    // raises the warning -Wobjc-string-concatenation).
2343
    if (State.Stack.back().IsInsideObjCArrayLiteral)
2344
      return nullptr;
2345

2346
    // The "DPI"/"DPI-C" in SystemVerilog direct programming interface
2347
    // imports/exports cannot be split, e.g.
2348
    // `import "DPI" function foo();`
2349
    // FIXME: make this use same infra as C++ import checks
2350
    if (Style.isVerilog() && Current.Previous &&
2351
        Current.Previous->isOneOf(tok::kw_export, Keywords.kw_import)) {
2352
      return nullptr;
2353
    }
2354
    StringRef Text = Current.TokenText;
2355

2356
    // We need this to address the case where there is an unbreakable tail only
2357
    // if certain other formatting decisions have been taken. The
2358
    // UnbreakableTailLength of Current is an overapproximation in that case and
2359
    // we need to be correct here.
2360
    unsigned UnbreakableTailLength = (State.NextToken && canBreak(State))
2361
                                         ? 0
2362
                                         : Current.UnbreakableTailLength;
2363

2364
    if (Style.isVerilog() || Style.Language == FormatStyle::LK_Java ||
2365
        Style.isJavaScript() || Style.isCSharp()) {
2366
      BreakableStringLiteralUsingOperators::QuoteStyleType QuoteStyle;
2367
      if (Style.isJavaScript() && Text.starts_with("'") &&
2368
          Text.ends_with("'")) {
2369
        QuoteStyle = BreakableStringLiteralUsingOperators::SingleQuotes;
2370
      } else if (Style.isCSharp() && Text.starts_with("@\"") &&
2371
                 Text.ends_with("\"")) {
2372
        QuoteStyle = BreakableStringLiteralUsingOperators::AtDoubleQuotes;
2373
      } else if (Text.starts_with("\"") && Text.ends_with("\"")) {
2374
        QuoteStyle = BreakableStringLiteralUsingOperators::DoubleQuotes;
2375
      } else {
2376
        return nullptr;
2377
      }
2378
      return std::make_unique<BreakableStringLiteralUsingOperators>(
2379
          Current, QuoteStyle,
2380
          /*UnindentPlus=*/shouldUnindentNextOperator(Current), StartColumn,
2381
          UnbreakableTailLength, State.Line->InPPDirective, Encoding, Style);
2382
    }
2383

2384
    StringRef Prefix;
2385
    StringRef Postfix;
2386
    // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
2387
    // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
2388
    // reduce the overhead) for each FormatToken, which is a string, so that we
2389
    // don't run multiple checks here on the hot path.
2390
    if ((Text.ends_with(Postfix = "\"") &&
2391
         (Text.starts_with(Prefix = "@\"") || Text.starts_with(Prefix = "\"") ||
2392
          Text.starts_with(Prefix = "u\"") ||
2393
          Text.starts_with(Prefix = "U\"") ||
2394
          Text.starts_with(Prefix = "u8\"") ||
2395
          Text.starts_with(Prefix = "L\""))) ||
2396
        (Text.starts_with(Prefix = "_T(\"") &&
2397
         Text.ends_with(Postfix = "\")"))) {
2398
      return std::make_unique<BreakableStringLiteral>(
2399
          Current, StartColumn, Prefix, Postfix, UnbreakableTailLength,
2400
          State.Line->InPPDirective, Encoding, Style);
2401
    }
2402
  } else if (Current.is(TT_BlockComment)) {
2403
    if (!Style.ReflowComments ||
2404
        // If a comment token switches formatting, like
2405
        // /* clang-format on */, we don't want to break it further,
2406
        // but we may still want to adjust its indentation.
2407
        switchesFormatting(Current)) {
2408
      return nullptr;
2409
    }
2410
    return std::make_unique<BreakableBlockComment>(
2411
        Current, StartColumn, Current.OriginalColumn, !Current.Previous,
2412
        State.Line->InPPDirective, Encoding, Style, Whitespaces.useCRLF());
2413
  } else if (Current.is(TT_LineComment) &&
2414
             (!Current.Previous ||
2415
              Current.Previous->isNot(TT_ImplicitStringLiteral))) {
2416
    bool RegularComments = [&]() {
2417
      for (const FormatToken *T = &Current; T && T->is(TT_LineComment);
2418
           T = T->Next) {
2419
        if (!(T->TokenText.starts_with("//") || T->TokenText.starts_with("#")))
2420
          return false;
2421
      }
2422
      return true;
2423
    }();
2424
    if (!Style.ReflowComments ||
2425
        CommentPragmasRegex.match(Current.TokenText.substr(2)) ||
2426
        switchesFormatting(Current) || !RegularComments) {
2427
      return nullptr;
2428
    }
2429
    return std::make_unique<BreakableLineCommentSection>(
2430
        Current, StartColumn, /*InPPDirective=*/false, Encoding, Style);
2431
  }
2432
  return nullptr;
2433
}
2434

2435
std::pair<unsigned, bool>
2436
ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
2437
                                           LineState &State, bool AllowBreak,
2438
                                           bool DryRun, bool Strict) {
2439
  std::unique_ptr<const BreakableToken> Token =
2440
      createBreakableToken(Current, State, AllowBreak);
2441
  if (!Token)
2442
    return {0, false};
2443
  assert(Token->getLineCount() > 0);
2444
  unsigned ColumnLimit = getColumnLimit(State);
2445
  if (Current.is(TT_LineComment)) {
2446
    // We don't insert backslashes when breaking line comments.
2447
    ColumnLimit = Style.ColumnLimit;
2448
  }
2449
  if (ColumnLimit == 0) {
2450
    // To make the rest of the function easier set the column limit to the
2451
    // maximum, if there should be no limit.
2452
    ColumnLimit = std::numeric_limits<decltype(ColumnLimit)>::max();
2453
  }
2454
  if (Current.UnbreakableTailLength >= ColumnLimit)
2455
    return {0, false};
2456
  // ColumnWidth was already accounted into State.Column before calling
2457
  // breakProtrudingToken.
2458
  unsigned StartColumn = State.Column - Current.ColumnWidth;
2459
  unsigned NewBreakPenalty = Current.isStringLiteral()
2460
                                 ? Style.PenaltyBreakString
2461
                                 : Style.PenaltyBreakComment;
2462
  // Stores whether we intentionally decide to let a line exceed the column
2463
  // limit.
2464
  bool Exceeded = false;
2465
  // Stores whether we introduce a break anywhere in the token.
2466
  bool BreakInserted = Token->introducesBreakBeforeToken();
2467
  // Store whether we inserted a new line break at the end of the previous
2468
  // logical line.
2469
  bool NewBreakBefore = false;
2470
  // We use a conservative reflowing strategy. Reflow starts after a line is
2471
  // broken or the corresponding whitespace compressed. Reflow ends as soon as a
2472
  // line that doesn't get reflown with the previous line is reached.
2473
  bool Reflow = false;
2474
  // Keep track of where we are in the token:
2475
  // Where we are in the content of the current logical line.
2476
  unsigned TailOffset = 0;
2477
  // The column number we're currently at.
2478
  unsigned ContentStartColumn =
2479
      Token->getContentStartColumn(0, /*Break=*/false);
2480
  // The number of columns left in the current logical line after TailOffset.
2481
  unsigned RemainingTokenColumns =
2482
      Token->getRemainingLength(0, TailOffset, ContentStartColumn);
2483
  // Adapt the start of the token, for example indent.
2484
  if (!DryRun)
2485
    Token->adaptStartOfLine(0, Whitespaces);
2486

2487
  unsigned ContentIndent = 0;
2488
  unsigned Penalty = 0;
2489
  LLVM_DEBUG(llvm::dbgs() << "Breaking protruding token at column "
2490
                          << StartColumn << ".\n");
2491
  for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
2492
       LineIndex != EndIndex; ++LineIndex) {
2493
    LLVM_DEBUG(llvm::dbgs()
2494
               << "  Line: " << LineIndex << " (Reflow: " << Reflow << ")\n");
2495
    NewBreakBefore = false;
2496
    // If we did reflow the previous line, we'll try reflowing again. Otherwise
2497
    // we'll start reflowing if the current line is broken or whitespace is
2498
    // compressed.
2499
    bool TryReflow = Reflow;
2500
    // Break the current token until we can fit the rest of the line.
2501
    while (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
2502
      LLVM_DEBUG(llvm::dbgs() << "    Over limit, need: "
2503
                              << (ContentStartColumn + RemainingTokenColumns)
2504
                              << ", space: " << ColumnLimit
2505
                              << ", reflown prefix: " << ContentStartColumn
2506
                              << ", offset in line: " << TailOffset << "\n");
2507
      // If the current token doesn't fit, find the latest possible split in the
2508
      // current line so that breaking at it will be under the column limit.
2509
      // FIXME: Use the earliest possible split while reflowing to correctly
2510
      // compress whitespace within a line.
2511
      BreakableToken::Split Split =
2512
          Token->getSplit(LineIndex, TailOffset, ColumnLimit,
2513
                          ContentStartColumn, CommentPragmasRegex);
2514
      if (Split.first == StringRef::npos) {
2515
        // No break opportunity - update the penalty and continue with the next
2516
        // logical line.
2517
        if (LineIndex < EndIndex - 1) {
2518
          // The last line's penalty is handled in addNextStateToQueue() or when
2519
          // calling replaceWhitespaceAfterLastLine below.
2520
          Penalty += Style.PenaltyExcessCharacter *
2521
                     (ContentStartColumn + RemainingTokenColumns - ColumnLimit);
2522
        }
2523
        LLVM_DEBUG(llvm::dbgs() << "    No break opportunity.\n");
2524
        break;
2525
      }
2526
      assert(Split.first != 0);
2527

2528
      if (Token->supportsReflow()) {
2529
        // Check whether the next natural split point after the current one can
2530
        // still fit the line, either because we can compress away whitespace,
2531
        // or because the penalty the excess characters introduce is lower than
2532
        // the break penalty.
2533
        // We only do this for tokens that support reflowing, and thus allow us
2534
        // to change the whitespace arbitrarily (e.g. comments).
2535
        // Other tokens, like string literals, can be broken on arbitrary
2536
        // positions.
2537

2538
        // First, compute the columns from TailOffset to the next possible split
2539
        // position.
2540
        // For example:
2541
        // ColumnLimit:     |
2542
        // // Some text   that    breaks
2543
        //    ^ tail offset
2544
        //             ^-- split
2545
        //    ^-------- to split columns
2546
        //                    ^--- next split
2547
        //    ^--------------- to next split columns
2548
        unsigned ToSplitColumns = Token->getRangeLength(
2549
            LineIndex, TailOffset, Split.first, ContentStartColumn);
2550
        LLVM_DEBUG(llvm::dbgs() << "    ToSplit: " << ToSplitColumns << "\n");
2551

2552
        BreakableToken::Split NextSplit = Token->getSplit(
2553
            LineIndex, TailOffset + Split.first + Split.second, ColumnLimit,
2554
            ContentStartColumn + ToSplitColumns + 1, CommentPragmasRegex);
2555
        // Compute the columns necessary to fit the next non-breakable sequence
2556
        // into the current line.
2557
        unsigned ToNextSplitColumns = 0;
2558
        if (NextSplit.first == StringRef::npos) {
2559
          ToNextSplitColumns = Token->getRemainingLength(LineIndex, TailOffset,
2560
                                                         ContentStartColumn);
2561
        } else {
2562
          ToNextSplitColumns = Token->getRangeLength(
2563
              LineIndex, TailOffset,
2564
              Split.first + Split.second + NextSplit.first, ContentStartColumn);
2565
        }
2566
        // Compress the whitespace between the break and the start of the next
2567
        // unbreakable sequence.
2568
        ToNextSplitColumns =
2569
            Token->getLengthAfterCompression(ToNextSplitColumns, Split);
2570
        LLVM_DEBUG(llvm::dbgs()
2571
                   << "    ContentStartColumn: " << ContentStartColumn << "\n");
2572
        LLVM_DEBUG(llvm::dbgs()
2573
                   << "    ToNextSplit: " << ToNextSplitColumns << "\n");
2574
        // If the whitespace compression makes us fit, continue on the current
2575
        // line.
2576
        bool ContinueOnLine =
2577
            ContentStartColumn + ToNextSplitColumns <= ColumnLimit;
2578
        unsigned ExcessCharactersPenalty = 0;
2579
        if (!ContinueOnLine && !Strict) {
2580
          // Similarly, if the excess characters' penalty is lower than the
2581
          // penalty of introducing a new break, continue on the current line.
2582
          ExcessCharactersPenalty =
2583
              (ContentStartColumn + ToNextSplitColumns - ColumnLimit) *
2584
              Style.PenaltyExcessCharacter;
2585
          LLVM_DEBUG(llvm::dbgs()
2586
                     << "    Penalty excess: " << ExcessCharactersPenalty
2587
                     << "\n            break : " << NewBreakPenalty << "\n");
2588
          if (ExcessCharactersPenalty < NewBreakPenalty) {
2589
            Exceeded = true;
2590
            ContinueOnLine = true;
2591
          }
2592
        }
2593
        if (ContinueOnLine) {
2594
          LLVM_DEBUG(llvm::dbgs() << "    Continuing on line...\n");
2595
          // The current line fits after compressing the whitespace - reflow
2596
          // the next line into it if possible.
2597
          TryReflow = true;
2598
          if (!DryRun) {
2599
            Token->compressWhitespace(LineIndex, TailOffset, Split,
2600
                                      Whitespaces);
2601
          }
2602
          // When we continue on the same line, leave one space between content.
2603
          ContentStartColumn += ToSplitColumns + 1;
2604
          Penalty += ExcessCharactersPenalty;
2605
          TailOffset += Split.first + Split.second;
2606
          RemainingTokenColumns = Token->getRemainingLength(
2607
              LineIndex, TailOffset, ContentStartColumn);
2608
          continue;
2609
        }
2610
      }
2611
      LLVM_DEBUG(llvm::dbgs() << "    Breaking...\n");
2612
      // Update the ContentIndent only if the current line was not reflown with
2613
      // the previous line, since in that case the previous line should still
2614
      // determine the ContentIndent. Also never intent the last line.
2615
      if (!Reflow)
2616
        ContentIndent = Token->getContentIndent(LineIndex);
2617
      LLVM_DEBUG(llvm::dbgs()
2618
                 << "    ContentIndent: " << ContentIndent << "\n");
2619
      ContentStartColumn = ContentIndent + Token->getContentStartColumn(
2620
                                               LineIndex, /*Break=*/true);
2621

2622
      unsigned NewRemainingTokenColumns = Token->getRemainingLength(
2623
          LineIndex, TailOffset + Split.first + Split.second,
2624
          ContentStartColumn);
2625
      if (NewRemainingTokenColumns == 0) {
2626
        // No content to indent.
2627
        ContentIndent = 0;
2628
        ContentStartColumn =
2629
            Token->getContentStartColumn(LineIndex, /*Break=*/true);
2630
        NewRemainingTokenColumns = Token->getRemainingLength(
2631
            LineIndex, TailOffset + Split.first + Split.second,
2632
            ContentStartColumn);
2633
      }
2634

2635
      // When breaking before a tab character, it may be moved by a few columns,
2636
      // but will still be expanded to the next tab stop, so we don't save any
2637
      // columns.
2638
      if (NewRemainingTokenColumns >= RemainingTokenColumns) {
2639
        // FIXME: Do we need to adjust the penalty?
2640
        break;
2641
      }
2642

2643
      LLVM_DEBUG(llvm::dbgs() << "    Breaking at: " << TailOffset + Split.first
2644
                              << ", " << Split.second << "\n");
2645
      if (!DryRun) {
2646
        Token->insertBreak(LineIndex, TailOffset, Split, ContentIndent,
2647
                           Whitespaces);
2648
      }
2649

2650
      Penalty += NewBreakPenalty;
2651
      TailOffset += Split.first + Split.second;
2652
      RemainingTokenColumns = NewRemainingTokenColumns;
2653
      BreakInserted = true;
2654
      NewBreakBefore = true;
2655
    }
2656
    // In case there's another line, prepare the state for the start of the next
2657
    // line.
2658
    if (LineIndex + 1 != EndIndex) {
2659
      unsigned NextLineIndex = LineIndex + 1;
2660
      if (NewBreakBefore) {
2661
        // After breaking a line, try to reflow the next line into the current
2662
        // one once RemainingTokenColumns fits.
2663
        TryReflow = true;
2664
      }
2665
      if (TryReflow) {
2666
        // We decided that we want to try reflowing the next line into the
2667
        // current one.
2668
        // We will now adjust the state as if the reflow is successful (in
2669
        // preparation for the next line), and see whether that works. If we
2670
        // decide that we cannot reflow, we will later reset the state to the
2671
        // start of the next line.
2672
        Reflow = false;
2673
        // As we did not continue breaking the line, RemainingTokenColumns is
2674
        // known to fit after ContentStartColumn. Adapt ContentStartColumn to
2675
        // the position at which we want to format the next line if we do
2676
        // actually reflow.
2677
        // When we reflow, we need to add a space between the end of the current
2678
        // line and the next line's start column.
2679
        ContentStartColumn += RemainingTokenColumns + 1;
2680
        // Get the split that we need to reflow next logical line into the end
2681
        // of the current one; the split will include any leading whitespace of
2682
        // the next logical line.
2683
        BreakableToken::Split SplitBeforeNext =
2684
            Token->getReflowSplit(NextLineIndex, CommentPragmasRegex);
2685
        LLVM_DEBUG(llvm::dbgs()
2686
                   << "    Size of reflown text: " << ContentStartColumn
2687
                   << "\n    Potential reflow split: ");
2688
        if (SplitBeforeNext.first != StringRef::npos) {
2689
          LLVM_DEBUG(llvm::dbgs() << SplitBeforeNext.first << ", "
2690
                                  << SplitBeforeNext.second << "\n");
2691
          TailOffset = SplitBeforeNext.first + SplitBeforeNext.second;
2692
          // If the rest of the next line fits into the current line below the
2693
          // column limit, we can safely reflow.
2694
          RemainingTokenColumns = Token->getRemainingLength(
2695
              NextLineIndex, TailOffset, ContentStartColumn);
2696
          Reflow = true;
2697
          if (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
2698
            LLVM_DEBUG(llvm::dbgs()
2699
                       << "    Over limit after reflow, need: "
2700
                       << (ContentStartColumn + RemainingTokenColumns)
2701
                       << ", space: " << ColumnLimit
2702
                       << ", reflown prefix: " << ContentStartColumn
2703
                       << ", offset in line: " << TailOffset << "\n");
2704
            // If the whole next line does not fit, try to find a point in
2705
            // the next line at which we can break so that attaching the part
2706
            // of the next line to that break point onto the current line is
2707
            // below the column limit.
2708
            BreakableToken::Split Split =
2709
                Token->getSplit(NextLineIndex, TailOffset, ColumnLimit,
2710
                                ContentStartColumn, CommentPragmasRegex);
2711
            if (Split.first == StringRef::npos) {
2712
              LLVM_DEBUG(llvm::dbgs() << "    Did not find later break\n");
2713
              Reflow = false;
2714
            } else {
2715
              // Check whether the first split point gets us below the column
2716
              // limit. Note that we will execute this split below as part of
2717
              // the normal token breaking and reflow logic within the line.
2718
              unsigned ToSplitColumns = Token->getRangeLength(
2719
                  NextLineIndex, TailOffset, Split.first, ContentStartColumn);
2720
              if (ContentStartColumn + ToSplitColumns > ColumnLimit) {
2721
                LLVM_DEBUG(llvm::dbgs() << "    Next split protrudes, need: "
2722
                                        << (ContentStartColumn + ToSplitColumns)
2723
                                        << ", space: " << ColumnLimit);
2724
                unsigned ExcessCharactersPenalty =
2725
                    (ContentStartColumn + ToSplitColumns - ColumnLimit) *
2726
                    Style.PenaltyExcessCharacter;
2727
                if (NewBreakPenalty < ExcessCharactersPenalty)
2728
                  Reflow = false;
2729
              }
2730
            }
2731
          }
2732
        } else {
2733
          LLVM_DEBUG(llvm::dbgs() << "not found.\n");
2734
        }
2735
      }
2736
      if (!Reflow) {
2737
        // If we didn't reflow into the next line, the only space to consider is
2738
        // the next logical line. Reset our state to match the start of the next
2739
        // line.
2740
        TailOffset = 0;
2741
        ContentStartColumn =
2742
            Token->getContentStartColumn(NextLineIndex, /*Break=*/false);
2743
        RemainingTokenColumns = Token->getRemainingLength(
2744
            NextLineIndex, TailOffset, ContentStartColumn);
2745
        // Adapt the start of the token, for example indent.
2746
        if (!DryRun)
2747
          Token->adaptStartOfLine(NextLineIndex, Whitespaces);
2748
      } else {
2749
        // If we found a reflow split and have added a new break before the next
2750
        // line, we are going to remove the line break at the start of the next
2751
        // logical line. For example, here we'll add a new line break after
2752
        // 'text', and subsequently delete the line break between 'that' and
2753
        // 'reflows'.
2754
        //   // some text that
2755
        //   // reflows
2756
        // ->
2757
        //   // some text
2758
        //   // that reflows
2759
        // When adding the line break, we also added the penalty for it, so we
2760
        // need to subtract that penalty again when we remove the line break due
2761
        // to reflowing.
2762
        if (NewBreakBefore) {
2763
          assert(Penalty >= NewBreakPenalty);
2764
          Penalty -= NewBreakPenalty;
2765
        }
2766
        if (!DryRun)
2767
          Token->reflow(NextLineIndex, Whitespaces);
2768
      }
2769
    }
2770
  }
2771

2772
  BreakableToken::Split SplitAfterLastLine =
2773
      Token->getSplitAfterLastLine(TailOffset);
2774
  if (SplitAfterLastLine.first != StringRef::npos) {
2775
    LLVM_DEBUG(llvm::dbgs() << "Replacing whitespace after last line.\n");
2776

2777
    // We add the last line's penalty here, since that line is going to be split
2778
    // now.
2779
    Penalty += Style.PenaltyExcessCharacter *
2780
               (ContentStartColumn + RemainingTokenColumns - ColumnLimit);
2781

2782
    if (!DryRun) {
2783
      Token->replaceWhitespaceAfterLastLine(TailOffset, SplitAfterLastLine,
2784
                                            Whitespaces);
2785
    }
2786
    ContentStartColumn =
2787
        Token->getContentStartColumn(Token->getLineCount() - 1, /*Break=*/true);
2788
    RemainingTokenColumns = Token->getRemainingLength(
2789
        Token->getLineCount() - 1,
2790
        TailOffset + SplitAfterLastLine.first + SplitAfterLastLine.second,
2791
        ContentStartColumn);
2792
  }
2793

2794
  State.Column = ContentStartColumn + RemainingTokenColumns -
2795
                 Current.UnbreakableTailLength;
2796

2797
  if (BreakInserted) {
2798
    if (!DryRun)
2799
      Token->updateAfterBroken(Whitespaces);
2800

2801
    // If we break the token inside a parameter list, we need to break before
2802
    // the next parameter on all levels, so that the next parameter is clearly
2803
    // visible. Line comments already introduce a break.
2804
    if (Current.isNot(TT_LineComment))
2805
      for (ParenState &Paren : State.Stack)
2806
        Paren.BreakBeforeParameter = true;
2807

2808
    if (Current.is(TT_BlockComment))
2809
      State.NoContinuation = true;
2810

2811
    State.Stack.back().LastSpace = StartColumn;
2812
  }
2813

2814
  Token->updateNextToken(State);
2815

2816
  return {Penalty, Exceeded};
2817
}
2818

2819
unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
2820
  // In preprocessor directives reserve two chars for trailing " \".
2821
  return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
2822
}
2823

2824
bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
2825
  const FormatToken &Current = *State.NextToken;
2826
  if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral))
2827
    return false;
2828
  // We never consider raw string literals "multiline" for the purpose of
2829
  // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
2830
  // (see TokenAnnotator::mustBreakBefore().
2831
  if (Current.TokenText.starts_with("R\""))
2832
    return false;
2833
  if (Current.IsMultiline)
2834
    return true;
2835
  if (Current.getNextNonComment() &&
2836
      Current.getNextNonComment()->isStringLiteral()) {
2837
    return true; // Implicit concatenation.
2838
  }
2839
  if (Style.ColumnLimit != 0 && Style.BreakStringLiterals &&
2840
      State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
2841
          Style.ColumnLimit) {
2842
    return true; // String will be split.
2843
  }
2844
  return false;
2845
}
2846

2847
} // namespace format
2848
} // namespace clang
2849

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.