1 //===--- TokenAnnotator.cpp - Format C++ code -----------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// 10 /// \file 11 /// \brief This file implements a token annotator, i.e. creates 12 /// \c AnnotatedTokens out of \c FormatTokens with required extra information. 13 /// 14 //===----------------------------------------------------------------------===// 15 16 #include "TokenAnnotator.h" 17 #include "clang/Basic/SourceManager.h" 18 #include "llvm/ADT/SmallPtrSet.h" 19 #include "llvm/Support/Debug.h" 20 21 #define DEBUG_TYPE "format-token-annotator" 22 23 namespace clang { 24 namespace format { 25 26 namespace { 27 28 /// \brief A parser that gathers additional information about tokens. 29 /// 30 /// The \c TokenAnnotator tries to match parenthesis and square brakets and 31 /// store a parenthesis levels. It also tries to resolve matching "<" and ">" 32 /// into template parameter lists. 33 class AnnotatingParser { 34 public: 35 AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line, 36 const AdditionalKeywords &Keywords) 37 : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false), 38 Keywords(Keywords) { 39 Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false)); 40 resetTokenMetadata(CurrentToken); 41 } 42 43 private: 44 bool parseAngle() { 45 if (!CurrentToken || !CurrentToken->Previous) 46 return false; 47 if (NonTemplateLess.count(CurrentToken->Previous)) 48 return false; 49 50 const FormatToken& Previous = *CurrentToken->Previous; 51 if (Previous.Previous) { 52 if (Previous.Previous->Tok.isLiteral()) 53 return false; 54 if (Previous.Previous->is(tok::r_paren) && Contexts.size() > 1 && 55 (!Previous.Previous->MatchingParen || 56 !Previous.Previous->MatchingParen->is(TT_OverloadedOperatorLParen))) 57 return false; 58 } 59 60 FormatToken *Left = CurrentToken->Previous; 61 Left->ParentBracket = Contexts.back().ContextKind; 62 ScopedContextCreator ContextCreator(*this, tok::less, 12); 63 64 // If this angle is in the context of an expression, we need to be more 65 // hesitant to detect it as opening template parameters. 66 bool InExprContext = Contexts.back().IsExpression; 67 68 Contexts.back().IsExpression = false; 69 // If there's a template keyword before the opening angle bracket, this is a 70 // template parameter, not an argument. 71 Contexts.back().InTemplateArgument = 72 Left->Previous && Left->Previous->Tok.isNot(tok::kw_template); 73 74 if (Style.Language == FormatStyle::LK_Java && 75 CurrentToken->is(tok::question)) 76 next(); 77 78 while (CurrentToken) { 79 if (CurrentToken->is(tok::greater)) { 80 Left->MatchingParen = CurrentToken; 81 CurrentToken->MatchingParen = Left; 82 CurrentToken->Type = TT_TemplateCloser; 83 next(); 84 return true; 85 } 86 if (CurrentToken->is(tok::question) && 87 Style.Language == FormatStyle::LK_Java) { 88 next(); 89 continue; 90 } 91 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace) || 92 (CurrentToken->isOneOf(tok::colon, tok::question) && InExprContext)) 93 return false; 94 // If a && or || is found and interpreted as a binary operator, this set 95 // of angles is likely part of something like "a < b && c > d". If the 96 // angles are inside an expression, the ||/&& might also be a binary 97 // operator that was misinterpreted because we are parsing template 98 // parameters. 99 // FIXME: This is getting out of hand, write a decent parser. 100 if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) && 101 CurrentToken->Previous->is(TT_BinaryOperator) && 102 Contexts[Contexts.size() - 2].IsExpression && 103 !Line.startsWith(tok::kw_template)) 104 return false; 105 updateParameterCount(Left, CurrentToken); 106 if (!consumeToken()) 107 return false; 108 } 109 return false; 110 } 111 112 bool parseParens(bool LookForDecls = false) { 113 if (!CurrentToken) 114 return false; 115 FormatToken *Left = CurrentToken->Previous; 116 Left->ParentBracket = Contexts.back().ContextKind; 117 ScopedContextCreator ContextCreator(*this, tok::l_paren, 1); 118 119 // FIXME: This is a bit of a hack. Do better. 120 Contexts.back().ColonIsForRangeExpr = 121 Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr; 122 123 bool StartsObjCMethodExpr = false; 124 if (CurrentToken->is(tok::caret)) { 125 // (^ can start a block type. 126 Left->Type = TT_ObjCBlockLParen; 127 } else if (FormatToken *MaybeSel = Left->Previous) { 128 // @selector( starts a selector. 129 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous && 130 MaybeSel->Previous->is(tok::at)) { 131 StartsObjCMethodExpr = true; 132 } 133 } 134 135 if (Left->is(TT_OverloadedOperatorLParen)) { 136 Contexts.back().IsExpression = false; 137 } else if (Left->Previous && 138 (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype, 139 tok::kw_if, tok::kw_while, tok::l_paren, 140 tok::comma) || 141 Left->Previous->is(TT_BinaryOperator))) { 142 // static_assert, if and while usually contain expressions. 143 Contexts.back().IsExpression = true; 144 } else if (Left->Previous && Left->Previous->is(tok::r_square) && 145 Left->Previous->MatchingParen && 146 Left->Previous->MatchingParen->is(TT_LambdaLSquare)) { 147 // This is a parameter list of a lambda expression. 148 Contexts.back().IsExpression = false; 149 } else if (Line.InPPDirective && 150 (!Left->Previous || !Left->Previous->is(tok::identifier))) { 151 Contexts.back().IsExpression = true; 152 } else if (Contexts[Contexts.size() - 2].CaretFound) { 153 // This is the parameter list of an ObjC block. 154 Contexts.back().IsExpression = false; 155 } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) { 156 Left->Type = TT_AttributeParen; 157 } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) { 158 // The first argument to a foreach macro is a declaration. 159 Contexts.back().IsForEachMacro = true; 160 Contexts.back().IsExpression = false; 161 } else if (Left->Previous && Left->Previous->MatchingParen && 162 Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) { 163 Contexts.back().IsExpression = false; 164 } else if (!Line.MustBeDeclaration && !Line.InPPDirective) { 165 bool IsForOrCatch = 166 Left->Previous && Left->Previous->isOneOf(tok::kw_for, tok::kw_catch); 167 Contexts.back().IsExpression = !IsForOrCatch; 168 } 169 170 if (StartsObjCMethodExpr) { 171 Contexts.back().ColonIsObjCMethodExpr = true; 172 Left->Type = TT_ObjCMethodExpr; 173 } 174 175 bool MightBeFunctionType = CurrentToken->isOneOf(tok::star, tok::amp) && 176 !Contexts[Contexts.size() - 2].IsExpression; 177 bool HasMultipleLines = false; 178 bool HasMultipleParametersOnALine = false; 179 bool MightBeObjCForRangeLoop = 180 Left->Previous && Left->Previous->is(tok::kw_for); 181 while (CurrentToken) { 182 // LookForDecls is set when "if (" has been seen. Check for 183 // 'identifier' '*' 'identifier' followed by not '=' -- this 184 // '*' has to be a binary operator but determineStarAmpUsage() will 185 // categorize it as an unary operator, so set the right type here. 186 if (LookForDecls && CurrentToken->Next) { 187 FormatToken *Prev = CurrentToken->getPreviousNonComment(); 188 if (Prev) { 189 FormatToken *PrevPrev = Prev->getPreviousNonComment(); 190 FormatToken *Next = CurrentToken->Next; 191 if (PrevPrev && PrevPrev->is(tok::identifier) && 192 Prev->isOneOf(tok::star, tok::amp, tok::ampamp) && 193 CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) { 194 Prev->Type = TT_BinaryOperator; 195 LookForDecls = false; 196 } 197 } 198 } 199 200 if (CurrentToken->Previous->is(TT_PointerOrReference) && 201 CurrentToken->Previous->Previous->isOneOf(tok::l_paren, 202 tok::coloncolon)) 203 MightBeFunctionType = true; 204 if (CurrentToken->Previous->is(TT_BinaryOperator)) 205 Contexts.back().IsExpression = true; 206 if (CurrentToken->is(tok::r_paren)) { 207 if (MightBeFunctionType && CurrentToken->Next && 208 (CurrentToken->Next->is(tok::l_paren) || 209 (CurrentToken->Next->is(tok::l_square) && 210 Line.MustBeDeclaration))) 211 Left->Type = TT_FunctionTypeLParen; 212 Left->MatchingParen = CurrentToken; 213 CurrentToken->MatchingParen = Left; 214 215 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) && 216 Left->Previous && Left->Previous->is(tok::l_paren)) { 217 // Detect the case where macros are used to generate lambdas or 218 // function bodies, e.g.: 219 // auto my_lambda = MARCO((Type *type, int i) { .. body .. }); 220 for (FormatToken *Tok = Left; Tok != CurrentToken; Tok = Tok->Next) { 221 if (Tok->is(TT_BinaryOperator) && 222 Tok->isOneOf(tok::star, tok::amp, tok::ampamp)) 223 Tok->Type = TT_PointerOrReference; 224 } 225 } 226 227 if (StartsObjCMethodExpr) { 228 CurrentToken->Type = TT_ObjCMethodExpr; 229 if (Contexts.back().FirstObjCSelectorName) { 230 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 231 Contexts.back().LongestObjCSelectorName; 232 } 233 } 234 235 if (Left->is(TT_AttributeParen)) 236 CurrentToken->Type = TT_AttributeParen; 237 if (Left->Previous && Left->Previous->is(TT_JavaAnnotation)) 238 CurrentToken->Type = TT_JavaAnnotation; 239 if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation)) 240 CurrentToken->Type = TT_LeadingJavaAnnotation; 241 242 if (!HasMultipleLines) 243 Left->PackingKind = PPK_Inconclusive; 244 else if (HasMultipleParametersOnALine) 245 Left->PackingKind = PPK_BinPacked; 246 else 247 Left->PackingKind = PPK_OnePerLine; 248 249 next(); 250 return true; 251 } 252 if (CurrentToken->isOneOf(tok::r_square, tok::r_brace)) 253 return false; 254 255 if (CurrentToken->is(tok::l_brace)) 256 Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen 257 if (CurrentToken->is(tok::comma) && CurrentToken->Next && 258 !CurrentToken->Next->HasUnescapedNewline && 259 !CurrentToken->Next->isTrailingComment()) 260 HasMultipleParametersOnALine = true; 261 if (CurrentToken->isOneOf(tok::kw_const, tok::kw_auto) || 262 CurrentToken->isSimpleTypeSpecifier()) 263 Contexts.back().IsExpression = false; 264 if (CurrentToken->isOneOf(tok::semi, tok::colon)) 265 MightBeObjCForRangeLoop = false; 266 if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) 267 CurrentToken->Type = TT_ObjCForIn; 268 // When we discover a 'new', we set CanBeExpression to 'false' in order to 269 // parse the type correctly. Reset that after a comma. 270 if (CurrentToken->is(tok::comma)) 271 Contexts.back().CanBeExpression = true; 272 273 FormatToken *Tok = CurrentToken; 274 if (!consumeToken()) 275 return false; 276 updateParameterCount(Left, Tok); 277 if (CurrentToken && CurrentToken->HasUnescapedNewline) 278 HasMultipleLines = true; 279 } 280 return false; 281 } 282 283 bool parseSquare() { 284 if (!CurrentToken) 285 return false; 286 287 // A '[' could be an index subscript (after an identifier or after 288 // ')' or ']'), it could be the start of an Objective-C method 289 // expression, or it could the start of an Objective-C array literal. 290 FormatToken *Left = CurrentToken->Previous; 291 Left->ParentBracket = Contexts.back().ContextKind; 292 FormatToken *Parent = Left->getPreviousNonComment(); 293 bool StartsObjCMethodExpr = 294 Style.Language == FormatStyle::LK_Cpp && 295 Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) && 296 CurrentToken->isNot(tok::l_brace) && 297 (!Parent || 298 Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren, 299 tok::kw_return, tok::kw_throw) || 300 Parent->isUnaryOperator() || 301 Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) || 302 getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown); 303 bool ColonFound = false; 304 305 unsigned BindingIncrease = 1; 306 if (Left->is(TT_Unknown)) { 307 if (StartsObjCMethodExpr) { 308 Left->Type = TT_ObjCMethodExpr; 309 } else if (Style.Language == FormatStyle::LK_JavaScript && Parent && 310 Contexts.back().ContextKind == tok::l_brace && 311 Parent->isOneOf(tok::l_brace, tok::comma)) { 312 Left->Type = TT_JsComputedPropertyName; 313 } else if (Style.Language == FormatStyle::LK_Proto || 314 (Parent && 315 Parent->isOneOf(TT_BinaryOperator, tok::at, tok::comma, 316 tok::l_paren, tok::l_square, tok::question, 317 tok::colon, tok::kw_return, 318 // Should only be relevant to JavaScript: 319 tok::kw_default))) { 320 Left->Type = TT_ArrayInitializerLSquare; 321 } else { 322 BindingIncrease = 10; 323 Left->Type = TT_ArraySubscriptLSquare; 324 } 325 } 326 327 ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease); 328 Contexts.back().IsExpression = true; 329 Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr; 330 331 while (CurrentToken) { 332 if (CurrentToken->is(tok::r_square)) { 333 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) && 334 Left->is(TT_ObjCMethodExpr)) { 335 // An ObjC method call is rarely followed by an open parenthesis. 336 // FIXME: Do we incorrectly label ":" with this? 337 StartsObjCMethodExpr = false; 338 Left->Type = TT_Unknown; 339 } 340 if (StartsObjCMethodExpr && CurrentToken->Previous != Left) { 341 CurrentToken->Type = TT_ObjCMethodExpr; 342 // determineStarAmpUsage() thinks that '*' '[' is allocating an 343 // array of pointers, but if '[' starts a selector then '*' is a 344 // binary operator. 345 if (Parent && Parent->is(TT_PointerOrReference)) 346 Parent->Type = TT_BinaryOperator; 347 } 348 Left->MatchingParen = CurrentToken; 349 CurrentToken->MatchingParen = Left; 350 if (Contexts.back().FirstObjCSelectorName) { 351 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 352 Contexts.back().LongestObjCSelectorName; 353 if (Left->BlockParameterCount > 1) 354 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0; 355 } 356 next(); 357 return true; 358 } 359 if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace)) 360 return false; 361 if (CurrentToken->is(tok::colon)) { 362 if (Left->is(TT_ArraySubscriptLSquare)) { 363 Left->Type = TT_ObjCMethodExpr; 364 StartsObjCMethodExpr = true; 365 Contexts.back().ColonIsObjCMethodExpr = true; 366 if (Parent && Parent->is(tok::r_paren)) 367 Parent->Type = TT_CastRParen; 368 } 369 ColonFound = true; 370 } 371 if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) && 372 !ColonFound) 373 Left->Type = TT_ArrayInitializerLSquare; 374 FormatToken *Tok = CurrentToken; 375 if (!consumeToken()) 376 return false; 377 updateParameterCount(Left, Tok); 378 } 379 return false; 380 } 381 382 bool parseBrace() { 383 if (CurrentToken) { 384 FormatToken *Left = CurrentToken->Previous; 385 Left->ParentBracket = Contexts.back().ContextKind; 386 387 if (Contexts.back().CaretFound) 388 Left->Type = TT_ObjCBlockLBrace; 389 Contexts.back().CaretFound = false; 390 391 ScopedContextCreator ContextCreator(*this, tok::l_brace, 1); 392 Contexts.back().ColonIsDictLiteral = true; 393 if (Left->BlockKind == BK_BracedInit) 394 Contexts.back().IsExpression = true; 395 396 while (CurrentToken) { 397 if (CurrentToken->is(tok::r_brace)) { 398 Left->MatchingParen = CurrentToken; 399 CurrentToken->MatchingParen = Left; 400 next(); 401 return true; 402 } 403 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square)) 404 return false; 405 updateParameterCount(Left, CurrentToken); 406 if (CurrentToken->isOneOf(tok::colon, tok::l_brace)) { 407 FormatToken *Previous = CurrentToken->getPreviousNonComment(); 408 if (((CurrentToken->is(tok::colon) && 409 (!Contexts.back().ColonIsDictLiteral || 410 Style.Language != FormatStyle::LK_Cpp)) || 411 Style.Language == FormatStyle::LK_Proto) && 412 Previous->Tok.getIdentifierInfo()) 413 Previous->Type = TT_SelectorName; 414 if (CurrentToken->is(tok::colon) || 415 Style.Language == FormatStyle::LK_JavaScript) 416 Left->Type = TT_DictLiteral; 417 } 418 if (!consumeToken()) 419 return false; 420 } 421 } 422 return true; 423 } 424 425 void updateParameterCount(FormatToken *Left, FormatToken *Current) { 426 if (Current->is(tok::l_brace) && Current->BlockKind == BK_Block) 427 ++Left->BlockParameterCount; 428 if (Current->is(tok::comma)) { 429 ++Left->ParameterCount; 430 if (!Left->Role) 431 Left->Role.reset(new CommaSeparatedList(Style)); 432 Left->Role->CommaFound(Current); 433 } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) { 434 Left->ParameterCount = 1; 435 } 436 } 437 438 bool parseConditional() { 439 while (CurrentToken) { 440 if (CurrentToken->is(tok::colon)) { 441 CurrentToken->Type = TT_ConditionalExpr; 442 next(); 443 return true; 444 } 445 if (!consumeToken()) 446 return false; 447 } 448 return false; 449 } 450 451 bool parseTemplateDeclaration() { 452 if (CurrentToken && CurrentToken->is(tok::less)) { 453 CurrentToken->Type = TT_TemplateOpener; 454 next(); 455 if (!parseAngle()) 456 return false; 457 if (CurrentToken) 458 CurrentToken->Previous->ClosesTemplateDeclaration = true; 459 return true; 460 } 461 return false; 462 } 463 464 bool consumeToken() { 465 FormatToken *Tok = CurrentToken; 466 next(); 467 switch (Tok->Tok.getKind()) { 468 case tok::plus: 469 case tok::minus: 470 if (!Tok->Previous && Line.MustBeDeclaration) 471 Tok->Type = TT_ObjCMethodSpecifier; 472 break; 473 case tok::colon: 474 if (!Tok->Previous) 475 return false; 476 // Colons from ?: are handled in parseConditional(). 477 if (Style.Language == FormatStyle::LK_JavaScript) { 478 if (Contexts.back().ColonIsForRangeExpr || // colon in for loop 479 (Contexts.size() == 1 && // switch/case labels 480 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) || 481 Contexts.back().ContextKind == tok::l_paren || // function params 482 Contexts.back().ContextKind == tok::l_square || // array type 483 (Contexts.size() == 1 && 484 Line.MustBeDeclaration)) { // method/property declaration 485 Tok->Type = TT_JsTypeColon; 486 break; 487 } 488 } 489 if (Contexts.back().ColonIsDictLiteral || 490 Style.Language == FormatStyle::LK_Proto) { 491 Tok->Type = TT_DictLiteral; 492 } else if (Contexts.back().ColonIsObjCMethodExpr || 493 Line.startsWith(TT_ObjCMethodSpecifier)) { 494 Tok->Type = TT_ObjCMethodExpr; 495 Tok->Previous->Type = TT_SelectorName; 496 if (Tok->Previous->ColumnWidth > 497 Contexts.back().LongestObjCSelectorName) 498 Contexts.back().LongestObjCSelectorName = Tok->Previous->ColumnWidth; 499 if (!Contexts.back().FirstObjCSelectorName) 500 Contexts.back().FirstObjCSelectorName = Tok->Previous; 501 } else if (Contexts.back().ColonIsForRangeExpr) { 502 Tok->Type = TT_RangeBasedForLoopColon; 503 } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) { 504 Tok->Type = TT_BitFieldColon; 505 } else if (Contexts.size() == 1 && 506 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) { 507 if (Tok->Previous->is(tok::r_paren)) 508 Tok->Type = TT_CtorInitializerColon; 509 else 510 Tok->Type = TT_InheritanceColon; 511 } else if (Tok->Previous->is(tok::identifier) && Tok->Next && 512 Tok->Next->isOneOf(tok::r_paren, tok::comma)) { 513 // This handles a special macro in ObjC code where selectors including 514 // the colon are passed as macro arguments. 515 Tok->Type = TT_ObjCMethodExpr; 516 } else if (Contexts.back().ContextKind == tok::l_paren) { 517 Tok->Type = TT_InlineASMColon; 518 } 519 break; 520 case tok::kw_if: 521 case tok::kw_while: 522 if (CurrentToken && CurrentToken->is(tok::l_paren)) { 523 next(); 524 if (!parseParens(/*LookForDecls=*/true)) 525 return false; 526 } 527 break; 528 case tok::kw_for: 529 Contexts.back().ColonIsForRangeExpr = true; 530 next(); 531 if (!parseParens()) 532 return false; 533 break; 534 case tok::l_paren: 535 // When faced with 'operator()()', the kw_operator handler incorrectly 536 // marks the first l_paren as a OverloadedOperatorLParen. Here, we make 537 // the first two parens OverloadedOperators and the second l_paren an 538 // OverloadedOperatorLParen. 539 if (Tok->Previous && 540 Tok->Previous->is(tok::r_paren) && 541 Tok->Previous->MatchingParen && 542 Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) { 543 Tok->Previous->Type = TT_OverloadedOperator; 544 Tok->Previous->MatchingParen->Type = TT_OverloadedOperator; 545 Tok->Type = TT_OverloadedOperatorLParen; 546 } 547 548 if (!parseParens()) 549 return false; 550 if (Line.MustBeDeclaration && Contexts.size() == 1 && 551 !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) && 552 (!Tok->Previous || 553 !Tok->Previous->isOneOf(tok::kw_decltype, tok::kw___attribute, 554 TT_LeadingJavaAnnotation))) 555 Line.MightBeFunctionDecl = true; 556 break; 557 case tok::l_square: 558 if (!parseSquare()) 559 return false; 560 break; 561 case tok::l_brace: 562 if (!parseBrace()) 563 return false; 564 break; 565 case tok::less: 566 if (parseAngle()) { 567 Tok->Type = TT_TemplateOpener; 568 } else { 569 Tok->Type = TT_BinaryOperator; 570 NonTemplateLess.insert(Tok); 571 CurrentToken = Tok; 572 next(); 573 } 574 break; 575 case tok::r_paren: 576 case tok::r_square: 577 return false; 578 case tok::r_brace: 579 // Lines can start with '}'. 580 if (Tok->Previous) 581 return false; 582 break; 583 case tok::greater: 584 Tok->Type = TT_BinaryOperator; 585 break; 586 case tok::kw_operator: 587 while (CurrentToken && 588 !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) { 589 if (CurrentToken->isOneOf(tok::star, tok::amp)) 590 CurrentToken->Type = TT_PointerOrReference; 591 consumeToken(); 592 if (CurrentToken && 593 CurrentToken->Previous->isOneOf(TT_BinaryOperator, tok::comma)) 594 CurrentToken->Previous->Type = TT_OverloadedOperator; 595 } 596 if (CurrentToken) { 597 CurrentToken->Type = TT_OverloadedOperatorLParen; 598 if (CurrentToken->Previous->is(TT_BinaryOperator)) 599 CurrentToken->Previous->Type = TT_OverloadedOperator; 600 } 601 break; 602 case tok::question: 603 if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next && 604 Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren, 605 tok::r_brace)) { 606 // Question marks before semicolons, colons, etc. indicate optional 607 // types (fields, parameters), e.g. 608 // function(x?: string, y?) {...} 609 // class X { y?; } 610 Tok->Type = TT_JsTypeOptionalQuestion; 611 break; 612 } 613 // Declarations cannot be conditional expressions, this can only be part 614 // of a type declaration. 615 if (Line.MustBeDeclaration && 616 Style.Language == FormatStyle::LK_JavaScript) 617 break; 618 parseConditional(); 619 break; 620 case tok::kw_template: 621 parseTemplateDeclaration(); 622 break; 623 case tok::comma: 624 if (Contexts.back().InCtorInitializer) 625 Tok->Type = TT_CtorInitializerComma; 626 else if (Contexts.back().FirstStartOfName && 627 (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) { 628 Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true; 629 Line.IsMultiVariableDeclStmt = true; 630 } 631 if (Contexts.back().IsForEachMacro) 632 Contexts.back().IsExpression = true; 633 break; 634 default: 635 break; 636 } 637 return true; 638 } 639 640 void parseIncludeDirective() { 641 if (CurrentToken && CurrentToken->is(tok::less)) { 642 next(); 643 while (CurrentToken) { 644 if (CurrentToken->isNot(tok::comment) || CurrentToken->Next) 645 CurrentToken->Type = TT_ImplicitStringLiteral; 646 next(); 647 } 648 } 649 } 650 651 void parseWarningOrError() { 652 next(); 653 // We still want to format the whitespace left of the first token of the 654 // warning or error. 655 next(); 656 while (CurrentToken) { 657 CurrentToken->Type = TT_ImplicitStringLiteral; 658 next(); 659 } 660 } 661 662 void parsePragma() { 663 next(); // Consume "pragma". 664 if (CurrentToken && 665 CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) { 666 bool IsMark = CurrentToken->is(Keywords.kw_mark); 667 next(); // Consume "mark". 668 next(); // Consume first token (so we fix leading whitespace). 669 while (CurrentToken) { 670 if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator)) 671 CurrentToken->Type = TT_ImplicitStringLiteral; 672 next(); 673 } 674 } 675 } 676 677 LineType parsePreprocessorDirective() { 678 LineType Type = LT_PreprocessorDirective; 679 next(); 680 if (!CurrentToken) 681 return Type; 682 if (CurrentToken->Tok.is(tok::numeric_constant)) { 683 CurrentToken->SpacesRequiredBefore = 1; 684 return Type; 685 } 686 // Hashes in the middle of a line can lead to any strange token 687 // sequence. 688 if (!CurrentToken->Tok.getIdentifierInfo()) 689 return Type; 690 switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) { 691 case tok::pp_include: 692 case tok::pp_include_next: 693 case tok::pp_import: 694 next(); 695 parseIncludeDirective(); 696 Type = LT_ImportStatement; 697 break; 698 case tok::pp_error: 699 case tok::pp_warning: 700 parseWarningOrError(); 701 break; 702 case tok::pp_pragma: 703 parsePragma(); 704 break; 705 case tok::pp_if: 706 case tok::pp_elif: 707 Contexts.back().IsExpression = true; 708 parseLine(); 709 break; 710 default: 711 break; 712 } 713 while (CurrentToken) 714 next(); 715 return Type; 716 } 717 718 public: 719 LineType parseLine() { 720 NonTemplateLess.clear(); 721 if (CurrentToken->is(tok::hash)) 722 return parsePreprocessorDirective(); 723 724 // Directly allow to 'import <string-literal>' to support protocol buffer 725 // definitions (code.google.com/p/protobuf) or missing "#" (either way we 726 // should not break the line). 727 IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo(); 728 if ((Style.Language == FormatStyle::LK_Java && 729 CurrentToken->is(Keywords.kw_package)) || 730 (Info && Info->getPPKeywordID() == tok::pp_import && 731 CurrentToken->Next && 732 CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier, 733 tok::kw_static))) { 734 next(); 735 parseIncludeDirective(); 736 return LT_ImportStatement; 737 } 738 739 // If this line starts and ends in '<' and '>', respectively, it is likely 740 // part of "#define <a/b.h>". 741 if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) { 742 parseIncludeDirective(); 743 return LT_ImportStatement; 744 } 745 746 // In .proto files, top-level options are very similar to import statements 747 // and should not be line-wrapped. 748 if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 && 749 CurrentToken->is(Keywords.kw_option)) { 750 next(); 751 if (CurrentToken && CurrentToken->is(tok::identifier)) 752 return LT_ImportStatement; 753 } 754 755 bool KeywordVirtualFound = false; 756 bool ImportStatement = false; 757 while (CurrentToken) { 758 if (CurrentToken->is(tok::kw_virtual)) 759 KeywordVirtualFound = true; 760 if (isImportStatement(*CurrentToken)) 761 ImportStatement = true; 762 if (!consumeToken()) 763 return LT_Invalid; 764 } 765 if (KeywordVirtualFound) 766 return LT_VirtualFunctionDecl; 767 if (ImportStatement) 768 return LT_ImportStatement; 769 770 if (Line.startsWith(TT_ObjCMethodSpecifier)) { 771 if (Contexts.back().FirstObjCSelectorName) 772 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 773 Contexts.back().LongestObjCSelectorName; 774 return LT_ObjCMethodDecl; 775 } 776 777 return LT_Other; 778 } 779 780 private: 781 bool isImportStatement(const FormatToken &Tok) { 782 // FIXME: Closure-library specific stuff should not be hard-coded but be 783 // configurable. 784 return Style.Language == FormatStyle::LK_JavaScript && 785 Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) && 786 Tok.Next->Next && (Tok.Next->Next->TokenText == "module" || 787 Tok.Next->Next->TokenText == "provide" || 788 Tok.Next->Next->TokenText == "require" || 789 Tok.Next->Next->TokenText == "setTestOnly") && 790 Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren); 791 } 792 793 void resetTokenMetadata(FormatToken *Token) { 794 if (!Token) 795 return; 796 797 // Reset token type in case we have already looked at it and then 798 // recovered from an error (e.g. failure to find the matching >). 799 if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_ForEachMacro, 800 TT_FunctionLBrace, TT_ImplicitStringLiteral, 801 TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow, 802 TT_RegexLiteral)) 803 CurrentToken->Type = TT_Unknown; 804 CurrentToken->Role.reset(); 805 CurrentToken->MatchingParen = nullptr; 806 CurrentToken->FakeLParens.clear(); 807 CurrentToken->FakeRParens = 0; 808 } 809 810 void next() { 811 if (CurrentToken) { 812 CurrentToken->NestingLevel = Contexts.size() - 1; 813 CurrentToken->BindingStrength = Contexts.back().BindingStrength; 814 modifyContext(*CurrentToken); 815 determineTokenType(*CurrentToken); 816 CurrentToken = CurrentToken->Next; 817 } 818 819 resetTokenMetadata(CurrentToken); 820 } 821 822 /// \brief A struct to hold information valid in a specific context, e.g. 823 /// a pair of parenthesis. 824 struct Context { 825 Context(tok::TokenKind ContextKind, unsigned BindingStrength, 826 bool IsExpression) 827 : ContextKind(ContextKind), BindingStrength(BindingStrength), 828 IsExpression(IsExpression) {} 829 830 tok::TokenKind ContextKind; 831 unsigned BindingStrength; 832 bool IsExpression; 833 unsigned LongestObjCSelectorName = 0; 834 bool ColonIsForRangeExpr = false; 835 bool ColonIsDictLiteral = false; 836 bool ColonIsObjCMethodExpr = false; 837 FormatToken *FirstObjCSelectorName = nullptr; 838 FormatToken *FirstStartOfName = nullptr; 839 bool CanBeExpression = true; 840 bool InTemplateArgument = false; 841 bool InCtorInitializer = false; 842 bool CaretFound = false; 843 bool IsForEachMacro = false; 844 }; 845 846 /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime 847 /// of each instance. 848 struct ScopedContextCreator { 849 AnnotatingParser &P; 850 851 ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind, 852 unsigned Increase) 853 : P(P) { 854 P.Contexts.push_back(Context(ContextKind, 855 P.Contexts.back().BindingStrength + Increase, 856 P.Contexts.back().IsExpression)); 857 } 858 859 ~ScopedContextCreator() { P.Contexts.pop_back(); } 860 }; 861 862 void modifyContext(const FormatToken &Current) { 863 if (Current.getPrecedence() == prec::Assignment && 864 !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) && 865 (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) { 866 Contexts.back().IsExpression = true; 867 if (!Line.startsWith(TT_UnaryOperator)) { 868 for (FormatToken *Previous = Current.Previous; 869 Previous && Previous->Previous && 870 !Previous->Previous->isOneOf(tok::comma, tok::semi); 871 Previous = Previous->Previous) { 872 if (Previous->isOneOf(tok::r_square, tok::r_paren)) { 873 Previous = Previous->MatchingParen; 874 if (!Previous) 875 break; 876 } 877 if (Previous->opensScope()) 878 break; 879 if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) && 880 Previous->isOneOf(tok::star, tok::amp, tok::ampamp) && 881 Previous->Previous && Previous->Previous->isNot(tok::equal)) 882 Previous->Type = TT_PointerOrReference; 883 } 884 } 885 } else if (Current.is(tok::lessless) && 886 (!Current.Previous || !Current.Previous->is(tok::kw_operator))) { 887 Contexts.back().IsExpression = true; 888 } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) { 889 Contexts.back().IsExpression = true; 890 } else if (Current.is(TT_TrailingReturnArrow)) { 891 Contexts.back().IsExpression = false; 892 } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) { 893 Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java; 894 } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) { 895 for (FormatToken *Previous = Current.Previous; 896 Previous && Previous->isOneOf(tok::star, tok::amp); 897 Previous = Previous->Previous) 898 Previous->Type = TT_PointerOrReference; 899 if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer) 900 Contexts.back().IsExpression = false; 901 } else if (Current.Previous && 902 Current.Previous->is(TT_CtorInitializerColon)) { 903 Contexts.back().IsExpression = true; 904 Contexts.back().InCtorInitializer = true; 905 } else if (Current.is(tok::kw_new)) { 906 Contexts.back().CanBeExpression = false; 907 } else if (Current.isOneOf(tok::semi, tok::exclaim)) { 908 // This should be the condition or increment in a for-loop. 909 Contexts.back().IsExpression = true; 910 } 911 } 912 913 void determineTokenType(FormatToken &Current) { 914 if (!Current.is(TT_Unknown)) 915 // The token type is already known. 916 return; 917 918 // Line.MightBeFunctionDecl can only be true after the parentheses of a 919 // function declaration have been found. In this case, 'Current' is a 920 // trailing token of this declaration and thus cannot be a name. 921 if (Current.is(Keywords.kw_instanceof)) { 922 Current.Type = TT_BinaryOperator; 923 } else if (isStartOfName(Current) && 924 (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) { 925 Contexts.back().FirstStartOfName = &Current; 926 Current.Type = TT_StartOfName; 927 } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) { 928 AutoFound = true; 929 } else if (Current.is(tok::arrow) && 930 Style.Language == FormatStyle::LK_Java) { 931 Current.Type = TT_LambdaArrow; 932 } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration && 933 Current.NestingLevel == 0) { 934 Current.Type = TT_TrailingReturnArrow; 935 } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) { 936 Current.Type = 937 determineStarAmpUsage(Current, Contexts.back().CanBeExpression && 938 Contexts.back().IsExpression, 939 Contexts.back().InTemplateArgument); 940 } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) { 941 Current.Type = determinePlusMinusCaretUsage(Current); 942 if (Current.is(TT_UnaryOperator) && Current.is(tok::caret)) 943 Contexts.back().CaretFound = true; 944 } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) { 945 Current.Type = determineIncrementUsage(Current); 946 } else if (Current.isOneOf(tok::exclaim, tok::tilde)) { 947 Current.Type = TT_UnaryOperator; 948 } else if (Current.is(tok::question)) { 949 if (Style.Language == FormatStyle::LK_JavaScript && 950 Line.MustBeDeclaration) { 951 // In JavaScript, `interface X { foo?(): bar; }` is an optional method 952 // on the interface, not a ternary expression. 953 Current.Type = TT_JsTypeOptionalQuestion; 954 } else { 955 Current.Type = TT_ConditionalExpr; 956 } 957 } else if (Current.isBinaryOperator() && 958 (!Current.Previous || Current.Previous->isNot(tok::l_square))) { 959 Current.Type = TT_BinaryOperator; 960 } else if (Current.is(tok::comment)) { 961 if (Current.TokenText.startswith("/*")) { 962 if (Current.TokenText.endswith("*/")) 963 Current.Type = TT_BlockComment; 964 else 965 // The lexer has for some reason determined a comment here. But we 966 // cannot really handle it, if it isn't properly terminated. 967 Current.Tok.setKind(tok::unknown); 968 } else { 969 Current.Type = TT_LineComment; 970 } 971 } else if (Current.is(tok::r_paren)) { 972 if (rParenEndsCast(Current)) 973 Current.Type = TT_CastRParen; 974 if (Current.MatchingParen && Current.Next && 975 !Current.Next->isBinaryOperator() && 976 !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace)) 977 if (FormatToken *BeforeParen = Current.MatchingParen->Previous) 978 if (BeforeParen->is(tok::identifier) && 979 BeforeParen->TokenText == BeforeParen->TokenText.upper() && 980 (!BeforeParen->Previous || 981 BeforeParen->Previous->ClosesTemplateDeclaration)) 982 Current.Type = TT_FunctionAnnotationRParen; 983 } else if (Current.is(tok::at) && Current.Next) { 984 if (Current.Next->isStringLiteral()) { 985 Current.Type = TT_ObjCStringLiteral; 986 } else { 987 switch (Current.Next->Tok.getObjCKeywordID()) { 988 case tok::objc_interface: 989 case tok::objc_implementation: 990 case tok::objc_protocol: 991 Current.Type = TT_ObjCDecl; 992 break; 993 case tok::objc_property: 994 Current.Type = TT_ObjCProperty; 995 break; 996 default: 997 break; 998 } 999 } 1000 } else if (Current.is(tok::period)) { 1001 FormatToken *PreviousNoComment = Current.getPreviousNonComment(); 1002 if (PreviousNoComment && 1003 PreviousNoComment->isOneOf(tok::comma, tok::l_brace)) 1004 Current.Type = TT_DesignatedInitializerPeriod; 1005 else if (Style.Language == FormatStyle::LK_Java && Current.Previous && 1006 Current.Previous->isOneOf(TT_JavaAnnotation, 1007 TT_LeadingJavaAnnotation)) { 1008 Current.Type = Current.Previous->Type; 1009 } 1010 } else if (Current.isOneOf(tok::identifier, tok::kw_const) && 1011 Current.Previous && 1012 !Current.Previous->isOneOf(tok::equal, tok::at) && 1013 Line.MightBeFunctionDecl && Contexts.size() == 1) { 1014 // Line.MightBeFunctionDecl can only be true after the parentheses of a 1015 // function declaration have been found. 1016 Current.Type = TT_TrailingAnnotation; 1017 } else if ((Style.Language == FormatStyle::LK_Java || 1018 Style.Language == FormatStyle::LK_JavaScript) && 1019 Current.Previous) { 1020 if (Current.Previous->is(tok::at) && 1021 Current.isNot(Keywords.kw_interface)) { 1022 const FormatToken &AtToken = *Current.Previous; 1023 const FormatToken *Previous = AtToken.getPreviousNonComment(); 1024 if (!Previous || Previous->is(TT_LeadingJavaAnnotation)) 1025 Current.Type = TT_LeadingJavaAnnotation; 1026 else 1027 Current.Type = TT_JavaAnnotation; 1028 } else if (Current.Previous->is(tok::period) && 1029 Current.Previous->isOneOf(TT_JavaAnnotation, 1030 TT_LeadingJavaAnnotation)) { 1031 Current.Type = Current.Previous->Type; 1032 } 1033 } 1034 } 1035 1036 /// \brief Take a guess at whether \p Tok starts a name of a function or 1037 /// variable declaration. 1038 /// 1039 /// This is a heuristic based on whether \p Tok is an identifier following 1040 /// something that is likely a type. 1041 bool isStartOfName(const FormatToken &Tok) { 1042 if (Tok.isNot(tok::identifier) || !Tok.Previous) 1043 return false; 1044 1045 if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof)) 1046 return false; 1047 if (Style.Language == FormatStyle::LK_JavaScript && 1048 Tok.Previous->is(Keywords.kw_in)) 1049 return false; 1050 1051 // Skip "const" as it does not have an influence on whether this is a name. 1052 FormatToken *PreviousNotConst = Tok.Previous; 1053 while (PreviousNotConst && PreviousNotConst->is(tok::kw_const)) 1054 PreviousNotConst = PreviousNotConst->Previous; 1055 1056 if (!PreviousNotConst) 1057 return false; 1058 1059 bool IsPPKeyword = PreviousNotConst->is(tok::identifier) && 1060 PreviousNotConst->Previous && 1061 PreviousNotConst->Previous->is(tok::hash); 1062 1063 if (PreviousNotConst->is(TT_TemplateCloser)) 1064 return PreviousNotConst && PreviousNotConst->MatchingParen && 1065 PreviousNotConst->MatchingParen->Previous && 1066 PreviousNotConst->MatchingParen->Previous->isNot(tok::period) && 1067 PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template); 1068 1069 if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen && 1070 PreviousNotConst->MatchingParen->Previous && 1071 PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype)) 1072 return true; 1073 1074 return (!IsPPKeyword && 1075 PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) || 1076 PreviousNotConst->is(TT_PointerOrReference) || 1077 PreviousNotConst->isSimpleTypeSpecifier(); 1078 } 1079 1080 /// \brief Determine whether ')' is ending a cast. 1081 bool rParenEndsCast(const FormatToken &Tok) { 1082 // C-style casts are only used in C++ and Java. 1083 if (Style.Language != FormatStyle::LK_Cpp && 1084 Style.Language != FormatStyle::LK_Java) 1085 return false; 1086 1087 // Empty parens aren't casts and there are no casts at the end of the line. 1088 if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen) 1089 return false; 1090 1091 FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment(); 1092 if (LeftOfParens) { 1093 // If there is an opening parenthesis left of the current parentheses, 1094 // look past it as these might be chained casts. 1095 if (LeftOfParens->is(tok::r_paren)) { 1096 if (!LeftOfParens->MatchingParen || 1097 !LeftOfParens->MatchingParen->Previous) 1098 return false; 1099 LeftOfParens = LeftOfParens->MatchingParen->Previous; 1100 } 1101 1102 // If there is an identifier (or with a few exceptions a keyword) right 1103 // before the parentheses, this is unlikely to be a cast. 1104 if (LeftOfParens->Tok.getIdentifierInfo() && 1105 !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case, 1106 tok::kw_delete)) 1107 return false; 1108 1109 // Certain other tokens right before the parentheses are also signals that 1110 // this cannot be a cast. 1111 if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator, 1112 TT_TemplateCloser)) 1113 return false; 1114 } 1115 1116 if (Tok.Next->is(tok::question)) 1117 return false; 1118 1119 // As Java has no function types, a "(" after the ")" likely means that this 1120 // is a cast. 1121 if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren)) 1122 return true; 1123 1124 // If a (non-string) literal follows, this is likely a cast. 1125 if (Tok.Next->isNot(tok::string_literal) && 1126 (Tok.Next->Tok.isLiteral() || 1127 Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof))) 1128 return true; 1129 1130 // Heuristically try to determine whether the parentheses contain a type. 1131 bool ParensAreType = 1132 !Tok.Previous || 1133 Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) || 1134 Tok.Previous->isSimpleTypeSpecifier(); 1135 bool ParensCouldEndDecl = 1136 Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater); 1137 if (ParensAreType && !ParensCouldEndDecl) 1138 return true; 1139 1140 // At this point, we heuristically assume that there are no casts at the 1141 // start of the line. We assume that we have found most cases where there 1142 // are by the logic above, e.g. "(void)x;". 1143 if (!LeftOfParens) 1144 return false; 1145 1146 // If the following token is an identifier, this is a cast. All cases where 1147 // this can be something else are handled above. 1148 if (Tok.Next->is(tok::identifier)) 1149 return true; 1150 1151 if (!Tok.Next->Next) 1152 return false; 1153 1154 // If the next token after the parenthesis is a unary operator, assume 1155 // that this is cast, unless there are unexpected tokens inside the 1156 // parenthesis. 1157 bool NextIsUnary = 1158 Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star); 1159 if (!NextIsUnary || Tok.Next->is(tok::plus) || 1160 !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant)) 1161 return false; 1162 // Search for unexpected tokens. 1163 for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen; 1164 Prev = Prev->Previous) { 1165 if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon)) 1166 return false; 1167 } 1168 return true; 1169 } 1170 1171 /// \brief Return the type of the given token assuming it is * or &. 1172 TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression, 1173 bool InTemplateArgument) { 1174 if (Style.Language == FormatStyle::LK_JavaScript) 1175 return TT_BinaryOperator; 1176 1177 const FormatToken *PrevToken = Tok.getPreviousNonComment(); 1178 if (!PrevToken) 1179 return TT_UnaryOperator; 1180 1181 const FormatToken *NextToken = Tok.getNextNonComment(); 1182 if (!NextToken || 1183 NextToken->isOneOf(tok::arrow, Keywords.kw_final, 1184 Keywords.kw_override) || 1185 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment())) 1186 return TT_PointerOrReference; 1187 1188 if (PrevToken->is(tok::coloncolon)) 1189 return TT_PointerOrReference; 1190 1191 if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace, 1192 tok::comma, tok::semi, tok::kw_return, tok::colon, 1193 tok::equal, tok::kw_delete, tok::kw_sizeof) || 1194 PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr, 1195 TT_UnaryOperator, TT_CastRParen)) 1196 return TT_UnaryOperator; 1197 1198 if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare)) 1199 return TT_PointerOrReference; 1200 if (NextToken->is(tok::kw_operator) && !IsExpression) 1201 return TT_PointerOrReference; 1202 if (NextToken->isOneOf(tok::comma, tok::semi)) 1203 return TT_PointerOrReference; 1204 1205 if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen && 1206 PrevToken->MatchingParen->Previous && 1207 PrevToken->MatchingParen->Previous->isOneOf(tok::kw_typeof, 1208 tok::kw_decltype)) 1209 return TT_PointerOrReference; 1210 1211 if (PrevToken->Tok.isLiteral() || 1212 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true, 1213 tok::kw_false, tok::r_brace) || 1214 NextToken->Tok.isLiteral() || 1215 NextToken->isOneOf(tok::kw_true, tok::kw_false) || 1216 NextToken->isUnaryOperator() || 1217 // If we know we're in a template argument, there are no named 1218 // declarations. Thus, having an identifier on the right-hand side 1219 // indicates a binary operator. 1220 (InTemplateArgument && NextToken->Tok.isAnyIdentifier())) 1221 return TT_BinaryOperator; 1222 1223 // "&&(" is quite unlikely to be two successive unary "&". 1224 if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren)) 1225 return TT_BinaryOperator; 1226 1227 // This catches some cases where evaluation order is used as control flow: 1228 // aaa && aaa->f(); 1229 const FormatToken *NextNextToken = NextToken->getNextNonComment(); 1230 if (NextNextToken && NextNextToken->is(tok::arrow)) 1231 return TT_BinaryOperator; 1232 1233 // It is very unlikely that we are going to find a pointer or reference type 1234 // definition on the RHS of an assignment. 1235 if (IsExpression && !Contexts.back().CaretFound) 1236 return TT_BinaryOperator; 1237 1238 return TT_PointerOrReference; 1239 } 1240 1241 TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) { 1242 const FormatToken *PrevToken = Tok.getPreviousNonComment(); 1243 if (!PrevToken || PrevToken->is(TT_CastRParen)) 1244 return TT_UnaryOperator; 1245 1246 // Use heuristics to recognize unary operators. 1247 if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square, 1248 tok::question, tok::colon, tok::kw_return, 1249 tok::kw_case, tok::at, tok::l_brace)) 1250 return TT_UnaryOperator; 1251 1252 // There can't be two consecutive binary operators. 1253 if (PrevToken->is(TT_BinaryOperator)) 1254 return TT_UnaryOperator; 1255 1256 // Fall back to marking the token as binary operator. 1257 return TT_BinaryOperator; 1258 } 1259 1260 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements. 1261 TokenType determineIncrementUsage(const FormatToken &Tok) { 1262 const FormatToken *PrevToken = Tok.getPreviousNonComment(); 1263 if (!PrevToken || PrevToken->is(TT_CastRParen)) 1264 return TT_UnaryOperator; 1265 if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier)) 1266 return TT_TrailingUnaryOperator; 1267 1268 return TT_UnaryOperator; 1269 } 1270 1271 SmallVector<Context, 8> Contexts; 1272 1273 const FormatStyle &Style; 1274 AnnotatedLine &Line; 1275 FormatToken *CurrentToken; 1276 bool AutoFound; 1277 const AdditionalKeywords &Keywords; 1278 1279 // Set of "<" tokens that do not open a template parameter list. If parseAngle 1280 // determines that a specific token can't be a template opener, it will make 1281 // same decision irrespective of the decisions for tokens leading up to it. 1282 // Store this information to prevent this from causing exponential runtime. 1283 llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess; 1284 }; 1285 1286 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1; 1287 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2; 1288 1289 /// \brief Parses binary expressions by inserting fake parenthesis based on 1290 /// operator precedence. 1291 class ExpressionParser { 1292 public: 1293 ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords, 1294 AnnotatedLine &Line) 1295 : Style(Style), Keywords(Keywords), Current(Line.First) {} 1296 1297 /// \brief Parse expressions with the given operatore precedence. 1298 void parse(int Precedence = 0) { 1299 // Skip 'return' and ObjC selector colons as they are not part of a binary 1300 // expression. 1301 while (Current && (Current->is(tok::kw_return) || 1302 (Current->is(tok::colon) && 1303 Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)))) 1304 next(); 1305 1306 if (!Current || Precedence > PrecedenceArrowAndPeriod) 1307 return; 1308 1309 // Conditional expressions need to be parsed separately for proper nesting. 1310 if (Precedence == prec::Conditional) { 1311 parseConditionalExpr(); 1312 return; 1313 } 1314 1315 // Parse unary operators, which all have a higher precedence than binary 1316 // operators. 1317 if (Precedence == PrecedenceUnaryOperator) { 1318 parseUnaryOperator(); 1319 return; 1320 } 1321 1322 FormatToken *Start = Current; 1323 FormatToken *LatestOperator = nullptr; 1324 unsigned OperatorIndex = 0; 1325 1326 while (Current) { 1327 // Consume operators with higher precedence. 1328 parse(Precedence + 1); 1329 1330 int CurrentPrecedence = getCurrentPrecedence(); 1331 1332 if (Current && Current->is(TT_SelectorName) && 1333 Precedence == CurrentPrecedence) { 1334 if (LatestOperator) 1335 addFakeParenthesis(Start, prec::Level(Precedence)); 1336 Start = Current; 1337 } 1338 1339 // At the end of the line or when an operator with higher precedence is 1340 // found, insert fake parenthesis and return. 1341 if (!Current || (Current->closesScope() && Current->MatchingParen) || 1342 (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) || 1343 (CurrentPrecedence == prec::Conditional && 1344 Precedence == prec::Assignment && Current->is(tok::colon))) { 1345 break; 1346 } 1347 1348 // Consume scopes: (), [], <> and {} 1349 if (Current->opensScope()) { 1350 while (Current && !Current->closesScope()) { 1351 next(); 1352 parse(); 1353 } 1354 next(); 1355 } else { 1356 // Operator found. 1357 if (CurrentPrecedence == Precedence) { 1358 if (LatestOperator) 1359 LatestOperator->NextOperator = Current; 1360 LatestOperator = Current; 1361 Current->OperatorIndex = OperatorIndex; 1362 ++OperatorIndex; 1363 } 1364 next(/*SkipPastLeadingComments=*/Precedence > 0); 1365 } 1366 } 1367 1368 if (LatestOperator && (Current || Precedence > 0)) { 1369 // LatestOperator->LastOperator = true; 1370 if (Precedence == PrecedenceArrowAndPeriod) { 1371 // Call expressions don't have a binary operator precedence. 1372 addFakeParenthesis(Start, prec::Unknown); 1373 } else { 1374 addFakeParenthesis(Start, prec::Level(Precedence)); 1375 } 1376 } 1377 } 1378 1379 private: 1380 /// \brief Gets the precedence (+1) of the given token for binary operators 1381 /// and other tokens that we treat like binary operators. 1382 int getCurrentPrecedence() { 1383 if (Current) { 1384 const FormatToken *NextNonComment = Current->getNextNonComment(); 1385 if (Current->is(TT_ConditionalExpr)) 1386 return prec::Conditional; 1387 if (NextNonComment && NextNonComment->is(tok::colon) && 1388 NextNonComment->is(TT_DictLiteral)) 1389 return prec::Comma; 1390 if (Current->is(TT_LambdaArrow)) 1391 return prec::Comma; 1392 if (Current->is(TT_JsFatArrow)) 1393 return prec::Assignment; 1394 if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName, 1395 TT_JsComputedPropertyName) || 1396 (Current->is(tok::comment) && NextNonComment && 1397 NextNonComment->is(TT_SelectorName))) 1398 return 0; 1399 if (Current->is(TT_RangeBasedForLoopColon)) 1400 return prec::Comma; 1401 if ((Style.Language == FormatStyle::LK_Java || 1402 Style.Language == FormatStyle::LK_JavaScript) && 1403 Current->is(Keywords.kw_instanceof)) 1404 return prec::Relational; 1405 if (Style.Language == FormatStyle::LK_JavaScript && 1406 Current->is(Keywords.kw_in)) 1407 return prec::Relational; 1408 if (Current->is(TT_BinaryOperator) || Current->is(tok::comma)) 1409 return Current->getPrecedence(); 1410 if (Current->isOneOf(tok::period, tok::arrow)) 1411 return PrecedenceArrowAndPeriod; 1412 if (Style.Language == FormatStyle::LK_Java && 1413 Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements, 1414 Keywords.kw_throws)) 1415 return 0; 1416 } 1417 return -1; 1418 } 1419 1420 void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) { 1421 Start->FakeLParens.push_back(Precedence); 1422 if (Precedence > prec::Unknown) 1423 Start->StartsBinaryExpression = true; 1424 if (Current) { 1425 FormatToken *Previous = Current->Previous; 1426 while (Previous->is(tok::comment) && Previous->Previous) 1427 Previous = Previous->Previous; 1428 ++Previous->FakeRParens; 1429 if (Precedence > prec::Unknown) 1430 Previous->EndsBinaryExpression = true; 1431 } 1432 } 1433 1434 /// \brief Parse unary operator expressions and surround them with fake 1435 /// parentheses if appropriate. 1436 void parseUnaryOperator() { 1437 if (!Current || Current->isNot(TT_UnaryOperator)) { 1438 parse(PrecedenceArrowAndPeriod); 1439 return; 1440 } 1441 1442 FormatToken *Start = Current; 1443 next(); 1444 parseUnaryOperator(); 1445 1446 // The actual precedence doesn't matter. 1447 addFakeParenthesis(Start, prec::Unknown); 1448 } 1449 1450 void parseConditionalExpr() { 1451 while (Current && Current->isTrailingComment()) { 1452 next(); 1453 } 1454 FormatToken *Start = Current; 1455 parse(prec::LogicalOr); 1456 if (!Current || !Current->is(tok::question)) 1457 return; 1458 next(); 1459 parse(prec::Assignment); 1460 if (!Current || Current->isNot(TT_ConditionalExpr)) 1461 return; 1462 next(); 1463 parse(prec::Assignment); 1464 addFakeParenthesis(Start, prec::Conditional); 1465 } 1466 1467 void next(bool SkipPastLeadingComments = true) { 1468 if (Current) 1469 Current = Current->Next; 1470 while (Current && 1471 (Current->NewlinesBefore == 0 || SkipPastLeadingComments) && 1472 Current->isTrailingComment()) 1473 Current = Current->Next; 1474 } 1475 1476 const FormatStyle &Style; 1477 const AdditionalKeywords &Keywords; 1478 FormatToken *Current; 1479 }; 1480 1481 } // end anonymous namespace 1482 1483 void TokenAnnotator::setCommentLineLevels( 1484 SmallVectorImpl<AnnotatedLine *> &Lines) { 1485 const AnnotatedLine *NextNonCommentLine = nullptr; 1486 for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(), 1487 E = Lines.rend(); 1488 I != E; ++I) { 1489 if (NextNonCommentLine && (*I)->First->is(tok::comment) && 1490 (*I)->First->Next == nullptr) 1491 (*I)->Level = NextNonCommentLine->Level; 1492 else 1493 NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr; 1494 1495 setCommentLineLevels((*I)->Children); 1496 } 1497 } 1498 1499 void TokenAnnotator::annotate(AnnotatedLine &Line) { 1500 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(), 1501 E = Line.Children.end(); 1502 I != E; ++I) { 1503 annotate(**I); 1504 } 1505 AnnotatingParser Parser(Style, Line, Keywords); 1506 Line.Type = Parser.parseLine(); 1507 if (Line.Type == LT_Invalid) 1508 return; 1509 1510 ExpressionParser ExprParser(Style, Keywords, Line); 1511 ExprParser.parse(); 1512 1513 if (Line.startsWith(TT_ObjCMethodSpecifier)) 1514 Line.Type = LT_ObjCMethodDecl; 1515 else if (Line.startsWith(TT_ObjCDecl)) 1516 Line.Type = LT_ObjCDecl; 1517 else if (Line.startsWith(TT_ObjCProperty)) 1518 Line.Type = LT_ObjCProperty; 1519 1520 Line.First->SpacesRequiredBefore = 1; 1521 Line.First->CanBreakBefore = Line.First->MustBreakBefore; 1522 } 1523 1524 // This function heuristically determines whether 'Current' starts the name of a 1525 // function declaration. 1526 static bool isFunctionDeclarationName(const FormatToken &Current) { 1527 auto skipOperatorName = [](const FormatToken* Next) -> const FormatToken* { 1528 for (; Next; Next = Next->Next) { 1529 if (Next->is(TT_OverloadedOperatorLParen)) 1530 return Next; 1531 if (Next->is(TT_OverloadedOperator)) 1532 continue; 1533 if (Next->isOneOf(tok::kw_new, tok::kw_delete)) { 1534 // For 'new[]' and 'delete[]'. 1535 if (Next->Next && Next->Next->is(tok::l_square) && 1536 Next->Next->Next && Next->Next->Next->is(tok::r_square)) 1537 Next = Next->Next->Next; 1538 continue; 1539 } 1540 1541 break; 1542 } 1543 return nullptr; 1544 }; 1545 1546 const FormatToken *Next = Current.Next; 1547 if (Current.is(tok::kw_operator)) { 1548 if (Current.Previous && Current.Previous->is(tok::coloncolon)) 1549 return false; 1550 Next = skipOperatorName(Next); 1551 } else { 1552 if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0) 1553 return false; 1554 for (; Next; Next = Next->Next) { 1555 if (Next->is(TT_TemplateOpener)) { 1556 Next = Next->MatchingParen; 1557 } else if (Next->is(tok::coloncolon)) { 1558 Next = Next->Next; 1559 if (!Next) 1560 return false; 1561 if (Next->is(tok::kw_operator)) { 1562 Next = skipOperatorName(Next->Next); 1563 break; 1564 } 1565 if (!Next->is(tok::identifier)) 1566 return false; 1567 } else if (Next->is(tok::l_paren)) { 1568 break; 1569 } else { 1570 return false; 1571 } 1572 } 1573 } 1574 1575 if (!Next || !Next->is(tok::l_paren)) 1576 return false; 1577 if (Next->Next == Next->MatchingParen) 1578 return true; 1579 for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen; 1580 Tok = Tok->Next) { 1581 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() || 1582 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName)) 1583 return true; 1584 if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) || 1585 Tok->Tok.isLiteral()) 1586 return false; 1587 } 1588 return false; 1589 } 1590 1591 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const { 1592 assert(Line.MightBeFunctionDecl); 1593 1594 if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel || 1595 Style.AlwaysBreakAfterReturnType == 1596 FormatStyle::RTBS_TopLevelDefinitions) && 1597 Line.Level > 0) 1598 return false; 1599 1600 switch (Style.AlwaysBreakAfterReturnType) { 1601 case FormatStyle::RTBS_None: 1602 return false; 1603 case FormatStyle::RTBS_All: 1604 case FormatStyle::RTBS_TopLevel: 1605 return true; 1606 case FormatStyle::RTBS_AllDefinitions: 1607 case FormatStyle::RTBS_TopLevelDefinitions: 1608 return Line.mightBeFunctionDefinition(); 1609 } 1610 1611 return false; 1612 } 1613 1614 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) { 1615 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(), 1616 E = Line.Children.end(); 1617 I != E; ++I) { 1618 calculateFormattingInformation(**I); 1619 } 1620 1621 Line.First->TotalLength = 1622 Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth; 1623 if (!Line.First->Next) 1624 return; 1625 FormatToken *Current = Line.First->Next; 1626 bool InFunctionDecl = Line.MightBeFunctionDecl; 1627 while (Current) { 1628 if (isFunctionDeclarationName(*Current)) 1629 Current->Type = TT_FunctionDeclarationName; 1630 if (Current->is(TT_LineComment)) { 1631 if (Current->Previous->BlockKind == BK_BracedInit && 1632 Current->Previous->opensScope()) 1633 Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1; 1634 else 1635 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments; 1636 1637 // If we find a trailing comment, iterate backwards to determine whether 1638 // it seems to relate to a specific parameter. If so, break before that 1639 // parameter to avoid changing the comment's meaning. E.g. don't move 'b' 1640 // to the previous line in: 1641 // SomeFunction(a, 1642 // b, // comment 1643 // c); 1644 if (!Current->HasUnescapedNewline) { 1645 for (FormatToken *Parameter = Current->Previous; Parameter; 1646 Parameter = Parameter->Previous) { 1647 if (Parameter->isOneOf(tok::comment, tok::r_brace)) 1648 break; 1649 if (Parameter->Previous && Parameter->Previous->is(tok::comma)) { 1650 if (!Parameter->Previous->is(TT_CtorInitializerComma) && 1651 Parameter->HasUnescapedNewline) 1652 Parameter->MustBreakBefore = true; 1653 break; 1654 } 1655 } 1656 } 1657 } else if (Current->SpacesRequiredBefore == 0 && 1658 spaceRequiredBefore(Line, *Current)) { 1659 Current->SpacesRequiredBefore = 1; 1660 } 1661 1662 Current->MustBreakBefore = 1663 Current->MustBreakBefore || mustBreakBefore(Line, *Current); 1664 1665 if (!Current->MustBreakBefore && InFunctionDecl && 1666 Current->is(TT_FunctionDeclarationName)) 1667 Current->MustBreakBefore = mustBreakForReturnType(Line); 1668 1669 Current->CanBreakBefore = 1670 Current->MustBreakBefore || canBreakBefore(Line, *Current); 1671 unsigned ChildSize = 0; 1672 if (Current->Previous->Children.size() == 1) { 1673 FormatToken &LastOfChild = *Current->Previous->Children[0]->Last; 1674 ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit 1675 : LastOfChild.TotalLength + 1; 1676 } 1677 const FormatToken *Prev = Current->Previous; 1678 if (Current->MustBreakBefore || Prev->Children.size() > 1 || 1679 (Prev->Children.size() == 1 && 1680 Prev->Children[0]->First->MustBreakBefore) || 1681 Current->IsMultiline) 1682 Current->TotalLength = Prev->TotalLength + Style.ColumnLimit; 1683 else 1684 Current->TotalLength = Prev->TotalLength + Current->ColumnWidth + 1685 ChildSize + Current->SpacesRequiredBefore; 1686 1687 if (Current->is(TT_CtorInitializerColon)) 1688 InFunctionDecl = false; 1689 1690 // FIXME: Only calculate this if CanBreakBefore is true once static 1691 // initializers etc. are sorted out. 1692 // FIXME: Move magic numbers to a better place. 1693 Current->SplitPenalty = 20 * Current->BindingStrength + 1694 splitPenalty(Line, *Current, InFunctionDecl); 1695 1696 Current = Current->Next; 1697 } 1698 1699 calculateUnbreakableTailLengths(Line); 1700 for (Current = Line.First; Current != nullptr; Current = Current->Next) { 1701 if (Current->Role) 1702 Current->Role->precomputeFormattingInfos(Current); 1703 } 1704 1705 DEBUG({ printDebugInfo(Line); }); 1706 } 1707 1708 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) { 1709 unsigned UnbreakableTailLength = 0; 1710 FormatToken *Current = Line.Last; 1711 while (Current) { 1712 Current->UnbreakableTailLength = UnbreakableTailLength; 1713 if (Current->CanBreakBefore || 1714 Current->isOneOf(tok::comment, tok::string_literal)) { 1715 UnbreakableTailLength = 0; 1716 } else { 1717 UnbreakableTailLength += 1718 Current->ColumnWidth + Current->SpacesRequiredBefore; 1719 } 1720 Current = Current->Previous; 1721 } 1722 } 1723 1724 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line, 1725 const FormatToken &Tok, 1726 bool InFunctionDecl) { 1727 const FormatToken &Left = *Tok.Previous; 1728 const FormatToken &Right = Tok; 1729 1730 if (Left.is(tok::semi)) 1731 return 0; 1732 1733 if (Style.Language == FormatStyle::LK_Java) { 1734 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws)) 1735 return 1; 1736 if (Right.is(Keywords.kw_implements)) 1737 return 2; 1738 if (Left.is(tok::comma) && Left.NestingLevel == 0) 1739 return 3; 1740 } else if (Style.Language == FormatStyle::LK_JavaScript) { 1741 if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma)) 1742 return 100; 1743 if (Left.is(TT_JsTypeColon)) 1744 return 35; 1745 } 1746 1747 if (Left.is(tok::comma) || (Right.is(tok::identifier) && Right.Next && 1748 Right.Next->is(TT_DictLiteral))) 1749 return 1; 1750 if (Right.is(tok::l_square)) { 1751 if (Style.Language == FormatStyle::LK_Proto) 1752 return 1; 1753 if (Left.is(tok::r_square)) 1754 return 25; 1755 // Slightly prefer formatting local lambda definitions like functions. 1756 if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal)) 1757 return 35; 1758 if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare, 1759 TT_ArrayInitializerLSquare)) 1760 return 500; 1761 } 1762 1763 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) || 1764 Right.is(tok::kw_operator)) { 1765 if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt) 1766 return 3; 1767 if (Left.is(TT_StartOfName)) 1768 return 110; 1769 if (InFunctionDecl && Right.NestingLevel == 0) 1770 return Style.PenaltyReturnTypeOnItsOwnLine; 1771 return 200; 1772 } 1773 if (Right.is(TT_PointerOrReference)) 1774 return 190; 1775 if (Right.is(TT_LambdaArrow)) 1776 return 110; 1777 if (Left.is(tok::equal) && Right.is(tok::l_brace)) 1778 return 150; 1779 if (Left.is(TT_CastRParen)) 1780 return 100; 1781 if (Left.is(tok::coloncolon) || 1782 (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto)) 1783 return 500; 1784 if (Left.isOneOf(tok::kw_class, tok::kw_struct)) 1785 return 5000; 1786 1787 if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon)) 1788 return 2; 1789 1790 if (Right.isMemberAccess()) { 1791 // Breaking before the "./->" of a chained call/member access is reasonably 1792 // cheap, as formatting those with one call per line is generally 1793 // desirable. In particular, it should be cheaper to break before the call 1794 // than it is to break inside a call's parameters, which could lead to weird 1795 // "hanging" indents. The exception is the very last "./->" to support this 1796 // frequent pattern: 1797 // 1798 // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc( 1799 // dddddddd); 1800 // 1801 // which might otherwise be blown up onto many lines. Here, clang-format 1802 // won't produce "hanging" indents anyway as there is no other trailing 1803 // call. 1804 // 1805 // Also apply higher penalty is not a call as that might lead to a wrapping 1806 // like: 1807 // 1808 // aaaaaaa 1809 // .aaaaaaaaa.bbbbbbbb(cccccccc); 1810 return !Right.NextOperator || !Right.NextOperator->Previous->closesScope() 1811 ? 150 1812 : 35; 1813 } 1814 1815 if (Right.is(TT_TrailingAnnotation) && 1816 (!Right.Next || Right.Next->isNot(tok::l_paren))) { 1817 // Moving trailing annotations to the next line is fine for ObjC method 1818 // declarations. 1819 if (Line.startsWith(TT_ObjCMethodSpecifier)) 1820 return 10; 1821 // Generally, breaking before a trailing annotation is bad unless it is 1822 // function-like. It seems to be especially preferable to keep standard 1823 // annotations (i.e. "const", "final" and "override") on the same line. 1824 // Use a slightly higher penalty after ")" so that annotations like 1825 // "const override" are kept together. 1826 bool is_short_annotation = Right.TokenText.size() < 10; 1827 return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0); 1828 } 1829 1830 // In for-loops, prefer breaking at ',' and ';'. 1831 if (Line.startsWith(tok::kw_for) && Left.is(tok::equal)) 1832 return 4; 1833 1834 // In Objective-C method expressions, prefer breaking before "param:" over 1835 // breaking after it. 1836 if (Right.is(TT_SelectorName)) 1837 return 0; 1838 if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr)) 1839 return Line.MightBeFunctionDecl ? 50 : 500; 1840 1841 if (Left.is(tok::l_paren) && InFunctionDecl && 1842 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign) 1843 return 100; 1844 if (Left.is(tok::l_paren) && Left.Previous && 1845 Left.Previous->isOneOf(tok::kw_if, tok::kw_for)) 1846 return 1000; 1847 if (Left.is(tok::equal) && InFunctionDecl) 1848 return 110; 1849 if (Right.is(tok::r_brace)) 1850 return 1; 1851 if (Left.is(TT_TemplateOpener)) 1852 return 100; 1853 if (Left.opensScope()) { 1854 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign) 1855 return 0; 1856 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter 1857 : 19; 1858 } 1859 if (Left.is(TT_JavaAnnotation)) 1860 return 50; 1861 1862 if (Right.is(tok::lessless)) { 1863 if (Left.is(tok::string_literal) && 1864 (Right.NextOperator || Right.OperatorIndex != 1)) { 1865 StringRef Content = Left.TokenText; 1866 if (Content.startswith("\"")) 1867 Content = Content.drop_front(1); 1868 if (Content.endswith("\"")) 1869 Content = Content.drop_back(1); 1870 Content = Content.trim(); 1871 if (Content.size() > 1 && 1872 (Content.back() == ':' || Content.back() == '=')) 1873 return 25; 1874 } 1875 return 1; // Breaking at a << is really cheap. 1876 } 1877 if (Left.is(TT_ConditionalExpr)) 1878 return prec::Conditional; 1879 prec::Level Level = Left.getPrecedence(); 1880 if (Level != prec::Unknown) 1881 return Level; 1882 Level = Right.getPrecedence(); 1883 if (Level != prec::Unknown) 1884 return Level; 1885 1886 return 3; 1887 } 1888 1889 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line, 1890 const FormatToken &Left, 1891 const FormatToken &Right) { 1892 if (Left.is(tok::kw_return) && Right.isNot(tok::semi)) 1893 return true; 1894 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty && 1895 Left.Tok.getObjCKeywordID() == tok::objc_property) 1896 return true; 1897 if (Right.is(tok::hashhash)) 1898 return Left.is(tok::hash); 1899 if (Left.isOneOf(tok::hashhash, tok::hash)) 1900 return Right.is(tok::hash); 1901 if (Left.is(tok::l_paren) && Right.is(tok::r_paren)) 1902 return Style.SpaceInEmptyParentheses; 1903 if (Left.is(tok::l_paren) || Right.is(tok::r_paren)) 1904 return (Right.is(TT_CastRParen) || 1905 (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen))) 1906 ? Style.SpacesInCStyleCastParentheses 1907 : Style.SpacesInParentheses; 1908 if (Right.isOneOf(tok::semi, tok::comma)) 1909 return false; 1910 if (Right.is(tok::less) && 1911 (Left.is(tok::kw_template) || 1912 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList))) 1913 return true; 1914 if (Left.isOneOf(tok::exclaim, tok::tilde)) 1915 return false; 1916 if (Left.is(tok::at) && 1917 Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant, 1918 tok::numeric_constant, tok::l_paren, tok::l_brace, 1919 tok::kw_true, tok::kw_false)) 1920 return false; 1921 if (Left.is(tok::colon)) 1922 return !Left.is(TT_ObjCMethodExpr); 1923 if (Left.is(tok::coloncolon)) 1924 return false; 1925 if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) 1926 return false; 1927 if (Right.is(tok::ellipsis)) 1928 return Left.Tok.isLiteral(); 1929 if (Left.is(tok::l_square) && Right.is(tok::amp)) 1930 return false; 1931 if (Right.is(TT_PointerOrReference)) 1932 return (Left.is(tok::r_paren) && Left.MatchingParen && 1933 (Left.MatchingParen->is(TT_OverloadedOperatorLParen) || 1934 (Left.MatchingParen->Previous && 1935 Left.MatchingParen->Previous->is(TT_FunctionDeclarationName)))) || 1936 (Left.Tok.isLiteral() || 1937 (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) && 1938 (Style.PointerAlignment != FormatStyle::PAS_Left || 1939 Line.IsMultiVariableDeclStmt))); 1940 if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) && 1941 (!Left.is(TT_PointerOrReference) || 1942 (Style.PointerAlignment != FormatStyle::PAS_Right && 1943 !Line.IsMultiVariableDeclStmt))) 1944 return true; 1945 if (Left.is(TT_PointerOrReference)) 1946 return Right.Tok.isLiteral() || 1947 Right.isOneOf(TT_BlockComment, Keywords.kw_final, 1948 Keywords.kw_override) || 1949 (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) || 1950 (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare, 1951 tok::l_paren) && 1952 (Style.PointerAlignment != FormatStyle::PAS_Right && 1953 !Line.IsMultiVariableDeclStmt) && 1954 Left.Previous && 1955 !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon)); 1956 if (Right.is(tok::star) && Left.is(tok::l_paren)) 1957 return false; 1958 if (Left.is(tok::l_square)) 1959 return (Left.is(TT_ArrayInitializerLSquare) && 1960 Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) || 1961 (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets && 1962 Right.isNot(tok::r_square)); 1963 if (Right.is(tok::r_square)) 1964 return Right.MatchingParen && 1965 ((Style.SpacesInContainerLiterals && 1966 Right.MatchingParen->is(TT_ArrayInitializerLSquare)) || 1967 (Style.SpacesInSquareBrackets && 1968 Right.MatchingParen->is(TT_ArraySubscriptLSquare))); 1969 if (Right.is(tok::l_square) && 1970 !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare) && 1971 !Left.isOneOf(tok::numeric_constant, TT_DictLiteral)) 1972 return false; 1973 if (Left.is(tok::l_brace) && Right.is(tok::r_brace)) 1974 return !Left.Children.empty(); // No spaces in "{}". 1975 if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) || 1976 (Right.is(tok::r_brace) && Right.MatchingParen && 1977 Right.MatchingParen->BlockKind != BK_Block)) 1978 return !Style.Cpp11BracedListStyle; 1979 if (Left.is(TT_BlockComment)) 1980 return !Left.TokenText.endswith("=*/"); 1981 if (Right.is(tok::l_paren)) { 1982 if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen)) 1983 return true; 1984 return Line.Type == LT_ObjCDecl || Left.is(tok::semi) || 1985 (Style.SpaceBeforeParens != FormatStyle::SBPO_Never && 1986 (Left.isOneOf(tok::kw_if, tok::pp_elif, tok::kw_for, tok::kw_while, 1987 tok::kw_switch, tok::kw_case, TT_ForEachMacro, 1988 TT_ObjCForIn) || 1989 (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch, 1990 tok::kw_new, tok::kw_delete) && 1991 (!Left.Previous || Left.Previous->isNot(tok::period))))) || 1992 (Style.SpaceBeforeParens == FormatStyle::SBPO_Always && 1993 (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() || 1994 Left.is(tok::r_paren)) && 1995 Line.Type != LT_PreprocessorDirective); 1996 } 1997 if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword) 1998 return false; 1999 if (Right.is(TT_UnaryOperator)) 2000 return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) && 2001 (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr)); 2002 if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square, 2003 tok::r_paren) || 2004 Left.isSimpleTypeSpecifier()) && 2005 Right.is(tok::l_brace) && Right.getNextNonComment() && 2006 Right.BlockKind != BK_Block) 2007 return false; 2008 if (Left.is(tok::period) || Right.is(tok::period)) 2009 return false; 2010 if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L") 2011 return false; 2012 if (Left.is(TT_TemplateCloser) && Left.MatchingParen && 2013 Left.MatchingParen->Previous && 2014 Left.MatchingParen->Previous->is(tok::period)) 2015 // A.<B>DoSomething(); 2016 return false; 2017 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square)) 2018 return false; 2019 return true; 2020 } 2021 2022 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, 2023 const FormatToken &Right) { 2024 const FormatToken &Left = *Right.Previous; 2025 if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo()) 2026 return true; // Never ever merge two identifiers. 2027 if (Style.Language == FormatStyle::LK_Cpp) { 2028 if (Left.is(tok::kw_operator)) 2029 return Right.is(tok::coloncolon); 2030 } else if (Style.Language == FormatStyle::LK_Proto) { 2031 if (Right.is(tok::period) && 2032 Left.isOneOf(Keywords.kw_optional, Keywords.kw_required, 2033 Keywords.kw_repeated, Keywords.kw_extend)) 2034 return true; 2035 if (Right.is(tok::l_paren) && 2036 Left.isOneOf(Keywords.kw_returns, Keywords.kw_option)) 2037 return true; 2038 } else if (Style.Language == FormatStyle::LK_JavaScript) { 2039 if (Left.isOneOf(Keywords.kw_let, Keywords.kw_var, TT_JsFatArrow, 2040 Keywords.kw_in, Keywords.kw_of)) 2041 return true; 2042 if (Left.is(tok::kw_default) && Left.Previous && 2043 Left.Previous->is(tok::kw_export)) 2044 return true; 2045 if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace)) 2046 return true; 2047 if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion)) 2048 return false; 2049 if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) && 2050 Line.First->isOneOf(Keywords.kw_import, tok::kw_export)) 2051 return false; 2052 if (Left.is(tok::ellipsis)) 2053 return false; 2054 if (Left.is(TT_TemplateCloser) && 2055 !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square, 2056 Keywords.kw_implements, Keywords.kw_extends)) 2057 // Type assertions ('<type>expr') are not followed by whitespace. Other 2058 // locations that should have whitespace following are identified by the 2059 // above set of follower tokens. 2060 return false; 2061 } else if (Style.Language == FormatStyle::LK_Java) { 2062 if (Left.is(tok::r_square) && Right.is(tok::l_brace)) 2063 return true; 2064 if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren)) 2065 return Style.SpaceBeforeParens != FormatStyle::SBPO_Never; 2066 if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private, 2067 tok::kw_protected) || 2068 Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract, 2069 Keywords.kw_native)) && 2070 Right.is(TT_TemplateOpener)) 2071 return true; 2072 } 2073 if (Left.is(TT_ImplicitStringLiteral)) 2074 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd(); 2075 if (Line.Type == LT_ObjCMethodDecl) { 2076 if (Left.is(TT_ObjCMethodSpecifier)) 2077 return true; 2078 if (Left.is(tok::r_paren) && Right.is(tok::identifier)) 2079 // Don't space between ')' and <id> 2080 return false; 2081 } 2082 if (Line.Type == LT_ObjCProperty && 2083 (Right.is(tok::equal) || Left.is(tok::equal))) 2084 return false; 2085 2086 if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) || 2087 Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow)) 2088 return true; 2089 if (Right.is(TT_OverloadedOperatorLParen)) 2090 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always; 2091 if (Left.is(tok::comma)) 2092 return true; 2093 if (Right.is(tok::comma)) 2094 return false; 2095 if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen)) 2096 return true; 2097 if (Right.is(tok::colon)) { 2098 if (Line.First->isOneOf(tok::kw_case, tok::kw_default) || 2099 !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi)) 2100 return false; 2101 if (Right.is(TT_ObjCMethodExpr)) 2102 return false; 2103 if (Left.is(tok::question)) 2104 return false; 2105 if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon)) 2106 return false; 2107 if (Right.is(TT_DictLiteral)) 2108 return Style.SpacesInContainerLiterals; 2109 return true; 2110 } 2111 if (Left.is(TT_UnaryOperator)) 2112 return Right.is(TT_BinaryOperator); 2113 2114 // If the next token is a binary operator or a selector name, we have 2115 // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly. 2116 if (Left.is(TT_CastRParen)) 2117 return Style.SpaceAfterCStyleCast || 2118 Right.isOneOf(TT_BinaryOperator, TT_SelectorName); 2119 2120 if (Left.is(tok::greater) && Right.is(tok::greater)) 2121 return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) && 2122 (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles); 2123 if (Right.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) || 2124 Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar)) 2125 return false; 2126 if (!Style.SpaceBeforeAssignmentOperators && 2127 Right.getPrecedence() == prec::Assignment) 2128 return false; 2129 if (Right.is(tok::coloncolon) && Left.isNot(tok::l_brace)) 2130 return (Left.is(TT_TemplateOpener) && 2131 Style.Standard == FormatStyle::LS_Cpp03) || 2132 !(Left.isOneOf(tok::identifier, tok::l_paren, tok::r_paren, 2133 tok::l_square) || 2134 Left.isOneOf(TT_TemplateCloser, TT_TemplateOpener)); 2135 if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser))) 2136 return Style.SpacesInAngles; 2137 if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) || 2138 (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && 2139 !Right.is(tok::r_paren))) 2140 return true; 2141 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) && 2142 Right.isNot(TT_FunctionTypeLParen)) 2143 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always; 2144 if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) && 2145 Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen)) 2146 return false; 2147 if (Right.is(tok::less) && Left.isNot(tok::l_paren) && 2148 Line.startsWith(tok::hash)) 2149 return true; 2150 if (Right.is(TT_TrailingUnaryOperator)) 2151 return false; 2152 if (Left.is(TT_RegexLiteral)) 2153 return false; 2154 return spaceRequiredBetween(Line, Left, Right); 2155 } 2156 2157 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style. 2158 static bool isAllmanBrace(const FormatToken &Tok) { 2159 return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block && 2160 !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral); 2161 } 2162 2163 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line, 2164 const FormatToken &Right) { 2165 const FormatToken &Left = *Right.Previous; 2166 if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0) 2167 return true; 2168 2169 if (Style.Language == FormatStyle::LK_JavaScript) { 2170 // FIXME: This might apply to other languages and token kinds. 2171 if (Right.is(tok::char_constant) && Left.is(tok::plus) && Left.Previous && 2172 Left.Previous->is(tok::char_constant)) 2173 return true; 2174 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 && 2175 Left.Previous && Left.Previous->is(tok::equal) && 2176 Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export, 2177 tok::kw_const) && 2178 // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match 2179 // above. 2180 !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let)) 2181 // Object literals on the top level of a file are treated as "enum-style". 2182 // Each key/value pair is put on a separate line, instead of bin-packing. 2183 return true; 2184 if (Left.is(tok::l_brace) && Line.Level == 0 && 2185 (Line.startsWith(tok::kw_enum) || 2186 Line.startsWith(tok::kw_export, tok::kw_enum))) 2187 // JavaScript top-level enum key/value pairs are put on separate lines 2188 // instead of bin-packing. 2189 return true; 2190 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) && 2191 !Left.Children.empty()) 2192 // Support AllowShortFunctionsOnASingleLine for JavaScript. 2193 return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None || 2194 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty || 2195 (Left.NestingLevel == 0 && Line.Level == 0 && 2196 Style.AllowShortFunctionsOnASingleLine == 2197 FormatStyle::SFS_Inline); 2198 } else if (Style.Language == FormatStyle::LK_Java) { 2199 if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next && 2200 Right.Next->is(tok::string_literal)) 2201 return true; 2202 } 2203 2204 // If the last token before a '}' is a comma or a trailing comment, the 2205 // intention is to insert a line break after it in order to make shuffling 2206 // around entries easier. 2207 const FormatToken *BeforeClosingBrace = nullptr; 2208 if (Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) && 2209 Left.BlockKind != BK_Block && Left.MatchingParen) 2210 BeforeClosingBrace = Left.MatchingParen->Previous; 2211 else if (Right.MatchingParen && 2212 Right.MatchingParen->isOneOf(tok::l_brace, 2213 TT_ArrayInitializerLSquare)) 2214 BeforeClosingBrace = &Left; 2215 if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) || 2216 BeforeClosingBrace->isTrailingComment())) 2217 return true; 2218 2219 if (Right.is(tok::comment)) 2220 return Left.BlockKind != BK_BracedInit && 2221 Left.isNot(TT_CtorInitializerColon) && 2222 (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline); 2223 if (Left.isTrailingComment()) 2224 return true; 2225 if (Left.isStringLiteral() && 2226 (Right.isStringLiteral() || Right.is(TT_ObjCStringLiteral))) 2227 return true; 2228 if (Right.Previous->IsUnterminatedLiteral) 2229 return true; 2230 if (Right.is(tok::lessless) && Right.Next && 2231 Right.Previous->is(tok::string_literal) && 2232 Right.Next->is(tok::string_literal)) 2233 return true; 2234 if (Right.Previous->ClosesTemplateDeclaration && 2235 Right.Previous->MatchingParen && 2236 Right.Previous->MatchingParen->NestingLevel == 0 && 2237 Style.AlwaysBreakTemplateDeclarations) 2238 return true; 2239 if ((Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) && 2240 Style.BreakConstructorInitializersBeforeComma && 2241 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine) 2242 return true; 2243 if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\"")) 2244 // Raw string literals are special wrt. line breaks. The author has made a 2245 // deliberate choice and might have aligned the contents of the string 2246 // literal accordingly. Thus, we try keep existing line breaks. 2247 return Right.NewlinesBefore > 0; 2248 if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 && 2249 Style.Language == FormatStyle::LK_Proto) 2250 // Don't put enums onto single lines in protocol buffers. 2251 return true; 2252 if (Right.is(TT_InlineASMBrace)) 2253 return Right.HasUnescapedNewline; 2254 if (isAllmanBrace(Left) || isAllmanBrace(Right)) 2255 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) || 2256 (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) || 2257 (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct); 2258 if (Style.Language == FormatStyle::LK_Proto && Left.isNot(tok::l_brace) && 2259 Right.is(TT_SelectorName)) 2260 return true; 2261 if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine) 2262 return true; 2263 2264 if ((Style.Language == FormatStyle::LK_Java || 2265 Style.Language == FormatStyle::LK_JavaScript) && 2266 Left.is(TT_LeadingJavaAnnotation) && 2267 Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) && 2268 (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations)) 2269 return true; 2270 2271 return false; 2272 } 2273 2274 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line, 2275 const FormatToken &Right) { 2276 const FormatToken &Left = *Right.Previous; 2277 2278 // Language-specific stuff. 2279 if (Style.Language == FormatStyle::LK_Java) { 2280 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends, 2281 Keywords.kw_implements)) 2282 return false; 2283 if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends, 2284 Keywords.kw_implements)) 2285 return true; 2286 } else if (Style.Language == FormatStyle::LK_JavaScript) { 2287 if (Left.is(tok::kw_return)) 2288 return false; // Otherwise a semicolon is inserted. 2289 if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace)) 2290 return false; 2291 if (Left.is(TT_JsTypeColon)) 2292 return true; 2293 if (Right.NestingLevel == 0 && Right.is(Keywords.kw_is)) 2294 return false; 2295 if (Left.is(Keywords.kw_in)) 2296 return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None; 2297 if (Right.is(Keywords.kw_in)) 2298 return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None; 2299 } 2300 2301 if (Left.is(tok::at)) 2302 return false; 2303 if (Left.Tok.getObjCKeywordID() == tok::objc_interface) 2304 return false; 2305 if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation)) 2306 return !Right.is(tok::l_paren); 2307 if (Right.is(TT_PointerOrReference)) 2308 return Line.IsMultiVariableDeclStmt || 2309 (Style.PointerAlignment == FormatStyle::PAS_Right && 2310 (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName))); 2311 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) || 2312 Right.is(tok::kw_operator)) 2313 return true; 2314 if (Left.is(TT_PointerOrReference)) 2315 return false; 2316 if (Right.isTrailingComment()) 2317 // We rely on MustBreakBefore being set correctly here as we should not 2318 // change the "binding" behavior of a comment. 2319 // The first comment in a braced lists is always interpreted as belonging to 2320 // the first list element. Otherwise, it should be placed outside of the 2321 // list. 2322 return Left.BlockKind == BK_BracedInit; 2323 if (Left.is(tok::question) && Right.is(tok::colon)) 2324 return false; 2325 if (Right.is(TT_ConditionalExpr) || Right.is(tok::question)) 2326 return Style.BreakBeforeTernaryOperators; 2327 if (Left.is(TT_ConditionalExpr) || Left.is(tok::question)) 2328 return !Style.BreakBeforeTernaryOperators; 2329 if (Right.is(TT_InheritanceColon)) 2330 return true; 2331 if (Right.is(tok::colon) && 2332 !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon)) 2333 return false; 2334 if (Left.is(tok::colon) && (Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr))) 2335 return true; 2336 if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next && 2337 Right.Next->is(TT_ObjCMethodExpr))) 2338 return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls. 2339 if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty) 2340 return true; 2341 if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen)) 2342 return true; 2343 if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen, 2344 TT_OverloadedOperator)) 2345 return false; 2346 if (Left.is(TT_RangeBasedForLoopColon)) 2347 return true; 2348 if (Right.is(TT_RangeBasedForLoopColon)) 2349 return false; 2350 if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) || 2351 Left.is(tok::kw_operator)) 2352 return false; 2353 if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) && 2354 Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0) 2355 return false; 2356 if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen)) 2357 return false; 2358 if (Left.is(tok::l_paren) && Left.Previous && 2359 (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen))) 2360 return false; 2361 if (Right.is(TT_ImplicitStringLiteral)) 2362 return false; 2363 2364 if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser)) 2365 return false; 2366 if (Right.is(tok::r_square) && Right.MatchingParen && 2367 Right.MatchingParen->is(TT_LambdaLSquare)) 2368 return false; 2369 2370 // We only break before r_brace if there was a corresponding break before 2371 // the l_brace, which is tracked by BreakBeforeClosingBrace. 2372 if (Right.is(tok::r_brace)) 2373 return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block; 2374 2375 // Allow breaking after a trailing annotation, e.g. after a method 2376 // declaration. 2377 if (Left.is(TT_TrailingAnnotation)) 2378 return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren, 2379 tok::less, tok::coloncolon); 2380 2381 if (Right.is(tok::kw___attribute)) 2382 return true; 2383 2384 if (Left.is(tok::identifier) && Right.is(tok::string_literal)) 2385 return true; 2386 2387 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral)) 2388 return true; 2389 2390 if (Left.is(TT_CtorInitializerComma) && 2391 Style.BreakConstructorInitializersBeforeComma) 2392 return false; 2393 if (Right.is(TT_CtorInitializerComma) && 2394 Style.BreakConstructorInitializersBeforeComma) 2395 return true; 2396 if ((Left.is(tok::greater) && Right.is(tok::greater)) || 2397 (Left.is(tok::less) && Right.is(tok::less))) 2398 return false; 2399 if (Right.is(TT_BinaryOperator) && 2400 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None && 2401 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All || 2402 Right.getPrecedence() != prec::Assignment)) 2403 return true; 2404 if (Left.is(TT_ArrayInitializerLSquare)) 2405 return true; 2406 if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const)) 2407 return true; 2408 if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) && 2409 !Left.isOneOf(tok::arrowstar, tok::lessless) && 2410 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All && 2411 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None || 2412 Left.getPrecedence() == prec::Assignment)) 2413 return true; 2414 return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace, 2415 tok::kw_class, tok::kw_struct) || 2416 Right.isMemberAccess() || 2417 Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless, 2418 tok::colon, tok::l_square, tok::at) || 2419 (Left.is(tok::r_paren) && 2420 Right.isOneOf(tok::identifier, tok::kw_const)) || 2421 (Left.is(tok::l_paren) && !Right.is(tok::r_paren)); 2422 } 2423 2424 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) { 2425 llvm::errs() << "AnnotatedTokens:\n"; 2426 const FormatToken *Tok = Line.First; 2427 while (Tok) { 2428 llvm::errs() << " M=" << Tok->MustBreakBefore 2429 << " C=" << Tok->CanBreakBefore 2430 << " T=" << getTokenTypeName(Tok->Type) 2431 << " S=" << Tok->SpacesRequiredBefore 2432 << " B=" << Tok->BlockParameterCount 2433 << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName() 2434 << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind 2435 << " FakeLParens="; 2436 for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i) 2437 llvm::errs() << Tok->FakeLParens[i] << "/"; 2438 llvm::errs() << " FakeRParens=" << Tok->FakeRParens << "\n"; 2439 if (!Tok->Next) 2440 assert(Tok == Line.Last); 2441 Tok = Tok->Next; 2442 } 2443 llvm::errs() << "----\n"; 2444 } 2445 2446 } // namespace format 2447 } // namespace clang 2448