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