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