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