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