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