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