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