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