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