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