1 //===--- UnwrappedLineParser.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 contains the implementation of the UnwrappedLineParser, 11 /// which turns a stream of tokens into UnwrappedLines. 12 /// 13 //===----------------------------------------------------------------------===// 14 15 #include "UnwrappedLineParser.h" 16 #include "FormatToken.h" 17 #include "FormatTokenSource.h" 18 #include "Macros.h" 19 #include "TokenAnnotator.h" 20 #include "clang/Basic/TokenKinds.h" 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/ADT/StringRef.h" 23 #include "llvm/Support/Debug.h" 24 #include "llvm/Support/raw_os_ostream.h" 25 #include "llvm/Support/raw_ostream.h" 26 27 #include <utility> 28 29 #define DEBUG_TYPE "format-parser" 30 31 namespace clang { 32 namespace format { 33 34 namespace { 35 36 void printLine(llvm::raw_ostream &OS, const UnwrappedLine &Line, 37 StringRef Prefix = "", bool PrintText = false) { 38 OS << Prefix << "Line(" << Line.Level << ", FSC=" << Line.FirstStartColumn 39 << ")" << (Line.InPPDirective ? " MACRO" : "") << ": "; 40 bool NewLine = false; 41 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(), 42 E = Line.Tokens.end(); 43 I != E; ++I) { 44 if (NewLine) { 45 OS << Prefix; 46 NewLine = false; 47 } 48 OS << I->Tok->Tok.getName() << "[" 49 << "T=" << (unsigned)I->Tok->getType() 50 << ", OC=" << I->Tok->OriginalColumn << ", \"" << I->Tok->TokenText 51 << "\"] "; 52 for (const auto *CI = I->Children.begin(), *CE = I->Children.end(); 53 CI != CE; ++CI) { 54 OS << "\n"; 55 printLine(OS, *CI, (Prefix + " ").str()); 56 NewLine = true; 57 } 58 } 59 if (!NewLine) 60 OS << "\n"; 61 } 62 63 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line) { 64 printLine(llvm::dbgs(), Line); 65 } 66 67 class ScopedDeclarationState { 68 public: 69 ScopedDeclarationState(UnwrappedLine &Line, llvm::BitVector &Stack, 70 bool MustBeDeclaration) 71 : Line(Line), Stack(Stack) { 72 Line.MustBeDeclaration = MustBeDeclaration; 73 Stack.push_back(MustBeDeclaration); 74 } 75 ~ScopedDeclarationState() { 76 Stack.pop_back(); 77 if (!Stack.empty()) 78 Line.MustBeDeclaration = Stack.back(); 79 else 80 Line.MustBeDeclaration = true; 81 } 82 83 private: 84 UnwrappedLine &Line; 85 llvm::BitVector &Stack; 86 }; 87 88 } // end anonymous namespace 89 90 std::ostream &operator<<(std::ostream &Stream, const UnwrappedLine &Line) { 91 llvm::raw_os_ostream OS(Stream); 92 printLine(OS, Line); 93 return Stream; 94 } 95 96 class ScopedLineState { 97 public: 98 ScopedLineState(UnwrappedLineParser &Parser, 99 bool SwitchToPreprocessorLines = false) 100 : Parser(Parser), OriginalLines(Parser.CurrentLines) { 101 if (SwitchToPreprocessorLines) 102 Parser.CurrentLines = &Parser.PreprocessorDirectives; 103 else if (!Parser.Line->Tokens.empty()) 104 Parser.CurrentLines = &Parser.Line->Tokens.back().Children; 105 PreBlockLine = std::move(Parser.Line); 106 Parser.Line = std::make_unique<UnwrappedLine>(); 107 Parser.Line->Level = PreBlockLine->Level; 108 Parser.Line->PPLevel = PreBlockLine->PPLevel; 109 Parser.Line->InPPDirective = PreBlockLine->InPPDirective; 110 Parser.Line->InMacroBody = PreBlockLine->InMacroBody; 111 Parser.Line->UnbracedBodyLevel = PreBlockLine->UnbracedBodyLevel; 112 } 113 114 ~ScopedLineState() { 115 if (!Parser.Line->Tokens.empty()) 116 Parser.addUnwrappedLine(); 117 assert(Parser.Line->Tokens.empty()); 118 Parser.Line = std::move(PreBlockLine); 119 if (Parser.CurrentLines == &Parser.PreprocessorDirectives) 120 Parser.AtEndOfPPLine = true; 121 Parser.CurrentLines = OriginalLines; 122 } 123 124 private: 125 UnwrappedLineParser &Parser; 126 127 std::unique_ptr<UnwrappedLine> PreBlockLine; 128 SmallVectorImpl<UnwrappedLine> *OriginalLines; 129 }; 130 131 class CompoundStatementIndenter { 132 public: 133 CompoundStatementIndenter(UnwrappedLineParser *Parser, 134 const FormatStyle &Style, unsigned &LineLevel) 135 : CompoundStatementIndenter(Parser, LineLevel, 136 Style.BraceWrapping.AfterControlStatement == 137 FormatStyle::BWACS_Always, 138 Style.BraceWrapping.IndentBraces) {} 139 CompoundStatementIndenter(UnwrappedLineParser *Parser, unsigned &LineLevel, 140 bool WrapBrace, bool IndentBrace) 141 : LineLevel(LineLevel), OldLineLevel(LineLevel) { 142 if (WrapBrace) 143 Parser->addUnwrappedLine(); 144 if (IndentBrace) 145 ++LineLevel; 146 } 147 ~CompoundStatementIndenter() { LineLevel = OldLineLevel; } 148 149 private: 150 unsigned &LineLevel; 151 unsigned OldLineLevel; 152 }; 153 154 UnwrappedLineParser::UnwrappedLineParser( 155 SourceManager &SourceMgr, const FormatStyle &Style, 156 const AdditionalKeywords &Keywords, unsigned FirstStartColumn, 157 ArrayRef<FormatToken *> Tokens, UnwrappedLineConsumer &Callback, 158 llvm::SpecificBumpPtrAllocator<FormatToken> &Allocator, 159 IdentifierTable &IdentTable) 160 : Line(new UnwrappedLine), AtEndOfPPLine(false), CurrentLines(&Lines), 161 Style(Style), IsCpp(Style.isCpp()), 162 LangOpts(getFormattingLangOpts(Style)), Keywords(Keywords), 163 CommentPragmasRegex(Style.CommentPragmas), Tokens(nullptr), 164 Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1), 165 IncludeGuard(Style.IndentPPDirectives == FormatStyle::PPDIS_None 166 ? IG_Rejected 167 : IG_Inited), 168 IncludeGuardToken(nullptr), FirstStartColumn(FirstStartColumn), 169 Macros(Style.Macros, SourceMgr, Style, Allocator, IdentTable) {} 170 171 void UnwrappedLineParser::reset() { 172 PPBranchLevel = -1; 173 IncludeGuard = Style.IndentPPDirectives == FormatStyle::PPDIS_None 174 ? IG_Rejected 175 : IG_Inited; 176 IncludeGuardToken = nullptr; 177 Line.reset(new UnwrappedLine); 178 CommentsBeforeNextToken.clear(); 179 FormatTok = nullptr; 180 AtEndOfPPLine = false; 181 IsDecltypeAutoFunction = false; 182 PreprocessorDirectives.clear(); 183 CurrentLines = &Lines; 184 DeclarationScopeStack.clear(); 185 NestedTooDeep.clear(); 186 NestedLambdas.clear(); 187 PPStack.clear(); 188 Line->FirstStartColumn = FirstStartColumn; 189 190 if (!Unexpanded.empty()) 191 for (FormatToken *Token : AllTokens) 192 Token->MacroCtx.reset(); 193 CurrentExpandedLines.clear(); 194 ExpandedLines.clear(); 195 Unexpanded.clear(); 196 InExpansion = false; 197 Reconstruct.reset(); 198 } 199 200 void UnwrappedLineParser::parse() { 201 IndexedTokenSource TokenSource(AllTokens); 202 Line->FirstStartColumn = FirstStartColumn; 203 do { 204 LLVM_DEBUG(llvm::dbgs() << "----\n"); 205 reset(); 206 Tokens = &TokenSource; 207 TokenSource.reset(); 208 209 readToken(); 210 parseFile(); 211 212 // If we found an include guard then all preprocessor directives (other than 213 // the guard) are over-indented by one. 214 if (IncludeGuard == IG_Found) { 215 for (auto &Line : Lines) 216 if (Line.InPPDirective && Line.Level > 0) 217 --Line.Level; 218 } 219 220 // Create line with eof token. 221 assert(eof()); 222 pushToken(FormatTok); 223 addUnwrappedLine(); 224 225 // In a first run, format everything with the lines containing macro calls 226 // replaced by the expansion. 227 if (!ExpandedLines.empty()) { 228 LLVM_DEBUG(llvm::dbgs() << "Expanded lines:\n"); 229 for (const auto &Line : Lines) { 230 if (!Line.Tokens.empty()) { 231 auto it = ExpandedLines.find(Line.Tokens.begin()->Tok); 232 if (it != ExpandedLines.end()) { 233 for (const auto &Expanded : it->second) { 234 LLVM_DEBUG(printDebugInfo(Expanded)); 235 Callback.consumeUnwrappedLine(Expanded); 236 } 237 continue; 238 } 239 } 240 LLVM_DEBUG(printDebugInfo(Line)); 241 Callback.consumeUnwrappedLine(Line); 242 } 243 Callback.finishRun(); 244 } 245 246 LLVM_DEBUG(llvm::dbgs() << "Unwrapped lines:\n"); 247 for (const UnwrappedLine &Line : Lines) { 248 LLVM_DEBUG(printDebugInfo(Line)); 249 Callback.consumeUnwrappedLine(Line); 250 } 251 Callback.finishRun(); 252 Lines.clear(); 253 while (!PPLevelBranchIndex.empty() && 254 PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) { 255 PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1); 256 PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1); 257 } 258 if (!PPLevelBranchIndex.empty()) { 259 ++PPLevelBranchIndex.back(); 260 assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size()); 261 assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back()); 262 } 263 } while (!PPLevelBranchIndex.empty()); 264 } 265 266 void UnwrappedLineParser::parseFile() { 267 // The top-level context in a file always has declarations, except for pre- 268 // processor directives and JavaScript files. 269 bool MustBeDeclaration = !Line->InPPDirective && !Style.isJavaScript(); 270 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack, 271 MustBeDeclaration); 272 if (Style.isTextProto() || (Style.isJson() && FormatTok->IsFirst)) 273 parseBracedList(); 274 else 275 parseLevel(); 276 // Make sure to format the remaining tokens. 277 // 278 // LK_TextProto is special since its top-level is parsed as the body of a 279 // braced list, which does not necessarily have natural line separators such 280 // as a semicolon. Comments after the last entry that have been determined to 281 // not belong to that line, as in: 282 // key: value 283 // // endfile comment 284 // do not have a chance to be put on a line of their own until this point. 285 // Here we add this newline before end-of-file comments. 286 if (Style.isTextProto() && !CommentsBeforeNextToken.empty()) 287 addUnwrappedLine(); 288 flushComments(true); 289 addUnwrappedLine(); 290 } 291 292 void UnwrappedLineParser::parseCSharpGenericTypeConstraint() { 293 do { 294 switch (FormatTok->Tok.getKind()) { 295 case tok::l_brace: 296 case tok::semi: 297 return; 298 default: 299 if (FormatTok->is(Keywords.kw_where)) { 300 addUnwrappedLine(); 301 nextToken(); 302 parseCSharpGenericTypeConstraint(); 303 break; 304 } 305 nextToken(); 306 break; 307 } 308 } while (!eof()); 309 } 310 311 void UnwrappedLineParser::parseCSharpAttribute() { 312 int UnpairedSquareBrackets = 1; 313 do { 314 switch (FormatTok->Tok.getKind()) { 315 case tok::r_square: 316 nextToken(); 317 --UnpairedSquareBrackets; 318 if (UnpairedSquareBrackets == 0) { 319 addUnwrappedLine(); 320 return; 321 } 322 break; 323 case tok::l_square: 324 ++UnpairedSquareBrackets; 325 nextToken(); 326 break; 327 default: 328 nextToken(); 329 break; 330 } 331 } while (!eof()); 332 } 333 334 bool UnwrappedLineParser::precededByCommentOrPPDirective() const { 335 if (!Lines.empty() && Lines.back().InPPDirective) 336 return true; 337 338 const FormatToken *Previous = Tokens->getPreviousToken(); 339 return Previous && Previous->is(tok::comment) && 340 (Previous->IsMultiline || Previous->NewlinesBefore > 0); 341 } 342 343 /// Parses a level, that is ???. 344 /// \param OpeningBrace Opening brace (\p nullptr if absent) of that level. 345 /// \param IfKind The \p if statement kind in the level. 346 /// \param IfLeftBrace The left brace of the \p if block in the level. 347 /// \returns true if a simple block of if/else/for/while, or false otherwise. 348 /// (A simple block has a single statement.) 349 bool UnwrappedLineParser::parseLevel(const FormatToken *OpeningBrace, 350 IfStmtKind *IfKind, 351 FormatToken **IfLeftBrace) { 352 const bool InRequiresExpression = 353 OpeningBrace && OpeningBrace->is(TT_RequiresExpressionLBrace); 354 const bool IsPrecededByCommentOrPPDirective = 355 !Style.RemoveBracesLLVM || precededByCommentOrPPDirective(); 356 FormatToken *IfLBrace = nullptr; 357 bool HasDoWhile = false; 358 bool HasLabel = false; 359 unsigned StatementCount = 0; 360 bool SwitchLabelEncountered = false; 361 362 do { 363 if (FormatTok->isAttribute()) { 364 nextToken(); 365 if (FormatTok->is(tok::l_paren)) 366 parseParens(); 367 continue; 368 } 369 tok::TokenKind Kind = FormatTok->Tok.getKind(); 370 if (FormatTok->is(TT_MacroBlockBegin)) 371 Kind = tok::l_brace; 372 else if (FormatTok->is(TT_MacroBlockEnd)) 373 Kind = tok::r_brace; 374 375 auto ParseDefault = [this, OpeningBrace, IfKind, &IfLBrace, &HasDoWhile, 376 &HasLabel, &StatementCount] { 377 parseStructuralElement(OpeningBrace, IfKind, &IfLBrace, 378 HasDoWhile ? nullptr : &HasDoWhile, 379 HasLabel ? nullptr : &HasLabel); 380 ++StatementCount; 381 assert(StatementCount > 0 && "StatementCount overflow!"); 382 }; 383 384 switch (Kind) { 385 case tok::comment: 386 nextToken(); 387 addUnwrappedLine(); 388 break; 389 case tok::l_brace: 390 if (InRequiresExpression) { 391 FormatTok->setFinalizedType(TT_CompoundRequirementLBrace); 392 } else if (FormatTok->Previous && 393 FormatTok->Previous->ClosesRequiresClause) { 394 // We need the 'default' case here to correctly parse a function 395 // l_brace. 396 ParseDefault(); 397 continue; 398 } 399 if (!InRequiresExpression && FormatTok->isNot(TT_MacroBlockBegin)) { 400 if (tryToParseBracedList()) 401 continue; 402 FormatTok->setFinalizedType(TT_BlockLBrace); 403 } 404 parseBlock(); 405 ++StatementCount; 406 assert(StatementCount > 0 && "StatementCount overflow!"); 407 addUnwrappedLine(); 408 break; 409 case tok::r_brace: 410 if (OpeningBrace) { 411 if (!Style.RemoveBracesLLVM || Line->InPPDirective || 412 !OpeningBrace->isOneOf(TT_ControlStatementLBrace, TT_ElseLBrace)) { 413 return false; 414 } 415 if (FormatTok->isNot(tok::r_brace) || StatementCount != 1 || HasLabel || 416 HasDoWhile || IsPrecededByCommentOrPPDirective || 417 precededByCommentOrPPDirective()) { 418 return false; 419 } 420 const FormatToken *Next = Tokens->peekNextToken(); 421 if (Next->is(tok::comment) && Next->NewlinesBefore == 0) 422 return false; 423 if (IfLeftBrace) 424 *IfLeftBrace = IfLBrace; 425 return true; 426 } 427 nextToken(); 428 addUnwrappedLine(); 429 break; 430 case tok::kw_default: { 431 unsigned StoredPosition = Tokens->getPosition(); 432 auto *Next = Tokens->getNextNonComment(); 433 FormatTok = Tokens->setPosition(StoredPosition); 434 if (!Next->isOneOf(tok::colon, tok::arrow)) { 435 // default not followed by `:` or `->` is not a case label; treat it 436 // like an identifier. 437 parseStructuralElement(); 438 break; 439 } 440 // Else, if it is 'default:', fall through to the case handling. 441 [[fallthrough]]; 442 } 443 case tok::kw_case: 444 if (Style.Language == FormatStyle::LK_Proto || Style.isVerilog() || 445 (Style.isJavaScript() && Line->MustBeDeclaration)) { 446 // Proto: there are no switch/case statements 447 // Verilog: Case labels don't have this word. We handle case 448 // labels including default in TokenAnnotator. 449 // JavaScript: A 'case: string' style field declaration. 450 ParseDefault(); 451 break; 452 } 453 if (!SwitchLabelEncountered && 454 (Style.IndentCaseLabels || 455 (OpeningBrace && OpeningBrace->is(TT_SwitchExpressionLBrace)) || 456 (Line->InPPDirective && Line->Level == 1))) { 457 ++Line->Level; 458 } 459 SwitchLabelEncountered = true; 460 parseStructuralElement(); 461 break; 462 case tok::l_square: 463 if (Style.isCSharp()) { 464 nextToken(); 465 parseCSharpAttribute(); 466 break; 467 } 468 if (handleCppAttributes()) 469 break; 470 [[fallthrough]]; 471 default: 472 ParseDefault(); 473 break; 474 } 475 } while (!eof()); 476 477 return false; 478 } 479 480 void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) { 481 // We'll parse forward through the tokens until we hit 482 // a closing brace or eof - note that getNextToken() will 483 // parse macros, so this will magically work inside macro 484 // definitions, too. 485 unsigned StoredPosition = Tokens->getPosition(); 486 FormatToken *Tok = FormatTok; 487 const FormatToken *PrevTok = Tok->Previous; 488 // Keep a stack of positions of lbrace tokens. We will 489 // update information about whether an lbrace starts a 490 // braced init list or a different block during the loop. 491 struct StackEntry { 492 FormatToken *Tok; 493 const FormatToken *PrevTok; 494 }; 495 SmallVector<StackEntry, 8> LBraceStack; 496 assert(Tok->is(tok::l_brace)); 497 498 do { 499 auto *NextTok = Tokens->getNextNonComment(); 500 501 if (!Line->InMacroBody && !Style.isTableGen()) { 502 // Skip PPDirective lines (except macro definitions) and comments. 503 while (NextTok->is(tok::hash)) { 504 NextTok = Tokens->getNextToken(); 505 if (NextTok->isOneOf(tok::pp_not_keyword, tok::pp_define)) 506 break; 507 do { 508 NextTok = Tokens->getNextToken(); 509 } while (!NextTok->HasUnescapedNewline && NextTok->isNot(tok::eof)); 510 511 while (NextTok->is(tok::comment)) 512 NextTok = Tokens->getNextToken(); 513 } 514 } 515 516 switch (Tok->Tok.getKind()) { 517 case tok::l_brace: 518 if (Style.isJavaScript() && PrevTok) { 519 if (PrevTok->isOneOf(tok::colon, tok::less)) { 520 // A ':' indicates this code is in a type, or a braced list 521 // following a label in an object literal ({a: {b: 1}}). 522 // A '<' could be an object used in a comparison, but that is nonsense 523 // code (can never return true), so more likely it is a generic type 524 // argument (`X<{a: string; b: number}>`). 525 // The code below could be confused by semicolons between the 526 // individual members in a type member list, which would normally 527 // trigger BK_Block. In both cases, this must be parsed as an inline 528 // braced init. 529 Tok->setBlockKind(BK_BracedInit); 530 } else if (PrevTok->is(tok::r_paren)) { 531 // `) { }` can only occur in function or method declarations in JS. 532 Tok->setBlockKind(BK_Block); 533 } 534 } else { 535 Tok->setBlockKind(BK_Unknown); 536 } 537 LBraceStack.push_back({Tok, PrevTok}); 538 break; 539 case tok::r_brace: 540 if (LBraceStack.empty()) 541 break; 542 if (auto *LBrace = LBraceStack.back().Tok; LBrace->is(BK_Unknown)) { 543 bool ProbablyBracedList = false; 544 if (Style.Language == FormatStyle::LK_Proto) { 545 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square); 546 } else if (LBrace->isNot(TT_EnumLBrace)) { 547 // Using OriginalColumn to distinguish between ObjC methods and 548 // binary operators is a bit hacky. 549 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) && 550 NextTok->OriginalColumn == 0; 551 552 // Try to detect a braced list. Note that regardless how we mark inner 553 // braces here, we will overwrite the BlockKind later if we parse a 554 // braced list (where all blocks inside are by default braced lists), 555 // or when we explicitly detect blocks (for example while parsing 556 // lambdas). 557 558 // If we already marked the opening brace as braced list, the closing 559 // must also be part of it. 560 ProbablyBracedList = LBrace->is(TT_BracedListLBrace); 561 562 ProbablyBracedList = ProbablyBracedList || 563 (Style.isJavaScript() && 564 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in, 565 Keywords.kw_as)); 566 ProbablyBracedList = 567 ProbablyBracedList || 568 (IsCpp && (PrevTok->Tok.isLiteral() || 569 NextTok->isOneOf(tok::l_paren, tok::arrow))); 570 571 // If there is a comma, semicolon or right paren after the closing 572 // brace, we assume this is a braced initializer list. 573 // FIXME: Some of these do not apply to JS, e.g. "} {" can never be a 574 // braced list in JS. 575 ProbablyBracedList = 576 ProbablyBracedList || 577 NextTok->isOneOf(tok::comma, tok::period, tok::colon, 578 tok::r_paren, tok::r_square, tok::ellipsis); 579 580 // Distinguish between braced list in a constructor initializer list 581 // followed by constructor body, or just adjacent blocks. 582 ProbablyBracedList = 583 ProbablyBracedList || 584 (NextTok->is(tok::l_brace) && LBraceStack.back().PrevTok && 585 LBraceStack.back().PrevTok->isOneOf(tok::identifier, 586 tok::greater)); 587 588 ProbablyBracedList = 589 ProbablyBracedList || 590 (NextTok->is(tok::identifier) && 591 !PrevTok->isOneOf(tok::semi, tok::r_brace, tok::l_brace)); 592 593 ProbablyBracedList = ProbablyBracedList || 594 (NextTok->is(tok::semi) && 595 (!ExpectClassBody || LBraceStack.size() != 1)); 596 597 ProbablyBracedList = 598 ProbablyBracedList || 599 (NextTok->isBinaryOperator() && !NextIsObjCMethod); 600 601 if (!Style.isCSharp() && NextTok->is(tok::l_square)) { 602 // We can have an array subscript after a braced init 603 // list, but C++11 attributes are expected after blocks. 604 NextTok = Tokens->getNextToken(); 605 ProbablyBracedList = NextTok->isNot(tok::l_square); 606 } 607 608 // Cpp macro definition body that is a nonempty braced list or block: 609 if (IsCpp && Line->InMacroBody && PrevTok != FormatTok && 610 !FormatTok->Previous && NextTok->is(tok::eof) && 611 // A statement can end with only `;` (simple statement), a block 612 // closing brace (compound statement), or `:` (label statement). 613 // If PrevTok is a block opening brace, Tok ends an empty block. 614 !PrevTok->isOneOf(tok::semi, BK_Block, tok::colon)) { 615 ProbablyBracedList = true; 616 } 617 } 618 const auto BlockKind = ProbablyBracedList ? BK_BracedInit : BK_Block; 619 Tok->setBlockKind(BlockKind); 620 LBrace->setBlockKind(BlockKind); 621 } 622 LBraceStack.pop_back(); 623 break; 624 case tok::identifier: 625 if (Tok->isNot(TT_StatementMacro)) 626 break; 627 [[fallthrough]]; 628 case tok::at: 629 case tok::semi: 630 case tok::kw_if: 631 case tok::kw_while: 632 case tok::kw_for: 633 case tok::kw_switch: 634 case tok::kw_try: 635 case tok::kw___try: 636 if (!LBraceStack.empty() && LBraceStack.back().Tok->is(BK_Unknown)) 637 LBraceStack.back().Tok->setBlockKind(BK_Block); 638 break; 639 default: 640 break; 641 } 642 643 PrevTok = Tok; 644 Tok = NextTok; 645 } while (Tok->isNot(tok::eof) && !LBraceStack.empty()); 646 647 // Assume other blocks for all unclosed opening braces. 648 for (const auto &Entry : LBraceStack) 649 if (Entry.Tok->is(BK_Unknown)) 650 Entry.Tok->setBlockKind(BK_Block); 651 652 FormatTok = Tokens->setPosition(StoredPosition); 653 } 654 655 // Sets the token type of the directly previous right brace. 656 void UnwrappedLineParser::setPreviousRBraceType(TokenType Type) { 657 if (auto Prev = FormatTok->getPreviousNonComment(); 658 Prev && Prev->is(tok::r_brace)) { 659 Prev->setFinalizedType(Type); 660 } 661 } 662 663 template <class T> 664 static inline void hash_combine(std::size_t &seed, const T &v) { 665 std::hash<T> hasher; 666 seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); 667 } 668 669 size_t UnwrappedLineParser::computePPHash() const { 670 size_t h = 0; 671 for (const auto &i : PPStack) { 672 hash_combine(h, size_t(i.Kind)); 673 hash_combine(h, i.Line); 674 } 675 return h; 676 } 677 678 // Checks whether \p ParsedLine might fit on a single line. If \p OpeningBrace 679 // is not null, subtracts its length (plus the preceding space) when computing 680 // the length of \p ParsedLine. We must clone the tokens of \p ParsedLine before 681 // running the token annotator on it so that we can restore them afterward. 682 bool UnwrappedLineParser::mightFitOnOneLine( 683 UnwrappedLine &ParsedLine, const FormatToken *OpeningBrace) const { 684 const auto ColumnLimit = Style.ColumnLimit; 685 if (ColumnLimit == 0) 686 return true; 687 688 auto &Tokens = ParsedLine.Tokens; 689 assert(!Tokens.empty()); 690 691 const auto *LastToken = Tokens.back().Tok; 692 assert(LastToken); 693 694 SmallVector<UnwrappedLineNode> SavedTokens(Tokens.size()); 695 696 int Index = 0; 697 for (const auto &Token : Tokens) { 698 assert(Token.Tok); 699 auto &SavedToken = SavedTokens[Index++]; 700 SavedToken.Tok = new FormatToken; 701 SavedToken.Tok->copyFrom(*Token.Tok); 702 SavedToken.Children = std::move(Token.Children); 703 } 704 705 AnnotatedLine Line(ParsedLine); 706 assert(Line.Last == LastToken); 707 708 TokenAnnotator Annotator(Style, Keywords); 709 Annotator.annotate(Line); 710 Annotator.calculateFormattingInformation(Line); 711 712 auto Length = LastToken->TotalLength; 713 if (OpeningBrace) { 714 assert(OpeningBrace != Tokens.front().Tok); 715 if (auto Prev = OpeningBrace->Previous; 716 Prev && Prev->TotalLength + ColumnLimit == OpeningBrace->TotalLength) { 717 Length -= ColumnLimit; 718 } 719 Length -= OpeningBrace->TokenText.size() + 1; 720 } 721 722 if (const auto *FirstToken = Line.First; FirstToken->is(tok::r_brace)) { 723 assert(!OpeningBrace || OpeningBrace->is(TT_ControlStatementLBrace)); 724 Length -= FirstToken->TokenText.size() + 1; 725 } 726 727 Index = 0; 728 for (auto &Token : Tokens) { 729 const auto &SavedToken = SavedTokens[Index++]; 730 Token.Tok->copyFrom(*SavedToken.Tok); 731 Token.Children = std::move(SavedToken.Children); 732 delete SavedToken.Tok; 733 } 734 735 // If these change PPLevel needs to be used for get correct indentation. 736 assert(!Line.InMacroBody); 737 assert(!Line.InPPDirective); 738 return Line.Level * Style.IndentWidth + Length <= ColumnLimit; 739 } 740 741 FormatToken *UnwrappedLineParser::parseBlock(bool MustBeDeclaration, 742 unsigned AddLevels, bool MunchSemi, 743 bool KeepBraces, 744 IfStmtKind *IfKind, 745 bool UnindentWhitesmithsBraces) { 746 auto HandleVerilogBlockLabel = [this]() { 747 // ":" name 748 if (Style.isVerilog() && FormatTok->is(tok::colon)) { 749 nextToken(); 750 if (Keywords.isVerilogIdentifier(*FormatTok)) 751 nextToken(); 752 } 753 }; 754 755 // Whether this is a Verilog-specific block that has a special header like a 756 // module. 757 const bool VerilogHierarchy = 758 Style.isVerilog() && Keywords.isVerilogHierarchy(*FormatTok); 759 assert((FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) || 760 (Style.isVerilog() && 761 (Keywords.isVerilogBegin(*FormatTok) || VerilogHierarchy))) && 762 "'{' or macro block token expected"); 763 FormatToken *Tok = FormatTok; 764 const bool FollowedByComment = Tokens->peekNextToken()->is(tok::comment); 765 auto Index = CurrentLines->size(); 766 const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin); 767 FormatTok->setBlockKind(BK_Block); 768 769 // For Whitesmiths mode, jump to the next level prior to skipping over the 770 // braces. 771 if (!VerilogHierarchy && AddLevels > 0 && 772 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) { 773 ++Line->Level; 774 } 775 776 size_t PPStartHash = computePPHash(); 777 778 const unsigned InitialLevel = Line->Level; 779 if (VerilogHierarchy) { 780 AddLevels += parseVerilogHierarchyHeader(); 781 } else { 782 nextToken(/*LevelDifference=*/AddLevels); 783 HandleVerilogBlockLabel(); 784 } 785 786 // Bail out if there are too many levels. Otherwise, the stack might overflow. 787 if (Line->Level > 300) 788 return nullptr; 789 790 if (MacroBlock && FormatTok->is(tok::l_paren)) 791 parseParens(); 792 793 size_t NbPreprocessorDirectives = 794 !parsingPPDirective() ? PreprocessorDirectives.size() : 0; 795 addUnwrappedLine(); 796 size_t OpeningLineIndex = 797 CurrentLines->empty() 798 ? (UnwrappedLine::kInvalidIndex) 799 : (CurrentLines->size() - 1 - NbPreprocessorDirectives); 800 801 // Whitesmiths is weird here. The brace needs to be indented for the namespace 802 // block, but the block itself may not be indented depending on the style 803 // settings. This allows the format to back up one level in those cases. 804 if (UnindentWhitesmithsBraces) 805 --Line->Level; 806 807 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack, 808 MustBeDeclaration); 809 if (AddLevels > 0u && Style.BreakBeforeBraces != FormatStyle::BS_Whitesmiths) 810 Line->Level += AddLevels; 811 812 FormatToken *IfLBrace = nullptr; 813 const bool SimpleBlock = parseLevel(Tok, IfKind, &IfLBrace); 814 815 if (eof()) 816 return IfLBrace; 817 818 if (MacroBlock ? FormatTok->isNot(TT_MacroBlockEnd) 819 : FormatTok->isNot(tok::r_brace)) { 820 Line->Level = InitialLevel; 821 FormatTok->setBlockKind(BK_Block); 822 return IfLBrace; 823 } 824 825 if (FormatTok->is(tok::r_brace)) { 826 FormatTok->setBlockKind(BK_Block); 827 if (Tok->is(TT_NamespaceLBrace)) 828 FormatTok->setFinalizedType(TT_NamespaceRBrace); 829 } 830 831 const bool IsFunctionRBrace = 832 FormatTok->is(tok::r_brace) && Tok->is(TT_FunctionLBrace); 833 834 auto RemoveBraces = [=]() mutable { 835 if (!SimpleBlock) 836 return false; 837 assert(Tok->isOneOf(TT_ControlStatementLBrace, TT_ElseLBrace)); 838 assert(FormatTok->is(tok::r_brace)); 839 const bool WrappedOpeningBrace = !Tok->Previous; 840 if (WrappedOpeningBrace && FollowedByComment) 841 return false; 842 const bool HasRequiredIfBraces = IfLBrace && !IfLBrace->Optional; 843 if (KeepBraces && !HasRequiredIfBraces) 844 return false; 845 if (Tok->isNot(TT_ElseLBrace) || !HasRequiredIfBraces) { 846 const FormatToken *Previous = Tokens->getPreviousToken(); 847 assert(Previous); 848 if (Previous->is(tok::r_brace) && !Previous->Optional) 849 return false; 850 } 851 assert(!CurrentLines->empty()); 852 auto &LastLine = CurrentLines->back(); 853 if (LastLine.Level == InitialLevel + 1 && !mightFitOnOneLine(LastLine)) 854 return false; 855 if (Tok->is(TT_ElseLBrace)) 856 return true; 857 if (WrappedOpeningBrace) { 858 assert(Index > 0); 859 --Index; // The line above the wrapped l_brace. 860 Tok = nullptr; 861 } 862 return mightFitOnOneLine((*CurrentLines)[Index], Tok); 863 }; 864 if (RemoveBraces()) { 865 Tok->MatchingParen = FormatTok; 866 FormatTok->MatchingParen = Tok; 867 } 868 869 size_t PPEndHash = computePPHash(); 870 871 // Munch the closing brace. 872 nextToken(/*LevelDifference=*/-AddLevels); 873 874 // When this is a function block and there is an unnecessary semicolon 875 // afterwards then mark it as optional (so the RemoveSemi pass can get rid of 876 // it later). 877 if (Style.RemoveSemicolon && IsFunctionRBrace) { 878 while (FormatTok->is(tok::semi)) { 879 FormatTok->Optional = true; 880 nextToken(); 881 } 882 } 883 884 HandleVerilogBlockLabel(); 885 886 if (MacroBlock && FormatTok->is(tok::l_paren)) 887 parseParens(); 888 889 Line->Level = InitialLevel; 890 891 if (FormatTok->is(tok::kw_noexcept)) { 892 // A noexcept in a requires expression. 893 nextToken(); 894 } 895 896 if (FormatTok->is(tok::arrow)) { 897 // Following the } or noexcept we can find a trailing return type arrow 898 // as part of an implicit conversion constraint. 899 nextToken(); 900 parseStructuralElement(); 901 } 902 903 if (MunchSemi && FormatTok->is(tok::semi)) 904 nextToken(); 905 906 if (PPStartHash == PPEndHash) { 907 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex; 908 if (OpeningLineIndex != UnwrappedLine::kInvalidIndex) { 909 // Update the opening line to add the forward reference as well 910 (*CurrentLines)[OpeningLineIndex].MatchingClosingBlockLineIndex = 911 CurrentLines->size() - 1; 912 } 913 } 914 915 return IfLBrace; 916 } 917 918 static bool isGoogScope(const UnwrappedLine &Line) { 919 // FIXME: Closure-library specific stuff should not be hard-coded but be 920 // configurable. 921 if (Line.Tokens.size() < 4) 922 return false; 923 auto I = Line.Tokens.begin(); 924 if (I->Tok->TokenText != "goog") 925 return false; 926 ++I; 927 if (I->Tok->isNot(tok::period)) 928 return false; 929 ++I; 930 if (I->Tok->TokenText != "scope") 931 return false; 932 ++I; 933 return I->Tok->is(tok::l_paren); 934 } 935 936 static bool isIIFE(const UnwrappedLine &Line, 937 const AdditionalKeywords &Keywords) { 938 // Look for the start of an immediately invoked anonymous function. 939 // https://en.wikipedia.org/wiki/Immediately-invoked_function_expression 940 // This is commonly done in JavaScript to create a new, anonymous scope. 941 // Example: (function() { ... })() 942 if (Line.Tokens.size() < 3) 943 return false; 944 auto I = Line.Tokens.begin(); 945 if (I->Tok->isNot(tok::l_paren)) 946 return false; 947 ++I; 948 if (I->Tok->isNot(Keywords.kw_function)) 949 return false; 950 ++I; 951 return I->Tok->is(tok::l_paren); 952 } 953 954 static bool ShouldBreakBeforeBrace(const FormatStyle &Style, 955 const FormatToken &InitialToken) { 956 tok::TokenKind Kind = InitialToken.Tok.getKind(); 957 if (InitialToken.is(TT_NamespaceMacro)) 958 Kind = tok::kw_namespace; 959 960 switch (Kind) { 961 case tok::kw_namespace: 962 return Style.BraceWrapping.AfterNamespace; 963 case tok::kw_class: 964 return Style.BraceWrapping.AfterClass; 965 case tok::kw_union: 966 return Style.BraceWrapping.AfterUnion; 967 case tok::kw_struct: 968 return Style.BraceWrapping.AfterStruct; 969 case tok::kw_enum: 970 return Style.BraceWrapping.AfterEnum; 971 default: 972 return false; 973 } 974 } 975 976 void UnwrappedLineParser::parseChildBlock() { 977 assert(FormatTok->is(tok::l_brace)); 978 FormatTok->setBlockKind(BK_Block); 979 const FormatToken *OpeningBrace = FormatTok; 980 nextToken(); 981 { 982 bool SkipIndent = (Style.isJavaScript() && 983 (isGoogScope(*Line) || isIIFE(*Line, Keywords))); 984 ScopedLineState LineState(*this); 985 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack, 986 /*MustBeDeclaration=*/false); 987 Line->Level += SkipIndent ? 0 : 1; 988 parseLevel(OpeningBrace); 989 flushComments(isOnNewLine(*FormatTok)); 990 Line->Level -= SkipIndent ? 0 : 1; 991 } 992 nextToken(); 993 } 994 995 void UnwrappedLineParser::parsePPDirective() { 996 assert(FormatTok->is(tok::hash) && "'#' expected"); 997 ScopedMacroState MacroState(*Line, Tokens, FormatTok); 998 999 nextToken(); 1000 1001 if (!FormatTok->Tok.getIdentifierInfo()) { 1002 parsePPUnknown(); 1003 return; 1004 } 1005 1006 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) { 1007 case tok::pp_define: 1008 parsePPDefine(); 1009 return; 1010 case tok::pp_if: 1011 parsePPIf(/*IfDef=*/false); 1012 break; 1013 case tok::pp_ifdef: 1014 case tok::pp_ifndef: 1015 parsePPIf(/*IfDef=*/true); 1016 break; 1017 case tok::pp_else: 1018 case tok::pp_elifdef: 1019 case tok::pp_elifndef: 1020 case tok::pp_elif: 1021 parsePPElse(); 1022 break; 1023 case tok::pp_endif: 1024 parsePPEndIf(); 1025 break; 1026 case tok::pp_pragma: 1027 parsePPPragma(); 1028 break; 1029 case tok::pp_error: 1030 case tok::pp_warning: 1031 nextToken(); 1032 if (!eof() && Style.isCpp()) 1033 FormatTok->setFinalizedType(TT_AfterPPDirective); 1034 [[fallthrough]]; 1035 default: 1036 parsePPUnknown(); 1037 break; 1038 } 1039 } 1040 1041 void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) { 1042 size_t Line = CurrentLines->size(); 1043 if (CurrentLines == &PreprocessorDirectives) 1044 Line += Lines.size(); 1045 1046 if (Unreachable || 1047 (!PPStack.empty() && PPStack.back().Kind == PP_Unreachable)) { 1048 PPStack.push_back({PP_Unreachable, Line}); 1049 } else { 1050 PPStack.push_back({PP_Conditional, Line}); 1051 } 1052 } 1053 1054 void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) { 1055 ++PPBranchLevel; 1056 assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size()); 1057 if (PPBranchLevel == (int)PPLevelBranchIndex.size()) { 1058 PPLevelBranchIndex.push_back(0); 1059 PPLevelBranchCount.push_back(0); 1060 } 1061 PPChainBranchIndex.push(Unreachable ? -1 : 0); 1062 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0; 1063 conditionalCompilationCondition(Unreachable || Skip); 1064 } 1065 1066 void UnwrappedLineParser::conditionalCompilationAlternative() { 1067 if (!PPStack.empty()) 1068 PPStack.pop_back(); 1069 assert(PPBranchLevel < (int)PPLevelBranchIndex.size()); 1070 if (!PPChainBranchIndex.empty()) 1071 ++PPChainBranchIndex.top(); 1072 conditionalCompilationCondition( 1073 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() && 1074 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top()); 1075 } 1076 1077 void UnwrappedLineParser::conditionalCompilationEnd() { 1078 assert(PPBranchLevel < (int)PPLevelBranchIndex.size()); 1079 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) { 1080 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) 1081 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1; 1082 } 1083 // Guard against #endif's without #if. 1084 if (PPBranchLevel > -1) 1085 --PPBranchLevel; 1086 if (!PPChainBranchIndex.empty()) 1087 PPChainBranchIndex.pop(); 1088 if (!PPStack.empty()) 1089 PPStack.pop_back(); 1090 } 1091 1092 void UnwrappedLineParser::parsePPIf(bool IfDef) { 1093 bool IfNDef = FormatTok->is(tok::pp_ifndef); 1094 nextToken(); 1095 bool Unreachable = false; 1096 if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText == "0")) 1097 Unreachable = true; 1098 if (IfDef && !IfNDef && FormatTok->TokenText == "SWIG") 1099 Unreachable = true; 1100 conditionalCompilationStart(Unreachable); 1101 FormatToken *IfCondition = FormatTok; 1102 // If there's a #ifndef on the first line, and the only lines before it are 1103 // comments, it could be an include guard. 1104 bool MaybeIncludeGuard = IfNDef; 1105 if (IncludeGuard == IG_Inited && MaybeIncludeGuard) { 1106 for (auto &Line : Lines) { 1107 if (Line.Tokens.front().Tok->isNot(tok::comment)) { 1108 MaybeIncludeGuard = false; 1109 IncludeGuard = IG_Rejected; 1110 break; 1111 } 1112 } 1113 } 1114 --PPBranchLevel; 1115 parsePPUnknown(); 1116 ++PPBranchLevel; 1117 if (IncludeGuard == IG_Inited && MaybeIncludeGuard) { 1118 IncludeGuard = IG_IfNdefed; 1119 IncludeGuardToken = IfCondition; 1120 } 1121 } 1122 1123 void UnwrappedLineParser::parsePPElse() { 1124 // If a potential include guard has an #else, it's not an include guard. 1125 if (IncludeGuard == IG_Defined && PPBranchLevel == 0) 1126 IncludeGuard = IG_Rejected; 1127 // Don't crash when there is an #else without an #if. 1128 assert(PPBranchLevel >= -1); 1129 if (PPBranchLevel == -1) 1130 conditionalCompilationStart(/*Unreachable=*/true); 1131 conditionalCompilationAlternative(); 1132 --PPBranchLevel; 1133 parsePPUnknown(); 1134 ++PPBranchLevel; 1135 } 1136 1137 void UnwrappedLineParser::parsePPEndIf() { 1138 conditionalCompilationEnd(); 1139 parsePPUnknown(); 1140 // If the #endif of a potential include guard is the last thing in the file, 1141 // then we found an include guard. 1142 if (IncludeGuard == IG_Defined && PPBranchLevel == -1 && Tokens->isEOF() && 1143 Style.IndentPPDirectives != FormatStyle::PPDIS_None) { 1144 IncludeGuard = IG_Found; 1145 } 1146 } 1147 1148 void UnwrappedLineParser::parsePPDefine() { 1149 nextToken(); 1150 1151 if (!FormatTok->Tok.getIdentifierInfo()) { 1152 IncludeGuard = IG_Rejected; 1153 IncludeGuardToken = nullptr; 1154 parsePPUnknown(); 1155 return; 1156 } 1157 1158 bool MaybeIncludeGuard = false; 1159 if (IncludeGuard == IG_IfNdefed && 1160 IncludeGuardToken->TokenText == FormatTok->TokenText) { 1161 IncludeGuard = IG_Defined; 1162 IncludeGuardToken = nullptr; 1163 for (auto &Line : Lines) { 1164 if (!Line.Tokens.front().Tok->isOneOf(tok::comment, tok::hash)) { 1165 IncludeGuard = IG_Rejected; 1166 break; 1167 } 1168 } 1169 MaybeIncludeGuard = IncludeGuard == IG_Defined; 1170 } 1171 1172 // In the context of a define, even keywords should be treated as normal 1173 // identifiers. Setting the kind to identifier is not enough, because we need 1174 // to treat additional keywords like __except as well, which are already 1175 // identifiers. Setting the identifier info to null interferes with include 1176 // guard processing above, and changes preprocessing nesting. 1177 FormatTok->Tok.setKind(tok::identifier); 1178 FormatTok->Tok.setIdentifierInfo(Keywords.kw_internal_ident_after_define); 1179 nextToken(); 1180 1181 // IncludeGuard can't have a non-empty macro definition. 1182 if (MaybeIncludeGuard && !eof()) 1183 IncludeGuard = IG_Rejected; 1184 1185 if (FormatTok->Tok.getKind() == tok::l_paren && 1186 !FormatTok->hasWhitespaceBefore()) { 1187 parseParens(); 1188 } 1189 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None) 1190 Line->Level += PPBranchLevel + 1; 1191 addUnwrappedLine(); 1192 ++Line->Level; 1193 1194 Line->PPLevel = PPBranchLevel + (IncludeGuard == IG_Defined ? 0 : 1); 1195 assert((int)Line->PPLevel >= 0); 1196 Line->InMacroBody = true; 1197 1198 if (Style.SkipMacroDefinitionBody) { 1199 while (!eof()) { 1200 FormatTok->Finalized = true; 1201 FormatTok = Tokens->getNextToken(); 1202 } 1203 addUnwrappedLine(); 1204 return; 1205 } 1206 1207 // Errors during a preprocessor directive can only affect the layout of the 1208 // preprocessor directive, and thus we ignore them. An alternative approach 1209 // would be to use the same approach we use on the file level (no 1210 // re-indentation if there was a structural error) within the macro 1211 // definition. 1212 parseFile(); 1213 } 1214 1215 void UnwrappedLineParser::parsePPPragma() { 1216 Line->InPragmaDirective = true; 1217 parsePPUnknown(); 1218 } 1219 1220 void UnwrappedLineParser::parsePPUnknown() { 1221 while (!eof()) 1222 nextToken(); 1223 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None) 1224 Line->Level += PPBranchLevel + 1; 1225 addUnwrappedLine(); 1226 } 1227 1228 // Here we exclude certain tokens that are not usually the first token in an 1229 // unwrapped line. This is used in attempt to distinguish macro calls without 1230 // trailing semicolons from other constructs split to several lines. 1231 static bool tokenCanStartNewLine(const FormatToken &Tok) { 1232 // Semicolon can be a null-statement, l_square can be a start of a macro or 1233 // a C++11 attribute, but this doesn't seem to be common. 1234 return !Tok.isOneOf(tok::semi, tok::l_brace, 1235 // Tokens that can only be used as binary operators and a 1236 // part of overloaded operator names. 1237 tok::period, tok::periodstar, tok::arrow, tok::arrowstar, 1238 tok::less, tok::greater, tok::slash, tok::percent, 1239 tok::lessless, tok::greatergreater, tok::equal, 1240 tok::plusequal, tok::minusequal, tok::starequal, 1241 tok::slashequal, tok::percentequal, tok::ampequal, 1242 tok::pipeequal, tok::caretequal, tok::greatergreaterequal, 1243 tok::lesslessequal, 1244 // Colon is used in labels, base class lists, initializer 1245 // lists, range-based for loops, ternary operator, but 1246 // should never be the first token in an unwrapped line. 1247 tok::colon, 1248 // 'noexcept' is a trailing annotation. 1249 tok::kw_noexcept); 1250 } 1251 1252 static bool mustBeJSIdent(const AdditionalKeywords &Keywords, 1253 const FormatToken *FormatTok) { 1254 // FIXME: This returns true for C/C++ keywords like 'struct'. 1255 return FormatTok->is(tok::identifier) && 1256 (!FormatTok->Tok.getIdentifierInfo() || 1257 !FormatTok->isOneOf( 1258 Keywords.kw_in, Keywords.kw_of, Keywords.kw_as, Keywords.kw_async, 1259 Keywords.kw_await, Keywords.kw_yield, Keywords.kw_finally, 1260 Keywords.kw_function, Keywords.kw_import, Keywords.kw_is, 1261 Keywords.kw_let, Keywords.kw_var, tok::kw_const, 1262 Keywords.kw_abstract, Keywords.kw_extends, Keywords.kw_implements, 1263 Keywords.kw_instanceof, Keywords.kw_interface, 1264 Keywords.kw_override, Keywords.kw_throws, Keywords.kw_from)); 1265 } 1266 1267 static bool mustBeJSIdentOrValue(const AdditionalKeywords &Keywords, 1268 const FormatToken *FormatTok) { 1269 return FormatTok->Tok.isLiteral() || 1270 FormatTok->isOneOf(tok::kw_true, tok::kw_false) || 1271 mustBeJSIdent(Keywords, FormatTok); 1272 } 1273 1274 // isJSDeclOrStmt returns true if |FormatTok| starts a declaration or statement 1275 // when encountered after a value (see mustBeJSIdentOrValue). 1276 static bool isJSDeclOrStmt(const AdditionalKeywords &Keywords, 1277 const FormatToken *FormatTok) { 1278 return FormatTok->isOneOf( 1279 tok::kw_return, Keywords.kw_yield, 1280 // conditionals 1281 tok::kw_if, tok::kw_else, 1282 // loops 1283 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break, 1284 // switch/case 1285 tok::kw_switch, tok::kw_case, 1286 // exceptions 1287 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.kw_finally, 1288 // declaration 1289 tok::kw_const, tok::kw_class, Keywords.kw_var, Keywords.kw_let, 1290 Keywords.kw_async, Keywords.kw_function, 1291 // import/export 1292 Keywords.kw_import, tok::kw_export); 1293 } 1294 1295 // Checks whether a token is a type in K&R C (aka C78). 1296 static bool isC78Type(const FormatToken &Tok) { 1297 return Tok.isOneOf(tok::kw_char, tok::kw_short, tok::kw_int, tok::kw_long, 1298 tok::kw_unsigned, tok::kw_float, tok::kw_double, 1299 tok::identifier); 1300 } 1301 1302 // This function checks whether a token starts the first parameter declaration 1303 // in a K&R C (aka C78) function definition, e.g.: 1304 // int f(a, b) 1305 // short a, b; 1306 // { 1307 // return a + b; 1308 // } 1309 static bool isC78ParameterDecl(const FormatToken *Tok, const FormatToken *Next, 1310 const FormatToken *FuncName) { 1311 assert(Tok); 1312 assert(Next); 1313 assert(FuncName); 1314 1315 if (FuncName->isNot(tok::identifier)) 1316 return false; 1317 1318 const FormatToken *Prev = FuncName->Previous; 1319 if (!Prev || (Prev->isNot(tok::star) && !isC78Type(*Prev))) 1320 return false; 1321 1322 if (!isC78Type(*Tok) && 1323 !Tok->isOneOf(tok::kw_register, tok::kw_struct, tok::kw_union)) { 1324 return false; 1325 } 1326 1327 if (Next->isNot(tok::star) && !Next->Tok.getIdentifierInfo()) 1328 return false; 1329 1330 Tok = Tok->Previous; 1331 if (!Tok || Tok->isNot(tok::r_paren)) 1332 return false; 1333 1334 Tok = Tok->Previous; 1335 if (!Tok || Tok->isNot(tok::identifier)) 1336 return false; 1337 1338 return Tok->Previous && Tok->Previous->isOneOf(tok::l_paren, tok::comma); 1339 } 1340 1341 bool UnwrappedLineParser::parseModuleImport() { 1342 assert(FormatTok->is(Keywords.kw_import) && "'import' expected"); 1343 1344 if (auto Token = Tokens->peekNextToken(/*SkipComment=*/true); 1345 !Token->Tok.getIdentifierInfo() && 1346 !Token->isOneOf(tok::colon, tok::less, tok::string_literal)) { 1347 return false; 1348 } 1349 1350 nextToken(); 1351 while (!eof()) { 1352 if (FormatTok->is(tok::colon)) { 1353 FormatTok->setFinalizedType(TT_ModulePartitionColon); 1354 } 1355 // Handle import <foo/bar.h> as we would an include statement. 1356 else if (FormatTok->is(tok::less)) { 1357 nextToken(); 1358 while (!FormatTok->isOneOf(tok::semi, tok::greater) && !eof()) { 1359 // Mark tokens up to the trailing line comments as implicit string 1360 // literals. 1361 if (FormatTok->isNot(tok::comment) && 1362 !FormatTok->TokenText.starts_with("//")) { 1363 FormatTok->setFinalizedType(TT_ImplicitStringLiteral); 1364 } 1365 nextToken(); 1366 } 1367 } 1368 if (FormatTok->is(tok::semi)) { 1369 nextToken(); 1370 break; 1371 } 1372 nextToken(); 1373 } 1374 1375 addUnwrappedLine(); 1376 return true; 1377 } 1378 1379 // readTokenWithJavaScriptASI reads the next token and terminates the current 1380 // line if JavaScript Automatic Semicolon Insertion must 1381 // happen between the current token and the next token. 1382 // 1383 // This method is conservative - it cannot cover all edge cases of JavaScript, 1384 // but only aims to correctly handle certain well known cases. It *must not* 1385 // return true in speculative cases. 1386 void UnwrappedLineParser::readTokenWithJavaScriptASI() { 1387 FormatToken *Previous = FormatTok; 1388 readToken(); 1389 FormatToken *Next = FormatTok; 1390 1391 bool IsOnSameLine = 1392 CommentsBeforeNextToken.empty() 1393 ? Next->NewlinesBefore == 0 1394 : CommentsBeforeNextToken.front()->NewlinesBefore == 0; 1395 if (IsOnSameLine) 1396 return; 1397 1398 bool PreviousMustBeValue = mustBeJSIdentOrValue(Keywords, Previous); 1399 bool PreviousStartsTemplateExpr = 1400 Previous->is(TT_TemplateString) && Previous->TokenText.ends_with("${"); 1401 if (PreviousMustBeValue || Previous->is(tok::r_paren)) { 1402 // If the line contains an '@' sign, the previous token might be an 1403 // annotation, which can precede another identifier/value. 1404 bool HasAt = llvm::any_of(Line->Tokens, [](UnwrappedLineNode &LineNode) { 1405 return LineNode.Tok->is(tok::at); 1406 }); 1407 if (HasAt) 1408 return; 1409 } 1410 if (Next->is(tok::exclaim) && PreviousMustBeValue) 1411 return addUnwrappedLine(); 1412 bool NextMustBeValue = mustBeJSIdentOrValue(Keywords, Next); 1413 bool NextEndsTemplateExpr = 1414 Next->is(TT_TemplateString) && Next->TokenText.starts_with("}"); 1415 if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr && 1416 (PreviousMustBeValue || 1417 Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus, 1418 tok::minusminus))) { 1419 return addUnwrappedLine(); 1420 } 1421 if ((PreviousMustBeValue || Previous->is(tok::r_paren)) && 1422 isJSDeclOrStmt(Keywords, Next)) { 1423 return addUnwrappedLine(); 1424 } 1425 } 1426 1427 void UnwrappedLineParser::parseStructuralElement( 1428 const FormatToken *OpeningBrace, IfStmtKind *IfKind, 1429 FormatToken **IfLeftBrace, bool *HasDoWhile, bool *HasLabel) { 1430 if (Style.isTableGen() && FormatTok->is(tok::pp_include)) { 1431 nextToken(); 1432 if (FormatTok->is(tok::string_literal)) 1433 nextToken(); 1434 addUnwrappedLine(); 1435 return; 1436 } 1437 1438 if (IsCpp) { 1439 while (FormatTok->is(tok::l_square) && handleCppAttributes()) { 1440 } 1441 } else if (Style.isVerilog()) { 1442 if (Keywords.isVerilogStructuredProcedure(*FormatTok)) { 1443 parseForOrWhileLoop(/*HasParens=*/false); 1444 return; 1445 } 1446 if (FormatTok->isOneOf(Keywords.kw_foreach, Keywords.kw_repeat)) { 1447 parseForOrWhileLoop(); 1448 return; 1449 } 1450 if (FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert, 1451 Keywords.kw_assume, Keywords.kw_cover)) { 1452 parseIfThenElse(IfKind, /*KeepBraces=*/false, /*IsVerilogAssert=*/true); 1453 return; 1454 } 1455 1456 // Skip things that can exist before keywords like 'if' and 'case'. 1457 while (true) { 1458 if (FormatTok->isOneOf(Keywords.kw_priority, Keywords.kw_unique, 1459 Keywords.kw_unique0)) { 1460 nextToken(); 1461 } else if (FormatTok->is(tok::l_paren) && 1462 Tokens->peekNextToken()->is(tok::star)) { 1463 parseParens(); 1464 } else { 1465 break; 1466 } 1467 } 1468 } 1469 1470 // Tokens that only make sense at the beginning of a line. 1471 if (FormatTok->isAccessSpecifierKeyword()) { 1472 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp()) 1473 nextToken(); 1474 else 1475 parseAccessSpecifier(); 1476 return; 1477 } 1478 switch (FormatTok->Tok.getKind()) { 1479 case tok::kw_asm: 1480 nextToken(); 1481 if (FormatTok->is(tok::l_brace)) { 1482 FormatTok->setFinalizedType(TT_InlineASMBrace); 1483 nextToken(); 1484 while (FormatTok && !eof()) { 1485 if (FormatTok->is(tok::r_brace)) { 1486 FormatTok->setFinalizedType(TT_InlineASMBrace); 1487 nextToken(); 1488 addUnwrappedLine(); 1489 break; 1490 } 1491 FormatTok->Finalized = true; 1492 nextToken(); 1493 } 1494 } 1495 break; 1496 case tok::kw_namespace: 1497 parseNamespace(); 1498 return; 1499 case tok::kw_if: { 1500 if (Style.isJavaScript() && Line->MustBeDeclaration) { 1501 // field/method declaration. 1502 break; 1503 } 1504 FormatToken *Tok = parseIfThenElse(IfKind); 1505 if (IfLeftBrace) 1506 *IfLeftBrace = Tok; 1507 return; 1508 } 1509 case tok::kw_for: 1510 case tok::kw_while: 1511 if (Style.isJavaScript() && Line->MustBeDeclaration) { 1512 // field/method declaration. 1513 break; 1514 } 1515 parseForOrWhileLoop(); 1516 return; 1517 case tok::kw_do: 1518 if (Style.isJavaScript() && Line->MustBeDeclaration) { 1519 // field/method declaration. 1520 break; 1521 } 1522 parseDoWhile(); 1523 if (HasDoWhile) 1524 *HasDoWhile = true; 1525 return; 1526 case tok::kw_switch: 1527 if (Style.isJavaScript() && Line->MustBeDeclaration) { 1528 // 'switch: string' field declaration. 1529 break; 1530 } 1531 parseSwitch(/*IsExpr=*/false); 1532 return; 1533 case tok::kw_default: { 1534 // In Verilog default along with other labels are handled in the next loop. 1535 if (Style.isVerilog()) 1536 break; 1537 if (Style.isJavaScript() && Line->MustBeDeclaration) { 1538 // 'default: string' field declaration. 1539 break; 1540 } 1541 auto *Default = FormatTok; 1542 nextToken(); 1543 if (FormatTok->is(tok::colon)) { 1544 FormatTok->setFinalizedType(TT_CaseLabelColon); 1545 parseLabel(); 1546 return; 1547 } 1548 if (FormatTok->is(tok::arrow)) { 1549 FormatTok->setFinalizedType(TT_CaseLabelArrow); 1550 Default->setFinalizedType(TT_SwitchExpressionLabel); 1551 parseLabel(); 1552 return; 1553 } 1554 // e.g. "default void f() {}" in a Java interface. 1555 break; 1556 } 1557 case tok::kw_case: 1558 // Proto: there are no switch/case statements. 1559 if (Style.Language == FormatStyle::LK_Proto) { 1560 nextToken(); 1561 return; 1562 } 1563 if (Style.isVerilog()) { 1564 parseBlock(); 1565 addUnwrappedLine(); 1566 return; 1567 } 1568 if (Style.isJavaScript() && Line->MustBeDeclaration) { 1569 // 'case: string' field declaration. 1570 nextToken(); 1571 break; 1572 } 1573 parseCaseLabel(); 1574 return; 1575 case tok::kw_goto: 1576 nextToken(); 1577 if (FormatTok->is(tok::kw_case)) 1578 nextToken(); 1579 break; 1580 case tok::kw_try: 1581 case tok::kw___try: 1582 if (Style.isJavaScript() && Line->MustBeDeclaration) { 1583 // field/method declaration. 1584 break; 1585 } 1586 parseTryCatch(); 1587 return; 1588 case tok::kw_extern: 1589 nextToken(); 1590 if (Style.isVerilog()) { 1591 // In Verilog and extern module declaration looks like a start of module. 1592 // But there is no body and endmodule. So we handle it separately. 1593 if (Keywords.isVerilogHierarchy(*FormatTok)) { 1594 parseVerilogHierarchyHeader(); 1595 return; 1596 } 1597 } else if (FormatTok->is(tok::string_literal)) { 1598 nextToken(); 1599 if (FormatTok->is(tok::l_brace)) { 1600 if (Style.BraceWrapping.AfterExternBlock) 1601 addUnwrappedLine(); 1602 // Either we indent or for backwards compatibility we follow the 1603 // AfterExternBlock style. 1604 unsigned AddLevels = 1605 (Style.IndentExternBlock == FormatStyle::IEBS_Indent) || 1606 (Style.BraceWrapping.AfterExternBlock && 1607 Style.IndentExternBlock == 1608 FormatStyle::IEBS_AfterExternBlock) 1609 ? 1u 1610 : 0u; 1611 parseBlock(/*MustBeDeclaration=*/true, AddLevels); 1612 addUnwrappedLine(); 1613 return; 1614 } 1615 } 1616 break; 1617 case tok::kw_export: 1618 if (Style.isJavaScript()) { 1619 parseJavaScriptEs6ImportExport(); 1620 return; 1621 } 1622 if (IsCpp) { 1623 nextToken(); 1624 if (FormatTok->is(tok::kw_namespace)) { 1625 parseNamespace(); 1626 return; 1627 } 1628 if (FormatTok->is(tok::l_brace)) { 1629 parseCppExportBlock(); 1630 return; 1631 } 1632 if (FormatTok->is(Keywords.kw_import) && parseModuleImport()) 1633 return; 1634 } 1635 break; 1636 case tok::kw_inline: 1637 nextToken(); 1638 if (FormatTok->is(tok::kw_namespace)) { 1639 parseNamespace(); 1640 return; 1641 } 1642 break; 1643 case tok::identifier: 1644 if (FormatTok->is(TT_ForEachMacro)) { 1645 parseForOrWhileLoop(); 1646 return; 1647 } 1648 if (FormatTok->is(TT_MacroBlockBegin)) { 1649 parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u, 1650 /*MunchSemi=*/false); 1651 return; 1652 } 1653 if (FormatTok->is(Keywords.kw_import)) { 1654 if (Style.isJavaScript()) { 1655 parseJavaScriptEs6ImportExport(); 1656 return; 1657 } 1658 if (Style.Language == FormatStyle::LK_Proto) { 1659 nextToken(); 1660 if (FormatTok->is(tok::kw_public)) 1661 nextToken(); 1662 if (FormatTok->isNot(tok::string_literal)) 1663 return; 1664 nextToken(); 1665 if (FormatTok->is(tok::semi)) 1666 nextToken(); 1667 addUnwrappedLine(); 1668 return; 1669 } 1670 if (IsCpp && parseModuleImport()) 1671 return; 1672 } 1673 if (IsCpp && FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals, 1674 Keywords.kw_slots, Keywords.kw_qslots)) { 1675 nextToken(); 1676 if (FormatTok->is(tok::colon)) { 1677 nextToken(); 1678 addUnwrappedLine(); 1679 return; 1680 } 1681 } 1682 if (IsCpp && FormatTok->is(TT_StatementMacro)) { 1683 parseStatementMacro(); 1684 return; 1685 } 1686 if (IsCpp && FormatTok->is(TT_NamespaceMacro)) { 1687 parseNamespace(); 1688 return; 1689 } 1690 // In Verilog labels can be any expression, so we don't do them here. 1691 // JS doesn't have macros, and within classes colons indicate fields, not 1692 // labels. 1693 // TableGen doesn't have labels. 1694 if (!Style.isJavaScript() && !Style.isVerilog() && !Style.isTableGen() && 1695 Tokens->peekNextToken()->is(tok::colon) && !Line->MustBeDeclaration) { 1696 nextToken(); 1697 if (!Line->InMacroBody || CurrentLines->size() > 1) 1698 Line->Tokens.begin()->Tok->MustBreakBefore = true; 1699 FormatTok->setFinalizedType(TT_GotoLabelColon); 1700 parseLabel(!Style.IndentGotoLabels); 1701 if (HasLabel) 1702 *HasLabel = true; 1703 return; 1704 } 1705 if (Style.isJava() && FormatTok->is(Keywords.kw_record)) { 1706 parseRecord(/*ParseAsExpr=*/false, /*IsJavaRecord=*/true); 1707 addUnwrappedLine(); 1708 return; 1709 } 1710 // In all other cases, parse the declaration. 1711 break; 1712 default: 1713 break; 1714 } 1715 1716 bool SeenEqual = false; 1717 for (const bool InRequiresExpression = 1718 OpeningBrace && OpeningBrace->isOneOf(TT_RequiresExpressionLBrace, 1719 TT_CompoundRequirementLBrace); 1720 !eof();) { 1721 const FormatToken *Previous = FormatTok->Previous; 1722 switch (FormatTok->Tok.getKind()) { 1723 case tok::at: 1724 nextToken(); 1725 if (FormatTok->is(tok::l_brace)) { 1726 nextToken(); 1727 parseBracedList(); 1728 break; 1729 } 1730 if (Style.isJava() && FormatTok->is(Keywords.kw_interface)) { 1731 nextToken(); 1732 break; 1733 } 1734 switch (bool IsAutoRelease = false; FormatTok->Tok.getObjCKeywordID()) { 1735 case tok::objc_public: 1736 case tok::objc_protected: 1737 case tok::objc_package: 1738 case tok::objc_private: 1739 return parseAccessSpecifier(); 1740 case tok::objc_interface: 1741 case tok::objc_implementation: 1742 return parseObjCInterfaceOrImplementation(); 1743 case tok::objc_protocol: 1744 if (parseObjCProtocol()) 1745 return; 1746 break; 1747 case tok::objc_end: 1748 return; // Handled by the caller. 1749 case tok::objc_optional: 1750 case tok::objc_required: 1751 nextToken(); 1752 addUnwrappedLine(); 1753 return; 1754 case tok::objc_autoreleasepool: 1755 IsAutoRelease = true; 1756 [[fallthrough]]; 1757 case tok::objc_synchronized: 1758 nextToken(); 1759 if (!IsAutoRelease && FormatTok->is(tok::l_paren)) { 1760 // Skip synchronization object 1761 parseParens(); 1762 } 1763 if (FormatTok->is(tok::l_brace)) { 1764 if (Style.BraceWrapping.AfterControlStatement == 1765 FormatStyle::BWACS_Always) { 1766 addUnwrappedLine(); 1767 } 1768 parseBlock(); 1769 } 1770 addUnwrappedLine(); 1771 return; 1772 case tok::objc_try: 1773 // This branch isn't strictly necessary (the kw_try case below would 1774 // do this too after the tok::at is parsed above). But be explicit. 1775 parseTryCatch(); 1776 return; 1777 default: 1778 break; 1779 } 1780 break; 1781 case tok::kw_requires: { 1782 if (IsCpp) { 1783 bool ParsedClause = parseRequires(SeenEqual); 1784 if (ParsedClause) 1785 return; 1786 } else { 1787 nextToken(); 1788 } 1789 break; 1790 } 1791 case tok::kw_enum: 1792 // Ignore if this is part of "template <enum ..." or "... -> enum" or 1793 // "template <..., enum ...>". 1794 if (Previous && Previous->isOneOf(tok::less, tok::arrow, tok::comma)) { 1795 nextToken(); 1796 break; 1797 } 1798 1799 // parseEnum falls through and does not yet add an unwrapped line as an 1800 // enum definition can start a structural element. 1801 if (!parseEnum()) 1802 break; 1803 // This only applies to C++ and Verilog. 1804 if (!IsCpp && !Style.isVerilog()) { 1805 addUnwrappedLine(); 1806 return; 1807 } 1808 break; 1809 case tok::kw_typedef: 1810 nextToken(); 1811 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS, 1812 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS, 1813 Keywords.kw_CF_CLOSED_ENUM, 1814 Keywords.kw_NS_CLOSED_ENUM)) { 1815 parseEnum(); 1816 } 1817 break; 1818 case tok::kw_class: 1819 if (Style.isVerilog()) { 1820 parseBlock(); 1821 addUnwrappedLine(); 1822 return; 1823 } 1824 if (Style.isTableGen()) { 1825 // Do nothing special. In this case the l_brace becomes FunctionLBrace. 1826 // This is same as def and so on. 1827 nextToken(); 1828 break; 1829 } 1830 [[fallthrough]]; 1831 case tok::kw_struct: 1832 case tok::kw_union: 1833 if (parseStructLike()) 1834 return; 1835 break; 1836 case tok::kw_decltype: 1837 nextToken(); 1838 if (FormatTok->is(tok::l_paren)) { 1839 parseParens(); 1840 if (FormatTok->Previous && 1841 FormatTok->Previous->endsSequence(tok::r_paren, tok::kw_auto, 1842 tok::l_paren)) { 1843 Line->SeenDecltypeAuto = true; 1844 } 1845 } 1846 break; 1847 case tok::period: 1848 nextToken(); 1849 // In Java, classes have an implicit static member "class". 1850 if (Style.isJava() && FormatTok && FormatTok->is(tok::kw_class)) 1851 nextToken(); 1852 if (Style.isJavaScript() && FormatTok && 1853 FormatTok->Tok.getIdentifierInfo()) { 1854 // JavaScript only has pseudo keywords, all keywords are allowed to 1855 // appear in "IdentifierName" positions. See http://es5.github.io/#x7.6 1856 nextToken(); 1857 } 1858 break; 1859 case tok::semi: 1860 nextToken(); 1861 addUnwrappedLine(); 1862 return; 1863 case tok::r_brace: 1864 addUnwrappedLine(); 1865 return; 1866 case tok::l_paren: { 1867 parseParens(); 1868 // Break the unwrapped line if a K&R C function definition has a parameter 1869 // declaration. 1870 if (OpeningBrace || !IsCpp || !Previous || eof()) 1871 break; 1872 if (isC78ParameterDecl(FormatTok, 1873 Tokens->peekNextToken(/*SkipComment=*/true), 1874 Previous)) { 1875 addUnwrappedLine(); 1876 return; 1877 } 1878 break; 1879 } 1880 case tok::kw_operator: 1881 nextToken(); 1882 if (FormatTok->isBinaryOperator()) 1883 nextToken(); 1884 break; 1885 case tok::caret: { 1886 const auto *Prev = FormatTok->getPreviousNonComment(); 1887 nextToken(); 1888 if (Prev && Prev->is(tok::identifier)) 1889 break; 1890 // Block return type. 1891 if (FormatTok->Tok.isAnyIdentifier() || FormatTok->isTypeName(LangOpts)) { 1892 nextToken(); 1893 // Return types: pointers are ok too. 1894 while (FormatTok->is(tok::star)) 1895 nextToken(); 1896 } 1897 // Block argument list. 1898 if (FormatTok->is(tok::l_paren)) 1899 parseParens(); 1900 // Block body. 1901 if (FormatTok->is(tok::l_brace)) 1902 parseChildBlock(); 1903 break; 1904 } 1905 case tok::l_brace: 1906 if (InRequiresExpression) 1907 FormatTok->setFinalizedType(TT_BracedListLBrace); 1908 if (!tryToParsePropertyAccessor() && !tryToParseBracedList()) { 1909 IsDecltypeAutoFunction = Line->SeenDecltypeAuto; 1910 // A block outside of parentheses must be the last part of a 1911 // structural element. 1912 // FIXME: Figure out cases where this is not true, and add projections 1913 // for them (the one we know is missing are lambdas). 1914 if (Style.isJava() && 1915 Line->Tokens.front().Tok->is(Keywords.kw_synchronized)) { 1916 // If necessary, we could set the type to something different than 1917 // TT_FunctionLBrace. 1918 if (Style.BraceWrapping.AfterControlStatement == 1919 FormatStyle::BWACS_Always) { 1920 addUnwrappedLine(); 1921 } 1922 } else if (Style.BraceWrapping.AfterFunction) { 1923 addUnwrappedLine(); 1924 } 1925 if (!Previous || Previous->isNot(TT_TypeDeclarationParen)) 1926 FormatTok->setFinalizedType(TT_FunctionLBrace); 1927 parseBlock(); 1928 IsDecltypeAutoFunction = false; 1929 addUnwrappedLine(); 1930 return; 1931 } 1932 // Otherwise this was a braced init list, and the structural 1933 // element continues. 1934 break; 1935 case tok::kw_try: 1936 if (Style.isJavaScript() && Line->MustBeDeclaration) { 1937 // field/method declaration. 1938 nextToken(); 1939 break; 1940 } 1941 // We arrive here when parsing function-try blocks. 1942 if (Style.BraceWrapping.AfterFunction) 1943 addUnwrappedLine(); 1944 parseTryCatch(); 1945 return; 1946 case tok::identifier: { 1947 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where) && 1948 Line->MustBeDeclaration) { 1949 addUnwrappedLine(); 1950 parseCSharpGenericTypeConstraint(); 1951 break; 1952 } 1953 if (FormatTok->is(TT_MacroBlockEnd)) { 1954 addUnwrappedLine(); 1955 return; 1956 } 1957 1958 // Function declarations (as opposed to function expressions) are parsed 1959 // on their own unwrapped line by continuing this loop. Function 1960 // expressions (functions that are not on their own line) must not create 1961 // a new unwrapped line, so they are special cased below. 1962 size_t TokenCount = Line->Tokens.size(); 1963 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_function) && 1964 (TokenCount > 1 || 1965 (TokenCount == 1 && 1966 Line->Tokens.front().Tok->isNot(Keywords.kw_async)))) { 1967 tryToParseJSFunction(); 1968 break; 1969 } 1970 if ((Style.isJavaScript() || Style.isJava()) && 1971 FormatTok->is(Keywords.kw_interface)) { 1972 if (Style.isJavaScript()) { 1973 // In JavaScript/TypeScript, "interface" can be used as a standalone 1974 // identifier, e.g. in `var interface = 1;`. If "interface" is 1975 // followed by another identifier, it is very like to be an actual 1976 // interface declaration. 1977 unsigned StoredPosition = Tokens->getPosition(); 1978 FormatToken *Next = Tokens->getNextToken(); 1979 FormatTok = Tokens->setPosition(StoredPosition); 1980 if (!mustBeJSIdent(Keywords, Next)) { 1981 nextToken(); 1982 break; 1983 } 1984 } 1985 parseRecord(); 1986 addUnwrappedLine(); 1987 return; 1988 } 1989 1990 if (Style.isVerilog()) { 1991 if (FormatTok->is(Keywords.kw_table)) { 1992 parseVerilogTable(); 1993 return; 1994 } 1995 if (Keywords.isVerilogBegin(*FormatTok) || 1996 Keywords.isVerilogHierarchy(*FormatTok)) { 1997 parseBlock(); 1998 addUnwrappedLine(); 1999 return; 2000 } 2001 } 2002 2003 if (!IsCpp && FormatTok->is(Keywords.kw_interface)) { 2004 if (parseStructLike()) 2005 return; 2006 break; 2007 } 2008 2009 if (IsCpp && FormatTok->is(TT_StatementMacro)) { 2010 parseStatementMacro(); 2011 return; 2012 } 2013 2014 // See if the following token should start a new unwrapped line. 2015 StringRef Text = FormatTok->TokenText; 2016 2017 FormatToken *PreviousToken = FormatTok; 2018 nextToken(); 2019 2020 // JS doesn't have macros, and within classes colons indicate fields, not 2021 // labels. 2022 if (Style.isJavaScript()) 2023 break; 2024 2025 auto OneTokenSoFar = [&]() { 2026 auto I = Line->Tokens.begin(), E = Line->Tokens.end(); 2027 while (I != E && I->Tok->is(tok::comment)) 2028 ++I; 2029 if (Style.isVerilog()) 2030 while (I != E && I->Tok->is(tok::hash)) 2031 ++I; 2032 return I != E && (++I == E); 2033 }; 2034 if (OneTokenSoFar()) { 2035 // Recognize function-like macro usages without trailing semicolon as 2036 // well as free-standing macros like Q_OBJECT. 2037 bool FunctionLike = FormatTok->is(tok::l_paren); 2038 if (FunctionLike) 2039 parseParens(); 2040 2041 bool FollowedByNewline = 2042 CommentsBeforeNextToken.empty() 2043 ? FormatTok->NewlinesBefore > 0 2044 : CommentsBeforeNextToken.front()->NewlinesBefore > 0; 2045 2046 if (FollowedByNewline && 2047 (Text.size() >= 5 || 2048 (FunctionLike && FormatTok->isNot(tok::l_paren))) && 2049 tokenCanStartNewLine(*FormatTok) && Text == Text.upper()) { 2050 if (PreviousToken->isNot(TT_UntouchableMacroFunc)) 2051 PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro); 2052 addUnwrappedLine(); 2053 return; 2054 } 2055 } 2056 break; 2057 } 2058 case tok::equal: 2059 if ((Style.isJavaScript() || Style.isCSharp()) && 2060 FormatTok->is(TT_FatArrow)) { 2061 tryToParseChildBlock(); 2062 break; 2063 } 2064 2065 SeenEqual = true; 2066 nextToken(); 2067 if (FormatTok->is(tok::l_brace)) { 2068 // Block kind should probably be set to BK_BracedInit for any language. 2069 // C# needs this change to ensure that array initialisers and object 2070 // initialisers are indented the same way. 2071 if (Style.isCSharp()) 2072 FormatTok->setBlockKind(BK_BracedInit); 2073 // TableGen's defset statement has syntax of the form, 2074 // `defset <type> <name> = { <statement>... }` 2075 if (Style.isTableGen() && 2076 Line->Tokens.begin()->Tok->is(Keywords.kw_defset)) { 2077 FormatTok->setFinalizedType(TT_FunctionLBrace); 2078 parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u, 2079 /*MunchSemi=*/false); 2080 addUnwrappedLine(); 2081 break; 2082 } 2083 nextToken(); 2084 parseBracedList(); 2085 } else if (Style.Language == FormatStyle::LK_Proto && 2086 FormatTok->is(tok::less)) { 2087 nextToken(); 2088 parseBracedList(/*IsAngleBracket=*/true); 2089 } 2090 break; 2091 case tok::l_square: 2092 parseSquare(); 2093 break; 2094 case tok::kw_new: 2095 if (Style.isCSharp() && 2096 (Tokens->peekNextToken()->isAccessSpecifierKeyword() || 2097 (Previous && Previous->isAccessSpecifierKeyword()))) { 2098 nextToken(); 2099 } else { 2100 parseNew(); 2101 } 2102 break; 2103 case tok::kw_switch: 2104 if (Style.isJava()) 2105 parseSwitch(/*IsExpr=*/true); 2106 else 2107 nextToken(); 2108 break; 2109 case tok::kw_case: 2110 // Proto: there are no switch/case statements. 2111 if (Style.Language == FormatStyle::LK_Proto) { 2112 nextToken(); 2113 return; 2114 } 2115 // In Verilog switch is called case. 2116 if (Style.isVerilog()) { 2117 parseBlock(); 2118 addUnwrappedLine(); 2119 return; 2120 } 2121 if (Style.isJavaScript() && Line->MustBeDeclaration) { 2122 // 'case: string' field declaration. 2123 nextToken(); 2124 break; 2125 } 2126 parseCaseLabel(); 2127 break; 2128 case tok::kw_default: 2129 nextToken(); 2130 if (Style.isVerilog()) { 2131 if (FormatTok->is(tok::colon)) { 2132 // The label will be handled in the next iteration. 2133 break; 2134 } 2135 if (FormatTok->is(Keywords.kw_clocking)) { 2136 // A default clocking block. 2137 parseBlock(); 2138 addUnwrappedLine(); 2139 return; 2140 } 2141 parseVerilogCaseLabel(); 2142 return; 2143 } 2144 break; 2145 case tok::colon: 2146 nextToken(); 2147 if (Style.isVerilog()) { 2148 parseVerilogCaseLabel(); 2149 return; 2150 } 2151 break; 2152 case tok::greater: 2153 nextToken(); 2154 if (FormatTok->is(tok::l_brace)) 2155 FormatTok->Previous->setFinalizedType(TT_TemplateCloser); 2156 break; 2157 default: 2158 nextToken(); 2159 break; 2160 } 2161 } 2162 } 2163 2164 bool UnwrappedLineParser::tryToParsePropertyAccessor() { 2165 assert(FormatTok->is(tok::l_brace)); 2166 if (!Style.isCSharp()) 2167 return false; 2168 // See if it's a property accessor. 2169 if (!FormatTok->Previous || FormatTok->Previous->isNot(tok::identifier)) 2170 return false; 2171 2172 // See if we are inside a property accessor. 2173 // 2174 // Record the current tokenPosition so that we can advance and 2175 // reset the current token. `Next` is not set yet so we need 2176 // another way to advance along the token stream. 2177 unsigned int StoredPosition = Tokens->getPosition(); 2178 FormatToken *Tok = Tokens->getNextToken(); 2179 2180 // A trivial property accessor is of the form: 2181 // { [ACCESS_SPECIFIER] [get]; [ACCESS_SPECIFIER] [set|init] } 2182 // Track these as they do not require line breaks to be introduced. 2183 bool HasSpecialAccessor = false; 2184 bool IsTrivialPropertyAccessor = true; 2185 bool HasAttribute = false; 2186 while (!eof()) { 2187 if (const bool IsAccessorKeyword = 2188 Tok->isOneOf(Keywords.kw_get, Keywords.kw_init, Keywords.kw_set); 2189 IsAccessorKeyword || Tok->isAccessSpecifierKeyword() || 2190 Tok->isOneOf(tok::l_square, tok::semi, Keywords.kw_internal)) { 2191 if (IsAccessorKeyword) 2192 HasSpecialAccessor = true; 2193 else if (Tok->is(tok::l_square)) 2194 HasAttribute = true; 2195 Tok = Tokens->getNextToken(); 2196 continue; 2197 } 2198 if (Tok->isNot(tok::r_brace)) 2199 IsTrivialPropertyAccessor = false; 2200 break; 2201 } 2202 2203 if (!HasSpecialAccessor || HasAttribute) { 2204 Tokens->setPosition(StoredPosition); 2205 return false; 2206 } 2207 2208 // Try to parse the property accessor: 2209 // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties 2210 Tokens->setPosition(StoredPosition); 2211 if (!IsTrivialPropertyAccessor && Style.BraceWrapping.AfterFunction) 2212 addUnwrappedLine(); 2213 nextToken(); 2214 do { 2215 switch (FormatTok->Tok.getKind()) { 2216 case tok::r_brace: 2217 nextToken(); 2218 if (FormatTok->is(tok::equal)) { 2219 while (!eof() && FormatTok->isNot(tok::semi)) 2220 nextToken(); 2221 nextToken(); 2222 } 2223 addUnwrappedLine(); 2224 return true; 2225 case tok::l_brace: 2226 ++Line->Level; 2227 parseBlock(/*MustBeDeclaration=*/true); 2228 addUnwrappedLine(); 2229 --Line->Level; 2230 break; 2231 case tok::equal: 2232 if (FormatTok->is(TT_FatArrow)) { 2233 ++Line->Level; 2234 do { 2235 nextToken(); 2236 } while (!eof() && FormatTok->isNot(tok::semi)); 2237 nextToken(); 2238 addUnwrappedLine(); 2239 --Line->Level; 2240 break; 2241 } 2242 nextToken(); 2243 break; 2244 default: 2245 if (FormatTok->isOneOf(Keywords.kw_get, Keywords.kw_init, 2246 Keywords.kw_set) && 2247 !IsTrivialPropertyAccessor) { 2248 // Non-trivial get/set needs to be on its own line. 2249 addUnwrappedLine(); 2250 } 2251 nextToken(); 2252 } 2253 } while (!eof()); 2254 2255 // Unreachable for well-formed code (paired '{' and '}'). 2256 return true; 2257 } 2258 2259 bool UnwrappedLineParser::tryToParseLambda() { 2260 assert(FormatTok->is(tok::l_square)); 2261 if (!IsCpp) { 2262 nextToken(); 2263 return false; 2264 } 2265 FormatToken &LSquare = *FormatTok; 2266 if (!tryToParseLambdaIntroducer()) 2267 return false; 2268 2269 bool SeenArrow = false; 2270 bool InTemplateParameterList = false; 2271 2272 while (FormatTok->isNot(tok::l_brace)) { 2273 if (FormatTok->isTypeName(LangOpts) || FormatTok->isAttribute()) { 2274 nextToken(); 2275 continue; 2276 } 2277 switch (FormatTok->Tok.getKind()) { 2278 case tok::l_brace: 2279 break; 2280 case tok::l_paren: 2281 parseParens(/*AmpAmpTokenType=*/TT_PointerOrReference); 2282 break; 2283 case tok::l_square: 2284 parseSquare(); 2285 break; 2286 case tok::less: 2287 assert(FormatTok->Previous); 2288 if (FormatTok->Previous->is(tok::r_square)) 2289 InTemplateParameterList = true; 2290 nextToken(); 2291 break; 2292 case tok::kw_auto: 2293 case tok::kw_class: 2294 case tok::kw_struct: 2295 case tok::kw_union: 2296 case tok::kw_template: 2297 case tok::kw_typename: 2298 case tok::amp: 2299 case tok::star: 2300 case tok::kw_const: 2301 case tok::kw_constexpr: 2302 case tok::kw_consteval: 2303 case tok::comma: 2304 case tok::greater: 2305 case tok::identifier: 2306 case tok::numeric_constant: 2307 case tok::coloncolon: 2308 case tok::kw_mutable: 2309 case tok::kw_noexcept: 2310 case tok::kw_static: 2311 nextToken(); 2312 break; 2313 // Specialization of a template with an integer parameter can contain 2314 // arithmetic, logical, comparison and ternary operators. 2315 // 2316 // FIXME: This also accepts sequences of operators that are not in the scope 2317 // of a template argument list. 2318 // 2319 // In a C++ lambda a template type can only occur after an arrow. We use 2320 // this as an heuristic to distinguish between Objective-C expressions 2321 // followed by an `a->b` expression, such as: 2322 // ([obj func:arg] + a->b) 2323 // Otherwise the code below would parse as a lambda. 2324 case tok::plus: 2325 case tok::minus: 2326 case tok::exclaim: 2327 case tok::tilde: 2328 case tok::slash: 2329 case tok::percent: 2330 case tok::lessless: 2331 case tok::pipe: 2332 case tok::pipepipe: 2333 case tok::ampamp: 2334 case tok::caret: 2335 case tok::equalequal: 2336 case tok::exclaimequal: 2337 case tok::greaterequal: 2338 case tok::lessequal: 2339 case tok::question: 2340 case tok::colon: 2341 case tok::ellipsis: 2342 case tok::kw_true: 2343 case tok::kw_false: 2344 if (SeenArrow || InTemplateParameterList) { 2345 nextToken(); 2346 break; 2347 } 2348 return true; 2349 case tok::arrow: 2350 // This might or might not actually be a lambda arrow (this could be an 2351 // ObjC method invocation followed by a dereferencing arrow). We might 2352 // reset this back to TT_Unknown in TokenAnnotator. 2353 FormatTok->setFinalizedType(TT_LambdaArrow); 2354 SeenArrow = true; 2355 nextToken(); 2356 break; 2357 case tok::kw_requires: { 2358 auto *RequiresToken = FormatTok; 2359 nextToken(); 2360 parseRequiresClause(RequiresToken); 2361 break; 2362 } 2363 case tok::equal: 2364 if (!InTemplateParameterList) 2365 return true; 2366 nextToken(); 2367 break; 2368 default: 2369 return true; 2370 } 2371 } 2372 2373 FormatTok->setFinalizedType(TT_LambdaLBrace); 2374 LSquare.setFinalizedType(TT_LambdaLSquare); 2375 2376 NestedLambdas.push_back(Line->SeenDecltypeAuto); 2377 parseChildBlock(); 2378 assert(!NestedLambdas.empty()); 2379 NestedLambdas.pop_back(); 2380 2381 return true; 2382 } 2383 2384 bool UnwrappedLineParser::tryToParseLambdaIntroducer() { 2385 const FormatToken *Previous = FormatTok->Previous; 2386 const FormatToken *LeftSquare = FormatTok; 2387 nextToken(); 2388 if (Previous) { 2389 if (Previous->Tok.getIdentifierInfo() && 2390 !Previous->isOneOf(tok::kw_return, tok::kw_co_await, tok::kw_co_yield, 2391 tok::kw_co_return)) { 2392 return false; 2393 } 2394 if (Previous->closesScope()) { 2395 // Not a potential C-style cast. 2396 if (Previous->isNot(tok::r_paren)) 2397 return false; 2398 const auto *BeforeRParen = Previous->getPreviousNonComment(); 2399 // Lambdas can be cast to function types only, e.g. `std::function<int()>` 2400 // and `int (*)()`. 2401 if (!BeforeRParen || !BeforeRParen->isOneOf(tok::greater, tok::r_paren)) 2402 return false; 2403 } 2404 } 2405 if (LeftSquare->isCppStructuredBinding(IsCpp)) 2406 return false; 2407 if (FormatTok->is(tok::l_square) || tok::isLiteral(FormatTok->Tok.getKind())) 2408 return false; 2409 if (FormatTok->is(tok::r_square)) { 2410 const FormatToken *Next = Tokens->peekNextToken(/*SkipComment=*/true); 2411 if (Next->is(tok::greater)) 2412 return false; 2413 } 2414 parseSquare(/*LambdaIntroducer=*/true); 2415 return true; 2416 } 2417 2418 void UnwrappedLineParser::tryToParseJSFunction() { 2419 assert(FormatTok->is(Keywords.kw_function)); 2420 if (FormatTok->is(Keywords.kw_async)) 2421 nextToken(); 2422 // Consume "function". 2423 nextToken(); 2424 2425 // Consume * (generator function). Treat it like C++'s overloaded operators. 2426 if (FormatTok->is(tok::star)) { 2427 FormatTok->setFinalizedType(TT_OverloadedOperator); 2428 nextToken(); 2429 } 2430 2431 // Consume function name. 2432 if (FormatTok->is(tok::identifier)) 2433 nextToken(); 2434 2435 if (FormatTok->isNot(tok::l_paren)) 2436 return; 2437 2438 // Parse formal parameter list. 2439 parseParens(); 2440 2441 if (FormatTok->is(tok::colon)) { 2442 // Parse a type definition. 2443 nextToken(); 2444 2445 // Eat the type declaration. For braced inline object types, balance braces, 2446 // otherwise just parse until finding an l_brace for the function body. 2447 if (FormatTok->is(tok::l_brace)) 2448 tryToParseBracedList(); 2449 else 2450 while (!FormatTok->isOneOf(tok::l_brace, tok::semi) && !eof()) 2451 nextToken(); 2452 } 2453 2454 if (FormatTok->is(tok::semi)) 2455 return; 2456 2457 parseChildBlock(); 2458 } 2459 2460 bool UnwrappedLineParser::tryToParseBracedList() { 2461 if (FormatTok->is(BK_Unknown)) 2462 calculateBraceTypes(); 2463 assert(FormatTok->isNot(BK_Unknown)); 2464 if (FormatTok->is(BK_Block)) 2465 return false; 2466 nextToken(); 2467 parseBracedList(); 2468 return true; 2469 } 2470 2471 bool UnwrappedLineParser::tryToParseChildBlock() { 2472 assert(Style.isJavaScript() || Style.isCSharp()); 2473 assert(FormatTok->is(TT_FatArrow)); 2474 // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType TT_FatArrow. 2475 // They always start an expression or a child block if followed by a curly 2476 // brace. 2477 nextToken(); 2478 if (FormatTok->isNot(tok::l_brace)) 2479 return false; 2480 parseChildBlock(); 2481 return true; 2482 } 2483 2484 bool UnwrappedLineParser::parseBracedList(bool IsAngleBracket, bool IsEnum) { 2485 assert(!IsAngleBracket || !IsEnum); 2486 bool HasError = false; 2487 2488 // FIXME: Once we have an expression parser in the UnwrappedLineParser, 2489 // replace this by using parseAssignmentExpression() inside. 2490 do { 2491 if (Style.isCSharp() && FormatTok->is(TT_FatArrow) && 2492 tryToParseChildBlock()) { 2493 continue; 2494 } 2495 if (Style.isJavaScript()) { 2496 if (FormatTok->is(Keywords.kw_function)) { 2497 tryToParseJSFunction(); 2498 continue; 2499 } 2500 if (FormatTok->is(tok::l_brace)) { 2501 // Could be a method inside of a braced list `{a() { return 1; }}`. 2502 if (tryToParseBracedList()) 2503 continue; 2504 parseChildBlock(); 2505 } 2506 } 2507 if (FormatTok->is(IsAngleBracket ? tok::greater : tok::r_brace)) { 2508 if (IsEnum) { 2509 FormatTok->setBlockKind(BK_Block); 2510 if (!Style.AllowShortEnumsOnASingleLine) 2511 addUnwrappedLine(); 2512 } 2513 nextToken(); 2514 return !HasError; 2515 } 2516 switch (FormatTok->Tok.getKind()) { 2517 case tok::l_square: 2518 if (Style.isCSharp()) 2519 parseSquare(); 2520 else 2521 tryToParseLambda(); 2522 break; 2523 case tok::l_paren: 2524 parseParens(); 2525 // JavaScript can just have free standing methods and getters/setters in 2526 // object literals. Detect them by a "{" following ")". 2527 if (Style.isJavaScript()) { 2528 if (FormatTok->is(tok::l_brace)) 2529 parseChildBlock(); 2530 break; 2531 } 2532 break; 2533 case tok::l_brace: 2534 // Assume there are no blocks inside a braced init list apart 2535 // from the ones we explicitly parse out (like lambdas). 2536 FormatTok->setBlockKind(BK_BracedInit); 2537 if (!IsAngleBracket) { 2538 auto *Prev = FormatTok->Previous; 2539 if (Prev && Prev->is(tok::greater)) 2540 Prev->setFinalizedType(TT_TemplateCloser); 2541 } 2542 nextToken(); 2543 parseBracedList(); 2544 break; 2545 case tok::less: 2546 nextToken(); 2547 if (IsAngleBracket) 2548 parseBracedList(/*IsAngleBracket=*/true); 2549 break; 2550 case tok::semi: 2551 // JavaScript (or more precisely TypeScript) can have semicolons in braced 2552 // lists (in so-called TypeMemberLists). Thus, the semicolon cannot be 2553 // used for error recovery if we have otherwise determined that this is 2554 // a braced list. 2555 if (Style.isJavaScript()) { 2556 nextToken(); 2557 break; 2558 } 2559 HasError = true; 2560 if (!IsEnum) 2561 return false; 2562 nextToken(); 2563 break; 2564 case tok::comma: 2565 nextToken(); 2566 if (IsEnum && !Style.AllowShortEnumsOnASingleLine) 2567 addUnwrappedLine(); 2568 break; 2569 default: 2570 nextToken(); 2571 break; 2572 } 2573 } while (!eof()); 2574 return false; 2575 } 2576 2577 /// Parses a pair of parentheses (and everything between them). 2578 /// \param AmpAmpTokenType If different than TT_Unknown sets this type for all 2579 /// double ampersands. This applies for all nested scopes as well. 2580 /// 2581 /// Returns whether there is a `=` token between the parentheses. 2582 bool UnwrappedLineParser::parseParens(TokenType AmpAmpTokenType, 2583 bool InMacroCall) { 2584 assert(FormatTok->is(tok::l_paren) && "'(' expected."); 2585 auto *LParen = FormatTok; 2586 auto *Prev = FormatTok->Previous; 2587 bool SeenComma = false; 2588 bool SeenEqual = false; 2589 bool MightBeFoldExpr = false; 2590 nextToken(); 2591 const bool MightBeStmtExpr = FormatTok->is(tok::l_brace); 2592 if (!InMacroCall && Prev && Prev->is(TT_FunctionLikeMacro)) 2593 InMacroCall = true; 2594 do { 2595 switch (FormatTok->Tok.getKind()) { 2596 case tok::l_paren: 2597 if (parseParens(AmpAmpTokenType, InMacroCall)) 2598 SeenEqual = true; 2599 if (Style.isJava() && FormatTok->is(tok::l_brace)) 2600 parseChildBlock(); 2601 break; 2602 case tok::r_paren: { 2603 auto *RParen = FormatTok; 2604 nextToken(); 2605 if (Prev) { 2606 auto OptionalParens = [&] { 2607 if (MightBeStmtExpr || MightBeFoldExpr || SeenComma || InMacroCall || 2608 Line->InMacroBody || 2609 Style.RemoveParentheses == FormatStyle::RPS_Leave || 2610 RParen->getPreviousNonComment() == LParen) { 2611 return false; 2612 } 2613 const bool DoubleParens = 2614 Prev->is(tok::l_paren) && FormatTok->is(tok::r_paren); 2615 if (DoubleParens) { 2616 const auto *PrevPrev = Prev->getPreviousNonComment(); 2617 const bool Excluded = 2618 PrevPrev && 2619 (PrevPrev->isOneOf(tok::kw___attribute, tok::kw_decltype) || 2620 (SeenEqual && 2621 (PrevPrev->isOneOf(tok::kw_if, tok::kw_while) || 2622 PrevPrev->endsSequence(tok::kw_constexpr, tok::kw_if)))); 2623 if (!Excluded) 2624 return true; 2625 } else { 2626 const bool CommaSeparated = 2627 Prev->isOneOf(tok::l_paren, tok::comma) && 2628 FormatTok->isOneOf(tok::comma, tok::r_paren); 2629 if (CommaSeparated && 2630 // LParen is not preceded by ellipsis, comma. 2631 !Prev->endsSequence(tok::comma, tok::ellipsis) && 2632 // RParen is not followed by comma, ellipsis. 2633 !(FormatTok->is(tok::comma) && 2634 Tokens->peekNextToken()->is(tok::ellipsis))) { 2635 return true; 2636 } 2637 const bool ReturnParens = 2638 Style.RemoveParentheses == FormatStyle::RPS_ReturnStatement && 2639 ((NestedLambdas.empty() && !IsDecltypeAutoFunction) || 2640 (!NestedLambdas.empty() && !NestedLambdas.back())) && 2641 Prev->isOneOf(tok::kw_return, tok::kw_co_return) && 2642 FormatTok->is(tok::semi); 2643 if (ReturnParens) 2644 return true; 2645 } 2646 return false; 2647 }; 2648 if (Prev->is(TT_TypenameMacro)) { 2649 LParen->setFinalizedType(TT_TypeDeclarationParen); 2650 RParen->setFinalizedType(TT_TypeDeclarationParen); 2651 } else if (Prev->is(tok::greater) && RParen->Previous == LParen) { 2652 Prev->setFinalizedType(TT_TemplateCloser); 2653 } else if (OptionalParens()) { 2654 LParen->Optional = true; 2655 RParen->Optional = true; 2656 } 2657 } 2658 return SeenEqual; 2659 } 2660 case tok::r_brace: 2661 // A "}" inside parenthesis is an error if there wasn't a matching "{". 2662 return SeenEqual; 2663 case tok::l_square: 2664 tryToParseLambda(); 2665 break; 2666 case tok::l_brace: 2667 if (!tryToParseBracedList()) 2668 parseChildBlock(); 2669 break; 2670 case tok::at: 2671 nextToken(); 2672 if (FormatTok->is(tok::l_brace)) { 2673 nextToken(); 2674 parseBracedList(); 2675 } 2676 break; 2677 case tok::comma: 2678 SeenComma = true; 2679 nextToken(); 2680 break; 2681 case tok::ellipsis: 2682 MightBeFoldExpr = true; 2683 nextToken(); 2684 break; 2685 case tok::equal: 2686 SeenEqual = true; 2687 if (Style.isCSharp() && FormatTok->is(TT_FatArrow)) 2688 tryToParseChildBlock(); 2689 else 2690 nextToken(); 2691 break; 2692 case tok::kw_class: 2693 if (Style.isJavaScript()) 2694 parseRecord(/*ParseAsExpr=*/true); 2695 else 2696 nextToken(); 2697 break; 2698 case tok::identifier: 2699 if (Style.isJavaScript() && (FormatTok->is(Keywords.kw_function))) 2700 tryToParseJSFunction(); 2701 else 2702 nextToken(); 2703 break; 2704 case tok::kw_switch: 2705 if (Style.isJava()) 2706 parseSwitch(/*IsExpr=*/true); 2707 else 2708 nextToken(); 2709 break; 2710 case tok::kw_requires: { 2711 auto RequiresToken = FormatTok; 2712 nextToken(); 2713 parseRequiresExpression(RequiresToken); 2714 break; 2715 } 2716 case tok::ampamp: 2717 if (AmpAmpTokenType != TT_Unknown) 2718 FormatTok->setFinalizedType(AmpAmpTokenType); 2719 [[fallthrough]]; 2720 default: 2721 nextToken(); 2722 break; 2723 } 2724 } while (!eof()); 2725 return SeenEqual; 2726 } 2727 2728 void UnwrappedLineParser::parseSquare(bool LambdaIntroducer) { 2729 if (!LambdaIntroducer) { 2730 assert(FormatTok->is(tok::l_square) && "'[' expected."); 2731 if (tryToParseLambda()) 2732 return; 2733 } 2734 do { 2735 switch (FormatTok->Tok.getKind()) { 2736 case tok::l_paren: 2737 parseParens(); 2738 break; 2739 case tok::r_square: 2740 nextToken(); 2741 return; 2742 case tok::r_brace: 2743 // A "}" inside parenthesis is an error if there wasn't a matching "{". 2744 return; 2745 case tok::l_square: 2746 parseSquare(); 2747 break; 2748 case tok::l_brace: { 2749 if (!tryToParseBracedList()) 2750 parseChildBlock(); 2751 break; 2752 } 2753 case tok::at: 2754 case tok::colon: 2755 nextToken(); 2756 if (FormatTok->is(tok::l_brace)) { 2757 nextToken(); 2758 parseBracedList(); 2759 } 2760 break; 2761 default: 2762 nextToken(); 2763 break; 2764 } 2765 } while (!eof()); 2766 } 2767 2768 void UnwrappedLineParser::keepAncestorBraces() { 2769 if (!Style.RemoveBracesLLVM) 2770 return; 2771 2772 const int MaxNestingLevels = 2; 2773 const int Size = NestedTooDeep.size(); 2774 if (Size >= MaxNestingLevels) 2775 NestedTooDeep[Size - MaxNestingLevels] = true; 2776 NestedTooDeep.push_back(false); 2777 } 2778 2779 static FormatToken *getLastNonComment(const UnwrappedLine &Line) { 2780 for (const auto &Token : llvm::reverse(Line.Tokens)) 2781 if (Token.Tok->isNot(tok::comment)) 2782 return Token.Tok; 2783 2784 return nullptr; 2785 } 2786 2787 void UnwrappedLineParser::parseUnbracedBody(bool CheckEOF) { 2788 FormatToken *Tok = nullptr; 2789 2790 if (Style.InsertBraces && !Line->InPPDirective && !Line->Tokens.empty() && 2791 PreprocessorDirectives.empty() && FormatTok->isNot(tok::semi)) { 2792 Tok = Style.BraceWrapping.AfterControlStatement == FormatStyle::BWACS_Never 2793 ? getLastNonComment(*Line) 2794 : Line->Tokens.back().Tok; 2795 assert(Tok); 2796 if (Tok->BraceCount < 0) { 2797 assert(Tok->BraceCount == -1); 2798 Tok = nullptr; 2799 } else { 2800 Tok->BraceCount = -1; 2801 } 2802 } 2803 2804 addUnwrappedLine(); 2805 ++Line->Level; 2806 ++Line->UnbracedBodyLevel; 2807 parseStructuralElement(); 2808 --Line->UnbracedBodyLevel; 2809 2810 if (Tok) { 2811 assert(!Line->InPPDirective); 2812 Tok = nullptr; 2813 for (const auto &L : llvm::reverse(*CurrentLines)) { 2814 if (!L.InPPDirective && getLastNonComment(L)) { 2815 Tok = L.Tokens.back().Tok; 2816 break; 2817 } 2818 } 2819 assert(Tok); 2820 ++Tok->BraceCount; 2821 } 2822 2823 if (CheckEOF && eof()) 2824 addUnwrappedLine(); 2825 2826 --Line->Level; 2827 } 2828 2829 static void markOptionalBraces(FormatToken *LeftBrace) { 2830 if (!LeftBrace) 2831 return; 2832 2833 assert(LeftBrace->is(tok::l_brace)); 2834 2835 FormatToken *RightBrace = LeftBrace->MatchingParen; 2836 if (!RightBrace) { 2837 assert(!LeftBrace->Optional); 2838 return; 2839 } 2840 2841 assert(RightBrace->is(tok::r_brace)); 2842 assert(RightBrace->MatchingParen == LeftBrace); 2843 assert(LeftBrace->Optional == RightBrace->Optional); 2844 2845 LeftBrace->Optional = true; 2846 RightBrace->Optional = true; 2847 } 2848 2849 void UnwrappedLineParser::handleAttributes() { 2850 // Handle AttributeMacro, e.g. `if (x) UNLIKELY`. 2851 if (FormatTok->isAttribute()) 2852 nextToken(); 2853 else if (FormatTok->is(tok::l_square)) 2854 handleCppAttributes(); 2855 } 2856 2857 bool UnwrappedLineParser::handleCppAttributes() { 2858 // Handle [[likely]] / [[unlikely]] attributes. 2859 assert(FormatTok->is(tok::l_square)); 2860 if (!tryToParseSimpleAttribute()) 2861 return false; 2862 parseSquare(); 2863 return true; 2864 } 2865 2866 /// Returns whether \c Tok begins a block. 2867 bool UnwrappedLineParser::isBlockBegin(const FormatToken &Tok) const { 2868 // FIXME: rename the function or make 2869 // Tok.isOneOf(tok::l_brace, TT_MacroBlockBegin) work. 2870 return Style.isVerilog() ? Keywords.isVerilogBegin(Tok) 2871 : Tok.is(tok::l_brace); 2872 } 2873 2874 FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind, 2875 bool KeepBraces, 2876 bool IsVerilogAssert) { 2877 assert((FormatTok->is(tok::kw_if) || 2878 (Style.isVerilog() && 2879 FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert, 2880 Keywords.kw_assume, Keywords.kw_cover))) && 2881 "'if' expected"); 2882 nextToken(); 2883 2884 if (IsVerilogAssert) { 2885 // Handle `assert #0` and `assert final`. 2886 if (FormatTok->is(Keywords.kw_verilogHash)) { 2887 nextToken(); 2888 if (FormatTok->is(tok::numeric_constant)) 2889 nextToken(); 2890 } else if (FormatTok->isOneOf(Keywords.kw_final, Keywords.kw_property, 2891 Keywords.kw_sequence)) { 2892 nextToken(); 2893 } 2894 } 2895 2896 // TableGen's if statement has the form of `if <cond> then { ... }`. 2897 if (Style.isTableGen()) { 2898 while (!eof() && FormatTok->isNot(Keywords.kw_then)) { 2899 // Simply skip until then. This range only contains a value. 2900 nextToken(); 2901 } 2902 } 2903 2904 // Handle `if !consteval`. 2905 if (FormatTok->is(tok::exclaim)) 2906 nextToken(); 2907 2908 bool KeepIfBraces = true; 2909 if (FormatTok->is(tok::kw_consteval)) { 2910 nextToken(); 2911 } else { 2912 KeepIfBraces = !Style.RemoveBracesLLVM || KeepBraces; 2913 if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier)) 2914 nextToken(); 2915 if (FormatTok->is(tok::l_paren)) { 2916 FormatTok->setFinalizedType(TT_ConditionLParen); 2917 parseParens(); 2918 } 2919 } 2920 handleAttributes(); 2921 // The then action is optional in Verilog assert statements. 2922 if (IsVerilogAssert && FormatTok->is(tok::semi)) { 2923 nextToken(); 2924 addUnwrappedLine(); 2925 return nullptr; 2926 } 2927 2928 bool NeedsUnwrappedLine = false; 2929 keepAncestorBraces(); 2930 2931 FormatToken *IfLeftBrace = nullptr; 2932 IfStmtKind IfBlockKind = IfStmtKind::NotIf; 2933 2934 if (isBlockBegin(*FormatTok)) { 2935 FormatTok->setFinalizedType(TT_ControlStatementLBrace); 2936 IfLeftBrace = FormatTok; 2937 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2938 parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u, 2939 /*MunchSemi=*/true, KeepIfBraces, &IfBlockKind); 2940 setPreviousRBraceType(TT_ControlStatementRBrace); 2941 if (Style.BraceWrapping.BeforeElse) 2942 addUnwrappedLine(); 2943 else 2944 NeedsUnwrappedLine = true; 2945 } else if (IsVerilogAssert && FormatTok->is(tok::kw_else)) { 2946 addUnwrappedLine(); 2947 } else { 2948 parseUnbracedBody(); 2949 } 2950 2951 if (Style.RemoveBracesLLVM) { 2952 assert(!NestedTooDeep.empty()); 2953 KeepIfBraces = KeepIfBraces || 2954 (IfLeftBrace && !IfLeftBrace->MatchingParen) || 2955 NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly || 2956 IfBlockKind == IfStmtKind::IfElseIf; 2957 } 2958 2959 bool KeepElseBraces = KeepIfBraces; 2960 FormatToken *ElseLeftBrace = nullptr; 2961 IfStmtKind Kind = IfStmtKind::IfOnly; 2962 2963 if (FormatTok->is(tok::kw_else)) { 2964 if (Style.RemoveBracesLLVM) { 2965 NestedTooDeep.back() = false; 2966 Kind = IfStmtKind::IfElse; 2967 } 2968 nextToken(); 2969 handleAttributes(); 2970 if (isBlockBegin(*FormatTok)) { 2971 const bool FollowedByIf = Tokens->peekNextToken()->is(tok::kw_if); 2972 FormatTok->setFinalizedType(TT_ElseLBrace); 2973 ElseLeftBrace = FormatTok; 2974 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2975 IfStmtKind ElseBlockKind = IfStmtKind::NotIf; 2976 FormatToken *IfLBrace = 2977 parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u, 2978 /*MunchSemi=*/true, KeepElseBraces, &ElseBlockKind); 2979 setPreviousRBraceType(TT_ElseRBrace); 2980 if (FormatTok->is(tok::kw_else)) { 2981 KeepElseBraces = KeepElseBraces || 2982 ElseBlockKind == IfStmtKind::IfOnly || 2983 ElseBlockKind == IfStmtKind::IfElseIf; 2984 } else if (FollowedByIf && IfLBrace && !IfLBrace->Optional) { 2985 KeepElseBraces = true; 2986 assert(ElseLeftBrace->MatchingParen); 2987 markOptionalBraces(ElseLeftBrace); 2988 } 2989 addUnwrappedLine(); 2990 } else if (!IsVerilogAssert && FormatTok->is(tok::kw_if)) { 2991 const FormatToken *Previous = Tokens->getPreviousToken(); 2992 assert(Previous); 2993 const bool IsPrecededByComment = Previous->is(tok::comment); 2994 if (IsPrecededByComment) { 2995 addUnwrappedLine(); 2996 ++Line->Level; 2997 } 2998 bool TooDeep = true; 2999 if (Style.RemoveBracesLLVM) { 3000 Kind = IfStmtKind::IfElseIf; 3001 TooDeep = NestedTooDeep.pop_back_val(); 3002 } 3003 ElseLeftBrace = parseIfThenElse(/*IfKind=*/nullptr, KeepIfBraces); 3004 if (Style.RemoveBracesLLVM) 3005 NestedTooDeep.push_back(TooDeep); 3006 if (IsPrecededByComment) 3007 --Line->Level; 3008 } else { 3009 parseUnbracedBody(/*CheckEOF=*/true); 3010 } 3011 } else { 3012 KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse; 3013 if (NeedsUnwrappedLine) 3014 addUnwrappedLine(); 3015 } 3016 3017 if (!Style.RemoveBracesLLVM) 3018 return nullptr; 3019 3020 assert(!NestedTooDeep.empty()); 3021 KeepElseBraces = KeepElseBraces || 3022 (ElseLeftBrace && !ElseLeftBrace->MatchingParen) || 3023 NestedTooDeep.back(); 3024 3025 NestedTooDeep.pop_back(); 3026 3027 if (!KeepIfBraces && !KeepElseBraces) { 3028 markOptionalBraces(IfLeftBrace); 3029 markOptionalBraces(ElseLeftBrace); 3030 } else if (IfLeftBrace) { 3031 FormatToken *IfRightBrace = IfLeftBrace->MatchingParen; 3032 if (IfRightBrace) { 3033 assert(IfRightBrace->MatchingParen == IfLeftBrace); 3034 assert(!IfLeftBrace->Optional); 3035 assert(!IfRightBrace->Optional); 3036 IfLeftBrace->MatchingParen = nullptr; 3037 IfRightBrace->MatchingParen = nullptr; 3038 } 3039 } 3040 3041 if (IfKind) 3042 *IfKind = Kind; 3043 3044 return IfLeftBrace; 3045 } 3046 3047 void UnwrappedLineParser::parseTryCatch() { 3048 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected"); 3049 nextToken(); 3050 bool NeedsUnwrappedLine = false; 3051 bool HasCtorInitializer = false; 3052 if (FormatTok->is(tok::colon)) { 3053 auto *Colon = FormatTok; 3054 // We are in a function try block, what comes is an initializer list. 3055 nextToken(); 3056 if (FormatTok->is(tok::identifier)) { 3057 HasCtorInitializer = true; 3058 Colon->setFinalizedType(TT_CtorInitializerColon); 3059 } 3060 3061 // In case identifiers were removed by clang-tidy, what might follow is 3062 // multiple commas in sequence - before the first identifier. 3063 while (FormatTok->is(tok::comma)) 3064 nextToken(); 3065 3066 while (FormatTok->is(tok::identifier)) { 3067 nextToken(); 3068 if (FormatTok->is(tok::l_paren)) { 3069 parseParens(); 3070 } else if (FormatTok->is(tok::l_brace)) { 3071 nextToken(); 3072 parseBracedList(); 3073 } 3074 3075 // In case identifiers were removed by clang-tidy, what might follow is 3076 // multiple commas in sequence - after the first identifier. 3077 while (FormatTok->is(tok::comma)) 3078 nextToken(); 3079 } 3080 } 3081 // Parse try with resource. 3082 if (Style.isJava() && FormatTok->is(tok::l_paren)) 3083 parseParens(); 3084 3085 keepAncestorBraces(); 3086 3087 if (FormatTok->is(tok::l_brace)) { 3088 if (HasCtorInitializer) 3089 FormatTok->setFinalizedType(TT_FunctionLBrace); 3090 CompoundStatementIndenter Indenter(this, Style, Line->Level); 3091 parseBlock(); 3092 if (Style.BraceWrapping.BeforeCatch) 3093 addUnwrappedLine(); 3094 else 3095 NeedsUnwrappedLine = true; 3096 } else if (FormatTok->isNot(tok::kw_catch)) { 3097 // The C++ standard requires a compound-statement after a try. 3098 // If there's none, we try to assume there's a structuralElement 3099 // and try to continue. 3100 addUnwrappedLine(); 3101 ++Line->Level; 3102 parseStructuralElement(); 3103 --Line->Level; 3104 } 3105 for (bool SeenCatch = false;;) { 3106 if (FormatTok->is(tok::at)) 3107 nextToken(); 3108 if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except, 3109 tok::kw___finally, tok::objc_catch, 3110 tok::objc_finally) || 3111 ((Style.isJava() || Style.isJavaScript()) && 3112 FormatTok->is(Keywords.kw_finally)))) { 3113 break; 3114 } 3115 if (FormatTok->is(tok::kw_catch)) 3116 SeenCatch = true; 3117 nextToken(); 3118 while (FormatTok->isNot(tok::l_brace)) { 3119 if (FormatTok->is(tok::l_paren)) { 3120 parseParens(); 3121 continue; 3122 } 3123 if (FormatTok->isOneOf(tok::semi, tok::r_brace) || eof()) { 3124 if (Style.RemoveBracesLLVM) 3125 NestedTooDeep.pop_back(); 3126 return; 3127 } 3128 nextToken(); 3129 } 3130 if (SeenCatch) { 3131 FormatTok->setFinalizedType(TT_ControlStatementLBrace); 3132 SeenCatch = false; 3133 } 3134 NeedsUnwrappedLine = false; 3135 Line->MustBeDeclaration = false; 3136 CompoundStatementIndenter Indenter(this, Style, Line->Level); 3137 parseBlock(); 3138 if (Style.BraceWrapping.BeforeCatch) 3139 addUnwrappedLine(); 3140 else 3141 NeedsUnwrappedLine = true; 3142 } 3143 3144 if (Style.RemoveBracesLLVM) 3145 NestedTooDeep.pop_back(); 3146 3147 if (NeedsUnwrappedLine) 3148 addUnwrappedLine(); 3149 } 3150 3151 void UnwrappedLineParser::parseNamespaceOrExportBlock(unsigned AddLevels) { 3152 bool ManageWhitesmithsBraces = 3153 AddLevels == 0u && Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths; 3154 3155 // If we're in Whitesmiths mode, indent the brace if we're not indenting 3156 // the whole block. 3157 if (ManageWhitesmithsBraces) 3158 ++Line->Level; 3159 3160 // Munch the semicolon after the block. This is more common than one would 3161 // think. Putting the semicolon into its own line is very ugly. 3162 parseBlock(/*MustBeDeclaration=*/true, AddLevels, /*MunchSemi=*/true, 3163 /*KeepBraces=*/true, /*IfKind=*/nullptr, ManageWhitesmithsBraces); 3164 3165 addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep); 3166 3167 if (ManageWhitesmithsBraces) 3168 --Line->Level; 3169 } 3170 3171 void UnwrappedLineParser::parseNamespace() { 3172 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) && 3173 "'namespace' expected"); 3174 3175 const FormatToken &InitialToken = *FormatTok; 3176 nextToken(); 3177 if (InitialToken.is(TT_NamespaceMacro)) { 3178 parseParens(); 3179 } else { 3180 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline, 3181 tok::l_square, tok::period, tok::l_paren) || 3182 (Style.isCSharp() && FormatTok->is(tok::kw_union))) { 3183 if (FormatTok->is(tok::l_square)) 3184 parseSquare(); 3185 else if (FormatTok->is(tok::l_paren)) 3186 parseParens(); 3187 else 3188 nextToken(); 3189 } 3190 } 3191 if (FormatTok->is(tok::l_brace)) { 3192 FormatTok->setFinalizedType(TT_NamespaceLBrace); 3193 3194 if (ShouldBreakBeforeBrace(Style, InitialToken)) 3195 addUnwrappedLine(); 3196 3197 unsigned AddLevels = 3198 Style.NamespaceIndentation == FormatStyle::NI_All || 3199 (Style.NamespaceIndentation == FormatStyle::NI_Inner && 3200 DeclarationScopeStack.size() > 1) 3201 ? 1u 3202 : 0u; 3203 parseNamespaceOrExportBlock(AddLevels); 3204 } 3205 // FIXME: Add error handling. 3206 } 3207 3208 void UnwrappedLineParser::parseCppExportBlock() { 3209 parseNamespaceOrExportBlock(/*AddLevels=*/Style.IndentExportBlock ? 1 : 0); 3210 } 3211 3212 void UnwrappedLineParser::parseNew() { 3213 assert(FormatTok->is(tok::kw_new) && "'new' expected"); 3214 nextToken(); 3215 3216 if (Style.isCSharp()) { 3217 do { 3218 // Handle constructor invocation, e.g. `new(field: value)`. 3219 if (FormatTok->is(tok::l_paren)) 3220 parseParens(); 3221 3222 // Handle array initialization syntax, e.g. `new[] {10, 20, 30}`. 3223 if (FormatTok->is(tok::l_brace)) 3224 parseBracedList(); 3225 3226 if (FormatTok->isOneOf(tok::semi, tok::comma)) 3227 return; 3228 3229 nextToken(); 3230 } while (!eof()); 3231 } 3232 3233 if (!Style.isJava()) 3234 return; 3235 3236 // In Java, we can parse everything up to the parens, which aren't optional. 3237 do { 3238 // There should not be a ;, { or } before the new's open paren. 3239 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace)) 3240 return; 3241 3242 // Consume the parens. 3243 if (FormatTok->is(tok::l_paren)) { 3244 parseParens(); 3245 3246 // If there is a class body of an anonymous class, consume that as child. 3247 if (FormatTok->is(tok::l_brace)) 3248 parseChildBlock(); 3249 return; 3250 } 3251 nextToken(); 3252 } while (!eof()); 3253 } 3254 3255 void UnwrappedLineParser::parseLoopBody(bool KeepBraces, bool WrapRightBrace) { 3256 keepAncestorBraces(); 3257 3258 if (isBlockBegin(*FormatTok)) { 3259 FormatTok->setFinalizedType(TT_ControlStatementLBrace); 3260 FormatToken *LeftBrace = FormatTok; 3261 CompoundStatementIndenter Indenter(this, Style, Line->Level); 3262 parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u, 3263 /*MunchSemi=*/true, KeepBraces); 3264 setPreviousRBraceType(TT_ControlStatementRBrace); 3265 if (!KeepBraces) { 3266 assert(!NestedTooDeep.empty()); 3267 if (!NestedTooDeep.back()) 3268 markOptionalBraces(LeftBrace); 3269 } 3270 if (WrapRightBrace) 3271 addUnwrappedLine(); 3272 } else { 3273 parseUnbracedBody(); 3274 } 3275 3276 if (!KeepBraces) 3277 NestedTooDeep.pop_back(); 3278 } 3279 3280 void UnwrappedLineParser::parseForOrWhileLoop(bool HasParens) { 3281 assert((FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) || 3282 (Style.isVerilog() && 3283 FormatTok->isOneOf(Keywords.kw_always, Keywords.kw_always_comb, 3284 Keywords.kw_always_ff, Keywords.kw_always_latch, 3285 Keywords.kw_final, Keywords.kw_initial, 3286 Keywords.kw_foreach, Keywords.kw_forever, 3287 Keywords.kw_repeat))) && 3288 "'for', 'while' or foreach macro expected"); 3289 const bool KeepBraces = !Style.RemoveBracesLLVM || 3290 !FormatTok->isOneOf(tok::kw_for, tok::kw_while); 3291 3292 nextToken(); 3293 // JS' for await ( ... 3294 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await)) 3295 nextToken(); 3296 if (IsCpp && FormatTok->is(tok::kw_co_await)) 3297 nextToken(); 3298 if (HasParens && FormatTok->is(tok::l_paren)) { 3299 // The type is only set for Verilog basically because we were afraid to 3300 // change the existing behavior for loops. See the discussion on D121756 for 3301 // details. 3302 if (Style.isVerilog()) 3303 FormatTok->setFinalizedType(TT_ConditionLParen); 3304 parseParens(); 3305 } 3306 3307 if (Style.isVerilog()) { 3308 // Event control. 3309 parseVerilogSensitivityList(); 3310 } else if (Style.AllowShortLoopsOnASingleLine && FormatTok->is(tok::semi) && 3311 Tokens->getPreviousToken()->is(tok::r_paren)) { 3312 nextToken(); 3313 addUnwrappedLine(); 3314 return; 3315 } 3316 3317 handleAttributes(); 3318 parseLoopBody(KeepBraces, /*WrapRightBrace=*/true); 3319 } 3320 3321 void UnwrappedLineParser::parseDoWhile() { 3322 assert(FormatTok->is(tok::kw_do) && "'do' expected"); 3323 nextToken(); 3324 3325 parseLoopBody(/*KeepBraces=*/true, Style.BraceWrapping.BeforeWhile); 3326 3327 // FIXME: Add error handling. 3328 if (FormatTok->isNot(tok::kw_while)) { 3329 addUnwrappedLine(); 3330 return; 3331 } 3332 3333 FormatTok->setFinalizedType(TT_DoWhile); 3334 3335 // If in Whitesmiths mode, the line with the while() needs to be indented 3336 // to the same level as the block. 3337 if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) 3338 ++Line->Level; 3339 3340 nextToken(); 3341 parseStructuralElement(); 3342 } 3343 3344 void UnwrappedLineParser::parseLabel(bool LeftAlignLabel) { 3345 nextToken(); 3346 unsigned OldLineLevel = Line->Level; 3347 3348 if (LeftAlignLabel) 3349 Line->Level = 0; 3350 else if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0)) 3351 --Line->Level; 3352 3353 if (!Style.IndentCaseBlocks && CommentsBeforeNextToken.empty() && 3354 FormatTok->is(tok::l_brace)) { 3355 3356 CompoundStatementIndenter Indenter(this, Line->Level, 3357 Style.BraceWrapping.AfterCaseLabel, 3358 Style.BraceWrapping.IndentBraces); 3359 parseBlock(); 3360 if (FormatTok->is(tok::kw_break)) { 3361 if (Style.BraceWrapping.AfterControlStatement == 3362 FormatStyle::BWACS_Always) { 3363 addUnwrappedLine(); 3364 if (!Style.IndentCaseBlocks && 3365 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) { 3366 ++Line->Level; 3367 } 3368 } 3369 parseStructuralElement(); 3370 } 3371 addUnwrappedLine(); 3372 } else { 3373 if (FormatTok->is(tok::semi)) 3374 nextToken(); 3375 addUnwrappedLine(); 3376 } 3377 Line->Level = OldLineLevel; 3378 if (FormatTok->isNot(tok::l_brace)) { 3379 parseStructuralElement(); 3380 addUnwrappedLine(); 3381 } 3382 } 3383 3384 void UnwrappedLineParser::parseCaseLabel() { 3385 assert(FormatTok->is(tok::kw_case) && "'case' expected"); 3386 auto *Case = FormatTok; 3387 3388 // FIXME: fix handling of complex expressions here. 3389 do { 3390 nextToken(); 3391 if (FormatTok->is(tok::colon)) { 3392 FormatTok->setFinalizedType(TT_CaseLabelColon); 3393 break; 3394 } 3395 if (Style.isJava() && FormatTok->is(tok::arrow)) { 3396 FormatTok->setFinalizedType(TT_CaseLabelArrow); 3397 Case->setFinalizedType(TT_SwitchExpressionLabel); 3398 break; 3399 } 3400 } while (!eof()); 3401 parseLabel(); 3402 } 3403 3404 void UnwrappedLineParser::parseSwitch(bool IsExpr) { 3405 assert(FormatTok->is(tok::kw_switch) && "'switch' expected"); 3406 nextToken(); 3407 if (FormatTok->is(tok::l_paren)) 3408 parseParens(); 3409 3410 keepAncestorBraces(); 3411 3412 if (FormatTok->is(tok::l_brace)) { 3413 CompoundStatementIndenter Indenter(this, Style, Line->Level); 3414 FormatTok->setFinalizedType(IsExpr ? TT_SwitchExpressionLBrace 3415 : TT_ControlStatementLBrace); 3416 if (IsExpr) 3417 parseChildBlock(); 3418 else 3419 parseBlock(); 3420 setPreviousRBraceType(TT_ControlStatementRBrace); 3421 if (!IsExpr) 3422 addUnwrappedLine(); 3423 } else { 3424 addUnwrappedLine(); 3425 ++Line->Level; 3426 parseStructuralElement(); 3427 --Line->Level; 3428 } 3429 3430 if (Style.RemoveBracesLLVM) 3431 NestedTooDeep.pop_back(); 3432 } 3433 3434 void UnwrappedLineParser::parseAccessSpecifier() { 3435 nextToken(); 3436 // Understand Qt's slots. 3437 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots)) 3438 nextToken(); 3439 // Otherwise, we don't know what it is, and we'd better keep the next token. 3440 if (FormatTok->is(tok::colon)) 3441 nextToken(); 3442 addUnwrappedLine(); 3443 } 3444 3445 /// Parses a requires, decides if it is a clause or an expression. 3446 /// \pre The current token has to be the requires keyword. 3447 /// \returns true if it parsed a clause. 3448 bool UnwrappedLineParser::parseRequires(bool SeenEqual) { 3449 assert(FormatTok->is(tok::kw_requires) && "'requires' expected"); 3450 auto RequiresToken = FormatTok; 3451 3452 // We try to guess if it is a requires clause, or a requires expression. For 3453 // that we first consume the keyword and check the next token. 3454 nextToken(); 3455 3456 switch (FormatTok->Tok.getKind()) { 3457 case tok::l_brace: 3458 // This can only be an expression, never a clause. 3459 parseRequiresExpression(RequiresToken); 3460 return false; 3461 case tok::l_paren: 3462 // Clauses and expression can start with a paren, it's unclear what we have. 3463 break; 3464 default: 3465 // All other tokens can only be a clause. 3466 parseRequiresClause(RequiresToken); 3467 return true; 3468 } 3469 3470 // Looking forward we would have to decide if there are function declaration 3471 // like arguments to the requires expression: 3472 // requires (T t) { 3473 // Or there is a constraint expression for the requires clause: 3474 // requires (C<T> && ... 3475 3476 // But first let's look behind. 3477 auto *PreviousNonComment = RequiresToken->getPreviousNonComment(); 3478 3479 if (!PreviousNonComment || 3480 PreviousNonComment->is(TT_RequiresExpressionLBrace)) { 3481 // If there is no token, or an expression left brace, we are a requires 3482 // clause within a requires expression. 3483 parseRequiresClause(RequiresToken); 3484 return true; 3485 } 3486 3487 switch (PreviousNonComment->Tok.getKind()) { 3488 case tok::greater: 3489 case tok::r_paren: 3490 case tok::kw_noexcept: 3491 case tok::kw_const: 3492 case tok::star: 3493 case tok::amp: 3494 // This is a requires clause. 3495 parseRequiresClause(RequiresToken); 3496 return true; 3497 case tok::ampamp: { 3498 // This can be either: 3499 // if (... && requires (T t) ...) 3500 // Or 3501 // void member(...) && requires (C<T> ... 3502 // We check the one token before that for a const: 3503 // void member(...) const && requires (C<T> ... 3504 auto PrevPrev = PreviousNonComment->getPreviousNonComment(); 3505 if ((PrevPrev && PrevPrev->is(tok::kw_const)) || !SeenEqual) { 3506 parseRequiresClause(RequiresToken); 3507 return true; 3508 } 3509 break; 3510 } 3511 default: 3512 if (PreviousNonComment->isTypeOrIdentifier(LangOpts)) { 3513 // This is a requires clause. 3514 parseRequiresClause(RequiresToken); 3515 return true; 3516 } 3517 // It's an expression. 3518 parseRequiresExpression(RequiresToken); 3519 return false; 3520 } 3521 3522 // Now we look forward and try to check if the paren content is a parameter 3523 // list. The parameters can be cv-qualified and contain references or 3524 // pointers. 3525 // So we want basically to check for TYPE NAME, but TYPE can contain all kinds 3526 // of stuff: typename, const, *, &, &&, ::, identifiers. 3527 3528 unsigned StoredPosition = Tokens->getPosition(); 3529 FormatToken *NextToken = Tokens->getNextToken(); 3530 int Lookahead = 0; 3531 auto PeekNext = [&Lookahead, &NextToken, this] { 3532 ++Lookahead; 3533 NextToken = Tokens->getNextToken(); 3534 }; 3535 3536 bool FoundType = false; 3537 bool LastWasColonColon = false; 3538 int OpenAngles = 0; 3539 3540 for (; Lookahead < 50; PeekNext()) { 3541 switch (NextToken->Tok.getKind()) { 3542 case tok::kw_volatile: 3543 case tok::kw_const: 3544 case tok::comma: 3545 if (OpenAngles == 0) { 3546 FormatTok = Tokens->setPosition(StoredPosition); 3547 parseRequiresExpression(RequiresToken); 3548 return false; 3549 } 3550 break; 3551 case tok::eof: 3552 // Break out of the loop. 3553 Lookahead = 50; 3554 break; 3555 case tok::coloncolon: 3556 LastWasColonColon = true; 3557 break; 3558 case tok::kw_decltype: 3559 case tok::identifier: 3560 if (FoundType && !LastWasColonColon && OpenAngles == 0) { 3561 FormatTok = Tokens->setPosition(StoredPosition); 3562 parseRequiresExpression(RequiresToken); 3563 return false; 3564 } 3565 FoundType = true; 3566 LastWasColonColon = false; 3567 break; 3568 case tok::less: 3569 ++OpenAngles; 3570 break; 3571 case tok::greater: 3572 --OpenAngles; 3573 break; 3574 default: 3575 if (NextToken->isTypeName(LangOpts)) { 3576 FormatTok = Tokens->setPosition(StoredPosition); 3577 parseRequiresExpression(RequiresToken); 3578 return false; 3579 } 3580 break; 3581 } 3582 } 3583 // This seems to be a complicated expression, just assume it's a clause. 3584 FormatTok = Tokens->setPosition(StoredPosition); 3585 parseRequiresClause(RequiresToken); 3586 return true; 3587 } 3588 3589 /// Parses a requires clause. 3590 /// \param RequiresToken The requires keyword token, which starts this clause. 3591 /// \pre We need to be on the next token after the requires keyword. 3592 /// \sa parseRequiresExpression 3593 /// 3594 /// Returns if it either has finished parsing the clause, or it detects, that 3595 /// the clause is incorrect. 3596 void UnwrappedLineParser::parseRequiresClause(FormatToken *RequiresToken) { 3597 assert(FormatTok->getPreviousNonComment() == RequiresToken); 3598 assert(RequiresToken->is(tok::kw_requires) && "'requires' expected"); 3599 3600 // If there is no previous token, we are within a requires expression, 3601 // otherwise we will always have the template or function declaration in front 3602 // of it. 3603 bool InRequiresExpression = 3604 !RequiresToken->Previous || 3605 RequiresToken->Previous->is(TT_RequiresExpressionLBrace); 3606 3607 RequiresToken->setFinalizedType(InRequiresExpression 3608 ? TT_RequiresClauseInARequiresExpression 3609 : TT_RequiresClause); 3610 3611 // NOTE: parseConstraintExpression is only ever called from this function. 3612 // It could be inlined into here. 3613 parseConstraintExpression(); 3614 3615 if (!InRequiresExpression && FormatTok->Previous) 3616 FormatTok->Previous->ClosesRequiresClause = true; 3617 } 3618 3619 /// Parses a requires expression. 3620 /// \param RequiresToken The requires keyword token, which starts this clause. 3621 /// \pre We need to be on the next token after the requires keyword. 3622 /// \sa parseRequiresClause 3623 /// 3624 /// Returns if it either has finished parsing the expression, or it detects, 3625 /// that the expression is incorrect. 3626 void UnwrappedLineParser::parseRequiresExpression(FormatToken *RequiresToken) { 3627 assert(FormatTok->getPreviousNonComment() == RequiresToken); 3628 assert(RequiresToken->is(tok::kw_requires) && "'requires' expected"); 3629 3630 RequiresToken->setFinalizedType(TT_RequiresExpression); 3631 3632 if (FormatTok->is(tok::l_paren)) { 3633 FormatTok->setFinalizedType(TT_RequiresExpressionLParen); 3634 parseParens(); 3635 } 3636 3637 if (FormatTok->is(tok::l_brace)) { 3638 FormatTok->setFinalizedType(TT_RequiresExpressionLBrace); 3639 parseChildBlock(); 3640 } 3641 } 3642 3643 /// Parses a constraint expression. 3644 /// 3645 /// This is the body of a requires clause. It returns, when the parsing is 3646 /// complete, or the expression is incorrect. 3647 void UnwrappedLineParser::parseConstraintExpression() { 3648 // The special handling for lambdas is needed since tryToParseLambda() eats a 3649 // token and if a requires expression is the last part of a requires clause 3650 // and followed by an attribute like [[nodiscard]] the ClosesRequiresClause is 3651 // not set on the correct token. Thus we need to be aware if we even expect a 3652 // lambda to be possible. 3653 // template <typename T> requires requires { ... } [[nodiscard]] ...; 3654 bool LambdaNextTimeAllowed = true; 3655 3656 // Within lambda declarations, it is permitted to put a requires clause after 3657 // its template parameter list, which would place the requires clause right 3658 // before the parentheses of the parameters of the lambda declaration. Thus, 3659 // we track if we expect to see grouping parentheses at all. 3660 // Without this check, `requires foo<T> (T t)` in the below example would be 3661 // seen as the whole requires clause, accidentally eating the parameters of 3662 // the lambda. 3663 // [&]<typename T> requires foo<T> (T t) { ... }; 3664 bool TopLevelParensAllowed = true; 3665 3666 do { 3667 bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed, false); 3668 3669 switch (FormatTok->Tok.getKind()) { 3670 case tok::kw_requires: { 3671 auto RequiresToken = FormatTok; 3672 nextToken(); 3673 parseRequiresExpression(RequiresToken); 3674 break; 3675 } 3676 3677 case tok::l_paren: 3678 if (!TopLevelParensAllowed) 3679 return; 3680 parseParens(/*AmpAmpTokenType=*/TT_BinaryOperator); 3681 TopLevelParensAllowed = false; 3682 break; 3683 3684 case tok::l_square: 3685 if (!LambdaThisTimeAllowed || !tryToParseLambda()) 3686 return; 3687 break; 3688 3689 case tok::kw_const: 3690 case tok::semi: 3691 case tok::kw_class: 3692 case tok::kw_struct: 3693 case tok::kw_union: 3694 return; 3695 3696 case tok::l_brace: 3697 // Potential function body. 3698 return; 3699 3700 case tok::ampamp: 3701 case tok::pipepipe: 3702 FormatTok->setFinalizedType(TT_BinaryOperator); 3703 nextToken(); 3704 LambdaNextTimeAllowed = true; 3705 TopLevelParensAllowed = true; 3706 break; 3707 3708 case tok::comma: 3709 case tok::comment: 3710 LambdaNextTimeAllowed = LambdaThisTimeAllowed; 3711 nextToken(); 3712 break; 3713 3714 case tok::kw_sizeof: 3715 case tok::greater: 3716 case tok::greaterequal: 3717 case tok::greatergreater: 3718 case tok::less: 3719 case tok::lessequal: 3720 case tok::lessless: 3721 case tok::equalequal: 3722 case tok::exclaim: 3723 case tok::exclaimequal: 3724 case tok::plus: 3725 case tok::minus: 3726 case tok::star: 3727 case tok::slash: 3728 LambdaNextTimeAllowed = true; 3729 TopLevelParensAllowed = true; 3730 // Just eat them. 3731 nextToken(); 3732 break; 3733 3734 case tok::numeric_constant: 3735 case tok::coloncolon: 3736 case tok::kw_true: 3737 case tok::kw_false: 3738 TopLevelParensAllowed = false; 3739 // Just eat them. 3740 nextToken(); 3741 break; 3742 3743 case tok::kw_static_cast: 3744 case tok::kw_const_cast: 3745 case tok::kw_reinterpret_cast: 3746 case tok::kw_dynamic_cast: 3747 nextToken(); 3748 if (FormatTok->isNot(tok::less)) 3749 return; 3750 3751 nextToken(); 3752 parseBracedList(/*IsAngleBracket=*/true); 3753 break; 3754 3755 default: 3756 if (!FormatTok->Tok.getIdentifierInfo()) { 3757 // Identifiers are part of the default case, we check for more then 3758 // tok::identifier to handle builtin type traits. 3759 return; 3760 } 3761 3762 // We need to differentiate identifiers for a template deduction guide, 3763 // variables, or function return types (the constraint expression has 3764 // ended before that), and basically all other cases. But it's easier to 3765 // check the other way around. 3766 assert(FormatTok->Previous); 3767 switch (FormatTok->Previous->Tok.getKind()) { 3768 case tok::coloncolon: // Nested identifier. 3769 case tok::ampamp: // Start of a function or variable for the 3770 case tok::pipepipe: // constraint expression. (binary) 3771 case tok::exclaim: // The same as above, but unary. 3772 case tok::kw_requires: // Initial identifier of a requires clause. 3773 case tok::equal: // Initial identifier of a concept declaration. 3774 break; 3775 default: 3776 return; 3777 } 3778 3779 // Read identifier with optional template declaration. 3780 nextToken(); 3781 if (FormatTok->is(tok::less)) { 3782 nextToken(); 3783 parseBracedList(/*IsAngleBracket=*/true); 3784 } 3785 TopLevelParensAllowed = false; 3786 break; 3787 } 3788 } while (!eof()); 3789 } 3790 3791 bool UnwrappedLineParser::parseEnum() { 3792 const FormatToken &InitialToken = *FormatTok; 3793 3794 // Won't be 'enum' for NS_ENUMs. 3795 if (FormatTok->is(tok::kw_enum)) 3796 nextToken(); 3797 3798 // In TypeScript, "enum" can also be used as property name, e.g. in interface 3799 // declarations. An "enum" keyword followed by a colon would be a syntax 3800 // error and thus assume it is just an identifier. 3801 if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question)) 3802 return false; 3803 3804 // In protobuf, "enum" can be used as a field name. 3805 if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal)) 3806 return false; 3807 3808 if (IsCpp) { 3809 // Eat up enum class ... 3810 if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct)) 3811 nextToken(); 3812 while (FormatTok->is(tok::l_square)) 3813 if (!handleCppAttributes()) 3814 return false; 3815 } 3816 3817 while (FormatTok->Tok.getIdentifierInfo() || 3818 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less, 3819 tok::greater, tok::comma, tok::question, 3820 tok::l_square)) { 3821 if (Style.isVerilog()) { 3822 FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName); 3823 nextToken(); 3824 // In Verilog the base type can have dimensions. 3825 while (FormatTok->is(tok::l_square)) 3826 parseSquare(); 3827 } else { 3828 nextToken(); 3829 } 3830 // We can have macros or attributes in between 'enum' and the enum name. 3831 if (FormatTok->is(tok::l_paren)) 3832 parseParens(); 3833 if (FormatTok->is(tok::identifier)) { 3834 nextToken(); 3835 // If there are two identifiers in a row, this is likely an elaborate 3836 // return type. In Java, this can be "implements", etc. 3837 if (IsCpp && FormatTok->is(tok::identifier)) 3838 return false; 3839 } 3840 } 3841 3842 // Just a declaration or something is wrong. 3843 if (FormatTok->isNot(tok::l_brace)) 3844 return true; 3845 FormatTok->setFinalizedType(TT_EnumLBrace); 3846 FormatTok->setBlockKind(BK_Block); 3847 3848 if (Style.isJava()) { 3849 // Java enums are different. 3850 parseJavaEnumBody(); 3851 return true; 3852 } 3853 if (Style.Language == FormatStyle::LK_Proto) { 3854 parseBlock(/*MustBeDeclaration=*/true); 3855 return true; 3856 } 3857 3858 if (!Style.AllowShortEnumsOnASingleLine && 3859 ShouldBreakBeforeBrace(Style, InitialToken)) { 3860 addUnwrappedLine(); 3861 } 3862 // Parse enum body. 3863 nextToken(); 3864 if (!Style.AllowShortEnumsOnASingleLine) { 3865 addUnwrappedLine(); 3866 Line->Level += 1; 3867 } 3868 bool HasError = !parseBracedList(/*IsAngleBracket=*/false, /*IsEnum=*/true); 3869 if (!Style.AllowShortEnumsOnASingleLine) 3870 Line->Level -= 1; 3871 if (HasError) { 3872 if (FormatTok->is(tok::semi)) 3873 nextToken(); 3874 addUnwrappedLine(); 3875 } 3876 setPreviousRBraceType(TT_EnumRBrace); 3877 return true; 3878 3879 // There is no addUnwrappedLine() here so that we fall through to parsing a 3880 // structural element afterwards. Thus, in "enum A {} n, m;", 3881 // "} n, m;" will end up in one unwrapped line. 3882 } 3883 3884 bool UnwrappedLineParser::parseStructLike() { 3885 // parseRecord falls through and does not yet add an unwrapped line as a 3886 // record declaration or definition can start a structural element. 3887 parseRecord(); 3888 // This does not apply to Java, JavaScript and C#. 3889 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp()) { 3890 if (FormatTok->is(tok::semi)) 3891 nextToken(); 3892 addUnwrappedLine(); 3893 return true; 3894 } 3895 return false; 3896 } 3897 3898 namespace { 3899 // A class used to set and restore the Token position when peeking 3900 // ahead in the token source. 3901 class ScopedTokenPosition { 3902 unsigned StoredPosition; 3903 FormatTokenSource *Tokens; 3904 3905 public: 3906 ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) { 3907 assert(Tokens && "Tokens expected to not be null"); 3908 StoredPosition = Tokens->getPosition(); 3909 } 3910 3911 ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); } 3912 }; 3913 } // namespace 3914 3915 // Look to see if we have [[ by looking ahead, if 3916 // its not then rewind to the original position. 3917 bool UnwrappedLineParser::tryToParseSimpleAttribute() { 3918 ScopedTokenPosition AutoPosition(Tokens); 3919 FormatToken *Tok = Tokens->getNextToken(); 3920 // We already read the first [ check for the second. 3921 if (Tok->isNot(tok::l_square)) 3922 return false; 3923 // Double check that the attribute is just something 3924 // fairly simple. 3925 while (Tok->isNot(tok::eof)) { 3926 if (Tok->is(tok::r_square)) 3927 break; 3928 Tok = Tokens->getNextToken(); 3929 } 3930 if (Tok->is(tok::eof)) 3931 return false; 3932 Tok = Tokens->getNextToken(); 3933 if (Tok->isNot(tok::r_square)) 3934 return false; 3935 Tok = Tokens->getNextToken(); 3936 if (Tok->is(tok::semi)) 3937 return false; 3938 return true; 3939 } 3940 3941 void UnwrappedLineParser::parseJavaEnumBody() { 3942 assert(FormatTok->is(tok::l_brace)); 3943 const FormatToken *OpeningBrace = FormatTok; 3944 3945 // Determine whether the enum is simple, i.e. does not have a semicolon or 3946 // constants with class bodies. Simple enums can be formatted like braced 3947 // lists, contracted to a single line, etc. 3948 unsigned StoredPosition = Tokens->getPosition(); 3949 bool IsSimple = true; 3950 FormatToken *Tok = Tokens->getNextToken(); 3951 while (Tok->isNot(tok::eof)) { 3952 if (Tok->is(tok::r_brace)) 3953 break; 3954 if (Tok->isOneOf(tok::l_brace, tok::semi)) { 3955 IsSimple = false; 3956 break; 3957 } 3958 // FIXME: This will also mark enums with braces in the arguments to enum 3959 // constants as "not simple". This is probably fine in practice, though. 3960 Tok = Tokens->getNextToken(); 3961 } 3962 FormatTok = Tokens->setPosition(StoredPosition); 3963 3964 if (IsSimple) { 3965 nextToken(); 3966 parseBracedList(); 3967 addUnwrappedLine(); 3968 return; 3969 } 3970 3971 // Parse the body of a more complex enum. 3972 // First add a line for everything up to the "{". 3973 nextToken(); 3974 addUnwrappedLine(); 3975 ++Line->Level; 3976 3977 // Parse the enum constants. 3978 while (!eof()) { 3979 if (FormatTok->is(tok::l_brace)) { 3980 // Parse the constant's class body. 3981 parseBlock(/*MustBeDeclaration=*/true, /*AddLevels=*/1u, 3982 /*MunchSemi=*/false); 3983 } else if (FormatTok->is(tok::l_paren)) { 3984 parseParens(); 3985 } else if (FormatTok->is(tok::comma)) { 3986 nextToken(); 3987 addUnwrappedLine(); 3988 } else if (FormatTok->is(tok::semi)) { 3989 nextToken(); 3990 addUnwrappedLine(); 3991 break; 3992 } else if (FormatTok->is(tok::r_brace)) { 3993 addUnwrappedLine(); 3994 break; 3995 } else { 3996 nextToken(); 3997 } 3998 } 3999 4000 // Parse the class body after the enum's ";" if any. 4001 parseLevel(OpeningBrace); 4002 nextToken(); 4003 --Line->Level; 4004 addUnwrappedLine(); 4005 } 4006 4007 void UnwrappedLineParser::parseRecord(bool ParseAsExpr, bool IsJavaRecord) { 4008 assert(!IsJavaRecord || FormatTok->is(Keywords.kw_record)); 4009 const FormatToken &InitialToken = *FormatTok; 4010 nextToken(); 4011 4012 FormatToken *ClassName = 4013 IsJavaRecord && FormatTok->is(tok::identifier) ? FormatTok : nullptr; 4014 bool IsDerived = false; 4015 auto IsNonMacroIdentifier = [](const FormatToken *Tok) { 4016 return Tok->is(tok::identifier) && Tok->TokenText != Tok->TokenText.upper(); 4017 }; 4018 // JavaScript/TypeScript supports anonymous classes like: 4019 // a = class extends foo { } 4020 bool JSPastExtendsOrImplements = false; 4021 // The actual identifier can be a nested name specifier, and in macros 4022 // it is often token-pasted. 4023 // An [[attribute]] can be before the identifier. 4024 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash, 4025 tok::kw_alignas, tok::l_square) || 4026 FormatTok->isAttribute() || 4027 ((Style.isJava() || Style.isJavaScript()) && 4028 FormatTok->isOneOf(tok::period, tok::comma))) { 4029 if (Style.isJavaScript() && 4030 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) { 4031 JSPastExtendsOrImplements = true; 4032 // JavaScript/TypeScript supports inline object types in 4033 // extends/implements positions: 4034 // class Foo implements {bar: number} { } 4035 nextToken(); 4036 if (FormatTok->is(tok::l_brace)) { 4037 tryToParseBracedList(); 4038 continue; 4039 } 4040 } 4041 if (FormatTok->is(tok::l_square) && handleCppAttributes()) 4042 continue; 4043 auto *Previous = FormatTok; 4044 nextToken(); 4045 switch (FormatTok->Tok.getKind()) { 4046 case tok::l_paren: 4047 // We can have macros in between 'class' and the class name. 4048 if (IsJavaRecord || !IsNonMacroIdentifier(Previous) || 4049 // e.g. `struct macro(a) S { int i; };` 4050 Previous->Previous == &InitialToken) { 4051 parseParens(); 4052 } 4053 break; 4054 case tok::coloncolon: 4055 case tok::hashhash: 4056 break; 4057 default: 4058 if (JSPastExtendsOrImplements || ClassName || 4059 Previous->isNot(tok::identifier) || Previous->is(TT_AttributeMacro)) { 4060 break; 4061 } 4062 if (const auto Text = Previous->TokenText; 4063 Text.size() == 1 || Text != Text.upper()) { 4064 ClassName = Previous; 4065 } 4066 } 4067 } 4068 4069 auto IsListInitialization = [&] { 4070 if (!ClassName || IsDerived || JSPastExtendsOrImplements) 4071 return false; 4072 assert(FormatTok->is(tok::l_brace)); 4073 const auto *Prev = FormatTok->getPreviousNonComment(); 4074 assert(Prev); 4075 return Prev != ClassName && Prev->is(tok::identifier) && 4076 Prev->isNot(Keywords.kw_final) && tryToParseBracedList(); 4077 }; 4078 4079 if (FormatTok->isOneOf(tok::colon, tok::less)) { 4080 int AngleNestingLevel = 0; 4081 do { 4082 if (FormatTok->is(tok::less)) 4083 ++AngleNestingLevel; 4084 else if (FormatTok->is(tok::greater)) 4085 --AngleNestingLevel; 4086 4087 if (AngleNestingLevel == 0) { 4088 if (FormatTok->is(tok::colon)) { 4089 IsDerived = true; 4090 } else if (!IsDerived && FormatTok->is(tok::identifier) && 4091 FormatTok->Previous->is(tok::coloncolon)) { 4092 ClassName = FormatTok; 4093 } else if (FormatTok->is(tok::l_paren) && 4094 IsNonMacroIdentifier(FormatTok->Previous)) { 4095 break; 4096 } 4097 } 4098 if (FormatTok->is(tok::l_brace)) { 4099 if (AngleNestingLevel == 0 && IsListInitialization()) 4100 return; 4101 calculateBraceTypes(/*ExpectClassBody=*/true); 4102 if (!tryToParseBracedList()) 4103 break; 4104 } 4105 if (FormatTok->is(tok::l_square)) { 4106 FormatToken *Previous = FormatTok->Previous; 4107 if (!Previous || (Previous->isNot(tok::r_paren) && 4108 !Previous->isTypeOrIdentifier(LangOpts))) { 4109 // Don't try parsing a lambda if we had a closing parenthesis before, 4110 // it was probably a pointer to an array: int (*)[]. 4111 if (!tryToParseLambda()) 4112 continue; 4113 } else { 4114 parseSquare(); 4115 continue; 4116 } 4117 } 4118 if (FormatTok->is(tok::semi)) 4119 return; 4120 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) { 4121 addUnwrappedLine(); 4122 nextToken(); 4123 parseCSharpGenericTypeConstraint(); 4124 break; 4125 } 4126 nextToken(); 4127 } while (!eof()); 4128 } 4129 4130 auto GetBraceTypes = 4131 [](const FormatToken &RecordTok) -> std::pair<TokenType, TokenType> { 4132 switch (RecordTok.Tok.getKind()) { 4133 case tok::kw_class: 4134 return {TT_ClassLBrace, TT_ClassRBrace}; 4135 case tok::kw_struct: 4136 return {TT_StructLBrace, TT_StructRBrace}; 4137 case tok::kw_union: 4138 return {TT_UnionLBrace, TT_UnionRBrace}; 4139 default: 4140 // Useful for e.g. interface. 4141 return {TT_RecordLBrace, TT_RecordRBrace}; 4142 } 4143 }; 4144 if (FormatTok->is(tok::l_brace)) { 4145 if (IsListInitialization()) 4146 return; 4147 if (ClassName) 4148 ClassName->setFinalizedType(TT_ClassHeadName); 4149 auto [OpenBraceType, ClosingBraceType] = GetBraceTypes(InitialToken); 4150 FormatTok->setFinalizedType(OpenBraceType); 4151 if (ParseAsExpr) { 4152 parseChildBlock(); 4153 } else { 4154 if (ShouldBreakBeforeBrace(Style, InitialToken)) 4155 addUnwrappedLine(); 4156 4157 unsigned AddLevels = Style.IndentAccessModifiers ? 2u : 1u; 4158 parseBlock(/*MustBeDeclaration=*/true, AddLevels, /*MunchSemi=*/false); 4159 } 4160 setPreviousRBraceType(ClosingBraceType); 4161 } 4162 // There is no addUnwrappedLine() here so that we fall through to parsing a 4163 // structural element afterwards. Thus, in "class A {} n, m;", 4164 // "} n, m;" will end up in one unwrapped line. 4165 } 4166 4167 void UnwrappedLineParser::parseObjCMethod() { 4168 assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) && 4169 "'(' or identifier expected."); 4170 do { 4171 if (FormatTok->is(tok::semi)) { 4172 nextToken(); 4173 addUnwrappedLine(); 4174 return; 4175 } else if (FormatTok->is(tok::l_brace)) { 4176 if (Style.BraceWrapping.AfterFunction) 4177 addUnwrappedLine(); 4178 parseBlock(); 4179 addUnwrappedLine(); 4180 return; 4181 } else { 4182 nextToken(); 4183 } 4184 } while (!eof()); 4185 } 4186 4187 void UnwrappedLineParser::parseObjCProtocolList() { 4188 assert(FormatTok->is(tok::less) && "'<' expected."); 4189 do { 4190 nextToken(); 4191 // Early exit in case someone forgot a close angle. 4192 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end)) 4193 return; 4194 } while (!eof() && FormatTok->isNot(tok::greater)); 4195 nextToken(); // Skip '>'. 4196 } 4197 4198 void UnwrappedLineParser::parseObjCUntilAtEnd() { 4199 do { 4200 if (FormatTok->is(tok::objc_end)) { 4201 nextToken(); 4202 addUnwrappedLine(); 4203 break; 4204 } 4205 if (FormatTok->is(tok::l_brace)) { 4206 parseBlock(); 4207 // In ObjC interfaces, nothing should be following the "}". 4208 addUnwrappedLine(); 4209 } else if (FormatTok->is(tok::r_brace)) { 4210 // Ignore stray "}". parseStructuralElement doesn't consume them. 4211 nextToken(); 4212 addUnwrappedLine(); 4213 } else if (FormatTok->isOneOf(tok::minus, tok::plus)) { 4214 nextToken(); 4215 parseObjCMethod(); 4216 } else { 4217 parseStructuralElement(); 4218 } 4219 } while (!eof()); 4220 } 4221 4222 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() { 4223 assert(FormatTok->isOneOf(tok::objc_interface, tok::objc_implementation)); 4224 nextToken(); 4225 nextToken(); // interface name 4226 4227 // @interface can be followed by a lightweight generic 4228 // specialization list, then either a base class or a category. 4229 if (FormatTok->is(tok::less)) 4230 parseObjCLightweightGenerics(); 4231 if (FormatTok->is(tok::colon)) { 4232 nextToken(); 4233 nextToken(); // base class name 4234 // The base class can also have lightweight generics applied to it. 4235 if (FormatTok->is(tok::less)) 4236 parseObjCLightweightGenerics(); 4237 } else if (FormatTok->is(tok::l_paren)) { 4238 // Skip category, if present. 4239 parseParens(); 4240 } 4241 4242 if (FormatTok->is(tok::less)) 4243 parseObjCProtocolList(); 4244 4245 if (FormatTok->is(tok::l_brace)) { 4246 if (Style.BraceWrapping.AfterObjCDeclaration) 4247 addUnwrappedLine(); 4248 parseBlock(/*MustBeDeclaration=*/true); 4249 } 4250 4251 // With instance variables, this puts '}' on its own line. Without instance 4252 // variables, this ends the @interface line. 4253 addUnwrappedLine(); 4254 4255 parseObjCUntilAtEnd(); 4256 } 4257 4258 void UnwrappedLineParser::parseObjCLightweightGenerics() { 4259 assert(FormatTok->is(tok::less)); 4260 // Unlike protocol lists, generic parameterizations support 4261 // nested angles: 4262 // 4263 // @interface Foo<ValueType : id <NSCopying, NSSecureCoding>> : 4264 // NSObject <NSCopying, NSSecureCoding> 4265 // 4266 // so we need to count how many open angles we have left. 4267 unsigned NumOpenAngles = 1; 4268 do { 4269 nextToken(); 4270 // Early exit in case someone forgot a close angle. 4271 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end)) 4272 break; 4273 if (FormatTok->is(tok::less)) { 4274 ++NumOpenAngles; 4275 } else if (FormatTok->is(tok::greater)) { 4276 assert(NumOpenAngles > 0 && "'>' makes NumOpenAngles negative"); 4277 --NumOpenAngles; 4278 } 4279 } while (!eof() && NumOpenAngles != 0); 4280 nextToken(); // Skip '>'. 4281 } 4282 4283 // Returns true for the declaration/definition form of @protocol, 4284 // false for the expression form. 4285 bool UnwrappedLineParser::parseObjCProtocol() { 4286 assert(FormatTok->is(tok::objc_protocol)); 4287 nextToken(); 4288 4289 if (FormatTok->is(tok::l_paren)) { 4290 // The expression form of @protocol, e.g. "Protocol* p = @protocol(foo);". 4291 return false; 4292 } 4293 4294 // The definition/declaration form, 4295 // @protocol Foo 4296 // - (int)someMethod; 4297 // @end 4298 4299 nextToken(); // protocol name 4300 4301 if (FormatTok->is(tok::less)) 4302 parseObjCProtocolList(); 4303 4304 // Check for protocol declaration. 4305 if (FormatTok->is(tok::semi)) { 4306 nextToken(); 4307 addUnwrappedLine(); 4308 return true; 4309 } 4310 4311 addUnwrappedLine(); 4312 parseObjCUntilAtEnd(); 4313 return true; 4314 } 4315 4316 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() { 4317 bool IsImport = FormatTok->is(Keywords.kw_import); 4318 assert(IsImport || FormatTok->is(tok::kw_export)); 4319 nextToken(); 4320 4321 // Consume the "default" in "export default class/function". 4322 if (FormatTok->is(tok::kw_default)) 4323 nextToken(); 4324 4325 // Consume "async function", "function" and "default function", so that these 4326 // get parsed as free-standing JS functions, i.e. do not require a trailing 4327 // semicolon. 4328 if (FormatTok->is(Keywords.kw_async)) 4329 nextToken(); 4330 if (FormatTok->is(Keywords.kw_function)) { 4331 nextToken(); 4332 return; 4333 } 4334 4335 // For imports, `export *`, `export {...}`, consume the rest of the line up 4336 // to the terminating `;`. For everything else, just return and continue 4337 // parsing the structural element, i.e. the declaration or expression for 4338 // `export default`. 4339 if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) && 4340 !FormatTok->isStringLiteral() && 4341 !(FormatTok->is(Keywords.kw_type) && 4342 Tokens->peekNextToken()->isOneOf(tok::l_brace, tok::star))) { 4343 return; 4344 } 4345 4346 while (!eof()) { 4347 if (FormatTok->is(tok::semi)) 4348 return; 4349 if (Line->Tokens.empty()) { 4350 // Common issue: Automatic Semicolon Insertion wrapped the line, so the 4351 // import statement should terminate. 4352 return; 4353 } 4354 if (FormatTok->is(tok::l_brace)) { 4355 FormatTok->setBlockKind(BK_Block); 4356 nextToken(); 4357 parseBracedList(); 4358 } else { 4359 nextToken(); 4360 } 4361 } 4362 } 4363 4364 void UnwrappedLineParser::parseStatementMacro() { 4365 nextToken(); 4366 if (FormatTok->is(tok::l_paren)) 4367 parseParens(); 4368 if (FormatTok->is(tok::semi)) 4369 nextToken(); 4370 addUnwrappedLine(); 4371 } 4372 4373 void UnwrappedLineParser::parseVerilogHierarchyIdentifier() { 4374 // consume things like a::`b.c[d:e] or a::* 4375 while (true) { 4376 if (FormatTok->isOneOf(tok::star, tok::period, tok::periodstar, 4377 tok::coloncolon, tok::hash) || 4378 Keywords.isVerilogIdentifier(*FormatTok)) { 4379 nextToken(); 4380 } else if (FormatTok->is(tok::l_square)) { 4381 parseSquare(); 4382 } else { 4383 break; 4384 } 4385 } 4386 } 4387 4388 void UnwrappedLineParser::parseVerilogSensitivityList() { 4389 if (FormatTok->isNot(tok::at)) 4390 return; 4391 nextToken(); 4392 // A block event expression has 2 at signs. 4393 if (FormatTok->is(tok::at)) 4394 nextToken(); 4395 switch (FormatTok->Tok.getKind()) { 4396 case tok::star: 4397 nextToken(); 4398 break; 4399 case tok::l_paren: 4400 parseParens(); 4401 break; 4402 default: 4403 parseVerilogHierarchyIdentifier(); 4404 break; 4405 } 4406 } 4407 4408 unsigned UnwrappedLineParser::parseVerilogHierarchyHeader() { 4409 unsigned AddLevels = 0; 4410 4411 if (FormatTok->is(Keywords.kw_clocking)) { 4412 nextToken(); 4413 if (Keywords.isVerilogIdentifier(*FormatTok)) 4414 nextToken(); 4415 parseVerilogSensitivityList(); 4416 if (FormatTok->is(tok::semi)) 4417 nextToken(); 4418 } else if (FormatTok->isOneOf(tok::kw_case, Keywords.kw_casex, 4419 Keywords.kw_casez, Keywords.kw_randcase, 4420 Keywords.kw_randsequence)) { 4421 if (Style.IndentCaseLabels) 4422 AddLevels++; 4423 nextToken(); 4424 if (FormatTok->is(tok::l_paren)) { 4425 FormatTok->setFinalizedType(TT_ConditionLParen); 4426 parseParens(); 4427 } 4428 if (FormatTok->isOneOf(Keywords.kw_inside, Keywords.kw_matches)) 4429 nextToken(); 4430 // The case header has no semicolon. 4431 } else { 4432 // "module" etc. 4433 nextToken(); 4434 // all the words like the name of the module and specifiers like 4435 // "automatic" and the width of function return type 4436 while (true) { 4437 if (FormatTok->is(tok::l_square)) { 4438 auto Prev = FormatTok->getPreviousNonComment(); 4439 if (Prev && Keywords.isVerilogIdentifier(*Prev)) 4440 Prev->setFinalizedType(TT_VerilogDimensionedTypeName); 4441 parseSquare(); 4442 } else if (Keywords.isVerilogIdentifier(*FormatTok) || 4443 FormatTok->isOneOf(tok::hash, tok::hashhash, tok::coloncolon, 4444 Keywords.kw_automatic, tok::kw_static)) { 4445 nextToken(); 4446 } else { 4447 break; 4448 } 4449 } 4450 4451 auto NewLine = [this]() { 4452 addUnwrappedLine(); 4453 Line->IsContinuation = true; 4454 }; 4455 4456 // package imports 4457 while (FormatTok->is(Keywords.kw_import)) { 4458 NewLine(); 4459 nextToken(); 4460 parseVerilogHierarchyIdentifier(); 4461 if (FormatTok->is(tok::semi)) 4462 nextToken(); 4463 } 4464 4465 // parameters and ports 4466 if (FormatTok->is(Keywords.kw_verilogHash)) { 4467 NewLine(); 4468 nextToken(); 4469 if (FormatTok->is(tok::l_paren)) { 4470 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen); 4471 parseParens(); 4472 } 4473 } 4474 if (FormatTok->is(tok::l_paren)) { 4475 NewLine(); 4476 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen); 4477 parseParens(); 4478 } 4479 4480 // extends and implements 4481 if (FormatTok->is(Keywords.kw_extends)) { 4482 NewLine(); 4483 nextToken(); 4484 parseVerilogHierarchyIdentifier(); 4485 if (FormatTok->is(tok::l_paren)) 4486 parseParens(); 4487 } 4488 if (FormatTok->is(Keywords.kw_implements)) { 4489 NewLine(); 4490 do { 4491 nextToken(); 4492 parseVerilogHierarchyIdentifier(); 4493 } while (FormatTok->is(tok::comma)); 4494 } 4495 4496 // Coverage event for cover groups. 4497 if (FormatTok->is(tok::at)) { 4498 NewLine(); 4499 parseVerilogSensitivityList(); 4500 } 4501 4502 if (FormatTok->is(tok::semi)) 4503 nextToken(/*LevelDifference=*/1); 4504 addUnwrappedLine(); 4505 } 4506 4507 return AddLevels; 4508 } 4509 4510 void UnwrappedLineParser::parseVerilogTable() { 4511 assert(FormatTok->is(Keywords.kw_table)); 4512 nextToken(/*LevelDifference=*/1); 4513 addUnwrappedLine(); 4514 4515 auto InitialLevel = Line->Level++; 4516 while (!eof() && !Keywords.isVerilogEnd(*FormatTok)) { 4517 FormatToken *Tok = FormatTok; 4518 nextToken(); 4519 if (Tok->is(tok::semi)) 4520 addUnwrappedLine(); 4521 else if (Tok->isOneOf(tok::star, tok::colon, tok::question, tok::minus)) 4522 Tok->setFinalizedType(TT_VerilogTableItem); 4523 } 4524 Line->Level = InitialLevel; 4525 nextToken(/*LevelDifference=*/-1); 4526 addUnwrappedLine(); 4527 } 4528 4529 void UnwrappedLineParser::parseVerilogCaseLabel() { 4530 // The label will get unindented in AnnotatingParser. If there are no leading 4531 // spaces, indent the rest here so that things inside the block will be 4532 // indented relative to things outside. We don't use parseLabel because we 4533 // don't know whether this colon is a label or a ternary expression at this 4534 // point. 4535 auto OrigLevel = Line->Level; 4536 auto FirstLine = CurrentLines->size(); 4537 if (Line->Level == 0 || (Line->InPPDirective && Line->Level <= 1)) 4538 ++Line->Level; 4539 else if (!Style.IndentCaseBlocks && Keywords.isVerilogBegin(*FormatTok)) 4540 --Line->Level; 4541 parseStructuralElement(); 4542 // Restore the indentation in both the new line and the line that has the 4543 // label. 4544 if (CurrentLines->size() > FirstLine) 4545 (*CurrentLines)[FirstLine].Level = OrigLevel; 4546 Line->Level = OrigLevel; 4547 } 4548 4549 bool UnwrappedLineParser::containsExpansion(const UnwrappedLine &Line) const { 4550 for (const auto &N : Line.Tokens) { 4551 if (N.Tok->MacroCtx) 4552 return true; 4553 for (const UnwrappedLine &Child : N.Children) 4554 if (containsExpansion(Child)) 4555 return true; 4556 } 4557 return false; 4558 } 4559 4560 void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) { 4561 if (Line->Tokens.empty()) 4562 return; 4563 LLVM_DEBUG({ 4564 if (!parsingPPDirective()) { 4565 llvm::dbgs() << "Adding unwrapped line:\n"; 4566 printDebugInfo(*Line); 4567 } 4568 }); 4569 4570 // If this line closes a block when in Whitesmiths mode, remember that 4571 // information so that the level can be decreased after the line is added. 4572 // This has to happen after the addition of the line since the line itself 4573 // needs to be indented. 4574 bool ClosesWhitesmithsBlock = 4575 Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex && 4576 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths; 4577 4578 // If the current line was expanded from a macro call, we use it to 4579 // reconstruct an unwrapped line from the structure of the expanded unwrapped 4580 // line and the unexpanded token stream. 4581 if (!parsingPPDirective() && !InExpansion && containsExpansion(*Line)) { 4582 if (!Reconstruct) 4583 Reconstruct.emplace(Line->Level, Unexpanded); 4584 Reconstruct->addLine(*Line); 4585 4586 // While the reconstructed unexpanded lines are stored in the normal 4587 // flow of lines, the expanded lines are stored on the side to be analyzed 4588 // in an extra step. 4589 CurrentExpandedLines.push_back(std::move(*Line)); 4590 4591 if (Reconstruct->finished()) { 4592 UnwrappedLine Reconstructed = std::move(*Reconstruct).takeResult(); 4593 assert(!Reconstructed.Tokens.empty() && 4594 "Reconstructed must at least contain the macro identifier."); 4595 assert(!parsingPPDirective()); 4596 LLVM_DEBUG({ 4597 llvm::dbgs() << "Adding unexpanded line:\n"; 4598 printDebugInfo(Reconstructed); 4599 }); 4600 ExpandedLines[Reconstructed.Tokens.begin()->Tok] = CurrentExpandedLines; 4601 Lines.push_back(std::move(Reconstructed)); 4602 CurrentExpandedLines.clear(); 4603 Reconstruct.reset(); 4604 } 4605 } else { 4606 // At the top level we only get here when no unexpansion is going on, or 4607 // when conditional formatting led to unfinished macro reconstructions. 4608 assert(!Reconstruct || (CurrentLines != &Lines) || !PPStack.empty()); 4609 CurrentLines->push_back(std::move(*Line)); 4610 } 4611 Line->Tokens.clear(); 4612 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex; 4613 Line->FirstStartColumn = 0; 4614 Line->IsContinuation = false; 4615 Line->SeenDecltypeAuto = false; 4616 4617 if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove) 4618 --Line->Level; 4619 if (!parsingPPDirective() && !PreprocessorDirectives.empty()) { 4620 CurrentLines->append( 4621 std::make_move_iterator(PreprocessorDirectives.begin()), 4622 std::make_move_iterator(PreprocessorDirectives.end())); 4623 PreprocessorDirectives.clear(); 4624 } 4625 // Disconnect the current token from the last token on the previous line. 4626 FormatTok->Previous = nullptr; 4627 } 4628 4629 bool UnwrappedLineParser::eof() const { return FormatTok->is(tok::eof); } 4630 4631 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) { 4632 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) && 4633 FormatTok.NewlinesBefore > 0; 4634 } 4635 4636 // Checks if \p FormatTok is a line comment that continues the line comment 4637 // section on \p Line. 4638 static bool 4639 continuesLineCommentSection(const FormatToken &FormatTok, 4640 const UnwrappedLine &Line, const FormatStyle &Style, 4641 const llvm::Regex &CommentPragmasRegex) { 4642 if (Line.Tokens.empty() || Style.ReflowComments != FormatStyle::RCS_Always) 4643 return false; 4644 4645 StringRef IndentContent = FormatTok.TokenText; 4646 if (FormatTok.TokenText.starts_with("//") || 4647 FormatTok.TokenText.starts_with("/*")) { 4648 IndentContent = FormatTok.TokenText.substr(2); 4649 } 4650 if (CommentPragmasRegex.match(IndentContent)) 4651 return false; 4652 4653 // If Line starts with a line comment, then FormatTok continues the comment 4654 // section if its original column is greater or equal to the original start 4655 // column of the line. 4656 // 4657 // Define the min column token of a line as follows: if a line ends in '{' or 4658 // contains a '{' followed by a line comment, then the min column token is 4659 // that '{'. Otherwise, the min column token of the line is the first token of 4660 // the line. 4661 // 4662 // If Line starts with a token other than a line comment, then FormatTok 4663 // continues the comment section if its original column is greater than the 4664 // original start column of the min column token of the line. 4665 // 4666 // For example, the second line comment continues the first in these cases: 4667 // 4668 // // first line 4669 // // second line 4670 // 4671 // and: 4672 // 4673 // // first line 4674 // // second line 4675 // 4676 // and: 4677 // 4678 // int i; // first line 4679 // // second line 4680 // 4681 // and: 4682 // 4683 // do { // first line 4684 // // second line 4685 // int i; 4686 // } while (true); 4687 // 4688 // and: 4689 // 4690 // enum { 4691 // a, // first line 4692 // // second line 4693 // b 4694 // }; 4695 // 4696 // The second line comment doesn't continue the first in these cases: 4697 // 4698 // // first line 4699 // // second line 4700 // 4701 // and: 4702 // 4703 // int i; // first line 4704 // // second line 4705 // 4706 // and: 4707 // 4708 // do { // first line 4709 // // second line 4710 // int i; 4711 // } while (true); 4712 // 4713 // and: 4714 // 4715 // enum { 4716 // a, // first line 4717 // // second line 4718 // }; 4719 const FormatToken *MinColumnToken = Line.Tokens.front().Tok; 4720 4721 // Scan for '{//'. If found, use the column of '{' as a min column for line 4722 // comment section continuation. 4723 const FormatToken *PreviousToken = nullptr; 4724 for (const UnwrappedLineNode &Node : Line.Tokens) { 4725 if (PreviousToken && PreviousToken->is(tok::l_brace) && 4726 isLineComment(*Node.Tok)) { 4727 MinColumnToken = PreviousToken; 4728 break; 4729 } 4730 PreviousToken = Node.Tok; 4731 4732 // Grab the last newline preceding a token in this unwrapped line. 4733 if (Node.Tok->NewlinesBefore > 0) 4734 MinColumnToken = Node.Tok; 4735 } 4736 if (PreviousToken && PreviousToken->is(tok::l_brace)) 4737 MinColumnToken = PreviousToken; 4738 4739 return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok, 4740 MinColumnToken); 4741 } 4742 4743 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) { 4744 bool JustComments = Line->Tokens.empty(); 4745 for (FormatToken *Tok : CommentsBeforeNextToken) { 4746 // Line comments that belong to the same line comment section are put on the 4747 // same line since later we might want to reflow content between them. 4748 // Additional fine-grained breaking of line comment sections is controlled 4749 // by the class BreakableLineCommentSection in case it is desirable to keep 4750 // several line comment sections in the same unwrapped line. 4751 // 4752 // FIXME: Consider putting separate line comment sections as children to the 4753 // unwrapped line instead. 4754 Tok->ContinuesLineCommentSection = 4755 continuesLineCommentSection(*Tok, *Line, Style, CommentPragmasRegex); 4756 if (isOnNewLine(*Tok) && JustComments && !Tok->ContinuesLineCommentSection) 4757 addUnwrappedLine(); 4758 pushToken(Tok); 4759 } 4760 if (NewlineBeforeNext && JustComments) 4761 addUnwrappedLine(); 4762 CommentsBeforeNextToken.clear(); 4763 } 4764 4765 void UnwrappedLineParser::nextToken(int LevelDifference) { 4766 if (eof()) 4767 return; 4768 flushComments(isOnNewLine(*FormatTok)); 4769 pushToken(FormatTok); 4770 FormatToken *Previous = FormatTok; 4771 if (!Style.isJavaScript()) 4772 readToken(LevelDifference); 4773 else 4774 readTokenWithJavaScriptASI(); 4775 FormatTok->Previous = Previous; 4776 if (Style.isVerilog()) { 4777 // Blocks in Verilog can have `begin` and `end` instead of braces. For 4778 // keywords like `begin`, we can't treat them the same as left braces 4779 // because some contexts require one of them. For example structs use 4780 // braces and if blocks use keywords, and a left brace can occur in an if 4781 // statement, but it is not a block. For keywords like `end`, we simply 4782 // treat them the same as right braces. 4783 if (Keywords.isVerilogEnd(*FormatTok)) 4784 FormatTok->Tok.setKind(tok::r_brace); 4785 } 4786 } 4787 4788 void UnwrappedLineParser::distributeComments( 4789 const ArrayRef<FormatToken *> &Comments, const FormatToken *NextTok) { 4790 // Whether or not a line comment token continues a line is controlled by 4791 // the method continuesLineCommentSection, with the following caveat: 4792 // 4793 // Define a trail of Comments to be a nonempty proper postfix of Comments such 4794 // that each comment line from the trail is aligned with the next token, if 4795 // the next token exists. If a trail exists, the beginning of the maximal 4796 // trail is marked as a start of a new comment section. 4797 // 4798 // For example in this code: 4799 // 4800 // int a; // line about a 4801 // // line 1 about b 4802 // // line 2 about b 4803 // int b; 4804 // 4805 // the two lines about b form a maximal trail, so there are two sections, the 4806 // first one consisting of the single comment "// line about a" and the 4807 // second one consisting of the next two comments. 4808 if (Comments.empty()) 4809 return; 4810 bool ShouldPushCommentsInCurrentLine = true; 4811 bool HasTrailAlignedWithNextToken = false; 4812 unsigned StartOfTrailAlignedWithNextToken = 0; 4813 if (NextTok) { 4814 // We are skipping the first element intentionally. 4815 for (unsigned i = Comments.size() - 1; i > 0; --i) { 4816 if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) { 4817 HasTrailAlignedWithNextToken = true; 4818 StartOfTrailAlignedWithNextToken = i; 4819 } 4820 } 4821 } 4822 for (unsigned i = 0, e = Comments.size(); i < e; ++i) { 4823 FormatToken *FormatTok = Comments[i]; 4824 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) { 4825 FormatTok->ContinuesLineCommentSection = false; 4826 } else { 4827 FormatTok->ContinuesLineCommentSection = continuesLineCommentSection( 4828 *FormatTok, *Line, Style, CommentPragmasRegex); 4829 } 4830 if (!FormatTok->ContinuesLineCommentSection && 4831 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) { 4832 ShouldPushCommentsInCurrentLine = false; 4833 } 4834 if (ShouldPushCommentsInCurrentLine) 4835 pushToken(FormatTok); 4836 else 4837 CommentsBeforeNextToken.push_back(FormatTok); 4838 } 4839 } 4840 4841 void UnwrappedLineParser::readToken(int LevelDifference) { 4842 SmallVector<FormatToken *, 1> Comments; 4843 bool PreviousWasComment = false; 4844 bool FirstNonCommentOnLine = false; 4845 do { 4846 FormatTok = Tokens->getNextToken(); 4847 assert(FormatTok); 4848 while (FormatTok->isOneOf(TT_ConflictStart, TT_ConflictEnd, 4849 TT_ConflictAlternative)) { 4850 if (FormatTok->is(TT_ConflictStart)) 4851 conditionalCompilationStart(/*Unreachable=*/false); 4852 else if (FormatTok->is(TT_ConflictAlternative)) 4853 conditionalCompilationAlternative(); 4854 else if (FormatTok->is(TT_ConflictEnd)) 4855 conditionalCompilationEnd(); 4856 FormatTok = Tokens->getNextToken(); 4857 FormatTok->MustBreakBefore = true; 4858 FormatTok->MustBreakBeforeFinalized = true; 4859 } 4860 4861 auto IsFirstNonCommentOnLine = [](bool FirstNonCommentOnLine, 4862 const FormatToken &Tok, 4863 bool PreviousWasComment) { 4864 auto IsFirstOnLine = [](const FormatToken &Tok) { 4865 return Tok.HasUnescapedNewline || Tok.IsFirst; 4866 }; 4867 4868 // Consider preprocessor directives preceded by block comments as first 4869 // on line. 4870 if (PreviousWasComment) 4871 return FirstNonCommentOnLine || IsFirstOnLine(Tok); 4872 return IsFirstOnLine(Tok); 4873 }; 4874 4875 FirstNonCommentOnLine = IsFirstNonCommentOnLine( 4876 FirstNonCommentOnLine, *FormatTok, PreviousWasComment); 4877 PreviousWasComment = FormatTok->is(tok::comment); 4878 4879 while (!Line->InPPDirective && FormatTok->is(tok::hash) && 4880 FirstNonCommentOnLine) { 4881 // In Verilog, the backtick is used for macro invocations. In TableGen, 4882 // the single hash is used for the paste operator. 4883 const auto *Next = Tokens->peekNextToken(); 4884 if ((Style.isVerilog() && !Keywords.isVerilogPPDirective(*Next)) || 4885 (Style.isTableGen() && 4886 !Next->isOneOf(tok::kw_else, tok::pp_define, tok::pp_ifdef, 4887 tok::pp_ifndef, tok::pp_endif))) { 4888 break; 4889 } 4890 distributeComments(Comments, FormatTok); 4891 Comments.clear(); 4892 // If there is an unfinished unwrapped line, we flush the preprocessor 4893 // directives only after that unwrapped line was finished later. 4894 bool SwitchToPreprocessorLines = !Line->Tokens.empty(); 4895 ScopedLineState BlockState(*this, SwitchToPreprocessorLines); 4896 assert((LevelDifference >= 0 || 4897 static_cast<unsigned>(-LevelDifference) <= Line->Level) && 4898 "LevelDifference makes Line->Level negative"); 4899 Line->Level += LevelDifference; 4900 // Comments stored before the preprocessor directive need to be output 4901 // before the preprocessor directive, at the same level as the 4902 // preprocessor directive, as we consider them to apply to the directive. 4903 if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash && 4904 PPBranchLevel > 0) { 4905 Line->Level += PPBranchLevel; 4906 } 4907 assert(Line->Level >= Line->UnbracedBodyLevel); 4908 Line->Level -= Line->UnbracedBodyLevel; 4909 flushComments(isOnNewLine(*FormatTok)); 4910 parsePPDirective(); 4911 PreviousWasComment = FormatTok->is(tok::comment); 4912 FirstNonCommentOnLine = IsFirstNonCommentOnLine( 4913 FirstNonCommentOnLine, *FormatTok, PreviousWasComment); 4914 } 4915 4916 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) && 4917 !Line->InPPDirective) { 4918 continue; 4919 } 4920 4921 if (FormatTok->is(tok::identifier) && 4922 Macros.defined(FormatTok->TokenText) && 4923 // FIXME: Allow expanding macros in preprocessor directives. 4924 !Line->InPPDirective) { 4925 FormatToken *ID = FormatTok; 4926 unsigned Position = Tokens->getPosition(); 4927 4928 // To correctly parse the code, we need to replace the tokens of the macro 4929 // call with its expansion. 4930 auto PreCall = std::move(Line); 4931 Line.reset(new UnwrappedLine); 4932 bool OldInExpansion = InExpansion; 4933 InExpansion = true; 4934 // We parse the macro call into a new line. 4935 auto Args = parseMacroCall(); 4936 InExpansion = OldInExpansion; 4937 assert(Line->Tokens.front().Tok == ID); 4938 // And remember the unexpanded macro call tokens. 4939 auto UnexpandedLine = std::move(Line); 4940 // Reset to the old line. 4941 Line = std::move(PreCall); 4942 4943 LLVM_DEBUG({ 4944 llvm::dbgs() << "Macro call: " << ID->TokenText << "("; 4945 if (Args) { 4946 llvm::dbgs() << "("; 4947 for (const auto &Arg : Args.value()) 4948 for (const auto &T : Arg) 4949 llvm::dbgs() << T->TokenText << " "; 4950 llvm::dbgs() << ")"; 4951 } 4952 llvm::dbgs() << "\n"; 4953 }); 4954 if (Macros.objectLike(ID->TokenText) && Args && 4955 !Macros.hasArity(ID->TokenText, Args->size())) { 4956 // The macro is either 4957 // - object-like, but we got argumnets, or 4958 // - overloaded to be both object-like and function-like, but none of 4959 // the function-like arities match the number of arguments. 4960 // Thus, expand as object-like macro. 4961 LLVM_DEBUG(llvm::dbgs() 4962 << "Macro \"" << ID->TokenText 4963 << "\" not overloaded for arity " << Args->size() 4964 << "or not function-like, using object-like overload."); 4965 Args.reset(); 4966 UnexpandedLine->Tokens.resize(1); 4967 Tokens->setPosition(Position); 4968 nextToken(); 4969 assert(!Args && Macros.objectLike(ID->TokenText)); 4970 } 4971 if ((!Args && Macros.objectLike(ID->TokenText)) || 4972 (Args && Macros.hasArity(ID->TokenText, Args->size()))) { 4973 // Next, we insert the expanded tokens in the token stream at the 4974 // current position, and continue parsing. 4975 Unexpanded[ID] = std::move(UnexpandedLine); 4976 SmallVector<FormatToken *, 8> Expansion = 4977 Macros.expand(ID, std::move(Args)); 4978 if (!Expansion.empty()) 4979 FormatTok = Tokens->insertTokens(Expansion); 4980 4981 LLVM_DEBUG({ 4982 llvm::dbgs() << "Expanded: "; 4983 for (const auto &T : Expansion) 4984 llvm::dbgs() << T->TokenText << " "; 4985 llvm::dbgs() << "\n"; 4986 }); 4987 } else { 4988 LLVM_DEBUG({ 4989 llvm::dbgs() << "Did not expand macro \"" << ID->TokenText 4990 << "\", because it was used "; 4991 if (Args) 4992 llvm::dbgs() << "with " << Args->size(); 4993 else 4994 llvm::dbgs() << "without"; 4995 llvm::dbgs() << " arguments, which doesn't match any definition.\n"; 4996 }); 4997 Tokens->setPosition(Position); 4998 FormatTok = ID; 4999 } 5000 } 5001 5002 if (FormatTok->isNot(tok::comment)) { 5003 distributeComments(Comments, FormatTok); 5004 Comments.clear(); 5005 return; 5006 } 5007 5008 Comments.push_back(FormatTok); 5009 } while (!eof()); 5010 5011 distributeComments(Comments, nullptr); 5012 Comments.clear(); 5013 } 5014 5015 namespace { 5016 template <typename Iterator> 5017 void pushTokens(Iterator Begin, Iterator End, 5018 SmallVectorImpl<FormatToken *> &Into) { 5019 for (auto I = Begin; I != End; ++I) { 5020 Into.push_back(I->Tok); 5021 for (const auto &Child : I->Children) 5022 pushTokens(Child.Tokens.begin(), Child.Tokens.end(), Into); 5023 } 5024 } 5025 } // namespace 5026 5027 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>> 5028 UnwrappedLineParser::parseMacroCall() { 5029 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>> Args; 5030 assert(Line->Tokens.empty()); 5031 nextToken(); 5032 if (FormatTok->isNot(tok::l_paren)) 5033 return Args; 5034 unsigned Position = Tokens->getPosition(); 5035 FormatToken *Tok = FormatTok; 5036 nextToken(); 5037 Args.emplace(); 5038 auto ArgStart = std::prev(Line->Tokens.end()); 5039 5040 int Parens = 0; 5041 do { 5042 switch (FormatTok->Tok.getKind()) { 5043 case tok::l_paren: 5044 ++Parens; 5045 nextToken(); 5046 break; 5047 case tok::r_paren: { 5048 if (Parens > 0) { 5049 --Parens; 5050 nextToken(); 5051 break; 5052 } 5053 Args->push_back({}); 5054 pushTokens(std::next(ArgStart), Line->Tokens.end(), Args->back()); 5055 nextToken(); 5056 return Args; 5057 } 5058 case tok::comma: { 5059 if (Parens > 0) { 5060 nextToken(); 5061 break; 5062 } 5063 Args->push_back({}); 5064 pushTokens(std::next(ArgStart), Line->Tokens.end(), Args->back()); 5065 nextToken(); 5066 ArgStart = std::prev(Line->Tokens.end()); 5067 break; 5068 } 5069 default: 5070 nextToken(); 5071 break; 5072 } 5073 } while (!eof()); 5074 Line->Tokens.resize(1); 5075 Tokens->setPosition(Position); 5076 FormatTok = Tok; 5077 return {}; 5078 } 5079 5080 void UnwrappedLineParser::pushToken(FormatToken *Tok) { 5081 Line->Tokens.push_back(UnwrappedLineNode(Tok)); 5082 if (AtEndOfPPLine) { 5083 auto &Tok = *Line->Tokens.back().Tok; 5084 Tok.MustBreakBefore = true; 5085 Tok.MustBreakBeforeFinalized = true; 5086 Tok.FirstAfterPPLine = true; 5087 AtEndOfPPLine = false; 5088 } 5089 } 5090 5091 } // end namespace format 5092 } // end namespace clang 5093