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