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