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