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