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