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