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