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