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