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