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