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 "clang/Basic/TokenKinds.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/Support/Debug.h" 21 22 #define DEBUG_TYPE "format-token-annotator" 23 24 namespace clang { 25 namespace format { 26 27 namespace { 28 29 /// Returns \c true if the line starts with a token that can start a statement 30 /// with an initializer. 31 static bool startsWithInitStatement(const AnnotatedLine &Line) { 32 return Line.startsWith(tok::kw_for) || Line.startsWith(tok::kw_if) || 33 Line.startsWith(tok::kw_switch); 34 } 35 36 /// Returns \c true if the token can be used as an identifier in 37 /// an Objective-C \c \@selector, \c false otherwise. 38 /// 39 /// Because getFormattingLangOpts() always lexes source code as 40 /// Objective-C++, C++ keywords like \c new and \c delete are 41 /// lexed as tok::kw_*, not tok::identifier, even for Objective-C. 42 /// 43 /// For Objective-C and Objective-C++, both identifiers and keywords 44 /// are valid inside @selector(...) (or a macro which 45 /// invokes @selector(...)). So, we allow treat any identifier or 46 /// keyword as a potential Objective-C selector component. 47 static bool canBeObjCSelectorComponent(const FormatToken &Tok) { 48 return Tok.Tok.getIdentifierInfo() != nullptr; 49 } 50 51 /// With `Left` being '(', check if we're at either `[...](` or 52 /// `[...]<...>(`, where the [ opens a lambda capture list. 53 static bool isLambdaParameterList(const FormatToken *Left) { 54 // Skip <...> if present. 55 if (Left->Previous && Left->Previous->is(tok::greater) && 56 Left->Previous->MatchingParen && 57 Left->Previous->MatchingParen->is(TT_TemplateOpener)) 58 Left = Left->Previous->MatchingParen; 59 60 // Check for `[...]`. 61 return Left->Previous && Left->Previous->is(tok::r_square) && 62 Left->Previous->MatchingParen && 63 Left->Previous->MatchingParen->is(TT_LambdaLSquare); 64 } 65 66 /// Returns \c true if the token is followed by a boolean condition, \c false 67 /// otherwise. 68 static bool isKeywordWithCondition(const FormatToken &Tok) { 69 return Tok.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while, tok::kw_switch, 70 tok::kw_constexpr, tok::kw_catch); 71 } 72 73 /// A parser that gathers additional information about tokens. 74 /// 75 /// The \c TokenAnnotator tries to match parenthesis and square brakets and 76 /// store a parenthesis levels. It also tries to resolve matching "<" and ">" 77 /// into template parameter lists. 78 class AnnotatingParser { 79 public: 80 AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line, 81 const AdditionalKeywords &Keywords) 82 : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false), 83 Keywords(Keywords) { 84 Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false)); 85 resetTokenMetadata(); 86 } 87 88 private: 89 bool parseAngle() { 90 if (!CurrentToken || !CurrentToken->Previous) 91 return false; 92 if (NonTemplateLess.count(CurrentToken->Previous)) 93 return false; 94 95 const FormatToken &Previous = *CurrentToken->Previous; // The '<'. 96 if (Previous.Previous) { 97 if (Previous.Previous->Tok.isLiteral()) 98 return false; 99 if (Previous.Previous->is(tok::r_paren) && Contexts.size() > 1 && 100 (!Previous.Previous->MatchingParen || 101 !Previous.Previous->MatchingParen->is(TT_OverloadedOperatorLParen))) 102 return false; 103 } 104 105 FormatToken *Left = CurrentToken->Previous; 106 Left->ParentBracket = Contexts.back().ContextKind; 107 ScopedContextCreator ContextCreator(*this, tok::less, 12); 108 109 // If this angle is in the context of an expression, we need to be more 110 // hesitant to detect it as opening template parameters. 111 bool InExprContext = Contexts.back().IsExpression; 112 113 Contexts.back().IsExpression = false; 114 // If there's a template keyword before the opening angle bracket, this is a 115 // template parameter, not an argument. 116 if (Left->Previous && Left->Previous->isNot(tok::kw_template)) 117 Contexts.back().ContextType = Context::TemplateArgument; 118 119 if (Style.Language == FormatStyle::LK_Java && 120 CurrentToken->is(tok::question)) 121 next(); 122 123 while (CurrentToken) { 124 if (CurrentToken->is(tok::greater)) { 125 // Try to do a better job at looking for ">>" within the condition of 126 // a statement. Conservatively insert spaces between consecutive ">" 127 // tokens to prevent splitting right bitshift operators and potentially 128 // altering program semantics. This check is overly conservative and 129 // will prevent spaces from being inserted in select nested template 130 // parameter cases, but should not alter program semantics. 131 if (CurrentToken->Next && CurrentToken->Next->is(tok::greater) && 132 Left->ParentBracket != tok::less && 133 (isKeywordWithCondition(*Line.First) || 134 CurrentToken->getStartOfNonWhitespace() == 135 CurrentToken->Next->getStartOfNonWhitespace().getLocWithOffset( 136 -1))) 137 return false; 138 Left->MatchingParen = CurrentToken; 139 CurrentToken->MatchingParen = Left; 140 // In TT_Proto, we must distignuish between: 141 // map<key, value> 142 // msg < item: data > 143 // msg: < item: data > 144 // In TT_TextProto, map<key, value> does not occur. 145 if (Style.Language == FormatStyle::LK_TextProto || 146 (Style.Language == FormatStyle::LK_Proto && Left->Previous && 147 Left->Previous->isOneOf(TT_SelectorName, TT_DictLiteral))) 148 CurrentToken->setType(TT_DictLiteral); 149 else 150 CurrentToken->setType(TT_TemplateCloser); 151 next(); 152 return true; 153 } 154 if (CurrentToken->is(tok::question) && 155 Style.Language == FormatStyle::LK_Java) { 156 next(); 157 continue; 158 } 159 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace) || 160 (CurrentToken->isOneOf(tok::colon, tok::question) && InExprContext && 161 !Style.isCSharp() && Style.Language != FormatStyle::LK_Proto && 162 Style.Language != FormatStyle::LK_TextProto)) 163 return false; 164 // If a && or || is found and interpreted as a binary operator, this set 165 // of angles is likely part of something like "a < b && c > d". If the 166 // angles are inside an expression, the ||/&& might also be a binary 167 // operator that was misinterpreted because we are parsing template 168 // parameters. 169 // FIXME: This is getting out of hand, write a decent parser. 170 if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) && 171 CurrentToken->Previous->is(TT_BinaryOperator) && 172 Contexts[Contexts.size() - 2].IsExpression && 173 !Line.startsWith(tok::kw_template)) 174 return false; 175 updateParameterCount(Left, CurrentToken); 176 if (Style.Language == FormatStyle::LK_Proto) { 177 if (FormatToken *Previous = CurrentToken->getPreviousNonComment()) { 178 if (CurrentToken->is(tok::colon) || 179 (CurrentToken->isOneOf(tok::l_brace, tok::less) && 180 Previous->isNot(tok::colon))) 181 Previous->setType(TT_SelectorName); 182 } 183 } 184 if (!consumeToken()) 185 return false; 186 } 187 return false; 188 } 189 190 bool parseUntouchableParens() { 191 while (CurrentToken) { 192 CurrentToken->Finalized = true; 193 switch (CurrentToken->Tok.getKind()) { 194 case tok::l_paren: 195 next(); 196 if (!parseUntouchableParens()) 197 return false; 198 continue; 199 case tok::r_paren: 200 next(); 201 return true; 202 default: 203 // no-op 204 break; 205 } 206 next(); 207 } 208 return false; 209 } 210 211 bool parseParens(bool LookForDecls = false) { 212 if (!CurrentToken) 213 return false; 214 assert(CurrentToken->Previous && "Unknown previous token"); 215 FormatToken &OpeningParen = *CurrentToken->Previous; 216 assert(OpeningParen.is(tok::l_paren)); 217 FormatToken *PrevNonComment = OpeningParen.getPreviousNonComment(); 218 OpeningParen.ParentBracket = Contexts.back().ContextKind; 219 ScopedContextCreator ContextCreator(*this, tok::l_paren, 1); 220 221 // FIXME: This is a bit of a hack. Do better. 222 Contexts.back().ColonIsForRangeExpr = 223 Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr; 224 225 if (OpeningParen.Previous && 226 OpeningParen.Previous->is(TT_UntouchableMacroFunc)) { 227 OpeningParen.Finalized = true; 228 return parseUntouchableParens(); 229 } 230 231 bool StartsObjCMethodExpr = false; 232 if (FormatToken *MaybeSel = OpeningParen.Previous) { 233 // @selector( starts a selector. 234 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous && 235 MaybeSel->Previous->is(tok::at)) 236 StartsObjCMethodExpr = true; 237 } 238 239 if (OpeningParen.is(TT_OverloadedOperatorLParen)) { 240 // Find the previous kw_operator token. 241 FormatToken *Prev = &OpeningParen; 242 while (!Prev->is(tok::kw_operator)) { 243 Prev = Prev->Previous; 244 assert(Prev && "Expect a kw_operator prior to the OperatorLParen!"); 245 } 246 247 // If faced with "a.operator*(argument)" or "a->operator*(argument)", 248 // i.e. the operator is called as a member function, 249 // then the argument must be an expression. 250 bool OperatorCalledAsMemberFunction = 251 Prev->Previous && Prev->Previous->isOneOf(tok::period, tok::arrow); 252 Contexts.back().IsExpression = OperatorCalledAsMemberFunction; 253 } else if (Style.isJavaScript() && 254 (Line.startsWith(Keywords.kw_type, tok::identifier) || 255 Line.startsWith(tok::kw_export, Keywords.kw_type, 256 tok::identifier))) { 257 // type X = (...); 258 // export type X = (...); 259 Contexts.back().IsExpression = false; 260 } else if (OpeningParen.Previous && 261 (OpeningParen.Previous->isOneOf(tok::kw_static_assert, 262 tok::kw_while, tok::l_paren, 263 tok::comma, TT_BinaryOperator) || 264 OpeningParen.Previous->isIf())) { 265 // static_assert, if and while usually contain expressions. 266 Contexts.back().IsExpression = true; 267 } else if (Style.isJavaScript() && OpeningParen.Previous && 268 (OpeningParen.Previous->is(Keywords.kw_function) || 269 (OpeningParen.Previous->endsSequence(tok::identifier, 270 Keywords.kw_function)))) { 271 // function(...) or function f(...) 272 Contexts.back().IsExpression = false; 273 } else if (Style.isJavaScript() && OpeningParen.Previous && 274 OpeningParen.Previous->is(TT_JsTypeColon)) { 275 // let x: (SomeType); 276 Contexts.back().IsExpression = false; 277 } else if (isLambdaParameterList(&OpeningParen)) { 278 // This is a parameter list of a lambda expression. 279 Contexts.back().IsExpression = false; 280 } else if (Line.InPPDirective && 281 (!OpeningParen.Previous || 282 !OpeningParen.Previous->is(tok::identifier))) { 283 Contexts.back().IsExpression = true; 284 } else if (Contexts[Contexts.size() - 2].CaretFound) { 285 // This is the parameter list of an ObjC block. 286 Contexts.back().IsExpression = false; 287 } else if (OpeningParen.Previous && 288 OpeningParen.Previous->is(TT_ForEachMacro)) { 289 // The first argument to a foreach macro is a declaration. 290 Contexts.back().ContextType = Context::ForEachMacro; 291 Contexts.back().IsExpression = false; 292 } else if (OpeningParen.Previous && OpeningParen.Previous->MatchingParen && 293 OpeningParen.Previous->MatchingParen->is(TT_ObjCBlockLParen)) { 294 Contexts.back().IsExpression = false; 295 } else if (!Line.MustBeDeclaration && !Line.InPPDirective) { 296 bool IsForOrCatch = 297 OpeningParen.Previous && 298 OpeningParen.Previous->isOneOf(tok::kw_for, tok::kw_catch); 299 Contexts.back().IsExpression = !IsForOrCatch; 300 } 301 302 // Infer the role of the l_paren based on the previous token if we haven't 303 // detected one one yet. 304 if (PrevNonComment && OpeningParen.is(TT_Unknown)) { 305 if (PrevNonComment->is(tok::kw___attribute)) { 306 OpeningParen.setType(TT_AttributeParen); 307 } else if (PrevNonComment->isOneOf(TT_TypenameMacro, tok::kw_decltype, 308 tok::kw_typeof, tok::kw__Atomic, 309 tok::kw___underlying_type)) { 310 OpeningParen.setType(TT_TypeDeclarationParen); 311 // decltype() and typeof() usually contain expressions. 312 if (PrevNonComment->isOneOf(tok::kw_decltype, tok::kw_typeof)) 313 Contexts.back().IsExpression = true; 314 } 315 } 316 317 if (StartsObjCMethodExpr) { 318 Contexts.back().ColonIsObjCMethodExpr = true; 319 OpeningParen.setType(TT_ObjCMethodExpr); 320 } 321 322 // MightBeFunctionType and ProbablyFunctionType are used for 323 // function pointer and reference types as well as Objective-C 324 // block types: 325 // 326 // void (*FunctionPointer)(void); 327 // void (&FunctionReference)(void); 328 // void (&&FunctionReference)(void); 329 // void (^ObjCBlock)(void); 330 bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression; 331 bool ProbablyFunctionType = 332 CurrentToken->isOneOf(tok::star, tok::amp, tok::ampamp, tok::caret); 333 bool HasMultipleLines = false; 334 bool HasMultipleParametersOnALine = false; 335 bool MightBeObjCForRangeLoop = 336 OpeningParen.Previous && OpeningParen.Previous->is(tok::kw_for); 337 FormatToken *PossibleObjCForInToken = nullptr; 338 while (CurrentToken) { 339 // LookForDecls is set when "if (" has been seen. Check for 340 // 'identifier' '*' 'identifier' followed by not '=' -- this 341 // '*' has to be a binary operator but determineStarAmpUsage() will 342 // categorize it as an unary operator, so set the right type here. 343 if (LookForDecls && CurrentToken->Next) { 344 FormatToken *Prev = CurrentToken->getPreviousNonComment(); 345 if (Prev) { 346 FormatToken *PrevPrev = Prev->getPreviousNonComment(); 347 FormatToken *Next = CurrentToken->Next; 348 if (PrevPrev && PrevPrev->is(tok::identifier) && 349 Prev->isOneOf(tok::star, tok::amp, tok::ampamp) && 350 CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) { 351 Prev->setType(TT_BinaryOperator); 352 LookForDecls = false; 353 } 354 } 355 } 356 357 if (CurrentToken->Previous->is(TT_PointerOrReference) && 358 CurrentToken->Previous->Previous->isOneOf(tok::l_paren, 359 tok::coloncolon)) 360 ProbablyFunctionType = true; 361 if (CurrentToken->is(tok::comma)) 362 MightBeFunctionType = false; 363 if (CurrentToken->Previous->is(TT_BinaryOperator)) 364 Contexts.back().IsExpression = true; 365 if (CurrentToken->is(tok::r_paren)) { 366 if (OpeningParen.isNot(TT_CppCastLParen) && MightBeFunctionType && 367 ProbablyFunctionType && CurrentToken->Next && 368 (CurrentToken->Next->is(tok::l_paren) || 369 (CurrentToken->Next->is(tok::l_square) && Line.MustBeDeclaration))) 370 OpeningParen.setType(OpeningParen.Next->is(tok::caret) 371 ? TT_ObjCBlockLParen 372 : TT_FunctionTypeLParen); 373 OpeningParen.MatchingParen = CurrentToken; 374 CurrentToken->MatchingParen = &OpeningParen; 375 376 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) && 377 OpeningParen.Previous && OpeningParen.Previous->is(tok::l_paren)) { 378 // Detect the case where macros are used to generate lambdas or 379 // function bodies, e.g.: 380 // auto my_lambda = MACRO((Type *type, int i) { .. body .. }); 381 for (FormatToken *Tok = &OpeningParen; Tok != CurrentToken; 382 Tok = Tok->Next) 383 if (Tok->is(TT_BinaryOperator) && 384 Tok->isOneOf(tok::star, tok::amp, tok::ampamp)) 385 Tok->setType(TT_PointerOrReference); 386 } 387 388 if (StartsObjCMethodExpr) { 389 CurrentToken->setType(TT_ObjCMethodExpr); 390 if (Contexts.back().FirstObjCSelectorName) { 391 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 392 Contexts.back().LongestObjCSelectorName; 393 } 394 } 395 396 if (OpeningParen.is(TT_AttributeParen)) 397 CurrentToken->setType(TT_AttributeParen); 398 if (OpeningParen.is(TT_TypeDeclarationParen)) 399 CurrentToken->setType(TT_TypeDeclarationParen); 400 if (OpeningParen.Previous && 401 OpeningParen.Previous->is(TT_JavaAnnotation)) 402 CurrentToken->setType(TT_JavaAnnotation); 403 if (OpeningParen.Previous && 404 OpeningParen.Previous->is(TT_LeadingJavaAnnotation)) 405 CurrentToken->setType(TT_LeadingJavaAnnotation); 406 if (OpeningParen.Previous && 407 OpeningParen.Previous->is(TT_AttributeSquare)) 408 CurrentToken->setType(TT_AttributeSquare); 409 410 if (!HasMultipleLines) 411 OpeningParen.setPackingKind(PPK_Inconclusive); 412 else if (HasMultipleParametersOnALine) 413 OpeningParen.setPackingKind(PPK_BinPacked); 414 else 415 OpeningParen.setPackingKind(PPK_OnePerLine); 416 417 next(); 418 return true; 419 } 420 if (CurrentToken->isOneOf(tok::r_square, tok::r_brace)) 421 return false; 422 423 if (CurrentToken->is(tok::l_brace) && OpeningParen.is(TT_ObjCBlockLParen)) 424 OpeningParen.setType(TT_Unknown); 425 if (CurrentToken->is(tok::comma) && CurrentToken->Next && 426 !CurrentToken->Next->HasUnescapedNewline && 427 !CurrentToken->Next->isTrailingComment()) 428 HasMultipleParametersOnALine = true; 429 bool ProbablyFunctionTypeLParen = 430 (CurrentToken->is(tok::l_paren) && CurrentToken->Next && 431 CurrentToken->Next->isOneOf(tok::star, tok::amp, tok::caret)); 432 if ((CurrentToken->Previous->isOneOf(tok::kw_const, tok::kw_auto) || 433 CurrentToken->Previous->isSimpleTypeSpecifier()) && 434 !(CurrentToken->is(tok::l_brace) || 435 (CurrentToken->is(tok::l_paren) && !ProbablyFunctionTypeLParen))) 436 Contexts.back().IsExpression = false; 437 if (CurrentToken->isOneOf(tok::semi, tok::colon)) { 438 MightBeObjCForRangeLoop = false; 439 if (PossibleObjCForInToken) { 440 PossibleObjCForInToken->setType(TT_Unknown); 441 PossibleObjCForInToken = nullptr; 442 } 443 } 444 if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) { 445 PossibleObjCForInToken = CurrentToken; 446 PossibleObjCForInToken->setType(TT_ObjCForIn); 447 } 448 // When we discover a 'new', we set CanBeExpression to 'false' in order to 449 // parse the type correctly. Reset that after a comma. 450 if (CurrentToken->is(tok::comma)) 451 Contexts.back().CanBeExpression = true; 452 453 FormatToken *Tok = CurrentToken; 454 if (!consumeToken()) 455 return false; 456 updateParameterCount(&OpeningParen, Tok); 457 if (CurrentToken && CurrentToken->HasUnescapedNewline) 458 HasMultipleLines = true; 459 } 460 return false; 461 } 462 463 bool isCSharpAttributeSpecifier(const FormatToken &Tok) { 464 if (!Style.isCSharp()) 465 return false; 466 467 // `identifier[i]` is not an attribute. 468 if (Tok.Previous && Tok.Previous->is(tok::identifier)) 469 return false; 470 471 // Chains of [] in `identifier[i][j][k]` are not attributes. 472 if (Tok.Previous && Tok.Previous->is(tok::r_square)) { 473 auto *MatchingParen = Tok.Previous->MatchingParen; 474 if (!MatchingParen || MatchingParen->is(TT_ArraySubscriptLSquare)) 475 return false; 476 } 477 478 const FormatToken *AttrTok = Tok.Next; 479 if (!AttrTok) 480 return false; 481 482 // Just an empty declaration e.g. string []. 483 if (AttrTok->is(tok::r_square)) 484 return false; 485 486 // Move along the tokens inbetween the '[' and ']' e.g. [STAThread]. 487 while (AttrTok && AttrTok->isNot(tok::r_square)) 488 AttrTok = AttrTok->Next; 489 490 if (!AttrTok) 491 return false; 492 493 // Allow an attribute to be the only content of a file. 494 AttrTok = AttrTok->Next; 495 if (!AttrTok) 496 return true; 497 498 // Limit this to being an access modifier that follows. 499 if (AttrTok->isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected, 500 tok::comment, tok::kw_class, tok::kw_static, 501 tok::l_square, Keywords.kw_internal)) 502 return true; 503 504 // incase its a [XXX] retval func(.... 505 if (AttrTok->Next && 506 AttrTok->Next->startsSequence(tok::identifier, tok::l_paren)) 507 return true; 508 509 return false; 510 } 511 512 bool isCpp11AttributeSpecifier(const FormatToken &Tok) { 513 if (!Style.isCpp() || !Tok.startsSequence(tok::l_square, tok::l_square)) 514 return false; 515 // The first square bracket is part of an ObjC array literal 516 if (Tok.Previous && Tok.Previous->is(tok::at)) 517 return false; 518 const FormatToken *AttrTok = Tok.Next->Next; 519 if (!AttrTok) 520 return false; 521 // C++17 '[[using ns: foo, bar(baz, blech)]]' 522 // We assume nobody will name an ObjC variable 'using'. 523 if (AttrTok->startsSequence(tok::kw_using, tok::identifier, tok::colon)) 524 return true; 525 if (AttrTok->isNot(tok::identifier)) 526 return false; 527 while (AttrTok && !AttrTok->startsSequence(tok::r_square, tok::r_square)) { 528 // ObjC message send. We assume nobody will use : in a C++11 attribute 529 // specifier parameter, although this is technically valid: 530 // [[foo(:)]]. 531 if (AttrTok->is(tok::colon) || 532 AttrTok->startsSequence(tok::identifier, tok::identifier) || 533 AttrTok->startsSequence(tok::r_paren, tok::identifier)) 534 return false; 535 if (AttrTok->is(tok::ellipsis)) 536 return true; 537 AttrTok = AttrTok->Next; 538 } 539 return AttrTok && AttrTok->startsSequence(tok::r_square, tok::r_square); 540 } 541 542 bool parseSquare() { 543 if (!CurrentToken) 544 return false; 545 546 // A '[' could be an index subscript (after an identifier or after 547 // ')' or ']'), it could be the start of an Objective-C method 548 // expression, it could the start of an Objective-C array literal, 549 // or it could be a C++ attribute specifier [[foo::bar]]. 550 FormatToken *Left = CurrentToken->Previous; 551 Left->ParentBracket = Contexts.back().ContextKind; 552 FormatToken *Parent = Left->getPreviousNonComment(); 553 554 // Cases where '>' is followed by '['. 555 // In C++, this can happen either in array of templates (foo<int>[10]) 556 // or when array is a nested template type (unique_ptr<type1<type2>[]>). 557 bool CppArrayTemplates = 558 Style.isCpp() && Parent && Parent->is(TT_TemplateCloser) && 559 (Contexts.back().CanBeExpression || Contexts.back().IsExpression || 560 Contexts.back().ContextType == Context::TemplateArgument); 561 562 bool IsCpp11AttributeSpecifier = isCpp11AttributeSpecifier(*Left) || 563 Contexts.back().InCpp11AttributeSpecifier; 564 565 // Treat C# Attributes [STAThread] much like C++ attributes [[...]]. 566 bool IsCSharpAttributeSpecifier = 567 isCSharpAttributeSpecifier(*Left) || 568 Contexts.back().InCSharpAttributeSpecifier; 569 570 bool InsideInlineASM = Line.startsWith(tok::kw_asm); 571 bool IsCppStructuredBinding = Left->isCppStructuredBinding(Style); 572 bool StartsObjCMethodExpr = 573 !IsCppStructuredBinding && !InsideInlineASM && !CppArrayTemplates && 574 Style.isCpp() && !IsCpp11AttributeSpecifier && 575 !IsCSharpAttributeSpecifier && Contexts.back().CanBeExpression && 576 Left->isNot(TT_LambdaLSquare) && 577 !CurrentToken->isOneOf(tok::l_brace, tok::r_square) && 578 (!Parent || 579 Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren, 580 tok::kw_return, tok::kw_throw) || 581 Parent->isUnaryOperator() || 582 // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen. 583 Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) || 584 (getBinOpPrecedence(Parent->Tok.getKind(), true, true) > 585 prec::Unknown)); 586 bool ColonFound = false; 587 588 unsigned BindingIncrease = 1; 589 if (IsCppStructuredBinding) { 590 Left->setType(TT_StructuredBindingLSquare); 591 } else if (Left->is(TT_Unknown)) { 592 if (StartsObjCMethodExpr) { 593 Left->setType(TT_ObjCMethodExpr); 594 } else if (InsideInlineASM) { 595 Left->setType(TT_InlineASMSymbolicNameLSquare); 596 } else if (IsCpp11AttributeSpecifier) { 597 Left->setType(TT_AttributeSquare); 598 } else if (Style.isJavaScript() && Parent && 599 Contexts.back().ContextKind == tok::l_brace && 600 Parent->isOneOf(tok::l_brace, tok::comma)) { 601 Left->setType(TT_JsComputedPropertyName); 602 } else if (Style.isCpp() && Contexts.back().ContextKind == tok::l_brace && 603 Parent && Parent->isOneOf(tok::l_brace, tok::comma)) { 604 Left->setType(TT_DesignatedInitializerLSquare); 605 } else if (IsCSharpAttributeSpecifier) { 606 Left->setType(TT_AttributeSquare); 607 } else if (CurrentToken->is(tok::r_square) && Parent && 608 Parent->is(TT_TemplateCloser)) { 609 Left->setType(TT_ArraySubscriptLSquare); 610 } else if (Style.Language == FormatStyle::LK_Proto || 611 Style.Language == FormatStyle::LK_TextProto) { 612 // Square braces in LK_Proto can either be message field attributes: 613 // 614 // optional Aaa aaa = 1 [ 615 // (aaa) = aaa 616 // ]; 617 // 618 // extensions 123 [ 619 // (aaa) = aaa 620 // ]; 621 // 622 // or text proto extensions (in options): 623 // 624 // option (Aaa.options) = { 625 // [type.type/type] { 626 // key: value 627 // } 628 // } 629 // 630 // or repeated fields (in options): 631 // 632 // option (Aaa.options) = { 633 // keys: [ 1, 2, 3 ] 634 // } 635 // 636 // In the first and the third case we want to spread the contents inside 637 // the square braces; in the second we want to keep them inline. 638 Left->setType(TT_ArrayInitializerLSquare); 639 if (!Left->endsSequence(tok::l_square, tok::numeric_constant, 640 tok::equal) && 641 !Left->endsSequence(tok::l_square, tok::numeric_constant, 642 tok::identifier) && 643 !Left->endsSequence(tok::l_square, tok::colon, TT_SelectorName)) { 644 Left->setType(TT_ProtoExtensionLSquare); 645 BindingIncrease = 10; 646 } 647 } else if (!CppArrayTemplates && Parent && 648 Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at, 649 tok::comma, tok::l_paren, tok::l_square, 650 tok::question, tok::colon, tok::kw_return, 651 // Should only be relevant to JavaScript: 652 tok::kw_default)) { 653 Left->setType(TT_ArrayInitializerLSquare); 654 } else { 655 BindingIncrease = 10; 656 Left->setType(TT_ArraySubscriptLSquare); 657 } 658 } 659 660 ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease); 661 Contexts.back().IsExpression = true; 662 if (Style.isJavaScript() && Parent && Parent->is(TT_JsTypeColon)) 663 Contexts.back().IsExpression = false; 664 665 Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr; 666 Contexts.back().InCpp11AttributeSpecifier = IsCpp11AttributeSpecifier; 667 Contexts.back().InCSharpAttributeSpecifier = IsCSharpAttributeSpecifier; 668 669 while (CurrentToken) { 670 if (CurrentToken->is(tok::r_square)) { 671 if (IsCpp11AttributeSpecifier) 672 CurrentToken->setType(TT_AttributeSquare); 673 if (IsCSharpAttributeSpecifier) 674 CurrentToken->setType(TT_AttributeSquare); 675 else if (((CurrentToken->Next && 676 CurrentToken->Next->is(tok::l_paren)) || 677 (CurrentToken->Previous && 678 CurrentToken->Previous->Previous == Left)) && 679 Left->is(TT_ObjCMethodExpr)) { 680 // An ObjC method call is rarely followed by an open parenthesis. It 681 // also can't be composed of just one token, unless it's a macro that 682 // will be expanded to more tokens. 683 // FIXME: Do we incorrectly label ":" with this? 684 StartsObjCMethodExpr = false; 685 Left->setType(TT_Unknown); 686 } 687 if (StartsObjCMethodExpr && CurrentToken->Previous != Left) { 688 CurrentToken->setType(TT_ObjCMethodExpr); 689 // If we haven't seen a colon yet, make sure the last identifier 690 // before the r_square is tagged as a selector name component. 691 if (!ColonFound && CurrentToken->Previous && 692 CurrentToken->Previous->is(TT_Unknown) && 693 canBeObjCSelectorComponent(*CurrentToken->Previous)) 694 CurrentToken->Previous->setType(TT_SelectorName); 695 // determineStarAmpUsage() thinks that '*' '[' is allocating an 696 // array of pointers, but if '[' starts a selector then '*' is a 697 // binary operator. 698 if (Parent && Parent->is(TT_PointerOrReference)) 699 Parent->overwriteFixedType(TT_BinaryOperator); 700 } 701 // An arrow after an ObjC method expression is not a lambda arrow. 702 if (CurrentToken->getType() == TT_ObjCMethodExpr && 703 CurrentToken->Next && CurrentToken->Next->is(TT_LambdaArrow)) 704 CurrentToken->Next->overwriteFixedType(TT_Unknown); 705 Left->MatchingParen = CurrentToken; 706 CurrentToken->MatchingParen = Left; 707 // FirstObjCSelectorName is set when a colon is found. This does 708 // not work, however, when the method has no parameters. 709 // Here, we set FirstObjCSelectorName when the end of the method call is 710 // reached, in case it was not set already. 711 if (!Contexts.back().FirstObjCSelectorName) { 712 FormatToken *Previous = CurrentToken->getPreviousNonComment(); 713 if (Previous && Previous->is(TT_SelectorName)) { 714 Previous->ObjCSelectorNameParts = 1; 715 Contexts.back().FirstObjCSelectorName = Previous; 716 } 717 } else { 718 Left->ParameterCount = 719 Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts; 720 } 721 if (Contexts.back().FirstObjCSelectorName) { 722 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 723 Contexts.back().LongestObjCSelectorName; 724 if (Left->BlockParameterCount > 1) 725 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0; 726 } 727 next(); 728 return true; 729 } 730 if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace)) 731 return false; 732 if (CurrentToken->is(tok::colon)) { 733 if (IsCpp11AttributeSpecifier && 734 CurrentToken->endsSequence(tok::colon, tok::identifier, 735 tok::kw_using)) { 736 // Remember that this is a [[using ns: foo]] C++ attribute, so we 737 // don't add a space before the colon (unlike other colons). 738 CurrentToken->setType(TT_AttributeColon); 739 } else if (Left->isOneOf(TT_ArraySubscriptLSquare, 740 TT_DesignatedInitializerLSquare)) { 741 Left->setType(TT_ObjCMethodExpr); 742 StartsObjCMethodExpr = true; 743 Contexts.back().ColonIsObjCMethodExpr = true; 744 if (Parent && Parent->is(tok::r_paren)) 745 // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen. 746 Parent->setType(TT_CastRParen); 747 } 748 ColonFound = true; 749 } 750 if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) && 751 !ColonFound) 752 Left->setType(TT_ArrayInitializerLSquare); 753 FormatToken *Tok = CurrentToken; 754 if (!consumeToken()) 755 return false; 756 updateParameterCount(Left, Tok); 757 } 758 return false; 759 } 760 761 bool couldBeInStructArrayInitializer() const { 762 if (Contexts.size() < 2) 763 return false; 764 // We want to back up no more then 2 context levels i.e. 765 // . { { <- 766 const auto End = std::next(Contexts.rbegin(), 2); 767 auto Last = Contexts.rbegin(); 768 unsigned Depth = 0; 769 for (; Last != End; ++Last) 770 if (Last->ContextKind == tok::l_brace) 771 ++Depth; 772 return Depth == 2 && Last->ContextKind != tok::l_brace; 773 } 774 775 bool parseBrace() { 776 if (!CurrentToken) 777 return true; 778 779 assert(CurrentToken->Previous); 780 FormatToken &OpeningBrace = *CurrentToken->Previous; 781 assert(OpeningBrace.is(tok::l_brace)); 782 OpeningBrace.ParentBracket = Contexts.back().ContextKind; 783 784 if (Contexts.back().CaretFound) 785 OpeningBrace.overwriteFixedType(TT_ObjCBlockLBrace); 786 Contexts.back().CaretFound = false; 787 788 ScopedContextCreator ContextCreator(*this, tok::l_brace, 1); 789 Contexts.back().ColonIsDictLiteral = true; 790 if (OpeningBrace.is(BK_BracedInit)) 791 Contexts.back().IsExpression = true; 792 if (Style.isJavaScript() && OpeningBrace.Previous && 793 OpeningBrace.Previous->is(TT_JsTypeColon)) 794 Contexts.back().IsExpression = false; 795 796 unsigned CommaCount = 0; 797 while (CurrentToken) { 798 if (CurrentToken->is(tok::r_brace)) { 799 assert(OpeningBrace.Optional == CurrentToken->Optional); 800 OpeningBrace.MatchingParen = CurrentToken; 801 CurrentToken->MatchingParen = &OpeningBrace; 802 if (Style.AlignArrayOfStructures != FormatStyle::AIAS_None) { 803 if (OpeningBrace.ParentBracket == tok::l_brace && 804 couldBeInStructArrayInitializer() && CommaCount > 0) 805 Contexts.back().ContextType = Context::StructArrayInitializer; 806 } 807 next(); 808 return true; 809 } 810 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square)) 811 return false; 812 updateParameterCount(&OpeningBrace, CurrentToken); 813 if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) { 814 FormatToken *Previous = CurrentToken->getPreviousNonComment(); 815 if (Previous->is(TT_JsTypeOptionalQuestion)) 816 Previous = Previous->getPreviousNonComment(); 817 if ((CurrentToken->is(tok::colon) && 818 (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) || 819 Style.Language == FormatStyle::LK_Proto || 820 Style.Language == FormatStyle::LK_TextProto) { 821 OpeningBrace.setType(TT_DictLiteral); 822 if (Previous->Tok.getIdentifierInfo() || 823 Previous->is(tok::string_literal)) 824 Previous->setType(TT_SelectorName); 825 } 826 if (CurrentToken->is(tok::colon) && OpeningBrace.is(TT_Unknown)) 827 OpeningBrace.setType(TT_DictLiteral); 828 else if (Style.isJavaScript()) 829 OpeningBrace.overwriteFixedType(TT_DictLiteral); 830 } 831 if (CurrentToken->is(tok::comma)) { 832 if (Style.isJavaScript()) 833 OpeningBrace.overwriteFixedType(TT_DictLiteral); 834 ++CommaCount; 835 } 836 if (!consumeToken()) 837 return false; 838 } 839 return true; 840 } 841 842 void updateParameterCount(FormatToken *Left, FormatToken *Current) { 843 // For ObjC methods, the number of parameters is calculated differently as 844 // method declarations have a different structure (the parameters are not 845 // inside a bracket scope). 846 if (Current->is(tok::l_brace) && Current->is(BK_Block)) 847 ++Left->BlockParameterCount; 848 if (Current->is(tok::comma)) { 849 ++Left->ParameterCount; 850 if (!Left->Role) 851 Left->Role.reset(new CommaSeparatedList(Style)); 852 Left->Role->CommaFound(Current); 853 } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) { 854 Left->ParameterCount = 1; 855 } 856 } 857 858 bool parseConditional() { 859 while (CurrentToken) { 860 if (CurrentToken->is(tok::colon)) { 861 CurrentToken->setType(TT_ConditionalExpr); 862 next(); 863 return true; 864 } 865 if (!consumeToken()) 866 return false; 867 } 868 return false; 869 } 870 871 bool parseTemplateDeclaration() { 872 if (CurrentToken && CurrentToken->is(tok::less)) { 873 CurrentToken->setType(TT_TemplateOpener); 874 next(); 875 if (!parseAngle()) 876 return false; 877 if (CurrentToken) 878 CurrentToken->Previous->ClosesTemplateDeclaration = true; 879 return true; 880 } 881 return false; 882 } 883 884 bool consumeToken() { 885 FormatToken *Tok = CurrentToken; 886 next(); 887 switch (Tok->Tok.getKind()) { 888 case tok::plus: 889 case tok::minus: 890 if (!Tok->Previous && Line.MustBeDeclaration) 891 Tok->setType(TT_ObjCMethodSpecifier); 892 break; 893 case tok::colon: 894 if (!Tok->Previous) 895 return false; 896 // Colons from ?: are handled in parseConditional(). 897 if (Style.isJavaScript()) { 898 if (Contexts.back().ColonIsForRangeExpr || // colon in for loop 899 (Contexts.size() == 1 && // switch/case labels 900 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) || 901 Contexts.back().ContextKind == tok::l_paren || // function params 902 Contexts.back().ContextKind == tok::l_square || // array type 903 (!Contexts.back().IsExpression && 904 Contexts.back().ContextKind == tok::l_brace) || // object type 905 (Contexts.size() == 1 && 906 Line.MustBeDeclaration)) { // method/property declaration 907 Contexts.back().IsExpression = false; 908 Tok->setType(TT_JsTypeColon); 909 break; 910 } 911 } else if (Style.isCSharp()) { 912 if (Contexts.back().InCSharpAttributeSpecifier) { 913 Tok->setType(TT_AttributeColon); 914 break; 915 } 916 if (Contexts.back().ContextKind == tok::l_paren) { 917 Tok->setType(TT_CSharpNamedArgumentColon); 918 break; 919 } 920 } 921 if (Line.First->isOneOf(Keywords.kw_module, Keywords.kw_import) || 922 Line.First->startsSequence(tok::kw_export, Keywords.kw_module) || 923 Line.First->startsSequence(tok::kw_export, Keywords.kw_import)) { 924 Tok->setType(TT_ModulePartitionColon); 925 } else if (Contexts.back().ColonIsDictLiteral || 926 Style.Language == FormatStyle::LK_Proto || 927 Style.Language == FormatStyle::LK_TextProto) { 928 Tok->setType(TT_DictLiteral); 929 if (Style.Language == FormatStyle::LK_TextProto) { 930 if (FormatToken *Previous = Tok->getPreviousNonComment()) 931 Previous->setType(TT_SelectorName); 932 } 933 } else if (Contexts.back().ColonIsObjCMethodExpr || 934 Line.startsWith(TT_ObjCMethodSpecifier)) { 935 Tok->setType(TT_ObjCMethodExpr); 936 const FormatToken *BeforePrevious = Tok->Previous->Previous; 937 // Ensure we tag all identifiers in method declarations as 938 // TT_SelectorName. 939 bool UnknownIdentifierInMethodDeclaration = 940 Line.startsWith(TT_ObjCMethodSpecifier) && 941 Tok->Previous->is(tok::identifier) && Tok->Previous->is(TT_Unknown); 942 if (!BeforePrevious || 943 // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen. 944 !(BeforePrevious->is(TT_CastRParen) || 945 (BeforePrevious->is(TT_ObjCMethodExpr) && 946 BeforePrevious->is(tok::colon))) || 947 BeforePrevious->is(tok::r_square) || 948 Contexts.back().LongestObjCSelectorName == 0 || 949 UnknownIdentifierInMethodDeclaration) { 950 Tok->Previous->setType(TT_SelectorName); 951 if (!Contexts.back().FirstObjCSelectorName) 952 Contexts.back().FirstObjCSelectorName = Tok->Previous; 953 else if (Tok->Previous->ColumnWidth > 954 Contexts.back().LongestObjCSelectorName) 955 Contexts.back().LongestObjCSelectorName = 956 Tok->Previous->ColumnWidth; 957 Tok->Previous->ParameterIndex = 958 Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts; 959 ++Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts; 960 } 961 } else if (Contexts.back().ColonIsForRangeExpr) { 962 Tok->setType(TT_RangeBasedForLoopColon); 963 } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) { 964 Tok->setType(TT_BitFieldColon); 965 } else if (Contexts.size() == 1 && 966 !Line.First->isOneOf(tok::kw_enum, tok::kw_case, 967 tok::kw_default)) { 968 FormatToken *Prev = Tok->getPreviousNonComment(); 969 if (!Prev) 970 break; 971 if (Prev->isOneOf(tok::r_paren, tok::kw_noexcept)) 972 Tok->setType(TT_CtorInitializerColon); 973 else if (Prev->is(tok::kw_try)) { 974 // Member initializer list within function try block. 975 FormatToken *PrevPrev = Prev->getPreviousNonComment(); 976 if (!PrevPrev) 977 break; 978 if (PrevPrev && PrevPrev->isOneOf(tok::r_paren, tok::kw_noexcept)) 979 Tok->setType(TT_CtorInitializerColon); 980 } else 981 Tok->setType(TT_InheritanceColon); 982 } else if (canBeObjCSelectorComponent(*Tok->Previous) && Tok->Next && 983 (Tok->Next->isOneOf(tok::r_paren, tok::comma) || 984 (canBeObjCSelectorComponent(*Tok->Next) && Tok->Next->Next && 985 Tok->Next->Next->is(tok::colon)))) { 986 // This handles a special macro in ObjC code where selectors including 987 // the colon are passed as macro arguments. 988 Tok->setType(TT_ObjCMethodExpr); 989 } else if (Contexts.back().ContextKind == tok::l_paren) { 990 Tok->setType(TT_InlineASMColon); 991 } 992 break; 993 case tok::pipe: 994 case tok::amp: 995 // | and & in declarations/type expressions represent union and 996 // intersection types, respectively. 997 if (Style.isJavaScript() && !Contexts.back().IsExpression) 998 Tok->setType(TT_JsTypeOperator); 999 break; 1000 case tok::kw_if: 1001 if (CurrentToken && 1002 CurrentToken->isOneOf(tok::kw_constexpr, tok::identifier)) 1003 next(); 1004 LLVM_FALLTHROUGH; 1005 case tok::kw_while: 1006 if (CurrentToken && CurrentToken->is(tok::l_paren)) { 1007 next(); 1008 if (!parseParens(/*LookForDecls=*/true)) 1009 return false; 1010 } 1011 break; 1012 case tok::kw_for: 1013 if (Style.isJavaScript()) { 1014 // x.for and {for: ...} 1015 if ((Tok->Previous && Tok->Previous->is(tok::period)) || 1016 (Tok->Next && Tok->Next->is(tok::colon))) 1017 break; 1018 // JS' for await ( ... 1019 if (CurrentToken && CurrentToken->is(Keywords.kw_await)) 1020 next(); 1021 } 1022 if (Style.isCpp() && CurrentToken && CurrentToken->is(tok::kw_co_await)) 1023 next(); 1024 Contexts.back().ColonIsForRangeExpr = true; 1025 if (!CurrentToken || CurrentToken->isNot(tok::l_paren)) 1026 return false; 1027 next(); 1028 if (!parseParens()) 1029 return false; 1030 break; 1031 case tok::l_paren: 1032 // When faced with 'operator()()', the kw_operator handler incorrectly 1033 // marks the first l_paren as a OverloadedOperatorLParen. Here, we make 1034 // the first two parens OverloadedOperators and the second l_paren an 1035 // OverloadedOperatorLParen. 1036 if (Tok->Previous && Tok->Previous->is(tok::r_paren) && 1037 Tok->Previous->MatchingParen && 1038 Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) { 1039 Tok->Previous->setType(TT_OverloadedOperator); 1040 Tok->Previous->MatchingParen->setType(TT_OverloadedOperator); 1041 Tok->setType(TT_OverloadedOperatorLParen); 1042 } 1043 1044 if (!parseParens()) 1045 return false; 1046 if (Line.MustBeDeclaration && Contexts.size() == 1 && 1047 !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) && 1048 !Tok->isOneOf(TT_TypeDeclarationParen, TT_RequiresExpressionLParen) && 1049 (!Tok->Previous || !Tok->Previous->isOneOf(tok::kw___attribute, 1050 TT_LeadingJavaAnnotation))) 1051 Line.MightBeFunctionDecl = true; 1052 break; 1053 case tok::l_square: 1054 if (!parseSquare()) 1055 return false; 1056 break; 1057 case tok::l_brace: 1058 if (Style.Language == FormatStyle::LK_TextProto) { 1059 FormatToken *Previous = Tok->getPreviousNonComment(); 1060 if (Previous && Previous->getType() != TT_DictLiteral) 1061 Previous->setType(TT_SelectorName); 1062 } 1063 if (!parseBrace()) 1064 return false; 1065 break; 1066 case tok::less: 1067 if (parseAngle()) { 1068 Tok->setType(TT_TemplateOpener); 1069 // In TT_Proto, we must distignuish between: 1070 // map<key, value> 1071 // msg < item: data > 1072 // msg: < item: data > 1073 // In TT_TextProto, map<key, value> does not occur. 1074 if (Style.Language == FormatStyle::LK_TextProto || 1075 (Style.Language == FormatStyle::LK_Proto && Tok->Previous && 1076 Tok->Previous->isOneOf(TT_SelectorName, TT_DictLiteral))) { 1077 Tok->setType(TT_DictLiteral); 1078 FormatToken *Previous = Tok->getPreviousNonComment(); 1079 if (Previous && Previous->getType() != TT_DictLiteral) 1080 Previous->setType(TT_SelectorName); 1081 } 1082 } else { 1083 Tok->setType(TT_BinaryOperator); 1084 NonTemplateLess.insert(Tok); 1085 CurrentToken = Tok; 1086 next(); 1087 } 1088 break; 1089 case tok::r_paren: 1090 case tok::r_square: 1091 return false; 1092 case tok::r_brace: 1093 // Lines can start with '}'. 1094 if (Tok->Previous) 1095 return false; 1096 break; 1097 case tok::greater: 1098 if (Style.Language != FormatStyle::LK_TextProto) 1099 Tok->setType(TT_BinaryOperator); 1100 if (Tok->Previous && Tok->Previous->is(TT_TemplateCloser)) 1101 Tok->SpacesRequiredBefore = 1; 1102 break; 1103 case tok::kw_operator: 1104 if (Style.Language == FormatStyle::LK_TextProto || 1105 Style.Language == FormatStyle::LK_Proto) 1106 break; 1107 while (CurrentToken && 1108 !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) { 1109 if (CurrentToken->isOneOf(tok::star, tok::amp)) 1110 CurrentToken->setType(TT_PointerOrReference); 1111 consumeToken(); 1112 if (CurrentToken && CurrentToken->is(tok::comma) && 1113 CurrentToken->Previous->isNot(tok::kw_operator)) 1114 break; 1115 if (CurrentToken && CurrentToken->Previous->isOneOf( 1116 TT_BinaryOperator, TT_UnaryOperator, tok::comma, 1117 tok::star, tok::arrow, tok::amp, tok::ampamp)) 1118 CurrentToken->Previous->setType(TT_OverloadedOperator); 1119 } 1120 if (CurrentToken && CurrentToken->is(tok::l_paren)) 1121 CurrentToken->setType(TT_OverloadedOperatorLParen); 1122 if (CurrentToken && CurrentToken->Previous->is(TT_BinaryOperator)) 1123 CurrentToken->Previous->setType(TT_OverloadedOperator); 1124 break; 1125 case tok::question: 1126 if (Style.isJavaScript() && Tok->Next && 1127 Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren, 1128 tok::r_brace)) { 1129 // Question marks before semicolons, colons, etc. indicate optional 1130 // types (fields, parameters), e.g. 1131 // function(x?: string, y?) {...} 1132 // class X { y?; } 1133 Tok->setType(TT_JsTypeOptionalQuestion); 1134 break; 1135 } 1136 // Declarations cannot be conditional expressions, this can only be part 1137 // of a type declaration. 1138 if (Line.MustBeDeclaration && !Contexts.back().IsExpression && 1139 Style.isJavaScript()) 1140 break; 1141 if (Style.isCSharp()) { 1142 // `Type?)`, `Type?>`, `Type? name;` and `Type? name =` can only be 1143 // nullable types. 1144 // Line.MustBeDeclaration will be true for `Type? name;`. 1145 if ((!Contexts.back().IsExpression && Line.MustBeDeclaration) || 1146 (Tok->Next && Tok->Next->isOneOf(tok::r_paren, tok::greater)) || 1147 (Tok->Next && Tok->Next->is(tok::identifier) && Tok->Next->Next && 1148 Tok->Next->Next->is(tok::equal))) { 1149 Tok->setType(TT_CSharpNullable); 1150 break; 1151 } 1152 } 1153 parseConditional(); 1154 break; 1155 case tok::kw_template: 1156 parseTemplateDeclaration(); 1157 break; 1158 case tok::comma: 1159 switch (Contexts.back().ContextType) { 1160 case Context::CtorInitializer: 1161 Tok->setType(TT_CtorInitializerComma); 1162 break; 1163 case Context::InheritanceList: 1164 Tok->setType(TT_InheritanceComma); 1165 break; 1166 default: 1167 if (Contexts.back().FirstStartOfName && 1168 (Contexts.size() == 1 || startsWithInitStatement(Line))) { 1169 Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true; 1170 Line.IsMultiVariableDeclStmt = true; 1171 } 1172 break; 1173 } 1174 if (Contexts.back().ContextType == Context::ForEachMacro) 1175 Contexts.back().IsExpression = true; 1176 break; 1177 case tok::identifier: 1178 if (Tok->isOneOf(Keywords.kw___has_include, 1179 Keywords.kw___has_include_next)) 1180 parseHasInclude(); 1181 if (Style.isCSharp() && Tok->is(Keywords.kw_where) && Tok->Next && 1182 Tok->Next->isNot(tok::l_paren)) { 1183 Tok->setType(TT_CSharpGenericTypeConstraint); 1184 parseCSharpGenericTypeConstraint(); 1185 } 1186 break; 1187 case tok::arrow: 1188 if (Tok->Previous && Tok->Previous->is(tok::kw_noexcept)) 1189 Tok->setType(TT_TrailingReturnArrow); 1190 break; 1191 default: 1192 break; 1193 } 1194 return true; 1195 } 1196 1197 void parseCSharpGenericTypeConstraint() { 1198 int OpenAngleBracketsCount = 0; 1199 while (CurrentToken) { 1200 if (CurrentToken->is(tok::less)) { 1201 // parseAngle is too greedy and will consume the whole line. 1202 CurrentToken->setType(TT_TemplateOpener); 1203 ++OpenAngleBracketsCount; 1204 next(); 1205 } else if (CurrentToken->is(tok::greater)) { 1206 CurrentToken->setType(TT_TemplateCloser); 1207 --OpenAngleBracketsCount; 1208 next(); 1209 } else if (CurrentToken->is(tok::comma) && OpenAngleBracketsCount == 0) { 1210 // We allow line breaks after GenericTypeConstraintComma's 1211 // so do not flag commas in Generics as GenericTypeConstraintComma's. 1212 CurrentToken->setType(TT_CSharpGenericTypeConstraintComma); 1213 next(); 1214 } else if (CurrentToken->is(Keywords.kw_where)) { 1215 CurrentToken->setType(TT_CSharpGenericTypeConstraint); 1216 next(); 1217 } else if (CurrentToken->is(tok::colon)) { 1218 CurrentToken->setType(TT_CSharpGenericTypeConstraintColon); 1219 next(); 1220 } else { 1221 next(); 1222 } 1223 } 1224 } 1225 1226 void parseIncludeDirective() { 1227 if (CurrentToken && CurrentToken->is(tok::less)) { 1228 next(); 1229 while (CurrentToken) { 1230 // Mark tokens up to the trailing line comments as implicit string 1231 // literals. 1232 if (CurrentToken->isNot(tok::comment) && 1233 !CurrentToken->TokenText.startswith("//")) 1234 CurrentToken->setType(TT_ImplicitStringLiteral); 1235 next(); 1236 } 1237 } 1238 } 1239 1240 void parseWarningOrError() { 1241 next(); 1242 // We still want to format the whitespace left of the first token of the 1243 // warning or error. 1244 next(); 1245 while (CurrentToken) { 1246 CurrentToken->setType(TT_ImplicitStringLiteral); 1247 next(); 1248 } 1249 } 1250 1251 void parsePragma() { 1252 next(); // Consume "pragma". 1253 if (CurrentToken && 1254 CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) { 1255 bool IsMark = CurrentToken->is(Keywords.kw_mark); 1256 next(); // Consume "mark". 1257 next(); // Consume first token (so we fix leading whitespace). 1258 while (CurrentToken) { 1259 if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator)) 1260 CurrentToken->setType(TT_ImplicitStringLiteral); 1261 next(); 1262 } 1263 } 1264 } 1265 1266 void parseHasInclude() { 1267 if (!CurrentToken || !CurrentToken->is(tok::l_paren)) 1268 return; 1269 next(); // '(' 1270 parseIncludeDirective(); 1271 next(); // ')' 1272 } 1273 1274 LineType parsePreprocessorDirective() { 1275 bool IsFirstToken = CurrentToken->IsFirst; 1276 LineType Type = LT_PreprocessorDirective; 1277 next(); 1278 if (!CurrentToken) 1279 return Type; 1280 1281 if (Style.isJavaScript() && IsFirstToken) { 1282 // JavaScript files can contain shebang lines of the form: 1283 // #!/usr/bin/env node 1284 // Treat these like C++ #include directives. 1285 while (CurrentToken) { 1286 // Tokens cannot be comments here. 1287 CurrentToken->setType(TT_ImplicitStringLiteral); 1288 next(); 1289 } 1290 return LT_ImportStatement; 1291 } 1292 1293 if (CurrentToken->is(tok::numeric_constant)) { 1294 CurrentToken->SpacesRequiredBefore = 1; 1295 return Type; 1296 } 1297 // Hashes in the middle of a line can lead to any strange token 1298 // sequence. 1299 if (!CurrentToken->Tok.getIdentifierInfo()) 1300 return Type; 1301 switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) { 1302 case tok::pp_include: 1303 case tok::pp_include_next: 1304 case tok::pp_import: 1305 next(); 1306 parseIncludeDirective(); 1307 Type = LT_ImportStatement; 1308 break; 1309 case tok::pp_error: 1310 case tok::pp_warning: 1311 parseWarningOrError(); 1312 break; 1313 case tok::pp_pragma: 1314 parsePragma(); 1315 break; 1316 case tok::pp_if: 1317 case tok::pp_elif: 1318 Contexts.back().IsExpression = true; 1319 next(); 1320 parseLine(); 1321 break; 1322 default: 1323 break; 1324 } 1325 while (CurrentToken) { 1326 FormatToken *Tok = CurrentToken; 1327 next(); 1328 if (Tok->is(tok::l_paren)) 1329 parseParens(); 1330 else if (Tok->isOneOf(Keywords.kw___has_include, 1331 Keywords.kw___has_include_next)) 1332 parseHasInclude(); 1333 } 1334 return Type; 1335 } 1336 1337 public: 1338 LineType parseLine() { 1339 if (!CurrentToken) 1340 return LT_Invalid; 1341 NonTemplateLess.clear(); 1342 if (CurrentToken->is(tok::hash)) 1343 return parsePreprocessorDirective(); 1344 1345 // Directly allow to 'import <string-literal>' to support protocol buffer 1346 // definitions (github.com/google/protobuf) or missing "#" (either way we 1347 // should not break the line). 1348 IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo(); 1349 if ((Style.Language == FormatStyle::LK_Java && 1350 CurrentToken->is(Keywords.kw_package)) || 1351 (Info && Info->getPPKeywordID() == tok::pp_import && 1352 CurrentToken->Next && 1353 CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier, 1354 tok::kw_static))) { 1355 next(); 1356 parseIncludeDirective(); 1357 return LT_ImportStatement; 1358 } 1359 1360 // If this line starts and ends in '<' and '>', respectively, it is likely 1361 // part of "#define <a/b.h>". 1362 if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) { 1363 parseIncludeDirective(); 1364 return LT_ImportStatement; 1365 } 1366 1367 // In .proto files, top-level options and package statements are very 1368 // similar to import statements and should not be line-wrapped. 1369 if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 && 1370 CurrentToken->isOneOf(Keywords.kw_option, Keywords.kw_package)) { 1371 next(); 1372 if (CurrentToken && CurrentToken->is(tok::identifier)) { 1373 while (CurrentToken) 1374 next(); 1375 return LT_ImportStatement; 1376 } 1377 } 1378 1379 bool KeywordVirtualFound = false; 1380 bool ImportStatement = false; 1381 1382 // import {...} from '...'; 1383 if (Style.isJavaScript() && CurrentToken->is(Keywords.kw_import)) 1384 ImportStatement = true; 1385 1386 while (CurrentToken) { 1387 if (CurrentToken->is(tok::kw_virtual)) 1388 KeywordVirtualFound = true; 1389 if (Style.isJavaScript()) { 1390 // export {...} from '...'; 1391 // An export followed by "from 'some string';" is a re-export from 1392 // another module identified by a URI and is treated as a 1393 // LT_ImportStatement (i.e. prevent wraps on it for long URIs). 1394 // Just "export {...};" or "export class ..." should not be treated as 1395 // an import in this sense. 1396 if (Line.First->is(tok::kw_export) && 1397 CurrentToken->is(Keywords.kw_from) && CurrentToken->Next && 1398 CurrentToken->Next->isStringLiteral()) 1399 ImportStatement = true; 1400 if (isClosureImportStatement(*CurrentToken)) 1401 ImportStatement = true; 1402 } 1403 if (!consumeToken()) 1404 return LT_Invalid; 1405 } 1406 if (KeywordVirtualFound) 1407 return LT_VirtualFunctionDecl; 1408 if (ImportStatement) 1409 return LT_ImportStatement; 1410 1411 if (Line.startsWith(TT_ObjCMethodSpecifier)) { 1412 if (Contexts.back().FirstObjCSelectorName) 1413 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 1414 Contexts.back().LongestObjCSelectorName; 1415 return LT_ObjCMethodDecl; 1416 } 1417 1418 for (const auto &ctx : Contexts) 1419 if (ctx.ContextType == Context::StructArrayInitializer) 1420 return LT_ArrayOfStructInitializer; 1421 1422 return LT_Other; 1423 } 1424 1425 private: 1426 bool isClosureImportStatement(const FormatToken &Tok) { 1427 // FIXME: Closure-library specific stuff should not be hard-coded but be 1428 // configurable. 1429 return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) && 1430 Tok.Next->Next && 1431 (Tok.Next->Next->TokenText == "module" || 1432 Tok.Next->Next->TokenText == "provide" || 1433 Tok.Next->Next->TokenText == "require" || 1434 Tok.Next->Next->TokenText == "requireType" || 1435 Tok.Next->Next->TokenText == "forwardDeclare") && 1436 Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren); 1437 } 1438 1439 void resetTokenMetadata() { 1440 if (!CurrentToken) 1441 return; 1442 1443 // Reset token type in case we have already looked at it and then 1444 // recovered from an error (e.g. failure to find the matching >). 1445 if (!CurrentToken->isTypeFinalized() && 1446 !CurrentToken->isOneOf( 1447 TT_LambdaLSquare, TT_LambdaLBrace, TT_AttributeMacro, TT_IfMacro, 1448 TT_ForEachMacro, TT_TypenameMacro, TT_FunctionLBrace, 1449 TT_ImplicitStringLiteral, TT_InlineASMBrace, TT_FatArrow, 1450 TT_LambdaArrow, TT_NamespaceMacro, TT_OverloadedOperator, 1451 TT_RegexLiteral, TT_TemplateString, TT_ObjCStringLiteral, 1452 TT_UntouchableMacroFunc, TT_StatementAttributeLikeMacro, 1453 TT_FunctionLikeOrFreestandingMacro, TT_ClassLBrace, TT_EnumLBrace, 1454 TT_RecordLBrace, TT_StructLBrace, TT_UnionLBrace, TT_RequiresClause, 1455 TT_RequiresClauseInARequiresExpression, TT_RequiresExpression, 1456 TT_RequiresExpressionLParen, TT_RequiresExpressionLBrace, 1457 TT_CompoundRequirementLBrace, TT_BracedListLBrace)) 1458 CurrentToken->setType(TT_Unknown); 1459 CurrentToken->Role.reset(); 1460 CurrentToken->MatchingParen = nullptr; 1461 CurrentToken->FakeLParens.clear(); 1462 CurrentToken->FakeRParens = 0; 1463 } 1464 1465 void next() { 1466 if (!CurrentToken) 1467 return; 1468 1469 CurrentToken->NestingLevel = Contexts.size() - 1; 1470 CurrentToken->BindingStrength = Contexts.back().BindingStrength; 1471 modifyContext(*CurrentToken); 1472 determineTokenType(*CurrentToken); 1473 CurrentToken = CurrentToken->Next; 1474 1475 resetTokenMetadata(); 1476 } 1477 1478 /// A struct to hold information valid in a specific context, e.g. 1479 /// a pair of parenthesis. 1480 struct Context { 1481 Context(tok::TokenKind ContextKind, unsigned BindingStrength, 1482 bool IsExpression) 1483 : ContextKind(ContextKind), BindingStrength(BindingStrength), 1484 IsExpression(IsExpression) {} 1485 1486 tok::TokenKind ContextKind; 1487 unsigned BindingStrength; 1488 bool IsExpression; 1489 unsigned LongestObjCSelectorName = 0; 1490 bool ColonIsForRangeExpr = false; 1491 bool ColonIsDictLiteral = false; 1492 bool ColonIsObjCMethodExpr = false; 1493 FormatToken *FirstObjCSelectorName = nullptr; 1494 FormatToken *FirstStartOfName = nullptr; 1495 bool CanBeExpression = true; 1496 bool CaretFound = false; 1497 bool InCpp11AttributeSpecifier = false; 1498 bool InCSharpAttributeSpecifier = false; 1499 enum { 1500 Unknown, 1501 // Like the part after `:` in a constructor. 1502 // Context(...) : IsExpression(IsExpression) 1503 CtorInitializer, 1504 // Like in the parentheses in a foreach. 1505 ForEachMacro, 1506 // Like the inheritance list in a class declaration. 1507 // class Input : public IO 1508 InheritanceList, 1509 // Like in the braced list. 1510 // int x[] = {}; 1511 StructArrayInitializer, 1512 // Like in `static_cast<int>`. 1513 TemplateArgument, 1514 } ContextType = Unknown; 1515 }; 1516 1517 /// Puts a new \c Context onto the stack \c Contexts for the lifetime 1518 /// of each instance. 1519 struct ScopedContextCreator { 1520 AnnotatingParser &P; 1521 1522 ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind, 1523 unsigned Increase) 1524 : P(P) { 1525 P.Contexts.push_back(Context(ContextKind, 1526 P.Contexts.back().BindingStrength + Increase, 1527 P.Contexts.back().IsExpression)); 1528 } 1529 1530 ~ScopedContextCreator() { 1531 if (P.Style.AlignArrayOfStructures != FormatStyle::AIAS_None) { 1532 if (P.Contexts.back().ContextType == Context::StructArrayInitializer) { 1533 P.Contexts.pop_back(); 1534 P.Contexts.back().ContextType = Context::StructArrayInitializer; 1535 return; 1536 } 1537 } 1538 P.Contexts.pop_back(); 1539 } 1540 }; 1541 1542 void modifyContext(const FormatToken &Current) { 1543 auto AssignmentStartsExpression = [&]() { 1544 if (Current.getPrecedence() != prec::Assignment) 1545 return false; 1546 1547 if (Line.First->isOneOf(tok::kw_using, tok::kw_return)) 1548 return false; 1549 if (Line.First->is(tok::kw_template)) { 1550 assert(Current.Previous); 1551 if (Current.Previous->is(tok::kw_operator)) { 1552 // `template ... operator=` cannot be an expression. 1553 return false; 1554 } 1555 1556 // `template` keyword can start a variable template. 1557 const FormatToken *Tok = Line.First->getNextNonComment(); 1558 assert(Tok); // Current token is on the same line. 1559 if (Tok->isNot(TT_TemplateOpener)) { 1560 // Explicit template instantiations do not have `<>`. 1561 return false; 1562 } 1563 1564 Tok = Tok->MatchingParen; 1565 if (!Tok) 1566 return false; 1567 Tok = Tok->getNextNonComment(); 1568 if (!Tok) 1569 return false; 1570 1571 if (Tok->isOneOf(tok::kw_class, tok::kw_enum, tok::kw_concept, 1572 tok::kw_struct, tok::kw_using)) 1573 return false; 1574 1575 return true; 1576 } 1577 1578 // Type aliases use `type X = ...;` in TypeScript and can be exported 1579 // using `export type ...`. 1580 if (Style.isJavaScript() && 1581 (Line.startsWith(Keywords.kw_type, tok::identifier) || 1582 Line.startsWith(tok::kw_export, Keywords.kw_type, tok::identifier))) 1583 return false; 1584 1585 return !Current.Previous || Current.Previous->isNot(tok::kw_operator); 1586 }; 1587 1588 if (AssignmentStartsExpression()) { 1589 Contexts.back().IsExpression = true; 1590 if (!Line.startsWith(TT_UnaryOperator)) { 1591 for (FormatToken *Previous = Current.Previous; 1592 Previous && Previous->Previous && 1593 !Previous->Previous->isOneOf(tok::comma, tok::semi); 1594 Previous = Previous->Previous) { 1595 if (Previous->isOneOf(tok::r_square, tok::r_paren)) { 1596 Previous = Previous->MatchingParen; 1597 if (!Previous) 1598 break; 1599 } 1600 if (Previous->opensScope()) 1601 break; 1602 if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) && 1603 Previous->isOneOf(tok::star, tok::amp, tok::ampamp) && 1604 Previous->Previous && Previous->Previous->isNot(tok::equal)) 1605 Previous->setType(TT_PointerOrReference); 1606 } 1607 } 1608 } else if (Current.is(tok::lessless) && 1609 (!Current.Previous || !Current.Previous->is(tok::kw_operator))) { 1610 Contexts.back().IsExpression = true; 1611 } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) { 1612 Contexts.back().IsExpression = true; 1613 } else if (Current.is(TT_TrailingReturnArrow)) { 1614 Contexts.back().IsExpression = false; 1615 } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) { 1616 Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java; 1617 } else if (Current.Previous && 1618 Current.Previous->is(TT_CtorInitializerColon)) { 1619 Contexts.back().IsExpression = true; 1620 Contexts.back().ContextType = Context::CtorInitializer; 1621 } else if (Current.Previous && Current.Previous->is(TT_InheritanceColon)) { 1622 Contexts.back().ContextType = Context::InheritanceList; 1623 } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) { 1624 for (FormatToken *Previous = Current.Previous; 1625 Previous && Previous->isOneOf(tok::star, tok::amp); 1626 Previous = Previous->Previous) 1627 Previous->setType(TT_PointerOrReference); 1628 if (Line.MustBeDeclaration && 1629 Contexts.front().ContextType != Context::CtorInitializer) 1630 Contexts.back().IsExpression = false; 1631 } else if (Current.is(tok::kw_new)) { 1632 Contexts.back().CanBeExpression = false; 1633 } else if (Current.is(tok::semi) || 1634 (Current.is(tok::exclaim) && Current.Previous && 1635 !Current.Previous->is(tok::kw_operator))) { 1636 // This should be the condition or increment in a for-loop. 1637 // But not operator !() (can't use TT_OverloadedOperator here as its not 1638 // been annotated yet). 1639 Contexts.back().IsExpression = true; 1640 } 1641 } 1642 1643 static FormatToken *untilMatchingParen(FormatToken *Current) { 1644 // Used when `MatchingParen` is not yet established. 1645 int ParenLevel = 0; 1646 while (Current) { 1647 if (Current->is(tok::l_paren)) 1648 ++ParenLevel; 1649 if (Current->is(tok::r_paren)) 1650 --ParenLevel; 1651 if (ParenLevel < 1) 1652 break; 1653 Current = Current->Next; 1654 } 1655 return Current; 1656 } 1657 1658 static bool isDeductionGuide(FormatToken &Current) { 1659 // Look for a deduction guide template<T> A(...) -> A<...>; 1660 if (Current.Previous && Current.Previous->is(tok::r_paren) && 1661 Current.startsSequence(tok::arrow, tok::identifier, tok::less)) { 1662 // Find the TemplateCloser. 1663 FormatToken *TemplateCloser = Current.Next->Next; 1664 int NestingLevel = 0; 1665 while (TemplateCloser) { 1666 // Skip over an expressions in parens A<(3 < 2)>; 1667 if (TemplateCloser->is(tok::l_paren)) { 1668 // No Matching Paren yet so skip to matching paren 1669 TemplateCloser = untilMatchingParen(TemplateCloser); 1670 if (!TemplateCloser) 1671 break; 1672 } 1673 if (TemplateCloser->is(tok::less)) 1674 ++NestingLevel; 1675 if (TemplateCloser->is(tok::greater)) 1676 --NestingLevel; 1677 if (NestingLevel < 1) 1678 break; 1679 TemplateCloser = TemplateCloser->Next; 1680 } 1681 // Assuming we have found the end of the template ensure its followed 1682 // with a semi-colon. 1683 if (TemplateCloser && TemplateCloser->Next && 1684 TemplateCloser->Next->is(tok::semi) && 1685 Current.Previous->MatchingParen) { 1686 // Determine if the identifier `A` prior to the A<..>; is the same as 1687 // prior to the A(..) 1688 FormatToken *LeadingIdentifier = 1689 Current.Previous->MatchingParen->Previous; 1690 1691 // Differentiate a deduction guide by seeing the 1692 // > of the template prior to the leading identifier. 1693 if (LeadingIdentifier) { 1694 FormatToken *PriorLeadingIdentifier = LeadingIdentifier->Previous; 1695 // Skip back past explicit decoration 1696 if (PriorLeadingIdentifier && 1697 PriorLeadingIdentifier->is(tok::kw_explicit)) 1698 PriorLeadingIdentifier = PriorLeadingIdentifier->Previous; 1699 1700 return PriorLeadingIdentifier && 1701 (PriorLeadingIdentifier->is(TT_TemplateCloser) || 1702 PriorLeadingIdentifier->ClosesRequiresClause) && 1703 LeadingIdentifier->TokenText == Current.Next->TokenText; 1704 } 1705 } 1706 } 1707 return false; 1708 } 1709 1710 void determineTokenType(FormatToken &Current) { 1711 if (!Current.is(TT_Unknown)) 1712 // The token type is already known. 1713 return; 1714 1715 if ((Style.isJavaScript() || Style.isCSharp()) && 1716 Current.is(tok::exclaim)) { 1717 if (Current.Previous) { 1718 bool IsIdentifier = 1719 Style.isJavaScript() 1720 ? Keywords.IsJavaScriptIdentifier( 1721 *Current.Previous, /* AcceptIdentifierName= */ true) 1722 : Current.Previous->is(tok::identifier); 1723 if (IsIdentifier || 1724 Current.Previous->isOneOf( 1725 tok::kw_default, tok::kw_namespace, tok::r_paren, tok::r_square, 1726 tok::r_brace, tok::kw_false, tok::kw_true, Keywords.kw_type, 1727 Keywords.kw_get, Keywords.kw_init, Keywords.kw_set) || 1728 Current.Previous->Tok.isLiteral()) { 1729 Current.setType(TT_NonNullAssertion); 1730 return; 1731 } 1732 } 1733 if (Current.Next && 1734 Current.Next->isOneOf(TT_BinaryOperator, Keywords.kw_as)) { 1735 Current.setType(TT_NonNullAssertion); 1736 return; 1737 } 1738 } 1739 1740 // Line.MightBeFunctionDecl can only be true after the parentheses of a 1741 // function declaration have been found. In this case, 'Current' is a 1742 // trailing token of this declaration and thus cannot be a name. 1743 if (Current.is(Keywords.kw_instanceof)) { 1744 Current.setType(TT_BinaryOperator); 1745 } else if (isStartOfName(Current) && 1746 (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) { 1747 Contexts.back().FirstStartOfName = &Current; 1748 Current.setType(TT_StartOfName); 1749 } else if (Current.is(tok::semi)) { 1750 // Reset FirstStartOfName after finding a semicolon so that a for loop 1751 // with multiple increment statements is not confused with a for loop 1752 // having multiple variable declarations. 1753 Contexts.back().FirstStartOfName = nullptr; 1754 } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) { 1755 AutoFound = true; 1756 } else if (Current.is(tok::arrow) && 1757 Style.Language == FormatStyle::LK_Java) { 1758 Current.setType(TT_LambdaArrow); 1759 } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration && 1760 Current.NestingLevel == 0 && 1761 !Current.Previous->isOneOf(tok::kw_operator, tok::identifier)) { 1762 // not auto operator->() -> xxx; 1763 Current.setType(TT_TrailingReturnArrow); 1764 } else if (Current.is(tok::arrow) && Current.Previous && 1765 Current.Previous->is(tok::r_brace)) { 1766 // Concept implicit conversion constraint needs to be treated like 1767 // a trailing return type ... } -> <type>. 1768 Current.setType(TT_TrailingReturnArrow); 1769 } else if (isDeductionGuide(Current)) { 1770 // Deduction guides trailing arrow " A(...) -> A<T>;". 1771 Current.setType(TT_TrailingReturnArrow); 1772 } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) { 1773 Current.setType(determineStarAmpUsage( 1774 Current, 1775 Contexts.back().CanBeExpression && Contexts.back().IsExpression, 1776 Contexts.back().ContextType == Context::TemplateArgument)); 1777 } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) { 1778 Current.setType(determinePlusMinusCaretUsage(Current)); 1779 if (Current.is(TT_UnaryOperator) && Current.is(tok::caret)) 1780 Contexts.back().CaretFound = true; 1781 } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) { 1782 Current.setType(determineIncrementUsage(Current)); 1783 } else if (Current.isOneOf(tok::exclaim, tok::tilde)) { 1784 Current.setType(TT_UnaryOperator); 1785 } else if (Current.is(tok::question)) { 1786 if (Style.isJavaScript() && Line.MustBeDeclaration && 1787 !Contexts.back().IsExpression) { 1788 // In JavaScript, `interface X { foo?(): bar; }` is an optional method 1789 // on the interface, not a ternary expression. 1790 Current.setType(TT_JsTypeOptionalQuestion); 1791 } else { 1792 Current.setType(TT_ConditionalExpr); 1793 } 1794 } else if (Current.isBinaryOperator() && 1795 (!Current.Previous || Current.Previous->isNot(tok::l_square)) && 1796 (!Current.is(tok::greater) && 1797 Style.Language != FormatStyle::LK_TextProto)) { 1798 Current.setType(TT_BinaryOperator); 1799 } else if (Current.is(tok::comment)) { 1800 if (Current.TokenText.startswith("/*")) 1801 if (Current.TokenText.endswith("*/")) 1802 Current.setType(TT_BlockComment); 1803 else 1804 // The lexer has for some reason determined a comment here. But we 1805 // cannot really handle it, if it isn't properly terminated. 1806 Current.Tok.setKind(tok::unknown); 1807 else 1808 Current.setType(TT_LineComment); 1809 } else if (Current.is(tok::l_paren)) { 1810 if (lParenStartsCppCast(Current)) 1811 Current.setType(TT_CppCastLParen); 1812 } else if (Current.is(tok::r_paren)) { 1813 if (rParenEndsCast(Current)) 1814 Current.setType(TT_CastRParen); 1815 if (Current.MatchingParen && Current.Next && 1816 !Current.Next->isBinaryOperator() && 1817 !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace, 1818 tok::comma, tok::period, tok::arrow, 1819 tok::coloncolon)) 1820 if (FormatToken *AfterParen = Current.MatchingParen->Next) { 1821 // Make sure this isn't the return type of an Obj-C block declaration 1822 if (AfterParen->isNot(tok::caret)) { 1823 if (FormatToken *BeforeParen = Current.MatchingParen->Previous) 1824 if (BeforeParen->is(tok::identifier) && 1825 !BeforeParen->is(TT_TypenameMacro) && 1826 BeforeParen->TokenText == BeforeParen->TokenText.upper() && 1827 (!BeforeParen->Previous || 1828 BeforeParen->Previous->ClosesTemplateDeclaration)) 1829 Current.setType(TT_FunctionAnnotationRParen); 1830 } 1831 } 1832 } else if (Current.is(tok::at) && Current.Next && !Style.isJavaScript() && 1833 Style.Language != FormatStyle::LK_Java) { 1834 // In Java & JavaScript, "@..." is a decorator or annotation. In ObjC, it 1835 // marks declarations and properties that need special formatting. 1836 switch (Current.Next->Tok.getObjCKeywordID()) { 1837 case tok::objc_interface: 1838 case tok::objc_implementation: 1839 case tok::objc_protocol: 1840 Current.setType(TT_ObjCDecl); 1841 break; 1842 case tok::objc_property: 1843 Current.setType(TT_ObjCProperty); 1844 break; 1845 default: 1846 break; 1847 } 1848 } else if (Current.is(tok::period)) { 1849 FormatToken *PreviousNoComment = Current.getPreviousNonComment(); 1850 if (PreviousNoComment && 1851 PreviousNoComment->isOneOf(tok::comma, tok::l_brace)) 1852 Current.setType(TT_DesignatedInitializerPeriod); 1853 else if (Style.Language == FormatStyle::LK_Java && Current.Previous && 1854 Current.Previous->isOneOf(TT_JavaAnnotation, 1855 TT_LeadingJavaAnnotation)) 1856 Current.setType(Current.Previous->getType()); 1857 } else if (canBeObjCSelectorComponent(Current) && 1858 // FIXME(bug 36976): ObjC return types shouldn't use 1859 // TT_CastRParen. 1860 Current.Previous && Current.Previous->is(TT_CastRParen) && 1861 Current.Previous->MatchingParen && 1862 Current.Previous->MatchingParen->Previous && 1863 Current.Previous->MatchingParen->Previous->is( 1864 TT_ObjCMethodSpecifier)) { 1865 // This is the first part of an Objective-C selector name. (If there's no 1866 // colon after this, this is the only place which annotates the identifier 1867 // as a selector.) 1868 Current.setType(TT_SelectorName); 1869 } else if (Current.isOneOf(tok::identifier, tok::kw_const, tok::kw_noexcept, 1870 tok::kw_requires) && 1871 Current.Previous && 1872 !Current.Previous->isOneOf(tok::equal, tok::at) && 1873 Line.MightBeFunctionDecl && Contexts.size() == 1) { 1874 // Line.MightBeFunctionDecl can only be true after the parentheses of a 1875 // function declaration have been found. 1876 Current.setType(TT_TrailingAnnotation); 1877 } else if ((Style.Language == FormatStyle::LK_Java || 1878 Style.isJavaScript()) && 1879 Current.Previous) { 1880 if (Current.Previous->is(tok::at) && 1881 Current.isNot(Keywords.kw_interface)) { 1882 const FormatToken &AtToken = *Current.Previous; 1883 const FormatToken *Previous = AtToken.getPreviousNonComment(); 1884 if (!Previous || Previous->is(TT_LeadingJavaAnnotation)) 1885 Current.setType(TT_LeadingJavaAnnotation); 1886 else 1887 Current.setType(TT_JavaAnnotation); 1888 } else if (Current.Previous->is(tok::period) && 1889 Current.Previous->isOneOf(TT_JavaAnnotation, 1890 TT_LeadingJavaAnnotation)) { 1891 Current.setType(Current.Previous->getType()); 1892 } 1893 } 1894 } 1895 1896 /// Take a guess at whether \p Tok starts a name of a function or 1897 /// variable declaration. 1898 /// 1899 /// This is a heuristic based on whether \p Tok is an identifier following 1900 /// something that is likely a type. 1901 bool isStartOfName(const FormatToken &Tok) { 1902 if (Tok.isNot(tok::identifier) || !Tok.Previous) 1903 return false; 1904 1905 if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof, 1906 Keywords.kw_as)) 1907 return false; 1908 if (Style.isJavaScript() && Tok.Previous->is(Keywords.kw_in)) 1909 return false; 1910 1911 // Skip "const" as it does not have an influence on whether this is a name. 1912 FormatToken *PreviousNotConst = Tok.getPreviousNonComment(); 1913 1914 // For javascript const can be like "let" or "var" 1915 if (!Style.isJavaScript()) 1916 while (PreviousNotConst && PreviousNotConst->is(tok::kw_const)) 1917 PreviousNotConst = PreviousNotConst->getPreviousNonComment(); 1918 1919 if (!PreviousNotConst) 1920 return false; 1921 1922 if (PreviousNotConst->ClosesRequiresClause) 1923 return false; 1924 1925 bool IsPPKeyword = PreviousNotConst->is(tok::identifier) && 1926 PreviousNotConst->Previous && 1927 PreviousNotConst->Previous->is(tok::hash); 1928 1929 if (PreviousNotConst->is(TT_TemplateCloser)) 1930 return PreviousNotConst && PreviousNotConst->MatchingParen && 1931 PreviousNotConst->MatchingParen->Previous && 1932 PreviousNotConst->MatchingParen->Previous->isNot(tok::period) && 1933 PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template); 1934 1935 if (PreviousNotConst->is(tok::r_paren) && 1936 PreviousNotConst->is(TT_TypeDeclarationParen)) 1937 return true; 1938 1939 // If is a preprocess keyword like #define. 1940 if (IsPPKeyword) 1941 return false; 1942 1943 // int a or auto a. 1944 if (PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) 1945 return true; 1946 1947 // *a or &a or &&a. 1948 if (PreviousNotConst->is(TT_PointerOrReference)) 1949 return true; 1950 1951 // MyClass a; 1952 if (PreviousNotConst->isSimpleTypeSpecifier()) 1953 return true; 1954 1955 // const a = in JavaScript. 1956 return Style.isJavaScript() && PreviousNotConst->is(tok::kw_const); 1957 } 1958 1959 /// Determine whether '(' is starting a C++ cast. 1960 bool lParenStartsCppCast(const FormatToken &Tok) { 1961 // C-style casts are only used in C++. 1962 if (!Style.isCpp()) 1963 return false; 1964 1965 FormatToken *LeftOfParens = Tok.getPreviousNonComment(); 1966 if (LeftOfParens && LeftOfParens->is(TT_TemplateCloser) && 1967 LeftOfParens->MatchingParen) { 1968 auto *Prev = LeftOfParens->MatchingParen->getPreviousNonComment(); 1969 if (Prev && Prev->isOneOf(tok::kw_const_cast, tok::kw_dynamic_cast, 1970 tok::kw_reinterpret_cast, tok::kw_static_cast)) 1971 // FIXME: Maybe we should handle identifiers ending with "_cast", 1972 // e.g. any_cast? 1973 return true; 1974 } 1975 return false; 1976 } 1977 1978 /// Determine whether ')' is ending a cast. 1979 bool rParenEndsCast(const FormatToken &Tok) { 1980 // C-style casts are only used in C++, C# and Java. 1981 if (!Style.isCSharp() && !Style.isCpp() && 1982 Style.Language != FormatStyle::LK_Java) 1983 return false; 1984 1985 // Empty parens aren't casts and there are no casts at the end of the line. 1986 if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen) 1987 return false; 1988 1989 FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment(); 1990 if (LeftOfParens) { 1991 // If there is a closing parenthesis left of the current 1992 // parentheses, look past it as these might be chained casts. 1993 if (LeftOfParens->is(tok::r_paren) && 1994 LeftOfParens->isNot(TT_CastRParen)) { 1995 if (!LeftOfParens->MatchingParen || 1996 !LeftOfParens->MatchingParen->Previous) 1997 return false; 1998 LeftOfParens = LeftOfParens->MatchingParen->Previous; 1999 } 2000 2001 if (LeftOfParens->is(tok::r_square)) { 2002 // delete[] (void *)ptr; 2003 auto MayBeArrayDelete = [](FormatToken *Tok) -> FormatToken * { 2004 if (Tok->isNot(tok::r_square)) 2005 return nullptr; 2006 2007 Tok = Tok->getPreviousNonComment(); 2008 if (!Tok || Tok->isNot(tok::l_square)) 2009 return nullptr; 2010 2011 Tok = Tok->getPreviousNonComment(); 2012 if (!Tok || Tok->isNot(tok::kw_delete)) 2013 return nullptr; 2014 return Tok; 2015 }; 2016 if (FormatToken *MaybeDelete = MayBeArrayDelete(LeftOfParens)) 2017 LeftOfParens = MaybeDelete; 2018 } 2019 2020 // The Condition directly below this one will see the operator arguments 2021 // as a (void *foo) cast. 2022 // void operator delete(void *foo) ATTRIB; 2023 if (LeftOfParens->Tok.getIdentifierInfo() && LeftOfParens->Previous && 2024 LeftOfParens->Previous->is(tok::kw_operator)) 2025 return false; 2026 2027 // If there is an identifier (or with a few exceptions a keyword) right 2028 // before the parentheses, this is unlikely to be a cast. 2029 if (LeftOfParens->Tok.getIdentifierInfo() && 2030 !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case, 2031 tok::kw_delete)) 2032 return false; 2033 2034 // Certain other tokens right before the parentheses are also signals that 2035 // this cannot be a cast. 2036 if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator, 2037 TT_TemplateCloser, tok::ellipsis)) 2038 return false; 2039 } 2040 2041 if (Tok.Next->is(tok::question)) 2042 return false; 2043 2044 // `foreach((A a, B b) in someList)` should not be seen as a cast. 2045 if (Tok.Next->is(Keywords.kw_in) && Style.isCSharp()) 2046 return false; 2047 2048 // Functions which end with decorations like volatile, noexcept are unlikely 2049 // to be casts. 2050 if (Tok.Next->isOneOf(tok::kw_noexcept, tok::kw_volatile, tok::kw_const, 2051 tok::kw_requires, tok::kw_throw, tok::arrow, 2052 Keywords.kw_override, Keywords.kw_final) || 2053 isCpp11AttributeSpecifier(*Tok.Next)) 2054 return false; 2055 2056 // As Java has no function types, a "(" after the ")" likely means that this 2057 // is a cast. 2058 if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren)) 2059 return true; 2060 2061 // If a (non-string) literal follows, this is likely a cast. 2062 if (Tok.Next->isNot(tok::string_literal) && 2063 (Tok.Next->Tok.isLiteral() || 2064 Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof))) 2065 return true; 2066 2067 // Heuristically try to determine whether the parentheses contain a type. 2068 auto IsQualifiedPointerOrReference = [](FormatToken *T) { 2069 // This is used to handle cases such as x = (foo *const)&y; 2070 assert(!T->isSimpleTypeSpecifier() && "Should have already been checked"); 2071 // Strip trailing qualifiers such as const or volatile when checking 2072 // whether the parens could be a cast to a pointer/reference type. 2073 while (T) { 2074 if (T->is(TT_AttributeParen)) { 2075 // Handle `x = (foo *__attribute__((foo)))&v;`: 2076 if (T->MatchingParen && T->MatchingParen->Previous && 2077 T->MatchingParen->Previous->is(tok::kw___attribute)) { 2078 T = T->MatchingParen->Previous->Previous; 2079 continue; 2080 } 2081 } else if (T->is(TT_AttributeSquare)) { 2082 // Handle `x = (foo *[[clang::foo]])&v;`: 2083 if (T->MatchingParen && T->MatchingParen->Previous) { 2084 T = T->MatchingParen->Previous; 2085 continue; 2086 } 2087 } else if (T->canBePointerOrReferenceQualifier()) { 2088 T = T->Previous; 2089 continue; 2090 } 2091 break; 2092 } 2093 return T && T->is(TT_PointerOrReference); 2094 }; 2095 bool ParensAreType = 2096 !Tok.Previous || 2097 Tok.Previous->isOneOf(TT_TemplateCloser, TT_TypeDeclarationParen) || 2098 Tok.Previous->isSimpleTypeSpecifier() || 2099 IsQualifiedPointerOrReference(Tok.Previous); 2100 bool ParensCouldEndDecl = 2101 Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater); 2102 if (ParensAreType && !ParensCouldEndDecl) 2103 return true; 2104 2105 // At this point, we heuristically assume that there are no casts at the 2106 // start of the line. We assume that we have found most cases where there 2107 // are by the logic above, e.g. "(void)x;". 2108 if (!LeftOfParens) 2109 return false; 2110 2111 // Certain token types inside the parentheses mean that this can't be a 2112 // cast. 2113 for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok; 2114 Token = Token->Next) 2115 if (Token->is(TT_BinaryOperator)) 2116 return false; 2117 2118 // If the following token is an identifier or 'this', this is a cast. All 2119 // cases where this can be something else are handled above. 2120 if (Tok.Next->isOneOf(tok::identifier, tok::kw_this)) 2121 return true; 2122 2123 // Look for a cast `( x ) (`. 2124 if (Tok.Next->is(tok::l_paren) && Tok.Previous && Tok.Previous->Previous) { 2125 if (Tok.Previous->is(tok::identifier) && 2126 Tok.Previous->Previous->is(tok::l_paren)) 2127 return true; 2128 } 2129 2130 if (!Tok.Next->Next) 2131 return false; 2132 2133 // If the next token after the parenthesis is a unary operator, assume 2134 // that this is cast, unless there are unexpected tokens inside the 2135 // parenthesis. 2136 bool NextIsUnary = 2137 Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star); 2138 if (!NextIsUnary || Tok.Next->is(tok::plus) || 2139 !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant)) 2140 return false; 2141 // Search for unexpected tokens. 2142 for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen; 2143 Prev = Prev->Previous) 2144 if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon)) 2145 return false; 2146 return true; 2147 } 2148 2149 /// Returns true if the token is used as a unary operator. 2150 bool determineUnaryOperatorByUsage(const FormatToken &Tok) { 2151 const FormatToken *PrevToken = Tok.getPreviousNonComment(); 2152 if (!PrevToken) 2153 return true; 2154 2155 // These keywords are deliberately not included here because they may 2156 // precede only one of unary star/amp and plus/minus but not both. They are 2157 // either included in determineStarAmpUsage or determinePlusMinusCaretUsage. 2158 // 2159 // @ - It may be followed by a unary `-` in Objective-C literals. We don't 2160 // know how they can be followed by a star or amp. 2161 if (PrevToken->isOneOf( 2162 TT_ConditionalExpr, tok::l_paren, tok::comma, tok::colon, tok::semi, 2163 tok::equal, tok::question, tok::l_square, tok::l_brace, 2164 tok::kw_case, tok::kw_co_await, tok::kw_co_return, tok::kw_co_yield, 2165 tok::kw_delete, tok::kw_return, tok::kw_throw)) 2166 return true; 2167 2168 // We put sizeof here instead of only in determineStarAmpUsage. In the cases 2169 // where the unary `+` operator is overloaded, it is reasonable to write 2170 // things like `sizeof +x`. Like commit 446d6ec996c6c3. 2171 if (PrevToken->is(tok::kw_sizeof)) 2172 return true; 2173 2174 // A sequence of leading unary operators. 2175 if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator)) 2176 return true; 2177 2178 // There can't be two consecutive binary operators. 2179 if (PrevToken->is(TT_BinaryOperator)) 2180 return true; 2181 2182 return false; 2183 } 2184 2185 /// Return the type of the given token assuming it is * or &. 2186 TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression, 2187 bool InTemplateArgument) { 2188 if (Style.isJavaScript()) 2189 return TT_BinaryOperator; 2190 2191 // && in C# must be a binary operator. 2192 if (Style.isCSharp() && Tok.is(tok::ampamp)) 2193 return TT_BinaryOperator; 2194 2195 const FormatToken *PrevToken = Tok.getPreviousNonComment(); 2196 if (!PrevToken) 2197 return TT_UnaryOperator; 2198 2199 const FormatToken *NextToken = Tok.getNextNonComment(); 2200 2201 if (InTemplateArgument && NextToken && NextToken->is(tok::kw_noexcept)) 2202 return TT_BinaryOperator; 2203 2204 if (!NextToken || 2205 NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_noexcept) || 2206 NextToken->canBePointerOrReferenceQualifier() || 2207 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment())) 2208 return TT_PointerOrReference; 2209 2210 if (PrevToken->is(tok::coloncolon)) 2211 return TT_PointerOrReference; 2212 2213 if (PrevToken->is(tok::r_paren) && PrevToken->is(TT_TypeDeclarationParen)) 2214 return TT_PointerOrReference; 2215 2216 if (determineUnaryOperatorByUsage(Tok)) 2217 return TT_UnaryOperator; 2218 2219 if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare)) 2220 return TT_PointerOrReference; 2221 if (NextToken->is(tok::kw_operator) && !IsExpression) 2222 return TT_PointerOrReference; 2223 if (NextToken->isOneOf(tok::comma, tok::semi)) 2224 return TT_PointerOrReference; 2225 2226 if (PrevToken->Tok.isLiteral() || 2227 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true, 2228 tok::kw_false, tok::r_brace)) 2229 return TT_BinaryOperator; 2230 2231 const FormatToken *NextNonParen = NextToken; 2232 while (NextNonParen && NextNonParen->is(tok::l_paren)) 2233 NextNonParen = NextNonParen->getNextNonComment(); 2234 if (NextNonParen && (NextNonParen->Tok.isLiteral() || 2235 NextNonParen->isOneOf(tok::kw_true, tok::kw_false) || 2236 NextNonParen->isUnaryOperator())) 2237 return TT_BinaryOperator; 2238 2239 // If we know we're in a template argument, there are no named declarations. 2240 // Thus, having an identifier on the right-hand side indicates a binary 2241 // operator. 2242 if (InTemplateArgument && NextToken->Tok.isAnyIdentifier()) 2243 return TT_BinaryOperator; 2244 2245 // "&&(" is quite unlikely to be two successive unary "&". 2246 if (Tok.is(tok::ampamp) && NextToken->is(tok::l_paren)) 2247 return TT_BinaryOperator; 2248 2249 // This catches some cases where evaluation order is used as control flow: 2250 // aaa && aaa->f(); 2251 if (NextToken->Tok.isAnyIdentifier()) { 2252 const FormatToken *NextNextToken = NextToken->getNextNonComment(); 2253 if (NextNextToken && NextNextToken->is(tok::arrow)) 2254 return TT_BinaryOperator; 2255 } 2256 2257 // It is very unlikely that we are going to find a pointer or reference type 2258 // definition on the RHS of an assignment. 2259 if (IsExpression && !Contexts.back().CaretFound) 2260 return TT_BinaryOperator; 2261 2262 return TT_PointerOrReference; 2263 } 2264 2265 TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) { 2266 if (determineUnaryOperatorByUsage(Tok)) 2267 return TT_UnaryOperator; 2268 2269 const FormatToken *PrevToken = Tok.getPreviousNonComment(); 2270 if (!PrevToken) 2271 return TT_UnaryOperator; 2272 2273 if (PrevToken->is(tok::at)) 2274 return TT_UnaryOperator; 2275 2276 // Fall back to marking the token as binary operator. 2277 return TT_BinaryOperator; 2278 } 2279 2280 /// Determine whether ++/-- are pre- or post-increments/-decrements. 2281 TokenType determineIncrementUsage(const FormatToken &Tok) { 2282 const FormatToken *PrevToken = Tok.getPreviousNonComment(); 2283 if (!PrevToken || PrevToken->is(TT_CastRParen)) 2284 return TT_UnaryOperator; 2285 if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier)) 2286 return TT_TrailingUnaryOperator; 2287 2288 return TT_UnaryOperator; 2289 } 2290 2291 SmallVector<Context, 8> Contexts; 2292 2293 const FormatStyle &Style; 2294 AnnotatedLine &Line; 2295 FormatToken *CurrentToken; 2296 bool AutoFound; 2297 const AdditionalKeywords &Keywords; 2298 2299 // Set of "<" tokens that do not open a template parameter list. If parseAngle 2300 // determines that a specific token can't be a template opener, it will make 2301 // same decision irrespective of the decisions for tokens leading up to it. 2302 // Store this information to prevent this from causing exponential runtime. 2303 llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess; 2304 }; 2305 2306 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1; 2307 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2; 2308 2309 /// Parses binary expressions by inserting fake parenthesis based on 2310 /// operator precedence. 2311 class ExpressionParser { 2312 public: 2313 ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords, 2314 AnnotatedLine &Line) 2315 : Style(Style), Keywords(Keywords), Line(Line), Current(Line.First) {} 2316 2317 /// Parse expressions with the given operator precedence. 2318 void parse(int Precedence = 0) { 2319 // Skip 'return' and ObjC selector colons as they are not part of a binary 2320 // expression. 2321 while (Current && (Current->is(tok::kw_return) || 2322 (Current->is(tok::colon) && 2323 Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)))) 2324 next(); 2325 2326 if (!Current || Precedence > PrecedenceArrowAndPeriod) 2327 return; 2328 2329 // Conditional expressions need to be parsed separately for proper nesting. 2330 if (Precedence == prec::Conditional) { 2331 parseConditionalExpr(); 2332 return; 2333 } 2334 2335 // Parse unary operators, which all have a higher precedence than binary 2336 // operators. 2337 if (Precedence == PrecedenceUnaryOperator) { 2338 parseUnaryOperator(); 2339 return; 2340 } 2341 2342 FormatToken *Start = Current; 2343 FormatToken *LatestOperator = nullptr; 2344 unsigned OperatorIndex = 0; 2345 2346 while (Current) { 2347 // Consume operators with higher precedence. 2348 parse(Precedence + 1); 2349 2350 int CurrentPrecedence = getCurrentPrecedence(); 2351 2352 if (Precedence == CurrentPrecedence && Current && 2353 Current->is(TT_SelectorName)) { 2354 if (LatestOperator) 2355 addFakeParenthesis(Start, prec::Level(Precedence)); 2356 Start = Current; 2357 } 2358 2359 // At the end of the line or when an operator with higher precedence is 2360 // found, insert fake parenthesis and return. 2361 if (!Current || 2362 (Current->closesScope() && 2363 (Current->MatchingParen || Current->is(TT_TemplateString))) || 2364 (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) || 2365 (CurrentPrecedence == prec::Conditional && 2366 Precedence == prec::Assignment && Current->is(tok::colon))) 2367 break; 2368 2369 // Consume scopes: (), [], <> and {} 2370 // In addition to that we handle require clauses as scope, so that the 2371 // constraints in that are correctly indented. 2372 if (Current->opensScope() || 2373 Current->isOneOf(TT_RequiresClause, 2374 TT_RequiresClauseInARequiresExpression)) { 2375 // In fragment of a JavaScript template string can look like '}..${' and 2376 // thus close a scope and open a new one at the same time. 2377 while (Current && (!Current->closesScope() || Current->opensScope())) { 2378 next(); 2379 parse(); 2380 } 2381 next(); 2382 } else { 2383 // Operator found. 2384 if (CurrentPrecedence == Precedence) { 2385 if (LatestOperator) 2386 LatestOperator->NextOperator = Current; 2387 LatestOperator = Current; 2388 Current->OperatorIndex = OperatorIndex; 2389 ++OperatorIndex; 2390 } 2391 next(/*SkipPastLeadingComments=*/Precedence > 0); 2392 } 2393 } 2394 2395 if (LatestOperator && (Current || Precedence > 0)) { 2396 // The requires clauses do not neccessarily end in a semicolon or a brace, 2397 // but just go over to struct/class or a function declaration, we need to 2398 // intervene so that the fake right paren is inserted correctly. 2399 auto End = 2400 (Start->Previous && 2401 Start->Previous->isOneOf(TT_RequiresClause, 2402 TT_RequiresClauseInARequiresExpression)) 2403 ? [this](){ 2404 auto Ret = Current ? Current : Line.Last; 2405 while (!Ret->ClosesRequiresClause && Ret->Previous) 2406 Ret = Ret->Previous; 2407 return Ret; 2408 }() 2409 : nullptr; 2410 2411 if (Precedence == PrecedenceArrowAndPeriod) { 2412 // Call expressions don't have a binary operator precedence. 2413 addFakeParenthesis(Start, prec::Unknown, End); 2414 } else { 2415 addFakeParenthesis(Start, prec::Level(Precedence), End); 2416 } 2417 } 2418 } 2419 2420 private: 2421 /// Gets the precedence (+1) of the given token for binary operators 2422 /// and other tokens that we treat like binary operators. 2423 int getCurrentPrecedence() { 2424 if (Current) { 2425 const FormatToken *NextNonComment = Current->getNextNonComment(); 2426 if (Current->is(TT_ConditionalExpr)) 2427 return prec::Conditional; 2428 if (NextNonComment && Current->is(TT_SelectorName) && 2429 (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) || 2430 ((Style.Language == FormatStyle::LK_Proto || 2431 Style.Language == FormatStyle::LK_TextProto) && 2432 NextNonComment->is(tok::less)))) 2433 return prec::Assignment; 2434 if (Current->is(TT_JsComputedPropertyName)) 2435 return prec::Assignment; 2436 if (Current->is(TT_LambdaArrow)) 2437 return prec::Comma; 2438 if (Current->is(TT_FatArrow)) 2439 return prec::Assignment; 2440 if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) || 2441 (Current->is(tok::comment) && NextNonComment && 2442 NextNonComment->is(TT_SelectorName))) 2443 return 0; 2444 if (Current->is(TT_RangeBasedForLoopColon)) 2445 return prec::Comma; 2446 if ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) && 2447 Current->is(Keywords.kw_instanceof)) 2448 return prec::Relational; 2449 if (Style.isJavaScript() && 2450 Current->isOneOf(Keywords.kw_in, Keywords.kw_as)) 2451 return prec::Relational; 2452 if (Current->is(TT_BinaryOperator) || Current->is(tok::comma)) 2453 return Current->getPrecedence(); 2454 if (Current->isOneOf(tok::period, tok::arrow)) 2455 return PrecedenceArrowAndPeriod; 2456 if ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) && 2457 Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements, 2458 Keywords.kw_throws)) 2459 return 0; 2460 } 2461 return -1; 2462 } 2463 2464 void addFakeParenthesis(FormatToken *Start, prec::Level Precedence, 2465 FormatToken *End = nullptr) { 2466 Start->FakeLParens.push_back(Precedence); 2467 if (Precedence > prec::Unknown) 2468 Start->StartsBinaryExpression = true; 2469 if (!End && Current) 2470 End = Current->getPreviousNonComment(); 2471 if (End) { 2472 ++End->FakeRParens; 2473 if (Precedence > prec::Unknown) 2474 End->EndsBinaryExpression = true; 2475 } 2476 } 2477 2478 /// Parse unary operator expressions and surround them with fake 2479 /// parentheses if appropriate. 2480 void parseUnaryOperator() { 2481 llvm::SmallVector<FormatToken *, 2> Tokens; 2482 while (Current && Current->is(TT_UnaryOperator)) { 2483 Tokens.push_back(Current); 2484 next(); 2485 } 2486 parse(PrecedenceArrowAndPeriod); 2487 for (FormatToken *Token : llvm::reverse(Tokens)) 2488 // The actual precedence doesn't matter. 2489 addFakeParenthesis(Token, prec::Unknown); 2490 } 2491 2492 void parseConditionalExpr() { 2493 while (Current && Current->isTrailingComment()) 2494 next(); 2495 FormatToken *Start = Current; 2496 parse(prec::LogicalOr); 2497 if (!Current || !Current->is(tok::question)) 2498 return; 2499 next(); 2500 parse(prec::Assignment); 2501 if (!Current || Current->isNot(TT_ConditionalExpr)) 2502 return; 2503 next(); 2504 parse(prec::Assignment); 2505 addFakeParenthesis(Start, prec::Conditional); 2506 } 2507 2508 void next(bool SkipPastLeadingComments = true) { 2509 if (Current) 2510 Current = Current->Next; 2511 while (Current && 2512 (Current->NewlinesBefore == 0 || SkipPastLeadingComments) && 2513 Current->isTrailingComment()) 2514 Current = Current->Next; 2515 } 2516 2517 const FormatStyle &Style; 2518 const AdditionalKeywords &Keywords; 2519 const AnnotatedLine &Line; 2520 FormatToken *Current; 2521 }; 2522 2523 } // end anonymous namespace 2524 2525 void TokenAnnotator::setCommentLineLevels( 2526 SmallVectorImpl<AnnotatedLine *> &Lines) const { 2527 const AnnotatedLine *NextNonCommentLine = nullptr; 2528 for (AnnotatedLine *Line : llvm::reverse(Lines)) { 2529 assert(Line->First); 2530 2531 // If the comment is currently aligned with the line immediately following 2532 // it, that's probably intentional and we should keep it. 2533 if (NextNonCommentLine && Line->isComment() && 2534 NextNonCommentLine->First->NewlinesBefore <= 1 && 2535 NextNonCommentLine->First->OriginalColumn == 2536 Line->First->OriginalColumn) { 2537 // Align comments for preprocessor lines with the # in column 0 if 2538 // preprocessor lines are not indented. Otherwise, align with the next 2539 // line. 2540 Line->Level = 2541 (Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash && 2542 (NextNonCommentLine->Type == LT_PreprocessorDirective || 2543 NextNonCommentLine->Type == LT_ImportStatement)) 2544 ? 0 2545 : NextNonCommentLine->Level; 2546 } else { 2547 NextNonCommentLine = Line->First->isNot(tok::r_brace) ? Line : nullptr; 2548 } 2549 2550 setCommentLineLevels(Line->Children); 2551 } 2552 } 2553 2554 static unsigned maxNestingDepth(const AnnotatedLine &Line) { 2555 unsigned Result = 0; 2556 for (const auto *Tok = Line.First; Tok != nullptr; Tok = Tok->Next) 2557 Result = std::max(Result, Tok->NestingLevel); 2558 return Result; 2559 } 2560 2561 void TokenAnnotator::annotate(AnnotatedLine &Line) const { 2562 for (auto &Child : Line.Children) 2563 annotate(*Child); 2564 2565 AnnotatingParser Parser(Style, Line, Keywords); 2566 Line.Type = Parser.parseLine(); 2567 2568 // With very deep nesting, ExpressionParser uses lots of stack and the 2569 // formatting algorithm is very slow. We're not going to do a good job here 2570 // anyway - it's probably generated code being formatted by mistake. 2571 // Just skip the whole line. 2572 if (maxNestingDepth(Line) > 50) 2573 Line.Type = LT_Invalid; 2574 2575 if (Line.Type == LT_Invalid) 2576 return; 2577 2578 ExpressionParser ExprParser(Style, Keywords, Line); 2579 ExprParser.parse(); 2580 2581 if (Line.startsWith(TT_ObjCMethodSpecifier)) 2582 Line.Type = LT_ObjCMethodDecl; 2583 else if (Line.startsWith(TT_ObjCDecl)) 2584 Line.Type = LT_ObjCDecl; 2585 else if (Line.startsWith(TT_ObjCProperty)) 2586 Line.Type = LT_ObjCProperty; 2587 2588 Line.First->SpacesRequiredBefore = 1; 2589 Line.First->CanBreakBefore = Line.First->MustBreakBefore; 2590 } 2591 2592 // This function heuristically determines whether 'Current' starts the name of a 2593 // function declaration. 2594 static bool isFunctionDeclarationName(bool IsCpp, const FormatToken &Current, 2595 const AnnotatedLine &Line) { 2596 auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * { 2597 for (; Next; Next = Next->Next) { 2598 if (Next->is(TT_OverloadedOperatorLParen)) 2599 return Next; 2600 if (Next->is(TT_OverloadedOperator)) 2601 continue; 2602 if (Next->isOneOf(tok::kw_new, tok::kw_delete)) { 2603 // For 'new[]' and 'delete[]'. 2604 if (Next->Next && 2605 Next->Next->startsSequence(tok::l_square, tok::r_square)) 2606 Next = Next->Next->Next; 2607 continue; 2608 } 2609 if (Next->startsSequence(tok::l_square, tok::r_square)) { 2610 // For operator[](). 2611 Next = Next->Next; 2612 continue; 2613 } 2614 if ((Next->isSimpleTypeSpecifier() || Next->is(tok::identifier)) && 2615 Next->Next && Next->Next->isOneOf(tok::star, tok::amp, tok::ampamp)) { 2616 // For operator void*(), operator char*(), operator Foo*(). 2617 Next = Next->Next; 2618 continue; 2619 } 2620 if (Next->is(TT_TemplateOpener) && Next->MatchingParen) { 2621 Next = Next->MatchingParen; 2622 continue; 2623 } 2624 2625 break; 2626 } 2627 return nullptr; 2628 }; 2629 2630 // Find parentheses of parameter list. 2631 const FormatToken *Next = Current.Next; 2632 if (Current.is(tok::kw_operator)) { 2633 if (Current.Previous && Current.Previous->is(tok::coloncolon)) 2634 return false; 2635 Next = skipOperatorName(Next); 2636 } else { 2637 if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0) 2638 return false; 2639 for (; Next; Next = Next->Next) { 2640 if (Next->is(TT_TemplateOpener)) { 2641 Next = Next->MatchingParen; 2642 } else if (Next->is(tok::coloncolon)) { 2643 Next = Next->Next; 2644 if (!Next) 2645 return false; 2646 if (Next->is(tok::kw_operator)) { 2647 Next = skipOperatorName(Next->Next); 2648 break; 2649 } 2650 if (!Next->is(tok::identifier)) 2651 return false; 2652 } else if (Next->is(tok::l_paren)) { 2653 break; 2654 } else { 2655 return false; 2656 } 2657 } 2658 } 2659 2660 // Check whether parameter list can belong to a function declaration. 2661 if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen) 2662 return false; 2663 // If the lines ends with "{", this is likely a function definition. 2664 if (Line.Last->is(tok::l_brace)) 2665 return true; 2666 if (Next->Next == Next->MatchingParen) 2667 return true; // Empty parentheses. 2668 // If there is an &/&& after the r_paren, this is likely a function. 2669 if (Next->MatchingParen->Next && 2670 Next->MatchingParen->Next->is(TT_PointerOrReference)) 2671 return true; 2672 2673 // Check for K&R C function definitions (and C++ function definitions with 2674 // unnamed parameters), e.g.: 2675 // int f(i) 2676 // { 2677 // return i + 1; 2678 // } 2679 // bool g(size_t = 0, bool b = false) 2680 // { 2681 // return !b; 2682 // } 2683 if (IsCpp && Next->Next && Next->Next->is(tok::identifier) && 2684 !Line.endsWith(tok::semi)) 2685 return true; 2686 2687 for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen; 2688 Tok = Tok->Next) { 2689 if (Tok->is(TT_TypeDeclarationParen)) 2690 return true; 2691 if (Tok->isOneOf(tok::l_paren, TT_TemplateOpener) && Tok->MatchingParen) { 2692 Tok = Tok->MatchingParen; 2693 continue; 2694 } 2695 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() || 2696 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis)) 2697 return true; 2698 if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) || 2699 Tok->Tok.isLiteral()) 2700 return false; 2701 } 2702 return false; 2703 } 2704 2705 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const { 2706 assert(Line.MightBeFunctionDecl); 2707 2708 if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel || 2709 Style.AlwaysBreakAfterReturnType == 2710 FormatStyle::RTBS_TopLevelDefinitions) && 2711 Line.Level > 0) 2712 return false; 2713 2714 switch (Style.AlwaysBreakAfterReturnType) { 2715 case FormatStyle::RTBS_None: 2716 return false; 2717 case FormatStyle::RTBS_All: 2718 case FormatStyle::RTBS_TopLevel: 2719 return true; 2720 case FormatStyle::RTBS_AllDefinitions: 2721 case FormatStyle::RTBS_TopLevelDefinitions: 2722 return Line.mightBeFunctionDefinition(); 2723 } 2724 2725 return false; 2726 } 2727 2728 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) const { 2729 for (AnnotatedLine *ChildLine : Line.Children) 2730 calculateFormattingInformation(*ChildLine); 2731 2732 Line.First->TotalLength = 2733 Line.First->IsMultiline ? Style.ColumnLimit 2734 : Line.FirstStartColumn + Line.First->ColumnWidth; 2735 FormatToken *Current = Line.First->Next; 2736 bool InFunctionDecl = Line.MightBeFunctionDecl; 2737 bool AlignArrayOfStructures = 2738 (Style.AlignArrayOfStructures != FormatStyle::AIAS_None && 2739 Line.Type == LT_ArrayOfStructInitializer); 2740 if (AlignArrayOfStructures) 2741 calculateArrayInitializerColumnList(Line); 2742 2743 while (Current) { 2744 if (isFunctionDeclarationName(Style.isCpp(), *Current, Line)) 2745 Current->setType(TT_FunctionDeclarationName); 2746 const FormatToken *Prev = Current->Previous; 2747 if (Current->is(TT_LineComment)) { 2748 if (Prev->is(BK_BracedInit) && Prev->opensScope()) 2749 Current->SpacesRequiredBefore = 2750 (Style.Cpp11BracedListStyle && !Style.SpacesInParentheses) ? 0 : 1; 2751 else 2752 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments; 2753 2754 // If we find a trailing comment, iterate backwards to determine whether 2755 // it seems to relate to a specific parameter. If so, break before that 2756 // parameter to avoid changing the comment's meaning. E.g. don't move 'b' 2757 // to the previous line in: 2758 // SomeFunction(a, 2759 // b, // comment 2760 // c); 2761 if (!Current->HasUnescapedNewline) { 2762 for (FormatToken *Parameter = Current->Previous; Parameter; 2763 Parameter = Parameter->Previous) { 2764 if (Parameter->isOneOf(tok::comment, tok::r_brace)) 2765 break; 2766 if (Parameter->Previous && Parameter->Previous->is(tok::comma)) { 2767 if (!Parameter->Previous->is(TT_CtorInitializerComma) && 2768 Parameter->HasUnescapedNewline) 2769 Parameter->MustBreakBefore = true; 2770 break; 2771 } 2772 } 2773 } 2774 } else if (Current->SpacesRequiredBefore == 0 && 2775 spaceRequiredBefore(Line, *Current)) { 2776 Current->SpacesRequiredBefore = 1; 2777 } 2778 2779 const auto &Children = Prev->Children; 2780 if (!Children.empty() && Children.back()->Last->is(TT_LineComment)) { 2781 Current->MustBreakBefore = true; 2782 } else { 2783 Current->MustBreakBefore = 2784 Current->MustBreakBefore || mustBreakBefore(Line, *Current); 2785 if (!Current->MustBreakBefore && InFunctionDecl && 2786 Current->is(TT_FunctionDeclarationName)) 2787 Current->MustBreakBefore = mustBreakForReturnType(Line); 2788 } 2789 2790 Current->CanBreakBefore = 2791 Current->MustBreakBefore || canBreakBefore(Line, *Current); 2792 unsigned ChildSize = 0; 2793 if (Prev->Children.size() == 1) { 2794 FormatToken &LastOfChild = *Prev->Children[0]->Last; 2795 ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit 2796 : LastOfChild.TotalLength + 1; 2797 } 2798 if (Current->MustBreakBefore || Prev->Children.size() > 1 || 2799 (Prev->Children.size() == 1 && 2800 Prev->Children[0]->First->MustBreakBefore) || 2801 Current->IsMultiline) 2802 Current->TotalLength = Prev->TotalLength + Style.ColumnLimit; 2803 else 2804 Current->TotalLength = Prev->TotalLength + Current->ColumnWidth + 2805 ChildSize + Current->SpacesRequiredBefore; 2806 2807 if (Current->is(TT_CtorInitializerColon)) 2808 InFunctionDecl = false; 2809 2810 // FIXME: Only calculate this if CanBreakBefore is true once static 2811 // initializers etc. are sorted out. 2812 // FIXME: Move magic numbers to a better place. 2813 2814 // Reduce penalty for aligning ObjC method arguments using the colon 2815 // alignment as this is the canonical way (still prefer fitting everything 2816 // into one line if possible). Trying to fit a whole expression into one 2817 // line should not force other line breaks (e.g. when ObjC method 2818 // expression is a part of other expression). 2819 Current->SplitPenalty = splitPenalty(Line, *Current, InFunctionDecl); 2820 if (Style.Language == FormatStyle::LK_ObjC && 2821 Current->is(TT_SelectorName) && Current->ParameterIndex > 0) { 2822 if (Current->ParameterIndex == 1) 2823 Current->SplitPenalty += 5 * Current->BindingStrength; 2824 } else { 2825 Current->SplitPenalty += 20 * Current->BindingStrength; 2826 } 2827 2828 Current = Current->Next; 2829 } 2830 2831 calculateUnbreakableTailLengths(Line); 2832 unsigned IndentLevel = Line.Level; 2833 for (Current = Line.First; Current != nullptr; Current = Current->Next) { 2834 if (Current->Role) 2835 Current->Role->precomputeFormattingInfos(Current); 2836 if (Current->MatchingParen && 2837 Current->MatchingParen->opensBlockOrBlockTypeList(Style) && 2838 IndentLevel > 0) 2839 --IndentLevel; 2840 Current->IndentLevel = IndentLevel; 2841 if (Current->opensBlockOrBlockTypeList(Style)) 2842 ++IndentLevel; 2843 } 2844 2845 LLVM_DEBUG({ printDebugInfo(Line); }); 2846 } 2847 2848 void TokenAnnotator::calculateUnbreakableTailLengths( 2849 AnnotatedLine &Line) const { 2850 unsigned UnbreakableTailLength = 0; 2851 FormatToken *Current = Line.Last; 2852 while (Current) { 2853 Current->UnbreakableTailLength = UnbreakableTailLength; 2854 if (Current->CanBreakBefore || 2855 Current->isOneOf(tok::comment, tok::string_literal)) { 2856 UnbreakableTailLength = 0; 2857 } else { 2858 UnbreakableTailLength += 2859 Current->ColumnWidth + Current->SpacesRequiredBefore; 2860 } 2861 Current = Current->Previous; 2862 } 2863 } 2864 2865 void TokenAnnotator::calculateArrayInitializerColumnList( 2866 AnnotatedLine &Line) const { 2867 if (Line.First == Line.Last) 2868 return; 2869 auto *CurrentToken = Line.First; 2870 CurrentToken->ArrayInitializerLineStart = true; 2871 unsigned Depth = 0; 2872 while (CurrentToken != nullptr && CurrentToken != Line.Last) { 2873 if (CurrentToken->is(tok::l_brace)) { 2874 CurrentToken->IsArrayInitializer = true; 2875 if (CurrentToken->Next != nullptr) 2876 CurrentToken->Next->MustBreakBefore = true; 2877 CurrentToken = 2878 calculateInitializerColumnList(Line, CurrentToken->Next, Depth + 1); 2879 } else { 2880 CurrentToken = CurrentToken->Next; 2881 } 2882 } 2883 } 2884 2885 FormatToken *TokenAnnotator::calculateInitializerColumnList( 2886 AnnotatedLine &Line, FormatToken *CurrentToken, unsigned Depth) const { 2887 while (CurrentToken != nullptr && CurrentToken != Line.Last) { 2888 if (CurrentToken->is(tok::l_brace)) 2889 ++Depth; 2890 else if (CurrentToken->is(tok::r_brace)) 2891 --Depth; 2892 if (Depth == 2 && CurrentToken->isOneOf(tok::l_brace, tok::comma)) { 2893 CurrentToken = CurrentToken->Next; 2894 if (CurrentToken == nullptr) 2895 break; 2896 CurrentToken->StartsColumn = true; 2897 CurrentToken = CurrentToken->Previous; 2898 } 2899 CurrentToken = CurrentToken->Next; 2900 } 2901 return CurrentToken; 2902 } 2903 2904 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line, 2905 const FormatToken &Tok, 2906 bool InFunctionDecl) const { 2907 const FormatToken &Left = *Tok.Previous; 2908 const FormatToken &Right = Tok; 2909 2910 if (Left.is(tok::semi)) 2911 return 0; 2912 2913 if (Style.Language == FormatStyle::LK_Java) { 2914 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws)) 2915 return 1; 2916 if (Right.is(Keywords.kw_implements)) 2917 return 2; 2918 if (Left.is(tok::comma) && Left.NestingLevel == 0) 2919 return 3; 2920 } else if (Style.isJavaScript()) { 2921 if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma)) 2922 return 100; 2923 if (Left.is(TT_JsTypeColon)) 2924 return 35; 2925 if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) || 2926 (Right.is(TT_TemplateString) && Right.TokenText.startswith("}"))) 2927 return 100; 2928 // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()". 2929 if (Left.opensScope() && Right.closesScope()) 2930 return 200; 2931 } 2932 2933 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral)) 2934 return 1; 2935 if (Right.is(tok::l_square)) { 2936 if (Style.Language == FormatStyle::LK_Proto) 2937 return 1; 2938 if (Left.is(tok::r_square)) 2939 return 200; 2940 // Slightly prefer formatting local lambda definitions like functions. 2941 if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal)) 2942 return 35; 2943 if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare, 2944 TT_ArrayInitializerLSquare, 2945 TT_DesignatedInitializerLSquare, TT_AttributeSquare)) 2946 return 500; 2947 } 2948 2949 if (Left.is(tok::coloncolon) || 2950 (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto)) 2951 return 500; 2952 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) || 2953 Right.is(tok::kw_operator)) { 2954 if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt) 2955 return 3; 2956 if (Left.is(TT_StartOfName)) 2957 return 110; 2958 if (InFunctionDecl && Right.NestingLevel == 0) 2959 return Style.PenaltyReturnTypeOnItsOwnLine; 2960 return 200; 2961 } 2962 if (Right.is(TT_PointerOrReference)) 2963 return 190; 2964 if (Right.is(TT_LambdaArrow)) 2965 return 110; 2966 if (Left.is(tok::equal) && Right.is(tok::l_brace)) 2967 return 160; 2968 if (Left.is(TT_CastRParen)) 2969 return 100; 2970 if (Left.isOneOf(tok::kw_class, tok::kw_struct)) 2971 return 5000; 2972 if (Left.is(tok::comment)) 2973 return 1000; 2974 2975 if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon, 2976 TT_CtorInitializerColon)) 2977 return 2; 2978 2979 if (Right.isMemberAccess()) { 2980 // Breaking before the "./->" of a chained call/member access is reasonably 2981 // cheap, as formatting those with one call per line is generally 2982 // desirable. In particular, it should be cheaper to break before the call 2983 // than it is to break inside a call's parameters, which could lead to weird 2984 // "hanging" indents. The exception is the very last "./->" to support this 2985 // frequent pattern: 2986 // 2987 // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc( 2988 // dddddddd); 2989 // 2990 // which might otherwise be blown up onto many lines. Here, clang-format 2991 // won't produce "hanging" indents anyway as there is no other trailing 2992 // call. 2993 // 2994 // Also apply higher penalty is not a call as that might lead to a wrapping 2995 // like: 2996 // 2997 // aaaaaaa 2998 // .aaaaaaaaa.bbbbbbbb(cccccccc); 2999 return !Right.NextOperator || !Right.NextOperator->Previous->closesScope() 3000 ? 150 3001 : 35; 3002 } 3003 3004 if (Right.is(TT_TrailingAnnotation) && 3005 (!Right.Next || Right.Next->isNot(tok::l_paren))) { 3006 // Moving trailing annotations to the next line is fine for ObjC method 3007 // declarations. 3008 if (Line.startsWith(TT_ObjCMethodSpecifier)) 3009 return 10; 3010 // Generally, breaking before a trailing annotation is bad unless it is 3011 // function-like. It seems to be especially preferable to keep standard 3012 // annotations (i.e. "const", "final" and "override") on the same line. 3013 // Use a slightly higher penalty after ")" so that annotations like 3014 // "const override" are kept together. 3015 bool is_short_annotation = Right.TokenText.size() < 10; 3016 return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0); 3017 } 3018 3019 // In for-loops, prefer breaking at ',' and ';'. 3020 if (Line.startsWith(tok::kw_for) && Left.is(tok::equal)) 3021 return 4; 3022 3023 // In Objective-C method expressions, prefer breaking before "param:" over 3024 // breaking after it. 3025 if (Right.is(TT_SelectorName)) 3026 return 0; 3027 if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr)) 3028 return Line.MightBeFunctionDecl ? 50 : 500; 3029 3030 // In Objective-C type declarations, avoid breaking after the category's 3031 // open paren (we'll prefer breaking after the protocol list's opening 3032 // angle bracket, if present). 3033 if (Line.Type == LT_ObjCDecl && Left.is(tok::l_paren) && Left.Previous && 3034 Left.Previous->isOneOf(tok::identifier, tok::greater)) 3035 return 500; 3036 3037 if (Left.is(tok::l_paren) && Style.PenaltyBreakOpenParenthesis != 0) 3038 return Style.PenaltyBreakOpenParenthesis; 3039 if (Left.is(tok::l_paren) && InFunctionDecl && 3040 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign) 3041 return 100; 3042 if (Left.is(tok::l_paren) && Left.Previous && 3043 (Left.Previous->is(tok::kw_for) || Left.Previous->isIf())) 3044 return 1000; 3045 if (Left.is(tok::equal) && InFunctionDecl) 3046 return 110; 3047 if (Right.is(tok::r_brace)) 3048 return 1; 3049 if (Left.is(TT_TemplateOpener)) 3050 return 100; 3051 if (Left.opensScope()) { 3052 // If we aren't aligning after opening parens/braces we can always break 3053 // here unless the style does not want us to place all arguments on the 3054 // next line. 3055 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign && 3056 (Left.ParameterCount <= 1 || Style.AllowAllArgumentsOnNextLine)) 3057 return 0; 3058 if (Left.is(tok::l_brace) && !Style.Cpp11BracedListStyle) 3059 return 19; 3060 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter 3061 : 19; 3062 } 3063 if (Left.is(TT_JavaAnnotation)) 3064 return 50; 3065 3066 if (Left.is(TT_UnaryOperator)) 3067 return 60; 3068 if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous && 3069 Left.Previous->isLabelString() && 3070 (Left.NextOperator || Left.OperatorIndex != 0)) 3071 return 50; 3072 if (Right.is(tok::plus) && Left.isLabelString() && 3073 (Right.NextOperator || Right.OperatorIndex != 0)) 3074 return 25; 3075 if (Left.is(tok::comma)) 3076 return 1; 3077 if (Right.is(tok::lessless) && Left.isLabelString() && 3078 (Right.NextOperator || Right.OperatorIndex != 1)) 3079 return 25; 3080 if (Right.is(tok::lessless)) { 3081 // Breaking at a << is really cheap. 3082 if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0) 3083 // Slightly prefer to break before the first one in log-like statements. 3084 return 2; 3085 return 1; 3086 } 3087 if (Left.ClosesTemplateDeclaration) 3088 return Style.PenaltyBreakTemplateDeclaration; 3089 if (Left.ClosesRequiresClause) 3090 return 0; 3091 if (Left.is(TT_ConditionalExpr)) 3092 return prec::Conditional; 3093 prec::Level Level = Left.getPrecedence(); 3094 if (Level == prec::Unknown) 3095 Level = Right.getPrecedence(); 3096 if (Level == prec::Assignment) 3097 return Style.PenaltyBreakAssignment; 3098 if (Level != prec::Unknown) 3099 return Level; 3100 3101 return 3; 3102 } 3103 3104 bool TokenAnnotator::spaceRequiredBeforeParens(const FormatToken &Right) const { 3105 if (Style.SpaceBeforeParens == FormatStyle::SBPO_Always) 3106 return true; 3107 if (Right.is(TT_OverloadedOperatorLParen) && 3108 Style.SpaceBeforeParensOptions.AfterOverloadedOperator) 3109 return true; 3110 if (Style.SpaceBeforeParensOptions.BeforeNonEmptyParentheses && 3111 Right.ParameterCount > 0) 3112 return true; 3113 return false; 3114 } 3115 3116 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line, 3117 const FormatToken &Left, 3118 const FormatToken &Right) const { 3119 if (Left.is(tok::kw_return) && 3120 !Right.isOneOf(tok::semi, tok::r_paren, tok::hashhash)) 3121 return true; 3122 if (Style.isJson() && Left.is(tok::string_literal) && Right.is(tok::colon)) 3123 return false; 3124 if (Left.is(Keywords.kw_assert) && Style.Language == FormatStyle::LK_Java) 3125 return true; 3126 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty && 3127 Left.Tok.getObjCKeywordID() == tok::objc_property) 3128 return true; 3129 if (Right.is(tok::hashhash)) 3130 return Left.is(tok::hash); 3131 if (Left.isOneOf(tok::hashhash, tok::hash)) 3132 return Right.is(tok::hash); 3133 if ((Left.is(tok::l_paren) && Right.is(tok::r_paren)) || 3134 (Left.is(tok::l_brace) && Left.isNot(BK_Block) && 3135 Right.is(tok::r_brace) && Right.isNot(BK_Block))) 3136 return Style.SpaceInEmptyParentheses; 3137 if (Style.SpacesInConditionalStatement) { 3138 const FormatToken *LeftParen = nullptr; 3139 if (Left.is(tok::l_paren)) 3140 LeftParen = &Left; 3141 else if (Right.is(tok::r_paren) && Right.MatchingParen) 3142 LeftParen = Right.MatchingParen; 3143 if (LeftParen && LeftParen->Previous && 3144 isKeywordWithCondition(*LeftParen->Previous)) 3145 return true; 3146 } 3147 3148 // auto{x} auto(x) 3149 if (Left.is(tok::kw_auto) && Right.isOneOf(tok::l_paren, tok::l_brace)) 3150 return false; 3151 3152 // operator co_await(x) 3153 if (Right.is(tok::l_paren) && Left.is(tok::kw_co_await) && Left.Previous && 3154 Left.Previous->is(tok::kw_operator)) 3155 return false; 3156 // co_await (x), co_yield (x), co_return (x) 3157 if (Left.isOneOf(tok::kw_co_await, tok::kw_co_yield, tok::kw_co_return) && 3158 !Right.isOneOf(tok::semi, tok::r_paren)) 3159 return true; 3160 3161 if (Left.is(tok::l_paren) || Right.is(tok::r_paren)) 3162 return (Right.is(TT_CastRParen) || 3163 (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen))) 3164 ? Style.SpacesInCStyleCastParentheses 3165 : Style.SpacesInParentheses; 3166 if (Right.isOneOf(tok::semi, tok::comma)) 3167 return false; 3168 if (Right.is(tok::less) && Line.Type == LT_ObjCDecl) { 3169 bool IsLightweightGeneric = Right.MatchingParen && 3170 Right.MatchingParen->Next && 3171 Right.MatchingParen->Next->is(tok::colon); 3172 return !IsLightweightGeneric && Style.ObjCSpaceBeforeProtocolList; 3173 } 3174 if (Right.is(tok::less) && Left.is(tok::kw_template)) 3175 return Style.SpaceAfterTemplateKeyword; 3176 if (Left.isOneOf(tok::exclaim, tok::tilde)) 3177 return false; 3178 if (Left.is(tok::at) && 3179 Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant, 3180 tok::numeric_constant, tok::l_paren, tok::l_brace, 3181 tok::kw_true, tok::kw_false)) 3182 return false; 3183 if (Left.is(tok::colon)) 3184 return !Left.is(TT_ObjCMethodExpr); 3185 if (Left.is(tok::coloncolon)) 3186 return false; 3187 if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) { 3188 if (Style.Language == FormatStyle::LK_TextProto || 3189 (Style.Language == FormatStyle::LK_Proto && 3190 (Left.is(TT_DictLiteral) || Right.is(TT_DictLiteral)))) { 3191 // Format empty list as `<>`. 3192 if (Left.is(tok::less) && Right.is(tok::greater)) 3193 return false; 3194 return !Style.Cpp11BracedListStyle; 3195 } 3196 return false; 3197 } 3198 if (Right.is(tok::ellipsis)) 3199 return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous && 3200 Left.Previous->is(tok::kw_case)); 3201 if (Left.is(tok::l_square) && Right.is(tok::amp)) 3202 return Style.SpacesInSquareBrackets; 3203 if (Right.is(TT_PointerOrReference)) { 3204 if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) { 3205 if (!Left.MatchingParen) 3206 return true; 3207 FormatToken *TokenBeforeMatchingParen = 3208 Left.MatchingParen->getPreviousNonComment(); 3209 if (!TokenBeforeMatchingParen || !Left.is(TT_TypeDeclarationParen)) 3210 return true; 3211 } 3212 // Add a space if the previous token is a pointer qualifier or the closing 3213 // parenthesis of __attribute__(()) expression and the style requires spaces 3214 // after pointer qualifiers. 3215 if ((Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_After || 3216 Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both) && 3217 (Left.is(TT_AttributeParen) || Left.canBePointerOrReferenceQualifier())) 3218 return true; 3219 if (Left.Tok.isLiteral()) 3220 return true; 3221 // for (auto a = 0, b = 0; const auto & c : {1, 2, 3}) 3222 if (Left.isTypeOrIdentifier() && Right.Next && Right.Next->Next && 3223 Right.Next->Next->is(TT_RangeBasedForLoopColon)) 3224 return getTokenPointerOrReferenceAlignment(Right) != 3225 FormatStyle::PAS_Left; 3226 return !Left.isOneOf(TT_PointerOrReference, tok::l_paren) && 3227 (getTokenPointerOrReferenceAlignment(Right) != 3228 FormatStyle::PAS_Left || 3229 (Line.IsMultiVariableDeclStmt && 3230 (Left.NestingLevel == 0 || 3231 (Left.NestingLevel == 1 && startsWithInitStatement(Line))))); 3232 } 3233 if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) && 3234 (!Left.is(TT_PointerOrReference) || 3235 (getTokenPointerOrReferenceAlignment(Left) != FormatStyle::PAS_Right && 3236 !Line.IsMultiVariableDeclStmt))) 3237 return true; 3238 if (Left.is(TT_PointerOrReference)) { 3239 // Add a space if the next token is a pointer qualifier and the style 3240 // requires spaces before pointer qualifiers. 3241 if ((Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Before || 3242 Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both) && 3243 Right.canBePointerOrReferenceQualifier()) 3244 return true; 3245 // & 1 3246 if (Right.Tok.isLiteral()) 3247 return true; 3248 // & /* comment 3249 if (Right.is(TT_BlockComment)) 3250 return true; 3251 // foo() -> const Bar * override/final 3252 if (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) && 3253 !Right.is(TT_StartOfName)) 3254 return true; 3255 // & { 3256 if (Right.is(tok::l_brace) && Right.is(BK_Block)) 3257 return true; 3258 // for (auto a = 0, b = 0; const auto& c : {1, 2, 3}) 3259 if (Left.Previous && Left.Previous->isTypeOrIdentifier() && Right.Next && 3260 Right.Next->is(TT_RangeBasedForLoopColon)) 3261 return getTokenPointerOrReferenceAlignment(Left) != 3262 FormatStyle::PAS_Right; 3263 if (Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare, 3264 tok::l_paren)) 3265 return false; 3266 if (getTokenPointerOrReferenceAlignment(Left) == FormatStyle::PAS_Right) 3267 return false; 3268 // FIXME: Setting IsMultiVariableDeclStmt for the whole line is error-prone, 3269 // because it does not take into account nested scopes like lambdas. 3270 // In multi-variable declaration statements, attach */& to the variable 3271 // independently of the style. However, avoid doing it if we are in a nested 3272 // scope, e.g. lambda. We still need to special-case statements with 3273 // initializers. 3274 if (Line.IsMultiVariableDeclStmt && 3275 (Left.NestingLevel == Line.First->NestingLevel || 3276 ((Left.NestingLevel == Line.First->NestingLevel + 1) && 3277 startsWithInitStatement(Line)))) 3278 return false; 3279 return Left.Previous && !Left.Previous->isOneOf( 3280 tok::l_paren, tok::coloncolon, tok::l_square); 3281 } 3282 // Ensure right pointer alignment with ellipsis e.g. int *...P 3283 if (Left.is(tok::ellipsis) && Left.Previous && 3284 Left.Previous->isOneOf(tok::star, tok::amp, tok::ampamp)) 3285 return Style.PointerAlignment != FormatStyle::PAS_Right; 3286 3287 if (Right.is(tok::star) && Left.is(tok::l_paren)) 3288 return false; 3289 if (Left.is(tok::star) && Right.isOneOf(tok::star, tok::amp, tok::ampamp)) 3290 return false; 3291 if (Right.isOneOf(tok::star, tok::amp, tok::ampamp)) { 3292 const FormatToken *Previous = &Left; 3293 while (Previous && !Previous->is(tok::kw_operator)) { 3294 if (Previous->is(tok::identifier) || Previous->isSimpleTypeSpecifier()) { 3295 Previous = Previous->getPreviousNonComment(); 3296 continue; 3297 } 3298 if (Previous->is(TT_TemplateCloser) && Previous->MatchingParen) { 3299 Previous = Previous->MatchingParen->getPreviousNonComment(); 3300 continue; 3301 } 3302 if (Previous->is(tok::coloncolon)) { 3303 Previous = Previous->getPreviousNonComment(); 3304 continue; 3305 } 3306 break; 3307 } 3308 // Space between the type and the * in: 3309 // operator void*() 3310 // operator char*() 3311 // operator void const*() 3312 // operator void volatile*() 3313 // operator /*comment*/ const char*() 3314 // operator volatile /*comment*/ char*() 3315 // operator Foo*() 3316 // operator C<T>*() 3317 // operator std::Foo*() 3318 // operator C<T>::D<U>*() 3319 // dependent on PointerAlignment style. 3320 if (Previous) { 3321 if (Previous->endsSequence(tok::kw_operator)) 3322 return Style.PointerAlignment != FormatStyle::PAS_Left; 3323 if (Previous->is(tok::kw_const) || Previous->is(tok::kw_volatile)) 3324 return (Style.PointerAlignment != FormatStyle::PAS_Left) || 3325 (Style.SpaceAroundPointerQualifiers == 3326 FormatStyle::SAPQ_After) || 3327 (Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both); 3328 } 3329 } 3330 const auto SpaceRequiredForArrayInitializerLSquare = 3331 [](const FormatToken &LSquareTok, const FormatStyle &Style) { 3332 return Style.SpacesInContainerLiterals || 3333 ((Style.Language == FormatStyle::LK_Proto || 3334 Style.Language == FormatStyle::LK_TextProto) && 3335 !Style.Cpp11BracedListStyle && 3336 LSquareTok.endsSequence(tok::l_square, tok::colon, 3337 TT_SelectorName)); 3338 }; 3339 if (Left.is(tok::l_square)) 3340 return (Left.is(TT_ArrayInitializerLSquare) && Right.isNot(tok::r_square) && 3341 SpaceRequiredForArrayInitializerLSquare(Left, Style)) || 3342 (Left.isOneOf(TT_ArraySubscriptLSquare, TT_StructuredBindingLSquare, 3343 TT_LambdaLSquare) && 3344 Style.SpacesInSquareBrackets && Right.isNot(tok::r_square)); 3345 if (Right.is(tok::r_square)) 3346 return Right.MatchingParen && 3347 ((Right.MatchingParen->is(TT_ArrayInitializerLSquare) && 3348 SpaceRequiredForArrayInitializerLSquare(*Right.MatchingParen, 3349 Style)) || 3350 (Style.SpacesInSquareBrackets && 3351 Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare, 3352 TT_StructuredBindingLSquare, 3353 TT_LambdaLSquare)) || 3354 Right.MatchingParen->is(TT_AttributeParen)); 3355 if (Right.is(tok::l_square) && 3356 !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare, 3357 TT_DesignatedInitializerLSquare, 3358 TT_StructuredBindingLSquare, TT_AttributeSquare) && 3359 !Left.isOneOf(tok::numeric_constant, TT_DictLiteral) && 3360 !(!Left.is(tok::r_square) && Style.SpaceBeforeSquareBrackets && 3361 Right.is(TT_ArraySubscriptLSquare))) 3362 return false; 3363 if (Left.is(tok::l_brace) && Right.is(tok::r_brace)) 3364 return !Left.Children.empty(); // No spaces in "{}". 3365 if ((Left.is(tok::l_brace) && Left.isNot(BK_Block)) || 3366 (Right.is(tok::r_brace) && Right.MatchingParen && 3367 Right.MatchingParen->isNot(BK_Block))) 3368 return Style.Cpp11BracedListStyle ? Style.SpacesInParentheses : true; 3369 if (Left.is(TT_BlockComment)) 3370 // No whitespace in x(/*foo=*/1), except for JavaScript. 3371 return Style.isJavaScript() || !Left.TokenText.endswith("=*/"); 3372 3373 // Space between template and attribute. 3374 // e.g. template <typename T> [[nodiscard]] ... 3375 if (Left.is(TT_TemplateCloser) && Right.is(TT_AttributeSquare)) 3376 return true; 3377 // Space before parentheses common for all languages 3378 if (Right.is(tok::l_paren)) { 3379 if (Left.is(TT_TemplateCloser) && Right.isNot(TT_FunctionTypeLParen)) 3380 return spaceRequiredBeforeParens(Right); 3381 if (Left.isOneOf(TT_RequiresClause, TT_RequiresClauseInARequiresExpression)) 3382 return Style.SpaceBeforeParensOptions.AfterRequiresInClause || 3383 spaceRequiredBeforeParens(Right); 3384 if (Left.is(TT_RequiresExpression)) 3385 return Style.SpaceBeforeParensOptions.AfterRequiresInExpression || 3386 spaceRequiredBeforeParens(Right); 3387 if ((Left.is(tok::r_paren) && Left.is(TT_AttributeParen)) || 3388 (Left.is(tok::r_square) && Left.is(TT_AttributeSquare))) 3389 return true; 3390 if (Left.is(TT_ForEachMacro)) 3391 return Style.SpaceBeforeParensOptions.AfterForeachMacros || 3392 spaceRequiredBeforeParens(Right); 3393 if (Left.is(TT_IfMacro)) 3394 return Style.SpaceBeforeParensOptions.AfterIfMacros || 3395 spaceRequiredBeforeParens(Right); 3396 if (Line.Type == LT_ObjCDecl) 3397 return true; 3398 if (Left.is(tok::semi)) 3399 return true; 3400 if (Left.isOneOf(tok::pp_elif, tok::kw_for, tok::kw_while, tok::kw_switch, 3401 tok::kw_case, TT_ForEachMacro, TT_ObjCForIn) || 3402 Left.isIf(Line.Type != LT_PreprocessorDirective)) 3403 return Style.SpaceBeforeParensOptions.AfterControlStatements || 3404 spaceRequiredBeforeParens(Right); 3405 3406 // TODO add Operator overloading specific Options to 3407 // SpaceBeforeParensOptions 3408 if (Right.is(TT_OverloadedOperatorLParen)) 3409 return spaceRequiredBeforeParens(Right); 3410 // Function declaration or definition 3411 if (Line.MightBeFunctionDecl && (Left.is(TT_FunctionDeclarationName))) { 3412 if (Line.mightBeFunctionDefinition()) 3413 return Style.SpaceBeforeParensOptions.AfterFunctionDefinitionName || 3414 spaceRequiredBeforeParens(Right); 3415 else 3416 return Style.SpaceBeforeParensOptions.AfterFunctionDeclarationName || 3417 spaceRequiredBeforeParens(Right); 3418 } 3419 // Lambda 3420 if (Line.Type != LT_PreprocessorDirective && Left.is(tok::r_square) && 3421 Left.MatchingParen && Left.MatchingParen->is(TT_LambdaLSquare)) 3422 return Style.SpaceBeforeParensOptions.AfterFunctionDefinitionName || 3423 spaceRequiredBeforeParens(Right); 3424 if (!Left.Previous || Left.Previous->isNot(tok::period)) { 3425 if (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch)) 3426 return Style.SpaceBeforeParensOptions.AfterControlStatements || 3427 spaceRequiredBeforeParens(Right); 3428 if (Left.isOneOf(tok::kw_new, tok::kw_delete)) 3429 return ((!Line.MightBeFunctionDecl || !Left.Previous) && 3430 Style.SpaceBeforeParens != FormatStyle::SBPO_Never) || 3431 spaceRequiredBeforeParens(Right); 3432 3433 if (Left.is(tok::r_square) && Left.MatchingParen && 3434 Left.MatchingParen->Previous && 3435 Left.MatchingParen->Previous->is(tok::kw_delete)) 3436 return (Style.SpaceBeforeParens != FormatStyle::SBPO_Never) || 3437 spaceRequiredBeforeParens(Right); 3438 } 3439 // Handle builtins like identifiers. 3440 if (Line.Type != LT_PreprocessorDirective && 3441 (Left.Tok.getIdentifierInfo() || Left.is(tok::r_paren))) 3442 return spaceRequiredBeforeParens(Right); 3443 return false; 3444 } 3445 if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword) 3446 return false; 3447 if (Right.is(TT_UnaryOperator)) 3448 return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) && 3449 (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr)); 3450 if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square, 3451 tok::r_paren) || 3452 Left.isSimpleTypeSpecifier()) && 3453 Right.is(tok::l_brace) && Right.getNextNonComment() && 3454 Right.isNot(BK_Block)) 3455 return false; 3456 if (Left.is(tok::period) || Right.is(tok::period)) 3457 return false; 3458 // u#str, U#str, L#str, u8#str 3459 // uR#str, UR#str, LR#str, u8R#str 3460 if (Right.is(tok::hash) && Left.is(tok::identifier) && 3461 (Left.TokenText == "L" || Left.TokenText == "u" || 3462 Left.TokenText == "U" || Left.TokenText == "u8" || 3463 Left.TokenText == "LR" || Left.TokenText == "uR" || 3464 Left.TokenText == "UR" || Left.TokenText == "u8R")) 3465 return false; 3466 if (Left.is(TT_TemplateCloser) && Left.MatchingParen && 3467 Left.MatchingParen->Previous && 3468 (Left.MatchingParen->Previous->is(tok::period) || 3469 Left.MatchingParen->Previous->is(tok::coloncolon))) 3470 // Java call to generic function with explicit type: 3471 // A.<B<C<...>>>DoSomething(); 3472 // A::<B<C<...>>>DoSomething(); // With a Java 8 method reference. 3473 return false; 3474 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square)) 3475 return false; 3476 if (Left.is(tok::l_brace) && Left.endsSequence(TT_DictLiteral, tok::at)) 3477 // Objective-C dictionary literal -> no space after opening brace. 3478 return false; 3479 if (Right.is(tok::r_brace) && Right.MatchingParen && 3480 Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at)) 3481 // Objective-C dictionary literal -> no space before closing brace. 3482 return false; 3483 if (Right.getType() == TT_TrailingAnnotation && 3484 Right.isOneOf(tok::amp, tok::ampamp) && 3485 Left.isOneOf(tok::kw_const, tok::kw_volatile) && 3486 (!Right.Next || Right.Next->is(tok::semi))) 3487 // Match const and volatile ref-qualifiers without any additional 3488 // qualifiers such as 3489 // void Fn() const &; 3490 return getTokenReferenceAlignment(Right) != FormatStyle::PAS_Left; 3491 3492 return true; 3493 } 3494 3495 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, 3496 const FormatToken &Right) const { 3497 const FormatToken &Left = *Right.Previous; 3498 3499 // If the token is finalized don't touch it (as it could be in a 3500 // clang-format-off section). 3501 if (Left.Finalized) 3502 return Right.hasWhitespaceBefore(); 3503 3504 if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo()) 3505 return true; // Never ever merge two identifiers. 3506 3507 // Leave a space between * and /* to avoid C4138 `comment end` found outside 3508 // of comment. 3509 if (Left.is(tok::star) && Right.is(tok::comment)) 3510 return true; 3511 3512 if (Style.isCpp()) { 3513 // Space between import <iostream>. 3514 // or import .....; 3515 if (Left.is(Keywords.kw_import) && Right.isOneOf(tok::less, tok::ellipsis)) 3516 return true; 3517 // Space between `module :` and `import :`. 3518 if (Left.isOneOf(Keywords.kw_module, Keywords.kw_import) && 3519 Right.is(TT_ModulePartitionColon)) 3520 return true; 3521 // No space between import foo:bar but keep a space between import :bar; 3522 if (Left.is(tok::identifier) && Right.is(TT_ModulePartitionColon)) 3523 return false; 3524 // No space between :bar; 3525 if (Left.is(TT_ModulePartitionColon) && 3526 Right.isOneOf(tok::identifier, tok::kw_private)) 3527 return false; 3528 if (Left.is(tok::ellipsis) && Right.is(tok::identifier) && 3529 Line.First->is(Keywords.kw_import)) 3530 return false; 3531 // Space in __attribute__((attr)) ::type. 3532 if (Left.is(TT_AttributeParen) && Right.is(tok::coloncolon)) 3533 return true; 3534 3535 if (Left.is(tok::kw_operator)) 3536 return Right.is(tok::coloncolon); 3537 if (Right.is(tok::l_brace) && Right.is(BK_BracedInit) && 3538 !Left.opensScope() && Style.SpaceBeforeCpp11BracedList) 3539 return true; 3540 if (Left.is(tok::less) && Left.is(TT_OverloadedOperator) && 3541 Right.is(TT_TemplateOpener)) 3542 return true; 3543 } else if (Style.Language == FormatStyle::LK_Proto || 3544 Style.Language == FormatStyle::LK_TextProto) { 3545 if (Right.is(tok::period) && 3546 Left.isOneOf(Keywords.kw_optional, Keywords.kw_required, 3547 Keywords.kw_repeated, Keywords.kw_extend)) 3548 return true; 3549 if (Right.is(tok::l_paren) && 3550 Left.isOneOf(Keywords.kw_returns, Keywords.kw_option)) 3551 return true; 3552 if (Right.isOneOf(tok::l_brace, tok::less) && Left.is(TT_SelectorName)) 3553 return true; 3554 // Slashes occur in text protocol extension syntax: [type/type] { ... }. 3555 if (Left.is(tok::slash) || Right.is(tok::slash)) 3556 return false; 3557 if (Left.MatchingParen && 3558 Left.MatchingParen->is(TT_ProtoExtensionLSquare) && 3559 Right.isOneOf(tok::l_brace, tok::less)) 3560 return !Style.Cpp11BracedListStyle; 3561 // A percent is probably part of a formatting specification, such as %lld. 3562 if (Left.is(tok::percent)) 3563 return false; 3564 // Preserve the existence of a space before a percent for cases like 0x%04x 3565 // and "%d %d" 3566 if (Left.is(tok::numeric_constant) && Right.is(tok::percent)) 3567 return Right.hasWhitespaceBefore(); 3568 } else if (Style.isJson()) { 3569 if (Right.is(tok::colon)) 3570 return false; 3571 } else if (Style.isCSharp()) { 3572 // Require spaces around '{' and before '}' unless they appear in 3573 // interpolated strings. Interpolated strings are merged into a single token 3574 // so cannot have spaces inserted by this function. 3575 3576 // No space between 'this' and '[' 3577 if (Left.is(tok::kw_this) && Right.is(tok::l_square)) 3578 return false; 3579 3580 // No space between 'new' and '(' 3581 if (Left.is(tok::kw_new) && Right.is(tok::l_paren)) 3582 return false; 3583 3584 // Space before { (including space within '{ {'). 3585 if (Right.is(tok::l_brace)) 3586 return true; 3587 3588 // Spaces inside braces. 3589 if (Left.is(tok::l_brace) && Right.isNot(tok::r_brace)) 3590 return true; 3591 3592 if (Left.isNot(tok::l_brace) && Right.is(tok::r_brace)) 3593 return true; 3594 3595 // Spaces around '=>'. 3596 if (Left.is(TT_FatArrow) || Right.is(TT_FatArrow)) 3597 return true; 3598 3599 // No spaces around attribute target colons 3600 if (Left.is(TT_AttributeColon) || Right.is(TT_AttributeColon)) 3601 return false; 3602 3603 // space between type and variable e.g. Dictionary<string,string> foo; 3604 if (Left.is(TT_TemplateCloser) && Right.is(TT_StartOfName)) 3605 return true; 3606 3607 // spaces inside square brackets. 3608 if (Left.is(tok::l_square) || Right.is(tok::r_square)) 3609 return Style.SpacesInSquareBrackets; 3610 3611 // No space before ? in nullable types. 3612 if (Right.is(TT_CSharpNullable)) 3613 return false; 3614 3615 // No space before null forgiving '!'. 3616 if (Right.is(TT_NonNullAssertion)) 3617 return false; 3618 3619 // No space between consecutive commas '[,,]'. 3620 if (Left.is(tok::comma) && Right.is(tok::comma)) 3621 return false; 3622 3623 // space after var in `var (key, value)` 3624 if (Left.is(Keywords.kw_var) && Right.is(tok::l_paren)) 3625 return true; 3626 3627 // space between keywords and paren e.g. "using (" 3628 if (Right.is(tok::l_paren)) 3629 if (Left.isOneOf(tok::kw_using, Keywords.kw_async, Keywords.kw_when, 3630 Keywords.kw_lock)) 3631 return Style.SpaceBeforeParensOptions.AfterControlStatements || 3632 spaceRequiredBeforeParens(Right); 3633 3634 // space between method modifier and opening parenthesis of a tuple return 3635 // type 3636 if (Left.isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected, 3637 tok::kw_virtual, tok::kw_extern, tok::kw_static, 3638 Keywords.kw_internal, Keywords.kw_abstract, 3639 Keywords.kw_sealed, Keywords.kw_override, 3640 Keywords.kw_async, Keywords.kw_unsafe) && 3641 Right.is(tok::l_paren)) 3642 return true; 3643 } else if (Style.isJavaScript()) { 3644 if (Left.is(TT_FatArrow)) 3645 return true; 3646 // for await ( ... 3647 if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && Left.Previous && 3648 Left.Previous->is(tok::kw_for)) 3649 return true; 3650 if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) && 3651 Right.MatchingParen) { 3652 const FormatToken *Next = Right.MatchingParen->getNextNonComment(); 3653 // An async arrow function, for example: `x = async () => foo();`, 3654 // as opposed to calling a function called async: `x = async();` 3655 if (Next && Next->is(TT_FatArrow)) 3656 return true; 3657 } 3658 if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) || 3659 (Right.is(TT_TemplateString) && Right.TokenText.startswith("}"))) 3660 return false; 3661 // In tagged template literals ("html`bar baz`"), there is no space between 3662 // the tag identifier and the template string. 3663 if (Keywords.IsJavaScriptIdentifier(Left, 3664 /* AcceptIdentifierName= */ false) && 3665 Right.is(TT_TemplateString)) 3666 return false; 3667 if (Right.is(tok::star) && 3668 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield)) 3669 return false; 3670 if (Right.isOneOf(tok::l_brace, tok::l_square) && 3671 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield, 3672 Keywords.kw_extends, Keywords.kw_implements)) 3673 return true; 3674 if (Right.is(tok::l_paren)) { 3675 // JS methods can use some keywords as names (e.g. `delete()`). 3676 if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo()) 3677 return false; 3678 // Valid JS method names can include keywords, e.g. `foo.delete()` or 3679 // `bar.instanceof()`. Recognize call positions by preceding period. 3680 if (Left.Previous && Left.Previous->is(tok::period) && 3681 Left.Tok.getIdentifierInfo()) 3682 return false; 3683 // Additional unary JavaScript operators that need a space after. 3684 if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof, 3685 tok::kw_void)) 3686 return true; 3687 } 3688 // `foo as const;` casts into a const type. 3689 if (Left.endsSequence(tok::kw_const, Keywords.kw_as)) 3690 return false; 3691 if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in, 3692 tok::kw_const) || 3693 // "of" is only a keyword if it appears after another identifier 3694 // (e.g. as "const x of y" in a for loop), or after a destructuring 3695 // operation (const [x, y] of z, const {a, b} of c). 3696 (Left.is(Keywords.kw_of) && Left.Previous && 3697 (Left.Previous->is(tok::identifier) || 3698 Left.Previous->isOneOf(tok::r_square, tok::r_brace)))) && 3699 (!Left.Previous || !Left.Previous->is(tok::period))) 3700 return true; 3701 if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && Left.Previous && 3702 Left.Previous->is(tok::period) && Right.is(tok::l_paren)) 3703 return false; 3704 if (Left.is(Keywords.kw_as) && 3705 Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren)) 3706 return true; 3707 if (Left.is(tok::kw_default) && Left.Previous && 3708 Left.Previous->is(tok::kw_export)) 3709 return true; 3710 if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace)) 3711 return true; 3712 if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion)) 3713 return false; 3714 if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator)) 3715 return false; 3716 if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) && 3717 Line.First->isOneOf(Keywords.kw_import, tok::kw_export)) 3718 return false; 3719 if (Left.is(tok::ellipsis)) 3720 return false; 3721 if (Left.is(TT_TemplateCloser) && 3722 !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square, 3723 Keywords.kw_implements, Keywords.kw_extends)) 3724 // Type assertions ('<type>expr') are not followed by whitespace. Other 3725 // locations that should have whitespace following are identified by the 3726 // above set of follower tokens. 3727 return false; 3728 if (Right.is(TT_NonNullAssertion)) 3729 return false; 3730 if (Left.is(TT_NonNullAssertion) && 3731 Right.isOneOf(Keywords.kw_as, Keywords.kw_in)) 3732 return true; // "x! as string", "x! in y" 3733 } else if (Style.Language == FormatStyle::LK_Java) { 3734 if (Left.is(tok::r_square) && Right.is(tok::l_brace)) 3735 return true; 3736 if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren)) 3737 return Style.SpaceBeforeParensOptions.AfterControlStatements || 3738 spaceRequiredBeforeParens(Right); 3739 if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private, 3740 tok::kw_protected) || 3741 Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract, 3742 Keywords.kw_native)) && 3743 Right.is(TT_TemplateOpener)) 3744 return true; 3745 } 3746 if (Left.is(TT_ImplicitStringLiteral)) 3747 return Right.hasWhitespaceBefore(); 3748 if (Line.Type == LT_ObjCMethodDecl) { 3749 if (Left.is(TT_ObjCMethodSpecifier)) 3750 return true; 3751 if (Left.is(tok::r_paren) && canBeObjCSelectorComponent(Right)) 3752 // Don't space between ')' and <id> or ')' and 'new'. 'new' is not a 3753 // keyword in Objective-C, and '+ (instancetype)new;' is a standard class 3754 // method declaration. 3755 return false; 3756 } 3757 if (Line.Type == LT_ObjCProperty && 3758 (Right.is(tok::equal) || Left.is(tok::equal))) 3759 return false; 3760 3761 if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) || 3762 Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow)) 3763 return true; 3764 if (Left.is(tok::comma) && !Right.is(TT_OverloadedOperatorLParen)) 3765 return true; 3766 if (Right.is(tok::comma)) 3767 return false; 3768 if (Right.is(TT_ObjCBlockLParen)) 3769 return true; 3770 if (Right.is(TT_CtorInitializerColon)) 3771 return Style.SpaceBeforeCtorInitializerColon; 3772 if (Right.is(TT_InheritanceColon) && !Style.SpaceBeforeInheritanceColon) 3773 return false; 3774 if (Right.is(TT_RangeBasedForLoopColon) && 3775 !Style.SpaceBeforeRangeBasedForLoopColon) 3776 return false; 3777 if (Left.is(TT_BitFieldColon)) 3778 return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both || 3779 Style.BitFieldColonSpacing == FormatStyle::BFCS_After; 3780 if (Right.is(tok::colon)) { 3781 if (Line.First->isOneOf(tok::kw_default, tok::kw_case)) 3782 return Style.SpaceBeforeCaseColon; 3783 const FormatToken *Next = Right.getNextNonComment(); 3784 if (!Next || Next->is(tok::semi)) 3785 return false; 3786 if (Right.is(TT_ObjCMethodExpr)) 3787 return false; 3788 if (Left.is(tok::question)) 3789 return false; 3790 if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon)) 3791 return false; 3792 if (Right.is(TT_DictLiteral)) 3793 return Style.SpacesInContainerLiterals; 3794 if (Right.is(TT_AttributeColon)) 3795 return false; 3796 if (Right.is(TT_CSharpNamedArgumentColon)) 3797 return false; 3798 if (Right.is(TT_BitFieldColon)) 3799 return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both || 3800 Style.BitFieldColonSpacing == FormatStyle::BFCS_Before; 3801 return true; 3802 } 3803 // Do not merge "- -" into "--". 3804 if ((Left.isOneOf(tok::minus, tok::minusminus) && 3805 Right.isOneOf(tok::minus, tok::minusminus)) || 3806 (Left.isOneOf(tok::plus, tok::plusplus) && 3807 Right.isOneOf(tok::plus, tok::plusplus))) 3808 return true; 3809 if (Left.is(TT_UnaryOperator)) { 3810 if (!Right.is(tok::l_paren)) { 3811 // The alternative operators for ~ and ! are "compl" and "not". 3812 // If they are used instead, we do not want to combine them with 3813 // the token to the right, unless that is a left paren. 3814 if (Left.is(tok::exclaim) && Left.TokenText == "not") 3815 return true; 3816 if (Left.is(tok::tilde) && Left.TokenText == "compl") 3817 return true; 3818 // Lambda captures allow for a lone &, so "&]" needs to be properly 3819 // handled. 3820 if (Left.is(tok::amp) && Right.is(tok::r_square)) 3821 return Style.SpacesInSquareBrackets; 3822 } 3823 return (Style.SpaceAfterLogicalNot && Left.is(tok::exclaim)) || 3824 Right.is(TT_BinaryOperator); 3825 } 3826 3827 // If the next token is a binary operator or a selector name, we have 3828 // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly. 3829 if (Left.is(TT_CastRParen)) 3830 return Style.SpaceAfterCStyleCast || 3831 Right.isOneOf(TT_BinaryOperator, TT_SelectorName); 3832 3833 auto ShouldAddSpacesInAngles = [this, &Right]() { 3834 if (this->Style.SpacesInAngles == FormatStyle::SIAS_Always) 3835 return true; 3836 if (this->Style.SpacesInAngles == FormatStyle::SIAS_Leave) 3837 return Right.hasWhitespaceBefore(); 3838 return false; 3839 }; 3840 3841 if (Left.is(tok::greater) && Right.is(tok::greater)) { 3842 if (Style.Language == FormatStyle::LK_TextProto || 3843 (Style.Language == FormatStyle::LK_Proto && Left.is(TT_DictLiteral))) 3844 return !Style.Cpp11BracedListStyle; 3845 return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) && 3846 ((Style.Standard < FormatStyle::LS_Cpp11) || 3847 ShouldAddSpacesInAngles()); 3848 } 3849 if (Right.isOneOf(tok::arrow, tok::arrowstar, tok::periodstar) || 3850 Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) || 3851 (Right.is(tok::period) && Right.isNot(TT_DesignatedInitializerPeriod))) 3852 return false; 3853 if (!Style.SpaceBeforeAssignmentOperators && Left.isNot(TT_TemplateCloser) && 3854 Right.getPrecedence() == prec::Assignment) 3855 return false; 3856 if (Style.Language == FormatStyle::LK_Java && Right.is(tok::coloncolon) && 3857 (Left.is(tok::identifier) || Left.is(tok::kw_this))) 3858 return false; 3859 if (Right.is(tok::coloncolon) && Left.is(tok::identifier)) 3860 // Generally don't remove existing spaces between an identifier and "::". 3861 // The identifier might actually be a macro name such as ALWAYS_INLINE. If 3862 // this turns out to be too lenient, add analysis of the identifier itself. 3863 return Right.hasWhitespaceBefore(); 3864 if (Right.is(tok::coloncolon) && 3865 !Left.isOneOf(tok::l_brace, tok::comment, tok::l_paren)) 3866 // Put a space between < and :: in vector< ::std::string > 3867 return (Left.is(TT_TemplateOpener) && 3868 ((Style.Standard < FormatStyle::LS_Cpp11) || 3869 ShouldAddSpacesInAngles())) || 3870 !(Left.isOneOf(tok::l_paren, tok::r_paren, tok::l_square, 3871 tok::kw___super, TT_TemplateOpener, 3872 TT_TemplateCloser)) || 3873 (Left.is(tok::l_paren) && Style.SpacesInParentheses); 3874 if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser))) 3875 return ShouldAddSpacesInAngles(); 3876 // Space before TT_StructuredBindingLSquare. 3877 if (Right.is(TT_StructuredBindingLSquare)) 3878 return !Left.isOneOf(tok::amp, tok::ampamp) || 3879 getTokenReferenceAlignment(Left) != FormatStyle::PAS_Right; 3880 // Space before & or && following a TT_StructuredBindingLSquare. 3881 if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) && 3882 Right.isOneOf(tok::amp, tok::ampamp)) 3883 return getTokenReferenceAlignment(Right) != FormatStyle::PAS_Left; 3884 if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) || 3885 (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && 3886 !Right.is(tok::r_paren))) 3887 return true; 3888 if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) && 3889 Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen)) 3890 return false; 3891 if (Right.is(tok::less) && Left.isNot(tok::l_paren) && 3892 Line.startsWith(tok::hash)) 3893 return true; 3894 if (Right.is(TT_TrailingUnaryOperator)) 3895 return false; 3896 if (Left.is(TT_RegexLiteral)) 3897 return false; 3898 return spaceRequiredBetween(Line, Left, Right); 3899 } 3900 3901 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style. 3902 static bool isAllmanBrace(const FormatToken &Tok) { 3903 return Tok.is(tok::l_brace) && Tok.is(BK_Block) && 3904 !Tok.isOneOf(TT_ObjCBlockLBrace, TT_LambdaLBrace, TT_DictLiteral); 3905 } 3906 3907 // Returns 'true' if 'Tok' is a function argument. 3908 static bool IsFunctionArgument(const FormatToken &Tok) { 3909 return Tok.MatchingParen && Tok.MatchingParen->Next && 3910 Tok.MatchingParen->Next->isOneOf(tok::comma, tok::r_paren); 3911 } 3912 3913 static bool 3914 isItAnEmptyLambdaAllowed(const FormatToken &Tok, 3915 FormatStyle::ShortLambdaStyle ShortLambdaOption) { 3916 return Tok.Children.empty() && ShortLambdaOption != FormatStyle::SLS_None; 3917 } 3918 3919 static bool isAllmanLambdaBrace(const FormatToken &Tok) { 3920 return Tok.is(tok::l_brace) && Tok.is(BK_Block) && 3921 !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral); 3922 } 3923 3924 // Returns the first token on the line that is not a comment. 3925 static const FormatToken *getFirstNonComment(const AnnotatedLine &Line) { 3926 const FormatToken *Next = Line.First; 3927 if (!Next) 3928 return Next; 3929 if (Next->is(tok::comment)) 3930 Next = Next->getNextNonComment(); 3931 return Next; 3932 } 3933 3934 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line, 3935 const FormatToken &Right) const { 3936 const FormatToken &Left = *Right.Previous; 3937 if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0) 3938 return true; 3939 3940 if (Style.isCSharp()) { 3941 if (Left.is(TT_FatArrow) && Right.is(tok::l_brace) && 3942 Style.BraceWrapping.AfterFunction) 3943 return true; 3944 if (Right.is(TT_CSharpNamedArgumentColon) || 3945 Left.is(TT_CSharpNamedArgumentColon)) 3946 return false; 3947 if (Right.is(TT_CSharpGenericTypeConstraint)) 3948 return true; 3949 if (Right.Next && Right.Next->is(TT_FatArrow) && 3950 (Right.is(tok::numeric_constant) || 3951 (Right.is(tok::identifier) && Right.TokenText == "_"))) 3952 return true; 3953 3954 // Break after C# [...] and before public/protected/private/internal. 3955 if (Left.is(TT_AttributeSquare) && Left.is(tok::r_square) && 3956 (Right.isAccessSpecifier(/*ColonRequired=*/false) || 3957 Right.is(Keywords.kw_internal))) 3958 return true; 3959 // Break between ] and [ but only when there are really 2 attributes. 3960 if (Left.is(TT_AttributeSquare) && Right.is(TT_AttributeSquare) && 3961 Left.is(tok::r_square) && Right.is(tok::l_square)) 3962 return true; 3963 3964 } else if (Style.isJavaScript()) { 3965 // FIXME: This might apply to other languages and token kinds. 3966 if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous && 3967 Left.Previous->is(tok::string_literal)) 3968 return true; 3969 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 && 3970 Left.Previous && Left.Previous->is(tok::equal) && 3971 Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export, 3972 tok::kw_const) && 3973 // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match 3974 // above. 3975 !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let)) 3976 // Object literals on the top level of a file are treated as "enum-style". 3977 // Each key/value pair is put on a separate line, instead of bin-packing. 3978 return true; 3979 if (Left.is(tok::l_brace) && Line.Level == 0 && 3980 (Line.startsWith(tok::kw_enum) || 3981 Line.startsWith(tok::kw_const, tok::kw_enum) || 3982 Line.startsWith(tok::kw_export, tok::kw_enum) || 3983 Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum))) 3984 // JavaScript top-level enum key/value pairs are put on separate lines 3985 // instead of bin-packing. 3986 return true; 3987 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) && Left.Previous && 3988 Left.Previous->is(TT_FatArrow)) { 3989 // JS arrow function (=> {...}). 3990 switch (Style.AllowShortLambdasOnASingleLine) { 3991 case FormatStyle::SLS_All: 3992 return false; 3993 case FormatStyle::SLS_None: 3994 return true; 3995 case FormatStyle::SLS_Empty: 3996 return !Left.Children.empty(); 3997 case FormatStyle::SLS_Inline: 3998 // allow one-lining inline (e.g. in function call args) and empty arrow 3999 // functions. 4000 return (Left.NestingLevel == 0 && Line.Level == 0) && 4001 !Left.Children.empty(); 4002 } 4003 llvm_unreachable("Unknown FormatStyle::ShortLambdaStyle enum"); 4004 } 4005 4006 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) && 4007 !Left.Children.empty()) 4008 // Support AllowShortFunctionsOnASingleLine for JavaScript. 4009 return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None || 4010 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty || 4011 (Left.NestingLevel == 0 && Line.Level == 0 && 4012 Style.AllowShortFunctionsOnASingleLine & 4013 FormatStyle::SFS_InlineOnly); 4014 } else if (Style.Language == FormatStyle::LK_Java) { 4015 if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next && 4016 Right.Next->is(tok::string_literal)) 4017 return true; 4018 } else if (Style.Language == FormatStyle::LK_Cpp || 4019 Style.Language == FormatStyle::LK_ObjC || 4020 Style.Language == FormatStyle::LK_Proto || 4021 Style.Language == FormatStyle::LK_TableGen || 4022 Style.Language == FormatStyle::LK_TextProto) { 4023 if (Left.isStringLiteral() && Right.isStringLiteral()) 4024 return true; 4025 } 4026 4027 // Basic JSON newline processing. 4028 if (Style.isJson()) { 4029 // Always break after a JSON record opener. 4030 // { 4031 // } 4032 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace)) 4033 return true; 4034 // Always break after a JSON array opener. 4035 // [ 4036 // ] 4037 if (Left.is(TT_ArrayInitializerLSquare) && Left.is(tok::l_square) && 4038 !Right.is(tok::r_square)) 4039 return true; 4040 // Always break after successive entries. 4041 // 1, 4042 // 2 4043 if (Left.is(tok::comma)) 4044 return true; 4045 } 4046 4047 // If the last token before a '}', ']', or ')' is a comma or a trailing 4048 // comment, the intention is to insert a line break after it in order to make 4049 // shuffling around entries easier. Import statements, especially in 4050 // JavaScript, can be an exception to this rule. 4051 if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) { 4052 const FormatToken *BeforeClosingBrace = nullptr; 4053 if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) || 4054 (Style.isJavaScript() && Left.is(tok::l_paren))) && 4055 Left.isNot(BK_Block) && Left.MatchingParen) 4056 BeforeClosingBrace = Left.MatchingParen->Previous; 4057 else if (Right.MatchingParen && 4058 (Right.MatchingParen->isOneOf(tok::l_brace, 4059 TT_ArrayInitializerLSquare) || 4060 (Style.isJavaScript() && Right.MatchingParen->is(tok::l_paren)))) 4061 BeforeClosingBrace = &Left; 4062 if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) || 4063 BeforeClosingBrace->isTrailingComment())) 4064 return true; 4065 } 4066 4067 if (Right.is(tok::comment)) 4068 return Left.isNot(BK_BracedInit) && Left.isNot(TT_CtorInitializerColon) && 4069 (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline); 4070 if (Left.isTrailingComment()) 4071 return true; 4072 if (Left.IsUnterminatedLiteral) 4073 return true; 4074 if (Right.is(tok::lessless) && Right.Next && Left.is(tok::string_literal) && 4075 Right.Next->is(tok::string_literal)) 4076 return true; 4077 if (Right.is(TT_RequiresClause)) { 4078 switch (Style.RequiresClausePosition) { 4079 case FormatStyle::RCPS_OwnLine: 4080 case FormatStyle::RCPS_WithFollowing: 4081 return true; 4082 default: 4083 break; 4084 } 4085 } 4086 // Can break after template<> declaration 4087 if (Left.ClosesTemplateDeclaration && Left.MatchingParen && 4088 Left.MatchingParen->NestingLevel == 0) { 4089 // Put concepts on the next line e.g. 4090 // template<typename T> 4091 // concept ... 4092 if (Right.is(tok::kw_concept)) 4093 return Style.BreakBeforeConceptDeclarations == FormatStyle::BBCDS_Always; 4094 return Style.AlwaysBreakTemplateDeclarations == FormatStyle::BTDS_Yes; 4095 } 4096 if (Left.ClosesRequiresClause && Right.isNot(tok::semi)) { 4097 switch (Style.RequiresClausePosition) { 4098 case FormatStyle::RCPS_OwnLine: 4099 case FormatStyle::RCPS_WithPreceding: 4100 return true; 4101 default: 4102 break; 4103 } 4104 } 4105 if (Style.PackConstructorInitializers == FormatStyle::PCIS_Never) { 4106 if (Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon && 4107 (Left.is(TT_CtorInitializerComma) || Right.is(TT_CtorInitializerColon))) 4108 return true; 4109 4110 if (Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon && 4111 Left.isOneOf(TT_CtorInitializerColon, TT_CtorInitializerComma)) 4112 return true; 4113 } 4114 if (Style.PackConstructorInitializers < FormatStyle::PCIS_CurrentLine && 4115 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma && 4116 Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) 4117 return true; 4118 // Break only if we have multiple inheritance. 4119 if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma && 4120 Right.is(TT_InheritanceComma)) 4121 return true; 4122 if (Style.BreakInheritanceList == FormatStyle::BILS_AfterComma && 4123 Left.is(TT_InheritanceComma)) 4124 return true; 4125 if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\"")) 4126 // Multiline raw string literals are special wrt. line breaks. The author 4127 // has made a deliberate choice and might have aligned the contents of the 4128 // string literal accordingly. Thus, we try keep existing line breaks. 4129 return Right.IsMultiline && Right.NewlinesBefore > 0; 4130 if ((Left.is(tok::l_brace) || (Left.is(tok::less) && Left.Previous && 4131 Left.Previous->is(tok::equal))) && 4132 Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) { 4133 // Don't put enums or option definitions onto single lines in protocol 4134 // buffers. 4135 return true; 4136 } 4137 if (Right.is(TT_InlineASMBrace)) 4138 return Right.HasUnescapedNewline; 4139 4140 if (isAllmanBrace(Left) || isAllmanBrace(Right)) { 4141 auto FirstNonComment = getFirstNonComment(Line); 4142 bool AccessSpecifier = 4143 FirstNonComment && 4144 FirstNonComment->isOneOf(Keywords.kw_internal, tok::kw_public, 4145 tok::kw_private, tok::kw_protected); 4146 4147 if (Style.BraceWrapping.AfterEnum) { 4148 if (Line.startsWith(tok::kw_enum) || 4149 Line.startsWith(tok::kw_typedef, tok::kw_enum)) 4150 return true; 4151 // Ensure BraceWrapping for `public enum A {`. 4152 if (AccessSpecifier && FirstNonComment->Next && 4153 FirstNonComment->Next->is(tok::kw_enum)) 4154 return true; 4155 } 4156 4157 // Ensure BraceWrapping for `public interface A {`. 4158 if (Style.BraceWrapping.AfterClass && 4159 ((AccessSpecifier && FirstNonComment->Next && 4160 FirstNonComment->Next->is(Keywords.kw_interface)) || 4161 Line.startsWith(Keywords.kw_interface))) 4162 return true; 4163 4164 return (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) || 4165 (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct); 4166 } 4167 4168 if (Left.is(TT_ObjCBlockLBrace) && 4169 Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) 4170 return true; 4171 4172 // Ensure wrapping after __attribute__((XX)) and @interface etc. 4173 if (Left.is(TT_AttributeParen) && Right.is(TT_ObjCDecl)) 4174 return true; 4175 4176 if (Left.is(TT_LambdaLBrace)) { 4177 if (IsFunctionArgument(Left) && 4178 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline) 4179 return false; 4180 4181 if (Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_None || 4182 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline || 4183 (!Left.Children.empty() && 4184 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Empty)) 4185 return true; 4186 } 4187 4188 if (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT_LambdaLBrace) && 4189 Left.isOneOf(tok::star, tok::amp, tok::ampamp, TT_TemplateCloser)) 4190 return true; 4191 4192 // Put multiple Java annotation on a new line. 4193 if ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) && 4194 Left.is(TT_LeadingJavaAnnotation) && 4195 Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) && 4196 (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations)) 4197 return true; 4198 4199 if (Right.is(TT_ProtoExtensionLSquare)) 4200 return true; 4201 4202 // In text proto instances if a submessage contains at least 2 entries and at 4203 // least one of them is a submessage, like A { ... B { ... } ... }, 4204 // put all of the entries of A on separate lines by forcing the selector of 4205 // the submessage B to be put on a newline. 4206 // 4207 // Example: these can stay on one line: 4208 // a { scalar_1: 1 scalar_2: 2 } 4209 // a { b { key: value } } 4210 // 4211 // and these entries need to be on a new line even if putting them all in one 4212 // line is under the column limit: 4213 // a { 4214 // scalar: 1 4215 // b { key: value } 4216 // } 4217 // 4218 // We enforce this by breaking before a submessage field that has previous 4219 // siblings, *and* breaking before a field that follows a submessage field. 4220 // 4221 // Be careful to exclude the case [proto.ext] { ... } since the `]` is 4222 // the TT_SelectorName there, but we don't want to break inside the brackets. 4223 // 4224 // Another edge case is @submessage { key: value }, which is a common 4225 // substitution placeholder. In this case we want to keep `@` and `submessage` 4226 // together. 4227 // 4228 // We ensure elsewhere that extensions are always on their own line. 4229 if ((Style.Language == FormatStyle::LK_Proto || 4230 Style.Language == FormatStyle::LK_TextProto) && 4231 Right.is(TT_SelectorName) && !Right.is(tok::r_square) && Right.Next) { 4232 // Keep `@submessage` together in: 4233 // @submessage { key: value } 4234 if (Left.is(tok::at)) 4235 return false; 4236 // Look for the scope opener after selector in cases like: 4237 // selector { ... 4238 // selector: { ... 4239 // selector: @base { ... 4240 FormatToken *LBrace = Right.Next; 4241 if (LBrace && LBrace->is(tok::colon)) { 4242 LBrace = LBrace->Next; 4243 if (LBrace && LBrace->is(tok::at)) { 4244 LBrace = LBrace->Next; 4245 if (LBrace) 4246 LBrace = LBrace->Next; 4247 } 4248 } 4249 if (LBrace && 4250 // The scope opener is one of {, [, <: 4251 // selector { ... } 4252 // selector [ ... ] 4253 // selector < ... > 4254 // 4255 // In case of selector { ... }, the l_brace is TT_DictLiteral. 4256 // In case of an empty selector {}, the l_brace is not TT_DictLiteral, 4257 // so we check for immediately following r_brace. 4258 ((LBrace->is(tok::l_brace) && 4259 (LBrace->is(TT_DictLiteral) || 4260 (LBrace->Next && LBrace->Next->is(tok::r_brace)))) || 4261 LBrace->is(TT_ArrayInitializerLSquare) || LBrace->is(tok::less))) { 4262 // If Left.ParameterCount is 0, then this submessage entry is not the 4263 // first in its parent submessage, and we want to break before this entry. 4264 // If Left.ParameterCount is greater than 0, then its parent submessage 4265 // might contain 1 or more entries and we want to break before this entry 4266 // if it contains at least 2 entries. We deal with this case later by 4267 // detecting and breaking before the next entry in the parent submessage. 4268 if (Left.ParameterCount == 0) 4269 return true; 4270 // However, if this submessage is the first entry in its parent 4271 // submessage, Left.ParameterCount might be 1 in some cases. 4272 // We deal with this case later by detecting an entry 4273 // following a closing paren of this submessage. 4274 } 4275 4276 // If this is an entry immediately following a submessage, it will be 4277 // preceded by a closing paren of that submessage, like in: 4278 // left---. .---right 4279 // v v 4280 // sub: { ... } key: value 4281 // If there was a comment between `}` an `key` above, then `key` would be 4282 // put on a new line anyways. 4283 if (Left.isOneOf(tok::r_brace, tok::greater, tok::r_square)) 4284 return true; 4285 } 4286 4287 // Deal with lambda arguments in C++ - we want consistent line breaks whether 4288 // they happen to be at arg0, arg1 or argN. The selection is a bit nuanced 4289 // as aggressive line breaks are placed when the lambda is not the last arg. 4290 if ((Style.Language == FormatStyle::LK_Cpp || 4291 Style.Language == FormatStyle::LK_ObjC) && 4292 Left.is(tok::l_paren) && Left.BlockParameterCount > 0 && 4293 !Right.isOneOf(tok::l_paren, TT_LambdaLSquare)) { 4294 // Multiple lambdas in the same function call force line breaks. 4295 if (Left.BlockParameterCount > 1) 4296 return true; 4297 4298 // A lambda followed by another arg forces a line break. 4299 if (!Left.Role) 4300 return false; 4301 auto Comma = Left.Role->lastComma(); 4302 if (!Comma) 4303 return false; 4304 auto Next = Comma->getNextNonComment(); 4305 if (!Next) 4306 return false; 4307 if (!Next->isOneOf(TT_LambdaLSquare, tok::l_brace, tok::caret)) 4308 return true; 4309 } 4310 4311 return false; 4312 } 4313 4314 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line, 4315 const FormatToken &Right) const { 4316 const FormatToken &Left = *Right.Previous; 4317 // Language-specific stuff. 4318 if (Style.isCSharp()) { 4319 if (Left.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon) || 4320 Right.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon)) 4321 return false; 4322 // Only break after commas for generic type constraints. 4323 if (Line.First->is(TT_CSharpGenericTypeConstraint)) 4324 return Left.is(TT_CSharpGenericTypeConstraintComma); 4325 // Keep nullable operators attached to their identifiers. 4326 if (Right.is(TT_CSharpNullable)) 4327 return false; 4328 } else if (Style.Language == FormatStyle::LK_Java) { 4329 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends, 4330 Keywords.kw_implements)) 4331 return false; 4332 if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends, 4333 Keywords.kw_implements)) 4334 return true; 4335 } else if (Style.isJavaScript()) { 4336 const FormatToken *NonComment = Right.getPreviousNonComment(); 4337 if (NonComment && 4338 NonComment->isOneOf( 4339 tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break, 4340 tok::kw_throw, Keywords.kw_interface, Keywords.kw_type, 4341 tok::kw_static, tok::kw_public, tok::kw_private, tok::kw_protected, 4342 Keywords.kw_readonly, Keywords.kw_override, Keywords.kw_abstract, 4343 Keywords.kw_get, Keywords.kw_set, Keywords.kw_async, 4344 Keywords.kw_await)) 4345 return false; // Otherwise automatic semicolon insertion would trigger. 4346 if (Right.NestingLevel == 0 && 4347 (Left.Tok.getIdentifierInfo() || 4348 Left.isOneOf(tok::r_square, tok::r_paren)) && 4349 Right.isOneOf(tok::l_square, tok::l_paren)) 4350 return false; // Otherwise automatic semicolon insertion would trigger. 4351 if (NonComment && NonComment->is(tok::identifier) && 4352 NonComment->TokenText == "asserts") 4353 return false; 4354 if (Left.is(TT_FatArrow) && Right.is(tok::l_brace)) 4355 return false; 4356 if (Left.is(TT_JsTypeColon)) 4357 return true; 4358 // Don't wrap between ":" and "!" of a strict prop init ("field!: type;"). 4359 if (Left.is(tok::exclaim) && Right.is(tok::colon)) 4360 return false; 4361 // Look for is type annotations like: 4362 // function f(): a is B { ... } 4363 // Do not break before is in these cases. 4364 if (Right.is(Keywords.kw_is)) { 4365 const FormatToken *Next = Right.getNextNonComment(); 4366 // If `is` is followed by a colon, it's likely that it's a dict key, so 4367 // ignore it for this check. 4368 // For example this is common in Polymer: 4369 // Polymer({ 4370 // is: 'name', 4371 // ... 4372 // }); 4373 if (!Next || !Next->is(tok::colon)) 4374 return false; 4375 } 4376 if (Left.is(Keywords.kw_in)) 4377 return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None; 4378 if (Right.is(Keywords.kw_in)) 4379 return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None; 4380 if (Right.is(Keywords.kw_as)) 4381 return false; // must not break before as in 'x as type' casts 4382 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_infer)) { 4383 // extends and infer can appear as keywords in conditional types: 4384 // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types 4385 // do not break before them, as the expressions are subject to ASI. 4386 return false; 4387 } 4388 if (Left.is(Keywords.kw_as)) 4389 return true; 4390 if (Left.is(TT_NonNullAssertion)) 4391 return true; 4392 if (Left.is(Keywords.kw_declare) && 4393 Right.isOneOf(Keywords.kw_module, tok::kw_namespace, 4394 Keywords.kw_function, tok::kw_class, tok::kw_enum, 4395 Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var, 4396 Keywords.kw_let, tok::kw_const)) 4397 // See grammar for 'declare' statements at: 4398 // https://github.com/Microsoft/TypeScript/blob/main/doc/spec-ARCHIVED.md#A.10 4399 return false; 4400 if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) && 4401 Right.isOneOf(tok::identifier, tok::string_literal)) 4402 return false; // must not break in "module foo { ...}" 4403 if (Right.is(TT_TemplateString) && Right.closesScope()) 4404 return false; 4405 // Don't split tagged template literal so there is a break between the tag 4406 // identifier and template string. 4407 if (Left.is(tok::identifier) && Right.is(TT_TemplateString)) 4408 return false; 4409 if (Left.is(TT_TemplateString) && Left.opensScope()) 4410 return true; 4411 } 4412 4413 if (Left.is(tok::at)) 4414 return false; 4415 if (Left.Tok.getObjCKeywordID() == tok::objc_interface) 4416 return false; 4417 if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation)) 4418 return !Right.is(tok::l_paren); 4419 if (Right.is(TT_PointerOrReference)) 4420 return Line.IsMultiVariableDeclStmt || 4421 (getTokenPointerOrReferenceAlignment(Right) == 4422 FormatStyle::PAS_Right && 4423 (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName))); 4424 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) || 4425 Right.is(tok::kw_operator)) 4426 return true; 4427 if (Left.is(TT_PointerOrReference)) 4428 return false; 4429 if (Right.isTrailingComment()) 4430 // We rely on MustBreakBefore being set correctly here as we should not 4431 // change the "binding" behavior of a comment. 4432 // The first comment in a braced lists is always interpreted as belonging to 4433 // the first list element. Otherwise, it should be placed outside of the 4434 // list. 4435 return Left.is(BK_BracedInit) || 4436 (Left.is(TT_CtorInitializerColon) && 4437 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon); 4438 if (Left.is(tok::question) && Right.is(tok::colon)) 4439 return false; 4440 if (Right.is(TT_ConditionalExpr) || Right.is(tok::question)) 4441 return Style.BreakBeforeTernaryOperators; 4442 if (Left.is(TT_ConditionalExpr) || Left.is(tok::question)) 4443 return !Style.BreakBeforeTernaryOperators; 4444 if (Left.is(TT_InheritanceColon)) 4445 return Style.BreakInheritanceList == FormatStyle::BILS_AfterColon; 4446 if (Right.is(TT_InheritanceColon)) 4447 return Style.BreakInheritanceList != FormatStyle::BILS_AfterColon; 4448 if (Right.is(TT_ObjCMethodExpr) && !Right.is(tok::r_square) && 4449 Left.isNot(TT_SelectorName)) 4450 return true; 4451 4452 if (Right.is(tok::colon) && 4453 !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon)) 4454 return false; 4455 if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) { 4456 if (Style.Language == FormatStyle::LK_Proto || 4457 Style.Language == FormatStyle::LK_TextProto) { 4458 if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral()) 4459 return false; 4460 // Prevent cases like: 4461 // 4462 // submessage: 4463 // { key: valueeeeeeeeeeee } 4464 // 4465 // when the snippet does not fit into one line. 4466 // Prefer: 4467 // 4468 // submessage: { 4469 // key: valueeeeeeeeeeee 4470 // } 4471 // 4472 // instead, even if it is longer by one line. 4473 // 4474 // Note that this allows allows the "{" to go over the column limit 4475 // when the column limit is just between ":" and "{", but that does 4476 // not happen too often and alternative formattings in this case are 4477 // not much better. 4478 // 4479 // The code covers the cases: 4480 // 4481 // submessage: { ... } 4482 // submessage: < ... > 4483 // repeated: [ ... ] 4484 if (((Right.is(tok::l_brace) || Right.is(tok::less)) && 4485 Right.is(TT_DictLiteral)) || 4486 Right.is(TT_ArrayInitializerLSquare)) 4487 return false; 4488 } 4489 return true; 4490 } 4491 if (Right.is(tok::r_square) && Right.MatchingParen && 4492 Right.MatchingParen->is(TT_ProtoExtensionLSquare)) 4493 return false; 4494 if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next && 4495 Right.Next->is(TT_ObjCMethodExpr))) 4496 return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls. 4497 if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty) 4498 return true; 4499 if (Right.is(tok::kw_concept)) 4500 return Style.BreakBeforeConceptDeclarations != FormatStyle::BBCDS_Never; 4501 if (Right.is(TT_RequiresClause)) 4502 return true; 4503 if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen)) 4504 return true; 4505 if (Left.ClosesRequiresClause) 4506 return true; 4507 if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen, 4508 TT_OverloadedOperator)) 4509 return false; 4510 if (Left.is(TT_RangeBasedForLoopColon)) 4511 return true; 4512 if (Right.is(TT_RangeBasedForLoopColon)) 4513 return false; 4514 if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener)) 4515 return true; 4516 if ((Left.is(tok::greater) && Right.is(tok::greater)) || 4517 (Left.is(tok::less) && Right.is(tok::less))) 4518 return false; 4519 if (Right.is(TT_BinaryOperator) && 4520 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None && 4521 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All || 4522 Right.getPrecedence() != prec::Assignment)) 4523 return true; 4524 if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) || 4525 Left.is(tok::kw_operator)) 4526 return false; 4527 if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) && 4528 Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0) 4529 return false; 4530 if (Left.is(tok::equal) && Right.is(tok::l_brace) && 4531 !Style.Cpp11BracedListStyle) 4532 return false; 4533 if (Left.is(tok::l_paren) && 4534 Left.isOneOf(TT_AttributeParen, TT_TypeDeclarationParen)) 4535 return false; 4536 if (Left.is(tok::l_paren) && Left.Previous && 4537 (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen))) 4538 return false; 4539 if (Right.is(TT_ImplicitStringLiteral)) 4540 return false; 4541 4542 if (Right.is(TT_TemplateCloser)) 4543 return false; 4544 if (Right.is(tok::r_square) && Right.MatchingParen && 4545 Right.MatchingParen->is(TT_LambdaLSquare)) 4546 return false; 4547 4548 // We only break before r_brace if there was a corresponding break before 4549 // the l_brace, which is tracked by BreakBeforeClosingBrace. 4550 if (Right.is(tok::r_brace)) 4551 return Right.MatchingParen && Right.MatchingParen->is(BK_Block); 4552 4553 // We only break before r_paren if we're in a block indented context. 4554 if (Right.is(tok::r_paren)) { 4555 if (Style.AlignAfterOpenBracket != FormatStyle::BAS_BlockIndent || 4556 !Right.MatchingParen) 4557 return false; 4558 const FormatToken *Previous = Right.MatchingParen->Previous; 4559 return !(Previous && (Previous->is(tok::kw_for) || Previous->isIf())); 4560 } 4561 4562 // Allow breaking after a trailing annotation, e.g. after a method 4563 // declaration. 4564 if (Left.is(TT_TrailingAnnotation)) 4565 return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren, 4566 tok::less, tok::coloncolon); 4567 4568 if (Right.is(tok::kw___attribute) || 4569 (Right.is(tok::l_square) && Right.is(TT_AttributeSquare))) 4570 return !Left.is(TT_AttributeSquare); 4571 4572 if (Left.is(tok::identifier) && Right.is(tok::string_literal)) 4573 return true; 4574 4575 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral)) 4576 return true; 4577 4578 if (Left.is(TT_CtorInitializerColon)) 4579 return Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon; 4580 if (Right.is(TT_CtorInitializerColon)) 4581 return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon; 4582 if (Left.is(TT_CtorInitializerComma) && 4583 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) 4584 return false; 4585 if (Right.is(TT_CtorInitializerComma) && 4586 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) 4587 return true; 4588 if (Left.is(TT_InheritanceComma) && 4589 Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma) 4590 return false; 4591 if (Right.is(TT_InheritanceComma) && 4592 Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma) 4593 return true; 4594 if (Left.is(TT_ArrayInitializerLSquare)) 4595 return true; 4596 if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const)) 4597 return true; 4598 if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) && 4599 !Left.isOneOf(tok::arrowstar, tok::lessless) && 4600 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All && 4601 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None || 4602 Left.getPrecedence() == prec::Assignment)) 4603 return true; 4604 if ((Left.is(TT_AttributeSquare) && Right.is(tok::l_square)) || 4605 (Left.is(tok::r_square) && Right.is(TT_AttributeSquare))) 4606 return false; 4607 4608 auto ShortLambdaOption = Style.AllowShortLambdasOnASingleLine; 4609 if (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT_LambdaLBrace)) { 4610 if (isAllmanLambdaBrace(Left)) 4611 return !isItAnEmptyLambdaAllowed(Left, ShortLambdaOption); 4612 if (isAllmanLambdaBrace(Right)) 4613 return !isItAnEmptyLambdaAllowed(Right, ShortLambdaOption); 4614 } 4615 4616 return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace, 4617 tok::kw_class, tok::kw_struct, tok::comment) || 4618 Right.isMemberAccess() || 4619 Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless, 4620 tok::colon, tok::l_square, tok::at) || 4621 (Left.is(tok::r_paren) && 4622 Right.isOneOf(tok::identifier, tok::kw_const)) || 4623 (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) || 4624 (Left.is(TT_TemplateOpener) && !Right.is(TT_TemplateCloser)); 4625 } 4626 4627 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) const { 4628 llvm::errs() << "AnnotatedTokens(L=" << Line.Level << "):\n"; 4629 const FormatToken *Tok = Line.First; 4630 while (Tok) { 4631 llvm::errs() << " M=" << Tok->MustBreakBefore 4632 << " C=" << Tok->CanBreakBefore 4633 << " T=" << getTokenTypeName(Tok->getType()) 4634 << " S=" << Tok->SpacesRequiredBefore 4635 << " F=" << Tok->Finalized << " B=" << Tok->BlockParameterCount 4636 << " BK=" << Tok->getBlockKind() << " P=" << Tok->SplitPenalty 4637 << " Name=" << Tok->Tok.getName() << " L=" << Tok->TotalLength 4638 << " PPK=" << Tok->getPackingKind() << " FakeLParens="; 4639 for (prec::Level LParen : Tok->FakeLParens) 4640 llvm::errs() << LParen << "/"; 4641 llvm::errs() << " FakeRParens=" << Tok->FakeRParens; 4642 llvm::errs() << " II=" << Tok->Tok.getIdentifierInfo(); 4643 llvm::errs() << " Text='" << Tok->TokenText << "'\n"; 4644 if (!Tok->Next) 4645 assert(Tok == Line.Last); 4646 Tok = Tok->Next; 4647 } 4648 llvm::errs() << "----\n"; 4649 } 4650 4651 FormatStyle::PointerAlignmentStyle 4652 TokenAnnotator::getTokenReferenceAlignment(const FormatToken &Reference) const { 4653 assert(Reference.isOneOf(tok::amp, tok::ampamp)); 4654 switch (Style.ReferenceAlignment) { 4655 case FormatStyle::RAS_Pointer: 4656 return Style.PointerAlignment; 4657 case FormatStyle::RAS_Left: 4658 return FormatStyle::PAS_Left; 4659 case FormatStyle::RAS_Right: 4660 return FormatStyle::PAS_Right; 4661 case FormatStyle::RAS_Middle: 4662 return FormatStyle::PAS_Middle; 4663 } 4664 assert(0); //"Unhandled value of ReferenceAlignment" 4665 return Style.PointerAlignment; 4666 } 4667 4668 FormatStyle::PointerAlignmentStyle 4669 TokenAnnotator::getTokenPointerOrReferenceAlignment( 4670 const FormatToken &PointerOrReference) const { 4671 if (PointerOrReference.isOneOf(tok::amp, tok::ampamp)) { 4672 switch (Style.ReferenceAlignment) { 4673 case FormatStyle::RAS_Pointer: 4674 return Style.PointerAlignment; 4675 case FormatStyle::RAS_Left: 4676 return FormatStyle::PAS_Left; 4677 case FormatStyle::RAS_Right: 4678 return FormatStyle::PAS_Right; 4679 case FormatStyle::RAS_Middle: 4680 return FormatStyle::PAS_Middle; 4681 } 4682 } 4683 assert(PointerOrReference.is(tok::star)); 4684 return Style.PointerAlignment; 4685 } 4686 4687 } // namespace format 4688 } // namespace clang 4689