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