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