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