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