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