1 //===--- ContinuationIndenter.cpp - Format C++ code -----------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// 10 /// \file 11 /// \brief This file implements the continuation indenter. 12 /// 13 //===----------------------------------------------------------------------===// 14 15 #include "ContinuationIndenter.h" 16 #include "BreakableToken.h" 17 #include "FormatInternal.h" 18 #include "WhitespaceManager.h" 19 #include "clang/Basic/OperatorPrecedence.h" 20 #include "clang/Basic/SourceManager.h" 21 #include "clang/Format/Format.h" 22 #include "llvm/Support/Debug.h" 23 24 #define DEBUG_TYPE "format-indenter" 25 26 namespace clang { 27 namespace format { 28 29 // Returns the length of everything up to the first possible line break after 30 // the ), ], } or > matching \c Tok. 31 static unsigned getLengthToMatchingParen(const FormatToken &Tok) { 32 if (!Tok.MatchingParen) 33 return 0; 34 FormatToken *End = Tok.MatchingParen; 35 while (End->Next && !End->Next->CanBreakBefore) { 36 End = End->Next; 37 } 38 return End->TotalLength - Tok.TotalLength + 1; 39 } 40 41 static unsigned getLengthToNextOperator(const FormatToken &Tok) { 42 if (!Tok.NextOperator) 43 return 0; 44 return Tok.NextOperator->TotalLength - Tok.TotalLength; 45 } 46 47 // Returns \c true if \c Tok is the "." or "->" of a call and starts the next 48 // segment of a builder type call. 49 static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) { 50 return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope(); 51 } 52 53 // Returns \c true if \c Current starts a new parameter. 54 static bool startsNextParameter(const FormatToken &Current, 55 const FormatStyle &Style) { 56 const FormatToken &Previous = *Current.Previous; 57 if (Current.is(TT_CtorInitializerComma) && 58 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) 59 return true; 60 if (Style.Language == FormatStyle::LK_Proto && Current.is(TT_SelectorName)) 61 return true; 62 return Previous.is(tok::comma) && !Current.isTrailingComment() && 63 ((Previous.isNot(TT_CtorInitializerComma) || 64 Style.BreakConstructorInitializers != 65 FormatStyle::BCIS_BeforeComma) && 66 (Previous.isNot(TT_InheritanceComma) || 67 !Style.BreakBeforeInheritanceComma)); 68 } 69 70 static bool opensProtoMessageField(const FormatToken &LessTok, 71 const FormatStyle &Style) { 72 if (LessTok.isNot(tok::less)) 73 return false; 74 return Style.Language == FormatStyle::LK_TextProto || 75 (Style.Language == FormatStyle::LK_Proto && 76 (LessTok.NestingLevel > 0 || 77 (LessTok.Previous && LessTok.Previous->is(tok::equal)))); 78 } 79 80 // Returns the delimiter of a raw string literal, or None if TokenText is not 81 // the text of a raw string literal. The delimiter could be the empty string. 82 // For example, the delimiter of R"deli(cont)deli" is deli. 83 static llvm::Optional<StringRef> getRawStringDelimiter(StringRef TokenText) { 84 if (TokenText.size() < 5 // The smallest raw string possible is 'R"()"'. 85 || !TokenText.startswith("R\"") || !TokenText.endswith("\"")) 86 return None; 87 88 // A raw string starts with 'R"<delimiter>(' and delimiter is ascii and has 89 // size at most 16 by the standard, so the first '(' must be among the first 90 // 19 bytes. 91 size_t LParenPos = TokenText.substr(0, 19).find_first_of('('); 92 if (LParenPos == StringRef::npos) 93 return None; 94 StringRef Delimiter = TokenText.substr(2, LParenPos - 2); 95 96 // Check that the string ends in ')Delimiter"'. 97 size_t RParenPos = TokenText.size() - Delimiter.size() - 2; 98 if (TokenText[RParenPos] != ')') 99 return None; 100 if (!TokenText.substr(RParenPos + 1).startswith(Delimiter)) 101 return None; 102 return Delimiter; 103 } 104 105 // Returns the canonical delimiter for \p Language, or the empty string if no 106 // canonical delimiter is specified. 107 static StringRef 108 getCanonicalRawStringDelimiter(const FormatStyle &Style, 109 FormatStyle::LanguageKind Language) { 110 for (const auto &Format : Style.RawStringFormats) { 111 if (Format.Language == Language) 112 return StringRef(Format.CanonicalDelimiter); 113 } 114 return ""; 115 } 116 117 RawStringFormatStyleManager::RawStringFormatStyleManager( 118 const FormatStyle &CodeStyle) { 119 for (const auto &RawStringFormat : CodeStyle.RawStringFormats) { 120 llvm::Optional<FormatStyle> LanguageStyle = 121 CodeStyle.GetLanguageStyle(RawStringFormat.Language); 122 if (!LanguageStyle) { 123 FormatStyle PredefinedStyle; 124 if (!getPredefinedStyle(RawStringFormat.BasedOnStyle, 125 RawStringFormat.Language, &PredefinedStyle)) { 126 PredefinedStyle = getLLVMStyle(); 127 PredefinedStyle.Language = RawStringFormat.Language; 128 } 129 LanguageStyle = PredefinedStyle; 130 } 131 LanguageStyle->ColumnLimit = CodeStyle.ColumnLimit; 132 for (StringRef Delimiter : RawStringFormat.Delimiters) { 133 DelimiterStyle.insert({Delimiter, *LanguageStyle}); 134 } 135 for (StringRef EnclosingFunction : RawStringFormat.EnclosingFunctions) { 136 EnclosingFunctionStyle.insert({EnclosingFunction, *LanguageStyle}); 137 } 138 } 139 } 140 141 llvm::Optional<FormatStyle> 142 RawStringFormatStyleManager::getDelimiterStyle(StringRef Delimiter) const { 143 auto It = DelimiterStyle.find(Delimiter); 144 if (It == DelimiterStyle.end()) 145 return None; 146 return It->second; 147 } 148 149 llvm::Optional<FormatStyle> 150 RawStringFormatStyleManager::getEnclosingFunctionStyle( 151 StringRef EnclosingFunction) const { 152 auto It = EnclosingFunctionStyle.find(EnclosingFunction); 153 if (It == EnclosingFunctionStyle.end()) 154 return None; 155 return It->second; 156 } 157 158 ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style, 159 const AdditionalKeywords &Keywords, 160 const SourceManager &SourceMgr, 161 WhitespaceManager &Whitespaces, 162 encoding::Encoding Encoding, 163 bool BinPackInconclusiveFunctions) 164 : Style(Style), Keywords(Keywords), SourceMgr(SourceMgr), 165 Whitespaces(Whitespaces), Encoding(Encoding), 166 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions), 167 CommentPragmasRegex(Style.CommentPragmas), RawStringFormats(Style) {} 168 169 LineState ContinuationIndenter::getInitialState(unsigned FirstIndent, 170 unsigned FirstStartColumn, 171 const AnnotatedLine *Line, 172 bool DryRun) { 173 LineState State; 174 State.FirstIndent = FirstIndent; 175 if (FirstStartColumn && Line->First->NewlinesBefore == 0) 176 State.Column = FirstStartColumn; 177 else 178 State.Column = FirstIndent; 179 // With preprocessor directive indentation, the line starts on column 0 180 // since it's indented after the hash, but FirstIndent is set to the 181 // preprocessor indent. 182 if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash && 183 (Line->Type == LT_PreprocessorDirective || 184 Line->Type == LT_ImportStatement)) 185 State.Column = 0; 186 State.Line = Line; 187 State.NextToken = Line->First; 188 State.Stack.push_back(ParenState(FirstIndent, FirstIndent, 189 /*AvoidBinPacking=*/false, 190 /*NoLineBreak=*/false)); 191 State.LineContainsContinuedForLoopSection = false; 192 State.NoContinuation = false; 193 State.StartOfStringLiteral = 0; 194 State.StartOfLineLevel = 0; 195 State.LowestLevelOnLine = 0; 196 State.IgnoreStackForComparison = false; 197 198 if (Style.Language == FormatStyle::LK_TextProto) { 199 // We need this in order to deal with the bin packing of text fields at 200 // global scope. 201 State.Stack.back().AvoidBinPacking = true; 202 State.Stack.back().BreakBeforeParameter = true; 203 State.Stack.back().AlignColons = false; 204 } 205 206 // The first token has already been indented and thus consumed. 207 moveStateToNextToken(State, DryRun, /*Newline=*/false); 208 return State; 209 } 210 211 bool ContinuationIndenter::canBreak(const LineState &State) { 212 const FormatToken &Current = *State.NextToken; 213 const FormatToken &Previous = *Current.Previous; 214 assert(&Previous == Current.Previous); 215 if (!Current.CanBreakBefore && !(State.Stack.back().BreakBeforeClosingBrace && 216 Current.closesBlockOrBlockTypeList(Style))) 217 return false; 218 // The opening "{" of a braced list has to be on the same line as the first 219 // element if it is nested in another braced init list or function call. 220 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) && 221 Previous.isNot(TT_DictLiteral) && Previous.BlockKind == BK_BracedInit && 222 Previous.Previous && 223 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma)) 224 return false; 225 // This prevents breaks like: 226 // ... 227 // SomeParameter, OtherParameter).DoSomething( 228 // ... 229 // As they hide "DoSomething" and are generally bad for readability. 230 if (Previous.opensScope() && Previous.isNot(tok::l_brace) && 231 State.LowestLevelOnLine < State.StartOfLineLevel && 232 State.LowestLevelOnLine < Current.NestingLevel) 233 return false; 234 if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder) 235 return false; 236 237 // Don't create a 'hanging' indent if there are multiple blocks in a single 238 // statement. 239 if (Previous.is(tok::l_brace) && State.Stack.size() > 1 && 240 State.Stack[State.Stack.size() - 2].NestedBlockInlined && 241 State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks) 242 return false; 243 244 // Don't break after very short return types (e.g. "void") as that is often 245 // unexpected. 246 if (Current.is(TT_FunctionDeclarationName) && State.Column < 6) { 247 if (Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None) 248 return false; 249 } 250 251 // If binary operators are moved to the next line (including commas for some 252 // styles of constructor initializers), that's always ok. 253 if (!Current.isOneOf(TT_BinaryOperator, tok::comma) && 254 State.Stack.back().NoLineBreakInOperand) 255 return false; 256 257 return !State.Stack.back().NoLineBreak; 258 } 259 260 bool ContinuationIndenter::mustBreak(const LineState &State) { 261 const FormatToken &Current = *State.NextToken; 262 const FormatToken &Previous = *Current.Previous; 263 if (Current.MustBreakBefore || Current.is(TT_InlineASMColon)) 264 return true; 265 if (State.Stack.back().BreakBeforeClosingBrace && 266 Current.closesBlockOrBlockTypeList(Style)) 267 return true; 268 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection) 269 return true; 270 if (Style.Language == FormatStyle::LK_ObjC && 271 Current.ObjCSelectorNameParts > 1 && 272 Current.startsSequence(TT_SelectorName, tok::colon, tok::caret)) { 273 return true; 274 } 275 if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) || 276 (Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) && 277 Style.isCpp() && 278 // FIXME: This is a temporary workaround for the case where clang-format 279 // sets BreakBeforeParameter to avoid bin packing and this creates a 280 // completely unnecessary line break after a template type that isn't 281 // line-wrapped. 282 (Previous.NestingLevel == 1 || Style.BinPackParameters)) || 283 (Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) && 284 Previous.isNot(tok::question)) || 285 (!Style.BreakBeforeTernaryOperators && 286 Previous.is(TT_ConditionalExpr))) && 287 State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() && 288 !Current.isOneOf(tok::r_paren, tok::r_brace)) 289 return true; 290 if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) || 291 (Previous.is(TT_ArrayInitializerLSquare) && 292 Previous.ParameterCount > 1) || 293 opensProtoMessageField(Previous, Style)) && 294 Style.ColumnLimit > 0 && 295 getLengthToMatchingParen(Previous) + State.Column - 1 > 296 getColumnLimit(State)) 297 return true; 298 299 const FormatToken &BreakConstructorInitializersToken = 300 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon 301 ? Previous 302 : Current; 303 if (BreakConstructorInitializersToken.is(TT_CtorInitializerColon) && 304 (State.Column + State.Line->Last->TotalLength - Previous.TotalLength > 305 getColumnLimit(State) || 306 State.Stack.back().BreakBeforeParameter) && 307 (Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All || 308 Style.BreakConstructorInitializers != FormatStyle::BCIS_BeforeColon || 309 Style.ColumnLimit != 0)) 310 return true; 311 312 if (Current.is(TT_ObjCMethodExpr) && !Previous.is(TT_SelectorName) && 313 State.Line->startsWith(TT_ObjCMethodSpecifier)) 314 return true; 315 if (Current.is(TT_SelectorName) && State.Stack.back().ObjCSelectorNameFound && 316 State.Stack.back().BreakBeforeParameter) 317 return true; 318 319 unsigned NewLineColumn = getNewLineColumn(State); 320 if (Current.isMemberAccess() && Style.ColumnLimit != 0 && 321 State.Column + getLengthToNextOperator(Current) > Style.ColumnLimit && 322 (State.Column > NewLineColumn || 323 Current.NestingLevel < State.StartOfLineLevel)) 324 return true; 325 326 if (startsSegmentOfBuilderTypeCall(Current) && 327 (State.Stack.back().CallContinuation != 0 || 328 State.Stack.back().BreakBeforeParameter) && 329 // JavaScript is treated different here as there is a frequent pattern: 330 // SomeFunction(function() { 331 // ... 332 // }.bind(...)); 333 // FIXME: We should find a more generic solution to this problem. 334 !(State.Column <= NewLineColumn && 335 Style.Language == FormatStyle::LK_JavaScript)) 336 return true; 337 338 if (State.Column <= NewLineColumn) 339 return false; 340 341 if (Style.AlwaysBreakBeforeMultilineStrings && 342 (NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth || 343 Previous.is(tok::comma) || Current.NestingLevel < 2) && 344 !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) && 345 !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) && 346 nextIsMultilineString(State)) 347 return true; 348 349 // Using CanBreakBefore here and below takes care of the decision whether the 350 // current style uses wrapping before or after operators for the given 351 // operator. 352 if (Previous.is(TT_BinaryOperator) && Current.CanBreakBefore) { 353 // If we need to break somewhere inside the LHS of a binary expression, we 354 // should also break after the operator. Otherwise, the formatting would 355 // hide the operator precedence, e.g. in: 356 // if (aaaaaaaaaaaaaa == 357 // bbbbbbbbbbbbbb && c) {.. 358 // For comparisons, we only apply this rule, if the LHS is a binary 359 // expression itself as otherwise, the line breaks seem superfluous. 360 // We need special cases for ">>" which we have split into two ">" while 361 // lexing in order to make template parsing easier. 362 bool IsComparison = (Previous.getPrecedence() == prec::Relational || 363 Previous.getPrecedence() == prec::Equality || 364 Previous.getPrecedence() == prec::Spaceship) && 365 Previous.Previous && 366 Previous.Previous->isNot(TT_BinaryOperator); // For >>. 367 bool LHSIsBinaryExpr = 368 Previous.Previous && Previous.Previous->EndsBinaryExpression; 369 if ((!IsComparison || LHSIsBinaryExpr) && !Current.isTrailingComment() && 370 Previous.getPrecedence() != prec::Assignment && 371 State.Stack.back().BreakBeforeParameter) 372 return true; 373 } else if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore && 374 State.Stack.back().BreakBeforeParameter) { 375 return true; 376 } 377 378 // Same as above, but for the first "<<" operator. 379 if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) && 380 State.Stack.back().BreakBeforeParameter && 381 State.Stack.back().FirstLessLess == 0) 382 return true; 383 384 if (Current.NestingLevel == 0 && !Current.isTrailingComment()) { 385 // Always break after "template <...>" and leading annotations. This is only 386 // for cases where the entire line does not fit on a single line as a 387 // different LineFormatter would be used otherwise. 388 if (Previous.ClosesTemplateDeclaration) 389 return true; 390 if (Previous.is(TT_FunctionAnnotationRParen)) 391 return true; 392 if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) && 393 Current.isNot(TT_LeadingJavaAnnotation)) 394 return true; 395 } 396 397 // If the return type spans multiple lines, wrap before the function name. 398 if ((Current.is(TT_FunctionDeclarationName) || 399 (Current.is(tok::kw_operator) && !Previous.is(tok::coloncolon))) && 400 !Previous.is(tok::kw_template) && State.Stack.back().BreakBeforeParameter) 401 return true; 402 403 // The following could be precomputed as they do not depend on the state. 404 // However, as they should take effect only if the UnwrappedLine does not fit 405 // into the ColumnLimit, they are checked here in the ContinuationIndenter. 406 if (Style.ColumnLimit != 0 && Previous.BlockKind == BK_Block && 407 Previous.is(tok::l_brace) && !Current.isOneOf(tok::r_brace, tok::comment)) 408 return true; 409 410 if (Current.is(tok::lessless) && 411 ((Previous.is(tok::identifier) && Previous.TokenText == "endl") || 412 (Previous.Tok.isLiteral() && (Previous.TokenText.endswith("\\n\"") || 413 Previous.TokenText == "\'\\n\'")))) 414 return true; 415 416 if (Previous.is(TT_BlockComment) && Previous.IsMultiline) 417 return true; 418 419 if (State.NoContinuation) 420 return true; 421 422 return false; 423 } 424 425 unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline, 426 bool DryRun, 427 unsigned ExtraSpaces) { 428 const FormatToken &Current = *State.NextToken; 429 430 assert(!State.Stack.empty()); 431 State.NoContinuation = false; 432 433 if ((Current.is(TT_ImplicitStringLiteral) && 434 (Current.Previous->Tok.getIdentifierInfo() == nullptr || 435 Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() == 436 tok::pp_not_keyword))) { 437 unsigned EndColumn = 438 SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getEnd()); 439 if (Current.LastNewlineOffset != 0) { 440 // If there is a newline within this token, the final column will solely 441 // determined by the current end column. 442 State.Column = EndColumn; 443 } else { 444 unsigned StartColumn = 445 SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getBegin()); 446 assert(EndColumn >= StartColumn); 447 State.Column += EndColumn - StartColumn; 448 } 449 moveStateToNextToken(State, DryRun, /*Newline=*/false); 450 return 0; 451 } 452 453 unsigned Penalty = 0; 454 if (Newline) 455 Penalty = addTokenOnNewLine(State, DryRun); 456 else 457 addTokenOnCurrentLine(State, DryRun, ExtraSpaces); 458 459 return moveStateToNextToken(State, DryRun, Newline) + Penalty; 460 } 461 462 void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun, 463 unsigned ExtraSpaces) { 464 FormatToken &Current = *State.NextToken; 465 const FormatToken &Previous = *State.NextToken->Previous; 466 if (Current.is(tok::equal) && 467 (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) && 468 State.Stack.back().VariablePos == 0) { 469 State.Stack.back().VariablePos = State.Column; 470 // Move over * and & if they are bound to the variable name. 471 const FormatToken *Tok = &Previous; 472 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) { 473 State.Stack.back().VariablePos -= Tok->ColumnWidth; 474 if (Tok->SpacesRequiredBefore != 0) 475 break; 476 Tok = Tok->Previous; 477 } 478 if (Previous.PartOfMultiVariableDeclStmt) 479 State.Stack.back().LastSpace = State.Stack.back().VariablePos; 480 } 481 482 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces; 483 484 // Indent preprocessor directives after the hash if required. 485 int PPColumnCorrection = 0; 486 if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash && 487 Previous.is(tok::hash) && State.FirstIndent > 0 && 488 (State.Line->Type == LT_PreprocessorDirective || 489 State.Line->Type == LT_ImportStatement)) { 490 Spaces += State.FirstIndent; 491 492 // For preprocessor indent with tabs, State.Column will be 1 because of the 493 // hash. This causes second-level indents onward to have an extra space 494 // after the tabs. We avoid this misalignment by subtracting 1 from the 495 // column value passed to replaceWhitespace(). 496 if (Style.UseTab != FormatStyle::UT_Never) 497 PPColumnCorrection = -1; 498 } 499 500 if (!DryRun) 501 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, Spaces, 502 State.Column + Spaces + PPColumnCorrection); 503 504 // If "BreakBeforeInheritanceComma" mode, don't break within the inheritance 505 // declaration unless there is multiple inheritance. 506 if (Style.BreakBeforeInheritanceComma && Current.is(TT_InheritanceColon)) 507 State.Stack.back().NoLineBreak = true; 508 509 if (Current.is(TT_SelectorName) && 510 !State.Stack.back().ObjCSelectorNameFound) { 511 unsigned MinIndent = 512 std::max(State.FirstIndent + Style.ContinuationIndentWidth, 513 State.Stack.back().Indent); 514 unsigned FirstColonPos = State.Column + Spaces + Current.ColumnWidth; 515 if (Current.LongestObjCSelectorName == 0) 516 State.Stack.back().AlignColons = false; 517 else if (MinIndent + Current.LongestObjCSelectorName > FirstColonPos) 518 State.Stack.back().ColonPos = MinIndent + Current.LongestObjCSelectorName; 519 else 520 State.Stack.back().ColonPos = FirstColonPos; 521 } 522 523 // In "AlwaysBreak" mode, enforce wrapping directly after the parenthesis by 524 // disallowing any further line breaks if there is no line break after the 525 // opening parenthesis. Don't break if it doesn't conserve columns. 526 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_AlwaysBreak && 527 Previous.isOneOf(tok::l_paren, TT_TemplateOpener, tok::l_square) && 528 State.Column > getNewLineColumn(State) && 529 (!Previous.Previous || !Previous.Previous->isOneOf( 530 tok::kw_for, tok::kw_while, tok::kw_switch)) && 531 // Don't do this for simple (no expressions) one-argument function calls 532 // as that feels like needlessly wasting whitespace, e.g.: 533 // 534 // caaaaaaaaaaaall( 535 // caaaaaaaaaaaall( 536 // caaaaaaaaaaaall( 537 // caaaaaaaaaaaaaaaaaaaaaaall(aaaaaaaaaaaaaa, aaaaaaaaa)))); 538 Current.FakeLParens.size() > 0 && 539 Current.FakeLParens.back() > prec::Unknown) 540 State.Stack.back().NoLineBreak = true; 541 if (Previous.is(TT_TemplateString) && Previous.opensScope()) 542 State.Stack.back().NoLineBreak = true; 543 544 if (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign && 545 Previous.opensScope() && Previous.isNot(TT_ObjCMethodExpr) && 546 (Current.isNot(TT_LineComment) || Previous.BlockKind == BK_BracedInit)) 547 State.Stack.back().Indent = State.Column + Spaces; 548 if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style)) 549 State.Stack.back().NoLineBreak = true; 550 if (startsSegmentOfBuilderTypeCall(Current) && 551 State.Column > getNewLineColumn(State)) 552 State.Stack.back().ContainsUnwrappedBuilder = true; 553 554 if (Current.is(TT_LambdaArrow) && Style.Language == FormatStyle::LK_Java) 555 State.Stack.back().NoLineBreak = true; 556 if (Current.isMemberAccess() && Previous.is(tok::r_paren) && 557 (Previous.MatchingParen && 558 (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) 559 // If there is a function call with long parameters, break before trailing 560 // calls. This prevents things like: 561 // EXPECT_CALL(SomeLongParameter).Times( 562 // 2); 563 // We don't want to do this for short parameters as they can just be 564 // indexes. 565 State.Stack.back().NoLineBreak = true; 566 567 // Don't allow the RHS of an operator to be split over multiple lines unless 568 // there is a line-break right after the operator. 569 // Exclude relational operators, as there, it is always more desirable to 570 // have the LHS 'left' of the RHS. 571 const FormatToken *P = Current.getPreviousNonComment(); 572 if (!Current.is(tok::comment) && P && 573 (P->isOneOf(TT_BinaryOperator, tok::comma) || 574 (P->is(TT_ConditionalExpr) && P->is(tok::colon))) && 575 !P->isOneOf(TT_OverloadedOperator, TT_CtorInitializerComma) && 576 P->getPrecedence() != prec::Assignment && 577 P->getPrecedence() != prec::Relational && 578 P->getPrecedence() != prec::Spaceship) { 579 bool BreakBeforeOperator = 580 P->MustBreakBefore || P->is(tok::lessless) || 581 (P->is(TT_BinaryOperator) && 582 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) || 583 (P->is(TT_ConditionalExpr) && Style.BreakBeforeTernaryOperators); 584 // Don't do this if there are only two operands. In these cases, there is 585 // always a nice vertical separation between them and the extra line break 586 // does not help. 587 bool HasTwoOperands = 588 P->OperatorIndex == 0 && !P->NextOperator && !P->is(TT_ConditionalExpr); 589 if ((!BreakBeforeOperator && !(HasTwoOperands && Style.AlignOperands)) || 590 (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator)) 591 State.Stack.back().NoLineBreakInOperand = true; 592 } 593 594 State.Column += Spaces; 595 if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) && 596 Previous.Previous && 597 (Previous.Previous->isOneOf(tok::kw_if, tok::kw_for) || 598 Previous.Previous->endsSequence(tok::kw_constexpr, tok::kw_if))) { 599 // Treat the condition inside an if as if it was a second function 600 // parameter, i.e. let nested calls have a continuation indent. 601 State.Stack.back().LastSpace = State.Column; 602 State.Stack.back().NestedBlockIndent = State.Column; 603 } else if (!Current.isOneOf(tok::comment, tok::caret) && 604 ((Previous.is(tok::comma) && 605 !Previous.is(TT_OverloadedOperator)) || 606 (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) { 607 State.Stack.back().LastSpace = State.Column; 608 } else if (Previous.is(TT_CtorInitializerColon) && 609 Style.BreakConstructorInitializers == 610 FormatStyle::BCIS_AfterColon) { 611 State.Stack.back().Indent = State.Column; 612 State.Stack.back().LastSpace = State.Column; 613 } else if ((Previous.isOneOf(TT_BinaryOperator, TT_ConditionalExpr, 614 TT_CtorInitializerColon)) && 615 ((Previous.getPrecedence() != prec::Assignment && 616 (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 || 617 Previous.NextOperator)) || 618 Current.StartsBinaryExpression)) { 619 // Indent relative to the RHS of the expression unless this is a simple 620 // assignment without binary expression on the RHS. Also indent relative to 621 // unary operators and the colons of constructor initializers. 622 State.Stack.back().LastSpace = State.Column; 623 } else if (Previous.is(TT_InheritanceColon)) { 624 State.Stack.back().Indent = State.Column; 625 State.Stack.back().LastSpace = State.Column; 626 } else if (Previous.opensScope()) { 627 // If a function has a trailing call, indent all parameters from the 628 // opening parenthesis. This avoids confusing indents like: 629 // OuterFunction(InnerFunctionCall( // break 630 // ParameterToInnerFunction)) // break 631 // .SecondInnerFunctionCall(); 632 bool HasTrailingCall = false; 633 if (Previous.MatchingParen) { 634 const FormatToken *Next = Previous.MatchingParen->getNextNonComment(); 635 HasTrailingCall = Next && Next->isMemberAccess(); 636 } 637 if (HasTrailingCall && State.Stack.size() > 1 && 638 State.Stack[State.Stack.size() - 2].CallContinuation == 0) 639 State.Stack.back().LastSpace = State.Column; 640 } 641 } 642 643 unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State, 644 bool DryRun) { 645 FormatToken &Current = *State.NextToken; 646 const FormatToken &Previous = *State.NextToken->Previous; 647 648 // Extra penalty that needs to be added because of the way certain line 649 // breaks are chosen. 650 unsigned Penalty = 0; 651 652 const FormatToken *PreviousNonComment = Current.getPreviousNonComment(); 653 const FormatToken *NextNonComment = Previous.getNextNonComment(); 654 if (!NextNonComment) 655 NextNonComment = &Current; 656 // The first line break on any NestingLevel causes an extra penalty in order 657 // prefer similar line breaks. 658 if (!State.Stack.back().ContainsLineBreak) 659 Penalty += 15; 660 State.Stack.back().ContainsLineBreak = true; 661 662 Penalty += State.NextToken->SplitPenalty; 663 664 // Breaking before the first "<<" is generally not desirable if the LHS is 665 // short. Also always add the penalty if the LHS is split over multiple lines 666 // to avoid unnecessary line breaks that just work around this penalty. 667 if (NextNonComment->is(tok::lessless) && 668 State.Stack.back().FirstLessLess == 0 && 669 (State.Column <= Style.ColumnLimit / 3 || 670 State.Stack.back().BreakBeforeParameter)) 671 Penalty += Style.PenaltyBreakFirstLessLess; 672 673 State.Column = getNewLineColumn(State); 674 675 // Indent nested blocks relative to this column, unless in a very specific 676 // JavaScript special case where: 677 // 678 // var loooooong_name = 679 // function() { 680 // // code 681 // } 682 // 683 // is common and should be formatted like a free-standing function. The same 684 // goes for wrapping before the lambda return type arrow. 685 if (!Current.is(TT_LambdaArrow) && 686 (Style.Language != FormatStyle::LK_JavaScript || 687 Current.NestingLevel != 0 || !PreviousNonComment || 688 !PreviousNonComment->is(tok::equal) || 689 !Current.isOneOf(Keywords.kw_async, Keywords.kw_function))) 690 State.Stack.back().NestedBlockIndent = State.Column; 691 692 if (NextNonComment->isMemberAccess()) { 693 if (State.Stack.back().CallContinuation == 0) 694 State.Stack.back().CallContinuation = State.Column; 695 } else if (NextNonComment->is(TT_SelectorName)) { 696 if (!State.Stack.back().ObjCSelectorNameFound) { 697 if (NextNonComment->LongestObjCSelectorName == 0) { 698 State.Stack.back().AlignColons = false; 699 } else { 700 State.Stack.back().ColonPos = 701 (Style.IndentWrappedFunctionNames 702 ? std::max(State.Stack.back().Indent, 703 State.FirstIndent + Style.ContinuationIndentWidth) 704 : State.Stack.back().Indent) + 705 std::max(NextNonComment->LongestObjCSelectorName, 706 NextNonComment->ColumnWidth); 707 } 708 } else if (State.Stack.back().AlignColons && 709 State.Stack.back().ColonPos <= NextNonComment->ColumnWidth) { 710 State.Stack.back().ColonPos = State.Column + NextNonComment->ColumnWidth; 711 } 712 } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) && 713 PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) { 714 // FIXME: This is hacky, find a better way. The problem is that in an ObjC 715 // method expression, the block should be aligned to the line starting it, 716 // e.g.: 717 // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason 718 // ^(int *i) { 719 // // ... 720 // }]; 721 // Thus, we set LastSpace of the next higher NestingLevel, to which we move 722 // when we consume all of the "}"'s FakeRParens at the "{". 723 if (State.Stack.size() > 1) 724 State.Stack[State.Stack.size() - 2].LastSpace = 725 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 726 Style.ContinuationIndentWidth; 727 } 728 729 if ((PreviousNonComment && 730 PreviousNonComment->isOneOf(tok::comma, tok::semi) && 731 !State.Stack.back().AvoidBinPacking) || 732 Previous.is(TT_BinaryOperator)) 733 State.Stack.back().BreakBeforeParameter = false; 734 if (Previous.isOneOf(TT_TemplateCloser, TT_JavaAnnotation) && 735 Current.NestingLevel == 0) 736 State.Stack.back().BreakBeforeParameter = false; 737 if (NextNonComment->is(tok::question) || 738 (PreviousNonComment && PreviousNonComment->is(tok::question))) 739 State.Stack.back().BreakBeforeParameter = true; 740 if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore) 741 State.Stack.back().BreakBeforeParameter = false; 742 743 if (!DryRun) { 744 unsigned MaxEmptyLinesToKeep = Style.MaxEmptyLinesToKeep + 1; 745 if (Current.is(tok::r_brace) && Current.MatchingParen && 746 // Only strip trailing empty lines for l_braces that have children, i.e. 747 // for function expressions (lambdas, arrows, etc). 748 !Current.MatchingParen->Children.empty()) { 749 // lambdas and arrow functions are expressions, thus their r_brace is not 750 // on its own line, and thus not covered by UnwrappedLineFormatter's logic 751 // about removing empty lines on closing blocks. Special case them here. 752 MaxEmptyLinesToKeep = 1; 753 } 754 unsigned Newlines = std::max( 755 1u, std::min(Current.NewlinesBefore, MaxEmptyLinesToKeep)); 756 bool ContinuePPDirective = 757 State.Line->InPPDirective && State.Line->Type != LT_ImportStatement; 758 Whitespaces.replaceWhitespace(Current, Newlines, State.Column, State.Column, 759 ContinuePPDirective); 760 } 761 762 if (!Current.isTrailingComment()) 763 State.Stack.back().LastSpace = State.Column; 764 if (Current.is(tok::lessless)) 765 // If we are breaking before a "<<", we always want to indent relative to 766 // RHS. This is necessary only for "<<", as we special-case it and don't 767 // always indent relative to the RHS. 768 State.Stack.back().LastSpace += 3; // 3 -> width of "<< ". 769 770 State.StartOfLineLevel = Current.NestingLevel; 771 State.LowestLevelOnLine = Current.NestingLevel; 772 773 // Any break on this level means that the parent level has been broken 774 // and we need to avoid bin packing there. 775 bool NestedBlockSpecialCase = 776 !Style.isCpp() && Current.is(tok::r_brace) && State.Stack.size() > 1 && 777 State.Stack[State.Stack.size() - 2].NestedBlockInlined; 778 if (!NestedBlockSpecialCase) 779 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) 780 State.Stack[i].BreakBeforeParameter = true; 781 782 if (PreviousNonComment && 783 !PreviousNonComment->isOneOf(tok::comma, tok::colon, tok::semi) && 784 (PreviousNonComment->isNot(TT_TemplateCloser) || 785 Current.NestingLevel != 0) && 786 !PreviousNonComment->isOneOf( 787 TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation, 788 TT_LeadingJavaAnnotation) && 789 Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope()) 790 State.Stack.back().BreakBeforeParameter = true; 791 792 // If we break after { or the [ of an array initializer, we should also break 793 // before the corresponding } or ]. 794 if (PreviousNonComment && 795 (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) || 796 opensProtoMessageField(*PreviousNonComment, Style))) 797 State.Stack.back().BreakBeforeClosingBrace = true; 798 799 if (State.Stack.back().AvoidBinPacking) { 800 // If we are breaking after '(', '{', '<', this is not bin packing 801 // unless AllowAllParametersOfDeclarationOnNextLine is false or this is a 802 // dict/object literal. 803 if (!Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) || 804 (!Style.AllowAllParametersOfDeclarationOnNextLine && 805 State.Line->MustBeDeclaration) || 806 Previous.is(TT_DictLiteral)) 807 State.Stack.back().BreakBeforeParameter = true; 808 } 809 810 return Penalty; 811 } 812 813 unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) { 814 if (!State.NextToken || !State.NextToken->Previous) 815 return 0; 816 FormatToken &Current = *State.NextToken; 817 const FormatToken &Previous = *Current.Previous; 818 // If we are continuing an expression, we want to use the continuation indent. 819 unsigned ContinuationIndent = 820 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 821 Style.ContinuationIndentWidth; 822 const FormatToken *PreviousNonComment = Current.getPreviousNonComment(); 823 const FormatToken *NextNonComment = Previous.getNextNonComment(); 824 if (!NextNonComment) 825 NextNonComment = &Current; 826 827 // Java specific bits. 828 if (Style.Language == FormatStyle::LK_Java && 829 Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends)) 830 return std::max(State.Stack.back().LastSpace, 831 State.Stack.back().Indent + Style.ContinuationIndentWidth); 832 833 if (NextNonComment->is(tok::l_brace) && NextNonComment->BlockKind == BK_Block) 834 return Current.NestingLevel == 0 ? State.FirstIndent 835 : State.Stack.back().Indent; 836 if ((Current.isOneOf(tok::r_brace, tok::r_square) || 837 (Current.is(tok::greater) && 838 (Style.Language == FormatStyle::LK_Proto || 839 Style.Language == FormatStyle::LK_TextProto))) && 840 State.Stack.size() > 1) { 841 if (Current.closesBlockOrBlockTypeList(Style)) 842 return State.Stack[State.Stack.size() - 2].NestedBlockIndent; 843 if (Current.MatchingParen && 844 Current.MatchingParen->BlockKind == BK_BracedInit) 845 return State.Stack[State.Stack.size() - 2].LastSpace; 846 return State.FirstIndent; 847 } 848 // Indent a closing parenthesis at the previous level if followed by a semi or 849 // opening brace. This allows indentations such as: 850 // foo( 851 // a, 852 // ); 853 // function foo( 854 // a, 855 // ) { 856 // code(); // 857 // } 858 if (Current.is(tok::r_paren) && State.Stack.size() > 1 && 859 (!Current.Next || Current.Next->isOneOf(tok::semi, tok::l_brace))) 860 return State.Stack[State.Stack.size() - 2].LastSpace; 861 if (NextNonComment->is(TT_TemplateString) && NextNonComment->closesScope()) 862 return State.Stack[State.Stack.size() - 2].LastSpace; 863 if (Current.is(tok::identifier) && Current.Next && 864 (Current.Next->is(TT_DictLiteral) || 865 ((Style.Language == FormatStyle::LK_Proto || 866 Style.Language == FormatStyle::LK_TextProto) && 867 Current.Next->isOneOf(tok::less, tok::l_brace)))) 868 return State.Stack.back().Indent; 869 if (NextNonComment->is(TT_ObjCStringLiteral) && 870 State.StartOfStringLiteral != 0) 871 return State.StartOfStringLiteral - 1; 872 if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0) 873 return State.StartOfStringLiteral; 874 if (NextNonComment->is(tok::lessless) && 875 State.Stack.back().FirstLessLess != 0) 876 return State.Stack.back().FirstLessLess; 877 if (NextNonComment->isMemberAccess()) { 878 if (State.Stack.back().CallContinuation == 0) 879 return ContinuationIndent; 880 return State.Stack.back().CallContinuation; 881 } 882 if (State.Stack.back().QuestionColumn != 0 && 883 ((NextNonComment->is(tok::colon) && 884 NextNonComment->is(TT_ConditionalExpr)) || 885 Previous.is(TT_ConditionalExpr))) 886 return State.Stack.back().QuestionColumn; 887 if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0) 888 return State.Stack.back().VariablePos; 889 if ((PreviousNonComment && 890 (PreviousNonComment->ClosesTemplateDeclaration || 891 PreviousNonComment->isOneOf( 892 TT_AttributeParen, TT_AttributeSquare, TT_FunctionAnnotationRParen, 893 TT_JavaAnnotation, TT_LeadingJavaAnnotation))) || 894 (!Style.IndentWrappedFunctionNames && 895 NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName))) 896 return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent); 897 if (NextNonComment->is(TT_SelectorName)) { 898 if (!State.Stack.back().ObjCSelectorNameFound) { 899 unsigned MinIndent = State.Stack.back().Indent; 900 if (Style.IndentWrappedFunctionNames) 901 MinIndent = std::max(MinIndent, 902 State.FirstIndent + Style.ContinuationIndentWidth); 903 // If LongestObjCSelectorName is 0, we are indenting the first 904 // part of an ObjC selector (or a selector component which is 905 // not colon-aligned due to block formatting). 906 // 907 // Otherwise, we are indenting a subsequent part of an ObjC 908 // selector which should be colon-aligned to the longest 909 // component of the ObjC selector. 910 // 911 // In either case, we want to respect Style.IndentWrappedFunctionNames. 912 return MinIndent + 913 std::max(NextNonComment->LongestObjCSelectorName, 914 NextNonComment->ColumnWidth) - 915 NextNonComment->ColumnWidth; 916 } 917 if (!State.Stack.back().AlignColons) 918 return State.Stack.back().Indent; 919 if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth) 920 return State.Stack.back().ColonPos - NextNonComment->ColumnWidth; 921 return State.Stack.back().Indent; 922 } 923 if (NextNonComment->is(tok::colon) && NextNonComment->is(TT_ObjCMethodExpr)) 924 return State.Stack.back().ColonPos; 925 if (NextNonComment->is(TT_ArraySubscriptLSquare)) { 926 if (State.Stack.back().StartOfArraySubscripts != 0) 927 return State.Stack.back().StartOfArraySubscripts; 928 return ContinuationIndent; 929 } 930 931 // This ensure that we correctly format ObjC methods calls without inputs, 932 // i.e. where the last element isn't selector like: [callee method]; 933 if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 && 934 NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr)) 935 return State.Stack.back().Indent; 936 937 if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) || 938 Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon)) 939 return ContinuationIndent; 940 if (PreviousNonComment && PreviousNonComment->is(tok::colon) && 941 PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) 942 return ContinuationIndent; 943 if (NextNonComment->is(TT_CtorInitializerComma)) 944 return State.Stack.back().Indent; 945 if (PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) && 946 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) 947 return State.Stack.back().Indent; 948 if (NextNonComment->isOneOf(TT_CtorInitializerColon, TT_InheritanceColon, 949 TT_InheritanceComma)) 950 return State.FirstIndent + Style.ConstructorInitializerIndentWidth; 951 if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() && 952 !Current.isOneOf(tok::colon, tok::comment)) 953 return ContinuationIndent; 954 if (Current.is(TT_ProtoExtensionLSquare)) 955 return State.Stack.back().Indent; 956 if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment && 957 PreviousNonComment->isNot(tok::r_brace)) 958 // Ensure that we fall back to the continuation indent width instead of 959 // just flushing continuations left. 960 return State.Stack.back().Indent + Style.ContinuationIndentWidth; 961 return State.Stack.back().Indent; 962 } 963 964 unsigned ContinuationIndenter::moveStateToNextToken(LineState &State, 965 bool DryRun, bool Newline) { 966 assert(State.Stack.size()); 967 const FormatToken &Current = *State.NextToken; 968 969 if (Current.isOneOf(tok::comma, TT_BinaryOperator)) 970 State.Stack.back().NoLineBreakInOperand = false; 971 if (Current.is(TT_InheritanceColon)) 972 State.Stack.back().AvoidBinPacking = true; 973 if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) { 974 if (State.Stack.back().FirstLessLess == 0) 975 State.Stack.back().FirstLessLess = State.Column; 976 else 977 State.Stack.back().LastOperatorWrapped = Newline; 978 } 979 if (Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless)) 980 State.Stack.back().LastOperatorWrapped = Newline; 981 if (Current.is(TT_ConditionalExpr) && Current.Previous && 982 !Current.Previous->is(TT_ConditionalExpr)) 983 State.Stack.back().LastOperatorWrapped = Newline; 984 if (Current.is(TT_ArraySubscriptLSquare) && 985 State.Stack.back().StartOfArraySubscripts == 0) 986 State.Stack.back().StartOfArraySubscripts = State.Column; 987 if (Style.BreakBeforeTernaryOperators && Current.is(tok::question)) 988 State.Stack.back().QuestionColumn = State.Column; 989 if (!Style.BreakBeforeTernaryOperators && Current.isNot(tok::colon)) { 990 const FormatToken *Previous = Current.Previous; 991 while (Previous && Previous->isTrailingComment()) 992 Previous = Previous->Previous; 993 if (Previous && Previous->is(tok::question)) 994 State.Stack.back().QuestionColumn = State.Column; 995 } 996 if (!Current.opensScope() && !Current.closesScope() && 997 !Current.is(TT_PointerOrReference)) 998 State.LowestLevelOnLine = 999 std::min(State.LowestLevelOnLine, Current.NestingLevel); 1000 if (Current.isMemberAccess()) 1001 State.Stack.back().StartOfFunctionCall = 1002 !Current.NextOperator ? 0 : State.Column; 1003 if (Current.is(TT_SelectorName)) { 1004 State.Stack.back().ObjCSelectorNameFound = true; 1005 if (Style.IndentWrappedFunctionNames) { 1006 State.Stack.back().Indent = 1007 State.FirstIndent + Style.ContinuationIndentWidth; 1008 } 1009 } 1010 if (Current.is(TT_CtorInitializerColon) && 1011 Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon) { 1012 // Indent 2 from the column, so: 1013 // SomeClass::SomeClass() 1014 // : First(...), ... 1015 // Next(...) 1016 // ^ line up here. 1017 State.Stack.back().Indent = 1018 State.Column + 1019 (Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma 1020 ? 0 1021 : 2); 1022 State.Stack.back().NestedBlockIndent = State.Stack.back().Indent; 1023 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine) 1024 State.Stack.back().AvoidBinPacking = true; 1025 State.Stack.back().BreakBeforeParameter = false; 1026 } 1027 if (Current.is(TT_CtorInitializerColon) && 1028 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) { 1029 State.Stack.back().Indent = 1030 State.FirstIndent + Style.ConstructorInitializerIndentWidth; 1031 State.Stack.back().NestedBlockIndent = State.Stack.back().Indent; 1032 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine) 1033 State.Stack.back().AvoidBinPacking = true; 1034 } 1035 if (Current.is(TT_InheritanceColon)) 1036 State.Stack.back().Indent = 1037 State.FirstIndent + Style.ContinuationIndentWidth; 1038 if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline) 1039 State.Stack.back().NestedBlockIndent = 1040 State.Column + Current.ColumnWidth + 1; 1041 if (Current.isOneOf(TT_LambdaLSquare, TT_LambdaArrow)) 1042 State.Stack.back().LastSpace = State.Column; 1043 1044 // Insert scopes created by fake parenthesis. 1045 const FormatToken *Previous = Current.getPreviousNonComment(); 1046 1047 // Add special behavior to support a format commonly used for JavaScript 1048 // closures: 1049 // SomeFunction(function() { 1050 // foo(); 1051 // bar(); 1052 // }, a, b, c); 1053 if (Current.isNot(tok::comment) && Previous && 1054 Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) && 1055 !Previous->is(TT_DictLiteral) && State.Stack.size() > 1) { 1056 if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline) 1057 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) 1058 State.Stack[i].NoLineBreak = true; 1059 State.Stack[State.Stack.size() - 2].NestedBlockInlined = false; 1060 } 1061 if (Previous && 1062 (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) || 1063 Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr)) && 1064 !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) { 1065 State.Stack.back().NestedBlockInlined = 1066 !Newline && 1067 (Previous->isNot(tok::l_paren) || Previous->ParameterCount > 1); 1068 } 1069 1070 moveStatePastFakeLParens(State, Newline); 1071 moveStatePastScopeCloser(State); 1072 bool AllowBreak = !State.Stack.back().NoLineBreak && 1073 !State.Stack.back().NoLineBreakInOperand; 1074 moveStatePastScopeOpener(State, Newline); 1075 moveStatePastFakeRParens(State); 1076 1077 if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0) 1078 State.StartOfStringLiteral = State.Column + 1; 1079 else if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) 1080 State.StartOfStringLiteral = State.Column; 1081 else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) && 1082 !Current.isStringLiteral()) 1083 State.StartOfStringLiteral = 0; 1084 1085 State.Column += Current.ColumnWidth; 1086 State.NextToken = State.NextToken->Next; 1087 1088 unsigned Penalty = 1089 handleEndOfLine(Current, State, DryRun, AllowBreak); 1090 1091 if (Current.Role) 1092 Current.Role->formatFromToken(State, this, DryRun); 1093 // If the previous has a special role, let it consume tokens as appropriate. 1094 // It is necessary to start at the previous token for the only implemented 1095 // role (comma separated list). That way, the decision whether or not to break 1096 // after the "{" is already done and both options are tried and evaluated. 1097 // FIXME: This is ugly, find a better way. 1098 if (Previous && Previous->Role) 1099 Penalty += Previous->Role->formatAfterToken(State, this, DryRun); 1100 1101 return Penalty; 1102 } 1103 1104 void ContinuationIndenter::moveStatePastFakeLParens(LineState &State, 1105 bool Newline) { 1106 const FormatToken &Current = *State.NextToken; 1107 const FormatToken *Previous = Current.getPreviousNonComment(); 1108 1109 // Don't add extra indentation for the first fake parenthesis after 1110 // 'return', assignments or opening <({[. The indentation for these cases 1111 // is special cased. 1112 bool SkipFirstExtraIndent = 1113 (Previous && (Previous->opensScope() || 1114 Previous->isOneOf(tok::semi, tok::kw_return) || 1115 (Previous->getPrecedence() == prec::Assignment && 1116 Style.AlignOperands) || 1117 Previous->is(TT_ObjCMethodExpr))); 1118 for (SmallVectorImpl<prec::Level>::const_reverse_iterator 1119 I = Current.FakeLParens.rbegin(), 1120 E = Current.FakeLParens.rend(); 1121 I != E; ++I) { 1122 ParenState NewParenState = State.Stack.back(); 1123 NewParenState.ContainsLineBreak = false; 1124 NewParenState.LastOperatorWrapped = true; 1125 NewParenState.NoLineBreak = 1126 NewParenState.NoLineBreak || State.Stack.back().NoLineBreakInOperand; 1127 1128 // Don't propagate AvoidBinPacking into subexpressions of arg/param lists. 1129 if (*I > prec::Comma) 1130 NewParenState.AvoidBinPacking = false; 1131 1132 // Indent from 'LastSpace' unless these are fake parentheses encapsulating 1133 // a builder type call after 'return' or, if the alignment after opening 1134 // brackets is disabled. 1135 if (!Current.isTrailingComment() && 1136 (Style.AlignOperands || *I < prec::Assignment) && 1137 (!Previous || Previous->isNot(tok::kw_return) || 1138 (Style.Language != FormatStyle::LK_Java && *I > 0)) && 1139 (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign || 1140 *I != prec::Comma || Current.NestingLevel == 0)) 1141 NewParenState.Indent = 1142 std::max(std::max(State.Column, NewParenState.Indent), 1143 State.Stack.back().LastSpace); 1144 1145 // Do not indent relative to the fake parentheses inserted for "." or "->". 1146 // This is a special case to make the following to statements consistent: 1147 // OuterFunction(InnerFunctionCall( // break 1148 // ParameterToInnerFunction)); 1149 // OuterFunction(SomeObject.InnerFunctionCall( // break 1150 // ParameterToInnerFunction)); 1151 if (*I > prec::Unknown) 1152 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column); 1153 if (*I != prec::Conditional && !Current.is(TT_UnaryOperator) && 1154 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign) 1155 NewParenState.StartOfFunctionCall = State.Column; 1156 1157 // Always indent conditional expressions. Never indent expression where 1158 // the 'operator' is ',', ';' or an assignment (i.e. *I <= 1159 // prec::Assignment) as those have different indentation rules. Indent 1160 // other expression, unless the indentation needs to be skipped. 1161 if (*I == prec::Conditional || 1162 (!SkipFirstExtraIndent && *I > prec::Assignment && 1163 !Current.isTrailingComment())) 1164 NewParenState.Indent += Style.ContinuationIndentWidth; 1165 if ((Previous && !Previous->opensScope()) || *I != prec::Comma) 1166 NewParenState.BreakBeforeParameter = false; 1167 State.Stack.push_back(NewParenState); 1168 SkipFirstExtraIndent = false; 1169 } 1170 } 1171 1172 void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) { 1173 for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) { 1174 unsigned VariablePos = State.Stack.back().VariablePos; 1175 if (State.Stack.size() == 1) { 1176 // Do not pop the last element. 1177 break; 1178 } 1179 State.Stack.pop_back(); 1180 State.Stack.back().VariablePos = VariablePos; 1181 } 1182 } 1183 1184 void ContinuationIndenter::moveStatePastScopeOpener(LineState &State, 1185 bool Newline) { 1186 const FormatToken &Current = *State.NextToken; 1187 if (!Current.opensScope()) 1188 return; 1189 1190 if (Current.MatchingParen && Current.BlockKind == BK_Block) { 1191 moveStateToNewBlock(State); 1192 return; 1193 } 1194 1195 unsigned NewIndent; 1196 unsigned LastSpace = State.Stack.back().LastSpace; 1197 bool AvoidBinPacking; 1198 bool BreakBeforeParameter = false; 1199 unsigned NestedBlockIndent = std::max(State.Stack.back().StartOfFunctionCall, 1200 State.Stack.back().NestedBlockIndent); 1201 if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) || 1202 opensProtoMessageField(Current, Style)) { 1203 if (Current.opensBlockOrBlockTypeList(Style)) { 1204 NewIndent = Style.IndentWidth + 1205 std::min(State.Column, State.Stack.back().NestedBlockIndent); 1206 } else { 1207 NewIndent = State.Stack.back().LastSpace + Style.ContinuationIndentWidth; 1208 } 1209 const FormatToken *NextNoComment = Current.getNextNonComment(); 1210 bool EndsInComma = Current.MatchingParen && 1211 Current.MatchingParen->Previous && 1212 Current.MatchingParen->Previous->is(tok::comma); 1213 AvoidBinPacking = EndsInComma || Current.is(TT_DictLiteral) || 1214 Style.Language == FormatStyle::LK_Proto || 1215 Style.Language == FormatStyle::LK_TextProto || 1216 !Style.BinPackArguments || 1217 (NextNoComment && 1218 NextNoComment->isOneOf(TT_DesignatedInitializerPeriod, 1219 TT_DesignatedInitializerLSquare)); 1220 BreakBeforeParameter = EndsInComma; 1221 if (Current.ParameterCount > 1) 1222 NestedBlockIndent = std::max(NestedBlockIndent, State.Column + 1); 1223 } else { 1224 NewIndent = Style.ContinuationIndentWidth + 1225 std::max(State.Stack.back().LastSpace, 1226 State.Stack.back().StartOfFunctionCall); 1227 1228 // Ensure that different different brackets force relative alignment, e.g.: 1229 // void SomeFunction(vector< // break 1230 // int> v); 1231 // FIXME: We likely want to do this for more combinations of brackets. 1232 if (Current.is(tok::less) && Current.ParentBracket == tok::l_paren) { 1233 NewIndent = std::max(NewIndent, State.Stack.back().Indent); 1234 LastSpace = std::max(LastSpace, State.Stack.back().Indent); 1235 } 1236 1237 bool EndsInComma = 1238 Current.MatchingParen && 1239 Current.MatchingParen->getPreviousNonComment() && 1240 Current.MatchingParen->getPreviousNonComment()->is(tok::comma); 1241 1242 // If ObjCBinPackProtocolList is unspecified, fall back to BinPackParameters 1243 // for backwards compatibility. 1244 bool ObjCBinPackProtocolList = 1245 (Style.ObjCBinPackProtocolList == FormatStyle::BPS_Auto && 1246 Style.BinPackParameters) || 1247 Style.ObjCBinPackProtocolList == FormatStyle::BPS_Always; 1248 1249 bool BinPackDeclaration = 1250 (State.Line->Type != LT_ObjCDecl && Style.BinPackParameters) || 1251 (State.Line->Type == LT_ObjCDecl && ObjCBinPackProtocolList); 1252 1253 AvoidBinPacking = 1254 (Style.Language == FormatStyle::LK_JavaScript && EndsInComma) || 1255 (State.Line->MustBeDeclaration && !BinPackDeclaration) || 1256 (!State.Line->MustBeDeclaration && !Style.BinPackArguments) || 1257 (Style.ExperimentalAutoDetectBinPacking && 1258 (Current.PackingKind == PPK_OnePerLine || 1259 (!BinPackInconclusiveFunctions && 1260 Current.PackingKind == PPK_Inconclusive))); 1261 1262 if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen) { 1263 if (Style.ColumnLimit) { 1264 // If this '[' opens an ObjC call, determine whether all parameters fit 1265 // into one line and put one per line if they don't. 1266 if (getLengthToMatchingParen(Current) + State.Column > 1267 getColumnLimit(State)) 1268 BreakBeforeParameter = true; 1269 } else { 1270 // For ColumnLimit = 0, we have to figure out whether there is or has to 1271 // be a line break within this call. 1272 for (const FormatToken *Tok = &Current; 1273 Tok && Tok != Current.MatchingParen; Tok = Tok->Next) { 1274 if (Tok->MustBreakBefore || 1275 (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) { 1276 BreakBeforeParameter = true; 1277 break; 1278 } 1279 } 1280 } 1281 } 1282 1283 if (Style.Language == FormatStyle::LK_JavaScript && EndsInComma) 1284 BreakBeforeParameter = true; 1285 } 1286 // Generally inherit NoLineBreak from the current scope to nested scope. 1287 // However, don't do this for non-empty nested blocks, dict literals and 1288 // array literals as these follow different indentation rules. 1289 bool NoLineBreak = 1290 Current.Children.empty() && 1291 !Current.isOneOf(TT_DictLiteral, TT_ArrayInitializerLSquare) && 1292 (State.Stack.back().NoLineBreak || 1293 State.Stack.back().NoLineBreakInOperand || 1294 (Current.is(TT_TemplateOpener) && 1295 State.Stack.back().ContainsUnwrappedBuilder)); 1296 State.Stack.push_back( 1297 ParenState(NewIndent, LastSpace, AvoidBinPacking, NoLineBreak)); 1298 State.Stack.back().NestedBlockIndent = NestedBlockIndent; 1299 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter; 1300 State.Stack.back().HasMultipleNestedBlocks = Current.BlockParameterCount > 1; 1301 State.Stack.back().IsInsideObjCArrayLiteral = 1302 Current.is(TT_ArrayInitializerLSquare) && Current.Previous && 1303 Current.Previous->is(tok::at); 1304 } 1305 1306 void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) { 1307 const FormatToken &Current = *State.NextToken; 1308 if (!Current.closesScope()) 1309 return; 1310 1311 // If we encounter a closing ), ], } or >, we can remove a level from our 1312 // stacks. 1313 if (State.Stack.size() > 1 && 1314 (Current.isOneOf(tok::r_paren, tok::r_square, TT_TemplateString) || 1315 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) || 1316 State.NextToken->is(TT_TemplateCloser) || 1317 (Current.is(tok::greater) && Current.is(TT_DictLiteral)))) 1318 State.Stack.pop_back(); 1319 1320 if (Current.is(tok::r_square)) { 1321 // If this ends the array subscript expr, reset the corresponding value. 1322 const FormatToken *NextNonComment = Current.getNextNonComment(); 1323 if (NextNonComment && NextNonComment->isNot(tok::l_square)) 1324 State.Stack.back().StartOfArraySubscripts = 0; 1325 } 1326 } 1327 1328 void ContinuationIndenter::moveStateToNewBlock(LineState &State) { 1329 unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent; 1330 // ObjC block sometimes follow special indentation rules. 1331 unsigned NewIndent = 1332 NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace) 1333 ? Style.ObjCBlockIndentWidth 1334 : Style.IndentWidth); 1335 State.Stack.push_back(ParenState(NewIndent, State.Stack.back().LastSpace, 1336 /*AvoidBinPacking=*/true, 1337 /*NoLineBreak=*/false)); 1338 State.Stack.back().NestedBlockIndent = NestedBlockIndent; 1339 State.Stack.back().BreakBeforeParameter = true; 1340 } 1341 1342 static unsigned getLastLineEndColumn(StringRef Text, unsigned StartColumn, 1343 unsigned TabWidth, 1344 encoding::Encoding Encoding) { 1345 size_t LastNewlinePos = Text.find_last_of("\n"); 1346 if (LastNewlinePos == StringRef::npos) { 1347 return StartColumn + 1348 encoding::columnWidthWithTabs(Text, StartColumn, TabWidth, Encoding); 1349 } else { 1350 return encoding::columnWidthWithTabs(Text.substr(LastNewlinePos), 1351 /*StartColumn=*/0, TabWidth, Encoding); 1352 } 1353 } 1354 1355 unsigned ContinuationIndenter::reformatRawStringLiteral( 1356 const FormatToken &Current, LineState &State, 1357 const FormatStyle &RawStringStyle, bool DryRun) { 1358 unsigned StartColumn = State.Column - Current.ColumnWidth; 1359 StringRef OldDelimiter = *getRawStringDelimiter(Current.TokenText); 1360 StringRef NewDelimiter = 1361 getCanonicalRawStringDelimiter(Style, RawStringStyle.Language); 1362 if (NewDelimiter.empty() || OldDelimiter.empty()) 1363 NewDelimiter = OldDelimiter; 1364 // The text of a raw string is between the leading 'R"delimiter(' and the 1365 // trailing 'delimiter)"'. 1366 unsigned OldPrefixSize = 3 + OldDelimiter.size(); 1367 unsigned OldSuffixSize = 2 + OldDelimiter.size(); 1368 // We create a virtual text environment which expects a null-terminated 1369 // string, so we cannot use StringRef. 1370 std::string RawText = 1371 Current.TokenText.substr(OldPrefixSize).drop_back(OldSuffixSize); 1372 if (NewDelimiter != OldDelimiter) { 1373 // Don't update to the canonical delimiter 'deli' if ')deli"' occurs in the 1374 // raw string. 1375 std::string CanonicalDelimiterSuffix = (")" + NewDelimiter + "\"").str(); 1376 if (StringRef(RawText).contains(CanonicalDelimiterSuffix)) 1377 NewDelimiter = OldDelimiter; 1378 } 1379 1380 unsigned NewPrefixSize = 3 + NewDelimiter.size(); 1381 unsigned NewSuffixSize = 2 + NewDelimiter.size(); 1382 1383 // The first start column is the column the raw text starts after formatting. 1384 unsigned FirstStartColumn = StartColumn + NewPrefixSize; 1385 1386 // The next start column is the intended indentation a line break inside 1387 // the raw string at level 0. It is determined by the following rules: 1388 // - if the content starts on newline, it is one level more than the current 1389 // indent, and 1390 // - if the content does not start on a newline, it is the first start 1391 // column. 1392 // These rules have the advantage that the formatted content both does not 1393 // violate the rectangle rule and visually flows within the surrounding 1394 // source. 1395 bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n'; 1396 unsigned NextStartColumn = 1397 ContentStartsOnNewline 1398 ? State.Stack.back().NestedBlockIndent + Style.IndentWidth 1399 : FirstStartColumn; 1400 1401 // The last start column is the column the raw string suffix starts if it is 1402 // put on a newline. 1403 // The last start column is the intended indentation of the raw string postfix 1404 // if it is put on a newline. It is determined by the following rules: 1405 // - if the raw string prefix starts on a newline, it is the column where 1406 // that raw string prefix starts, and 1407 // - if the raw string prefix does not start on a newline, it is the current 1408 // indent. 1409 unsigned LastStartColumn = Current.NewlinesBefore 1410 ? FirstStartColumn - NewPrefixSize 1411 : State.Stack.back().NestedBlockIndent; 1412 1413 std::pair<tooling::Replacements, unsigned> Fixes = internal::reformat( 1414 RawStringStyle, RawText, {tooling::Range(0, RawText.size())}, 1415 FirstStartColumn, NextStartColumn, LastStartColumn, "<stdin>", 1416 /*Status=*/nullptr); 1417 1418 auto NewCode = applyAllReplacements(RawText, Fixes.first); 1419 tooling::Replacements NoFixes; 1420 if (!NewCode) { 1421 State.Column += Current.ColumnWidth; 1422 return 0; 1423 } 1424 if (!DryRun) { 1425 if (NewDelimiter != OldDelimiter) { 1426 // In 'R"delimiter(...', the delimiter starts 2 characters after the start 1427 // of the token. 1428 SourceLocation PrefixDelimiterStart = 1429 Current.Tok.getLocation().getLocWithOffset(2); 1430 auto PrefixErr = Whitespaces.addReplacement(tooling::Replacement( 1431 SourceMgr, PrefixDelimiterStart, OldDelimiter.size(), NewDelimiter)); 1432 if (PrefixErr) { 1433 llvm::errs() 1434 << "Failed to update the prefix delimiter of a raw string: " 1435 << llvm::toString(std::move(PrefixErr)) << "\n"; 1436 } 1437 // In 'R"delimiter(...)delimiter"', the suffix delimiter starts at 1438 // position length - 1 - |delimiter|. 1439 SourceLocation SuffixDelimiterStart = 1440 Current.Tok.getLocation().getLocWithOffset(Current.TokenText.size() - 1441 1 - OldDelimiter.size()); 1442 auto SuffixErr = Whitespaces.addReplacement(tooling::Replacement( 1443 SourceMgr, SuffixDelimiterStart, OldDelimiter.size(), NewDelimiter)); 1444 if (SuffixErr) { 1445 llvm::errs() 1446 << "Failed to update the suffix delimiter of a raw string: " 1447 << llvm::toString(std::move(SuffixErr)) << "\n"; 1448 } 1449 } 1450 SourceLocation OriginLoc = 1451 Current.Tok.getLocation().getLocWithOffset(OldPrefixSize); 1452 for (const tooling::Replacement &Fix : Fixes.first) { 1453 auto Err = Whitespaces.addReplacement(tooling::Replacement( 1454 SourceMgr, OriginLoc.getLocWithOffset(Fix.getOffset()), 1455 Fix.getLength(), Fix.getReplacementText())); 1456 if (Err) { 1457 llvm::errs() << "Failed to reformat raw string: " 1458 << llvm::toString(std::move(Err)) << "\n"; 1459 } 1460 } 1461 } 1462 unsigned RawLastLineEndColumn = getLastLineEndColumn( 1463 *NewCode, FirstStartColumn, Style.TabWidth, Encoding); 1464 State.Column = RawLastLineEndColumn + NewSuffixSize; 1465 // Since we're updating the column to after the raw string literal here, we 1466 // have to manually add the penalty for the prefix R"delim( over the column 1467 // limit. 1468 unsigned PrefixExcessCharacters = 1469 StartColumn + NewPrefixSize > Style.ColumnLimit ? 1470 StartColumn + NewPrefixSize - Style.ColumnLimit : 0; 1471 return Fixes.second + PrefixExcessCharacters * Style.PenaltyExcessCharacter; 1472 } 1473 1474 unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current, 1475 LineState &State) { 1476 // Break before further function parameters on all levels. 1477 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i) 1478 State.Stack[i].BreakBeforeParameter = true; 1479 1480 unsigned ColumnsUsed = State.Column; 1481 // We can only affect layout of the first and the last line, so the penalty 1482 // for all other lines is constant, and we ignore it. 1483 State.Column = Current.LastLineColumnWidth; 1484 1485 if (ColumnsUsed > getColumnLimit(State)) 1486 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State)); 1487 return 0; 1488 } 1489 1490 unsigned ContinuationIndenter::handleEndOfLine(const FormatToken &Current, 1491 LineState &State, bool DryRun, 1492 bool AllowBreak) { 1493 unsigned Penalty = 0; 1494 // Compute the raw string style to use in case this is a raw string literal 1495 // that can be reformatted. 1496 auto RawStringStyle = getRawStringStyle(Current, State); 1497 if (RawStringStyle && !Current.Finalized) { 1498 Penalty = reformatRawStringLiteral(Current, State, *RawStringStyle, DryRun); 1499 } else if (Current.IsMultiline && Current.isNot(TT_BlockComment)) { 1500 // Don't break multi-line tokens other than block comments and raw string 1501 // literals. Instead, just update the state. 1502 Penalty = addMultilineToken(Current, State); 1503 } else if (State.Line->Type != LT_ImportStatement) { 1504 // We generally don't break import statements. 1505 LineState OriginalState = State; 1506 1507 // Whether we force the reflowing algorithm to stay strictly within the 1508 // column limit. 1509 bool Strict = false; 1510 // Whether the first non-strict attempt at reflowing did intentionally 1511 // exceed the column limit. 1512 bool Exceeded = false; 1513 std::tie(Penalty, Exceeded) = breakProtrudingToken( 1514 Current, State, AllowBreak, /*DryRun=*/true, Strict); 1515 if (Exceeded) { 1516 // If non-strict reflowing exceeds the column limit, try whether strict 1517 // reflowing leads to an overall lower penalty. 1518 LineState StrictState = OriginalState; 1519 unsigned StrictPenalty = 1520 breakProtrudingToken(Current, StrictState, AllowBreak, 1521 /*DryRun=*/true, /*Strict=*/true) 1522 .first; 1523 Strict = StrictPenalty <= Penalty; 1524 if (Strict) { 1525 Penalty = StrictPenalty; 1526 State = StrictState; 1527 } 1528 } 1529 if (!DryRun) { 1530 // If we're not in dry-run mode, apply the changes with the decision on 1531 // strictness made above. 1532 breakProtrudingToken(Current, OriginalState, AllowBreak, /*DryRun=*/false, 1533 Strict); 1534 } 1535 } 1536 if (State.Column > getColumnLimit(State)) { 1537 unsigned ExcessCharacters = State.Column - getColumnLimit(State); 1538 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters; 1539 } 1540 return Penalty; 1541 } 1542 1543 // Returns the enclosing function name of a token, or the empty string if not 1544 // found. 1545 static StringRef getEnclosingFunctionName(const FormatToken &Current) { 1546 // Look for: 'function(' or 'function<templates>(' before Current. 1547 auto Tok = Current.getPreviousNonComment(); 1548 if (!Tok || !Tok->is(tok::l_paren)) 1549 return ""; 1550 Tok = Tok->getPreviousNonComment(); 1551 if (!Tok) 1552 return ""; 1553 if (Tok->is(TT_TemplateCloser)) { 1554 Tok = Tok->MatchingParen; 1555 if (Tok) 1556 Tok = Tok->getPreviousNonComment(); 1557 } 1558 if (!Tok || !Tok->is(tok::identifier)) 1559 return ""; 1560 return Tok->TokenText; 1561 } 1562 1563 llvm::Optional<FormatStyle> 1564 ContinuationIndenter::getRawStringStyle(const FormatToken &Current, 1565 const LineState &State) { 1566 if (!Current.isStringLiteral()) 1567 return None; 1568 auto Delimiter = getRawStringDelimiter(Current.TokenText); 1569 if (!Delimiter) 1570 return None; 1571 auto RawStringStyle = RawStringFormats.getDelimiterStyle(*Delimiter); 1572 if (!RawStringStyle) 1573 RawStringStyle = RawStringFormats.getEnclosingFunctionStyle( 1574 getEnclosingFunctionName(Current)); 1575 if (!RawStringStyle) 1576 return None; 1577 RawStringStyle->ColumnLimit = getColumnLimit(State); 1578 return RawStringStyle; 1579 } 1580 1581 std::unique_ptr<BreakableToken> ContinuationIndenter::createBreakableToken( 1582 const FormatToken &Current, LineState &State, bool AllowBreak) { 1583 unsigned StartColumn = State.Column - Current.ColumnWidth; 1584 if (Current.isStringLiteral()) { 1585 // FIXME: String literal breaking is currently disabled for Java and JS, as 1586 // it requires strings to be merged using "+" which we don't support. 1587 if (Style.Language == FormatStyle::LK_Java || 1588 Style.Language == FormatStyle::LK_JavaScript || 1589 !Style.BreakStringLiterals || 1590 !AllowBreak) 1591 return nullptr; 1592 1593 // Don't break string literals inside preprocessor directives (except for 1594 // #define directives, as their contents are stored in separate lines and 1595 // are not affected by this check). 1596 // This way we avoid breaking code with line directives and unknown 1597 // preprocessor directives that contain long string literals. 1598 if (State.Line->Type == LT_PreprocessorDirective) 1599 return nullptr; 1600 // Exempts unterminated string literals from line breaking. The user will 1601 // likely want to terminate the string before any line breaking is done. 1602 if (Current.IsUnterminatedLiteral) 1603 return nullptr; 1604 // Don't break string literals inside Objective-C array literals (doing so 1605 // raises the warning -Wobjc-string-concatenation). 1606 if (State.Stack.back().IsInsideObjCArrayLiteral) { 1607 return nullptr; 1608 } 1609 1610 StringRef Text = Current.TokenText; 1611 StringRef Prefix; 1612 StringRef Postfix; 1613 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'. 1614 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to 1615 // reduce the overhead) for each FormatToken, which is a string, so that we 1616 // don't run multiple checks here on the hot path. 1617 if ((Text.endswith(Postfix = "\"") && 1618 (Text.startswith(Prefix = "@\"") || Text.startswith(Prefix = "\"") || 1619 Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") || 1620 Text.startswith(Prefix = "u8\"") || 1621 Text.startswith(Prefix = "L\""))) || 1622 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) { 1623 // We need this to address the case where there is an unbreakable tail 1624 // only if certain other formatting decisions have been taken. The 1625 // UnbreakableTailLength of Current is an overapproximation is that case 1626 // and we need to be correct here. 1627 unsigned UnbreakableTailLength = (State.NextToken && canBreak(State)) 1628 ? 0 1629 : Current.UnbreakableTailLength; 1630 return llvm::make_unique<BreakableStringLiteral>( 1631 Current, StartColumn, Prefix, Postfix, UnbreakableTailLength, 1632 State.Line->InPPDirective, Encoding, Style); 1633 } 1634 } else if (Current.is(TT_BlockComment)) { 1635 if (!Style.ReflowComments || 1636 // If a comment token switches formatting, like 1637 // /* clang-format on */, we don't want to break it further, 1638 // but we may still want to adjust its indentation. 1639 switchesFormatting(Current)) { 1640 return nullptr; 1641 } 1642 return llvm::make_unique<BreakableBlockComment>( 1643 Current, StartColumn, Current.OriginalColumn, !Current.Previous, 1644 State.Line->InPPDirective, Encoding, Style); 1645 } else if (Current.is(TT_LineComment) && 1646 (Current.Previous == nullptr || 1647 Current.Previous->isNot(TT_ImplicitStringLiteral))) { 1648 if (!Style.ReflowComments || 1649 CommentPragmasRegex.match(Current.TokenText.substr(2)) || 1650 switchesFormatting(Current)) 1651 return nullptr; 1652 return llvm::make_unique<BreakableLineCommentSection>( 1653 Current, StartColumn, Current.OriginalColumn, !Current.Previous, 1654 /*InPPDirective=*/false, Encoding, Style); 1655 } 1656 return nullptr; 1657 } 1658 1659 std::pair<unsigned, bool> 1660 ContinuationIndenter::breakProtrudingToken(const FormatToken &Current, 1661 LineState &State, bool AllowBreak, 1662 bool DryRun, bool Strict) { 1663 std::unique_ptr<const BreakableToken> Token = 1664 createBreakableToken(Current, State, AllowBreak); 1665 if (!Token) 1666 return {0, false}; 1667 assert(Token->getLineCount() > 0); 1668 unsigned ColumnLimit = getColumnLimit(State); 1669 if (Current.is(TT_LineComment)) { 1670 // We don't insert backslashes when breaking line comments. 1671 ColumnLimit = Style.ColumnLimit; 1672 } 1673 if (Current.UnbreakableTailLength >= ColumnLimit) 1674 return {0, false}; 1675 // ColumnWidth was already accounted into State.Column before calling 1676 // breakProtrudingToken. 1677 unsigned StartColumn = State.Column - Current.ColumnWidth; 1678 unsigned NewBreakPenalty = Current.isStringLiteral() 1679 ? Style.PenaltyBreakString 1680 : Style.PenaltyBreakComment; 1681 // Stores whether we intentionally decide to let a line exceed the column 1682 // limit. 1683 bool Exceeded = false; 1684 // Stores whether we introduce a break anywhere in the token. 1685 bool BreakInserted = Token->introducesBreakBeforeToken(); 1686 // Store whether we inserted a new line break at the end of the previous 1687 // logical line. 1688 bool NewBreakBefore = false; 1689 // We use a conservative reflowing strategy. Reflow starts after a line is 1690 // broken or the corresponding whitespace compressed. Reflow ends as soon as a 1691 // line that doesn't get reflown with the previous line is reached. 1692 bool Reflow = false; 1693 // Keep track of where we are in the token: 1694 // Where we are in the content of the current logical line. 1695 unsigned TailOffset = 0; 1696 // The column number we're currently at. 1697 unsigned ContentStartColumn = 1698 Token->getContentStartColumn(0, /*Break=*/false); 1699 // The number of columns left in the current logical line after TailOffset. 1700 unsigned RemainingTokenColumns = 1701 Token->getRemainingLength(0, TailOffset, ContentStartColumn); 1702 // Adapt the start of the token, for example indent. 1703 if (!DryRun) 1704 Token->adaptStartOfLine(0, Whitespaces); 1705 1706 unsigned Penalty = 0; 1707 DEBUG(llvm::dbgs() << "Breaking protruding token at column " << StartColumn 1708 << ".\n"); 1709 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount(); 1710 LineIndex != EndIndex; ++LineIndex) { 1711 DEBUG(llvm::dbgs() << " Line: " << LineIndex << " (Reflow: " << Reflow 1712 << ")\n"); 1713 NewBreakBefore = false; 1714 // If we did reflow the previous line, we'll try reflowing again. Otherwise 1715 // we'll start reflowing if the current line is broken or whitespace is 1716 // compressed. 1717 bool TryReflow = Reflow; 1718 // Break the current token until we can fit the rest of the line. 1719 while (ContentStartColumn + RemainingTokenColumns > ColumnLimit) { 1720 DEBUG(llvm::dbgs() << " Over limit, need: " 1721 << (ContentStartColumn + RemainingTokenColumns) 1722 << ", space: " << ColumnLimit 1723 << ", reflown prefix: " << ContentStartColumn 1724 << ", offset in line: " << TailOffset << "\n"); 1725 // If the current token doesn't fit, find the latest possible split in the 1726 // current line so that breaking at it will be under the column limit. 1727 // FIXME: Use the earliest possible split while reflowing to correctly 1728 // compress whitespace within a line. 1729 BreakableToken::Split Split = 1730 Token->getSplit(LineIndex, TailOffset, ColumnLimit, 1731 ContentStartColumn, CommentPragmasRegex); 1732 if (Split.first == StringRef::npos) { 1733 // No break opportunity - update the penalty and continue with the next 1734 // logical line. 1735 if (LineIndex < EndIndex - 1) 1736 // The last line's penalty is handled in addNextStateToQueue(). 1737 Penalty += Style.PenaltyExcessCharacter * 1738 (ContentStartColumn + RemainingTokenColumns - ColumnLimit); 1739 DEBUG(llvm::dbgs() << " No break opportunity.\n"); 1740 break; 1741 } 1742 assert(Split.first != 0); 1743 1744 if (Token->supportsReflow()) { 1745 // Check whether the next natural split point after the current one can 1746 // still fit the line, either because we can compress away whitespace, 1747 // or because the penalty the excess characters introduce is lower than 1748 // the break penalty. 1749 // We only do this for tokens that support reflowing, and thus allow us 1750 // to change the whitespace arbitrarily (e.g. comments). 1751 // Other tokens, like string literals, can be broken on arbitrary 1752 // positions. 1753 1754 // First, compute the columns from TailOffset to the next possible split 1755 // position. 1756 // For example: 1757 // ColumnLimit: | 1758 // // Some text that breaks 1759 // ^ tail offset 1760 // ^-- split 1761 // ^-------- to split columns 1762 // ^--- next split 1763 // ^--------------- to next split columns 1764 unsigned ToSplitColumns = Token->getRangeLength( 1765 LineIndex, TailOffset, Split.first, ContentStartColumn); 1766 DEBUG(llvm::dbgs() << " ToSplit: " << ToSplitColumns << "\n"); 1767 1768 BreakableToken::Split NextSplit = Token->getSplit( 1769 LineIndex, TailOffset + Split.first + Split.second, ColumnLimit, 1770 ContentStartColumn + ToSplitColumns + 1, CommentPragmasRegex); 1771 // Compute the columns necessary to fit the next non-breakable sequence 1772 // into the current line. 1773 unsigned ToNextSplitColumns = 0; 1774 if (NextSplit.first == StringRef::npos) { 1775 ToNextSplitColumns = Token->getRemainingLength(LineIndex, TailOffset, 1776 ContentStartColumn); 1777 } else { 1778 ToNextSplitColumns = Token->getRangeLength( 1779 LineIndex, TailOffset, 1780 Split.first + Split.second + NextSplit.first, ContentStartColumn); 1781 } 1782 // Compress the whitespace between the break and the start of the next 1783 // unbreakable sequence. 1784 ToNextSplitColumns = 1785 Token->getLengthAfterCompression(ToNextSplitColumns, Split); 1786 DEBUG(llvm::dbgs() << " ContentStartColumn: " << ContentStartColumn 1787 << "\n"); 1788 DEBUG(llvm::dbgs() << " ToNextSplit: " << ToNextSplitColumns << "\n"); 1789 // If the whitespace compression makes us fit, continue on the current 1790 // line. 1791 bool ContinueOnLine = 1792 ContentStartColumn + ToNextSplitColumns <= ColumnLimit; 1793 unsigned ExcessCharactersPenalty = 0; 1794 if (!ContinueOnLine && !Strict) { 1795 // Similarly, if the excess characters' penalty is lower than the 1796 // penalty of introducing a new break, continue on the current line. 1797 ExcessCharactersPenalty = 1798 (ContentStartColumn + ToNextSplitColumns - ColumnLimit) * 1799 Style.PenaltyExcessCharacter; 1800 DEBUG(llvm::dbgs() 1801 << " Penalty excess: " << ExcessCharactersPenalty 1802 << "\n break : " << NewBreakPenalty << "\n"); 1803 if (ExcessCharactersPenalty < NewBreakPenalty) { 1804 Exceeded = true; 1805 ContinueOnLine = true; 1806 } 1807 } 1808 if (ContinueOnLine) { 1809 DEBUG(llvm::dbgs() << " Continuing on line...\n"); 1810 // The current line fits after compressing the whitespace - reflow 1811 // the next line into it if possible. 1812 TryReflow = true; 1813 if (!DryRun) 1814 Token->compressWhitespace(LineIndex, TailOffset, Split, 1815 Whitespaces); 1816 // When we continue on the same line, leave one space between content. 1817 ContentStartColumn += ToSplitColumns + 1; 1818 Penalty += ExcessCharactersPenalty; 1819 TailOffset += Split.first + Split.second; 1820 RemainingTokenColumns = Token->getRemainingLength( 1821 LineIndex, TailOffset, ContentStartColumn); 1822 continue; 1823 } 1824 } 1825 DEBUG(llvm::dbgs() << " Breaking...\n"); 1826 ContentStartColumn = 1827 Token->getContentStartColumn(LineIndex, /*Break=*/true); 1828 unsigned NewRemainingTokenColumns = Token->getRemainingLength( 1829 LineIndex, TailOffset + Split.first + Split.second, 1830 ContentStartColumn); 1831 1832 // When breaking before a tab character, it may be moved by a few columns, 1833 // but will still be expanded to the next tab stop, so we don't save any 1834 // columns. 1835 if (NewRemainingTokenColumns == RemainingTokenColumns) { 1836 // FIXME: Do we need to adjust the penalty? 1837 break; 1838 } 1839 assert(NewRemainingTokenColumns < RemainingTokenColumns); 1840 1841 DEBUG(llvm::dbgs() << " Breaking at: " << TailOffset + Split.first 1842 << ", " << Split.second << "\n"); 1843 if (!DryRun) 1844 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces); 1845 1846 Penalty += NewBreakPenalty; 1847 TailOffset += Split.first + Split.second; 1848 RemainingTokenColumns = NewRemainingTokenColumns; 1849 BreakInserted = true; 1850 NewBreakBefore = true; 1851 } 1852 // In case there's another line, prepare the state for the start of the next 1853 // line. 1854 if (LineIndex + 1 != EndIndex) { 1855 unsigned NextLineIndex = LineIndex + 1; 1856 if (NewBreakBefore) 1857 // After breaking a line, try to reflow the next line into the current 1858 // one once RemainingTokenColumns fits. 1859 TryReflow = true; 1860 if (TryReflow) { 1861 // We decided that we want to try reflowing the next line into the 1862 // current one. 1863 // We will now adjust the state as if the reflow is successful (in 1864 // preparation for the next line), and see whether that works. If we 1865 // decide that we cannot reflow, we will later reset the state to the 1866 // start of the next line. 1867 Reflow = false; 1868 // As we did not continue breaking the line, RemainingTokenColumns is 1869 // known to fit after ContentStartColumn. Adapt ContentStartColumn to 1870 // the position at which we want to format the next line if we do 1871 // actually reflow. 1872 // When we reflow, we need to add a space between the end of the current 1873 // line and the next line's start column. 1874 ContentStartColumn += RemainingTokenColumns + 1; 1875 // Get the split that we need to reflow next logical line into the end 1876 // of the current one; the split will include any leading whitespace of 1877 // the next logical line. 1878 BreakableToken::Split SplitBeforeNext = 1879 Token->getReflowSplit(NextLineIndex, CommentPragmasRegex); 1880 DEBUG(llvm::dbgs() << " Size of reflown text: " << ContentStartColumn 1881 << "\n Potential reflow split: "); 1882 if (SplitBeforeNext.first != StringRef::npos) { 1883 DEBUG(llvm::dbgs() << SplitBeforeNext.first << ", " 1884 << SplitBeforeNext.second << "\n"); 1885 TailOffset = SplitBeforeNext.first + SplitBeforeNext.second; 1886 // If the rest of the next line fits into the current line below the 1887 // column limit, we can safely reflow. 1888 RemainingTokenColumns = Token->getRemainingLength( 1889 NextLineIndex, TailOffset, ContentStartColumn); 1890 Reflow = true; 1891 if (ContentStartColumn + RemainingTokenColumns > ColumnLimit) { 1892 DEBUG(llvm::dbgs() << " Over limit after reflow, need: " 1893 << (ContentStartColumn + RemainingTokenColumns) 1894 << ", space: " << ColumnLimit 1895 << ", reflown prefix: " << ContentStartColumn 1896 << ", offset in line: " << TailOffset << "\n"); 1897 // If the whole next line does not fit, try to find a point in 1898 // the next line at which we can break so that attaching the part 1899 // of the next line to that break point onto the current line is 1900 // below the column limit. 1901 BreakableToken::Split Split = 1902 Token->getSplit(NextLineIndex, TailOffset, ColumnLimit, 1903 ContentStartColumn, CommentPragmasRegex); 1904 if (Split.first == StringRef::npos) { 1905 DEBUG(llvm::dbgs() << " Did not find later break\n"); 1906 Reflow = false; 1907 } else { 1908 // Check whether the first split point gets us below the column 1909 // limit. Note that we will execute this split below as part of 1910 // the normal token breaking and reflow logic within the line. 1911 unsigned ToSplitColumns = Token->getRangeLength( 1912 NextLineIndex, TailOffset, Split.first, ContentStartColumn); 1913 if (ContentStartColumn + ToSplitColumns > ColumnLimit) { 1914 DEBUG(llvm::dbgs() << " Next split protrudes, need: " 1915 << (ContentStartColumn + ToSplitColumns) 1916 << ", space: " << ColumnLimit); 1917 unsigned ExcessCharactersPenalty = 1918 (ContentStartColumn + ToSplitColumns - ColumnLimit) * 1919 Style.PenaltyExcessCharacter; 1920 if (NewBreakPenalty < ExcessCharactersPenalty) { 1921 Reflow = false; 1922 } 1923 } 1924 } 1925 } 1926 } else { 1927 DEBUG(llvm::dbgs() << "not found.\n"); 1928 } 1929 } 1930 if (!Reflow) { 1931 // If we didn't reflow into the next line, the only space to consider is 1932 // the next logical line. Reset our state to match the start of the next 1933 // line. 1934 TailOffset = 0; 1935 ContentStartColumn = 1936 Token->getContentStartColumn(NextLineIndex, /*Break=*/false); 1937 RemainingTokenColumns = Token->getRemainingLength( 1938 NextLineIndex, TailOffset, ContentStartColumn); 1939 // Adapt the start of the token, for example indent. 1940 if (!DryRun) 1941 Token->adaptStartOfLine(NextLineIndex, Whitespaces); 1942 } else { 1943 // If we found a reflow split and have added a new break before the next 1944 // line, we are going to remove the line break at the start of the next 1945 // logical line. For example, here we'll add a new line break after 1946 // 'text', and subsequently delete the line break between 'that' and 1947 // 'reflows'. 1948 // // some text that 1949 // // reflows 1950 // -> 1951 // // some text 1952 // // that reflows 1953 // When adding the line break, we also added the penalty for it, so we 1954 // need to subtract that penalty again when we remove the line break due 1955 // to reflowing. 1956 if (NewBreakBefore) { 1957 assert(Penalty >= NewBreakPenalty); 1958 Penalty -= NewBreakPenalty; 1959 } 1960 if (!DryRun) 1961 Token->reflow(NextLineIndex, Whitespaces); 1962 } 1963 } 1964 } 1965 1966 BreakableToken::Split SplitAfterLastLine = 1967 Token->getSplitAfterLastLine(TailOffset); 1968 if (SplitAfterLastLine.first != StringRef::npos) { 1969 DEBUG(llvm::dbgs() << "Replacing whitespace after last line.\n"); 1970 if (!DryRun) 1971 Token->replaceWhitespaceAfterLastLine(TailOffset, SplitAfterLastLine, 1972 Whitespaces); 1973 ContentStartColumn = 1974 Token->getContentStartColumn(Token->getLineCount() - 1, /*Break=*/true); 1975 RemainingTokenColumns = Token->getRemainingLength( 1976 Token->getLineCount() - 1, 1977 TailOffset + SplitAfterLastLine.first + SplitAfterLastLine.second, 1978 ContentStartColumn); 1979 } 1980 1981 State.Column = ContentStartColumn + RemainingTokenColumns - 1982 Current.UnbreakableTailLength; 1983 1984 if (BreakInserted) { 1985 // If we break the token inside a parameter list, we need to break before 1986 // the next parameter on all levels, so that the next parameter is clearly 1987 // visible. Line comments already introduce a break. 1988 if (Current.isNot(TT_LineComment)) { 1989 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i) 1990 State.Stack[i].BreakBeforeParameter = true; 1991 } 1992 1993 if (Current.is(TT_BlockComment)) 1994 State.NoContinuation = true; 1995 1996 State.Stack.back().LastSpace = StartColumn; 1997 } 1998 1999 Token->updateNextToken(State); 2000 2001 return {Penalty, Exceeded}; 2002 } 2003 2004 unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const { 2005 // In preprocessor directives reserve two chars for trailing " \" 2006 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0); 2007 } 2008 2009 bool ContinuationIndenter::nextIsMultilineString(const LineState &State) { 2010 const FormatToken &Current = *State.NextToken; 2011 if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral)) 2012 return false; 2013 // We never consider raw string literals "multiline" for the purpose of 2014 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased 2015 // (see TokenAnnotator::mustBreakBefore(). 2016 if (Current.TokenText.startswith("R\"")) 2017 return false; 2018 if (Current.IsMultiline) 2019 return true; 2020 if (Current.getNextNonComment() && 2021 Current.getNextNonComment()->isStringLiteral()) 2022 return true; // Implicit concatenation. 2023 if (Style.ColumnLimit != 0 && Style.BreakStringLiterals && 2024 State.Column + Current.ColumnWidth + Current.UnbreakableTailLength > 2025 Style.ColumnLimit) 2026 return true; // String will be split. 2027 return false; 2028 } 2029 2030 } // namespace format 2031 } // namespace clang 2032