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