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