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