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