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