1 //===--- TokenAnnotator.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 a token annotator, i.e. creates 11 /// \c AnnotatedTokens out of \c FormatTokens with required extra information. 12 /// 13 //===----------------------------------------------------------------------===// 14 15 #include "TokenAnnotator.h" 16 #include "FormatToken.h" 17 #include "clang/Basic/SourceManager.h" 18 #include "clang/Basic/TokenKinds.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/Support/Debug.h" 21 22 #define DEBUG_TYPE "format-token-annotator" 23 24 namespace clang { 25 namespace format { 26 27 namespace { 28 29 /// Returns \c true if the line starts with a token that can start a statement 30 /// with an initializer. 31 static bool startsWithInitStatement(const AnnotatedLine &Line) { 32 return Line.startsWith(tok::kw_for) || Line.startsWith(tok::kw_if) || 33 Line.startsWith(tok::kw_switch); 34 } 35 36 /// Returns \c true if the token can be used as an identifier in 37 /// an Objective-C \c \@selector, \c false otherwise. 38 /// 39 /// Because getFormattingLangOpts() always lexes source code as 40 /// Objective-C++, C++ keywords like \c new and \c delete are 41 /// lexed as tok::kw_*, not tok::identifier, even for Objective-C. 42 /// 43 /// For Objective-C and Objective-C++, both identifiers and keywords 44 /// are valid inside @selector(...) (or a macro which 45 /// invokes @selector(...)). So, we allow treat any identifier or 46 /// keyword as a potential Objective-C selector component. 47 static bool canBeObjCSelectorComponent(const FormatToken &Tok) { 48 return Tok.Tok.getIdentifierInfo() != nullptr; 49 } 50 51 /// With `Left` being '(', check if we're at either `[...](` or 52 /// `[...]<...>(`, where the [ opens a lambda capture list. 53 static bool isLambdaParameterList(const FormatToken *Left) { 54 // Skip <...> if present. 55 if (Left->Previous && Left->Previous->is(tok::greater) && 56 Left->Previous->MatchingParen && 57 Left->Previous->MatchingParen->is(TT_TemplateOpener)) 58 Left = Left->Previous->MatchingParen; 59 60 // Check for `[...]`. 61 return Left->Previous && Left->Previous->is(tok::r_square) && 62 Left->Previous->MatchingParen && 63 Left->Previous->MatchingParen->is(TT_LambdaLSquare); 64 } 65 66 /// Returns \c true if the token is followed by a boolean condition, \c false 67 /// otherwise. 68 static bool isKeywordWithCondition(const FormatToken &Tok) { 69 return Tok.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while, tok::kw_switch, 70 tok::kw_constexpr, tok::kw_catch); 71 } 72 73 /// A parser that gathers additional information about tokens. 74 /// 75 /// The \c TokenAnnotator tries to match parenthesis and square brakets and 76 /// store a parenthesis levels. It also tries to resolve matching "<" and ">" 77 /// into template parameter lists. 78 class AnnotatingParser { 79 public: 80 AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line, 81 const AdditionalKeywords &Keywords) 82 : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false), 83 Keywords(Keywords) { 84 Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false)); 85 resetTokenMetadata(); 86 } 87 88 private: 89 bool parseAngle() { 90 if (!CurrentToken || !CurrentToken->Previous) 91 return false; 92 if (NonTemplateLess.count(CurrentToken->Previous)) 93 return false; 94 95 const FormatToken &Previous = *CurrentToken->Previous; // The '<'. 96 if (Previous.Previous) { 97 if (Previous.Previous->Tok.isLiteral()) 98 return false; 99 if (Previous.Previous->is(tok::r_paren) && Contexts.size() > 1 && 100 (!Previous.Previous->MatchingParen || 101 !Previous.Previous->MatchingParen->is(TT_OverloadedOperatorLParen))) 102 return false; 103 } 104 105 FormatToken *Left = CurrentToken->Previous; 106 Left->ParentBracket = Contexts.back().ContextKind; 107 ScopedContextCreator ContextCreator(*this, tok::less, 12); 108 109 // If this angle is in the context of an expression, we need to be more 110 // hesitant to detect it as opening template parameters. 111 bool InExprContext = Contexts.back().IsExpression; 112 113 Contexts.back().IsExpression = false; 114 // If there's a template keyword before the opening angle bracket, this is a 115 // template parameter, not an argument. 116 Contexts.back().InTemplateArgument = 117 Left->Previous && Left->Previous->isNot(tok::kw_template); 118 119 if (Style.Language == FormatStyle::LK_Java && 120 CurrentToken->is(tok::question)) 121 next(); 122 123 while (CurrentToken) { 124 if (CurrentToken->is(tok::greater)) { 125 // Try to do a better job at looking for ">>" within the condition of 126 // a statement. Conservatively insert spaces between consecutive ">" 127 // tokens to prevent splitting right bitshift operators and potentially 128 // altering program semantics. This check is overly conservative and 129 // will prevent spaces from being inserted in select nested template 130 // parameter cases, but should not alter program semantics. 131 if (CurrentToken->Next && CurrentToken->Next->is(tok::greater) && 132 Left->ParentBracket != tok::less && 133 (isKeywordWithCondition(*Line.First) || 134 CurrentToken->getStartOfNonWhitespace() == 135 CurrentToken->Next->getStartOfNonWhitespace().getLocWithOffset( 136 -1))) 137 return false; 138 Left->MatchingParen = CurrentToken; 139 CurrentToken->MatchingParen = Left; 140 // In TT_Proto, we must distignuish between: 141 // map<key, value> 142 // msg < item: data > 143 // msg: < item: data > 144 // In TT_TextProto, map<key, value> does not occur. 145 if (Style.Language == FormatStyle::LK_TextProto || 146 (Style.Language == FormatStyle::LK_Proto && Left->Previous && 147 Left->Previous->isOneOf(TT_SelectorName, TT_DictLiteral))) 148 CurrentToken->setType(TT_DictLiteral); 149 else 150 CurrentToken->setType(TT_TemplateCloser); 151 next(); 152 return true; 153 } 154 if (CurrentToken->is(tok::question) && 155 Style.Language == FormatStyle::LK_Java) { 156 next(); 157 continue; 158 } 159 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace) || 160 (CurrentToken->isOneOf(tok::colon, tok::question) && InExprContext && 161 !Style.isCSharp() && Style.Language != FormatStyle::LK_Proto && 162 Style.Language != FormatStyle::LK_TextProto)) 163 return false; 164 // If a && or || is found and interpreted as a binary operator, this set 165 // of angles is likely part of something like "a < b && c > d". If the 166 // angles are inside an expression, the ||/&& might also be a binary 167 // operator that was misinterpreted because we are parsing template 168 // parameters. 169 // FIXME: This is getting out of hand, write a decent parser. 170 if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) && 171 CurrentToken->Previous->is(TT_BinaryOperator) && 172 Contexts[Contexts.size() - 2].IsExpression && 173 !Line.startsWith(tok::kw_template)) 174 return false; 175 updateParameterCount(Left, CurrentToken); 176 if (Style.Language == FormatStyle::LK_Proto) { 177 if (FormatToken *Previous = CurrentToken->getPreviousNonComment()) { 178 if (CurrentToken->is(tok::colon) || 179 (CurrentToken->isOneOf(tok::l_brace, tok::less) && 180 Previous->isNot(tok::colon))) 181 Previous->setType(TT_SelectorName); 182 } 183 } 184 if (!consumeToken()) 185 return false; 186 } 187 return false; 188 } 189 190 bool parseUntouchableParens() { 191 while (CurrentToken) { 192 CurrentToken->Finalized = true; 193 switch (CurrentToken->Tok.getKind()) { 194 case tok::l_paren: 195 next(); 196 if (!parseUntouchableParens()) 197 return false; 198 continue; 199 case tok::r_paren: 200 next(); 201 return true; 202 default: 203 // no-op 204 break; 205 } 206 next(); 207 } 208 return false; 209 } 210 211 bool parseParens(bool LookForDecls = false) { 212 if (!CurrentToken) 213 return false; 214 assert(CurrentToken->Previous && "Unknown previous token"); 215 FormatToken &OpeningParen = *CurrentToken->Previous; 216 assert(OpeningParen.is(tok::l_paren)); 217 FormatToken *PrevNonComment = OpeningParen.getPreviousNonComment(); 218 OpeningParen.ParentBracket = Contexts.back().ContextKind; 219 ScopedContextCreator ContextCreator(*this, tok::l_paren, 1); 220 221 // FIXME: This is a bit of a hack. Do better. 222 Contexts.back().ColonIsForRangeExpr = 223 Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr; 224 225 if (OpeningParen.Previous && 226 OpeningParen.Previous->is(TT_UntouchableMacroFunc)) { 227 OpeningParen.Finalized = true; 228 return parseUntouchableParens(); 229 } 230 231 bool StartsObjCMethodExpr = false; 232 if (FormatToken *MaybeSel = OpeningParen.Previous) { 233 // @selector( starts a selector. 234 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous && 235 MaybeSel->Previous->is(tok::at)) 236 StartsObjCMethodExpr = true; 237 } 238 239 if (OpeningParen.is(TT_OverloadedOperatorLParen)) { 240 // Find the previous kw_operator token. 241 FormatToken *Prev = &OpeningParen; 242 while (!Prev->is(tok::kw_operator)) { 243 Prev = Prev->Previous; 244 assert(Prev && "Expect a kw_operator prior to the OperatorLParen!"); 245 } 246 247 // If faced with "a.operator*(argument)" or "a->operator*(argument)", 248 // i.e. the operator is called as a member function, 249 // then the argument must be an expression. 250 bool OperatorCalledAsMemberFunction = 251 Prev->Previous && Prev->Previous->isOneOf(tok::period, tok::arrow); 252 Contexts.back().IsExpression = OperatorCalledAsMemberFunction; 253 } else if (Style.isJavaScript() && 254 (Line.startsWith(Keywords.kw_type, tok::identifier) || 255 Line.startsWith(tok::kw_export, Keywords.kw_type, 256 tok::identifier))) { 257 // type X = (...); 258 // export type X = (...); 259 Contexts.back().IsExpression = false; 260 } else if (OpeningParen.Previous && 261 (OpeningParen.Previous->isOneOf(tok::kw_static_assert, 262 tok::kw_while, tok::l_paren, 263 tok::comma) || 264 OpeningParen.Previous->isIf() || 265 OpeningParen.Previous->is(TT_BinaryOperator))) { 266 // static_assert, if and while usually contain expressions. 267 Contexts.back().IsExpression = true; 268 } else if (Style.isJavaScript() && OpeningParen.Previous && 269 (OpeningParen.Previous->is(Keywords.kw_function) || 270 (OpeningParen.Previous->endsSequence(tok::identifier, 271 Keywords.kw_function)))) { 272 // function(...) or function f(...) 273 Contexts.back().IsExpression = false; 274 } else if (Style.isJavaScript() && OpeningParen.Previous && 275 OpeningParen.Previous->is(TT_JsTypeColon)) { 276 // let x: (SomeType); 277 Contexts.back().IsExpression = false; 278 } else if (isLambdaParameterList(&OpeningParen)) { 279 // This is a parameter list of a lambda expression. 280 Contexts.back().IsExpression = false; 281 } else if (Line.InPPDirective && 282 (!OpeningParen.Previous || 283 !OpeningParen.Previous->is(tok::identifier))) { 284 Contexts.back().IsExpression = true; 285 } else if (Contexts[Contexts.size() - 2].CaretFound) { 286 // This is the parameter list of an ObjC block. 287 Contexts.back().IsExpression = false; 288 } else if (OpeningParen.Previous && 289 OpeningParen.Previous->is(TT_ForEachMacro)) { 290 // The first argument to a foreach macro is a declaration. 291 Contexts.back().IsForEachMacro = true; 292 Contexts.back().IsExpression = false; 293 } else if (OpeningParen.Previous && OpeningParen.Previous->MatchingParen && 294 OpeningParen.Previous->MatchingParen->is(TT_ObjCBlockLParen)) { 295 Contexts.back().IsExpression = false; 296 } else if (!Line.MustBeDeclaration && !Line.InPPDirective) { 297 bool IsForOrCatch = 298 OpeningParen.Previous && 299 OpeningParen.Previous->isOneOf(tok::kw_for, tok::kw_catch); 300 Contexts.back().IsExpression = !IsForOrCatch; 301 } 302 303 // Infer the role of the l_paren based on the previous token if we haven't 304 // detected one one yet. 305 if (PrevNonComment && OpeningParen.is(TT_Unknown)) { 306 if (PrevNonComment->is(tok::kw___attribute)) { 307 OpeningParen.setType(TT_AttributeParen); 308 } else if (PrevNonComment->isOneOf(TT_TypenameMacro, tok::kw_decltype, 309 tok::kw_typeof, tok::kw__Atomic, 310 tok::kw___underlying_type)) { 311 OpeningParen.setType(TT_TypeDeclarationParen); 312 // decltype() and typeof() usually contain expressions. 313 if (PrevNonComment->isOneOf(tok::kw_decltype, tok::kw_typeof)) 314 Contexts.back().IsExpression = true; 315 } 316 } 317 318 if (StartsObjCMethodExpr) { 319 Contexts.back().ColonIsObjCMethodExpr = true; 320 OpeningParen.setType(TT_ObjCMethodExpr); 321 } 322 323 // MightBeFunctionType and ProbablyFunctionType are used for 324 // function pointer and reference types as well as Objective-C 325 // block types: 326 // 327 // void (*FunctionPointer)(void); 328 // void (&FunctionReference)(void); 329 // void (&&FunctionReference)(void); 330 // void (^ObjCBlock)(void); 331 bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression; 332 bool ProbablyFunctionType = 333 CurrentToken->isOneOf(tok::star, tok::amp, tok::ampamp, tok::caret); 334 bool HasMultipleLines = false; 335 bool HasMultipleParametersOnALine = false; 336 bool MightBeObjCForRangeLoop = 337 OpeningParen.Previous && OpeningParen.Previous->is(tok::kw_for); 338 FormatToken *PossibleObjCForInToken = nullptr; 339 while (CurrentToken) { 340 // LookForDecls is set when "if (" has been seen. Check for 341 // 'identifier' '*' 'identifier' followed by not '=' -- this 342 // '*' has to be a binary operator but determineStarAmpUsage() will 343 // categorize it as an unary operator, so set the right type here. 344 if (LookForDecls && CurrentToken->Next) { 345 FormatToken *Prev = CurrentToken->getPreviousNonComment(); 346 if (Prev) { 347 FormatToken *PrevPrev = Prev->getPreviousNonComment(); 348 FormatToken *Next = CurrentToken->Next; 349 if (PrevPrev && PrevPrev->is(tok::identifier) && 350 Prev->isOneOf(tok::star, tok::amp, tok::ampamp) && 351 CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) { 352 Prev->setType(TT_BinaryOperator); 353 LookForDecls = false; 354 } 355 } 356 } 357 358 if (CurrentToken->Previous->is(TT_PointerOrReference) && 359 CurrentToken->Previous->Previous->isOneOf(tok::l_paren, 360 tok::coloncolon)) 361 ProbablyFunctionType = true; 362 if (CurrentToken->is(tok::comma)) 363 MightBeFunctionType = false; 364 if (CurrentToken->Previous->is(TT_BinaryOperator)) 365 Contexts.back().IsExpression = true; 366 if (CurrentToken->is(tok::r_paren)) { 367 if (OpeningParen.isNot(TT_CppCastLParen) && MightBeFunctionType && 368 ProbablyFunctionType && CurrentToken->Next && 369 (CurrentToken->Next->is(tok::l_paren) || 370 (CurrentToken->Next->is(tok::l_square) && Line.MustBeDeclaration))) 371 OpeningParen.setType(OpeningParen.Next->is(tok::caret) 372 ? TT_ObjCBlockLParen 373 : TT_FunctionTypeLParen); 374 OpeningParen.MatchingParen = CurrentToken; 375 CurrentToken->MatchingParen = &OpeningParen; 376 377 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) && 378 OpeningParen.Previous && OpeningParen.Previous->is(tok::l_paren)) { 379 // Detect the case where macros are used to generate lambdas or 380 // function bodies, e.g.: 381 // auto my_lambda = MACRO((Type *type, int i) { .. body .. }); 382 for (FormatToken *Tok = &OpeningParen; Tok != CurrentToken; 383 Tok = Tok->Next) 384 if (Tok->is(TT_BinaryOperator) && 385 Tok->isOneOf(tok::star, tok::amp, tok::ampamp)) 386 Tok->setType(TT_PointerOrReference); 387 } 388 389 if (StartsObjCMethodExpr) { 390 CurrentToken->setType(TT_ObjCMethodExpr); 391 if (Contexts.back().FirstObjCSelectorName) { 392 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 393 Contexts.back().LongestObjCSelectorName; 394 } 395 } 396 397 if (OpeningParen.is(TT_AttributeParen)) 398 CurrentToken->setType(TT_AttributeParen); 399 if (OpeningParen.is(TT_TypeDeclarationParen)) 400 CurrentToken->setType(TT_TypeDeclarationParen); 401 if (OpeningParen.Previous && 402 OpeningParen.Previous->is(TT_JavaAnnotation)) 403 CurrentToken->setType(TT_JavaAnnotation); 404 if (OpeningParen.Previous && 405 OpeningParen.Previous->is(TT_LeadingJavaAnnotation)) 406 CurrentToken->setType(TT_LeadingJavaAnnotation); 407 if (OpeningParen.Previous && 408 OpeningParen.Previous->is(TT_AttributeSquare)) 409 CurrentToken->setType(TT_AttributeSquare); 410 411 if (!HasMultipleLines) 412 OpeningParen.setPackingKind(PPK_Inconclusive); 413 else if (HasMultipleParametersOnALine) 414 OpeningParen.setPackingKind(PPK_BinPacked); 415 else 416 OpeningParen.setPackingKind(PPK_OnePerLine); 417 418 next(); 419 return true; 420 } 421 if (CurrentToken->isOneOf(tok::r_square, tok::r_brace)) 422 return false; 423 424 if (CurrentToken->is(tok::l_brace) && OpeningParen.is(TT_ObjCBlockLParen)) 425 OpeningParen.setType(TT_Unknown); 426 if (CurrentToken->is(tok::comma) && CurrentToken->Next && 427 !CurrentToken->Next->HasUnescapedNewline && 428 !CurrentToken->Next->isTrailingComment()) 429 HasMultipleParametersOnALine = true; 430 bool ProbablyFunctionTypeLParen = 431 (CurrentToken->is(tok::l_paren) && CurrentToken->Next && 432 CurrentToken->Next->isOneOf(tok::star, tok::amp, tok::caret)); 433 if ((CurrentToken->Previous->isOneOf(tok::kw_const, tok::kw_auto) || 434 CurrentToken->Previous->isSimpleTypeSpecifier()) && 435 !(CurrentToken->is(tok::l_brace) || 436 (CurrentToken->is(tok::l_paren) && !ProbablyFunctionTypeLParen))) 437 Contexts.back().IsExpression = false; 438 if (CurrentToken->isOneOf(tok::semi, tok::colon)) { 439 MightBeObjCForRangeLoop = false; 440 if (PossibleObjCForInToken) { 441 PossibleObjCForInToken->setType(TT_Unknown); 442 PossibleObjCForInToken = nullptr; 443 } 444 } 445 if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) { 446 PossibleObjCForInToken = CurrentToken; 447 PossibleObjCForInToken->setType(TT_ObjCForIn); 448 } 449 // When we discover a 'new', we set CanBeExpression to 'false' in order to 450 // parse the type correctly. Reset that after a comma. 451 if (CurrentToken->is(tok::comma)) 452 Contexts.back().CanBeExpression = true; 453 454 FormatToken *Tok = CurrentToken; 455 if (!consumeToken()) 456 return false; 457 updateParameterCount(&OpeningParen, Tok); 458 if (CurrentToken && CurrentToken->HasUnescapedNewline) 459 HasMultipleLines = true; 460 } 461 return false; 462 } 463 464 bool isCSharpAttributeSpecifier(const FormatToken &Tok) { 465 if (!Style.isCSharp()) 466 return false; 467 468 // `identifier[i]` is not an attribute. 469 if (Tok.Previous && Tok.Previous->is(tok::identifier)) 470 return false; 471 472 // Chains of [] in `identifier[i][j][k]` are not attributes. 473 if (Tok.Previous && Tok.Previous->is(tok::r_square)) { 474 auto *MatchingParen = Tok.Previous->MatchingParen; 475 if (!MatchingParen || MatchingParen->is(TT_ArraySubscriptLSquare)) 476 return false; 477 } 478 479 const FormatToken *AttrTok = Tok.Next; 480 if (!AttrTok) 481 return false; 482 483 // Just an empty declaration e.g. string []. 484 if (AttrTok->is(tok::r_square)) 485 return false; 486 487 // Move along the tokens inbetween the '[' and ']' e.g. [STAThread]. 488 while (AttrTok && AttrTok->isNot(tok::r_square)) 489 AttrTok = AttrTok->Next; 490 491 if (!AttrTok) 492 return false; 493 494 // Allow an attribute to be the only content of a file. 495 AttrTok = AttrTok->Next; 496 if (!AttrTok) 497 return true; 498 499 // Limit this to being an access modifier that follows. 500 if (AttrTok->isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected, 501 tok::comment, tok::kw_class, tok::kw_static, 502 tok::l_square, Keywords.kw_internal)) 503 return true; 504 505 // incase its a [XXX] retval func(.... 506 if (AttrTok->Next && 507 AttrTok->Next->startsSequence(tok::identifier, tok::l_paren)) 508 return true; 509 510 return false; 511 } 512 513 bool isCpp11AttributeSpecifier(const FormatToken &Tok) { 514 if (!Style.isCpp() || !Tok.startsSequence(tok::l_square, tok::l_square)) 515 return false; 516 // The first square bracket is part of an ObjC array literal 517 if (Tok.Previous && Tok.Previous->is(tok::at)) 518 return false; 519 const FormatToken *AttrTok = Tok.Next->Next; 520 if (!AttrTok) 521 return false; 522 // C++17 '[[using ns: foo, bar(baz, blech)]]' 523 // We assume nobody will name an ObjC variable 'using'. 524 if (AttrTok->startsSequence(tok::kw_using, tok::identifier, tok::colon)) 525 return true; 526 if (AttrTok->isNot(tok::identifier)) 527 return false; 528 while (AttrTok && !AttrTok->startsSequence(tok::r_square, tok::r_square)) { 529 // ObjC message send. We assume nobody will use : in a C++11 attribute 530 // specifier parameter, although this is technically valid: 531 // [[foo(:)]]. 532 if (AttrTok->is(tok::colon) || 533 AttrTok->startsSequence(tok::identifier, tok::identifier) || 534 AttrTok->startsSequence(tok::r_paren, tok::identifier)) 535 return false; 536 if (AttrTok->is(tok::ellipsis)) 537 return true; 538 AttrTok = AttrTok->Next; 539 } 540 return AttrTok && AttrTok->startsSequence(tok::r_square, tok::r_square); 541 } 542 543 bool parseSquare() { 544 if (!CurrentToken) 545 return false; 546 547 // A '[' could be an index subscript (after an identifier or after 548 // ')' or ']'), it could be the start of an Objective-C method 549 // expression, it could the start of an Objective-C array literal, 550 // or it could be a C++ attribute specifier [[foo::bar]]. 551 FormatToken *Left = CurrentToken->Previous; 552 Left->ParentBracket = Contexts.back().ContextKind; 553 FormatToken *Parent = Left->getPreviousNonComment(); 554 555 // Cases where '>' is followed by '['. 556 // In C++, this can happen either in array of templates (foo<int>[10]) 557 // or when array is a nested template type (unique_ptr<type1<type2>[]>). 558 bool CppArrayTemplates = 559 Style.isCpp() && Parent && Parent->is(TT_TemplateCloser) && 560 (Contexts.back().CanBeExpression || Contexts.back().IsExpression || 561 Contexts.back().InTemplateArgument); 562 563 bool IsCpp11AttributeSpecifier = isCpp11AttributeSpecifier(*Left) || 564 Contexts.back().InCpp11AttributeSpecifier; 565 566 // Treat C# Attributes [STAThread] much like C++ attributes [[...]]. 567 bool IsCSharpAttributeSpecifier = 568 isCSharpAttributeSpecifier(*Left) || 569 Contexts.back().InCSharpAttributeSpecifier; 570 571 bool InsideInlineASM = Line.startsWith(tok::kw_asm); 572 bool IsCppStructuredBinding = Left->isCppStructuredBinding(Style); 573 bool StartsObjCMethodExpr = 574 !IsCppStructuredBinding && !InsideInlineASM && !CppArrayTemplates && 575 Style.isCpp() && !IsCpp11AttributeSpecifier && 576 !IsCSharpAttributeSpecifier && Contexts.back().CanBeExpression && 577 Left->isNot(TT_LambdaLSquare) && 578 !CurrentToken->isOneOf(tok::l_brace, tok::r_square) && 579 (!Parent || 580 Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren, 581 tok::kw_return, tok::kw_throw) || 582 Parent->isUnaryOperator() || 583 // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen. 584 Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) || 585 (getBinOpPrecedence(Parent->Tok.getKind(), true, true) > 586 prec::Unknown)); 587 bool ColonFound = false; 588 589 unsigned BindingIncrease = 1; 590 if (IsCppStructuredBinding) { 591 Left->setType(TT_StructuredBindingLSquare); 592 } else if (Left->is(TT_Unknown)) { 593 if (StartsObjCMethodExpr) { 594 Left->setType(TT_ObjCMethodExpr); 595 } else if (InsideInlineASM) { 596 Left->setType(TT_InlineASMSymbolicNameLSquare); 597 } else if (IsCpp11AttributeSpecifier) { 598 Left->setType(TT_AttributeSquare); 599 } else if (Style.isJavaScript() && Parent && 600 Contexts.back().ContextKind == tok::l_brace && 601 Parent->isOneOf(tok::l_brace, tok::comma)) { 602 Left->setType(TT_JsComputedPropertyName); 603 } else if (Style.isCpp() && Contexts.back().ContextKind == tok::l_brace && 604 Parent && Parent->isOneOf(tok::l_brace, tok::comma)) { 605 Left->setType(TT_DesignatedInitializerLSquare); 606 } else if (IsCSharpAttributeSpecifier) { 607 Left->setType(TT_AttributeSquare); 608 } else if (CurrentToken->is(tok::r_square) && Parent && 609 Parent->is(TT_TemplateCloser)) { 610 Left->setType(TT_ArraySubscriptLSquare); 611 } else if (Style.Language == FormatStyle::LK_Proto || 612 Style.Language == FormatStyle::LK_TextProto) { 613 // Square braces in LK_Proto can either be message field attributes: 614 // 615 // optional Aaa aaa = 1 [ 616 // (aaa) = aaa 617 // ]; 618 // 619 // extensions 123 [ 620 // (aaa) = aaa 621 // ]; 622 // 623 // or text proto extensions (in options): 624 // 625 // option (Aaa.options) = { 626 // [type.type/type] { 627 // key: value 628 // } 629 // } 630 // 631 // or repeated fields (in options): 632 // 633 // option (Aaa.options) = { 634 // keys: [ 1, 2, 3 ] 635 // } 636 // 637 // In the first and the third case we want to spread the contents inside 638 // the square braces; in the second we want to keep them inline. 639 Left->setType(TT_ArrayInitializerLSquare); 640 if (!Left->endsSequence(tok::l_square, tok::numeric_constant, 641 tok::equal) && 642 !Left->endsSequence(tok::l_square, tok::numeric_constant, 643 tok::identifier) && 644 !Left->endsSequence(tok::l_square, tok::colon, TT_SelectorName)) { 645 Left->setType(TT_ProtoExtensionLSquare); 646 BindingIncrease = 10; 647 } 648 } else if (!CppArrayTemplates && Parent && 649 Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at, 650 tok::comma, tok::l_paren, tok::l_square, 651 tok::question, tok::colon, tok::kw_return, 652 // Should only be relevant to JavaScript: 653 tok::kw_default)) { 654 Left->setType(TT_ArrayInitializerLSquare); 655 } else { 656 BindingIncrease = 10; 657 Left->setType(TT_ArraySubscriptLSquare); 658 } 659 } 660 661 ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease); 662 Contexts.back().IsExpression = true; 663 if (Style.isJavaScript() && Parent && Parent->is(TT_JsTypeColon)) 664 Contexts.back().IsExpression = false; 665 666 Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr; 667 Contexts.back().InCpp11AttributeSpecifier = IsCpp11AttributeSpecifier; 668 Contexts.back().InCSharpAttributeSpecifier = IsCSharpAttributeSpecifier; 669 670 while (CurrentToken) { 671 if (CurrentToken->is(tok::r_square)) { 672 if (IsCpp11AttributeSpecifier) 673 CurrentToken->setType(TT_AttributeSquare); 674 if (IsCSharpAttributeSpecifier) 675 CurrentToken->setType(TT_AttributeSquare); 676 else if (((CurrentToken->Next && 677 CurrentToken->Next->is(tok::l_paren)) || 678 (CurrentToken->Previous && 679 CurrentToken->Previous->Previous == Left)) && 680 Left->is(TT_ObjCMethodExpr)) { 681 // An ObjC method call is rarely followed by an open parenthesis. It 682 // also can't be composed of just one token, unless it's a macro that 683 // will be expanded to more tokens. 684 // FIXME: Do we incorrectly label ":" with this? 685 StartsObjCMethodExpr = false; 686 Left->setType(TT_Unknown); 687 } 688 if (StartsObjCMethodExpr && CurrentToken->Previous != Left) { 689 CurrentToken->setType(TT_ObjCMethodExpr); 690 // If we haven't seen a colon yet, make sure the last identifier 691 // before the r_square is tagged as a selector name component. 692 if (!ColonFound && CurrentToken->Previous && 693 CurrentToken->Previous->is(TT_Unknown) && 694 canBeObjCSelectorComponent(*CurrentToken->Previous)) 695 CurrentToken->Previous->setType(TT_SelectorName); 696 // determineStarAmpUsage() thinks that '*' '[' is allocating an 697 // array of pointers, but if '[' starts a selector then '*' is a 698 // binary operator. 699 if (Parent && Parent->is(TT_PointerOrReference)) 700 Parent->overwriteFixedType(TT_BinaryOperator); 701 } 702 // An arrow after an ObjC method expression is not a lambda arrow. 703 if (CurrentToken->getType() == TT_ObjCMethodExpr && 704 CurrentToken->Next && CurrentToken->Next->is(TT_LambdaArrow)) 705 CurrentToken->Next->overwriteFixedType(TT_Unknown); 706 Left->MatchingParen = CurrentToken; 707 CurrentToken->MatchingParen = Left; 708 // FirstObjCSelectorName is set when a colon is found. This does 709 // not work, however, when the method has no parameters. 710 // Here, we set FirstObjCSelectorName when the end of the method call is 711 // reached, in case it was not set already. 712 if (!Contexts.back().FirstObjCSelectorName) { 713 FormatToken *Previous = CurrentToken->getPreviousNonComment(); 714 if (Previous && Previous->is(TT_SelectorName)) { 715 Previous->ObjCSelectorNameParts = 1; 716 Contexts.back().FirstObjCSelectorName = Previous; 717 } 718 } else { 719 Left->ParameterCount = 720 Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts; 721 } 722 if (Contexts.back().FirstObjCSelectorName) { 723 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 724 Contexts.back().LongestObjCSelectorName; 725 if (Left->BlockParameterCount > 1) 726 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0; 727 } 728 next(); 729 return true; 730 } 731 if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace)) 732 return false; 733 if (CurrentToken->is(tok::colon)) { 734 if (IsCpp11AttributeSpecifier && 735 CurrentToken->endsSequence(tok::colon, tok::identifier, 736 tok::kw_using)) { 737 // Remember that this is a [[using ns: foo]] C++ attribute, so we 738 // don't add a space before the colon (unlike other colons). 739 CurrentToken->setType(TT_AttributeColon); 740 } else if (Left->isOneOf(TT_ArraySubscriptLSquare, 741 TT_DesignatedInitializerLSquare)) { 742 Left->setType(TT_ObjCMethodExpr); 743 StartsObjCMethodExpr = true; 744 Contexts.back().ColonIsObjCMethodExpr = true; 745 if (Parent && Parent->is(tok::r_paren)) 746 // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen. 747 Parent->setType(TT_CastRParen); 748 } 749 ColonFound = true; 750 } 751 if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) && 752 !ColonFound) 753 Left->setType(TT_ArrayInitializerLSquare); 754 FormatToken *Tok = CurrentToken; 755 if (!consumeToken()) 756 return false; 757 updateParameterCount(Left, Tok); 758 } 759 return false; 760 } 761 762 bool couldBeInStructArrayInitializer() const { 763 if (Contexts.size() < 2) 764 return false; 765 // We want to back up no more then 2 context levels i.e. 766 // . { { <- 767 const auto End = std::next(Contexts.rbegin(), 2); 768 auto Last = Contexts.rbegin(); 769 unsigned Depth = 0; 770 for (; Last != End; ++Last) 771 if (Last->ContextKind == tok::l_brace) 772 ++Depth; 773 return Depth == 2 && Last->ContextKind != tok::l_brace; 774 } 775 776 bool parseBrace() { 777 if (!CurrentToken) 778 return true; 779 780 assert(CurrentToken->Previous); 781 FormatToken &OpeningBrace = *CurrentToken->Previous; 782 assert(OpeningBrace.is(tok::l_brace)); 783 OpeningBrace.ParentBracket = Contexts.back().ContextKind; 784 785 if (Contexts.back().CaretFound) 786 OpeningBrace.setType(TT_ObjCBlockLBrace); 787 Contexts.back().CaretFound = false; 788 789 ScopedContextCreator ContextCreator(*this, tok::l_brace, 1); 790 Contexts.back().ColonIsDictLiteral = true; 791 if (OpeningBrace.is(BK_BracedInit)) 792 Contexts.back().IsExpression = true; 793 if (Style.isJavaScript() && OpeningBrace.Previous && 794 OpeningBrace.Previous->is(TT_JsTypeColon)) 795 Contexts.back().IsExpression = false; 796 797 unsigned CommaCount = 0; 798 while (CurrentToken) { 799 if (CurrentToken->is(tok::r_brace)) { 800 assert(OpeningBrace.Optional == CurrentToken->Optional); 801 OpeningBrace.MatchingParen = CurrentToken; 802 CurrentToken->MatchingParen = &OpeningBrace; 803 if (Style.AlignArrayOfStructures != FormatStyle::AIAS_None) { 804 if (OpeningBrace.ParentBracket == tok::l_brace && 805 couldBeInStructArrayInitializer() && CommaCount > 0) 806 Contexts.back().InStructArrayInitializer = true; 807 } 808 next(); 809 return true; 810 } 811 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square)) 812 return false; 813 updateParameterCount(&OpeningBrace, CurrentToken); 814 if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) { 815 FormatToken *Previous = CurrentToken->getPreviousNonComment(); 816 if (Previous->is(TT_JsTypeOptionalQuestion)) 817 Previous = Previous->getPreviousNonComment(); 818 if ((CurrentToken->is(tok::colon) && 819 (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) || 820 Style.Language == FormatStyle::LK_Proto || 821 Style.Language == FormatStyle::LK_TextProto) { 822 OpeningBrace.setType(TT_DictLiteral); 823 if (Previous->Tok.getIdentifierInfo() || 824 Previous->is(tok::string_literal)) 825 Previous->setType(TT_SelectorName); 826 } 827 if (CurrentToken->is(tok::colon) && OpeningBrace.is(TT_Unknown)) 828 OpeningBrace.setType(TT_DictLiteral); 829 else if (Style.isJavaScript()) 830 OpeningBrace.overwriteFixedType(TT_DictLiteral); 831 } 832 if (CurrentToken->is(tok::comma)) { 833 if (Style.isJavaScript()) 834 OpeningBrace.overwriteFixedType(TT_DictLiteral); 835 ++CommaCount; 836 } 837 if (!consumeToken()) 838 return false; 839 } 840 return true; 841 } 842 843 void updateParameterCount(FormatToken *Left, FormatToken *Current) { 844 // For ObjC methods, the number of parameters is calculated differently as 845 // method declarations have a different structure (the parameters are not 846 // inside a bracket scope). 847 if (Current->is(tok::l_brace) && Current->is(BK_Block)) 848 ++Left->BlockParameterCount; 849 if (Current->is(tok::comma)) { 850 ++Left->ParameterCount; 851 if (!Left->Role) 852 Left->Role.reset(new CommaSeparatedList(Style)); 853 Left->Role->CommaFound(Current); 854 } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) { 855 Left->ParameterCount = 1; 856 } 857 } 858 859 bool parseConditional() { 860 while (CurrentToken) { 861 if (CurrentToken->is(tok::colon)) { 862 CurrentToken->setType(TT_ConditionalExpr); 863 next(); 864 return true; 865 } 866 if (!consumeToken()) 867 return false; 868 } 869 return false; 870 } 871 872 bool parseTemplateDeclaration() { 873 if (CurrentToken && CurrentToken->is(tok::less)) { 874 CurrentToken->setType(TT_TemplateOpener); 875 next(); 876 if (!parseAngle()) 877 return false; 878 if (CurrentToken) 879 CurrentToken->Previous->ClosesTemplateDeclaration = true; 880 return true; 881 } 882 return false; 883 } 884 885 bool consumeToken() { 886 FormatToken *Tok = CurrentToken; 887 next(); 888 switch (Tok->Tok.getKind()) { 889 case tok::plus: 890 case tok::minus: 891 if (!Tok->Previous && Line.MustBeDeclaration) 892 Tok->setType(TT_ObjCMethodSpecifier); 893 break; 894 case tok::colon: 895 if (!Tok->Previous) 896 return false; 897 // Colons from ?: are handled in parseConditional(). 898 if (Style.isJavaScript()) { 899 if (Contexts.back().ColonIsForRangeExpr || // colon in for loop 900 (Contexts.size() == 1 && // switch/case labels 901 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) || 902 Contexts.back().ContextKind == tok::l_paren || // function params 903 Contexts.back().ContextKind == tok::l_square || // array type 904 (!Contexts.back().IsExpression && 905 Contexts.back().ContextKind == tok::l_brace) || // object type 906 (Contexts.size() == 1 && 907 Line.MustBeDeclaration)) { // method/property declaration 908 Contexts.back().IsExpression = false; 909 Tok->setType(TT_JsTypeColon); 910 break; 911 } 912 } else if (Style.isCSharp()) { 913 if (Contexts.back().InCSharpAttributeSpecifier) { 914 Tok->setType(TT_AttributeColon); 915 break; 916 } 917 if (Contexts.back().ContextKind == tok::l_paren) { 918 Tok->setType(TT_CSharpNamedArgumentColon); 919 break; 920 } 921 } 922 if (Line.First->isOneOf(Keywords.kw_module, Keywords.kw_import) || 923 Line.First->startsSequence(tok::kw_export, Keywords.kw_module) || 924 Line.First->startsSequence(tok::kw_export, Keywords.kw_import)) { 925 Tok->setType(TT_ModulePartitionColon); 926 } else if (Contexts.back().ColonIsDictLiteral || 927 Style.Language == FormatStyle::LK_Proto || 928 Style.Language == FormatStyle::LK_TextProto) { 929 Tok->setType(TT_DictLiteral); 930 if (Style.Language == FormatStyle::LK_TextProto) { 931 if (FormatToken *Previous = Tok->getPreviousNonComment()) 932 Previous->setType(TT_SelectorName); 933 } 934 } else if (Contexts.back().ColonIsObjCMethodExpr || 935 Line.startsWith(TT_ObjCMethodSpecifier)) { 936 Tok->setType(TT_ObjCMethodExpr); 937 const FormatToken *BeforePrevious = Tok->Previous->Previous; 938 // Ensure we tag all identifiers in method declarations as 939 // TT_SelectorName. 940 bool UnknownIdentifierInMethodDeclaration = 941 Line.startsWith(TT_ObjCMethodSpecifier) && 942 Tok->Previous->is(tok::identifier) && Tok->Previous->is(TT_Unknown); 943 if (!BeforePrevious || 944 // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen. 945 !(BeforePrevious->is(TT_CastRParen) || 946 (BeforePrevious->is(TT_ObjCMethodExpr) && 947 BeforePrevious->is(tok::colon))) || 948 BeforePrevious->is(tok::r_square) || 949 Contexts.back().LongestObjCSelectorName == 0 || 950 UnknownIdentifierInMethodDeclaration) { 951 Tok->Previous->setType(TT_SelectorName); 952 if (!Contexts.back().FirstObjCSelectorName) 953 Contexts.back().FirstObjCSelectorName = Tok->Previous; 954 else if (Tok->Previous->ColumnWidth > 955 Contexts.back().LongestObjCSelectorName) 956 Contexts.back().LongestObjCSelectorName = 957 Tok->Previous->ColumnWidth; 958 Tok->Previous->ParameterIndex = 959 Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts; 960 ++Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts; 961 } 962 } else if (Contexts.back().ColonIsForRangeExpr) { 963 Tok->setType(TT_RangeBasedForLoopColon); 964 } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) { 965 Tok->setType(TT_BitFieldColon); 966 } else if (Contexts.size() == 1 && 967 !Line.First->isOneOf(tok::kw_enum, tok::kw_case, 968 tok::kw_default)) { 969 FormatToken *Prev = Tok->getPreviousNonComment(); 970 if (!Prev) 971 break; 972 if (Prev->isOneOf(tok::r_paren, tok::kw_noexcept)) 973 Tok->setType(TT_CtorInitializerColon); 974 else if (Prev->is(tok::kw_try)) { 975 // Member initializer list within function try block. 976 FormatToken *PrevPrev = Prev->getPreviousNonComment(); 977 if (!PrevPrev) 978 break; 979 if (PrevPrev && PrevPrev->isOneOf(tok::r_paren, tok::kw_noexcept)) 980 Tok->setType(TT_CtorInitializerColon); 981 } else 982 Tok->setType(TT_InheritanceColon); 983 } else if (canBeObjCSelectorComponent(*Tok->Previous) && Tok->Next && 984 (Tok->Next->isOneOf(tok::r_paren, tok::comma) || 985 (canBeObjCSelectorComponent(*Tok->Next) && Tok->Next->Next && 986 Tok->Next->Next->is(tok::colon)))) { 987 // This handles a special macro in ObjC code where selectors including 988 // the colon are passed as macro arguments. 989 Tok->setType(TT_ObjCMethodExpr); 990 } else if (Contexts.back().ContextKind == tok::l_paren) { 991 Tok->setType(TT_InlineASMColon); 992 } 993 break; 994 case tok::pipe: 995 case tok::amp: 996 // | and & in declarations/type expressions represent union and 997 // intersection types, respectively. 998 if (Style.isJavaScript() && !Contexts.back().IsExpression) 999 Tok->setType(TT_JsTypeOperator); 1000 break; 1001 case tok::kw_if: 1002 if (CurrentToken && 1003 CurrentToken->isOneOf(tok::kw_constexpr, tok::identifier)) 1004 next(); 1005 LLVM_FALLTHROUGH; 1006 case tok::kw_while: 1007 if (CurrentToken && CurrentToken->is(tok::l_paren)) { 1008 next(); 1009 if (!parseParens(/*LookForDecls=*/true)) 1010 return false; 1011 } 1012 break; 1013 case tok::kw_for: 1014 if (Style.isJavaScript()) { 1015 // x.for and {for: ...} 1016 if ((Tok->Previous && Tok->Previous->is(tok::period)) || 1017 (Tok->Next && Tok->Next->is(tok::colon))) 1018 break; 1019 // JS' for await ( ... 1020 if (CurrentToken && CurrentToken->is(Keywords.kw_await)) 1021 next(); 1022 } 1023 if (Style.isCpp() && CurrentToken && CurrentToken->is(tok::kw_co_await)) 1024 next(); 1025 Contexts.back().ColonIsForRangeExpr = true; 1026 next(); 1027 if (!parseParens()) 1028 return false; 1029 break; 1030 case tok::l_paren: 1031 // When faced with 'operator()()', the kw_operator handler incorrectly 1032 // marks the first l_paren as a OverloadedOperatorLParen. Here, we make 1033 // the first two parens OverloadedOperators and the second l_paren an 1034 // OverloadedOperatorLParen. 1035 if (Tok->Previous && Tok->Previous->is(tok::r_paren) && 1036 Tok->Previous->MatchingParen && 1037 Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) { 1038 Tok->Previous->setType(TT_OverloadedOperator); 1039 Tok->Previous->MatchingParen->setType(TT_OverloadedOperator); 1040 Tok->setType(TT_OverloadedOperatorLParen); 1041 } 1042 1043 if (!parseParens()) 1044 return false; 1045 if (Line.MustBeDeclaration && Contexts.size() == 1 && 1046 !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) && 1047 !Tok->isOneOf(TT_TypeDeclarationParen, TT_RequiresExpressionLParen) && 1048 (!Tok->Previous || !Tok->Previous->isOneOf(tok::kw___attribute, 1049 TT_LeadingJavaAnnotation))) 1050 Line.MightBeFunctionDecl = true; 1051 break; 1052 case tok::l_square: 1053 if (!parseSquare()) 1054 return false; 1055 break; 1056 case tok::l_brace: 1057 if (Style.Language == FormatStyle::LK_TextProto) { 1058 FormatToken *Previous = Tok->getPreviousNonComment(); 1059 if (Previous && Previous->getType() != TT_DictLiteral) 1060 Previous->setType(TT_SelectorName); 1061 } 1062 if (!parseBrace()) 1063 return false; 1064 break; 1065 case tok::less: 1066 if (parseAngle()) { 1067 Tok->setType(TT_TemplateOpener); 1068 // In TT_Proto, we must distignuish between: 1069 // map<key, value> 1070 // msg < item: data > 1071 // msg: < item: data > 1072 // In TT_TextProto, map<key, value> does not occur. 1073 if (Style.Language == FormatStyle::LK_TextProto || 1074 (Style.Language == FormatStyle::LK_Proto && Tok->Previous && 1075 Tok->Previous->isOneOf(TT_SelectorName, TT_DictLiteral))) { 1076 Tok->setType(TT_DictLiteral); 1077 FormatToken *Previous = Tok->getPreviousNonComment(); 1078 if (Previous && Previous->getType() != TT_DictLiteral) 1079 Previous->setType(TT_SelectorName); 1080 } 1081 } else { 1082 Tok->setType(TT_BinaryOperator); 1083 NonTemplateLess.insert(Tok); 1084 CurrentToken = Tok; 1085 next(); 1086 } 1087 break; 1088 case tok::r_paren: 1089 case tok::r_square: 1090 return false; 1091 case tok::r_brace: 1092 // Lines can start with '}'. 1093 if (Tok->Previous) 1094 return false; 1095 break; 1096 case tok::greater: 1097 if (Style.Language != FormatStyle::LK_TextProto) 1098 Tok->setType(TT_BinaryOperator); 1099 if (Tok->Previous && Tok->Previous->is(TT_TemplateCloser)) 1100 Tok->SpacesRequiredBefore = 1; 1101 break; 1102 case tok::kw_operator: 1103 if (Style.Language == FormatStyle::LK_TextProto || 1104 Style.Language == FormatStyle::LK_Proto) 1105 break; 1106 while (CurrentToken && 1107 !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) { 1108 if (CurrentToken->isOneOf(tok::star, tok::amp)) 1109 CurrentToken->setType(TT_PointerOrReference); 1110 consumeToken(); 1111 if (CurrentToken && CurrentToken->is(tok::comma) && 1112 CurrentToken->Previous->isNot(tok::kw_operator)) 1113 break; 1114 if (CurrentToken && CurrentToken->Previous->isOneOf( 1115 TT_BinaryOperator, TT_UnaryOperator, tok::comma, 1116 tok::star, tok::arrow, tok::amp, tok::ampamp)) 1117 CurrentToken->Previous->setType(TT_OverloadedOperator); 1118 } 1119 if (CurrentToken && CurrentToken->is(tok::l_paren)) 1120 CurrentToken->setType(TT_OverloadedOperatorLParen); 1121 if (CurrentToken && CurrentToken->Previous->is(TT_BinaryOperator)) 1122 CurrentToken->Previous->setType(TT_OverloadedOperator); 1123 break; 1124 case tok::question: 1125 if (Style.isJavaScript() && Tok->Next && 1126 Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren, 1127 tok::r_brace)) { 1128 // Question marks before semicolons, colons, etc. indicate optional 1129 // types (fields, parameters), e.g. 1130 // function(x?: string, y?) {...} 1131 // class X { y?; } 1132 Tok->setType(TT_JsTypeOptionalQuestion); 1133 break; 1134 } 1135 // Declarations cannot be conditional expressions, this can only be part 1136 // of a type declaration. 1137 if (Line.MustBeDeclaration && !Contexts.back().IsExpression && 1138 Style.isJavaScript()) 1139 break; 1140 if (Style.isCSharp()) { 1141 // `Type?)`, `Type?>`, `Type? name;` and `Type? name =` can only be 1142 // nullable types. 1143 // Line.MustBeDeclaration will be true for `Type? name;`. 1144 if ((!Contexts.back().IsExpression && Line.MustBeDeclaration) || 1145 (Tok->Next && Tok->Next->isOneOf(tok::r_paren, tok::greater)) || 1146 (Tok->Next && Tok->Next->is(tok::identifier) && Tok->Next->Next && 1147 Tok->Next->Next->is(tok::equal))) { 1148 Tok->setType(TT_CSharpNullable); 1149 break; 1150 } 1151 } 1152 parseConditional(); 1153 break; 1154 case tok::kw_template: 1155 parseTemplateDeclaration(); 1156 break; 1157 case tok::comma: 1158 if (Contexts.back().InCtorInitializer) 1159 Tok->setType(TT_CtorInitializerComma); 1160 else if (Contexts.back().InInheritanceList) 1161 Tok->setType(TT_InheritanceComma); 1162 else if (Contexts.back().FirstStartOfName && 1163 (Contexts.size() == 1 || startsWithInitStatement(Line))) { 1164 Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true; 1165 Line.IsMultiVariableDeclStmt = true; 1166 } 1167 if (Contexts.back().IsForEachMacro) 1168 Contexts.back().IsExpression = true; 1169 break; 1170 case tok::identifier: 1171 if (Tok->isOneOf(Keywords.kw___has_include, 1172 Keywords.kw___has_include_next)) 1173 parseHasInclude(); 1174 if (Style.isCSharp() && Tok->is(Keywords.kw_where) && Tok->Next && 1175 Tok->Next->isNot(tok::l_paren)) { 1176 Tok->setType(TT_CSharpGenericTypeConstraint); 1177 parseCSharpGenericTypeConstraint(); 1178 } 1179 break; 1180 case tok::arrow: 1181 if (Tok->Previous && Tok->Previous->is(tok::kw_noexcept)) 1182 Tok->setType(TT_TrailingReturnArrow); 1183 break; 1184 default: 1185 break; 1186 } 1187 return true; 1188 } 1189 1190 void parseCSharpGenericTypeConstraint() { 1191 int OpenAngleBracketsCount = 0; 1192 while (CurrentToken) { 1193 if (CurrentToken->is(tok::less)) { 1194 // parseAngle is too greedy and will consume the whole line. 1195 CurrentToken->setType(TT_TemplateOpener); 1196 ++OpenAngleBracketsCount; 1197 next(); 1198 } else if (CurrentToken->is(tok::greater)) { 1199 CurrentToken->setType(TT_TemplateCloser); 1200 --OpenAngleBracketsCount; 1201 next(); 1202 } else if (CurrentToken->is(tok::comma) && OpenAngleBracketsCount == 0) { 1203 // We allow line breaks after GenericTypeConstraintComma's 1204 // so do not flag commas in Generics as GenericTypeConstraintComma's. 1205 CurrentToken->setType(TT_CSharpGenericTypeConstraintComma); 1206 next(); 1207 } else if (CurrentToken->is(Keywords.kw_where)) { 1208 CurrentToken->setType(TT_CSharpGenericTypeConstraint); 1209 next(); 1210 } else if (CurrentToken->is(tok::colon)) { 1211 CurrentToken->setType(TT_CSharpGenericTypeConstraintColon); 1212 next(); 1213 } else { 1214 next(); 1215 } 1216 } 1217 } 1218 1219 void parseIncludeDirective() { 1220 if (CurrentToken && CurrentToken->is(tok::less)) { 1221 next(); 1222 while (CurrentToken) { 1223 // Mark tokens up to the trailing line comments as implicit string 1224 // literals. 1225 if (CurrentToken->isNot(tok::comment) && 1226 !CurrentToken->TokenText.startswith("//")) 1227 CurrentToken->setType(TT_ImplicitStringLiteral); 1228 next(); 1229 } 1230 } 1231 } 1232 1233 void parseWarningOrError() { 1234 next(); 1235 // We still want to format the whitespace left of the first token of the 1236 // warning or error. 1237 next(); 1238 while (CurrentToken) { 1239 CurrentToken->setType(TT_ImplicitStringLiteral); 1240 next(); 1241 } 1242 } 1243 1244 void parsePragma() { 1245 next(); // Consume "pragma". 1246 if (CurrentToken && 1247 CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) { 1248 bool IsMark = CurrentToken->is(Keywords.kw_mark); 1249 next(); // Consume "mark". 1250 next(); // Consume first token (so we fix leading whitespace). 1251 while (CurrentToken) { 1252 if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator)) 1253 CurrentToken->setType(TT_ImplicitStringLiteral); 1254 next(); 1255 } 1256 } 1257 } 1258 1259 void parseHasInclude() { 1260 if (!CurrentToken || !CurrentToken->is(tok::l_paren)) 1261 return; 1262 next(); // '(' 1263 parseIncludeDirective(); 1264 next(); // ')' 1265 } 1266 1267 LineType parsePreprocessorDirective() { 1268 bool IsFirstToken = CurrentToken->IsFirst; 1269 LineType Type = LT_PreprocessorDirective; 1270 next(); 1271 if (!CurrentToken) 1272 return Type; 1273 1274 if (Style.isJavaScript() && IsFirstToken) { 1275 // JavaScript files can contain shebang lines of the form: 1276 // #!/usr/bin/env node 1277 // Treat these like C++ #include directives. 1278 while (CurrentToken) { 1279 // Tokens cannot be comments here. 1280 CurrentToken->setType(TT_ImplicitStringLiteral); 1281 next(); 1282 } 1283 return LT_ImportStatement; 1284 } 1285 1286 if (CurrentToken->is(tok::numeric_constant)) { 1287 CurrentToken->SpacesRequiredBefore = 1; 1288 return Type; 1289 } 1290 // Hashes in the middle of a line can lead to any strange token 1291 // sequence. 1292 if (!CurrentToken->Tok.getIdentifierInfo()) 1293 return Type; 1294 switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) { 1295 case tok::pp_include: 1296 case tok::pp_include_next: 1297 case tok::pp_import: 1298 next(); 1299 parseIncludeDirective(); 1300 Type = LT_ImportStatement; 1301 break; 1302 case tok::pp_error: 1303 case tok::pp_warning: 1304 parseWarningOrError(); 1305 break; 1306 case tok::pp_pragma: 1307 parsePragma(); 1308 break; 1309 case tok::pp_if: 1310 case tok::pp_elif: 1311 Contexts.back().IsExpression = true; 1312 next(); 1313 parseLine(); 1314 break; 1315 default: 1316 break; 1317 } 1318 while (CurrentToken) { 1319 FormatToken *Tok = CurrentToken; 1320 next(); 1321 if (Tok->is(tok::l_paren)) 1322 parseParens(); 1323 else if (Tok->isOneOf(Keywords.kw___has_include, 1324 Keywords.kw___has_include_next)) 1325 parseHasInclude(); 1326 } 1327 return Type; 1328 } 1329 1330 public: 1331 LineType parseLine() { 1332 if (!CurrentToken) 1333 return LT_Invalid; 1334 NonTemplateLess.clear(); 1335 if (CurrentToken->is(tok::hash)) 1336 return parsePreprocessorDirective(); 1337 1338 // Directly allow to 'import <string-literal>' to support protocol buffer 1339 // definitions (github.com/google/protobuf) or missing "#" (either way we 1340 // should not break the line). 1341 IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo(); 1342 if ((Style.Language == FormatStyle::LK_Java && 1343 CurrentToken->is(Keywords.kw_package)) || 1344 (Info && Info->getPPKeywordID() == tok::pp_import && 1345 CurrentToken->Next && 1346 CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier, 1347 tok::kw_static))) { 1348 next(); 1349 parseIncludeDirective(); 1350 return LT_ImportStatement; 1351 } 1352 1353 // If this line starts and ends in '<' and '>', respectively, it is likely 1354 // part of "#define <a/b.h>". 1355 if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) { 1356 parseIncludeDirective(); 1357 return LT_ImportStatement; 1358 } 1359 1360 // In .proto files, top-level options and package statements are very 1361 // similar to import statements and should not be line-wrapped. 1362 if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 && 1363 CurrentToken->isOneOf(Keywords.kw_option, Keywords.kw_package)) { 1364 next(); 1365 if (CurrentToken && CurrentToken->is(tok::identifier)) { 1366 while (CurrentToken) 1367 next(); 1368 return LT_ImportStatement; 1369 } 1370 } 1371 1372 bool KeywordVirtualFound = false; 1373 bool ImportStatement = false; 1374 1375 // import {...} from '...'; 1376 if (Style.isJavaScript() && CurrentToken->is(Keywords.kw_import)) 1377 ImportStatement = true; 1378 1379 while (CurrentToken) { 1380 if (CurrentToken->is(tok::kw_virtual)) 1381 KeywordVirtualFound = true; 1382 if (Style.isJavaScript()) { 1383 // export {...} from '...'; 1384 // An export followed by "from 'some string';" is a re-export from 1385 // another module identified by a URI and is treated as a 1386 // LT_ImportStatement (i.e. prevent wraps on it for long URIs). 1387 // Just "export {...};" or "export class ..." should not be treated as 1388 // an import in this sense. 1389 if (Line.First->is(tok::kw_export) && 1390 CurrentToken->is(Keywords.kw_from) && CurrentToken->Next && 1391 CurrentToken->Next->isStringLiteral()) 1392 ImportStatement = true; 1393 if (isClosureImportStatement(*CurrentToken)) 1394 ImportStatement = true; 1395 } 1396 if (!consumeToken()) 1397 return LT_Invalid; 1398 } 1399 if (KeywordVirtualFound) 1400 return LT_VirtualFunctionDecl; 1401 if (ImportStatement) 1402 return LT_ImportStatement; 1403 1404 if (Line.startsWith(TT_ObjCMethodSpecifier)) { 1405 if (Contexts.back().FirstObjCSelectorName) 1406 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 1407 Contexts.back().LongestObjCSelectorName; 1408 return LT_ObjCMethodDecl; 1409 } 1410 1411 for (const auto &ctx : Contexts) 1412 if (ctx.InStructArrayInitializer) 1413 return LT_ArrayOfStructInitializer; 1414 1415 return LT_Other; 1416 } 1417 1418 private: 1419 bool isClosureImportStatement(const FormatToken &Tok) { 1420 // FIXME: Closure-library specific stuff should not be hard-coded but be 1421 // configurable. 1422 return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) && 1423 Tok.Next->Next && 1424 (Tok.Next->Next->TokenText == "module" || 1425 Tok.Next->Next->TokenText == "provide" || 1426 Tok.Next->Next->TokenText == "require" || 1427 Tok.Next->Next->TokenText == "requireType" || 1428 Tok.Next->Next->TokenText == "forwardDeclare") && 1429 Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren); 1430 } 1431 1432 void resetTokenMetadata() { 1433 if (!CurrentToken) 1434 return; 1435 1436 // Reset token type in case we have already looked at it and then 1437 // recovered from an error (e.g. failure to find the matching >). 1438 if (!CurrentToken->isTypeFinalized() && 1439 !CurrentToken->isOneOf( 1440 TT_LambdaLSquare, TT_LambdaLBrace, TT_AttributeMacro, TT_IfMacro, 1441 TT_ForEachMacro, TT_TypenameMacro, TT_FunctionLBrace, 1442 TT_ImplicitStringLiteral, TT_InlineASMBrace, TT_FatArrow, 1443 TT_LambdaArrow, TT_NamespaceMacro, TT_OverloadedOperator, 1444 TT_RegexLiteral, TT_TemplateString, TT_ObjCStringLiteral, 1445 TT_UntouchableMacroFunc, TT_StatementAttributeLikeMacro, 1446 TT_FunctionLikeOrFreestandingMacro, TT_ClassLBrace, TT_EnumLBrace, 1447 TT_RecordLBrace, TT_StructLBrace, TT_UnionLBrace, TT_RequiresClause, 1448 TT_RequiresClauseInARequiresExpression, TT_RequiresExpression, 1449 TT_RequiresExpressionLParen, TT_RequiresExpressionLBrace, 1450 TT_CompoundRequirementLBrace, TT_BracedListLBrace)) 1451 CurrentToken->setType(TT_Unknown); 1452 CurrentToken->Role.reset(); 1453 CurrentToken->MatchingParen = nullptr; 1454 CurrentToken->FakeLParens.clear(); 1455 CurrentToken->FakeRParens = 0; 1456 } 1457 1458 void next() { 1459 if (!CurrentToken) 1460 return; 1461 1462 CurrentToken->NestingLevel = Contexts.size() - 1; 1463 CurrentToken->BindingStrength = Contexts.back().BindingStrength; 1464 modifyContext(*CurrentToken); 1465 determineTokenType(*CurrentToken); 1466 CurrentToken = CurrentToken->Next; 1467 1468 resetTokenMetadata(); 1469 } 1470 1471 /// A struct to hold information valid in a specific context, e.g. 1472 /// a pair of parenthesis. 1473 struct Context { 1474 Context(tok::TokenKind ContextKind, unsigned BindingStrength, 1475 bool IsExpression) 1476 : ContextKind(ContextKind), BindingStrength(BindingStrength), 1477 IsExpression(IsExpression) {} 1478 1479 tok::TokenKind ContextKind; 1480 unsigned BindingStrength; 1481 bool IsExpression; 1482 unsigned LongestObjCSelectorName = 0; 1483 bool ColonIsForRangeExpr = false; 1484 bool ColonIsDictLiteral = false; 1485 bool ColonIsObjCMethodExpr = false; 1486 FormatToken *FirstObjCSelectorName = nullptr; 1487 FormatToken *FirstStartOfName = nullptr; 1488 bool CanBeExpression = true; 1489 bool InTemplateArgument = false; 1490 bool InCtorInitializer = false; 1491 bool InInheritanceList = false; 1492 bool CaretFound = false; 1493 bool IsForEachMacro = false; 1494 bool InCpp11AttributeSpecifier = false; 1495 bool InCSharpAttributeSpecifier = false; 1496 bool InStructArrayInitializer = false; 1497 }; 1498 1499 /// Puts a new \c Context onto the stack \c Contexts for the lifetime 1500 /// of each instance. 1501 struct ScopedContextCreator { 1502 AnnotatingParser &P; 1503 1504 ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind, 1505 unsigned Increase) 1506 : P(P) { 1507 P.Contexts.push_back(Context(ContextKind, 1508 P.Contexts.back().BindingStrength + Increase, 1509 P.Contexts.back().IsExpression)); 1510 } 1511 1512 ~ScopedContextCreator() { 1513 if (P.Style.AlignArrayOfStructures != FormatStyle::AIAS_None) { 1514 if (P.Contexts.back().InStructArrayInitializer) { 1515 P.Contexts.pop_back(); 1516 P.Contexts.back().InStructArrayInitializer = true; 1517 return; 1518 } 1519 } 1520 P.Contexts.pop_back(); 1521 } 1522 }; 1523 1524 void modifyContext(const FormatToken &Current) { 1525 auto AssignmentStartsExpression = [&]() { 1526 if (Current.getPrecedence() != prec::Assignment) 1527 return false; 1528 1529 if (Line.First->isOneOf(tok::kw_using, tok::kw_return)) 1530 return false; 1531 if (Line.First->is(tok::kw_template)) { 1532 assert(Current.Previous); 1533 if (Current.Previous->is(tok::kw_operator)) { 1534 // `template ... operator=` cannot be an expression. 1535 return false; 1536 } 1537 1538 // `template` keyword can start a variable template. 1539 const FormatToken *Tok = Line.First->getNextNonComment(); 1540 assert(Tok); // Current token is on the same line. 1541 if (Tok->isNot(TT_TemplateOpener)) { 1542 // Explicit template instantiations do not have `<>`. 1543 return false; 1544 } 1545 1546 Tok = Tok->MatchingParen; 1547 if (!Tok) 1548 return false; 1549 Tok = Tok->getNextNonComment(); 1550 if (!Tok) 1551 return false; 1552 1553 if (Tok->isOneOf(tok::kw_class, tok::kw_enum, tok::kw_concept, 1554 tok::kw_struct, tok::kw_using)) 1555 return false; 1556 1557 return true; 1558 } 1559 1560 // Type aliases use `type X = ...;` in TypeScript and can be exported 1561 // using `export type ...`. 1562 if (Style.isJavaScript() && 1563 (Line.startsWith(Keywords.kw_type, tok::identifier) || 1564 Line.startsWith(tok::kw_export, Keywords.kw_type, tok::identifier))) 1565 return false; 1566 1567 return !Current.Previous || Current.Previous->isNot(tok::kw_operator); 1568 }; 1569 1570 if (AssignmentStartsExpression()) { 1571 Contexts.back().IsExpression = true; 1572 if (!Line.startsWith(TT_UnaryOperator)) { 1573 for (FormatToken *Previous = Current.Previous; 1574 Previous && Previous->Previous && 1575 !Previous->Previous->isOneOf(tok::comma, tok::semi); 1576 Previous = Previous->Previous) { 1577 if (Previous->isOneOf(tok::r_square, tok::r_paren)) { 1578 Previous = Previous->MatchingParen; 1579 if (!Previous) 1580 break; 1581 } 1582 if (Previous->opensScope()) 1583 break; 1584 if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) && 1585 Previous->isOneOf(tok::star, tok::amp, tok::ampamp) && 1586 Previous->Previous && Previous->Previous->isNot(tok::equal)) 1587 Previous->setType(TT_PointerOrReference); 1588 } 1589 } 1590 } else if (Current.is(tok::lessless) && 1591 (!Current.Previous || !Current.Previous->is(tok::kw_operator))) { 1592 Contexts.back().IsExpression = true; 1593 } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) { 1594 Contexts.back().IsExpression = true; 1595 } else if (Current.is(TT_TrailingReturnArrow)) { 1596 Contexts.back().IsExpression = false; 1597 } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) { 1598 Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java; 1599 } else if (Current.Previous && 1600 Current.Previous->is(TT_CtorInitializerColon)) { 1601 Contexts.back().IsExpression = true; 1602 Contexts.back().InCtorInitializer = true; 1603 } else if (Current.Previous && Current.Previous->is(TT_InheritanceColon)) { 1604 Contexts.back().InInheritanceList = true; 1605 } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) { 1606 for (FormatToken *Previous = Current.Previous; 1607 Previous && Previous->isOneOf(tok::star, tok::amp); 1608 Previous = Previous->Previous) 1609 Previous->setType(TT_PointerOrReference); 1610 if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer) 1611 Contexts.back().IsExpression = false; 1612 } else if (Current.is(tok::kw_new)) { 1613 Contexts.back().CanBeExpression = false; 1614 } else if (Current.is(tok::semi) || 1615 (Current.is(tok::exclaim) && Current.Previous && 1616 !Current.Previous->is(tok::kw_operator))) { 1617 // This should be the condition or increment in a for-loop. 1618 // But not operator !() (can't use TT_OverloadedOperator here as its not 1619 // been annotated yet). 1620 Contexts.back().IsExpression = true; 1621 } 1622 } 1623 1624 static FormatToken *untilMatchingParen(FormatToken *Current) { 1625 // Used when `MatchingParen` is not yet established. 1626 int ParenLevel = 0; 1627 while (Current) { 1628 if (Current->is(tok::l_paren)) 1629 ++ParenLevel; 1630 if (Current->is(tok::r_paren)) 1631 --ParenLevel; 1632 if (ParenLevel < 1) 1633 break; 1634 Current = Current->Next; 1635 } 1636 return Current; 1637 } 1638 1639 static bool isDeductionGuide(FormatToken &Current) { 1640 // Look for a deduction guide template<T> A(...) -> A<...>; 1641 if (Current.Previous && Current.Previous->is(tok::r_paren) && 1642 Current.startsSequence(tok::arrow, tok::identifier, tok::less)) { 1643 // Find the TemplateCloser. 1644 FormatToken *TemplateCloser = Current.Next->Next; 1645 int NestingLevel = 0; 1646 while (TemplateCloser) { 1647 // Skip over an expressions in parens A<(3 < 2)>; 1648 if (TemplateCloser->is(tok::l_paren)) { 1649 // No Matching Paren yet so skip to matching paren 1650 TemplateCloser = untilMatchingParen(TemplateCloser); 1651 if (!TemplateCloser) 1652 break; 1653 } 1654 if (TemplateCloser->is(tok::less)) 1655 ++NestingLevel; 1656 if (TemplateCloser->is(tok::greater)) 1657 --NestingLevel; 1658 if (NestingLevel < 1) 1659 break; 1660 TemplateCloser = TemplateCloser->Next; 1661 } 1662 // Assuming we have found the end of the template ensure its followed 1663 // with a semi-colon. 1664 if (TemplateCloser && TemplateCloser->Next && 1665 TemplateCloser->Next->is(tok::semi) && 1666 Current.Previous->MatchingParen) { 1667 // Determine if the identifier `A` prior to the A<..>; is the same as 1668 // prior to the A(..) 1669 FormatToken *LeadingIdentifier = 1670 Current.Previous->MatchingParen->Previous; 1671 1672 // Differentiate a deduction guide by seeing the 1673 // > of the template prior to the leading identifier. 1674 if (LeadingIdentifier) { 1675 FormatToken *PriorLeadingIdentifier = LeadingIdentifier->Previous; 1676 // Skip back past explicit decoration 1677 if (PriorLeadingIdentifier && 1678 PriorLeadingIdentifier->is(tok::kw_explicit)) 1679 PriorLeadingIdentifier = PriorLeadingIdentifier->Previous; 1680 1681 return PriorLeadingIdentifier && 1682 (PriorLeadingIdentifier->is(TT_TemplateCloser) || 1683 PriorLeadingIdentifier->ClosesRequiresClause) && 1684 LeadingIdentifier->TokenText == Current.Next->TokenText; 1685 } 1686 } 1687 } 1688 return false; 1689 } 1690 1691 void determineTokenType(FormatToken &Current) { 1692 if (!Current.is(TT_Unknown)) 1693 // The token type is already known. 1694 return; 1695 1696 if ((Style.isJavaScript() || Style.isCSharp()) && 1697 Current.is(tok::exclaim)) { 1698 if (Current.Previous) { 1699 bool IsIdentifier = 1700 Style.isJavaScript() 1701 ? Keywords.IsJavaScriptIdentifier( 1702 *Current.Previous, /* AcceptIdentifierName= */ true) 1703 : Current.Previous->is(tok::identifier); 1704 if (IsIdentifier || 1705 Current.Previous->isOneOf( 1706 tok::kw_default, tok::kw_namespace, tok::r_paren, tok::r_square, 1707 tok::r_brace, tok::kw_false, tok::kw_true, Keywords.kw_type, 1708 Keywords.kw_get, Keywords.kw_init, Keywords.kw_set) || 1709 Current.Previous->Tok.isLiteral()) { 1710 Current.setType(TT_NonNullAssertion); 1711 return; 1712 } 1713 } 1714 if (Current.Next && 1715 Current.Next->isOneOf(TT_BinaryOperator, Keywords.kw_as)) { 1716 Current.setType(TT_NonNullAssertion); 1717 return; 1718 } 1719 } 1720 1721 // Line.MightBeFunctionDecl can only be true after the parentheses of a 1722 // function declaration have been found. In this case, 'Current' is a 1723 // trailing token of this declaration and thus cannot be a name. 1724 if (Current.is(Keywords.kw_instanceof)) { 1725 Current.setType(TT_BinaryOperator); 1726 } else if (isStartOfName(Current) && 1727 (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) { 1728 Contexts.back().FirstStartOfName = &Current; 1729 Current.setType(TT_StartOfName); 1730 } else if (Current.is(tok::semi)) { 1731 // Reset FirstStartOfName after finding a semicolon so that a for loop 1732 // with multiple increment statements is not confused with a for loop 1733 // having multiple variable declarations. 1734 Contexts.back().FirstStartOfName = nullptr; 1735 } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) { 1736 AutoFound = true; 1737 } else if (Current.is(tok::arrow) && 1738 Style.Language == FormatStyle::LK_Java) { 1739 Current.setType(TT_LambdaArrow); 1740 } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration && 1741 Current.NestingLevel == 0 && 1742 !Current.Previous->isOneOf(tok::kw_operator, tok::identifier)) { 1743 // not auto operator->() -> xxx; 1744 Current.setType(TT_TrailingReturnArrow); 1745 } else if (Current.is(tok::arrow) && Current.Previous && 1746 Current.Previous->is(tok::r_brace)) { 1747 // Concept implicit conversion constraint needs to be treated like 1748 // a trailing return type ... } -> <type>. 1749 Current.setType(TT_TrailingReturnArrow); 1750 } else if (isDeductionGuide(Current)) { 1751 // Deduction guides trailing arrow " A(...) -> A<T>;". 1752 Current.setType(TT_TrailingReturnArrow); 1753 } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) { 1754 Current.setType(determineStarAmpUsage( 1755 Current, 1756 Contexts.back().CanBeExpression && Contexts.back().IsExpression, 1757 Contexts.back().InTemplateArgument)); 1758 } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) { 1759 Current.setType(determinePlusMinusCaretUsage(Current)); 1760 if (Current.is(TT_UnaryOperator) && Current.is(tok::caret)) 1761 Contexts.back().CaretFound = true; 1762 } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) { 1763 Current.setType(determineIncrementUsage(Current)); 1764 } else if (Current.isOneOf(tok::exclaim, tok::tilde)) { 1765 Current.setType(TT_UnaryOperator); 1766 } else if (Current.is(tok::question)) { 1767 if (Style.isJavaScript() && Line.MustBeDeclaration && 1768 !Contexts.back().IsExpression) { 1769 // In JavaScript, `interface X { foo?(): bar; }` is an optional method 1770 // on the interface, not a ternary expression. 1771 Current.setType(TT_JsTypeOptionalQuestion); 1772 } else { 1773 Current.setType(TT_ConditionalExpr); 1774 } 1775 } else if (Current.isBinaryOperator() && 1776 (!Current.Previous || Current.Previous->isNot(tok::l_square)) && 1777 (!Current.is(tok::greater) && 1778 Style.Language != FormatStyle::LK_TextProto)) { 1779 Current.setType(TT_BinaryOperator); 1780 } else if (Current.is(tok::comment)) { 1781 if (Current.TokenText.startswith("/*")) 1782 if (Current.TokenText.endswith("*/")) 1783 Current.setType(TT_BlockComment); 1784 else 1785 // The lexer has for some reason determined a comment here. But we 1786 // cannot really handle it, if it isn't properly terminated. 1787 Current.Tok.setKind(tok::unknown); 1788 else 1789 Current.setType(TT_LineComment); 1790 } else if (Current.is(tok::l_paren)) { 1791 if (lParenStartsCppCast(Current)) 1792 Current.setType(TT_CppCastLParen); 1793 } else if (Current.is(tok::r_paren)) { 1794 if (rParenEndsCast(Current)) 1795 Current.setType(TT_CastRParen); 1796 if (Current.MatchingParen && Current.Next && 1797 !Current.Next->isBinaryOperator() && 1798 !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace, 1799 tok::comma, tok::period, tok::arrow, 1800 tok::coloncolon)) 1801 if (FormatToken *AfterParen = Current.MatchingParen->Next) { 1802 // Make sure this isn't the return type of an Obj-C block declaration 1803 if (AfterParen->isNot(tok::caret)) { 1804 if (FormatToken *BeforeParen = Current.MatchingParen->Previous) 1805 if (BeforeParen->is(tok::identifier) && 1806 !BeforeParen->is(TT_TypenameMacro) && 1807 BeforeParen->TokenText == BeforeParen->TokenText.upper() && 1808 (!BeforeParen->Previous || 1809 BeforeParen->Previous->ClosesTemplateDeclaration)) 1810 Current.setType(TT_FunctionAnnotationRParen); 1811 } 1812 } 1813 } else if (Current.is(tok::at) && Current.Next && !Style.isJavaScript() && 1814 Style.Language != FormatStyle::LK_Java) { 1815 // In Java & JavaScript, "@..." is a decorator or annotation. In ObjC, it 1816 // marks declarations and properties that need special formatting. 1817 switch (Current.Next->Tok.getObjCKeywordID()) { 1818 case tok::objc_interface: 1819 case tok::objc_implementation: 1820 case tok::objc_protocol: 1821 Current.setType(TT_ObjCDecl); 1822 break; 1823 case tok::objc_property: 1824 Current.setType(TT_ObjCProperty); 1825 break; 1826 default: 1827 break; 1828 } 1829 } else if (Current.is(tok::period)) { 1830 FormatToken *PreviousNoComment = Current.getPreviousNonComment(); 1831 if (PreviousNoComment && 1832 PreviousNoComment->isOneOf(tok::comma, tok::l_brace)) 1833 Current.setType(TT_DesignatedInitializerPeriod); 1834 else if (Style.Language == FormatStyle::LK_Java && Current.Previous && 1835 Current.Previous->isOneOf(TT_JavaAnnotation, 1836 TT_LeadingJavaAnnotation)) 1837 Current.setType(Current.Previous->getType()); 1838 } else if (canBeObjCSelectorComponent(Current) && 1839 // FIXME(bug 36976): ObjC return types shouldn't use 1840 // TT_CastRParen. 1841 Current.Previous && Current.Previous->is(TT_CastRParen) && 1842 Current.Previous->MatchingParen && 1843 Current.Previous->MatchingParen->Previous && 1844 Current.Previous->MatchingParen->Previous->is( 1845 TT_ObjCMethodSpecifier)) { 1846 // This is the first part of an Objective-C selector name. (If there's no 1847 // colon after this, this is the only place which annotates the identifier 1848 // as a selector.) 1849 Current.setType(TT_SelectorName); 1850 } else if (Current.isOneOf(tok::identifier, tok::kw_const, tok::kw_noexcept, 1851 tok::kw_requires) && 1852 Current.Previous && 1853 !Current.Previous->isOneOf(tok::equal, tok::at) && 1854 Line.MightBeFunctionDecl && Contexts.size() == 1) { 1855 // Line.MightBeFunctionDecl can only be true after the parentheses of a 1856 // function declaration have been found. 1857 Current.setType(TT_TrailingAnnotation); 1858 } else if ((Style.Language == FormatStyle::LK_Java || 1859 Style.isJavaScript()) && 1860 Current.Previous) { 1861 if (Current.Previous->is(tok::at) && 1862 Current.isNot(Keywords.kw_interface)) { 1863 const FormatToken &AtToken = *Current.Previous; 1864 const FormatToken *Previous = AtToken.getPreviousNonComment(); 1865 if (!Previous || Previous->is(TT_LeadingJavaAnnotation)) 1866 Current.setType(TT_LeadingJavaAnnotation); 1867 else 1868 Current.setType(TT_JavaAnnotation); 1869 } else if (Current.Previous->is(tok::period) && 1870 Current.Previous->isOneOf(TT_JavaAnnotation, 1871 TT_LeadingJavaAnnotation)) { 1872 Current.setType(Current.Previous->getType()); 1873 } 1874 } 1875 } 1876 1877 /// Take a guess at whether \p Tok starts a name of a function or 1878 /// variable declaration. 1879 /// 1880 /// This is a heuristic based on whether \p Tok is an identifier following 1881 /// something that is likely a type. 1882 bool isStartOfName(const FormatToken &Tok) { 1883 if (Tok.isNot(tok::identifier) || !Tok.Previous) 1884 return false; 1885 1886 if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof, 1887 Keywords.kw_as)) 1888 return false; 1889 if (Style.isJavaScript() && Tok.Previous->is(Keywords.kw_in)) 1890 return false; 1891 1892 // Skip "const" as it does not have an influence on whether this is a name. 1893 FormatToken *PreviousNotConst = Tok.getPreviousNonComment(); 1894 1895 // For javascript const can be like "let" or "var" 1896 if (!Style.isJavaScript()) 1897 while (PreviousNotConst && PreviousNotConst->is(tok::kw_const)) 1898 PreviousNotConst = PreviousNotConst->getPreviousNonComment(); 1899 1900 if (!PreviousNotConst) 1901 return false; 1902 1903 if (PreviousNotConst->ClosesRequiresClause) 1904 return false; 1905 1906 bool IsPPKeyword = PreviousNotConst->is(tok::identifier) && 1907 PreviousNotConst->Previous && 1908 PreviousNotConst->Previous->is(tok::hash); 1909 1910 if (PreviousNotConst->is(TT_TemplateCloser)) 1911 return PreviousNotConst && PreviousNotConst->MatchingParen && 1912 PreviousNotConst->MatchingParen->Previous && 1913 PreviousNotConst->MatchingParen->Previous->isNot(tok::period) && 1914 PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template); 1915 1916 if (PreviousNotConst->is(tok::r_paren) && 1917 PreviousNotConst->is(TT_TypeDeclarationParen)) 1918 return true; 1919 1920 // If is a preprocess keyword like #define. 1921 if (IsPPKeyword) 1922 return false; 1923 1924 // int a or auto a. 1925 if (PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) 1926 return true; 1927 1928 // *a or &a or &&a. 1929 if (PreviousNotConst->is(TT_PointerOrReference)) 1930 return true; 1931 1932 // MyClass a; 1933 if (PreviousNotConst->isSimpleTypeSpecifier()) 1934 return true; 1935 1936 // const a = in JavaScript. 1937 return Style.isJavaScript() && PreviousNotConst->is(tok::kw_const); 1938 } 1939 1940 /// Determine whether '(' is starting a C++ cast. 1941 bool lParenStartsCppCast(const FormatToken &Tok) { 1942 // C-style casts are only used in C++. 1943 if (!Style.isCpp()) 1944 return false; 1945 1946 FormatToken *LeftOfParens = Tok.getPreviousNonComment(); 1947 if (LeftOfParens && LeftOfParens->is(TT_TemplateCloser) && 1948 LeftOfParens->MatchingParen) { 1949 auto *Prev = LeftOfParens->MatchingParen->getPreviousNonComment(); 1950 if (Prev && Prev->isOneOf(tok::kw_const_cast, tok::kw_dynamic_cast, 1951 tok::kw_reinterpret_cast, tok::kw_static_cast)) 1952 // FIXME: Maybe we should handle identifiers ending with "_cast", 1953 // e.g. any_cast? 1954 return true; 1955 } 1956 return false; 1957 } 1958 1959 /// Determine whether ')' is ending a cast. 1960 bool rParenEndsCast(const FormatToken &Tok) { 1961 // C-style casts are only used in C++, C# and Java. 1962 if (!Style.isCSharp() && !Style.isCpp() && 1963 Style.Language != FormatStyle::LK_Java) 1964 return false; 1965 1966 // Empty parens aren't casts and there are no casts at the end of the line. 1967 if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen) 1968 return false; 1969 1970 FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment(); 1971 if (LeftOfParens) { 1972 // If there is a closing parenthesis left of the current 1973 // parentheses, look past it as these might be chained casts. 1974 if (LeftOfParens->is(tok::r_paren) && 1975 LeftOfParens->isNot(TT_CastRParen)) { 1976 if (!LeftOfParens->MatchingParen || 1977 !LeftOfParens->MatchingParen->Previous) 1978 return false; 1979 LeftOfParens = LeftOfParens->MatchingParen->Previous; 1980 } 1981 1982 if (LeftOfParens->is(tok::r_square)) { 1983 // delete[] (void *)ptr; 1984 auto MayBeArrayDelete = [](FormatToken *Tok) -> FormatToken * { 1985 if (Tok->isNot(tok::r_square)) 1986 return nullptr; 1987 1988 Tok = Tok->getPreviousNonComment(); 1989 if (!Tok || Tok->isNot(tok::l_square)) 1990 return nullptr; 1991 1992 Tok = Tok->getPreviousNonComment(); 1993 if (!Tok || Tok->isNot(tok::kw_delete)) 1994 return nullptr; 1995 return Tok; 1996 }; 1997 if (FormatToken *MaybeDelete = MayBeArrayDelete(LeftOfParens)) 1998 LeftOfParens = MaybeDelete; 1999 } 2000 2001 // The Condition directly below this one will see the operator arguments 2002 // as a (void *foo) cast. 2003 // void operator delete(void *foo) ATTRIB; 2004 if (LeftOfParens->Tok.getIdentifierInfo() && LeftOfParens->Previous && 2005 LeftOfParens->Previous->is(tok::kw_operator)) 2006 return false; 2007 2008 // If there is an identifier (or with a few exceptions a keyword) right 2009 // before the parentheses, this is unlikely to be a cast. 2010 if (LeftOfParens->Tok.getIdentifierInfo() && 2011 !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case, 2012 tok::kw_delete)) 2013 return false; 2014 2015 // Certain other tokens right before the parentheses are also signals that 2016 // this cannot be a cast. 2017 if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator, 2018 TT_TemplateCloser, tok::ellipsis)) 2019 return false; 2020 } 2021 2022 if (Tok.Next->is(tok::question)) 2023 return false; 2024 2025 // `foreach((A a, B b) in someList)` should not be seen as a cast. 2026 if (Tok.Next->is(Keywords.kw_in) && Style.isCSharp()) 2027 return false; 2028 2029 // Functions which end with decorations like volatile, noexcept are unlikely 2030 // to be casts. 2031 if (Tok.Next->isOneOf(tok::kw_noexcept, tok::kw_volatile, tok::kw_const, 2032 tok::kw_requires, tok::kw_throw, tok::arrow, 2033 Keywords.kw_override, Keywords.kw_final) || 2034 isCpp11AttributeSpecifier(*Tok.Next)) 2035 return false; 2036 2037 // As Java has no function types, a "(" after the ")" likely means that this 2038 // is a cast. 2039 if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren)) 2040 return true; 2041 2042 // If a (non-string) literal follows, this is likely a cast. 2043 if (Tok.Next->isNot(tok::string_literal) && 2044 (Tok.Next->Tok.isLiteral() || 2045 Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof))) 2046 return true; 2047 2048 // Heuristically try to determine whether the parentheses contain a type. 2049 auto IsQualifiedPointerOrReference = [](FormatToken *T) { 2050 // This is used to handle cases such as x = (foo *const)&y; 2051 assert(!T->isSimpleTypeSpecifier() && "Should have already been checked"); 2052 // Strip trailing qualifiers such as const or volatile when checking 2053 // whether the parens could be a cast to a pointer/reference type. 2054 while (T) { 2055 if (T->is(TT_AttributeParen)) { 2056 // Handle `x = (foo *__attribute__((foo)))&v;`: 2057 if (T->MatchingParen && T->MatchingParen->Previous && 2058 T->MatchingParen->Previous->is(tok::kw___attribute)) { 2059 T = T->MatchingParen->Previous->Previous; 2060 continue; 2061 } 2062 } else if (T->is(TT_AttributeSquare)) { 2063 // Handle `x = (foo *[[clang::foo]])&v;`: 2064 if (T->MatchingParen && T->MatchingParen->Previous) { 2065 T = T->MatchingParen->Previous; 2066 continue; 2067 } 2068 } else if (T->canBePointerOrReferenceQualifier()) { 2069 T = T->Previous; 2070 continue; 2071 } 2072 break; 2073 } 2074 return T && T->is(TT_PointerOrReference); 2075 }; 2076 bool ParensAreType = 2077 !Tok.Previous || 2078 Tok.Previous->isOneOf(TT_TemplateCloser, TT_TypeDeclarationParen) || 2079 Tok.Previous->isSimpleTypeSpecifier() || 2080 IsQualifiedPointerOrReference(Tok.Previous); 2081 bool ParensCouldEndDecl = 2082 Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater); 2083 if (ParensAreType && !ParensCouldEndDecl) 2084 return true; 2085 2086 // At this point, we heuristically assume that there are no casts at the 2087 // start of the line. We assume that we have found most cases where there 2088 // are by the logic above, e.g. "(void)x;". 2089 if (!LeftOfParens) 2090 return false; 2091 2092 // Certain token types inside the parentheses mean that this can't be a 2093 // cast. 2094 for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok; 2095 Token = Token->Next) 2096 if (Token->is(TT_BinaryOperator)) 2097 return false; 2098 2099 // If the following token is an identifier or 'this', this is a cast. All 2100 // cases where this can be something else are handled above. 2101 if (Tok.Next->isOneOf(tok::identifier, tok::kw_this)) 2102 return true; 2103 2104 // Look for a cast `( x ) (`. 2105 if (Tok.Next->is(tok::l_paren) && Tok.Previous && Tok.Previous->Previous) { 2106 if (Tok.Previous->is(tok::identifier) && 2107 Tok.Previous->Previous->is(tok::l_paren)) 2108 return true; 2109 } 2110 2111 if (!Tok.Next->Next) 2112 return false; 2113 2114 // If the next token after the parenthesis is a unary operator, assume 2115 // that this is cast, unless there are unexpected tokens inside the 2116 // parenthesis. 2117 bool NextIsUnary = 2118 Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star); 2119 if (!NextIsUnary || Tok.Next->is(tok::plus) || 2120 !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant)) 2121 return false; 2122 // Search for unexpected tokens. 2123 for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen; 2124 Prev = Prev->Previous) 2125 if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon)) 2126 return false; 2127 return true; 2128 } 2129 2130 /// Return the type of the given token assuming it is * or &. 2131 TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression, 2132 bool InTemplateArgument) { 2133 if (Style.isJavaScript()) 2134 return TT_BinaryOperator; 2135 2136 // && in C# must be a binary operator. 2137 if (Style.isCSharp() && Tok.is(tok::ampamp)) 2138 return TT_BinaryOperator; 2139 2140 const FormatToken *PrevToken = Tok.getPreviousNonComment(); 2141 if (!PrevToken) 2142 return TT_UnaryOperator; 2143 2144 const FormatToken *NextToken = Tok.getNextNonComment(); 2145 2146 if (InTemplateArgument && NextToken && NextToken->is(tok::kw_noexcept)) 2147 return TT_BinaryOperator; 2148 2149 if (!NextToken || 2150 NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_noexcept) || 2151 NextToken->canBePointerOrReferenceQualifier() || 2152 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment())) 2153 return TT_PointerOrReference; 2154 2155 if (PrevToken->is(tok::coloncolon)) 2156 return TT_PointerOrReference; 2157 2158 if (PrevToken->is(tok::r_paren) && PrevToken->is(TT_TypeDeclarationParen)) 2159 return TT_PointerOrReference; 2160 2161 if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace, 2162 tok::comma, tok::semi, tok::kw_return, tok::colon, 2163 tok::kw_co_return, tok::kw_co_await, 2164 tok::kw_co_yield, tok::equal, tok::kw_delete, 2165 tok::kw_sizeof, tok::kw_throw, TT_BinaryOperator, 2166 TT_ConditionalExpr, TT_UnaryOperator, TT_CastRParen)) 2167 return TT_UnaryOperator; 2168 2169 if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare)) 2170 return TT_PointerOrReference; 2171 if (NextToken->is(tok::kw_operator) && !IsExpression) 2172 return TT_PointerOrReference; 2173 if (NextToken->isOneOf(tok::comma, tok::semi)) 2174 return TT_PointerOrReference; 2175 2176 if (PrevToken->Tok.isLiteral() || 2177 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true, 2178 tok::kw_false, tok::r_brace) || 2179 NextToken->Tok.isLiteral() || 2180 NextToken->isOneOf(tok::kw_true, tok::kw_false) || 2181 NextToken->isUnaryOperator() || 2182 // If we know we're in a template argument, there are no named 2183 // declarations. Thus, having an identifier on the right-hand side 2184 // indicates a binary operator. 2185 (InTemplateArgument && NextToken->Tok.isAnyIdentifier())) 2186 return TT_BinaryOperator; 2187 2188 // "&&(" is quite unlikely to be two successive unary "&". 2189 if (Tok.is(tok::ampamp) && NextToken->is(tok::l_paren)) 2190 return TT_BinaryOperator; 2191 2192 // This catches some cases where evaluation order is used as control flow: 2193 // aaa && aaa->f(); 2194 if (NextToken->Tok.isAnyIdentifier()) { 2195 const FormatToken *NextNextToken = NextToken->getNextNonComment(); 2196 if (NextNextToken && NextNextToken->is(tok::arrow)) 2197 return TT_BinaryOperator; 2198 } 2199 2200 // It is very unlikely that we are going to find a pointer or reference type 2201 // definition on the RHS of an assignment. 2202 if (IsExpression && !Contexts.back().CaretFound) 2203 return TT_BinaryOperator; 2204 2205 return TT_PointerOrReference; 2206 } 2207 2208 TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) { 2209 const FormatToken *PrevToken = Tok.getPreviousNonComment(); 2210 if (!PrevToken) 2211 return TT_UnaryOperator; 2212 2213 if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator)) 2214 // This must be a sequence of leading unary operators. 2215 return TT_UnaryOperator; 2216 2217 // Use heuristics to recognize unary operators. 2218 if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square, 2219 tok::question, tok::colon, tok::kw_return, 2220 tok::kw_case, tok::at, tok::l_brace, tok::kw_throw, 2221 tok::kw_co_return, tok::kw_co_yield)) 2222 return TT_UnaryOperator; 2223 2224 // There can't be two consecutive binary operators. 2225 if (PrevToken->is(TT_BinaryOperator)) 2226 return TT_UnaryOperator; 2227 2228 // Fall back to marking the token as binary operator. 2229 return TT_BinaryOperator; 2230 } 2231 2232 /// Determine whether ++/-- are pre- or post-increments/-decrements. 2233 TokenType determineIncrementUsage(const FormatToken &Tok) { 2234 const FormatToken *PrevToken = Tok.getPreviousNonComment(); 2235 if (!PrevToken || PrevToken->is(TT_CastRParen)) 2236 return TT_UnaryOperator; 2237 if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier)) 2238 return TT_TrailingUnaryOperator; 2239 2240 return TT_UnaryOperator; 2241 } 2242 2243 SmallVector<Context, 8> Contexts; 2244 2245 const FormatStyle &Style; 2246 AnnotatedLine &Line; 2247 FormatToken *CurrentToken; 2248 bool AutoFound; 2249 const AdditionalKeywords &Keywords; 2250 2251 // Set of "<" tokens that do not open a template parameter list. If parseAngle 2252 // determines that a specific token can't be a template opener, it will make 2253 // same decision irrespective of the decisions for tokens leading up to it. 2254 // Store this information to prevent this from causing exponential runtime. 2255 llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess; 2256 }; 2257 2258 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1; 2259 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2; 2260 2261 /// Parses binary expressions by inserting fake parenthesis based on 2262 /// operator precedence. 2263 class ExpressionParser { 2264 public: 2265 ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords, 2266 AnnotatedLine &Line) 2267 : Style(Style), Keywords(Keywords), Line(Line), Current(Line.First) {} 2268 2269 /// Parse expressions with the given operator precedence. 2270 void parse(int Precedence = 0) { 2271 // Skip 'return' and ObjC selector colons as they are not part of a binary 2272 // expression. 2273 while (Current && (Current->is(tok::kw_return) || 2274 (Current->is(tok::colon) && 2275 Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)))) 2276 next(); 2277 2278 if (!Current || Precedence > PrecedenceArrowAndPeriod) 2279 return; 2280 2281 // Conditional expressions need to be parsed separately for proper nesting. 2282 if (Precedence == prec::Conditional) { 2283 parseConditionalExpr(); 2284 return; 2285 } 2286 2287 // Parse unary operators, which all have a higher precedence than binary 2288 // operators. 2289 if (Precedence == PrecedenceUnaryOperator) { 2290 parseUnaryOperator(); 2291 return; 2292 } 2293 2294 FormatToken *Start = Current; 2295 FormatToken *LatestOperator = nullptr; 2296 unsigned OperatorIndex = 0; 2297 2298 while (Current) { 2299 // Consume operators with higher precedence. 2300 parse(Precedence + 1); 2301 2302 int CurrentPrecedence = getCurrentPrecedence(); 2303 2304 if (Precedence == CurrentPrecedence && Current && 2305 Current->is(TT_SelectorName)) { 2306 if (LatestOperator) 2307 addFakeParenthesis(Start, prec::Level(Precedence)); 2308 Start = Current; 2309 } 2310 2311 // At the end of the line or when an operator with higher precedence is 2312 // found, insert fake parenthesis and return. 2313 if (!Current || 2314 (Current->closesScope() && 2315 (Current->MatchingParen || Current->is(TT_TemplateString))) || 2316 (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) || 2317 (CurrentPrecedence == prec::Conditional && 2318 Precedence == prec::Assignment && Current->is(tok::colon))) 2319 break; 2320 2321 // Consume scopes: (), [], <> and {} 2322 // In addition to that we handle require clauses as scope, so that the 2323 // constraints in that are correctly indented. 2324 if (Current->opensScope() || 2325 Current->isOneOf(TT_RequiresClause, 2326 TT_RequiresClauseInARequiresExpression)) { 2327 // In fragment of a JavaScript template string can look like '}..${' and 2328 // thus close a scope and open a new one at the same time. 2329 while (Current && (!Current->closesScope() || Current->opensScope())) { 2330 next(); 2331 parse(); 2332 } 2333 next(); 2334 } else { 2335 // Operator found. 2336 if (CurrentPrecedence == Precedence) { 2337 if (LatestOperator) 2338 LatestOperator->NextOperator = Current; 2339 LatestOperator = Current; 2340 Current->OperatorIndex = OperatorIndex; 2341 ++OperatorIndex; 2342 } 2343 next(/*SkipPastLeadingComments=*/Precedence > 0); 2344 } 2345 } 2346 2347 if (LatestOperator && (Current || Precedence > 0)) { 2348 // The requires clauses do not neccessarily end in a semicolon or a brace, 2349 // but just go over to struct/class or a function declaration, we need to 2350 // intervene so that the fake right paren is inserted correctly. 2351 auto End = 2352 (Start->Previous && 2353 Start->Previous->isOneOf(TT_RequiresClause, 2354 TT_RequiresClauseInARequiresExpression)) 2355 ? [this](){ 2356 auto Ret = Current ? Current : Line.Last; 2357 while (!Ret->ClosesRequiresClause && Ret->Previous) 2358 Ret = Ret->Previous; 2359 return Ret; 2360 }() 2361 : nullptr; 2362 2363 if (Precedence == PrecedenceArrowAndPeriod) { 2364 // Call expressions don't have a binary operator precedence. 2365 addFakeParenthesis(Start, prec::Unknown, End); 2366 } else { 2367 addFakeParenthesis(Start, prec::Level(Precedence), End); 2368 } 2369 } 2370 } 2371 2372 private: 2373 /// Gets the precedence (+1) of the given token for binary operators 2374 /// and other tokens that we treat like binary operators. 2375 int getCurrentPrecedence() { 2376 if (Current) { 2377 const FormatToken *NextNonComment = Current->getNextNonComment(); 2378 if (Current->is(TT_ConditionalExpr)) 2379 return prec::Conditional; 2380 if (NextNonComment && Current->is(TT_SelectorName) && 2381 (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) || 2382 ((Style.Language == FormatStyle::LK_Proto || 2383 Style.Language == FormatStyle::LK_TextProto) && 2384 NextNonComment->is(tok::less)))) 2385 return prec::Assignment; 2386 if (Current->is(TT_JsComputedPropertyName)) 2387 return prec::Assignment; 2388 if (Current->is(TT_LambdaArrow)) 2389 return prec::Comma; 2390 if (Current->is(TT_FatArrow)) 2391 return prec::Assignment; 2392 if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) || 2393 (Current->is(tok::comment) && NextNonComment && 2394 NextNonComment->is(TT_SelectorName))) 2395 return 0; 2396 if (Current->is(TT_RangeBasedForLoopColon)) 2397 return prec::Comma; 2398 if ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) && 2399 Current->is(Keywords.kw_instanceof)) 2400 return prec::Relational; 2401 if (Style.isJavaScript() && 2402 Current->isOneOf(Keywords.kw_in, Keywords.kw_as)) 2403 return prec::Relational; 2404 if (Current->is(TT_BinaryOperator) || Current->is(tok::comma)) 2405 return Current->getPrecedence(); 2406 if (Current->isOneOf(tok::period, tok::arrow)) 2407 return PrecedenceArrowAndPeriod; 2408 if ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) && 2409 Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements, 2410 Keywords.kw_throws)) 2411 return 0; 2412 } 2413 return -1; 2414 } 2415 2416 void addFakeParenthesis(FormatToken *Start, prec::Level Precedence, 2417 FormatToken *End = nullptr) { 2418 Start->FakeLParens.push_back(Precedence); 2419 if (Precedence > prec::Unknown) 2420 Start->StartsBinaryExpression = true; 2421 if (!End && Current) 2422 End = Current->getPreviousNonComment(); 2423 if (End) { 2424 ++End->FakeRParens; 2425 if (Precedence > prec::Unknown) 2426 End->EndsBinaryExpression = true; 2427 } 2428 } 2429 2430 /// Parse unary operator expressions and surround them with fake 2431 /// parentheses if appropriate. 2432 void parseUnaryOperator() { 2433 llvm::SmallVector<FormatToken *, 2> Tokens; 2434 while (Current && Current->is(TT_UnaryOperator)) { 2435 Tokens.push_back(Current); 2436 next(); 2437 } 2438 parse(PrecedenceArrowAndPeriod); 2439 for (FormatToken *Token : llvm::reverse(Tokens)) 2440 // The actual precedence doesn't matter. 2441 addFakeParenthesis(Token, prec::Unknown); 2442 } 2443 2444 void parseConditionalExpr() { 2445 while (Current && Current->isTrailingComment()) 2446 next(); 2447 FormatToken *Start = Current; 2448 parse(prec::LogicalOr); 2449 if (!Current || !Current->is(tok::question)) 2450 return; 2451 next(); 2452 parse(prec::Assignment); 2453 if (!Current || Current->isNot(TT_ConditionalExpr)) 2454 return; 2455 next(); 2456 parse(prec::Assignment); 2457 addFakeParenthesis(Start, prec::Conditional); 2458 } 2459 2460 void next(bool SkipPastLeadingComments = true) { 2461 if (Current) 2462 Current = Current->Next; 2463 while (Current && 2464 (Current->NewlinesBefore == 0 || SkipPastLeadingComments) && 2465 Current->isTrailingComment()) 2466 Current = Current->Next; 2467 } 2468 2469 const FormatStyle &Style; 2470 const AdditionalKeywords &Keywords; 2471 const AnnotatedLine &Line; 2472 FormatToken *Current; 2473 }; 2474 2475 } // end anonymous namespace 2476 2477 void TokenAnnotator::setCommentLineLevels( 2478 SmallVectorImpl<AnnotatedLine *> &Lines) { 2479 const AnnotatedLine *NextNonCommentLine = nullptr; 2480 for (AnnotatedLine *Line : llvm::reverse(Lines)) { 2481 assert(Line->First); 2482 bool CommentLine = true; 2483 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) { 2484 if (!Tok->is(tok::comment)) { 2485 CommentLine = false; 2486 break; 2487 } 2488 } 2489 2490 // If the comment is currently aligned with the line immediately following 2491 // it, that's probably intentional and we should keep it. 2492 if (NextNonCommentLine && CommentLine && 2493 NextNonCommentLine->First->NewlinesBefore <= 1 && 2494 NextNonCommentLine->First->OriginalColumn == 2495 Line->First->OriginalColumn) { 2496 // Align comments for preprocessor lines with the # in column 0 if 2497 // preprocessor lines are not indented. Otherwise, align with the next 2498 // line. 2499 Line->Level = 2500 (Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash && 2501 (NextNonCommentLine->Type == LT_PreprocessorDirective || 2502 NextNonCommentLine->Type == LT_ImportStatement)) 2503 ? 0 2504 : NextNonCommentLine->Level; 2505 } else { 2506 NextNonCommentLine = Line->First->isNot(tok::r_brace) ? Line : nullptr; 2507 } 2508 2509 setCommentLineLevels(Line->Children); 2510 } 2511 } 2512 2513 static unsigned maxNestingDepth(const AnnotatedLine &Line) { 2514 unsigned Result = 0; 2515 for (const auto *Tok = Line.First; Tok != nullptr; Tok = Tok->Next) 2516 Result = std::max(Result, Tok->NestingLevel); 2517 return Result; 2518 } 2519 2520 void TokenAnnotator::annotate(AnnotatedLine &Line) { 2521 for (auto &Child : Line.Children) 2522 annotate(*Child); 2523 2524 AnnotatingParser Parser(Style, Line, Keywords); 2525 Line.Type = Parser.parseLine(); 2526 2527 // With very deep nesting, ExpressionParser uses lots of stack and the 2528 // formatting algorithm is very slow. We're not going to do a good job here 2529 // anyway - it's probably generated code being formatted by mistake. 2530 // Just skip the whole line. 2531 if (maxNestingDepth(Line) > 50) 2532 Line.Type = LT_Invalid; 2533 2534 if (Line.Type == LT_Invalid) 2535 return; 2536 2537 ExpressionParser ExprParser(Style, Keywords, Line); 2538 ExprParser.parse(); 2539 2540 if (Line.startsWith(TT_ObjCMethodSpecifier)) 2541 Line.Type = LT_ObjCMethodDecl; 2542 else if (Line.startsWith(TT_ObjCDecl)) 2543 Line.Type = LT_ObjCDecl; 2544 else if (Line.startsWith(TT_ObjCProperty)) 2545 Line.Type = LT_ObjCProperty; 2546 2547 Line.First->SpacesRequiredBefore = 1; 2548 Line.First->CanBreakBefore = Line.First->MustBreakBefore; 2549 } 2550 2551 // This function heuristically determines whether 'Current' starts the name of a 2552 // function declaration. 2553 static bool isFunctionDeclarationName(bool IsCpp, const FormatToken &Current, 2554 const AnnotatedLine &Line) { 2555 auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * { 2556 for (; Next; Next = Next->Next) { 2557 if (Next->is(TT_OverloadedOperatorLParen)) 2558 return Next; 2559 if (Next->is(TT_OverloadedOperator)) 2560 continue; 2561 if (Next->isOneOf(tok::kw_new, tok::kw_delete)) { 2562 // For 'new[]' and 'delete[]'. 2563 if (Next->Next && 2564 Next->Next->startsSequence(tok::l_square, tok::r_square)) 2565 Next = Next->Next->Next; 2566 continue; 2567 } 2568 if (Next->startsSequence(tok::l_square, tok::r_square)) { 2569 // For operator[](). 2570 Next = Next->Next; 2571 continue; 2572 } 2573 if ((Next->isSimpleTypeSpecifier() || Next->is(tok::identifier)) && 2574 Next->Next && Next->Next->isOneOf(tok::star, tok::amp, tok::ampamp)) { 2575 // For operator void*(), operator char*(), operator Foo*(). 2576 Next = Next->Next; 2577 continue; 2578 } 2579 if (Next->is(TT_TemplateOpener) && Next->MatchingParen) { 2580 Next = Next->MatchingParen; 2581 continue; 2582 } 2583 2584 break; 2585 } 2586 return nullptr; 2587 }; 2588 2589 // Find parentheses of parameter list. 2590 const FormatToken *Next = Current.Next; 2591 if (Current.is(tok::kw_operator)) { 2592 if (Current.Previous && Current.Previous->is(tok::coloncolon)) 2593 return false; 2594 Next = skipOperatorName(Next); 2595 } else { 2596 if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0) 2597 return false; 2598 for (; Next; Next = Next->Next) { 2599 if (Next->is(TT_TemplateOpener)) { 2600 Next = Next->MatchingParen; 2601 } else if (Next->is(tok::coloncolon)) { 2602 Next = Next->Next; 2603 if (!Next) 2604 return false; 2605 if (Next->is(tok::kw_operator)) { 2606 Next = skipOperatorName(Next->Next); 2607 break; 2608 } 2609 if (!Next->is(tok::identifier)) 2610 return false; 2611 } else if (Next->is(tok::l_paren)) { 2612 break; 2613 } else { 2614 return false; 2615 } 2616 } 2617 } 2618 2619 // Check whether parameter list can belong to a function declaration. 2620 if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen) 2621 return false; 2622 // If the lines ends with "{", this is likely a function definition. 2623 if (Line.Last->is(tok::l_brace)) 2624 return true; 2625 if (Next->Next == Next->MatchingParen) 2626 return true; // Empty parentheses. 2627 // If there is an &/&& after the r_paren, this is likely a function. 2628 if (Next->MatchingParen->Next && 2629 Next->MatchingParen->Next->is(TT_PointerOrReference)) 2630 return true; 2631 2632 // Check for K&R C function definitions (and C++ function definitions with 2633 // unnamed parameters), e.g.: 2634 // int f(i) 2635 // { 2636 // return i + 1; 2637 // } 2638 // bool g(size_t = 0, bool b = false) 2639 // { 2640 // return !b; 2641 // } 2642 if (IsCpp && Next->Next && Next->Next->is(tok::identifier) && 2643 !Line.endsWith(tok::semi)) 2644 return true; 2645 2646 for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen; 2647 Tok = Tok->Next) { 2648 if (Tok->is(TT_TypeDeclarationParen)) 2649 return true; 2650 if (Tok->isOneOf(tok::l_paren, TT_TemplateOpener) && Tok->MatchingParen) { 2651 Tok = Tok->MatchingParen; 2652 continue; 2653 } 2654 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() || 2655 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis)) 2656 return true; 2657 if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) || 2658 Tok->Tok.isLiteral()) 2659 return false; 2660 } 2661 return false; 2662 } 2663 2664 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const { 2665 assert(Line.MightBeFunctionDecl); 2666 2667 if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel || 2668 Style.AlwaysBreakAfterReturnType == 2669 FormatStyle::RTBS_TopLevelDefinitions) && 2670 Line.Level > 0) 2671 return false; 2672 2673 switch (Style.AlwaysBreakAfterReturnType) { 2674 case FormatStyle::RTBS_None: 2675 return false; 2676 case FormatStyle::RTBS_All: 2677 case FormatStyle::RTBS_TopLevel: 2678 return true; 2679 case FormatStyle::RTBS_AllDefinitions: 2680 case FormatStyle::RTBS_TopLevelDefinitions: 2681 return Line.mightBeFunctionDefinition(); 2682 } 2683 2684 return false; 2685 } 2686 2687 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) { 2688 for (AnnotatedLine *ChildLine : Line.Children) 2689 calculateFormattingInformation(*ChildLine); 2690 2691 Line.First->TotalLength = 2692 Line.First->IsMultiline ? Style.ColumnLimit 2693 : Line.FirstStartColumn + Line.First->ColumnWidth; 2694 FormatToken *Current = Line.First->Next; 2695 bool InFunctionDecl = Line.MightBeFunctionDecl; 2696 bool AlignArrayOfStructures = 2697 (Style.AlignArrayOfStructures != FormatStyle::AIAS_None && 2698 Line.Type == LT_ArrayOfStructInitializer); 2699 if (AlignArrayOfStructures) 2700 calculateArrayInitializerColumnList(Line); 2701 2702 while (Current) { 2703 if (isFunctionDeclarationName(Style.isCpp(), *Current, Line)) 2704 Current->setType(TT_FunctionDeclarationName); 2705 const FormatToken *Prev = Current->Previous; 2706 if (Current->is(TT_LineComment)) { 2707 if (Prev->is(BK_BracedInit) && Prev->opensScope()) 2708 Current->SpacesRequiredBefore = 2709 (Style.Cpp11BracedListStyle && !Style.SpacesInParentheses) ? 0 : 1; 2710 else 2711 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments; 2712 2713 // If we find a trailing comment, iterate backwards to determine whether 2714 // it seems to relate to a specific parameter. If so, break before that 2715 // parameter to avoid changing the comment's meaning. E.g. don't move 'b' 2716 // to the previous line in: 2717 // SomeFunction(a, 2718 // b, // comment 2719 // c); 2720 if (!Current->HasUnescapedNewline) { 2721 for (FormatToken *Parameter = Current->Previous; Parameter; 2722 Parameter = Parameter->Previous) { 2723 if (Parameter->isOneOf(tok::comment, tok::r_brace)) 2724 break; 2725 if (Parameter->Previous && Parameter->Previous->is(tok::comma)) { 2726 if (!Parameter->Previous->is(TT_CtorInitializerComma) && 2727 Parameter->HasUnescapedNewline) 2728 Parameter->MustBreakBefore = true; 2729 break; 2730 } 2731 } 2732 } 2733 } else if (Current->SpacesRequiredBefore == 0 && 2734 spaceRequiredBefore(Line, *Current)) { 2735 Current->SpacesRequiredBefore = 1; 2736 } 2737 2738 Current->MustBreakBefore = 2739 Current->MustBreakBefore || mustBreakBefore(Line, *Current); 2740 2741 if (!Current->MustBreakBefore && InFunctionDecl && 2742 Current->is(TT_FunctionDeclarationName)) 2743 Current->MustBreakBefore = mustBreakForReturnType(Line); 2744 2745 Current->CanBreakBefore = 2746 Current->MustBreakBefore || canBreakBefore(Line, *Current); 2747 unsigned ChildSize = 0; 2748 if (Prev->Children.size() == 1) { 2749 FormatToken &LastOfChild = *Prev->Children[0]->Last; 2750 ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit 2751 : LastOfChild.TotalLength + 1; 2752 } 2753 if (Current->MustBreakBefore || Prev->Children.size() > 1 || 2754 (Prev->Children.size() == 1 && 2755 Prev->Children[0]->First->MustBreakBefore) || 2756 Current->IsMultiline) 2757 Current->TotalLength = Prev->TotalLength + Style.ColumnLimit; 2758 else 2759 Current->TotalLength = Prev->TotalLength + Current->ColumnWidth + 2760 ChildSize + Current->SpacesRequiredBefore; 2761 2762 if (Current->is(TT_CtorInitializerColon)) 2763 InFunctionDecl = false; 2764 2765 // FIXME: Only calculate this if CanBreakBefore is true once static 2766 // initializers etc. are sorted out. 2767 // FIXME: Move magic numbers to a better place. 2768 2769 // Reduce penalty for aligning ObjC method arguments using the colon 2770 // alignment as this is the canonical way (still prefer fitting everything 2771 // into one line if possible). Trying to fit a whole expression into one 2772 // line should not force other line breaks (e.g. when ObjC method 2773 // expression is a part of other expression). 2774 Current->SplitPenalty = splitPenalty(Line, *Current, InFunctionDecl); 2775 if (Style.Language == FormatStyle::LK_ObjC && 2776 Current->is(TT_SelectorName) && Current->ParameterIndex > 0) { 2777 if (Current->ParameterIndex == 1) 2778 Current->SplitPenalty += 5 * Current->BindingStrength; 2779 } else { 2780 Current->SplitPenalty += 20 * Current->BindingStrength; 2781 } 2782 2783 Current = Current->Next; 2784 } 2785 2786 calculateUnbreakableTailLengths(Line); 2787 unsigned IndentLevel = Line.Level; 2788 for (Current = Line.First; Current != nullptr; Current = Current->Next) { 2789 if (Current->Role) 2790 Current->Role->precomputeFormattingInfos(Current); 2791 if (Current->MatchingParen && 2792 Current->MatchingParen->opensBlockOrBlockTypeList(Style) && 2793 IndentLevel > 0) 2794 --IndentLevel; 2795 Current->IndentLevel = IndentLevel; 2796 if (Current->opensBlockOrBlockTypeList(Style)) 2797 ++IndentLevel; 2798 } 2799 2800 LLVM_DEBUG({ printDebugInfo(Line); }); 2801 } 2802 2803 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) { 2804 unsigned UnbreakableTailLength = 0; 2805 FormatToken *Current = Line.Last; 2806 while (Current) { 2807 Current->UnbreakableTailLength = UnbreakableTailLength; 2808 if (Current->CanBreakBefore || 2809 Current->isOneOf(tok::comment, tok::string_literal)) { 2810 UnbreakableTailLength = 0; 2811 } else { 2812 UnbreakableTailLength += 2813 Current->ColumnWidth + Current->SpacesRequiredBefore; 2814 } 2815 Current = Current->Previous; 2816 } 2817 } 2818 2819 void TokenAnnotator::calculateArrayInitializerColumnList(AnnotatedLine &Line) { 2820 if (Line.First == Line.Last) 2821 return; 2822 auto *CurrentToken = Line.First; 2823 CurrentToken->ArrayInitializerLineStart = true; 2824 unsigned Depth = 0; 2825 while (CurrentToken != nullptr && CurrentToken != Line.Last) { 2826 if (CurrentToken->is(tok::l_brace)) { 2827 CurrentToken->IsArrayInitializer = true; 2828 if (CurrentToken->Next != nullptr) 2829 CurrentToken->Next->MustBreakBefore = true; 2830 CurrentToken = 2831 calculateInitializerColumnList(Line, CurrentToken->Next, Depth + 1); 2832 } else { 2833 CurrentToken = CurrentToken->Next; 2834 } 2835 } 2836 } 2837 2838 FormatToken *TokenAnnotator::calculateInitializerColumnList( 2839 AnnotatedLine &Line, FormatToken *CurrentToken, unsigned Depth) { 2840 while (CurrentToken != nullptr && CurrentToken != Line.Last) { 2841 if (CurrentToken->is(tok::l_brace)) 2842 ++Depth; 2843 else if (CurrentToken->is(tok::r_brace)) 2844 --Depth; 2845 if (Depth == 2 && CurrentToken->isOneOf(tok::l_brace, tok::comma)) { 2846 CurrentToken = CurrentToken->Next; 2847 if (CurrentToken == nullptr) 2848 break; 2849 CurrentToken->StartsColumn = true; 2850 CurrentToken = CurrentToken->Previous; 2851 } 2852 CurrentToken = CurrentToken->Next; 2853 } 2854 return CurrentToken; 2855 } 2856 2857 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line, 2858 const FormatToken &Tok, 2859 bool InFunctionDecl) { 2860 const FormatToken &Left = *Tok.Previous; 2861 const FormatToken &Right = Tok; 2862 2863 if (Left.is(tok::semi)) 2864 return 0; 2865 2866 if (Style.Language == FormatStyle::LK_Java) { 2867 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws)) 2868 return 1; 2869 if (Right.is(Keywords.kw_implements)) 2870 return 2; 2871 if (Left.is(tok::comma) && Left.NestingLevel == 0) 2872 return 3; 2873 } else if (Style.isJavaScript()) { 2874 if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma)) 2875 return 100; 2876 if (Left.is(TT_JsTypeColon)) 2877 return 35; 2878 if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) || 2879 (Right.is(TT_TemplateString) && Right.TokenText.startswith("}"))) 2880 return 100; 2881 // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()". 2882 if (Left.opensScope() && Right.closesScope()) 2883 return 200; 2884 } 2885 2886 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral)) 2887 return 1; 2888 if (Right.is(tok::l_square)) { 2889 if (Style.Language == FormatStyle::LK_Proto) 2890 return 1; 2891 if (Left.is(tok::r_square)) 2892 return 200; 2893 // Slightly prefer formatting local lambda definitions like functions. 2894 if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal)) 2895 return 35; 2896 if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare, 2897 TT_ArrayInitializerLSquare, 2898 TT_DesignatedInitializerLSquare, TT_AttributeSquare)) 2899 return 500; 2900 } 2901 2902 if (Left.is(tok::coloncolon) || 2903 (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto)) 2904 return 500; 2905 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) || 2906 Right.is(tok::kw_operator)) { 2907 if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt) 2908 return 3; 2909 if (Left.is(TT_StartOfName)) 2910 return 110; 2911 if (InFunctionDecl && Right.NestingLevel == 0) 2912 return Style.PenaltyReturnTypeOnItsOwnLine; 2913 return 200; 2914 } 2915 if (Right.is(TT_PointerOrReference)) 2916 return 190; 2917 if (Right.is(TT_LambdaArrow)) 2918 return 110; 2919 if (Left.is(tok::equal) && Right.is(tok::l_brace)) 2920 return 160; 2921 if (Left.is(TT_CastRParen)) 2922 return 100; 2923 if (Left.isOneOf(tok::kw_class, tok::kw_struct)) 2924 return 5000; 2925 if (Left.is(tok::comment)) 2926 return 1000; 2927 2928 if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon, 2929 TT_CtorInitializerColon)) 2930 return 2; 2931 2932 if (Right.isMemberAccess()) { 2933 // Breaking before the "./->" of a chained call/member access is reasonably 2934 // cheap, as formatting those with one call per line is generally 2935 // desirable. In particular, it should be cheaper to break before the call 2936 // than it is to break inside a call's parameters, which could lead to weird 2937 // "hanging" indents. The exception is the very last "./->" to support this 2938 // frequent pattern: 2939 // 2940 // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc( 2941 // dddddddd); 2942 // 2943 // which might otherwise be blown up onto many lines. Here, clang-format 2944 // won't produce "hanging" indents anyway as there is no other trailing 2945 // call. 2946 // 2947 // Also apply higher penalty is not a call as that might lead to a wrapping 2948 // like: 2949 // 2950 // aaaaaaa 2951 // .aaaaaaaaa.bbbbbbbb(cccccccc); 2952 return !Right.NextOperator || !Right.NextOperator->Previous->closesScope() 2953 ? 150 2954 : 35; 2955 } 2956 2957 if (Right.is(TT_TrailingAnnotation) && 2958 (!Right.Next || Right.Next->isNot(tok::l_paren))) { 2959 // Moving trailing annotations to the next line is fine for ObjC method 2960 // declarations. 2961 if (Line.startsWith(TT_ObjCMethodSpecifier)) 2962 return 10; 2963 // Generally, breaking before a trailing annotation is bad unless it is 2964 // function-like. It seems to be especially preferable to keep standard 2965 // annotations (i.e. "const", "final" and "override") on the same line. 2966 // Use a slightly higher penalty after ")" so that annotations like 2967 // "const override" are kept together. 2968 bool is_short_annotation = Right.TokenText.size() < 10; 2969 return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0); 2970 } 2971 2972 // In for-loops, prefer breaking at ',' and ';'. 2973 if (Line.startsWith(tok::kw_for) && Left.is(tok::equal)) 2974 return 4; 2975 2976 // In Objective-C method expressions, prefer breaking before "param:" over 2977 // breaking after it. 2978 if (Right.is(TT_SelectorName)) 2979 return 0; 2980 if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr)) 2981 return Line.MightBeFunctionDecl ? 50 : 500; 2982 2983 // In Objective-C type declarations, avoid breaking after the category's 2984 // open paren (we'll prefer breaking after the protocol list's opening 2985 // angle bracket, if present). 2986 if (Line.Type == LT_ObjCDecl && Left.is(tok::l_paren) && Left.Previous && 2987 Left.Previous->isOneOf(tok::identifier, tok::greater)) 2988 return 500; 2989 2990 if (Left.is(tok::l_paren) && Style.PenaltyBreakOpenParenthesis != 0) 2991 return Style.PenaltyBreakOpenParenthesis; 2992 if (Left.is(tok::l_paren) && InFunctionDecl && 2993 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign) 2994 return 100; 2995 if (Left.is(tok::l_paren) && Left.Previous && 2996 (Left.Previous->is(tok::kw_for) || Left.Previous->isIf())) 2997 return 1000; 2998 if (Left.is(tok::equal) && InFunctionDecl) 2999 return 110; 3000 if (Right.is(tok::r_brace)) 3001 return 1; 3002 if (Left.is(TT_TemplateOpener)) 3003 return 100; 3004 if (Left.opensScope()) { 3005 // If we aren't aligning after opening parens/braces we can always break 3006 // here unless the style does not want us to place all arguments on the 3007 // next line. 3008 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign && 3009 (Left.ParameterCount <= 1 || Style.AllowAllArgumentsOnNextLine)) 3010 return 0; 3011 if (Left.is(tok::l_brace) && !Style.Cpp11BracedListStyle) 3012 return 19; 3013 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter 3014 : 19; 3015 } 3016 if (Left.is(TT_JavaAnnotation)) 3017 return 50; 3018 3019 if (Left.is(TT_UnaryOperator)) 3020 return 60; 3021 if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous && 3022 Left.Previous->isLabelString() && 3023 (Left.NextOperator || Left.OperatorIndex != 0)) 3024 return 50; 3025 if (Right.is(tok::plus) && Left.isLabelString() && 3026 (Right.NextOperator || Right.OperatorIndex != 0)) 3027 return 25; 3028 if (Left.is(tok::comma)) 3029 return 1; 3030 if (Right.is(tok::lessless) && Left.isLabelString() && 3031 (Right.NextOperator || Right.OperatorIndex != 1)) 3032 return 25; 3033 if (Right.is(tok::lessless)) { 3034 // Breaking at a << is really cheap. 3035 if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0) 3036 // Slightly prefer to break before the first one in log-like statements. 3037 return 2; 3038 return 1; 3039 } 3040 if (Left.ClosesTemplateDeclaration) 3041 return Style.PenaltyBreakTemplateDeclaration; 3042 if (Left.ClosesRequiresClause) 3043 return 0; 3044 if (Left.is(TT_ConditionalExpr)) 3045 return prec::Conditional; 3046 prec::Level Level = Left.getPrecedence(); 3047 if (Level == prec::Unknown) 3048 Level = Right.getPrecedence(); 3049 if (Level == prec::Assignment) 3050 return Style.PenaltyBreakAssignment; 3051 if (Level != prec::Unknown) 3052 return Level; 3053 3054 return 3; 3055 } 3056 3057 bool TokenAnnotator::spaceRequiredBeforeParens(const FormatToken &Right) const { 3058 if (Style.SpaceBeforeParens == FormatStyle::SBPO_Always) 3059 return true; 3060 if (Right.is(TT_OverloadedOperatorLParen) && 3061 Style.SpaceBeforeParensOptions.AfterOverloadedOperator) 3062 return true; 3063 if (Style.SpaceBeforeParensOptions.BeforeNonEmptyParentheses && 3064 Right.ParameterCount > 0) 3065 return true; 3066 return false; 3067 } 3068 3069 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line, 3070 const FormatToken &Left, 3071 const FormatToken &Right) { 3072 if (Left.is(tok::kw_return) && 3073 !Right.isOneOf(tok::semi, tok::r_paren, tok::hashhash)) 3074 return true; 3075 if (Style.isJson() && Left.is(tok::string_literal) && Right.is(tok::colon)) 3076 return false; 3077 if (Left.is(Keywords.kw_assert) && Style.Language == FormatStyle::LK_Java) 3078 return true; 3079 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty && 3080 Left.Tok.getObjCKeywordID() == tok::objc_property) 3081 return true; 3082 if (Right.is(tok::hashhash)) 3083 return Left.is(tok::hash); 3084 if (Left.isOneOf(tok::hashhash, tok::hash)) 3085 return Right.is(tok::hash); 3086 if ((Left.is(tok::l_paren) && Right.is(tok::r_paren)) || 3087 (Left.is(tok::l_brace) && Left.isNot(BK_Block) && 3088 Right.is(tok::r_brace) && Right.isNot(BK_Block))) 3089 return Style.SpaceInEmptyParentheses; 3090 if (Style.SpacesInConditionalStatement) { 3091 if (Left.is(tok::l_paren) && Left.Previous && 3092 isKeywordWithCondition(*Left.Previous)) 3093 return true; 3094 if (Right.is(tok::r_paren) && Right.MatchingParen && 3095 Right.MatchingParen->Previous && 3096 isKeywordWithCondition(*Right.MatchingParen->Previous)) 3097 return true; 3098 } 3099 3100 // auto{x} auto(x) 3101 if (Left.is(tok::kw_auto) && Right.isOneOf(tok::l_paren, tok::l_brace)) 3102 return false; 3103 3104 // operator co_await(x) 3105 if (Right.is(tok::l_paren) && Left.is(tok::kw_co_await) && Left.Previous && 3106 Left.Previous->is(tok::kw_operator)) 3107 return false; 3108 // co_await (x), co_yield (x), co_return (x) 3109 if (Left.isOneOf(tok::kw_co_await, tok::kw_co_yield, tok::kw_co_return) && 3110 !Right.isOneOf(tok::semi, tok::r_paren)) 3111 return true; 3112 3113 if (Left.is(tok::l_paren) || Right.is(tok::r_paren)) 3114 return (Right.is(TT_CastRParen) || 3115 (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen))) 3116 ? Style.SpacesInCStyleCastParentheses 3117 : Style.SpacesInParentheses; 3118 if (Right.isOneOf(tok::semi, tok::comma)) 3119 return false; 3120 if (Right.is(tok::less) && Line.Type == LT_ObjCDecl) { 3121 bool IsLightweightGeneric = Right.MatchingParen && 3122 Right.MatchingParen->Next && 3123 Right.MatchingParen->Next->is(tok::colon); 3124 return !IsLightweightGeneric && Style.ObjCSpaceBeforeProtocolList; 3125 } 3126 if (Right.is(tok::less) && Left.is(tok::kw_template)) 3127 return Style.SpaceAfterTemplateKeyword; 3128 if (Left.isOneOf(tok::exclaim, tok::tilde)) 3129 return false; 3130 if (Left.is(tok::at) && 3131 Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant, 3132 tok::numeric_constant, tok::l_paren, tok::l_brace, 3133 tok::kw_true, tok::kw_false)) 3134 return false; 3135 if (Left.is(tok::colon)) 3136 return !Left.is(TT_ObjCMethodExpr); 3137 if (Left.is(tok::coloncolon)) 3138 return false; 3139 if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) { 3140 if (Style.Language == FormatStyle::LK_TextProto || 3141 (Style.Language == FormatStyle::LK_Proto && 3142 (Left.is(TT_DictLiteral) || Right.is(TT_DictLiteral)))) { 3143 // Format empty list as `<>`. 3144 if (Left.is(tok::less) && Right.is(tok::greater)) 3145 return false; 3146 return !Style.Cpp11BracedListStyle; 3147 } 3148 return false; 3149 } 3150 if (Right.is(tok::ellipsis)) 3151 return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous && 3152 Left.Previous->is(tok::kw_case)); 3153 if (Left.is(tok::l_square) && Right.is(tok::amp)) 3154 return Style.SpacesInSquareBrackets; 3155 if (Right.is(TT_PointerOrReference)) { 3156 if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) { 3157 if (!Left.MatchingParen) 3158 return true; 3159 FormatToken *TokenBeforeMatchingParen = 3160 Left.MatchingParen->getPreviousNonComment(); 3161 if (!TokenBeforeMatchingParen || !Left.is(TT_TypeDeclarationParen)) 3162 return true; 3163 } 3164 // Add a space if the previous token is a pointer qualifier or the closing 3165 // parenthesis of __attribute__(()) expression and the style requires spaces 3166 // after pointer qualifiers. 3167 if ((Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_After || 3168 Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both) && 3169 (Left.is(TT_AttributeParen) || Left.canBePointerOrReferenceQualifier())) 3170 return true; 3171 if (Left.Tok.isLiteral()) 3172 return true; 3173 // for (auto a = 0, b = 0; const auto & c : {1, 2, 3}) 3174 if (Left.isTypeOrIdentifier() && Right.Next && Right.Next->Next && 3175 Right.Next->Next->is(TT_RangeBasedForLoopColon)) 3176 return getTokenPointerOrReferenceAlignment(Right) != 3177 FormatStyle::PAS_Left; 3178 return !Left.isOneOf(TT_PointerOrReference, tok::l_paren) && 3179 (getTokenPointerOrReferenceAlignment(Right) != 3180 FormatStyle::PAS_Left || 3181 (Line.IsMultiVariableDeclStmt && 3182 (Left.NestingLevel == 0 || 3183 (Left.NestingLevel == 1 && startsWithInitStatement(Line))))); 3184 } 3185 if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) && 3186 (!Left.is(TT_PointerOrReference) || 3187 (getTokenPointerOrReferenceAlignment(Left) != FormatStyle::PAS_Right && 3188 !Line.IsMultiVariableDeclStmt))) 3189 return true; 3190 if (Left.is(TT_PointerOrReference)) { 3191 // Add a space if the next token is a pointer qualifier and the style 3192 // requires spaces before pointer qualifiers. 3193 if ((Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Before || 3194 Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both) && 3195 Right.canBePointerOrReferenceQualifier()) 3196 return true; 3197 // & 1 3198 if (Right.Tok.isLiteral()) 3199 return true; 3200 // & /* comment 3201 if (Right.is(TT_BlockComment)) 3202 return true; 3203 // foo() -> const Bar * override/final 3204 if (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) && 3205 !Right.is(TT_StartOfName)) 3206 return true; 3207 // & { 3208 if (Right.is(tok::l_brace) && Right.is(BK_Block)) 3209 return true; 3210 // for (auto a = 0, b = 0; const auto& c : {1, 2, 3}) 3211 if (Left.Previous && Left.Previous->isTypeOrIdentifier() && Right.Next && 3212 Right.Next->is(TT_RangeBasedForLoopColon)) 3213 return getTokenPointerOrReferenceAlignment(Left) != 3214 FormatStyle::PAS_Right; 3215 if (Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare, 3216 tok::l_paren)) 3217 return false; 3218 if (getTokenPointerOrReferenceAlignment(Left) == FormatStyle::PAS_Right) 3219 return false; 3220 // FIXME: Setting IsMultiVariableDeclStmt for the whole line is error-prone, 3221 // because it does not take into account nested scopes like lambdas. 3222 // In multi-variable declaration statements, attach */& to the variable 3223 // independently of the style. However, avoid doing it if we are in a nested 3224 // scope, e.g. lambda. We still need to special-case statements with 3225 // initializers. 3226 if (Line.IsMultiVariableDeclStmt && 3227 (Left.NestingLevel == Line.First->NestingLevel || 3228 ((Left.NestingLevel == Line.First->NestingLevel + 1) && 3229 startsWithInitStatement(Line)))) 3230 return false; 3231 return Left.Previous && !Left.Previous->isOneOf( 3232 tok::l_paren, tok::coloncolon, tok::l_square); 3233 } 3234 // Ensure right pointer alignment with ellipsis e.g. int *...P 3235 if (Left.is(tok::ellipsis) && Left.Previous && 3236 Left.Previous->isOneOf(tok::star, tok::amp, tok::ampamp)) 3237 return Style.PointerAlignment != FormatStyle::PAS_Right; 3238 3239 if (Right.is(tok::star) && Left.is(tok::l_paren)) 3240 return false; 3241 if (Left.is(tok::star) && Right.isOneOf(tok::star, tok::amp, tok::ampamp)) 3242 return false; 3243 if (Right.isOneOf(tok::star, tok::amp, tok::ampamp)) { 3244 const FormatToken *Previous = &Left; 3245 while (Previous && !Previous->is(tok::kw_operator)) { 3246 if (Previous->is(tok::identifier) || Previous->isSimpleTypeSpecifier()) { 3247 Previous = Previous->getPreviousNonComment(); 3248 continue; 3249 } 3250 if (Previous->is(TT_TemplateCloser) && Previous->MatchingParen) { 3251 Previous = Previous->MatchingParen->getPreviousNonComment(); 3252 continue; 3253 } 3254 if (Previous->is(tok::coloncolon)) { 3255 Previous = Previous->getPreviousNonComment(); 3256 continue; 3257 } 3258 break; 3259 } 3260 // Space between the type and the * in: 3261 // operator void*() 3262 // operator char*() 3263 // operator void const*() 3264 // operator void volatile*() 3265 // operator /*comment*/ const char*() 3266 // operator volatile /*comment*/ char*() 3267 // operator Foo*() 3268 // operator C<T>*() 3269 // operator std::Foo*() 3270 // operator C<T>::D<U>*() 3271 // dependent on PointerAlignment style. 3272 if (Previous) { 3273 if (Previous->endsSequence(tok::kw_operator)) 3274 return Style.PointerAlignment != FormatStyle::PAS_Left; 3275 if (Previous->is(tok::kw_const) || Previous->is(tok::kw_volatile)) 3276 return (Style.PointerAlignment != FormatStyle::PAS_Left) || 3277 (Style.SpaceAroundPointerQualifiers == 3278 FormatStyle::SAPQ_After) || 3279 (Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both); 3280 } 3281 } 3282 const auto SpaceRequiredForArrayInitializerLSquare = 3283 [](const FormatToken &LSquareTok, const FormatStyle &Style) { 3284 return Style.SpacesInContainerLiterals || 3285 ((Style.Language == FormatStyle::LK_Proto || 3286 Style.Language == FormatStyle::LK_TextProto) && 3287 !Style.Cpp11BracedListStyle && 3288 LSquareTok.endsSequence(tok::l_square, tok::colon, 3289 TT_SelectorName)); 3290 }; 3291 if (Left.is(tok::l_square)) 3292 return (Left.is(TT_ArrayInitializerLSquare) && Right.isNot(tok::r_square) && 3293 SpaceRequiredForArrayInitializerLSquare(Left, Style)) || 3294 (Left.isOneOf(TT_ArraySubscriptLSquare, TT_StructuredBindingLSquare, 3295 TT_LambdaLSquare) && 3296 Style.SpacesInSquareBrackets && Right.isNot(tok::r_square)); 3297 if (Right.is(tok::r_square)) 3298 return Right.MatchingParen && 3299 ((Right.MatchingParen->is(TT_ArrayInitializerLSquare) && 3300 SpaceRequiredForArrayInitializerLSquare(*Right.MatchingParen, 3301 Style)) || 3302 (Style.SpacesInSquareBrackets && 3303 Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare, 3304 TT_StructuredBindingLSquare, 3305 TT_LambdaLSquare)) || 3306 Right.MatchingParen->is(TT_AttributeParen)); 3307 if (Right.is(tok::l_square) && 3308 !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare, 3309 TT_DesignatedInitializerLSquare, 3310 TT_StructuredBindingLSquare, TT_AttributeSquare) && 3311 !Left.isOneOf(tok::numeric_constant, TT_DictLiteral) && 3312 !(!Left.is(tok::r_square) && Style.SpaceBeforeSquareBrackets && 3313 Right.is(TT_ArraySubscriptLSquare))) 3314 return false; 3315 if (Left.is(tok::l_brace) && Right.is(tok::r_brace)) 3316 return !Left.Children.empty(); // No spaces in "{}". 3317 if ((Left.is(tok::l_brace) && Left.isNot(BK_Block)) || 3318 (Right.is(tok::r_brace) && Right.MatchingParen && 3319 Right.MatchingParen->isNot(BK_Block))) 3320 return Style.Cpp11BracedListStyle ? Style.SpacesInParentheses : true; 3321 if (Left.is(TT_BlockComment)) 3322 // No whitespace in x(/*foo=*/1), except for JavaScript. 3323 return Style.isJavaScript() || !Left.TokenText.endswith("=*/"); 3324 3325 // Space between template and attribute. 3326 // e.g. template <typename T> [[nodiscard]] ... 3327 if (Left.is(TT_TemplateCloser) && Right.is(TT_AttributeSquare)) 3328 return true; 3329 // Space before parentheses common for all languages 3330 if (Right.is(tok::l_paren)) { 3331 if (Left.is(TT_TemplateCloser) && Right.isNot(TT_FunctionTypeLParen)) 3332 return spaceRequiredBeforeParens(Right); 3333 if (Left.isOneOf(TT_RequiresClause, TT_RequiresClauseInARequiresExpression)) 3334 return Style.SpaceBeforeParensOptions.AfterRequiresInClause || 3335 spaceRequiredBeforeParens(Right); 3336 if (Left.is(TT_RequiresExpression)) 3337 return Style.SpaceBeforeParensOptions.AfterRequiresInExpression || 3338 spaceRequiredBeforeParens(Right); 3339 if ((Left.is(tok::r_paren) && Left.is(TT_AttributeParen)) || 3340 (Left.is(tok::r_square) && Left.is(TT_AttributeSquare))) 3341 return true; 3342 if (Left.is(TT_ForEachMacro)) 3343 return Style.SpaceBeforeParensOptions.AfterForeachMacros || 3344 spaceRequiredBeforeParens(Right); 3345 if (Left.is(TT_IfMacro)) 3346 return Style.SpaceBeforeParensOptions.AfterIfMacros || 3347 spaceRequiredBeforeParens(Right); 3348 if (Line.Type == LT_ObjCDecl) 3349 return true; 3350 if (Left.is(tok::semi)) 3351 return true; 3352 if (Left.isOneOf(tok::pp_elif, tok::kw_for, tok::kw_while, tok::kw_switch, 3353 tok::kw_case, TT_ForEachMacro, TT_ObjCForIn)) 3354 return Style.SpaceBeforeParensOptions.AfterControlStatements || 3355 spaceRequiredBeforeParens(Right); 3356 if (Left.isIf(Line.Type != LT_PreprocessorDirective)) 3357 return Style.SpaceBeforeParensOptions.AfterControlStatements || 3358 spaceRequiredBeforeParens(Right); 3359 3360 // TODO add Operator overloading specific Options to 3361 // SpaceBeforeParensOptions 3362 if (Right.is(TT_OverloadedOperatorLParen)) 3363 return spaceRequiredBeforeParens(Right); 3364 // Function declaration or definition 3365 if (Line.MightBeFunctionDecl && (Left.is(TT_FunctionDeclarationName))) { 3366 if (Line.mightBeFunctionDefinition()) 3367 return Style.SpaceBeforeParensOptions.AfterFunctionDefinitionName || 3368 spaceRequiredBeforeParens(Right); 3369 else 3370 return Style.SpaceBeforeParensOptions.AfterFunctionDeclarationName || 3371 spaceRequiredBeforeParens(Right); 3372 } 3373 // Lambda 3374 if (Line.Type != LT_PreprocessorDirective && Left.is(tok::r_square) && 3375 Left.MatchingParen && Left.MatchingParen->is(TT_LambdaLSquare)) 3376 return Style.SpaceBeforeParensOptions.AfterFunctionDefinitionName || 3377 spaceRequiredBeforeParens(Right); 3378 if (!Left.Previous || Left.Previous->isNot(tok::period)) { 3379 if (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch)) 3380 return Style.SpaceBeforeParensOptions.AfterControlStatements || 3381 spaceRequiredBeforeParens(Right); 3382 if (Left.isOneOf(tok::kw_new, tok::kw_delete)) 3383 return ((!Line.MightBeFunctionDecl || !Left.Previous) && 3384 Style.SpaceBeforeParens != FormatStyle::SBPO_Never) || 3385 spaceRequiredBeforeParens(Right); 3386 3387 if (Left.is(tok::r_square) && Left.MatchingParen && 3388 Left.MatchingParen->Previous && 3389 Left.MatchingParen->Previous->is(tok::kw_delete)) 3390 return (Style.SpaceBeforeParens != FormatStyle::SBPO_Never) || 3391 spaceRequiredBeforeParens(Right); 3392 } 3393 if (Line.Type != LT_PreprocessorDirective && 3394 (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() || 3395 Left.is(tok::r_paren) || Left.isSimpleTypeSpecifier())) 3396 return spaceRequiredBeforeParens(Right); 3397 return false; 3398 } 3399 if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword) 3400 return false; 3401 if (Right.is(TT_UnaryOperator)) 3402 return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) && 3403 (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr)); 3404 if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square, 3405 tok::r_paren) || 3406 Left.isSimpleTypeSpecifier()) && 3407 Right.is(tok::l_brace) && Right.getNextNonComment() && 3408 Right.isNot(BK_Block)) 3409 return false; 3410 if (Left.is(tok::period) || Right.is(tok::period)) 3411 return false; 3412 // u#str, U#str, L#str, u8#str 3413 // uR#str, UR#str, LR#str, u8R#str 3414 if (Right.is(tok::hash) && Left.is(tok::identifier) && 3415 (Left.TokenText == "L" || Left.TokenText == "u" || 3416 Left.TokenText == "U" || Left.TokenText == "u8" || 3417 Left.TokenText == "LR" || Left.TokenText == "uR" || 3418 Left.TokenText == "UR" || Left.TokenText == "u8R")) 3419 return false; 3420 if (Left.is(TT_TemplateCloser) && Left.MatchingParen && 3421 Left.MatchingParen->Previous && 3422 (Left.MatchingParen->Previous->is(tok::period) || 3423 Left.MatchingParen->Previous->is(tok::coloncolon))) 3424 // Java call to generic function with explicit type: 3425 // A.<B<C<...>>>DoSomething(); 3426 // A::<B<C<...>>>DoSomething(); // With a Java 8 method reference. 3427 return false; 3428 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square)) 3429 return false; 3430 if (Left.is(tok::l_brace) && Left.endsSequence(TT_DictLiteral, tok::at)) 3431 // Objective-C dictionary literal -> no space after opening brace. 3432 return false; 3433 if (Right.is(tok::r_brace) && Right.MatchingParen && 3434 Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at)) 3435 // Objective-C dictionary literal -> no space before closing brace. 3436 return false; 3437 if (Right.getType() == TT_TrailingAnnotation && 3438 Right.isOneOf(tok::amp, tok::ampamp) && 3439 Left.isOneOf(tok::kw_const, tok::kw_volatile) && 3440 (!Right.Next || Right.Next->is(tok::semi))) 3441 // Match const and volatile ref-qualifiers without any additional 3442 // qualifiers such as 3443 // void Fn() const &; 3444 return getTokenReferenceAlignment(Right) != FormatStyle::PAS_Left; 3445 3446 return true; 3447 } 3448 3449 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, 3450 const FormatToken &Right) { 3451 const FormatToken &Left = *Right.Previous; 3452 3453 // If the token is finalized don't touch it (as it could be in a 3454 // clang-format-off section). 3455 if (Left.Finalized) 3456 return Right.hasWhitespaceBefore(); 3457 3458 if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo()) 3459 return true; // Never ever merge two identifiers. 3460 3461 // Leave a space between * and /* to avoid C4138 `comment end` found outside 3462 // of comment. 3463 if (Left.is(tok::star) && Right.is(tok::comment)) 3464 return true; 3465 3466 if (Style.isCpp()) { 3467 // Space between import <iostream>. 3468 // or import .....; 3469 if (Left.is(Keywords.kw_import) && Right.isOneOf(tok::less, tok::ellipsis)) 3470 return true; 3471 // Space between `module :` and `import :`. 3472 if (Left.isOneOf(Keywords.kw_module, Keywords.kw_import) && 3473 Right.is(TT_ModulePartitionColon)) 3474 return true; 3475 // No space between import foo:bar but keep a space between import :bar; 3476 if (Left.is(tok::identifier) && Right.is(TT_ModulePartitionColon)) 3477 return false; 3478 // No space between :bar; 3479 if (Left.is(TT_ModulePartitionColon) && 3480 Right.isOneOf(tok::identifier, tok::kw_private)) 3481 return false; 3482 if (Left.is(tok::ellipsis) && Right.is(tok::identifier) && 3483 Line.First->is(Keywords.kw_import)) 3484 return false; 3485 // Space in __attribute__((attr)) ::type. 3486 if (Left.is(TT_AttributeParen) && Right.is(tok::coloncolon)) 3487 return true; 3488 3489 if (Left.is(tok::kw_operator)) 3490 return Right.is(tok::coloncolon); 3491 if (Right.is(tok::l_brace) && Right.is(BK_BracedInit) && 3492 !Left.opensScope() && Style.SpaceBeforeCpp11BracedList) 3493 return true; 3494 if (Left.is(tok::less) && Left.is(TT_OverloadedOperator) && 3495 Right.is(TT_TemplateOpener)) 3496 return true; 3497 } else if (Style.Language == FormatStyle::LK_Proto || 3498 Style.Language == FormatStyle::LK_TextProto) { 3499 if (Right.is(tok::period) && 3500 Left.isOneOf(Keywords.kw_optional, Keywords.kw_required, 3501 Keywords.kw_repeated, Keywords.kw_extend)) 3502 return true; 3503 if (Right.is(tok::l_paren) && 3504 Left.isOneOf(Keywords.kw_returns, Keywords.kw_option)) 3505 return true; 3506 if (Right.isOneOf(tok::l_brace, tok::less) && Left.is(TT_SelectorName)) 3507 return true; 3508 // Slashes occur in text protocol extension syntax: [type/type] { ... }. 3509 if (Left.is(tok::slash) || Right.is(tok::slash)) 3510 return false; 3511 if (Left.MatchingParen && 3512 Left.MatchingParen->is(TT_ProtoExtensionLSquare) && 3513 Right.isOneOf(tok::l_brace, tok::less)) 3514 return !Style.Cpp11BracedListStyle; 3515 // A percent is probably part of a formatting specification, such as %lld. 3516 if (Left.is(tok::percent)) 3517 return false; 3518 // Preserve the existence of a space before a percent for cases like 0x%04x 3519 // and "%d %d" 3520 if (Left.is(tok::numeric_constant) && Right.is(tok::percent)) 3521 return Right.hasWhitespaceBefore(); 3522 } else if (Style.isJson()) { 3523 if (Right.is(tok::colon)) 3524 return false; 3525 } else if (Style.isCSharp()) { 3526 // Require spaces around '{' and before '}' unless they appear in 3527 // interpolated strings. Interpolated strings are merged into a single token 3528 // so cannot have spaces inserted by this function. 3529 3530 // No space between 'this' and '[' 3531 if (Left.is(tok::kw_this) && Right.is(tok::l_square)) 3532 return false; 3533 3534 // No space between 'new' and '(' 3535 if (Left.is(tok::kw_new) && Right.is(tok::l_paren)) 3536 return false; 3537 3538 // Space before { (including space within '{ {'). 3539 if (Right.is(tok::l_brace)) 3540 return true; 3541 3542 // Spaces inside braces. 3543 if (Left.is(tok::l_brace) && Right.isNot(tok::r_brace)) 3544 return true; 3545 3546 if (Left.isNot(tok::l_brace) && Right.is(tok::r_brace)) 3547 return true; 3548 3549 // Spaces around '=>'. 3550 if (Left.is(TT_FatArrow) || Right.is(TT_FatArrow)) 3551 return true; 3552 3553 // No spaces around attribute target colons 3554 if (Left.is(TT_AttributeColon) || Right.is(TT_AttributeColon)) 3555 return false; 3556 3557 // space between type and variable e.g. Dictionary<string,string> foo; 3558 if (Left.is(TT_TemplateCloser) && Right.is(TT_StartOfName)) 3559 return true; 3560 3561 // spaces inside square brackets. 3562 if (Left.is(tok::l_square) || Right.is(tok::r_square)) 3563 return Style.SpacesInSquareBrackets; 3564 3565 // No space before ? in nullable types. 3566 if (Right.is(TT_CSharpNullable)) 3567 return false; 3568 3569 // No space before null forgiving '!'. 3570 if (Right.is(TT_NonNullAssertion)) 3571 return false; 3572 3573 // No space between consecutive commas '[,,]'. 3574 if (Left.is(tok::comma) && Right.is(tok::comma)) 3575 return false; 3576 3577 // space after var in `var (key, value)` 3578 if (Left.is(Keywords.kw_var) && Right.is(tok::l_paren)) 3579 return true; 3580 3581 // space between keywords and paren e.g. "using (" 3582 if (Right.is(tok::l_paren)) 3583 if (Left.isOneOf(tok::kw_using, Keywords.kw_async, Keywords.kw_when, 3584 Keywords.kw_lock)) 3585 return Style.SpaceBeforeParensOptions.AfterControlStatements || 3586 spaceRequiredBeforeParens(Right); 3587 3588 // space between method modifier and opening parenthesis of a tuple return 3589 // type 3590 if (Left.isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected, 3591 tok::kw_virtual, tok::kw_extern, tok::kw_static, 3592 Keywords.kw_internal, Keywords.kw_abstract, 3593 Keywords.kw_sealed, Keywords.kw_override, 3594 Keywords.kw_async, Keywords.kw_unsafe) && 3595 Right.is(tok::l_paren)) 3596 return true; 3597 } else if (Style.isJavaScript()) { 3598 if (Left.is(TT_FatArrow)) 3599 return true; 3600 // for await ( ... 3601 if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && Left.Previous && 3602 Left.Previous->is(tok::kw_for)) 3603 return true; 3604 if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) && 3605 Right.MatchingParen) { 3606 const FormatToken *Next = Right.MatchingParen->getNextNonComment(); 3607 // An async arrow function, for example: `x = async () => foo();`, 3608 // as opposed to calling a function called async: `x = async();` 3609 if (Next && Next->is(TT_FatArrow)) 3610 return true; 3611 } 3612 if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) || 3613 (Right.is(TT_TemplateString) && Right.TokenText.startswith("}"))) 3614 return false; 3615 // In tagged template literals ("html`bar baz`"), there is no space between 3616 // the tag identifier and the template string. 3617 if (Keywords.IsJavaScriptIdentifier(Left, 3618 /* AcceptIdentifierName= */ false) && 3619 Right.is(TT_TemplateString)) 3620 return false; 3621 if (Right.is(tok::star) && 3622 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield)) 3623 return false; 3624 if (Right.isOneOf(tok::l_brace, tok::l_square) && 3625 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield, 3626 Keywords.kw_extends, Keywords.kw_implements)) 3627 return true; 3628 if (Right.is(tok::l_paren)) { 3629 // JS methods can use some keywords as names (e.g. `delete()`). 3630 if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo()) 3631 return false; 3632 // Valid JS method names can include keywords, e.g. `foo.delete()` or 3633 // `bar.instanceof()`. Recognize call positions by preceding period. 3634 if (Left.Previous && Left.Previous->is(tok::period) && 3635 Left.Tok.getIdentifierInfo()) 3636 return false; 3637 // Additional unary JavaScript operators that need a space after. 3638 if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof, 3639 tok::kw_void)) 3640 return true; 3641 } 3642 // `foo as const;` casts into a const type. 3643 if (Left.endsSequence(tok::kw_const, Keywords.kw_as)) 3644 return false; 3645 if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in, 3646 tok::kw_const) || 3647 // "of" is only a keyword if it appears after another identifier 3648 // (e.g. as "const x of y" in a for loop), or after a destructuring 3649 // operation (const [x, y] of z, const {a, b} of c). 3650 (Left.is(Keywords.kw_of) && Left.Previous && 3651 (Left.Previous->is(tok::identifier) || 3652 Left.Previous->isOneOf(tok::r_square, tok::r_brace)))) && 3653 (!Left.Previous || !Left.Previous->is(tok::period))) 3654 return true; 3655 if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && Left.Previous && 3656 Left.Previous->is(tok::period) && Right.is(tok::l_paren)) 3657 return false; 3658 if (Left.is(Keywords.kw_as) && 3659 Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren)) 3660 return true; 3661 if (Left.is(tok::kw_default) && Left.Previous && 3662 Left.Previous->is(tok::kw_export)) 3663 return true; 3664 if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace)) 3665 return true; 3666 if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion)) 3667 return false; 3668 if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator)) 3669 return false; 3670 if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) && 3671 Line.First->isOneOf(Keywords.kw_import, tok::kw_export)) 3672 return false; 3673 if (Left.is(tok::ellipsis)) 3674 return false; 3675 if (Left.is(TT_TemplateCloser) && 3676 !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square, 3677 Keywords.kw_implements, Keywords.kw_extends)) 3678 // Type assertions ('<type>expr') are not followed by whitespace. Other 3679 // locations that should have whitespace following are identified by the 3680 // above set of follower tokens. 3681 return false; 3682 if (Right.is(TT_NonNullAssertion)) 3683 return false; 3684 if (Left.is(TT_NonNullAssertion) && 3685 Right.isOneOf(Keywords.kw_as, Keywords.kw_in)) 3686 return true; // "x! as string", "x! in y" 3687 } else if (Style.Language == FormatStyle::LK_Java) { 3688 if (Left.is(tok::r_square) && Right.is(tok::l_brace)) 3689 return true; 3690 if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren)) 3691 return Style.SpaceBeforeParensOptions.AfterControlStatements || 3692 spaceRequiredBeforeParens(Right); 3693 if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private, 3694 tok::kw_protected) || 3695 Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract, 3696 Keywords.kw_native)) && 3697 Right.is(TT_TemplateOpener)) 3698 return true; 3699 } 3700 if (Left.is(TT_ImplicitStringLiteral)) 3701 return Right.hasWhitespaceBefore(); 3702 if (Line.Type == LT_ObjCMethodDecl) { 3703 if (Left.is(TT_ObjCMethodSpecifier)) 3704 return true; 3705 if (Left.is(tok::r_paren) && canBeObjCSelectorComponent(Right)) 3706 // Don't space between ')' and <id> or ')' and 'new'. 'new' is not a 3707 // keyword in Objective-C, and '+ (instancetype)new;' is a standard class 3708 // method declaration. 3709 return false; 3710 } 3711 if (Line.Type == LT_ObjCProperty && 3712 (Right.is(tok::equal) || Left.is(tok::equal))) 3713 return false; 3714 3715 if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) || 3716 Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow)) 3717 return true; 3718 if (Left.is(tok::comma) && !Right.is(TT_OverloadedOperatorLParen)) 3719 return true; 3720 if (Right.is(tok::comma)) 3721 return false; 3722 if (Right.is(TT_ObjCBlockLParen)) 3723 return true; 3724 if (Right.is(TT_CtorInitializerColon)) 3725 return Style.SpaceBeforeCtorInitializerColon; 3726 if (Right.is(TT_InheritanceColon) && !Style.SpaceBeforeInheritanceColon) 3727 return false; 3728 if (Right.is(TT_RangeBasedForLoopColon) && 3729 !Style.SpaceBeforeRangeBasedForLoopColon) 3730 return false; 3731 if (Left.is(TT_BitFieldColon)) 3732 return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both || 3733 Style.BitFieldColonSpacing == FormatStyle::BFCS_After; 3734 if (Right.is(tok::colon)) { 3735 if (Line.First->isOneOf(tok::kw_default, tok::kw_case)) 3736 return Style.SpaceBeforeCaseColon; 3737 const FormatToken *Next = Right.getNextNonComment(); 3738 if (!Next || Next->is(tok::semi)) 3739 return false; 3740 if (Right.is(TT_ObjCMethodExpr)) 3741 return false; 3742 if (Left.is(tok::question)) 3743 return false; 3744 if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon)) 3745 return false; 3746 if (Right.is(TT_DictLiteral)) 3747 return Style.SpacesInContainerLiterals; 3748 if (Right.is(TT_AttributeColon)) 3749 return false; 3750 if (Right.is(TT_CSharpNamedArgumentColon)) 3751 return false; 3752 if (Right.is(TT_BitFieldColon)) 3753 return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both || 3754 Style.BitFieldColonSpacing == FormatStyle::BFCS_Before; 3755 return true; 3756 } 3757 // Do not merge "- -" into "--". 3758 if ((Left.isOneOf(tok::minus, tok::minusminus) && 3759 Right.isOneOf(tok::minus, tok::minusminus)) || 3760 (Left.isOneOf(tok::plus, tok::plusplus) && 3761 Right.isOneOf(tok::plus, tok::plusplus))) 3762 return true; 3763 if (Left.is(TT_UnaryOperator)) { 3764 if (!Right.is(tok::l_paren)) { 3765 // The alternative operators for ~ and ! are "compl" and "not". 3766 // If they are used instead, we do not want to combine them with 3767 // the token to the right, unless that is a left paren. 3768 if (Left.is(tok::exclaim) && Left.TokenText == "not") 3769 return true; 3770 if (Left.is(tok::tilde) && Left.TokenText == "compl") 3771 return true; 3772 // Lambda captures allow for a lone &, so "&]" needs to be properly 3773 // handled. 3774 if (Left.is(tok::amp) && Right.is(tok::r_square)) 3775 return Style.SpacesInSquareBrackets; 3776 } 3777 return (Style.SpaceAfterLogicalNot && Left.is(tok::exclaim)) || 3778 Right.is(TT_BinaryOperator); 3779 } 3780 3781 // If the next token is a binary operator or a selector name, we have 3782 // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly. 3783 if (Left.is(TT_CastRParen)) 3784 return Style.SpaceAfterCStyleCast || 3785 Right.isOneOf(TT_BinaryOperator, TT_SelectorName); 3786 3787 auto ShouldAddSpacesInAngles = [this, &Right]() { 3788 if (this->Style.SpacesInAngles == FormatStyle::SIAS_Always) 3789 return true; 3790 if (this->Style.SpacesInAngles == FormatStyle::SIAS_Leave) 3791 return Right.hasWhitespaceBefore(); 3792 return false; 3793 }; 3794 3795 if (Left.is(tok::greater) && Right.is(tok::greater)) { 3796 if (Style.Language == FormatStyle::LK_TextProto || 3797 (Style.Language == FormatStyle::LK_Proto && Left.is(TT_DictLiteral))) 3798 return !Style.Cpp11BracedListStyle; 3799 return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) && 3800 ((Style.Standard < FormatStyle::LS_Cpp11) || 3801 ShouldAddSpacesInAngles()); 3802 } 3803 if (Right.isOneOf(tok::arrow, tok::arrowstar, tok::periodstar) || 3804 Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) || 3805 (Right.is(tok::period) && Right.isNot(TT_DesignatedInitializerPeriod))) 3806 return false; 3807 if (!Style.SpaceBeforeAssignmentOperators && Left.isNot(TT_TemplateCloser) && 3808 Right.getPrecedence() == prec::Assignment) 3809 return false; 3810 if (Style.Language == FormatStyle::LK_Java && Right.is(tok::coloncolon) && 3811 (Left.is(tok::identifier) || Left.is(tok::kw_this))) 3812 return false; 3813 if (Right.is(tok::coloncolon) && Left.is(tok::identifier)) 3814 // Generally don't remove existing spaces between an identifier and "::". 3815 // The identifier might actually be a macro name such as ALWAYS_INLINE. If 3816 // this turns out to be too lenient, add analysis of the identifier itself. 3817 return Right.hasWhitespaceBefore(); 3818 if (Right.is(tok::coloncolon) && 3819 !Left.isOneOf(tok::l_brace, tok::comment, tok::l_paren)) 3820 // Put a space between < and :: in vector< ::std::string > 3821 return (Left.is(TT_TemplateOpener) && 3822 ((Style.Standard < FormatStyle::LS_Cpp11) || 3823 ShouldAddSpacesInAngles())) || 3824 !(Left.isOneOf(tok::l_paren, tok::r_paren, tok::l_square, 3825 tok::kw___super, TT_TemplateOpener, 3826 TT_TemplateCloser)) || 3827 (Left.is(tok::l_paren) && Style.SpacesInParentheses); 3828 if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser))) 3829 return ShouldAddSpacesInAngles(); 3830 // Space before TT_StructuredBindingLSquare. 3831 if (Right.is(TT_StructuredBindingLSquare)) 3832 return !Left.isOneOf(tok::amp, tok::ampamp) || 3833 getTokenReferenceAlignment(Left) != FormatStyle::PAS_Right; 3834 // Space before & or && following a TT_StructuredBindingLSquare. 3835 if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) && 3836 Right.isOneOf(tok::amp, tok::ampamp)) 3837 return getTokenReferenceAlignment(Right) != FormatStyle::PAS_Left; 3838 if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) || 3839 (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && 3840 !Right.is(tok::r_paren))) 3841 return true; 3842 if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) && 3843 Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen)) 3844 return false; 3845 if (Right.is(tok::less) && Left.isNot(tok::l_paren) && 3846 Line.startsWith(tok::hash)) 3847 return true; 3848 if (Right.is(TT_TrailingUnaryOperator)) 3849 return false; 3850 if (Left.is(TT_RegexLiteral)) 3851 return false; 3852 return spaceRequiredBetween(Line, Left, Right); 3853 } 3854 3855 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style. 3856 static bool isAllmanBrace(const FormatToken &Tok) { 3857 return Tok.is(tok::l_brace) && Tok.is(BK_Block) && 3858 !Tok.isOneOf(TT_ObjCBlockLBrace, TT_LambdaLBrace, TT_DictLiteral); 3859 } 3860 3861 // Returns 'true' if 'Tok' is a function argument. 3862 static bool IsFunctionArgument(const FormatToken &Tok) { 3863 return Tok.MatchingParen && Tok.MatchingParen->Next && 3864 Tok.MatchingParen->Next->isOneOf(tok::comma, tok::r_paren); 3865 } 3866 3867 static bool 3868 isItAnEmptyLambdaAllowed(const FormatToken &Tok, 3869 FormatStyle::ShortLambdaStyle ShortLambdaOption) { 3870 return Tok.Children.empty() && ShortLambdaOption != FormatStyle::SLS_None; 3871 } 3872 3873 static bool isAllmanLambdaBrace(const FormatToken &Tok) { 3874 return Tok.is(tok::l_brace) && Tok.is(BK_Block) && 3875 !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral); 3876 } 3877 3878 // Returns the first token on the line that is not a comment. 3879 static const FormatToken *getFirstNonComment(const AnnotatedLine &Line) { 3880 const FormatToken *Next = Line.First; 3881 if (!Next) 3882 return Next; 3883 if (Next->is(tok::comment)) 3884 Next = Next->getNextNonComment(); 3885 return Next; 3886 } 3887 3888 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line, 3889 const FormatToken &Right) { 3890 const FormatToken &Left = *Right.Previous; 3891 if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0) 3892 return true; 3893 3894 if (Style.isCSharp()) { 3895 if (Left.is(TT_FatArrow) && Right.is(tok::l_brace) && 3896 Style.BraceWrapping.AfterFunction) 3897 return true; 3898 if (Right.is(TT_CSharpNamedArgumentColon) || 3899 Left.is(TT_CSharpNamedArgumentColon)) 3900 return false; 3901 if (Right.is(TT_CSharpGenericTypeConstraint)) 3902 return true; 3903 if (Right.Next && Right.Next->is(TT_FatArrow) && 3904 (Right.is(tok::numeric_constant) || 3905 (Right.is(tok::identifier) && Right.TokenText == "_"))) 3906 return true; 3907 3908 // Break after C# [...] and before public/protected/private/internal. 3909 if (Left.is(TT_AttributeSquare) && Left.is(tok::r_square) && 3910 (Right.isAccessSpecifier(/*ColonRequired=*/false) || 3911 Right.is(Keywords.kw_internal))) 3912 return true; 3913 // Break between ] and [ but only when there are really 2 attributes. 3914 if (Left.is(TT_AttributeSquare) && Right.is(TT_AttributeSquare) && 3915 Left.is(tok::r_square) && Right.is(tok::l_square)) 3916 return true; 3917 3918 } else if (Style.isJavaScript()) { 3919 // FIXME: This might apply to other languages and token kinds. 3920 if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous && 3921 Left.Previous->is(tok::string_literal)) 3922 return true; 3923 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 && 3924 Left.Previous && Left.Previous->is(tok::equal) && 3925 Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export, 3926 tok::kw_const) && 3927 // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match 3928 // above. 3929 !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let)) 3930 // Object literals on the top level of a file are treated as "enum-style". 3931 // Each key/value pair is put on a separate line, instead of bin-packing. 3932 return true; 3933 if (Left.is(tok::l_brace) && Line.Level == 0 && 3934 (Line.startsWith(tok::kw_enum) || 3935 Line.startsWith(tok::kw_const, tok::kw_enum) || 3936 Line.startsWith(tok::kw_export, tok::kw_enum) || 3937 Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum))) 3938 // JavaScript top-level enum key/value pairs are put on separate lines 3939 // instead of bin-packing. 3940 return true; 3941 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) && Left.Previous && 3942 Left.Previous->is(TT_FatArrow)) { 3943 // JS arrow function (=> {...}). 3944 switch (Style.AllowShortLambdasOnASingleLine) { 3945 case FormatStyle::SLS_All: 3946 return false; 3947 case FormatStyle::SLS_None: 3948 return true; 3949 case FormatStyle::SLS_Empty: 3950 return !Left.Children.empty(); 3951 case FormatStyle::SLS_Inline: 3952 // allow one-lining inline (e.g. in function call args) and empty arrow 3953 // functions. 3954 return (Left.NestingLevel == 0 && Line.Level == 0) && 3955 !Left.Children.empty(); 3956 } 3957 llvm_unreachable("Unknown FormatStyle::ShortLambdaStyle enum"); 3958 } 3959 3960 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) && 3961 !Left.Children.empty()) 3962 // Support AllowShortFunctionsOnASingleLine for JavaScript. 3963 return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None || 3964 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty || 3965 (Left.NestingLevel == 0 && Line.Level == 0 && 3966 Style.AllowShortFunctionsOnASingleLine & 3967 FormatStyle::SFS_InlineOnly); 3968 } else if (Style.Language == FormatStyle::LK_Java) { 3969 if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next && 3970 Right.Next->is(tok::string_literal)) 3971 return true; 3972 } else if (Style.Language == FormatStyle::LK_Cpp || 3973 Style.Language == FormatStyle::LK_ObjC || 3974 Style.Language == FormatStyle::LK_Proto || 3975 Style.Language == FormatStyle::LK_TableGen || 3976 Style.Language == FormatStyle::LK_TextProto) { 3977 if (Left.isStringLiteral() && Right.isStringLiteral()) 3978 return true; 3979 } 3980 3981 // Basic JSON newline processing. 3982 if (Style.isJson()) { 3983 // Always break after a JSON record opener. 3984 // { 3985 // } 3986 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace)) 3987 return true; 3988 // Always break after a JSON array opener. 3989 // [ 3990 // ] 3991 if (Left.is(TT_ArrayInitializerLSquare) && Left.is(tok::l_square) && 3992 !Right.is(tok::r_square)) 3993 return true; 3994 // Always break after successive entries. 3995 // 1, 3996 // 2 3997 if (Left.is(tok::comma)) 3998 return true; 3999 } 4000 4001 // If the last token before a '}', ']', or ')' is a comma or a trailing 4002 // comment, the intention is to insert a line break after it in order to make 4003 // shuffling around entries easier. Import statements, especially in 4004 // JavaScript, can be an exception to this rule. 4005 if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) { 4006 const FormatToken *BeforeClosingBrace = nullptr; 4007 if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) || 4008 (Style.isJavaScript() && Left.is(tok::l_paren))) && 4009 Left.isNot(BK_Block) && Left.MatchingParen) 4010 BeforeClosingBrace = Left.MatchingParen->Previous; 4011 else if (Right.MatchingParen && 4012 (Right.MatchingParen->isOneOf(tok::l_brace, 4013 TT_ArrayInitializerLSquare) || 4014 (Style.isJavaScript() && Right.MatchingParen->is(tok::l_paren)))) 4015 BeforeClosingBrace = &Left; 4016 if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) || 4017 BeforeClosingBrace->isTrailingComment())) 4018 return true; 4019 } 4020 4021 if (Right.is(tok::comment)) 4022 return Left.isNot(BK_BracedInit) && Left.isNot(TT_CtorInitializerColon) && 4023 (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline); 4024 if (Left.isTrailingComment()) 4025 return true; 4026 if (Left.IsUnterminatedLiteral) 4027 return true; 4028 if (Right.is(tok::lessless) && Right.Next && Left.is(tok::string_literal) && 4029 Right.Next->is(tok::string_literal)) 4030 return true; 4031 if (Right.is(TT_RequiresClause)) { 4032 switch (Style.RequiresClausePosition) { 4033 case FormatStyle::RCPS_OwnLine: 4034 case FormatStyle::RCPS_WithFollowing: 4035 return true; 4036 default: 4037 break; 4038 } 4039 } 4040 // Can break after template<> declaration 4041 if (Left.ClosesTemplateDeclaration && Left.MatchingParen && 4042 Left.MatchingParen->NestingLevel == 0) { 4043 // Put concepts on the next line e.g. 4044 // template<typename T> 4045 // concept ... 4046 if (Right.is(tok::kw_concept)) 4047 return Style.BreakBeforeConceptDeclarations == FormatStyle::BBCDS_Always; 4048 return Style.AlwaysBreakTemplateDeclarations == FormatStyle::BTDS_Yes; 4049 } 4050 if (Left.ClosesRequiresClause && Right.isNot(tok::semi)) { 4051 switch (Style.RequiresClausePosition) { 4052 case FormatStyle::RCPS_OwnLine: 4053 case FormatStyle::RCPS_WithPreceding: 4054 return true; 4055 default: 4056 break; 4057 } 4058 } 4059 if (Style.PackConstructorInitializers == FormatStyle::PCIS_Never) { 4060 if (Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon && 4061 (Left.is(TT_CtorInitializerComma) || Right.is(TT_CtorInitializerColon))) 4062 return true; 4063 4064 if (Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon && 4065 Left.isOneOf(TT_CtorInitializerColon, TT_CtorInitializerComma)) 4066 return true; 4067 } 4068 if (Style.PackConstructorInitializers < FormatStyle::PCIS_CurrentLine && 4069 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma && 4070 Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) 4071 return true; 4072 // Break only if we have multiple inheritance. 4073 if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma && 4074 Right.is(TT_InheritanceComma)) 4075 return true; 4076 if (Style.BreakInheritanceList == FormatStyle::BILS_AfterComma && 4077 Left.is(TT_InheritanceComma)) 4078 return true; 4079 if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\"")) 4080 // Multiline raw string literals are special wrt. line breaks. The author 4081 // has made a deliberate choice and might have aligned the contents of the 4082 // string literal accordingly. Thus, we try keep existing line breaks. 4083 return Right.IsMultiline && Right.NewlinesBefore > 0; 4084 if ((Left.is(tok::l_brace) || (Left.is(tok::less) && Left.Previous && 4085 Left.Previous->is(tok::equal))) && 4086 Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) { 4087 // Don't put enums or option definitions onto single lines in protocol 4088 // buffers. 4089 return true; 4090 } 4091 if (Right.is(TT_InlineASMBrace)) 4092 return Right.HasUnescapedNewline; 4093 4094 if (isAllmanBrace(Left) || isAllmanBrace(Right)) { 4095 auto FirstNonComment = getFirstNonComment(Line); 4096 bool AccessSpecifier = 4097 FirstNonComment && 4098 FirstNonComment->isOneOf(Keywords.kw_internal, tok::kw_public, 4099 tok::kw_private, tok::kw_protected); 4100 4101 if (Style.BraceWrapping.AfterEnum) { 4102 if (Line.startsWith(tok::kw_enum) || 4103 Line.startsWith(tok::kw_typedef, tok::kw_enum)) 4104 return true; 4105 // Ensure BraceWrapping for `public enum A {`. 4106 if (AccessSpecifier && FirstNonComment->Next && 4107 FirstNonComment->Next->is(tok::kw_enum)) 4108 return true; 4109 } 4110 4111 // Ensure BraceWrapping for `public interface A {`. 4112 if (Style.BraceWrapping.AfterClass && 4113 ((AccessSpecifier && FirstNonComment->Next && 4114 FirstNonComment->Next->is(Keywords.kw_interface)) || 4115 Line.startsWith(Keywords.kw_interface))) 4116 return true; 4117 4118 return (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) || 4119 (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct); 4120 } 4121 4122 if (Left.is(TT_ObjCBlockLBrace) && 4123 Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) 4124 return true; 4125 4126 // Ensure wrapping after __attribute__((XX)) and @interface etc. 4127 if (Left.is(TT_AttributeParen) && Right.is(TT_ObjCDecl)) 4128 return true; 4129 4130 if (Left.is(TT_LambdaLBrace)) { 4131 if (IsFunctionArgument(Left) && 4132 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline) 4133 return false; 4134 4135 if (Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_None || 4136 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline || 4137 (!Left.Children.empty() && 4138 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Empty)) 4139 return true; 4140 } 4141 4142 if (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT_LambdaLBrace) && 4143 Left.isOneOf(tok::star, tok::amp, tok::ampamp, TT_TemplateCloser)) 4144 return true; 4145 4146 // Put multiple Java annotation on a new line. 4147 if ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) && 4148 Left.is(TT_LeadingJavaAnnotation) && 4149 Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) && 4150 (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations)) 4151 return true; 4152 4153 if (Right.is(TT_ProtoExtensionLSquare)) 4154 return true; 4155 4156 // In text proto instances if a submessage contains at least 2 entries and at 4157 // least one of them is a submessage, like A { ... B { ... } ... }, 4158 // put all of the entries of A on separate lines by forcing the selector of 4159 // the submessage B to be put on a newline. 4160 // 4161 // Example: these can stay on one line: 4162 // a { scalar_1: 1 scalar_2: 2 } 4163 // a { b { key: value } } 4164 // 4165 // and these entries need to be on a new line even if putting them all in one 4166 // line is under the column limit: 4167 // a { 4168 // scalar: 1 4169 // b { key: value } 4170 // } 4171 // 4172 // We enforce this by breaking before a submessage field that has previous 4173 // siblings, *and* breaking before a field that follows a submessage field. 4174 // 4175 // Be careful to exclude the case [proto.ext] { ... } since the `]` is 4176 // the TT_SelectorName there, but we don't want to break inside the brackets. 4177 // 4178 // Another edge case is @submessage { key: value }, which is a common 4179 // substitution placeholder. In this case we want to keep `@` and `submessage` 4180 // together. 4181 // 4182 // We ensure elsewhere that extensions are always on their own line. 4183 if ((Style.Language == FormatStyle::LK_Proto || 4184 Style.Language == FormatStyle::LK_TextProto) && 4185 Right.is(TT_SelectorName) && !Right.is(tok::r_square) && Right.Next) { 4186 // Keep `@submessage` together in: 4187 // @submessage { key: value } 4188 if (Left.is(tok::at)) 4189 return false; 4190 // Look for the scope opener after selector in cases like: 4191 // selector { ... 4192 // selector: { ... 4193 // selector: @base { ... 4194 FormatToken *LBrace = Right.Next; 4195 if (LBrace && LBrace->is(tok::colon)) { 4196 LBrace = LBrace->Next; 4197 if (LBrace && LBrace->is(tok::at)) { 4198 LBrace = LBrace->Next; 4199 if (LBrace) 4200 LBrace = LBrace->Next; 4201 } 4202 } 4203 if (LBrace && 4204 // The scope opener is one of {, [, <: 4205 // selector { ... } 4206 // selector [ ... ] 4207 // selector < ... > 4208 // 4209 // In case of selector { ... }, the l_brace is TT_DictLiteral. 4210 // In case of an empty selector {}, the l_brace is not TT_DictLiteral, 4211 // so we check for immediately following r_brace. 4212 ((LBrace->is(tok::l_brace) && 4213 (LBrace->is(TT_DictLiteral) || 4214 (LBrace->Next && LBrace->Next->is(tok::r_brace)))) || 4215 LBrace->is(TT_ArrayInitializerLSquare) || LBrace->is(tok::less))) { 4216 // If Left.ParameterCount is 0, then this submessage entry is not the 4217 // first in its parent submessage, and we want to break before this entry. 4218 // If Left.ParameterCount is greater than 0, then its parent submessage 4219 // might contain 1 or more entries and we want to break before this entry 4220 // if it contains at least 2 entries. We deal with this case later by 4221 // detecting and breaking before the next entry in the parent submessage. 4222 if (Left.ParameterCount == 0) 4223 return true; 4224 // However, if this submessage is the first entry in its parent 4225 // submessage, Left.ParameterCount might be 1 in some cases. 4226 // We deal with this case later by detecting an entry 4227 // following a closing paren of this submessage. 4228 } 4229 4230 // If this is an entry immediately following a submessage, it will be 4231 // preceded by a closing paren of that submessage, like in: 4232 // left---. .---right 4233 // v v 4234 // sub: { ... } key: value 4235 // If there was a comment between `}` an `key` above, then `key` would be 4236 // put on a new line anyways. 4237 if (Left.isOneOf(tok::r_brace, tok::greater, tok::r_square)) 4238 return true; 4239 } 4240 4241 // Deal with lambda arguments in C++ - we want consistent line breaks whether 4242 // they happen to be at arg0, arg1 or argN. The selection is a bit nuanced 4243 // as aggressive line breaks are placed when the lambda is not the last arg. 4244 if ((Style.Language == FormatStyle::LK_Cpp || 4245 Style.Language == FormatStyle::LK_ObjC) && 4246 Left.is(tok::l_paren) && Left.BlockParameterCount > 0 && 4247 !Right.isOneOf(tok::l_paren, TT_LambdaLSquare)) { 4248 // Multiple lambdas in the same function call force line breaks. 4249 if (Left.BlockParameterCount > 1) 4250 return true; 4251 4252 // A lambda followed by another arg forces a line break. 4253 if (!Left.Role) 4254 return false; 4255 auto Comma = Left.Role->lastComma(); 4256 if (!Comma) 4257 return false; 4258 auto Next = Comma->getNextNonComment(); 4259 if (!Next) 4260 return false; 4261 if (!Next->isOneOf(TT_LambdaLSquare, tok::l_brace, tok::caret)) 4262 return true; 4263 } 4264 4265 return false; 4266 } 4267 4268 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line, 4269 const FormatToken &Right) { 4270 const FormatToken &Left = *Right.Previous; 4271 // Language-specific stuff. 4272 if (Style.isCSharp()) { 4273 if (Left.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon) || 4274 Right.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon)) 4275 return false; 4276 // Only break after commas for generic type constraints. 4277 if (Line.First->is(TT_CSharpGenericTypeConstraint)) 4278 return Left.is(TT_CSharpGenericTypeConstraintComma); 4279 // Keep nullable operators attached to their identifiers. 4280 if (Right.is(TT_CSharpNullable)) 4281 return false; 4282 } else if (Style.Language == FormatStyle::LK_Java) { 4283 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends, 4284 Keywords.kw_implements)) 4285 return false; 4286 if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends, 4287 Keywords.kw_implements)) 4288 return true; 4289 } else if (Style.isJavaScript()) { 4290 const FormatToken *NonComment = Right.getPreviousNonComment(); 4291 if (NonComment && 4292 NonComment->isOneOf( 4293 tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break, 4294 tok::kw_throw, Keywords.kw_interface, Keywords.kw_type, 4295 tok::kw_static, tok::kw_public, tok::kw_private, tok::kw_protected, 4296 Keywords.kw_readonly, Keywords.kw_override, Keywords.kw_abstract, 4297 Keywords.kw_get, Keywords.kw_set, Keywords.kw_async, 4298 Keywords.kw_await)) 4299 return false; // Otherwise automatic semicolon insertion would trigger. 4300 if (Right.NestingLevel == 0 && 4301 (Left.Tok.getIdentifierInfo() || 4302 Left.isOneOf(tok::r_square, tok::r_paren)) && 4303 Right.isOneOf(tok::l_square, tok::l_paren)) 4304 return false; // Otherwise automatic semicolon insertion would trigger. 4305 if (NonComment && NonComment->is(tok::identifier) && 4306 NonComment->TokenText == "asserts") 4307 return false; 4308 if (Left.is(TT_FatArrow) && Right.is(tok::l_brace)) 4309 return false; 4310 if (Left.is(TT_JsTypeColon)) 4311 return true; 4312 // Don't wrap between ":" and "!" of a strict prop init ("field!: type;"). 4313 if (Left.is(tok::exclaim) && Right.is(tok::colon)) 4314 return false; 4315 // Look for is type annotations like: 4316 // function f(): a is B { ... } 4317 // Do not break before is in these cases. 4318 if (Right.is(Keywords.kw_is)) { 4319 const FormatToken *Next = Right.getNextNonComment(); 4320 // If `is` is followed by a colon, it's likely that it's a dict key, so 4321 // ignore it for this check. 4322 // For example this is common in Polymer: 4323 // Polymer({ 4324 // is: 'name', 4325 // ... 4326 // }); 4327 if (!Next || !Next->is(tok::colon)) 4328 return false; 4329 } 4330 if (Left.is(Keywords.kw_in)) 4331 return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None; 4332 if (Right.is(Keywords.kw_in)) 4333 return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None; 4334 if (Right.is(Keywords.kw_as)) 4335 return false; // must not break before as in 'x as type' casts 4336 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_infer)) { 4337 // extends and infer can appear as keywords in conditional types: 4338 // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types 4339 // do not break before them, as the expressions are subject to ASI. 4340 return false; 4341 } 4342 if (Left.is(Keywords.kw_as)) 4343 return true; 4344 if (Left.is(TT_NonNullAssertion)) 4345 return true; 4346 if (Left.is(Keywords.kw_declare) && 4347 Right.isOneOf(Keywords.kw_module, tok::kw_namespace, 4348 Keywords.kw_function, tok::kw_class, tok::kw_enum, 4349 Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var, 4350 Keywords.kw_let, tok::kw_const)) 4351 // See grammar for 'declare' statements at: 4352 // https://github.com/Microsoft/TypeScript/blob/main/doc/spec-ARCHIVED.md#A.10 4353 return false; 4354 if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) && 4355 Right.isOneOf(tok::identifier, tok::string_literal)) 4356 return false; // must not break in "module foo { ...}" 4357 if (Right.is(TT_TemplateString) && Right.closesScope()) 4358 return false; 4359 // Don't split tagged template literal so there is a break between the tag 4360 // identifier and template string. 4361 if (Left.is(tok::identifier) && Right.is(TT_TemplateString)) 4362 return false; 4363 if (Left.is(TT_TemplateString) && Left.opensScope()) 4364 return true; 4365 } 4366 4367 if (Left.is(tok::at)) 4368 return false; 4369 if (Left.Tok.getObjCKeywordID() == tok::objc_interface) 4370 return false; 4371 if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation)) 4372 return !Right.is(tok::l_paren); 4373 if (Right.is(TT_PointerOrReference)) 4374 return Line.IsMultiVariableDeclStmt || 4375 (getTokenPointerOrReferenceAlignment(Right) == 4376 FormatStyle::PAS_Right && 4377 (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName))); 4378 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) || 4379 Right.is(tok::kw_operator)) 4380 return true; 4381 if (Left.is(TT_PointerOrReference)) 4382 return false; 4383 if (Right.isTrailingComment()) 4384 // We rely on MustBreakBefore being set correctly here as we should not 4385 // change the "binding" behavior of a comment. 4386 // The first comment in a braced lists is always interpreted as belonging to 4387 // the first list element. Otherwise, it should be placed outside of the 4388 // list. 4389 return Left.is(BK_BracedInit) || 4390 (Left.is(TT_CtorInitializerColon) && 4391 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon); 4392 if (Left.is(tok::question) && Right.is(tok::colon)) 4393 return false; 4394 if (Right.is(TT_ConditionalExpr) || Right.is(tok::question)) 4395 return Style.BreakBeforeTernaryOperators; 4396 if (Left.is(TT_ConditionalExpr) || Left.is(tok::question)) 4397 return !Style.BreakBeforeTernaryOperators; 4398 if (Left.is(TT_InheritanceColon)) 4399 return Style.BreakInheritanceList == FormatStyle::BILS_AfterColon; 4400 if (Right.is(TT_InheritanceColon)) 4401 return Style.BreakInheritanceList != FormatStyle::BILS_AfterColon; 4402 if (Right.is(TT_ObjCMethodExpr) && !Right.is(tok::r_square) && 4403 Left.isNot(TT_SelectorName)) 4404 return true; 4405 4406 if (Right.is(tok::colon) && 4407 !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon)) 4408 return false; 4409 if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) { 4410 if (Style.Language == FormatStyle::LK_Proto || 4411 Style.Language == FormatStyle::LK_TextProto) { 4412 if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral()) 4413 return false; 4414 // Prevent cases like: 4415 // 4416 // submessage: 4417 // { key: valueeeeeeeeeeee } 4418 // 4419 // when the snippet does not fit into one line. 4420 // Prefer: 4421 // 4422 // submessage: { 4423 // key: valueeeeeeeeeeee 4424 // } 4425 // 4426 // instead, even if it is longer by one line. 4427 // 4428 // Note that this allows allows the "{" to go over the column limit 4429 // when the column limit is just between ":" and "{", but that does 4430 // not happen too often and alternative formattings in this case are 4431 // not much better. 4432 // 4433 // The code covers the cases: 4434 // 4435 // submessage: { ... } 4436 // submessage: < ... > 4437 // repeated: [ ... ] 4438 if (((Right.is(tok::l_brace) || Right.is(tok::less)) && 4439 Right.is(TT_DictLiteral)) || 4440 Right.is(TT_ArrayInitializerLSquare)) 4441 return false; 4442 } 4443 return true; 4444 } 4445 if (Right.is(tok::r_square) && Right.MatchingParen && 4446 Right.MatchingParen->is(TT_ProtoExtensionLSquare)) 4447 return false; 4448 if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next && 4449 Right.Next->is(TT_ObjCMethodExpr))) 4450 return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls. 4451 if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty) 4452 return true; 4453 if (Right.is(tok::kw_concept)) 4454 return Style.BreakBeforeConceptDeclarations != FormatStyle::BBCDS_Never; 4455 if (Right.is(TT_RequiresClause)) 4456 return true; 4457 if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen)) 4458 return true; 4459 if (Left.ClosesRequiresClause) 4460 return true; 4461 if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen, 4462 TT_OverloadedOperator)) 4463 return false; 4464 if (Left.is(TT_RangeBasedForLoopColon)) 4465 return true; 4466 if (Right.is(TT_RangeBasedForLoopColon)) 4467 return false; 4468 if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener)) 4469 return true; 4470 if ((Left.is(tok::greater) && Right.is(tok::greater)) || 4471 (Left.is(tok::less) && Right.is(tok::less))) 4472 return false; 4473 if (Right.is(TT_BinaryOperator) && 4474 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None && 4475 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All || 4476 Right.getPrecedence() != prec::Assignment)) 4477 return true; 4478 if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) || 4479 Left.is(tok::kw_operator)) 4480 return false; 4481 if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) && 4482 Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0) 4483 return false; 4484 if (Left.is(tok::equal) && Right.is(tok::l_brace) && 4485 !Style.Cpp11BracedListStyle) 4486 return false; 4487 if (Left.is(tok::l_paren) && 4488 Left.isOneOf(TT_AttributeParen, TT_TypeDeclarationParen)) 4489 return false; 4490 if (Left.is(tok::l_paren) && Left.Previous && 4491 (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen))) 4492 return false; 4493 if (Right.is(TT_ImplicitStringLiteral)) 4494 return false; 4495 4496 if (Right.is(TT_TemplateCloser)) 4497 return false; 4498 if (Right.is(tok::r_square) && Right.MatchingParen && 4499 Right.MatchingParen->is(TT_LambdaLSquare)) 4500 return false; 4501 4502 // We only break before r_brace if there was a corresponding break before 4503 // the l_brace, which is tracked by BreakBeforeClosingBrace. 4504 if (Right.is(tok::r_brace)) 4505 return Right.MatchingParen && Right.MatchingParen->is(BK_Block); 4506 4507 // We only break before r_paren if we're in a block indented context. 4508 if (Right.is(tok::r_paren)) { 4509 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent) { 4510 return Right.MatchingParen && 4511 !(Right.MatchingParen->Previous && 4512 (Right.MatchingParen->Previous->is(tok::kw_for) || 4513 Right.MatchingParen->Previous->isIf())); 4514 } 4515 4516 return false; 4517 } 4518 4519 // Allow breaking after a trailing annotation, e.g. after a method 4520 // declaration. 4521 if (Left.is(TT_TrailingAnnotation)) 4522 return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren, 4523 tok::less, tok::coloncolon); 4524 4525 if (Right.is(tok::kw___attribute) || 4526 (Right.is(tok::l_square) && Right.is(TT_AttributeSquare))) 4527 return !Left.is(TT_AttributeSquare); 4528 4529 if (Left.is(tok::identifier) && Right.is(tok::string_literal)) 4530 return true; 4531 4532 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral)) 4533 return true; 4534 4535 if (Left.is(TT_CtorInitializerColon)) 4536 return Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon; 4537 if (Right.is(TT_CtorInitializerColon)) 4538 return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon; 4539 if (Left.is(TT_CtorInitializerComma) && 4540 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) 4541 return false; 4542 if (Right.is(TT_CtorInitializerComma) && 4543 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) 4544 return true; 4545 if (Left.is(TT_InheritanceComma) && 4546 Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma) 4547 return false; 4548 if (Right.is(TT_InheritanceComma) && 4549 Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma) 4550 return true; 4551 if (Left.is(TT_ArrayInitializerLSquare)) 4552 return true; 4553 if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const)) 4554 return true; 4555 if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) && 4556 !Left.isOneOf(tok::arrowstar, tok::lessless) && 4557 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All && 4558 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None || 4559 Left.getPrecedence() == prec::Assignment)) 4560 return true; 4561 if ((Left.is(TT_AttributeSquare) && Right.is(tok::l_square)) || 4562 (Left.is(tok::r_square) && Right.is(TT_AttributeSquare))) 4563 return false; 4564 4565 auto ShortLambdaOption = Style.AllowShortLambdasOnASingleLine; 4566 if (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT_LambdaLBrace)) { 4567 if (isAllmanLambdaBrace(Left)) 4568 return !isItAnEmptyLambdaAllowed(Left, ShortLambdaOption); 4569 if (isAllmanLambdaBrace(Right)) 4570 return !isItAnEmptyLambdaAllowed(Right, ShortLambdaOption); 4571 } 4572 4573 return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace, 4574 tok::kw_class, tok::kw_struct, tok::comment) || 4575 Right.isMemberAccess() || 4576 Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless, 4577 tok::colon, tok::l_square, tok::at) || 4578 (Left.is(tok::r_paren) && 4579 Right.isOneOf(tok::identifier, tok::kw_const)) || 4580 (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) || 4581 (Left.is(TT_TemplateOpener) && !Right.is(TT_TemplateCloser)); 4582 } 4583 4584 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) { 4585 llvm::errs() << "AnnotatedTokens(L=" << Line.Level << "):\n"; 4586 const FormatToken *Tok = Line.First; 4587 while (Tok) { 4588 llvm::errs() << " M=" << Tok->MustBreakBefore 4589 << " C=" << Tok->CanBreakBefore 4590 << " T=" << getTokenTypeName(Tok->getType()) 4591 << " S=" << Tok->SpacesRequiredBefore 4592 << " F=" << Tok->Finalized << " B=" << Tok->BlockParameterCount 4593 << " BK=" << Tok->getBlockKind() << " P=" << Tok->SplitPenalty 4594 << " Name=" << Tok->Tok.getName() << " L=" << Tok->TotalLength 4595 << " PPK=" << Tok->getPackingKind() << " FakeLParens="; 4596 for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i) 4597 llvm::errs() << Tok->FakeLParens[i] << "/"; 4598 llvm::errs() << " FakeRParens=" << Tok->FakeRParens; 4599 llvm::errs() << " II=" << Tok->Tok.getIdentifierInfo(); 4600 llvm::errs() << " Text='" << Tok->TokenText << "'\n"; 4601 if (!Tok->Next) 4602 assert(Tok == Line.Last); 4603 Tok = Tok->Next; 4604 } 4605 llvm::errs() << "----\n"; 4606 } 4607 4608 FormatStyle::PointerAlignmentStyle 4609 TokenAnnotator::getTokenReferenceAlignment(const FormatToken &Reference) { 4610 assert(Reference.isOneOf(tok::amp, tok::ampamp)); 4611 switch (Style.ReferenceAlignment) { 4612 case FormatStyle::RAS_Pointer: 4613 return Style.PointerAlignment; 4614 case FormatStyle::RAS_Left: 4615 return FormatStyle::PAS_Left; 4616 case FormatStyle::RAS_Right: 4617 return FormatStyle::PAS_Right; 4618 case FormatStyle::RAS_Middle: 4619 return FormatStyle::PAS_Middle; 4620 } 4621 assert(0); //"Unhandled value of ReferenceAlignment" 4622 return Style.PointerAlignment; 4623 } 4624 4625 FormatStyle::PointerAlignmentStyle 4626 TokenAnnotator::getTokenPointerOrReferenceAlignment( 4627 const FormatToken &PointerOrReference) { 4628 if (PointerOrReference.isOneOf(tok::amp, tok::ampamp)) { 4629 switch (Style.ReferenceAlignment) { 4630 case FormatStyle::RAS_Pointer: 4631 return Style.PointerAlignment; 4632 case FormatStyle::RAS_Left: 4633 return FormatStyle::PAS_Left; 4634 case FormatStyle::RAS_Right: 4635 return FormatStyle::PAS_Right; 4636 case FormatStyle::RAS_Middle: 4637 return FormatStyle::PAS_Middle; 4638 } 4639 } 4640 assert(PointerOrReference.is(tok::star)); 4641 return Style.PointerAlignment; 4642 } 4643 4644 } // namespace format 4645 } // namespace clang 4646