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