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::equal, tok::kw_delete, tok::kw_sizeof, 1968 tok::kw_throw) || 1969 PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr, 1970 TT_UnaryOperator, TT_CastRParen)) 1971 return TT_UnaryOperator; 1972 1973 if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare)) 1974 return TT_PointerOrReference; 1975 if (NextToken->is(tok::kw_operator) && !IsExpression) 1976 return TT_PointerOrReference; 1977 if (NextToken->isOneOf(tok::comma, tok::semi)) 1978 return TT_PointerOrReference; 1979 1980 if (PrevToken->Tok.isLiteral() || 1981 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true, 1982 tok::kw_false, tok::r_brace) || 1983 NextToken->Tok.isLiteral() || 1984 NextToken->isOneOf(tok::kw_true, tok::kw_false) || 1985 NextToken->isUnaryOperator() || 1986 // If we know we're in a template argument, there are no named 1987 // declarations. Thus, having an identifier on the right-hand side 1988 // indicates a binary operator. 1989 (InTemplateArgument && NextToken->Tok.isAnyIdentifier())) 1990 return TT_BinaryOperator; 1991 1992 // "&&(" is quite unlikely to be two successive unary "&". 1993 if (Tok.is(tok::ampamp) && NextToken->is(tok::l_paren)) 1994 return TT_BinaryOperator; 1995 1996 // This catches some cases where evaluation order is used as control flow: 1997 // aaa && aaa->f(); 1998 if (NextToken->Tok.isAnyIdentifier()) { 1999 const FormatToken *NextNextToken = NextToken->getNextNonComment(); 2000 if (NextNextToken && NextNextToken->is(tok::arrow)) 2001 return TT_BinaryOperator; 2002 } 2003 2004 // It is very unlikely that we are going to find a pointer or reference type 2005 // definition on the RHS of an assignment. 2006 if (IsExpression && !Contexts.back().CaretFound) 2007 return TT_BinaryOperator; 2008 2009 return TT_PointerOrReference; 2010 } 2011 2012 TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) { 2013 const FormatToken *PrevToken = Tok.getPreviousNonComment(); 2014 if (!PrevToken) 2015 return TT_UnaryOperator; 2016 2017 if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator)) 2018 // This must be a sequence of leading unary operators. 2019 return TT_UnaryOperator; 2020 2021 // Use heuristics to recognize unary operators. 2022 if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square, 2023 tok::question, tok::colon, tok::kw_return, 2024 tok::kw_case, tok::at, tok::l_brace, tok::kw_throw, 2025 tok::kw_co_return, tok::kw_co_yield)) 2026 return TT_UnaryOperator; 2027 2028 // There can't be two consecutive binary operators. 2029 if (PrevToken->is(TT_BinaryOperator)) 2030 return TT_UnaryOperator; 2031 2032 // Fall back to marking the token as binary operator. 2033 return TT_BinaryOperator; 2034 } 2035 2036 /// Determine whether ++/-- are pre- or post-increments/-decrements. 2037 TokenType determineIncrementUsage(const FormatToken &Tok) { 2038 const FormatToken *PrevToken = Tok.getPreviousNonComment(); 2039 if (!PrevToken || PrevToken->is(TT_CastRParen)) 2040 return TT_UnaryOperator; 2041 if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier)) 2042 return TT_TrailingUnaryOperator; 2043 2044 return TT_UnaryOperator; 2045 } 2046 2047 SmallVector<Context, 8> Contexts; 2048 2049 const FormatStyle &Style; 2050 AnnotatedLine &Line; 2051 FormatToken *CurrentToken; 2052 bool AutoFound; 2053 const AdditionalKeywords &Keywords; 2054 2055 // Set of "<" tokens that do not open a template parameter list. If parseAngle 2056 // determines that a specific token can't be a template opener, it will make 2057 // same decision irrespective of the decisions for tokens leading up to it. 2058 // Store this information to prevent this from causing exponential runtime. 2059 llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess; 2060 }; 2061 2062 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1; 2063 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2; 2064 2065 /// Parses binary expressions by inserting fake parenthesis based on 2066 /// operator precedence. 2067 class ExpressionParser { 2068 public: 2069 ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords, 2070 AnnotatedLine &Line) 2071 : Style(Style), Keywords(Keywords), Current(Line.First) {} 2072 2073 /// Parse expressions with the given operator precedence. 2074 void parse(int Precedence = 0) { 2075 // Skip 'return' and ObjC selector colons as they are not part of a binary 2076 // expression. 2077 while (Current && (Current->is(tok::kw_return) || 2078 (Current->is(tok::colon) && 2079 Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)))) 2080 next(); 2081 2082 if (!Current || Precedence > PrecedenceArrowAndPeriod) 2083 return; 2084 2085 // Conditional expressions need to be parsed separately for proper nesting. 2086 if (Precedence == prec::Conditional) { 2087 parseConditionalExpr(); 2088 return; 2089 } 2090 2091 // Parse unary operators, which all have a higher precedence than binary 2092 // operators. 2093 if (Precedence == PrecedenceUnaryOperator) { 2094 parseUnaryOperator(); 2095 return; 2096 } 2097 2098 FormatToken *Start = Current; 2099 FormatToken *LatestOperator = nullptr; 2100 unsigned OperatorIndex = 0; 2101 2102 while (Current) { 2103 // Consume operators with higher precedence. 2104 parse(Precedence + 1); 2105 2106 int CurrentPrecedence = getCurrentPrecedence(); 2107 2108 if (Current && Current->is(TT_SelectorName) && 2109 Precedence == CurrentPrecedence) { 2110 if (LatestOperator) 2111 addFakeParenthesis(Start, prec::Level(Precedence)); 2112 Start = Current; 2113 } 2114 2115 // At the end of the line or when an operator with higher precedence is 2116 // found, insert fake parenthesis and return. 2117 if (!Current || 2118 (Current->closesScope() && 2119 (Current->MatchingParen || Current->is(TT_TemplateString))) || 2120 (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) || 2121 (CurrentPrecedence == prec::Conditional && 2122 Precedence == prec::Assignment && Current->is(tok::colon))) { 2123 break; 2124 } 2125 2126 // Consume scopes: (), [], <> and {} 2127 if (Current->opensScope()) { 2128 // In fragment of a JavaScript template string can look like '}..${' and 2129 // thus close a scope and open a new one at the same time. 2130 while (Current && (!Current->closesScope() || Current->opensScope())) { 2131 next(); 2132 parse(); 2133 } 2134 next(); 2135 } else { 2136 // Operator found. 2137 if (CurrentPrecedence == Precedence) { 2138 if (LatestOperator) 2139 LatestOperator->NextOperator = Current; 2140 LatestOperator = Current; 2141 Current->OperatorIndex = OperatorIndex; 2142 ++OperatorIndex; 2143 } 2144 next(/*SkipPastLeadingComments=*/Precedence > 0); 2145 } 2146 } 2147 2148 if (LatestOperator && (Current || Precedence > 0)) { 2149 // LatestOperator->LastOperator = true; 2150 if (Precedence == PrecedenceArrowAndPeriod) { 2151 // Call expressions don't have a binary operator precedence. 2152 addFakeParenthesis(Start, prec::Unknown); 2153 } else { 2154 addFakeParenthesis(Start, prec::Level(Precedence)); 2155 } 2156 } 2157 } 2158 2159 private: 2160 /// Gets the precedence (+1) of the given token for binary operators 2161 /// and other tokens that we treat like binary operators. 2162 int getCurrentPrecedence() { 2163 if (Current) { 2164 const FormatToken *NextNonComment = Current->getNextNonComment(); 2165 if (Current->is(TT_ConditionalExpr)) 2166 return prec::Conditional; 2167 if (NextNonComment && Current->is(TT_SelectorName) && 2168 (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) || 2169 ((Style.Language == FormatStyle::LK_Proto || 2170 Style.Language == FormatStyle::LK_TextProto) && 2171 NextNonComment->is(tok::less)))) 2172 return prec::Assignment; 2173 if (Current->is(TT_JsComputedPropertyName)) 2174 return prec::Assignment; 2175 if (Current->is(TT_LambdaArrow)) 2176 return prec::Comma; 2177 if (Current->is(TT_JsFatArrow)) 2178 return prec::Assignment; 2179 if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) || 2180 (Current->is(tok::comment) && NextNonComment && 2181 NextNonComment->is(TT_SelectorName))) 2182 return 0; 2183 if (Current->is(TT_RangeBasedForLoopColon)) 2184 return prec::Comma; 2185 if ((Style.Language == FormatStyle::LK_Java || 2186 Style.Language == FormatStyle::LK_JavaScript) && 2187 Current->is(Keywords.kw_instanceof)) 2188 return prec::Relational; 2189 if (Style.Language == FormatStyle::LK_JavaScript && 2190 Current->isOneOf(Keywords.kw_in, Keywords.kw_as)) 2191 return prec::Relational; 2192 if (Current->is(TT_BinaryOperator) || Current->is(tok::comma)) 2193 return Current->getPrecedence(); 2194 if (Current->isOneOf(tok::period, tok::arrow)) 2195 return PrecedenceArrowAndPeriod; 2196 if ((Style.Language == FormatStyle::LK_Java || 2197 Style.Language == FormatStyle::LK_JavaScript) && 2198 Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements, 2199 Keywords.kw_throws)) 2200 return 0; 2201 } 2202 return -1; 2203 } 2204 2205 void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) { 2206 Start->FakeLParens.push_back(Precedence); 2207 if (Precedence > prec::Unknown) 2208 Start->StartsBinaryExpression = true; 2209 if (Current) { 2210 FormatToken *Previous = Current->Previous; 2211 while (Previous->is(tok::comment) && Previous->Previous) 2212 Previous = Previous->Previous; 2213 ++Previous->FakeRParens; 2214 if (Precedence > prec::Unknown) 2215 Previous->EndsBinaryExpression = true; 2216 } 2217 } 2218 2219 /// Parse unary operator expressions and surround them with fake 2220 /// parentheses if appropriate. 2221 void parseUnaryOperator() { 2222 llvm::SmallVector<FormatToken *, 2> Tokens; 2223 while (Current && Current->is(TT_UnaryOperator)) { 2224 Tokens.push_back(Current); 2225 next(); 2226 } 2227 parse(PrecedenceArrowAndPeriod); 2228 for (FormatToken *Token : llvm::reverse(Tokens)) 2229 // The actual precedence doesn't matter. 2230 addFakeParenthesis(Token, prec::Unknown); 2231 } 2232 2233 void parseConditionalExpr() { 2234 while (Current && Current->isTrailingComment()) { 2235 next(); 2236 } 2237 FormatToken *Start = Current; 2238 parse(prec::LogicalOr); 2239 if (!Current || !Current->is(tok::question)) 2240 return; 2241 next(); 2242 parse(prec::Assignment); 2243 if (!Current || Current->isNot(TT_ConditionalExpr)) 2244 return; 2245 next(); 2246 parse(prec::Assignment); 2247 addFakeParenthesis(Start, prec::Conditional); 2248 } 2249 2250 void next(bool SkipPastLeadingComments = true) { 2251 if (Current) 2252 Current = Current->Next; 2253 while (Current && 2254 (Current->NewlinesBefore == 0 || SkipPastLeadingComments) && 2255 Current->isTrailingComment()) 2256 Current = Current->Next; 2257 } 2258 2259 const FormatStyle &Style; 2260 const AdditionalKeywords &Keywords; 2261 FormatToken *Current; 2262 }; 2263 2264 } // end anonymous namespace 2265 2266 void TokenAnnotator::setCommentLineLevels( 2267 SmallVectorImpl<AnnotatedLine *> &Lines) { 2268 const AnnotatedLine *NextNonCommentLine = nullptr; 2269 for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(), 2270 E = Lines.rend(); 2271 I != E; ++I) { 2272 bool CommentLine = true; 2273 for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) { 2274 if (!Tok->is(tok::comment)) { 2275 CommentLine = false; 2276 break; 2277 } 2278 } 2279 2280 // If the comment is currently aligned with the line immediately following 2281 // it, that's probably intentional and we should keep it. 2282 if (NextNonCommentLine && CommentLine && 2283 NextNonCommentLine->First->NewlinesBefore <= 1 && 2284 NextNonCommentLine->First->OriginalColumn == 2285 (*I)->First->OriginalColumn) { 2286 // Align comments for preprocessor lines with the # in column 0 if 2287 // preprocessor lines are not indented. Otherwise, align with the next 2288 // line. 2289 (*I)->Level = 2290 (Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash && 2291 (NextNonCommentLine->Type == LT_PreprocessorDirective || 2292 NextNonCommentLine->Type == LT_ImportStatement)) 2293 ? 0 2294 : NextNonCommentLine->Level; 2295 } else { 2296 NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr; 2297 } 2298 2299 setCommentLineLevels((*I)->Children); 2300 } 2301 } 2302 2303 static unsigned maxNestingDepth(const AnnotatedLine &Line) { 2304 unsigned Result = 0; 2305 for (const auto *Tok = Line.First; Tok != nullptr; Tok = Tok->Next) 2306 Result = std::max(Result, Tok->NestingLevel); 2307 return Result; 2308 } 2309 2310 void TokenAnnotator::annotate(AnnotatedLine &Line) { 2311 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(), 2312 E = Line.Children.end(); 2313 I != E; ++I) { 2314 annotate(**I); 2315 } 2316 AnnotatingParser Parser(Style, Line, Keywords); 2317 Line.Type = Parser.parseLine(); 2318 2319 // With very deep nesting, ExpressionParser uses lots of stack and the 2320 // formatting algorithm is very slow. We're not going to do a good job here 2321 // anyway - it's probably generated code being formatted by mistake. 2322 // Just skip the whole line. 2323 if (maxNestingDepth(Line) > 50) 2324 Line.Type = LT_Invalid; 2325 2326 if (Line.Type == LT_Invalid) 2327 return; 2328 2329 ExpressionParser ExprParser(Style, Keywords, Line); 2330 ExprParser.parse(); 2331 2332 if (Line.startsWith(TT_ObjCMethodSpecifier)) 2333 Line.Type = LT_ObjCMethodDecl; 2334 else if (Line.startsWith(TT_ObjCDecl)) 2335 Line.Type = LT_ObjCDecl; 2336 else if (Line.startsWith(TT_ObjCProperty)) 2337 Line.Type = LT_ObjCProperty; 2338 2339 Line.First->SpacesRequiredBefore = 1; 2340 Line.First->CanBreakBefore = Line.First->MustBreakBefore; 2341 } 2342 2343 // This function heuristically determines whether 'Current' starts the name of a 2344 // function declaration. 2345 static bool isFunctionDeclarationName(const FormatToken &Current, 2346 const AnnotatedLine &Line) { 2347 auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * { 2348 for (; Next; Next = Next->Next) { 2349 if (Next->is(TT_OverloadedOperatorLParen)) 2350 return Next; 2351 if (Next->is(TT_OverloadedOperator)) 2352 continue; 2353 if (Next->isOneOf(tok::kw_new, tok::kw_delete)) { 2354 // For 'new[]' and 'delete[]'. 2355 if (Next->Next && 2356 Next->Next->startsSequence(tok::l_square, tok::r_square)) 2357 Next = Next->Next->Next; 2358 continue; 2359 } 2360 if (Next->startsSequence(tok::l_square, tok::r_square)) { 2361 // For operator[](). 2362 Next = Next->Next; 2363 continue; 2364 } 2365 if ((Next->isSimpleTypeSpecifier() || Next->is(tok::identifier)) && 2366 Next->Next && Next->Next->isOneOf(tok::star, tok::amp, tok::ampamp)) { 2367 // For operator void*(), operator char*(), operator Foo*(). 2368 Next = Next->Next; 2369 continue; 2370 } 2371 if (Next->is(TT_TemplateOpener) && Next->MatchingParen) { 2372 Next = Next->MatchingParen; 2373 continue; 2374 } 2375 2376 break; 2377 } 2378 return nullptr; 2379 }; 2380 2381 // Find parentheses of parameter list. 2382 const FormatToken *Next = Current.Next; 2383 if (Current.is(tok::kw_operator)) { 2384 if (Current.Previous && Current.Previous->is(tok::coloncolon)) 2385 return false; 2386 Next = skipOperatorName(Next); 2387 } else { 2388 if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0) 2389 return false; 2390 for (; Next; Next = Next->Next) { 2391 if (Next->is(TT_TemplateOpener)) { 2392 Next = Next->MatchingParen; 2393 } else if (Next->is(tok::coloncolon)) { 2394 Next = Next->Next; 2395 if (!Next) 2396 return false; 2397 if (Next->is(tok::kw_operator)) { 2398 Next = skipOperatorName(Next->Next); 2399 break; 2400 } 2401 if (!Next->is(tok::identifier)) 2402 return false; 2403 } else if (Next->is(tok::l_paren)) { 2404 break; 2405 } else { 2406 return false; 2407 } 2408 } 2409 } 2410 2411 // Check whether parameter list can belong to a function declaration. 2412 if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen) 2413 return false; 2414 // If the lines ends with "{", this is likely an function definition. 2415 if (Line.Last->is(tok::l_brace)) 2416 return true; 2417 if (Next->Next == Next->MatchingParen) 2418 return true; // Empty parentheses. 2419 // If there is an &/&& after the r_paren, this is likely a function. 2420 if (Next->MatchingParen->Next && 2421 Next->MatchingParen->Next->is(TT_PointerOrReference)) 2422 return true; 2423 for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen; 2424 Tok = Tok->Next) { 2425 if (Tok->is(TT_TypeDeclarationParen)) 2426 return true; 2427 if (Tok->isOneOf(tok::l_paren, TT_TemplateOpener) && Tok->MatchingParen) { 2428 Tok = Tok->MatchingParen; 2429 continue; 2430 } 2431 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() || 2432 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis)) 2433 return true; 2434 if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) || 2435 Tok->Tok.isLiteral()) 2436 return false; 2437 } 2438 return false; 2439 } 2440 2441 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const { 2442 assert(Line.MightBeFunctionDecl); 2443 2444 if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel || 2445 Style.AlwaysBreakAfterReturnType == 2446 FormatStyle::RTBS_TopLevelDefinitions) && 2447 Line.Level > 0) 2448 return false; 2449 2450 switch (Style.AlwaysBreakAfterReturnType) { 2451 case FormatStyle::RTBS_None: 2452 return false; 2453 case FormatStyle::RTBS_All: 2454 case FormatStyle::RTBS_TopLevel: 2455 return true; 2456 case FormatStyle::RTBS_AllDefinitions: 2457 case FormatStyle::RTBS_TopLevelDefinitions: 2458 return Line.mightBeFunctionDefinition(); 2459 } 2460 2461 return false; 2462 } 2463 2464 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) { 2465 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(), 2466 E = Line.Children.end(); 2467 I != E; ++I) { 2468 calculateFormattingInformation(**I); 2469 } 2470 2471 Line.First->TotalLength = 2472 Line.First->IsMultiline ? Style.ColumnLimit 2473 : Line.FirstStartColumn + Line.First->ColumnWidth; 2474 FormatToken *Current = Line.First->Next; 2475 bool InFunctionDecl = Line.MightBeFunctionDecl; 2476 while (Current) { 2477 if (isFunctionDeclarationName(*Current, Line)) 2478 Current->setType(TT_FunctionDeclarationName); 2479 if (Current->is(TT_LineComment)) { 2480 if (Current->Previous->is(BK_BracedInit) && 2481 Current->Previous->opensScope()) 2482 Current->SpacesRequiredBefore = 2483 (Style.Cpp11BracedListStyle && !Style.SpacesInParentheses) ? 0 : 1; 2484 else 2485 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments; 2486 2487 // If we find a trailing comment, iterate backwards to determine whether 2488 // it seems to relate to a specific parameter. If so, break before that 2489 // parameter to avoid changing the comment's meaning. E.g. don't move 'b' 2490 // to the previous line in: 2491 // SomeFunction(a, 2492 // b, // comment 2493 // c); 2494 if (!Current->HasUnescapedNewline) { 2495 for (FormatToken *Parameter = Current->Previous; Parameter; 2496 Parameter = Parameter->Previous) { 2497 if (Parameter->isOneOf(tok::comment, tok::r_brace)) 2498 break; 2499 if (Parameter->Previous && Parameter->Previous->is(tok::comma)) { 2500 if (!Parameter->Previous->is(TT_CtorInitializerComma) && 2501 Parameter->HasUnescapedNewline) 2502 Parameter->MustBreakBefore = true; 2503 break; 2504 } 2505 } 2506 } 2507 } else if (Current->SpacesRequiredBefore == 0 && 2508 spaceRequiredBefore(Line, *Current)) { 2509 Current->SpacesRequiredBefore = 1; 2510 } 2511 2512 Current->MustBreakBefore = 2513 Current->MustBreakBefore || mustBreakBefore(Line, *Current); 2514 2515 if (!Current->MustBreakBefore && InFunctionDecl && 2516 Current->is(TT_FunctionDeclarationName)) 2517 Current->MustBreakBefore = mustBreakForReturnType(Line); 2518 2519 Current->CanBreakBefore = 2520 Current->MustBreakBefore || canBreakBefore(Line, *Current); 2521 unsigned ChildSize = 0; 2522 if (Current->Previous->Children.size() == 1) { 2523 FormatToken &LastOfChild = *Current->Previous->Children[0]->Last; 2524 ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit 2525 : LastOfChild.TotalLength + 1; 2526 } 2527 const FormatToken *Prev = Current->Previous; 2528 if (Current->MustBreakBefore || Prev->Children.size() > 1 || 2529 (Prev->Children.size() == 1 && 2530 Prev->Children[0]->First->MustBreakBefore) || 2531 Current->IsMultiline) 2532 Current->TotalLength = Prev->TotalLength + Style.ColumnLimit; 2533 else 2534 Current->TotalLength = Prev->TotalLength + Current->ColumnWidth + 2535 ChildSize + Current->SpacesRequiredBefore; 2536 2537 if (Current->is(TT_CtorInitializerColon)) 2538 InFunctionDecl = false; 2539 2540 // FIXME: Only calculate this if CanBreakBefore is true once static 2541 // initializers etc. are sorted out. 2542 // FIXME: Move magic numbers to a better place. 2543 2544 // Reduce penalty for aligning ObjC method arguments using the colon 2545 // alignment as this is the canonical way (still prefer fitting everything 2546 // into one line if possible). Trying to fit a whole expression into one 2547 // line should not force other line breaks (e.g. when ObjC method 2548 // expression is a part of other expression). 2549 Current->SplitPenalty = splitPenalty(Line, *Current, InFunctionDecl); 2550 if (Style.Language == FormatStyle::LK_ObjC && 2551 Current->is(TT_SelectorName) && Current->ParameterIndex > 0) { 2552 if (Current->ParameterIndex == 1) 2553 Current->SplitPenalty += 5 * Current->BindingStrength; 2554 } else { 2555 Current->SplitPenalty += 20 * Current->BindingStrength; 2556 } 2557 2558 Current = Current->Next; 2559 } 2560 2561 calculateUnbreakableTailLengths(Line); 2562 unsigned IndentLevel = Line.Level; 2563 for (Current = Line.First; Current != nullptr; Current = Current->Next) { 2564 if (Current->Role) 2565 Current->Role->precomputeFormattingInfos(Current); 2566 if (Current->MatchingParen && 2567 Current->MatchingParen->opensBlockOrBlockTypeList(Style)) { 2568 assert(IndentLevel > 0); 2569 --IndentLevel; 2570 } 2571 Current->IndentLevel = IndentLevel; 2572 if (Current->opensBlockOrBlockTypeList(Style)) 2573 ++IndentLevel; 2574 } 2575 2576 LLVM_DEBUG({ printDebugInfo(Line); }); 2577 } 2578 2579 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) { 2580 unsigned UnbreakableTailLength = 0; 2581 FormatToken *Current = Line.Last; 2582 while (Current) { 2583 Current->UnbreakableTailLength = UnbreakableTailLength; 2584 if (Current->CanBreakBefore || 2585 Current->isOneOf(tok::comment, tok::string_literal)) { 2586 UnbreakableTailLength = 0; 2587 } else { 2588 UnbreakableTailLength += 2589 Current->ColumnWidth + Current->SpacesRequiredBefore; 2590 } 2591 Current = Current->Previous; 2592 } 2593 } 2594 2595 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line, 2596 const FormatToken &Tok, 2597 bool InFunctionDecl) { 2598 const FormatToken &Left = *Tok.Previous; 2599 const FormatToken &Right = Tok; 2600 2601 if (Left.is(tok::semi)) 2602 return 0; 2603 2604 if (Style.Language == FormatStyle::LK_Java) { 2605 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws)) 2606 return 1; 2607 if (Right.is(Keywords.kw_implements)) 2608 return 2; 2609 if (Left.is(tok::comma) && Left.NestingLevel == 0) 2610 return 3; 2611 } else if (Style.Language == FormatStyle::LK_JavaScript) { 2612 if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma)) 2613 return 100; 2614 if (Left.is(TT_JsTypeColon)) 2615 return 35; 2616 if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) || 2617 (Right.is(TT_TemplateString) && Right.TokenText.startswith("}"))) 2618 return 100; 2619 // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()". 2620 if (Left.opensScope() && Right.closesScope()) 2621 return 200; 2622 } 2623 2624 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral)) 2625 return 1; 2626 if (Right.is(tok::l_square)) { 2627 if (Style.Language == FormatStyle::LK_Proto) 2628 return 1; 2629 if (Left.is(tok::r_square)) 2630 return 200; 2631 // Slightly prefer formatting local lambda definitions like functions. 2632 if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal)) 2633 return 35; 2634 if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare, 2635 TT_ArrayInitializerLSquare, 2636 TT_DesignatedInitializerLSquare, TT_AttributeSquare)) 2637 return 500; 2638 } 2639 2640 if (Left.is(tok::coloncolon) || 2641 (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto)) 2642 return 500; 2643 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) || 2644 Right.is(tok::kw_operator)) { 2645 if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt) 2646 return 3; 2647 if (Left.is(TT_StartOfName)) 2648 return 110; 2649 if (InFunctionDecl && Right.NestingLevel == 0) 2650 return Style.PenaltyReturnTypeOnItsOwnLine; 2651 return 200; 2652 } 2653 if (Right.is(TT_PointerOrReference)) 2654 return 190; 2655 if (Right.is(TT_LambdaArrow)) 2656 return 110; 2657 if (Left.is(tok::equal) && Right.is(tok::l_brace)) 2658 return 160; 2659 if (Left.is(TT_CastRParen)) 2660 return 100; 2661 if (Left.isOneOf(tok::kw_class, tok::kw_struct)) 2662 return 5000; 2663 if (Left.is(tok::comment)) 2664 return 1000; 2665 2666 if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon, 2667 TT_CtorInitializerColon)) 2668 return 2; 2669 2670 if (Right.isMemberAccess()) { 2671 // Breaking before the "./->" of a chained call/member access is reasonably 2672 // cheap, as formatting those with one call per line is generally 2673 // desirable. In particular, it should be cheaper to break before the call 2674 // than it is to break inside a call's parameters, which could lead to weird 2675 // "hanging" indents. The exception is the very last "./->" to support this 2676 // frequent pattern: 2677 // 2678 // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc( 2679 // dddddddd); 2680 // 2681 // which might otherwise be blown up onto many lines. Here, clang-format 2682 // won't produce "hanging" indents anyway as there is no other trailing 2683 // call. 2684 // 2685 // Also apply higher penalty is not a call as that might lead to a wrapping 2686 // like: 2687 // 2688 // aaaaaaa 2689 // .aaaaaaaaa.bbbbbbbb(cccccccc); 2690 return !Right.NextOperator || !Right.NextOperator->Previous->closesScope() 2691 ? 150 2692 : 35; 2693 } 2694 2695 if (Right.is(TT_TrailingAnnotation) && 2696 (!Right.Next || Right.Next->isNot(tok::l_paren))) { 2697 // Moving trailing annotations to the next line is fine for ObjC method 2698 // declarations. 2699 if (Line.startsWith(TT_ObjCMethodSpecifier)) 2700 return 10; 2701 // Generally, breaking before a trailing annotation is bad unless it is 2702 // function-like. It seems to be especially preferable to keep standard 2703 // annotations (i.e. "const", "final" and "override") on the same line. 2704 // Use a slightly higher penalty after ")" so that annotations like 2705 // "const override" are kept together. 2706 bool is_short_annotation = Right.TokenText.size() < 10; 2707 return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0); 2708 } 2709 2710 // In for-loops, prefer breaking at ',' and ';'. 2711 if (Line.startsWith(tok::kw_for) && Left.is(tok::equal)) 2712 return 4; 2713 2714 // In Objective-C method expressions, prefer breaking before "param:" over 2715 // breaking after it. 2716 if (Right.is(TT_SelectorName)) 2717 return 0; 2718 if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr)) 2719 return Line.MightBeFunctionDecl ? 50 : 500; 2720 2721 // In Objective-C type declarations, avoid breaking after the category's 2722 // open paren (we'll prefer breaking after the protocol list's opening 2723 // angle bracket, if present). 2724 if (Line.Type == LT_ObjCDecl && Left.is(tok::l_paren) && Left.Previous && 2725 Left.Previous->isOneOf(tok::identifier, tok::greater)) 2726 return 500; 2727 2728 if (Left.is(tok::l_paren) && InFunctionDecl && 2729 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign) 2730 return 100; 2731 if (Left.is(tok::l_paren) && Left.Previous && 2732 (Left.Previous->is(tok::kw_for) || Left.Previous->isIf())) 2733 return 1000; 2734 if (Left.is(tok::equal) && InFunctionDecl) 2735 return 110; 2736 if (Right.is(tok::r_brace)) 2737 return 1; 2738 if (Left.is(TT_TemplateOpener)) 2739 return 100; 2740 if (Left.opensScope()) { 2741 // If we aren't aligning after opening parens/braces we can always break 2742 // here unless the style does not want us to place all arguments on the 2743 // next line. 2744 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign && 2745 (Left.ParameterCount <= 1 || Style.AllowAllArgumentsOnNextLine)) 2746 return 0; 2747 if (Left.is(tok::l_brace) && !Style.Cpp11BracedListStyle) 2748 return 19; 2749 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter 2750 : 19; 2751 } 2752 if (Left.is(TT_JavaAnnotation)) 2753 return 50; 2754 2755 if (Left.is(TT_UnaryOperator)) 2756 return 60; 2757 if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous && 2758 Left.Previous->isLabelString() && 2759 (Left.NextOperator || Left.OperatorIndex != 0)) 2760 return 50; 2761 if (Right.is(tok::plus) && Left.isLabelString() && 2762 (Right.NextOperator || Right.OperatorIndex != 0)) 2763 return 25; 2764 if (Left.is(tok::comma)) 2765 return 1; 2766 if (Right.is(tok::lessless) && Left.isLabelString() && 2767 (Right.NextOperator || Right.OperatorIndex != 1)) 2768 return 25; 2769 if (Right.is(tok::lessless)) { 2770 // Breaking at a << is really cheap. 2771 if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0) 2772 // Slightly prefer to break before the first one in log-like statements. 2773 return 2; 2774 return 1; 2775 } 2776 if (Left.ClosesTemplateDeclaration) 2777 return Style.PenaltyBreakTemplateDeclaration; 2778 if (Left.is(TT_ConditionalExpr)) 2779 return prec::Conditional; 2780 prec::Level Level = Left.getPrecedence(); 2781 if (Level == prec::Unknown) 2782 Level = Right.getPrecedence(); 2783 if (Level == prec::Assignment) 2784 return Style.PenaltyBreakAssignment; 2785 if (Level != prec::Unknown) 2786 return Level; 2787 2788 return 3; 2789 } 2790 2791 bool TokenAnnotator::spaceRequiredBeforeParens(const FormatToken &Right) const { 2792 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always || 2793 (Style.SpaceBeforeParens == FormatStyle::SBPO_NonEmptyParentheses && 2794 Right.ParameterCount > 0); 2795 } 2796 2797 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line, 2798 const FormatToken &Left, 2799 const FormatToken &Right) { 2800 if (Left.is(tok::kw_return) && Right.isNot(tok::semi)) 2801 return true; 2802 if (Left.is(Keywords.kw_assert) && Style.Language == FormatStyle::LK_Java) 2803 return true; 2804 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty && 2805 Left.Tok.getObjCKeywordID() == tok::objc_property) 2806 return true; 2807 if (Right.is(tok::hashhash)) 2808 return Left.is(tok::hash); 2809 if (Left.isOneOf(tok::hashhash, tok::hash)) 2810 return Right.is(tok::hash); 2811 if ((Left.is(tok::l_paren) && Right.is(tok::r_paren)) || 2812 (Left.is(tok::l_brace) && Left.isNot(BK_Block) && 2813 Right.is(tok::r_brace) && Right.isNot(BK_Block))) 2814 return Style.SpaceInEmptyParentheses; 2815 if (Style.SpacesInConditionalStatement) { 2816 if (Left.is(tok::l_paren) && Left.Previous && 2817 isKeywordWithCondition(*Left.Previous)) 2818 return true; 2819 if (Right.is(tok::r_paren) && Right.MatchingParen && 2820 Right.MatchingParen->Previous && 2821 isKeywordWithCondition(*Right.MatchingParen->Previous)) 2822 return true; 2823 } 2824 2825 // requires ( or requires( 2826 if (Right.is(tok::l_paren) && Left.is(tok::kw_requires)) 2827 return spaceRequiredBeforeParens(Right); 2828 // requires clause Concept1<T> && Concept2<T> 2829 if (Left.is(TT_ConstraintJunctions) && Right.is(tok::identifier)) 2830 return true; 2831 2832 if (Left.is(tok::l_paren) || Right.is(tok::r_paren)) 2833 return (Right.is(TT_CastRParen) || 2834 (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen))) 2835 ? Style.SpacesInCStyleCastParentheses 2836 : Style.SpacesInParentheses; 2837 if (Right.isOneOf(tok::semi, tok::comma)) 2838 return false; 2839 if (Right.is(tok::less) && Line.Type == LT_ObjCDecl) { 2840 bool IsLightweightGeneric = Right.MatchingParen && 2841 Right.MatchingParen->Next && 2842 Right.MatchingParen->Next->is(tok::colon); 2843 return !IsLightweightGeneric && Style.ObjCSpaceBeforeProtocolList; 2844 } 2845 if (Right.is(tok::less) && Left.is(tok::kw_template)) 2846 return Style.SpaceAfterTemplateKeyword; 2847 if (Left.isOneOf(tok::exclaim, tok::tilde)) 2848 return false; 2849 if (Left.is(tok::at) && 2850 Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant, 2851 tok::numeric_constant, tok::l_paren, tok::l_brace, 2852 tok::kw_true, tok::kw_false)) 2853 return false; 2854 if (Left.is(tok::colon)) 2855 return !Left.is(TT_ObjCMethodExpr); 2856 if (Left.is(tok::coloncolon)) 2857 return false; 2858 if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) { 2859 if (Style.Language == FormatStyle::LK_TextProto || 2860 (Style.Language == FormatStyle::LK_Proto && 2861 (Left.is(TT_DictLiteral) || Right.is(TT_DictLiteral)))) { 2862 // Format empty list as `<>`. 2863 if (Left.is(tok::less) && Right.is(tok::greater)) 2864 return false; 2865 return !Style.Cpp11BracedListStyle; 2866 } 2867 return false; 2868 } 2869 if (Right.is(tok::ellipsis)) 2870 return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous && 2871 Left.Previous->is(tok::kw_case)); 2872 if (Left.is(tok::l_square) && Right.is(tok::amp)) 2873 return Style.SpacesInSquareBrackets; 2874 if (Right.is(TT_PointerOrReference)) { 2875 if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) { 2876 if (!Left.MatchingParen) 2877 return true; 2878 FormatToken *TokenBeforeMatchingParen = 2879 Left.MatchingParen->getPreviousNonComment(); 2880 if (!TokenBeforeMatchingParen || !Left.is(TT_TypeDeclarationParen)) 2881 return true; 2882 } 2883 // Add a space if the previous token is a pointer qualifer or the closing 2884 // parenthesis of __attribute__(()) expression and the style requires spaces 2885 // after pointer qualifiers. 2886 if ((Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_After || 2887 Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both) && 2888 (Left.is(TT_AttributeParen) || Left.canBePointerOrReferenceQualifier())) 2889 return true; 2890 return (Left.Tok.isLiteral() || 2891 (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) && 2892 (Style.PointerAlignment != FormatStyle::PAS_Left || 2893 (Line.IsMultiVariableDeclStmt && 2894 (Left.NestingLevel == 0 || 2895 (Left.NestingLevel == 1 && Line.First->is(tok::kw_for))))))); 2896 } 2897 if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) && 2898 (!Left.is(TT_PointerOrReference) || 2899 (Style.PointerAlignment != FormatStyle::PAS_Right && 2900 !Line.IsMultiVariableDeclStmt))) 2901 return true; 2902 if (Left.is(TT_PointerOrReference)) { 2903 // Add a space if the next token is a pointer qualifer and the style 2904 // requires spaces before pointer qualifiers. 2905 if ((Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Before || 2906 Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both) && 2907 Right.canBePointerOrReferenceQualifier()) 2908 return true; 2909 return Right.Tok.isLiteral() || Right.is(TT_BlockComment) || 2910 (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) && 2911 !Right.is(TT_StartOfName)) || 2912 (Right.is(tok::l_brace) && Right.is(BK_Block)) || 2913 (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare, 2914 tok::l_paren) && 2915 (Style.PointerAlignment != FormatStyle::PAS_Right && 2916 !Line.IsMultiVariableDeclStmt) && 2917 Left.Previous && 2918 !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon, 2919 tok::l_square)); 2920 } 2921 // Ensure right pointer alignement with ellipsis e.g. int *...P 2922 if (Left.is(tok::ellipsis) && Left.Previous && 2923 Left.Previous->isOneOf(tok::star, tok::amp, tok::ampamp)) 2924 return Style.PointerAlignment != FormatStyle::PAS_Right; 2925 2926 if (Right.is(tok::star) && Left.is(tok::l_paren)) 2927 return false; 2928 if (Left.is(tok::star) && Right.isOneOf(tok::star, tok::amp, tok::ampamp)) 2929 return false; 2930 if (Right.isOneOf(tok::star, tok::amp, tok::ampamp)) { 2931 const FormatToken *Previous = &Left; 2932 while (Previous && !Previous->is(tok::kw_operator)) { 2933 if (Previous->is(tok::identifier) || Previous->isSimpleTypeSpecifier()) { 2934 Previous = Previous->getPreviousNonComment(); 2935 continue; 2936 } 2937 if (Previous->is(TT_TemplateCloser) && Previous->MatchingParen) { 2938 Previous = Previous->MatchingParen->getPreviousNonComment(); 2939 continue; 2940 } 2941 if (Previous->is(tok::coloncolon)) { 2942 Previous = Previous->getPreviousNonComment(); 2943 continue; 2944 } 2945 break; 2946 } 2947 // Space between the type and the * in: 2948 // operator void*() 2949 // operator char*() 2950 // operator /*comment*/ const char*() 2951 // operator volatile /*comment*/ char*() 2952 // operator Foo*() 2953 // operator C<T>*() 2954 // operator std::Foo*() 2955 // operator C<T>::D<U>*() 2956 // dependent on PointerAlignment style. 2957 if (Previous && 2958 (Previous->endsSequence(tok::kw_operator) || 2959 Previous->endsSequence(tok::kw_const, tok::kw_operator) || 2960 Previous->endsSequence(tok::kw_volatile, tok::kw_operator))) 2961 return (Style.PointerAlignment != FormatStyle::PAS_Left); 2962 } 2963 const auto SpaceRequiredForArrayInitializerLSquare = 2964 [](const FormatToken &LSquareTok, const FormatStyle &Style) { 2965 return Style.SpacesInContainerLiterals || 2966 ((Style.Language == FormatStyle::LK_Proto || 2967 Style.Language == FormatStyle::LK_TextProto) && 2968 !Style.Cpp11BracedListStyle && 2969 LSquareTok.endsSequence(tok::l_square, tok::colon, 2970 TT_SelectorName)); 2971 }; 2972 if (Left.is(tok::l_square)) 2973 return (Left.is(TT_ArrayInitializerLSquare) && Right.isNot(tok::r_square) && 2974 SpaceRequiredForArrayInitializerLSquare(Left, Style)) || 2975 (Left.isOneOf(TT_ArraySubscriptLSquare, TT_StructuredBindingLSquare, 2976 TT_LambdaLSquare) && 2977 Style.SpacesInSquareBrackets && Right.isNot(tok::r_square)); 2978 if (Right.is(tok::r_square)) 2979 return Right.MatchingParen && 2980 ((Right.MatchingParen->is(TT_ArrayInitializerLSquare) && 2981 SpaceRequiredForArrayInitializerLSquare(*Right.MatchingParen, 2982 Style)) || 2983 (Style.SpacesInSquareBrackets && 2984 Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare, 2985 TT_StructuredBindingLSquare, 2986 TT_LambdaLSquare)) || 2987 Right.MatchingParen->is(TT_AttributeParen)); 2988 if (Right.is(tok::l_square) && 2989 !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare, 2990 TT_DesignatedInitializerLSquare, 2991 TT_StructuredBindingLSquare, TT_AttributeSquare) && 2992 !Left.isOneOf(tok::numeric_constant, TT_DictLiteral) && 2993 !(!Left.is(tok::r_square) && Style.SpaceBeforeSquareBrackets && 2994 Right.is(TT_ArraySubscriptLSquare))) 2995 return false; 2996 if (Left.is(tok::l_brace) && Right.is(tok::r_brace)) 2997 return !Left.Children.empty(); // No spaces in "{}". 2998 if ((Left.is(tok::l_brace) && Left.isNot(BK_Block)) || 2999 (Right.is(tok::r_brace) && Right.MatchingParen && 3000 Right.MatchingParen->isNot(BK_Block))) 3001 return Style.Cpp11BracedListStyle ? Style.SpacesInParentheses : true; 3002 if (Left.is(TT_BlockComment)) 3003 // No whitespace in x(/*foo=*/1), except for JavaScript. 3004 return Style.Language == FormatStyle::LK_JavaScript || 3005 !Left.TokenText.endswith("=*/"); 3006 3007 // Space between template and attribute. 3008 // e.g. template <typename T> [[nodiscard]] ... 3009 if (Left.is(TT_TemplateCloser) && Right.is(TT_AttributeSquare)) 3010 return true; 3011 if (Right.is(tok::l_paren)) { 3012 if ((Left.is(tok::r_paren) && Left.is(TT_AttributeParen)) || 3013 (Left.is(tok::r_square) && Left.is(TT_AttributeSquare))) 3014 return true; 3015 if (Style.SpaceBeforeParens == 3016 FormatStyle::SBPO_ControlStatementsExceptForEachMacros && 3017 Left.is(TT_ForEachMacro)) 3018 return false; 3019 return Line.Type == LT_ObjCDecl || Left.is(tok::semi) || 3020 (Style.SpaceBeforeParens != FormatStyle::SBPO_Never && 3021 (Left.isOneOf(tok::pp_elif, tok::kw_for, tok::kw_while, 3022 tok::kw_switch, tok::kw_case, TT_ForEachMacro, 3023 TT_ObjCForIn) || 3024 Left.isIf(Line.Type != LT_PreprocessorDirective) || 3025 (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch, 3026 tok::kw_new, tok::kw_delete) && 3027 (!Left.Previous || Left.Previous->isNot(tok::period))))) || 3028 (spaceRequiredBeforeParens(Right) && 3029 (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() || 3030 Left.is(tok::r_paren) || Left.isSimpleTypeSpecifier() || 3031 (Left.is(tok::r_square) && Left.MatchingParen && 3032 Left.MatchingParen->is(TT_LambdaLSquare))) && 3033 Line.Type != LT_PreprocessorDirective); 3034 } 3035 if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword) 3036 return false; 3037 if (Right.is(TT_UnaryOperator)) 3038 return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) && 3039 (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr)); 3040 if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square, 3041 tok::r_paren) || 3042 Left.isSimpleTypeSpecifier()) && 3043 Right.is(tok::l_brace) && Right.getNextNonComment() && 3044 Right.isNot(BK_Block)) 3045 return false; 3046 if (Left.is(tok::period) || Right.is(tok::period)) 3047 return false; 3048 if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L") 3049 return false; 3050 if (Left.is(TT_TemplateCloser) && Left.MatchingParen && 3051 Left.MatchingParen->Previous && 3052 (Left.MatchingParen->Previous->is(tok::period) || 3053 Left.MatchingParen->Previous->is(tok::coloncolon))) 3054 // Java call to generic function with explicit type: 3055 // A.<B<C<...>>>DoSomething(); 3056 // A::<B<C<...>>>DoSomething(); // With a Java 8 method reference. 3057 return false; 3058 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square)) 3059 return false; 3060 if (Left.is(tok::l_brace) && Left.endsSequence(TT_DictLiteral, tok::at)) 3061 // Objective-C dictionary literal -> no space after opening brace. 3062 return false; 3063 if (Right.is(tok::r_brace) && Right.MatchingParen && 3064 Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at)) 3065 // Objective-C dictionary literal -> no space before closing brace. 3066 return false; 3067 if (Right.getType() == TT_TrailingAnnotation && 3068 Right.isOneOf(tok::amp, tok::ampamp) && 3069 Left.isOneOf(tok::kw_const, tok::kw_volatile) && 3070 (!Right.Next || Right.Next->is(tok::semi))) 3071 // Match const and volatile ref-qualifiers without any additional 3072 // qualifiers such as 3073 // void Fn() const &; 3074 return Style.PointerAlignment != FormatStyle::PAS_Left; 3075 return true; 3076 } 3077 3078 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, 3079 const FormatToken &Right) { 3080 const FormatToken &Left = *Right.Previous; 3081 if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo()) 3082 return true; // Never ever merge two identifiers. 3083 if (Style.isCpp()) { 3084 if (Left.is(tok::kw_operator)) 3085 return Right.is(tok::coloncolon); 3086 if (Right.is(tok::l_brace) && Right.is(BK_BracedInit) && 3087 !Left.opensScope() && Style.SpaceBeforeCpp11BracedList) 3088 return true; 3089 } else if (Style.Language == FormatStyle::LK_Proto || 3090 Style.Language == FormatStyle::LK_TextProto) { 3091 if (Right.is(tok::period) && 3092 Left.isOneOf(Keywords.kw_optional, Keywords.kw_required, 3093 Keywords.kw_repeated, Keywords.kw_extend)) 3094 return true; 3095 if (Right.is(tok::l_paren) && 3096 Left.isOneOf(Keywords.kw_returns, Keywords.kw_option)) 3097 return true; 3098 if (Right.isOneOf(tok::l_brace, tok::less) && Left.is(TT_SelectorName)) 3099 return true; 3100 // Slashes occur in text protocol extension syntax: [type/type] { ... }. 3101 if (Left.is(tok::slash) || Right.is(tok::slash)) 3102 return false; 3103 if (Left.MatchingParen && 3104 Left.MatchingParen->is(TT_ProtoExtensionLSquare) && 3105 Right.isOneOf(tok::l_brace, tok::less)) 3106 return !Style.Cpp11BracedListStyle; 3107 // A percent is probably part of a formatting specification, such as %lld. 3108 if (Left.is(tok::percent)) 3109 return false; 3110 // Preserve the existence of a space before a percent for cases like 0x%04x 3111 // and "%d %d" 3112 if (Left.is(tok::numeric_constant) && Right.is(tok::percent)) 3113 return Right.WhitespaceRange.getEnd() != Right.WhitespaceRange.getBegin(); 3114 } else if (Style.isCSharp()) { 3115 // Require spaces around '{' and before '}' unless they appear in 3116 // interpolated strings. Interpolated strings are merged into a single token 3117 // so cannot have spaces inserted by this function. 3118 3119 // No space between 'this' and '[' 3120 if (Left.is(tok::kw_this) && Right.is(tok::l_square)) 3121 return false; 3122 3123 // No space between 'new' and '(' 3124 if (Left.is(tok::kw_new) && Right.is(tok::l_paren)) 3125 return false; 3126 3127 // Space before { (including space within '{ {'). 3128 if (Right.is(tok::l_brace)) 3129 return true; 3130 3131 // Spaces inside braces. 3132 if (Left.is(tok::l_brace) && Right.isNot(tok::r_brace)) 3133 return true; 3134 3135 if (Left.isNot(tok::l_brace) && Right.is(tok::r_brace)) 3136 return true; 3137 3138 // Spaces around '=>'. 3139 if (Left.is(TT_JsFatArrow) || Right.is(TT_JsFatArrow)) 3140 return true; 3141 3142 // No spaces around attribute target colons 3143 if (Left.is(TT_AttributeColon) || Right.is(TT_AttributeColon)) 3144 return false; 3145 3146 // space between type and variable e.g. Dictionary<string,string> foo; 3147 if (Left.is(TT_TemplateCloser) && Right.is(TT_StartOfName)) 3148 return true; 3149 3150 // spaces inside square brackets. 3151 if (Left.is(tok::l_square) || Right.is(tok::r_square)) 3152 return Style.SpacesInSquareBrackets; 3153 3154 // No space before ? in nullable types. 3155 if (Right.is(TT_CSharpNullable)) 3156 return false; 3157 3158 // Require space after ? in nullable types except in generics and casts. 3159 if (Left.is(TT_CSharpNullable)) 3160 return !Right.isOneOf(TT_TemplateCloser, tok::r_paren); 3161 3162 // No space before or after '?.'. 3163 if (Left.is(TT_CSharpNullConditional) || Right.is(TT_CSharpNullConditional)) 3164 return false; 3165 3166 // Space before and after '??'. 3167 if (Left.is(TT_CSharpNullCoalescing) || Right.is(TT_CSharpNullCoalescing)) 3168 return true; 3169 3170 // No space before '?['. 3171 if (Right.is(TT_CSharpNullConditionalLSquare)) 3172 return false; 3173 3174 // No space between consecutive commas '[,,]'. 3175 if (Left.is(tok::comma) && Right.is(tok::comma)) 3176 return false; 3177 3178 // Possible space inside `?[ 0 ]`. 3179 if (Left.is(TT_CSharpNullConditionalLSquare)) 3180 return Style.SpacesInSquareBrackets; 3181 3182 // space after var in `var (key, value)` 3183 if (Left.is(Keywords.kw_var) && Right.is(tok::l_paren)) 3184 return true; 3185 3186 // space between keywords and paren e.g. "using (" 3187 if (Right.is(tok::l_paren)) 3188 if (Left.isOneOf(tok::kw_using, Keywords.kw_async, Keywords.kw_when, 3189 Keywords.kw_lock)) 3190 return Style.SpaceBeforeParens == FormatStyle::SBPO_ControlStatements || 3191 spaceRequiredBeforeParens(Right); 3192 3193 // space between method modifier and opening parenthesis of a tuple return 3194 // type 3195 if (Left.isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected, 3196 tok::kw_virtual, tok::kw_extern, tok::kw_static, 3197 Keywords.kw_internal, Keywords.kw_abstract, 3198 Keywords.kw_sealed, Keywords.kw_override, 3199 Keywords.kw_async, Keywords.kw_unsafe) && 3200 Right.is(tok::l_paren)) 3201 return true; 3202 } else if (Style.Language == FormatStyle::LK_JavaScript) { 3203 if (Left.is(TT_JsFatArrow)) 3204 return true; 3205 // for await ( ... 3206 if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && Left.Previous && 3207 Left.Previous->is(tok::kw_for)) 3208 return true; 3209 if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) && 3210 Right.MatchingParen) { 3211 const FormatToken *Next = Right.MatchingParen->getNextNonComment(); 3212 // An async arrow function, for example: `x = async () => foo();`, 3213 // as opposed to calling a function called async: `x = async();` 3214 if (Next && Next->is(TT_JsFatArrow)) 3215 return true; 3216 } 3217 if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) || 3218 (Right.is(TT_TemplateString) && Right.TokenText.startswith("}"))) 3219 return false; 3220 // In tagged template literals ("html`bar baz`"), there is no space between 3221 // the tag identifier and the template string. 3222 if (Keywords.IsJavaScriptIdentifier(Left, 3223 /* AcceptIdentifierName= */ false) && 3224 Right.is(TT_TemplateString)) 3225 return false; 3226 if (Right.is(tok::star) && 3227 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield)) 3228 return false; 3229 if (Right.isOneOf(tok::l_brace, tok::l_square) && 3230 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield, 3231 Keywords.kw_extends, Keywords.kw_implements)) 3232 return true; 3233 if (Right.is(tok::l_paren)) { 3234 // JS methods can use some keywords as names (e.g. `delete()`). 3235 if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo()) 3236 return false; 3237 // Valid JS method names can include keywords, e.g. `foo.delete()` or 3238 // `bar.instanceof()`. Recognize call positions by preceding period. 3239 if (Left.Previous && Left.Previous->is(tok::period) && 3240 Left.Tok.getIdentifierInfo()) 3241 return false; 3242 // Additional unary JavaScript operators that need a space after. 3243 if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof, 3244 tok::kw_void)) 3245 return true; 3246 } 3247 // `foo as const;` casts into a const type. 3248 if (Left.endsSequence(tok::kw_const, Keywords.kw_as)) { 3249 return false; 3250 } 3251 if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in, 3252 tok::kw_const) || 3253 // "of" is only a keyword if it appears after another identifier 3254 // (e.g. as "const x of y" in a for loop), or after a destructuring 3255 // operation (const [x, y] of z, const {a, b} of c). 3256 (Left.is(Keywords.kw_of) && Left.Previous && 3257 (Left.Previous->Tok.is(tok::identifier) || 3258 Left.Previous->isOneOf(tok::r_square, tok::r_brace)))) && 3259 (!Left.Previous || !Left.Previous->is(tok::period))) 3260 return true; 3261 if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && Left.Previous && 3262 Left.Previous->is(tok::period) && Right.is(tok::l_paren)) 3263 return false; 3264 if (Left.is(Keywords.kw_as) && 3265 Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren)) 3266 return true; 3267 if (Left.is(tok::kw_default) && Left.Previous && 3268 Left.Previous->is(tok::kw_export)) 3269 return true; 3270 if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace)) 3271 return true; 3272 if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion)) 3273 return false; 3274 if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator)) 3275 return false; 3276 if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) && 3277 Line.First->isOneOf(Keywords.kw_import, tok::kw_export)) 3278 return false; 3279 if (Left.is(tok::ellipsis)) 3280 return false; 3281 if (Left.is(TT_TemplateCloser) && 3282 !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square, 3283 Keywords.kw_implements, Keywords.kw_extends)) 3284 // Type assertions ('<type>expr') are not followed by whitespace. Other 3285 // locations that should have whitespace following are identified by the 3286 // above set of follower tokens. 3287 return false; 3288 if (Right.is(TT_JsNonNullAssertion)) 3289 return false; 3290 if (Left.is(TT_JsNonNullAssertion) && 3291 Right.isOneOf(Keywords.kw_as, Keywords.kw_in)) 3292 return true; // "x! as string", "x! in y" 3293 } else if (Style.Language == FormatStyle::LK_Java) { 3294 if (Left.is(tok::r_square) && Right.is(tok::l_brace)) 3295 return true; 3296 if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren)) 3297 return Style.SpaceBeforeParens != FormatStyle::SBPO_Never; 3298 if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private, 3299 tok::kw_protected) || 3300 Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract, 3301 Keywords.kw_native)) && 3302 Right.is(TT_TemplateOpener)) 3303 return true; 3304 } 3305 if (Left.is(TT_ImplicitStringLiteral)) 3306 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd(); 3307 if (Line.Type == LT_ObjCMethodDecl) { 3308 if (Left.is(TT_ObjCMethodSpecifier)) 3309 return true; 3310 if (Left.is(tok::r_paren) && canBeObjCSelectorComponent(Right)) 3311 // Don't space between ')' and <id> or ')' and 'new'. 'new' is not a 3312 // keyword in Objective-C, and '+ (instancetype)new;' is a standard class 3313 // method declaration. 3314 return false; 3315 } 3316 if (Line.Type == LT_ObjCProperty && 3317 (Right.is(tok::equal) || Left.is(tok::equal))) 3318 return false; 3319 3320 if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) || 3321 Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow)) 3322 return true; 3323 if (Right.is(TT_OverloadedOperatorLParen)) 3324 return spaceRequiredBeforeParens(Right); 3325 if (Left.is(tok::comma)) 3326 return true; 3327 if (Right.is(tok::comma)) 3328 return false; 3329 if (Right.is(TT_ObjCBlockLParen)) 3330 return true; 3331 if (Right.is(TT_CtorInitializerColon)) 3332 return Style.SpaceBeforeCtorInitializerColon; 3333 if (Right.is(TT_InheritanceColon) && !Style.SpaceBeforeInheritanceColon) 3334 return false; 3335 if (Right.is(TT_RangeBasedForLoopColon) && 3336 !Style.SpaceBeforeRangeBasedForLoopColon) 3337 return false; 3338 if (Left.is(TT_BitFieldColon)) 3339 return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both || 3340 Style.BitFieldColonSpacing == FormatStyle::BFCS_After; 3341 if (Right.is(tok::colon)) { 3342 if (Line.First->isOneOf(tok::kw_case, tok::kw_default) || 3343 !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi)) 3344 return false; 3345 if (Right.is(TT_ObjCMethodExpr)) 3346 return false; 3347 if (Left.is(tok::question)) 3348 return false; 3349 if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon)) 3350 return false; 3351 if (Right.is(TT_DictLiteral)) 3352 return Style.SpacesInContainerLiterals; 3353 if (Right.is(TT_AttributeColon)) 3354 return false; 3355 if (Right.is(TT_CSharpNamedArgumentColon)) 3356 return false; 3357 if (Right.is(TT_BitFieldColon)) 3358 return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both || 3359 Style.BitFieldColonSpacing == FormatStyle::BFCS_Before; 3360 return true; 3361 } 3362 if (Left.is(TT_UnaryOperator)) { 3363 if (!Right.is(tok::l_paren)) { 3364 // The alternative operators for ~ and ! are "compl" and "not". 3365 // If they are used instead, we do not want to combine them with 3366 // the token to the right, unless that is a left paren. 3367 if (Left.is(tok::exclaim) && Left.TokenText == "not") 3368 return true; 3369 if (Left.is(tok::tilde) && Left.TokenText == "compl") 3370 return true; 3371 // Lambda captures allow for a lone &, so "&]" needs to be properly 3372 // handled. 3373 if (Left.is(tok::amp) && Right.is(tok::r_square)) 3374 return Style.SpacesInSquareBrackets; 3375 } 3376 return (Style.SpaceAfterLogicalNot && Left.is(tok::exclaim)) || 3377 Right.is(TT_BinaryOperator); 3378 } 3379 3380 // If the next token is a binary operator or a selector name, we have 3381 // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly. 3382 if (Left.is(TT_CastRParen)) 3383 return Style.SpaceAfterCStyleCast || 3384 Right.isOneOf(TT_BinaryOperator, TT_SelectorName); 3385 3386 if (Left.is(tok::greater) && Right.is(tok::greater)) { 3387 if (Style.Language == FormatStyle::LK_TextProto || 3388 (Style.Language == FormatStyle::LK_Proto && Left.is(TT_DictLiteral))) 3389 return !Style.Cpp11BracedListStyle; 3390 return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) && 3391 (Style.Standard < FormatStyle::LS_Cpp11 || Style.SpacesInAngles); 3392 } 3393 if (Right.isOneOf(tok::arrow, tok::arrowstar, tok::periodstar) || 3394 Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) || 3395 (Right.is(tok::period) && Right.isNot(TT_DesignatedInitializerPeriod))) 3396 return false; 3397 if (!Style.SpaceBeforeAssignmentOperators && Left.isNot(TT_TemplateCloser) && 3398 Right.getPrecedence() == prec::Assignment) 3399 return false; 3400 if (Style.Language == FormatStyle::LK_Java && Right.is(tok::coloncolon) && 3401 (Left.is(tok::identifier) || Left.is(tok::kw_this))) 3402 return false; 3403 if (Right.is(tok::coloncolon) && Left.is(tok::identifier)) 3404 // Generally don't remove existing spaces between an identifier and "::". 3405 // The identifier might actually be a macro name such as ALWAYS_INLINE. If 3406 // this turns out to be too lenient, add analysis of the identifier itself. 3407 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd(); 3408 if (Right.is(tok::coloncolon) && 3409 !Left.isOneOf(tok::l_brace, tok::comment, tok::l_paren)) 3410 // Put a space between < and :: in vector< ::std::string > 3411 return (Left.is(TT_TemplateOpener) && 3412 (Style.Standard < FormatStyle::LS_Cpp11 || Style.SpacesInAngles)) || 3413 !(Left.isOneOf(tok::l_paren, tok::r_paren, tok::l_square, 3414 tok::kw___super, TT_TemplateOpener, 3415 TT_TemplateCloser)) || 3416 (Left.is(tok::l_paren) && Style.SpacesInParentheses); 3417 if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser))) 3418 return Style.SpacesInAngles; 3419 // Space before TT_StructuredBindingLSquare. 3420 if (Right.is(TT_StructuredBindingLSquare)) 3421 return !Left.isOneOf(tok::amp, tok::ampamp) || 3422 Style.PointerAlignment != FormatStyle::PAS_Right; 3423 // Space before & or && following a TT_StructuredBindingLSquare. 3424 if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) && 3425 Right.isOneOf(tok::amp, tok::ampamp)) 3426 return Style.PointerAlignment != FormatStyle::PAS_Left; 3427 if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) || 3428 (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && 3429 !Right.is(tok::r_paren))) 3430 return true; 3431 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) && 3432 Right.isNot(TT_FunctionTypeLParen)) 3433 return spaceRequiredBeforeParens(Right); 3434 if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) && 3435 Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen)) 3436 return false; 3437 if (Right.is(tok::less) && Left.isNot(tok::l_paren) && 3438 Line.startsWith(tok::hash)) 3439 return true; 3440 if (Right.is(TT_TrailingUnaryOperator)) 3441 return false; 3442 if (Left.is(TT_RegexLiteral)) 3443 return false; 3444 return spaceRequiredBetween(Line, Left, Right); 3445 } 3446 3447 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style. 3448 static bool isAllmanBrace(const FormatToken &Tok) { 3449 return Tok.is(tok::l_brace) && Tok.is(BK_Block) && 3450 !Tok.isOneOf(TT_ObjCBlockLBrace, TT_LambdaLBrace, TT_DictLiteral); 3451 } 3452 3453 // Returns 'true' if 'Tok' is an function argument. 3454 static bool IsFunctionArgument(const FormatToken &Tok) { 3455 return Tok.MatchingParen && Tok.MatchingParen->Next && 3456 Tok.MatchingParen->Next->isOneOf(tok::comma, tok::r_paren); 3457 } 3458 3459 static bool 3460 isItAnEmptyLambdaAllowed(const FormatToken &Tok, 3461 FormatStyle::ShortLambdaStyle ShortLambdaOption) { 3462 return Tok.Children.empty() && ShortLambdaOption != FormatStyle::SLS_None; 3463 } 3464 3465 static bool 3466 isItAInlineLambdaAllowed(const FormatToken &Tok, 3467 FormatStyle::ShortLambdaStyle ShortLambdaOption) { 3468 return (ShortLambdaOption == FormatStyle::SLS_Inline && 3469 IsFunctionArgument(Tok)) || 3470 (ShortLambdaOption == FormatStyle::SLS_All); 3471 } 3472 3473 static bool isOneChildWithoutMustBreakBefore(const FormatToken &Tok) { 3474 if (Tok.Children.size() != 1) 3475 return false; 3476 FormatToken *curElt = Tok.Children[0]->First; 3477 while (curElt) { 3478 if (curElt->MustBreakBefore) 3479 return false; 3480 curElt = curElt->Next; 3481 } 3482 return true; 3483 } 3484 static bool isAllmanLambdaBrace(const FormatToken &Tok) { 3485 return (Tok.is(tok::l_brace) && Tok.is(BK_Block) && 3486 !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral)); 3487 } 3488 3489 static bool isAllmanBraceIncludedBreakableLambda( 3490 const FormatToken &Tok, FormatStyle::ShortLambdaStyle ShortLambdaOption) { 3491 if (!isAllmanLambdaBrace(Tok)) 3492 return false; 3493 3494 if (isItAnEmptyLambdaAllowed(Tok, ShortLambdaOption)) 3495 return false; 3496 3497 return !isItAInlineLambdaAllowed(Tok, ShortLambdaOption) || 3498 !isOneChildWithoutMustBreakBefore(Tok); 3499 } 3500 3501 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line, 3502 const FormatToken &Right) { 3503 const FormatToken &Left = *Right.Previous; 3504 if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0) 3505 return true; 3506 3507 if (Style.isCSharp()) { 3508 if (Right.is(TT_CSharpNamedArgumentColon) || 3509 Left.is(TT_CSharpNamedArgumentColon)) 3510 return false; 3511 if (Right.is(TT_CSharpGenericTypeConstraint)) 3512 return true; 3513 } else if (Style.Language == FormatStyle::LK_JavaScript) { 3514 // FIXME: This might apply to other languages and token kinds. 3515 if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous && 3516 Left.Previous->is(tok::string_literal)) 3517 return true; 3518 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 && 3519 Left.Previous && Left.Previous->is(tok::equal) && 3520 Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export, 3521 tok::kw_const) && 3522 // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match 3523 // above. 3524 !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let)) 3525 // Object literals on the top level of a file are treated as "enum-style". 3526 // Each key/value pair is put on a separate line, instead of bin-packing. 3527 return true; 3528 if (Left.is(tok::l_brace) && Line.Level == 0 && 3529 (Line.startsWith(tok::kw_enum) || 3530 Line.startsWith(tok::kw_const, tok::kw_enum) || 3531 Line.startsWith(tok::kw_export, tok::kw_enum) || 3532 Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum))) 3533 // JavaScript top-level enum key/value pairs are put on separate lines 3534 // instead of bin-packing. 3535 return true; 3536 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) && Left.Previous && 3537 Left.Previous->is(TT_JsFatArrow)) { 3538 // JS arrow function (=> {...}). 3539 switch (Style.AllowShortLambdasOnASingleLine) { 3540 case FormatStyle::SLS_All: 3541 return false; 3542 case FormatStyle::SLS_None: 3543 return true; 3544 case FormatStyle::SLS_Empty: 3545 return !Left.Children.empty(); 3546 case FormatStyle::SLS_Inline: 3547 // allow one-lining inline (e.g. in function call args) and empty arrow 3548 // functions. 3549 return (Left.NestingLevel == 0 && Line.Level == 0) && 3550 !Left.Children.empty(); 3551 } 3552 llvm_unreachable("Unknown FormatStyle::ShortLambdaStyle enum"); 3553 } 3554 3555 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) && 3556 !Left.Children.empty()) 3557 // Support AllowShortFunctionsOnASingleLine for JavaScript. 3558 return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None || 3559 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty || 3560 (Left.NestingLevel == 0 && Line.Level == 0 && 3561 Style.AllowShortFunctionsOnASingleLine & 3562 FormatStyle::SFS_InlineOnly); 3563 } else if (Style.Language == FormatStyle::LK_Java) { 3564 if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next && 3565 Right.Next->is(tok::string_literal)) 3566 return true; 3567 } else if (Style.Language == FormatStyle::LK_Cpp || 3568 Style.Language == FormatStyle::LK_ObjC || 3569 Style.Language == FormatStyle::LK_Proto || 3570 Style.Language == FormatStyle::LK_TableGen || 3571 Style.Language == FormatStyle::LK_TextProto) { 3572 if (Left.isStringLiteral() && Right.isStringLiteral()) 3573 return true; 3574 } 3575 3576 // If the last token before a '}', ']', or ')' is a comma or a trailing 3577 // comment, the intention is to insert a line break after it in order to make 3578 // shuffling around entries easier. Import statements, especially in 3579 // JavaScript, can be an exception to this rule. 3580 if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) { 3581 const FormatToken *BeforeClosingBrace = nullptr; 3582 if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) || 3583 (Style.Language == FormatStyle::LK_JavaScript && 3584 Left.is(tok::l_paren))) && 3585 Left.isNot(BK_Block) && Left.MatchingParen) 3586 BeforeClosingBrace = Left.MatchingParen->Previous; 3587 else if (Right.MatchingParen && 3588 (Right.MatchingParen->isOneOf(tok::l_brace, 3589 TT_ArrayInitializerLSquare) || 3590 (Style.Language == FormatStyle::LK_JavaScript && 3591 Right.MatchingParen->is(tok::l_paren)))) 3592 BeforeClosingBrace = &Left; 3593 if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) || 3594 BeforeClosingBrace->isTrailingComment())) 3595 return true; 3596 } 3597 3598 if (Right.is(tok::comment)) 3599 return Left.isNot(BK_BracedInit) && Left.isNot(TT_CtorInitializerColon) && 3600 (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline); 3601 if (Left.isTrailingComment()) 3602 return true; 3603 if (Right.Previous->IsUnterminatedLiteral) 3604 return true; 3605 if (Right.is(tok::lessless) && Right.Next && 3606 Right.Previous->is(tok::string_literal) && 3607 Right.Next->is(tok::string_literal)) 3608 return true; 3609 // Can break after template<> declaration 3610 if (Right.Previous->ClosesTemplateDeclaration && 3611 Right.Previous->MatchingParen && 3612 Right.Previous->MatchingParen->NestingLevel == 0) { 3613 // Put concepts on the next line e.g. 3614 // template<typename T> 3615 // concept ... 3616 if (Right.is(tok::kw_concept)) 3617 return Style.BreakBeforeConceptDeclarations; 3618 return (Style.AlwaysBreakTemplateDeclarations == FormatStyle::BTDS_Yes); 3619 } 3620 if (Right.is(TT_CtorInitializerComma) && 3621 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma && 3622 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine) 3623 return true; 3624 if (Right.is(TT_CtorInitializerColon) && 3625 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma && 3626 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine) 3627 return true; 3628 // Break only if we have multiple inheritance. 3629 if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma && 3630 Right.is(TT_InheritanceComma)) 3631 return true; 3632 if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\"")) 3633 // Multiline raw string literals are special wrt. line breaks. The author 3634 // has made a deliberate choice and might have aligned the contents of the 3635 // string literal accordingly. Thus, we try keep existing line breaks. 3636 return Right.IsMultiline && Right.NewlinesBefore > 0; 3637 if ((Right.Previous->is(tok::l_brace) || 3638 (Right.Previous->is(tok::less) && Right.Previous->Previous && 3639 Right.Previous->Previous->is(tok::equal))) && 3640 Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) { 3641 // Don't put enums or option definitions onto single lines in protocol 3642 // buffers. 3643 return true; 3644 } 3645 if (Right.is(TT_InlineASMBrace)) 3646 return Right.HasUnescapedNewline; 3647 3648 auto ShortLambdaOption = Style.AllowShortLambdasOnASingleLine; 3649 if (Style.BraceWrapping.BeforeLambdaBody && 3650 (isAllmanBraceIncludedBreakableLambda(Left, ShortLambdaOption) || 3651 isAllmanBraceIncludedBreakableLambda(Right, ShortLambdaOption))) { 3652 return true; 3653 } 3654 3655 if (isAllmanBrace(Left) || isAllmanBrace(Right)) 3656 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) || 3657 (Line.startsWith(tok::kw_typedef, tok::kw_enum) && 3658 Style.BraceWrapping.AfterEnum) || 3659 (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) || 3660 (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct); 3661 if (Left.is(TT_ObjCBlockLBrace) && 3662 Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) 3663 return true; 3664 3665 if (Left.is(TT_LambdaLBrace)) { 3666 if (IsFunctionArgument(Left) && 3667 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline) 3668 return false; 3669 3670 if (Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_None || 3671 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline || 3672 (!Left.Children.empty() && 3673 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Empty)) 3674 return true; 3675 } 3676 3677 // Put multiple Java annotation on a new line. 3678 if ((Style.Language == FormatStyle::LK_Java || 3679 Style.Language == FormatStyle::LK_JavaScript) && 3680 Left.is(TT_LeadingJavaAnnotation) && 3681 Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) && 3682 (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations)) 3683 return true; 3684 3685 if (Right.is(TT_ProtoExtensionLSquare)) 3686 return true; 3687 3688 // In text proto instances if a submessage contains at least 2 entries and at 3689 // least one of them is a submessage, like A { ... B { ... } ... }, 3690 // put all of the entries of A on separate lines by forcing the selector of 3691 // the submessage B to be put on a newline. 3692 // 3693 // Example: these can stay on one line: 3694 // a { scalar_1: 1 scalar_2: 2 } 3695 // a { b { key: value } } 3696 // 3697 // and these entries need to be on a new line even if putting them all in one 3698 // line is under the column limit: 3699 // a { 3700 // scalar: 1 3701 // b { key: value } 3702 // } 3703 // 3704 // We enforce this by breaking before a submessage field that has previous 3705 // siblings, *and* breaking before a field that follows a submessage field. 3706 // 3707 // Be careful to exclude the case [proto.ext] { ... } since the `]` is 3708 // the TT_SelectorName there, but we don't want to break inside the brackets. 3709 // 3710 // Another edge case is @submessage { key: value }, which is a common 3711 // substitution placeholder. In this case we want to keep `@` and `submessage` 3712 // together. 3713 // 3714 // We ensure elsewhere that extensions are always on their own line. 3715 if ((Style.Language == FormatStyle::LK_Proto || 3716 Style.Language == FormatStyle::LK_TextProto) && 3717 Right.is(TT_SelectorName) && !Right.is(tok::r_square) && Right.Next) { 3718 // Keep `@submessage` together in: 3719 // @submessage { key: value } 3720 if (Right.Previous && Right.Previous->is(tok::at)) 3721 return false; 3722 // Look for the scope opener after selector in cases like: 3723 // selector { ... 3724 // selector: { ... 3725 // selector: @base { ... 3726 FormatToken *LBrace = Right.Next; 3727 if (LBrace && LBrace->is(tok::colon)) { 3728 LBrace = LBrace->Next; 3729 if (LBrace && LBrace->is(tok::at)) { 3730 LBrace = LBrace->Next; 3731 if (LBrace) 3732 LBrace = LBrace->Next; 3733 } 3734 } 3735 if (LBrace && 3736 // The scope opener is one of {, [, <: 3737 // selector { ... } 3738 // selector [ ... ] 3739 // selector < ... > 3740 // 3741 // In case of selector { ... }, the l_brace is TT_DictLiteral. 3742 // In case of an empty selector {}, the l_brace is not TT_DictLiteral, 3743 // so we check for immediately following r_brace. 3744 ((LBrace->is(tok::l_brace) && 3745 (LBrace->is(TT_DictLiteral) || 3746 (LBrace->Next && LBrace->Next->is(tok::r_brace)))) || 3747 LBrace->is(TT_ArrayInitializerLSquare) || LBrace->is(tok::less))) { 3748 // If Left.ParameterCount is 0, then this submessage entry is not the 3749 // first in its parent submessage, and we want to break before this entry. 3750 // If Left.ParameterCount is greater than 0, then its parent submessage 3751 // might contain 1 or more entries and we want to break before this entry 3752 // if it contains at least 2 entries. We deal with this case later by 3753 // detecting and breaking before the next entry in the parent submessage. 3754 if (Left.ParameterCount == 0) 3755 return true; 3756 // However, if this submessage is the first entry in its parent 3757 // submessage, Left.ParameterCount might be 1 in some cases. 3758 // We deal with this case later by detecting an entry 3759 // following a closing paren of this submessage. 3760 } 3761 3762 // If this is an entry immediately following a submessage, it will be 3763 // preceded by a closing paren of that submessage, like in: 3764 // left---. .---right 3765 // v v 3766 // sub: { ... } key: value 3767 // If there was a comment between `}` an `key` above, then `key` would be 3768 // put on a new line anyways. 3769 if (Left.isOneOf(tok::r_brace, tok::greater, tok::r_square)) 3770 return true; 3771 } 3772 3773 // Deal with lambda arguments in C++ - we want consistent line breaks whether 3774 // they happen to be at arg0, arg1 or argN. The selection is a bit nuanced 3775 // as aggressive line breaks are placed when the lambda is not the last arg. 3776 if ((Style.Language == FormatStyle::LK_Cpp || 3777 Style.Language == FormatStyle::LK_ObjC) && 3778 Left.is(tok::l_paren) && Left.BlockParameterCount > 0 && 3779 !Right.isOneOf(tok::l_paren, TT_LambdaLSquare)) { 3780 // Multiple lambdas in the same function call force line breaks. 3781 if (Left.BlockParameterCount > 1) 3782 return true; 3783 3784 // A lambda followed by another arg forces a line break. 3785 if (!Left.Role) 3786 return false; 3787 auto Comma = Left.Role->lastComma(); 3788 if (!Comma) 3789 return false; 3790 auto Next = Comma->getNextNonComment(); 3791 if (!Next) 3792 return false; 3793 if (!Next->isOneOf(TT_LambdaLSquare, tok::l_brace, tok::caret)) 3794 return true; 3795 } 3796 3797 return false; 3798 } 3799 3800 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line, 3801 const FormatToken &Right) { 3802 const FormatToken &Left = *Right.Previous; 3803 // Language-specific stuff. 3804 if (Style.isCSharp()) { 3805 if (Left.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon) || 3806 Right.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon)) 3807 return false; 3808 // Only break after commas for generic type constraints. 3809 if (Line.First->is(TT_CSharpGenericTypeConstraint)) 3810 return Left.is(TT_CSharpGenericTypeConstraintComma); 3811 } else if (Style.Language == FormatStyle::LK_Java) { 3812 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends, 3813 Keywords.kw_implements)) 3814 return false; 3815 if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends, 3816 Keywords.kw_implements)) 3817 return true; 3818 } else if (Style.Language == FormatStyle::LK_JavaScript) { 3819 const FormatToken *NonComment = Right.getPreviousNonComment(); 3820 if (NonComment && 3821 NonComment->isOneOf( 3822 tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break, 3823 tok::kw_throw, Keywords.kw_interface, Keywords.kw_type, 3824 tok::kw_static, tok::kw_public, tok::kw_private, tok::kw_protected, 3825 Keywords.kw_readonly, Keywords.kw_abstract, Keywords.kw_get, 3826 Keywords.kw_set, Keywords.kw_async, Keywords.kw_await)) 3827 return false; // Otherwise automatic semicolon insertion would trigger. 3828 if (Right.NestingLevel == 0 && 3829 (Left.Tok.getIdentifierInfo() || 3830 Left.isOneOf(tok::r_square, tok::r_paren)) && 3831 Right.isOneOf(tok::l_square, tok::l_paren)) 3832 return false; // Otherwise automatic semicolon insertion would trigger. 3833 if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace)) 3834 return false; 3835 if (Left.is(TT_JsTypeColon)) 3836 return true; 3837 // Don't wrap between ":" and "!" of a strict prop init ("field!: type;"). 3838 if (Left.is(tok::exclaim) && Right.is(tok::colon)) 3839 return false; 3840 // Look for is type annotations like: 3841 // function f(): a is B { ... } 3842 // Do not break before is in these cases. 3843 if (Right.is(Keywords.kw_is)) { 3844 const FormatToken *Next = Right.getNextNonComment(); 3845 // If `is` is followed by a colon, it's likely that it's a dict key, so 3846 // ignore it for this check. 3847 // For example this is common in Polymer: 3848 // Polymer({ 3849 // is: 'name', 3850 // ... 3851 // }); 3852 if (!Next || !Next->is(tok::colon)) 3853 return false; 3854 } 3855 if (Left.is(Keywords.kw_in)) 3856 return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None; 3857 if (Right.is(Keywords.kw_in)) 3858 return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None; 3859 if (Right.is(Keywords.kw_as)) 3860 return false; // must not break before as in 'x as type' casts 3861 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_infer)) { 3862 // extends and infer can appear as keywords in conditional types: 3863 // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types 3864 // do not break before them, as the expressions are subject to ASI. 3865 return false; 3866 } 3867 if (Left.is(Keywords.kw_as)) 3868 return true; 3869 if (Left.is(TT_JsNonNullAssertion)) 3870 return true; 3871 if (Left.is(Keywords.kw_declare) && 3872 Right.isOneOf(Keywords.kw_module, tok::kw_namespace, 3873 Keywords.kw_function, tok::kw_class, tok::kw_enum, 3874 Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var, 3875 Keywords.kw_let, tok::kw_const)) 3876 // See grammar for 'declare' statements at: 3877 // https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#A.10 3878 return false; 3879 if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) && 3880 Right.isOneOf(tok::identifier, tok::string_literal)) 3881 return false; // must not break in "module foo { ...}" 3882 if (Right.is(TT_TemplateString) && Right.closesScope()) 3883 return false; 3884 // Don't split tagged template literal so there is a break between the tag 3885 // identifier and template string. 3886 if (Left.is(tok::identifier) && Right.is(TT_TemplateString)) { 3887 return false; 3888 } 3889 if (Left.is(TT_TemplateString) && Left.opensScope()) 3890 return true; 3891 } 3892 3893 if (Left.is(tok::at)) 3894 return false; 3895 if (Left.Tok.getObjCKeywordID() == tok::objc_interface) 3896 return false; 3897 if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation)) 3898 return !Right.is(tok::l_paren); 3899 if (Right.is(TT_PointerOrReference)) 3900 return Line.IsMultiVariableDeclStmt || 3901 (Style.PointerAlignment == FormatStyle::PAS_Right && 3902 (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName))); 3903 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) || 3904 Right.is(tok::kw_operator)) 3905 return true; 3906 if (Left.is(TT_PointerOrReference)) 3907 return false; 3908 if (Right.isTrailingComment()) 3909 // We rely on MustBreakBefore being set correctly here as we should not 3910 // change the "binding" behavior of a comment. 3911 // The first comment in a braced lists is always interpreted as belonging to 3912 // the first list element. Otherwise, it should be placed outside of the 3913 // list. 3914 return Left.is(BK_BracedInit) || 3915 (Left.is(TT_CtorInitializerColon) && 3916 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon); 3917 if (Left.is(tok::question) && Right.is(tok::colon)) 3918 return false; 3919 if (Right.is(TT_ConditionalExpr) || Right.is(tok::question)) 3920 return Style.BreakBeforeTernaryOperators; 3921 if (Left.is(TT_ConditionalExpr) || Left.is(tok::question)) 3922 return !Style.BreakBeforeTernaryOperators; 3923 if (Left.is(TT_InheritanceColon)) 3924 return Style.BreakInheritanceList == FormatStyle::BILS_AfterColon; 3925 if (Right.is(TT_InheritanceColon)) 3926 return Style.BreakInheritanceList != FormatStyle::BILS_AfterColon; 3927 if (Right.is(TT_ObjCMethodExpr) && !Right.is(tok::r_square) && 3928 Left.isNot(TT_SelectorName)) 3929 return true; 3930 3931 if (Right.is(tok::colon) && 3932 !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon)) 3933 return false; 3934 if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) { 3935 if (Style.Language == FormatStyle::LK_Proto || 3936 Style.Language == FormatStyle::LK_TextProto) { 3937 if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral()) 3938 return false; 3939 // Prevent cases like: 3940 // 3941 // submessage: 3942 // { key: valueeeeeeeeeeee } 3943 // 3944 // when the snippet does not fit into one line. 3945 // Prefer: 3946 // 3947 // submessage: { 3948 // key: valueeeeeeeeeeee 3949 // } 3950 // 3951 // instead, even if it is longer by one line. 3952 // 3953 // Note that this allows allows the "{" to go over the column limit 3954 // when the column limit is just between ":" and "{", but that does 3955 // not happen too often and alternative formattings in this case are 3956 // not much better. 3957 // 3958 // The code covers the cases: 3959 // 3960 // submessage: { ... } 3961 // submessage: < ... > 3962 // repeated: [ ... ] 3963 if (((Right.is(tok::l_brace) || Right.is(tok::less)) && 3964 Right.is(TT_DictLiteral)) || 3965 Right.is(TT_ArrayInitializerLSquare)) 3966 return false; 3967 } 3968 return true; 3969 } 3970 if (Right.is(tok::r_square) && Right.MatchingParen && 3971 Right.MatchingParen->is(TT_ProtoExtensionLSquare)) 3972 return false; 3973 if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next && 3974 Right.Next->is(TT_ObjCMethodExpr))) 3975 return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls. 3976 if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty) 3977 return true; 3978 if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen)) 3979 return true; 3980 if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen, 3981 TT_OverloadedOperator)) 3982 return false; 3983 if (Left.is(TT_RangeBasedForLoopColon)) 3984 return true; 3985 if (Right.is(TT_RangeBasedForLoopColon)) 3986 return false; 3987 if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener)) 3988 return true; 3989 if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) || 3990 Left.is(tok::kw_operator)) 3991 return false; 3992 if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) && 3993 Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0) 3994 return false; 3995 if (Left.is(tok::equal) && Right.is(tok::l_brace) && 3996 !Style.Cpp11BracedListStyle) 3997 return false; 3998 if (Left.is(tok::l_paren) && 3999 Left.isOneOf(TT_AttributeParen, TT_TypeDeclarationParen)) 4000 return false; 4001 if (Left.is(tok::l_paren) && Left.Previous && 4002 (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen))) 4003 return false; 4004 if (Right.is(TT_ImplicitStringLiteral)) 4005 return false; 4006 4007 if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser)) 4008 return false; 4009 if (Right.is(tok::r_square) && Right.MatchingParen && 4010 Right.MatchingParen->is(TT_LambdaLSquare)) 4011 return false; 4012 4013 // We only break before r_brace if there was a corresponding break before 4014 // the l_brace, which is tracked by BreakBeforeClosingBrace. 4015 if (Right.is(tok::r_brace)) 4016 return Right.MatchingParen && Right.MatchingParen->is(BK_Block); 4017 4018 // Allow breaking after a trailing annotation, e.g. after a method 4019 // declaration. 4020 if (Left.is(TT_TrailingAnnotation)) 4021 return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren, 4022 tok::less, tok::coloncolon); 4023 4024 if (Right.is(tok::kw___attribute) || 4025 (Right.is(tok::l_square) && Right.is(TT_AttributeSquare))) 4026 return !Left.is(TT_AttributeSquare); 4027 4028 if (Left.is(tok::identifier) && Right.is(tok::string_literal)) 4029 return true; 4030 4031 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral)) 4032 return true; 4033 4034 if (Left.is(TT_CtorInitializerColon)) 4035 return Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon; 4036 if (Right.is(TT_CtorInitializerColon)) 4037 return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon; 4038 if (Left.is(TT_CtorInitializerComma) && 4039 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) 4040 return false; 4041 if (Right.is(TT_CtorInitializerComma) && 4042 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) 4043 return true; 4044 if (Left.is(TT_InheritanceComma) && 4045 Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma) 4046 return false; 4047 if (Right.is(TT_InheritanceComma) && 4048 Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma) 4049 return true; 4050 if ((Left.is(tok::greater) && Right.is(tok::greater)) || 4051 (Left.is(tok::less) && Right.is(tok::less))) 4052 return false; 4053 if (Right.is(TT_BinaryOperator) && 4054 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None && 4055 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All || 4056 Right.getPrecedence() != prec::Assignment)) 4057 return true; 4058 if (Left.is(TT_ArrayInitializerLSquare)) 4059 return true; 4060 if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const)) 4061 return true; 4062 if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) && 4063 !Left.isOneOf(tok::arrowstar, tok::lessless) && 4064 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All && 4065 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None || 4066 Left.getPrecedence() == prec::Assignment)) 4067 return true; 4068 if ((Left.is(TT_AttributeSquare) && Right.is(tok::l_square)) || 4069 (Left.is(tok::r_square) && Right.is(TT_AttributeSquare))) 4070 return false; 4071 4072 auto ShortLambdaOption = Style.AllowShortLambdasOnASingleLine; 4073 if (Style.BraceWrapping.BeforeLambdaBody) { 4074 if (isAllmanLambdaBrace(Left)) 4075 return !isItAnEmptyLambdaAllowed(Left, ShortLambdaOption); 4076 if (isAllmanLambdaBrace(Right)) 4077 return !isItAnEmptyLambdaAllowed(Right, ShortLambdaOption); 4078 } 4079 4080 return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace, 4081 tok::kw_class, tok::kw_struct, tok::comment) || 4082 Right.isMemberAccess() || 4083 Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless, 4084 tok::colon, tok::l_square, tok::at) || 4085 (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT_LambdaLBrace)) || 4086 (Left.is(tok::r_paren) && 4087 Right.isOneOf(tok::identifier, tok::kw_const)) || 4088 (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) || 4089 (Left.is(TT_TemplateOpener) && !Right.is(TT_TemplateCloser)); 4090 } 4091 4092 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) { 4093 llvm::errs() << "AnnotatedTokens(L=" << Line.Level << "):\n"; 4094 const FormatToken *Tok = Line.First; 4095 while (Tok) { 4096 llvm::errs() << " M=" << Tok->MustBreakBefore 4097 << " C=" << Tok->CanBreakBefore 4098 << " T=" << getTokenTypeName(Tok->getType()) 4099 << " S=" << Tok->SpacesRequiredBefore 4100 << " F=" << Tok->Finalized << " B=" << Tok->BlockParameterCount 4101 << " BK=" << Tok->getBlockKind() << " P=" << Tok->SplitPenalty 4102 << " Name=" << Tok->Tok.getName() << " L=" << Tok->TotalLength 4103 << " PPK=" << Tok->getPackingKind() << " FakeLParens="; 4104 for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i) 4105 llvm::errs() << Tok->FakeLParens[i] << "/"; 4106 llvm::errs() << " FakeRParens=" << Tok->FakeRParens; 4107 llvm::errs() << " II=" << Tok->Tok.getIdentifierInfo(); 4108 llvm::errs() << " Text='" << Tok->TokenText << "'\n"; 4109 if (!Tok->Next) 4110 assert(Tok == Line.Last); 4111 Tok = Tok->Next; 4112 } 4113 llvm::errs() << "----\n"; 4114 } 4115 4116 } // namespace format 4117 } // namespace clang 4118