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 "llvm/ADT/STLExtras.h" 18 #include "llvm/Support/Debug.h" 19 #include "llvm/Support/raw_ostream.h" 20 21 #include <algorithm> 22 #include <utility> 23 24 #define DEBUG_TYPE "format-parser" 25 26 namespace clang { 27 namespace format { 28 29 class FormatTokenSource { 30 public: 31 virtual ~FormatTokenSource() {} 32 33 // Returns the next token in the token stream. 34 virtual FormatToken *getNextToken() = 0; 35 36 // Returns the token preceding the token returned by the last call to 37 // getNextToken() in the token stream, or nullptr if no such token exists. 38 virtual FormatToken *getPreviousToken() = 0; 39 40 // Returns the token that would be returned by the next call to 41 // getNextToken(). 42 virtual FormatToken *peekNextToken() = 0; 43 44 // Returns the token that would be returned after the next N calls to 45 // getNextToken(). N needs to be greater than zero, and small enough that 46 // there are still tokens. Check for tok::eof with N-1 before calling it with 47 // N. 48 virtual FormatToken *peekNextToken(int N) = 0; 49 50 // Returns whether we are at the end of the file. 51 // This can be different from whether getNextToken() returned an eof token 52 // when the FormatTokenSource is a view on a part of the token stream. 53 virtual bool isEOF() = 0; 54 55 // Gets the current position in the token stream, to be used by setPosition(). 56 virtual unsigned getPosition() = 0; 57 58 // Resets the token stream to the state it was in when getPosition() returned 59 // Position, and return the token at that position in the stream. 60 virtual FormatToken *setPosition(unsigned Position) = 0; 61 }; 62 63 namespace { 64 65 class ScopedDeclarationState { 66 public: 67 ScopedDeclarationState(UnwrappedLine &Line, llvm::BitVector &Stack, 68 bool MustBeDeclaration) 69 : Line(Line), Stack(Stack) { 70 Line.MustBeDeclaration = MustBeDeclaration; 71 Stack.push_back(MustBeDeclaration); 72 } 73 ~ScopedDeclarationState() { 74 Stack.pop_back(); 75 if (!Stack.empty()) 76 Line.MustBeDeclaration = Stack.back(); 77 else 78 Line.MustBeDeclaration = true; 79 } 80 81 private: 82 UnwrappedLine &Line; 83 llvm::BitVector &Stack; 84 }; 85 86 static bool isLineComment(const FormatToken &FormatTok) { 87 return FormatTok.is(tok::comment) && !FormatTok.TokenText.startswith("/*"); 88 } 89 90 // Checks if \p FormatTok is a line comment that continues the line comment 91 // \p Previous. The original column of \p MinColumnToken is used to determine 92 // whether \p FormatTok is indented enough to the right to continue \p Previous. 93 static bool continuesLineComment(const FormatToken &FormatTok, 94 const FormatToken *Previous, 95 const FormatToken *MinColumnToken) { 96 if (!Previous || !MinColumnToken) 97 return false; 98 unsigned MinContinueColumn = 99 MinColumnToken->OriginalColumn + (isLineComment(*MinColumnToken) ? 0 : 1); 100 return isLineComment(FormatTok) && FormatTok.NewlinesBefore == 1 && 101 isLineComment(*Previous) && 102 FormatTok.OriginalColumn >= MinContinueColumn; 103 } 104 105 class ScopedMacroState : public FormatTokenSource { 106 public: 107 ScopedMacroState(UnwrappedLine &Line, FormatTokenSource *&TokenSource, 108 FormatToken *&ResetToken) 109 : Line(Line), TokenSource(TokenSource), ResetToken(ResetToken), 110 PreviousLineLevel(Line.Level), PreviousTokenSource(TokenSource), 111 Token(nullptr), PreviousToken(nullptr) { 112 FakeEOF.Tok.startToken(); 113 FakeEOF.Tok.setKind(tok::eof); 114 TokenSource = this; 115 Line.Level = 0; 116 Line.InPPDirective = true; 117 } 118 119 ~ScopedMacroState() override { 120 TokenSource = PreviousTokenSource; 121 ResetToken = Token; 122 Line.InPPDirective = false; 123 Line.Level = PreviousLineLevel; 124 } 125 126 FormatToken *getNextToken() override { 127 // The \c UnwrappedLineParser guards against this by never calling 128 // \c getNextToken() after it has encountered the first eof token. 129 assert(!eof()); 130 PreviousToken = Token; 131 Token = PreviousTokenSource->getNextToken(); 132 if (eof()) 133 return &FakeEOF; 134 return Token; 135 } 136 137 FormatToken *getPreviousToken() override { 138 return PreviousTokenSource->getPreviousToken(); 139 } 140 141 FormatToken *peekNextToken() override { 142 if (eof()) 143 return &FakeEOF; 144 return PreviousTokenSource->peekNextToken(); 145 } 146 147 FormatToken *peekNextToken(int N) override { 148 assert(N > 0); 149 if (eof()) 150 return &FakeEOF; 151 return PreviousTokenSource->peekNextToken(N); 152 } 153 154 bool isEOF() override { return PreviousTokenSource->isEOF(); } 155 156 unsigned getPosition() override { return PreviousTokenSource->getPosition(); } 157 158 FormatToken *setPosition(unsigned Position) override { 159 PreviousToken = nullptr; 160 Token = PreviousTokenSource->setPosition(Position); 161 return Token; 162 } 163 164 private: 165 bool eof() { 166 return Token && Token->HasUnescapedNewline && 167 !continuesLineComment(*Token, PreviousToken, 168 /*MinColumnToken=*/PreviousToken); 169 } 170 171 FormatToken FakeEOF; 172 UnwrappedLine &Line; 173 FormatTokenSource *&TokenSource; 174 FormatToken *&ResetToken; 175 unsigned PreviousLineLevel; 176 FormatTokenSource *PreviousTokenSource; 177 178 FormatToken *Token; 179 FormatToken *PreviousToken; 180 }; 181 182 } // end anonymous namespace 183 184 class ScopedLineState { 185 public: 186 ScopedLineState(UnwrappedLineParser &Parser, 187 bool SwitchToPreprocessorLines = false) 188 : Parser(Parser), OriginalLines(Parser.CurrentLines) { 189 if (SwitchToPreprocessorLines) 190 Parser.CurrentLines = &Parser.PreprocessorDirectives; 191 else if (!Parser.Line->Tokens.empty()) 192 Parser.CurrentLines = &Parser.Line->Tokens.back().Children; 193 PreBlockLine = std::move(Parser.Line); 194 Parser.Line = std::make_unique<UnwrappedLine>(); 195 Parser.Line->Level = PreBlockLine->Level; 196 Parser.Line->InPPDirective = PreBlockLine->InPPDirective; 197 } 198 199 ~ScopedLineState() { 200 if (!Parser.Line->Tokens.empty()) 201 Parser.addUnwrappedLine(); 202 assert(Parser.Line->Tokens.empty()); 203 Parser.Line = std::move(PreBlockLine); 204 if (Parser.CurrentLines == &Parser.PreprocessorDirectives) 205 Parser.MustBreakBeforeNextToken = true; 206 Parser.CurrentLines = OriginalLines; 207 } 208 209 private: 210 UnwrappedLineParser &Parser; 211 212 std::unique_ptr<UnwrappedLine> PreBlockLine; 213 SmallVectorImpl<UnwrappedLine> *OriginalLines; 214 }; 215 216 class CompoundStatementIndenter { 217 public: 218 CompoundStatementIndenter(UnwrappedLineParser *Parser, 219 const FormatStyle &Style, unsigned &LineLevel) 220 : CompoundStatementIndenter(Parser, LineLevel, 221 Style.BraceWrapping.AfterControlStatement, 222 Style.BraceWrapping.IndentBraces) {} 223 CompoundStatementIndenter(UnwrappedLineParser *Parser, unsigned &LineLevel, 224 bool WrapBrace, bool IndentBrace) 225 : LineLevel(LineLevel), OldLineLevel(LineLevel) { 226 if (WrapBrace) 227 Parser->addUnwrappedLine(); 228 if (IndentBrace) 229 ++LineLevel; 230 } 231 ~CompoundStatementIndenter() { LineLevel = OldLineLevel; } 232 233 private: 234 unsigned &LineLevel; 235 unsigned OldLineLevel; 236 }; 237 238 namespace { 239 240 class IndexedTokenSource : public FormatTokenSource { 241 public: 242 IndexedTokenSource(ArrayRef<FormatToken *> Tokens) 243 : Tokens(Tokens), Position(-1) {} 244 245 FormatToken *getNextToken() override { 246 if (Position >= 0 && Tokens[Position]->is(tok::eof)) { 247 LLVM_DEBUG({ 248 llvm::dbgs() << "Next "; 249 dbgToken(Position); 250 }); 251 return Tokens[Position]; 252 } 253 ++Position; 254 LLVM_DEBUG({ 255 llvm::dbgs() << "Next "; 256 dbgToken(Position); 257 }); 258 return Tokens[Position]; 259 } 260 261 FormatToken *getPreviousToken() override { 262 return Position > 0 ? Tokens[Position - 1] : nullptr; 263 } 264 265 FormatToken *peekNextToken() override { 266 int Next = Position + 1; 267 LLVM_DEBUG({ 268 llvm::dbgs() << "Peeking "; 269 dbgToken(Next); 270 }); 271 return Tokens[Next]; 272 } 273 274 FormatToken *peekNextToken(int N) override { 275 assert(N > 0); 276 int Next = Position + N; 277 LLVM_DEBUG({ 278 llvm::dbgs() << "Peeking (+" << (N - 1) << ") "; 279 dbgToken(Next); 280 }); 281 return Tokens[Next]; 282 } 283 284 bool isEOF() override { return Tokens[Position]->is(tok::eof); } 285 286 unsigned getPosition() override { 287 LLVM_DEBUG(llvm::dbgs() << "Getting Position: " << Position << "\n"); 288 assert(Position >= 0); 289 return Position; 290 } 291 292 FormatToken *setPosition(unsigned P) override { 293 LLVM_DEBUG(llvm::dbgs() << "Setting Position: " << P << "\n"); 294 Position = P; 295 return Tokens[Position]; 296 } 297 298 void reset() { Position = -1; } 299 300 private: 301 void dbgToken(int Position, llvm::StringRef Indent = "") { 302 FormatToken *Tok = Tokens[Position]; 303 llvm::dbgs() << Indent << "[" << Position 304 << "] Token: " << Tok->Tok.getName() << " / " << Tok->TokenText 305 << ", Macro: " << !!Tok->MacroCtx << "\n"; 306 } 307 308 ArrayRef<FormatToken *> Tokens; 309 int Position; 310 }; 311 312 } // end anonymous namespace 313 314 UnwrappedLineParser::UnwrappedLineParser(const FormatStyle &Style, 315 const AdditionalKeywords &Keywords, 316 unsigned FirstStartColumn, 317 ArrayRef<FormatToken *> Tokens, 318 UnwrappedLineConsumer &Callback) 319 : Line(new UnwrappedLine), MustBreakBeforeNextToken(false), 320 CurrentLines(&Lines), Style(Style), Keywords(Keywords), 321 CommentPragmasRegex(Style.CommentPragmas), Tokens(nullptr), 322 Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1), 323 IncludeGuard(Style.IndentPPDirectives == FormatStyle::PPDIS_None 324 ? IG_Rejected 325 : IG_Inited), 326 IncludeGuardToken(nullptr), FirstStartColumn(FirstStartColumn) {} 327 328 void UnwrappedLineParser::reset() { 329 PPBranchLevel = -1; 330 IncludeGuard = Style.IndentPPDirectives == FormatStyle::PPDIS_None 331 ? IG_Rejected 332 : IG_Inited; 333 IncludeGuardToken = nullptr; 334 Line.reset(new UnwrappedLine); 335 CommentsBeforeNextToken.clear(); 336 FormatTok = nullptr; 337 MustBreakBeforeNextToken = false; 338 PreprocessorDirectives.clear(); 339 CurrentLines = &Lines; 340 DeclarationScopeStack.clear(); 341 NestedTooDeep.clear(); 342 PPStack.clear(); 343 Line->FirstStartColumn = FirstStartColumn; 344 } 345 346 void UnwrappedLineParser::parse() { 347 IndexedTokenSource TokenSource(AllTokens); 348 Line->FirstStartColumn = FirstStartColumn; 349 do { 350 LLVM_DEBUG(llvm::dbgs() << "----\n"); 351 reset(); 352 Tokens = &TokenSource; 353 TokenSource.reset(); 354 355 readToken(); 356 parseFile(); 357 358 // If we found an include guard then all preprocessor directives (other than 359 // the guard) are over-indented by one. 360 if (IncludeGuard == IG_Found) 361 for (auto &Line : Lines) 362 if (Line.InPPDirective && Line.Level > 0) 363 --Line.Level; 364 365 // Create line with eof token. 366 pushToken(FormatTok); 367 addUnwrappedLine(); 368 369 for (const UnwrappedLine &Line : Lines) 370 Callback.consumeUnwrappedLine(Line); 371 372 Callback.finishRun(); 373 Lines.clear(); 374 while (!PPLevelBranchIndex.empty() && 375 PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) { 376 PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1); 377 PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1); 378 } 379 if (!PPLevelBranchIndex.empty()) { 380 ++PPLevelBranchIndex.back(); 381 assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size()); 382 assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back()); 383 } 384 } while (!PPLevelBranchIndex.empty()); 385 } 386 387 void UnwrappedLineParser::parseFile() { 388 // The top-level context in a file always has declarations, except for pre- 389 // processor directives and JavaScript files. 390 bool MustBeDeclaration = !Line->InPPDirective && !Style.isJavaScript(); 391 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack, 392 MustBeDeclaration); 393 if (Style.Language == FormatStyle::LK_TextProto) 394 parseBracedList(); 395 else 396 parseLevel(/*HasOpeningBrace=*/false, /*CanContainBracedList=*/true); 397 // Make sure to format the remaining tokens. 398 // 399 // LK_TextProto is special since its top-level is parsed as the body of a 400 // braced list, which does not necessarily have natural line separators such 401 // as a semicolon. Comments after the last entry that have been determined to 402 // not belong to that line, as in: 403 // key: value 404 // // endfile comment 405 // do not have a chance to be put on a line of their own until this point. 406 // Here we add this newline before end-of-file comments. 407 if (Style.Language == FormatStyle::LK_TextProto && 408 !CommentsBeforeNextToken.empty()) 409 addUnwrappedLine(); 410 flushComments(true); 411 addUnwrappedLine(); 412 } 413 414 void UnwrappedLineParser::parseCSharpGenericTypeConstraint() { 415 do { 416 switch (FormatTok->Tok.getKind()) { 417 case tok::l_brace: 418 return; 419 default: 420 if (FormatTok->is(Keywords.kw_where)) { 421 addUnwrappedLine(); 422 nextToken(); 423 parseCSharpGenericTypeConstraint(); 424 break; 425 } 426 nextToken(); 427 break; 428 } 429 } while (!eof()); 430 } 431 432 void UnwrappedLineParser::parseCSharpAttribute() { 433 int UnpairedSquareBrackets = 1; 434 do { 435 switch (FormatTok->Tok.getKind()) { 436 case tok::r_square: 437 nextToken(); 438 --UnpairedSquareBrackets; 439 if (UnpairedSquareBrackets == 0) { 440 addUnwrappedLine(); 441 return; 442 } 443 break; 444 case tok::l_square: 445 ++UnpairedSquareBrackets; 446 nextToken(); 447 break; 448 default: 449 nextToken(); 450 break; 451 } 452 } while (!eof()); 453 } 454 455 bool UnwrappedLineParser::precededByCommentOrPPDirective() const { 456 if (!Lines.empty() && Lines.back().InPPDirective) 457 return true; 458 459 const FormatToken *Previous = Tokens->getPreviousToken(); 460 return Previous && Previous->is(tok::comment) && 461 (Previous->IsMultiline || Previous->NewlinesBefore > 0); 462 } 463 /// \brief Parses a level, that is ???. 464 /// \param HasOpeningBrace If that level is started by an opening brace. 465 /// \param CanContainBracedList If the content can contain (at any level) a 466 /// braced list. 467 /// \param NextLBracesType The type for left brace found in this level. 468 /// \returns true if a simple block, or false otherwise. (A simple block has a 469 /// single statement.) 470 bool UnwrappedLineParser::parseLevel(bool HasOpeningBrace, 471 bool CanContainBracedList, 472 IfStmtKind *IfKind, 473 TokenType NextLBracesType) { 474 auto NextLevelLBracesType = NextLBracesType == TT_CompoundRequirementLBrace 475 ? TT_BracedListLBrace 476 : TT_Unknown; 477 const bool IsPrecededByCommentOrPPDirective = 478 !Style.RemoveBracesLLVM || precededByCommentOrPPDirective(); 479 bool HasLabel = false; 480 unsigned StatementCount = 0; 481 bool SwitchLabelEncountered = false; 482 do { 483 if (FormatTok->getType() == TT_AttributeMacro) { 484 nextToken(); 485 continue; 486 } 487 tok::TokenKind kind = FormatTok->Tok.getKind(); 488 if (FormatTok->getType() == TT_MacroBlockBegin) 489 kind = tok::l_brace; 490 else if (FormatTok->getType() == TT_MacroBlockEnd) 491 kind = tok::r_brace; 492 493 auto ParseDefault = [this, HasOpeningBrace, IfKind, NextLevelLBracesType, 494 &HasLabel, &StatementCount] { 495 parseStructuralElement(IfKind, !HasOpeningBrace, NextLevelLBracesType, 496 HasLabel ? nullptr : &HasLabel); 497 ++StatementCount; 498 assert(StatementCount > 0 && "StatementCount overflow!"); 499 }; 500 501 switch (kind) { 502 case tok::comment: 503 nextToken(); 504 addUnwrappedLine(); 505 break; 506 case tok::l_brace: 507 if (NextLBracesType != TT_Unknown) 508 FormatTok->setFinalizedType(NextLBracesType); 509 else if (FormatTok->Previous && 510 FormatTok->Previous->ClosesRequiresClause) { 511 // We need the 'default' case here to correctly parse a function 512 // l_brace. 513 ParseDefault(); 514 continue; 515 } 516 if (CanContainBracedList && !FormatTok->is(TT_MacroBlockBegin) && 517 tryToParseBracedList()) 518 continue; 519 parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u, 520 /*MunchSemi=*/true, /*UnindentWhitesmithBraces=*/false, 521 CanContainBracedList, 522 /*NextLBracesType=*/NextLBracesType); 523 ++StatementCount; 524 assert(StatementCount > 0 && "StatementCount overflow!"); 525 addUnwrappedLine(); 526 break; 527 case tok::r_brace: 528 if (HasOpeningBrace) { 529 if (!Style.RemoveBracesLLVM) 530 return false; 531 if (FormatTok->isNot(tok::r_brace) || StatementCount != 1 || HasLabel || 532 IsPrecededByCommentOrPPDirective || 533 precededByCommentOrPPDirective()) 534 return false; 535 const FormatToken *Next = Tokens->peekNextToken(); 536 return Next->isNot(tok::comment) || Next->NewlinesBefore > 0; 537 } 538 nextToken(); 539 addUnwrappedLine(); 540 break; 541 case tok::kw_default: { 542 unsigned StoredPosition = Tokens->getPosition(); 543 FormatToken *Next; 544 do { 545 Next = Tokens->getNextToken(); 546 assert(Next); 547 } while (Next->is(tok::comment)); 548 FormatTok = Tokens->setPosition(StoredPosition); 549 if (Next->isNot(tok::colon)) { 550 // default not followed by ':' is not a case label; treat it like 551 // an identifier. 552 parseStructuralElement(); 553 break; 554 } 555 // Else, if it is 'default:', fall through to the case handling. 556 LLVM_FALLTHROUGH; 557 } 558 case tok::kw_case: 559 if (Style.isJavaScript() && Line->MustBeDeclaration) { 560 // A 'case: string' style field declaration. 561 parseStructuralElement(); 562 break; 563 } 564 if (!SwitchLabelEncountered && 565 (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1))) 566 ++Line->Level; 567 SwitchLabelEncountered = true; 568 parseStructuralElement(); 569 break; 570 case tok::l_square: 571 if (Style.isCSharp()) { 572 nextToken(); 573 parseCSharpAttribute(); 574 break; 575 } 576 if (handleCppAttributes()) 577 break; 578 LLVM_FALLTHROUGH; 579 default: 580 ParseDefault(); 581 break; 582 } 583 } while (!eof()); 584 return false; 585 } 586 587 void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) { 588 // We'll parse forward through the tokens until we hit 589 // a closing brace or eof - note that getNextToken() will 590 // parse macros, so this will magically work inside macro 591 // definitions, too. 592 unsigned StoredPosition = Tokens->getPosition(); 593 FormatToken *Tok = FormatTok; 594 const FormatToken *PrevTok = Tok->Previous; 595 // Keep a stack of positions of lbrace tokens. We will 596 // update information about whether an lbrace starts a 597 // braced init list or a different block during the loop. 598 SmallVector<FormatToken *, 8> LBraceStack; 599 assert(Tok->is(tok::l_brace)); 600 do { 601 // Get next non-comment token. 602 FormatToken *NextTok; 603 do { 604 NextTok = Tokens->getNextToken(); 605 } while (NextTok->is(tok::comment)); 606 607 switch (Tok->Tok.getKind()) { 608 case tok::l_brace: 609 if (Style.isJavaScript() && PrevTok) { 610 if (PrevTok->isOneOf(tok::colon, tok::less)) 611 // A ':' indicates this code is in a type, or a braced list 612 // following a label in an object literal ({a: {b: 1}}). 613 // A '<' could be an object used in a comparison, but that is nonsense 614 // code (can never return true), so more likely it is a generic type 615 // argument (`X<{a: string; b: number}>`). 616 // The code below could be confused by semicolons between the 617 // individual members in a type member list, which would normally 618 // trigger BK_Block. In both cases, this must be parsed as an inline 619 // braced init. 620 Tok->setBlockKind(BK_BracedInit); 621 else if (PrevTok->is(tok::r_paren)) 622 // `) { }` can only occur in function or method declarations in JS. 623 Tok->setBlockKind(BK_Block); 624 } else { 625 Tok->setBlockKind(BK_Unknown); 626 } 627 LBraceStack.push_back(Tok); 628 break; 629 case tok::r_brace: 630 if (LBraceStack.empty()) 631 break; 632 if (LBraceStack.back()->is(BK_Unknown)) { 633 bool ProbablyBracedList = false; 634 if (Style.Language == FormatStyle::LK_Proto) { 635 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square); 636 } else { 637 // Skip NextTok over preprocessor lines, otherwise we may not 638 // properly diagnose the block as a braced intializer 639 // if the comma separator appears after the pp directive. 640 while (NextTok->is(tok::hash)) { 641 ScopedMacroState MacroState(*Line, Tokens, NextTok); 642 do { 643 NextTok = Tokens->getNextToken(); 644 } while (NextTok->isNot(tok::eof)); 645 } 646 647 // Using OriginalColumn to distinguish between ObjC methods and 648 // binary operators is a bit hacky. 649 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) && 650 NextTok->OriginalColumn == 0; 651 652 // Try to detect a braced list. Note that regardless how we mark inner 653 // braces here, we will overwrite the BlockKind later if we parse a 654 // braced list (where all blocks inside are by default braced lists), 655 // or when we explicitly detect blocks (for example while parsing 656 // lambdas). 657 658 // If we already marked the opening brace as braced list, the closing 659 // must also be part of it. 660 ProbablyBracedList = LBraceStack.back()->is(TT_BracedListLBrace); 661 662 ProbablyBracedList = ProbablyBracedList || 663 (Style.isJavaScript() && 664 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in, 665 Keywords.kw_as)); 666 ProbablyBracedList = ProbablyBracedList || 667 (Style.isCpp() && NextTok->is(tok::l_paren)); 668 669 // If there is a comma, semicolon or right paren after the closing 670 // brace, we assume this is a braced initializer list. 671 // FIXME: Some of these do not apply to JS, e.g. "} {" can never be a 672 // braced list in JS. 673 ProbablyBracedList = 674 ProbablyBracedList || 675 NextTok->isOneOf(tok::comma, tok::period, tok::colon, 676 tok::r_paren, tok::r_square, tok::l_brace, 677 tok::ellipsis); 678 679 ProbablyBracedList = 680 ProbablyBracedList || 681 (NextTok->is(tok::identifier) && 682 !PrevTok->isOneOf(tok::semi, tok::r_brace, tok::l_brace)); 683 684 ProbablyBracedList = ProbablyBracedList || 685 (NextTok->is(tok::semi) && 686 (!ExpectClassBody || LBraceStack.size() != 1)); 687 688 ProbablyBracedList = 689 ProbablyBracedList || 690 (NextTok->isBinaryOperator() && !NextIsObjCMethod); 691 692 if (!Style.isCSharp() && NextTok->is(tok::l_square)) { 693 // We can have an array subscript after a braced init 694 // list, but C++11 attributes are expected after blocks. 695 NextTok = Tokens->getNextToken(); 696 ProbablyBracedList = NextTok->isNot(tok::l_square); 697 } 698 } 699 if (ProbablyBracedList) { 700 Tok->setBlockKind(BK_BracedInit); 701 LBraceStack.back()->setBlockKind(BK_BracedInit); 702 } else { 703 Tok->setBlockKind(BK_Block); 704 LBraceStack.back()->setBlockKind(BK_Block); 705 } 706 } 707 LBraceStack.pop_back(); 708 break; 709 case tok::identifier: 710 if (!Tok->is(TT_StatementMacro)) 711 break; 712 LLVM_FALLTHROUGH; 713 case tok::at: 714 case tok::semi: 715 case tok::kw_if: 716 case tok::kw_while: 717 case tok::kw_for: 718 case tok::kw_switch: 719 case tok::kw_try: 720 case tok::kw___try: 721 if (!LBraceStack.empty() && LBraceStack.back()->is(BK_Unknown)) 722 LBraceStack.back()->setBlockKind(BK_Block); 723 break; 724 default: 725 break; 726 } 727 PrevTok = Tok; 728 Tok = NextTok; 729 } while (Tok->isNot(tok::eof) && !LBraceStack.empty()); 730 731 // Assume other blocks for all unclosed opening braces. 732 for (FormatToken *LBrace : LBraceStack) 733 if (LBrace->is(BK_Unknown)) 734 LBrace->setBlockKind(BK_Block); 735 736 FormatTok = Tokens->setPosition(StoredPosition); 737 } 738 739 template <class T> 740 static inline void hash_combine(std::size_t &seed, const T &v) { 741 std::hash<T> hasher; 742 seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); 743 } 744 745 size_t UnwrappedLineParser::computePPHash() const { 746 size_t h = 0; 747 for (const auto &i : PPStack) { 748 hash_combine(h, size_t(i.Kind)); 749 hash_combine(h, i.Line); 750 } 751 return h; 752 } 753 754 UnwrappedLineParser::IfStmtKind 755 UnwrappedLineParser::parseBlock(bool MustBeDeclaration, unsigned AddLevels, 756 bool MunchSemi, bool UnindentWhitesmithsBraces, 757 bool CanContainBracedList, 758 TokenType NextLBracesType) { 759 assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) && 760 "'{' or macro block token expected"); 761 FormatToken *Tok = FormatTok; 762 const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin); 763 FormatTok->setBlockKind(BK_Block); 764 765 // For Whitesmiths mode, jump to the next level prior to skipping over the 766 // braces. 767 if (AddLevels > 0 && Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) 768 ++Line->Level; 769 770 size_t PPStartHash = computePPHash(); 771 772 unsigned InitialLevel = Line->Level; 773 nextToken(/*LevelDifference=*/AddLevels); 774 775 if (MacroBlock && FormatTok->is(tok::l_paren)) 776 parseParens(); 777 778 size_t NbPreprocessorDirectives = 779 CurrentLines == &Lines ? PreprocessorDirectives.size() : 0; 780 addUnwrappedLine(); 781 size_t OpeningLineIndex = 782 CurrentLines->empty() 783 ? (UnwrappedLine::kInvalidIndex) 784 : (CurrentLines->size() - 1 - NbPreprocessorDirectives); 785 786 // Whitesmiths is weird here. The brace needs to be indented for the namespace 787 // block, but the block itself may not be indented depending on the style 788 // settings. This allows the format to back up one level in those cases. 789 if (UnindentWhitesmithsBraces) 790 --Line->Level; 791 792 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack, 793 MustBeDeclaration); 794 if (AddLevels > 0u && Style.BreakBeforeBraces != FormatStyle::BS_Whitesmiths) 795 Line->Level += AddLevels; 796 797 IfStmtKind IfKind = IfStmtKind::NotIf; 798 const bool SimpleBlock = parseLevel( 799 /*HasOpeningBrace=*/true, CanContainBracedList, &IfKind, NextLBracesType); 800 801 if (eof()) 802 return IfKind; 803 804 if (MacroBlock ? !FormatTok->is(TT_MacroBlockEnd) 805 : !FormatTok->is(tok::r_brace)) { 806 Line->Level = InitialLevel; 807 FormatTok->setBlockKind(BK_Block); 808 return IfKind; 809 } 810 811 if (SimpleBlock && Tok->is(tok::l_brace)) { 812 assert(FormatTok->is(tok::r_brace)); 813 const FormatToken *Previous = Tokens->getPreviousToken(); 814 assert(Previous); 815 if (Previous->isNot(tok::r_brace) || Previous->Optional) { 816 Tok->MatchingParen = FormatTok; 817 FormatTok->MatchingParen = Tok; 818 } 819 } 820 821 size_t PPEndHash = computePPHash(); 822 823 // Munch the closing brace. 824 nextToken(/*LevelDifference=*/-AddLevels); 825 826 if (MacroBlock && FormatTok->is(tok::l_paren)) 827 parseParens(); 828 829 if (FormatTok->is(tok::kw_noexcept)) { 830 // A noexcept in a requires expression. 831 nextToken(); 832 } 833 834 if (FormatTok->is(tok::arrow)) { 835 // Following the } or noexcept we can find a trailing return type arrow 836 // as part of an implicit conversion constraint. 837 nextToken(); 838 parseStructuralElement(); 839 } 840 841 if (MunchSemi && FormatTok->is(tok::semi)) 842 nextToken(); 843 844 Line->Level = InitialLevel; 845 846 if (PPStartHash == PPEndHash) { 847 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex; 848 if (OpeningLineIndex != UnwrappedLine::kInvalidIndex) { 849 // Update the opening line to add the forward reference as well 850 (*CurrentLines)[OpeningLineIndex].MatchingClosingBlockLineIndex = 851 CurrentLines->size() - 1; 852 } 853 } 854 855 return IfKind; 856 } 857 858 static bool isGoogScope(const UnwrappedLine &Line) { 859 // FIXME: Closure-library specific stuff should not be hard-coded but be 860 // configurable. 861 if (Line.Tokens.size() < 4) 862 return false; 863 auto I = Line.Tokens.begin(); 864 if (I->Tok->TokenText != "goog") 865 return false; 866 ++I; 867 if (I->Tok->isNot(tok::period)) 868 return false; 869 ++I; 870 if (I->Tok->TokenText != "scope") 871 return false; 872 ++I; 873 return I->Tok->is(tok::l_paren); 874 } 875 876 static bool isIIFE(const UnwrappedLine &Line, 877 const AdditionalKeywords &Keywords) { 878 // Look for the start of an immediately invoked anonymous function. 879 // https://en.wikipedia.org/wiki/Immediately-invoked_function_expression 880 // This is commonly done in JavaScript to create a new, anonymous scope. 881 // Example: (function() { ... })() 882 if (Line.Tokens.size() < 3) 883 return false; 884 auto I = Line.Tokens.begin(); 885 if (I->Tok->isNot(tok::l_paren)) 886 return false; 887 ++I; 888 if (I->Tok->isNot(Keywords.kw_function)) 889 return false; 890 ++I; 891 return I->Tok->is(tok::l_paren); 892 } 893 894 static bool ShouldBreakBeforeBrace(const FormatStyle &Style, 895 const FormatToken &InitialToken) { 896 tok::TokenKind Kind = InitialToken.Tok.getKind(); 897 if (InitialToken.is(TT_NamespaceMacro)) 898 Kind = tok::kw_namespace; 899 900 switch (Kind) { 901 case tok::kw_namespace: 902 return Style.BraceWrapping.AfterNamespace; 903 case tok::kw_class: 904 return Style.BraceWrapping.AfterClass; 905 case tok::kw_union: 906 return Style.BraceWrapping.AfterUnion; 907 case tok::kw_struct: 908 return Style.BraceWrapping.AfterStruct; 909 case tok::kw_enum: 910 return Style.BraceWrapping.AfterEnum; 911 default: 912 return false; 913 } 914 } 915 916 void UnwrappedLineParser::parseChildBlock( 917 bool CanContainBracedList, clang::format::TokenType NextLBracesType) { 918 FormatTok->setBlockKind(BK_Block); 919 nextToken(); 920 { 921 bool SkipIndent = (Style.isJavaScript() && 922 (isGoogScope(*Line) || isIIFE(*Line, Keywords))); 923 ScopedLineState LineState(*this); 924 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack, 925 /*MustBeDeclaration=*/false); 926 Line->Level += SkipIndent ? 0 : 1; 927 parseLevel(/*HasOpeningBrace=*/true, CanContainBracedList, 928 /*IfKind=*/nullptr, NextLBracesType); 929 flushComments(isOnNewLine(*FormatTok)); 930 Line->Level -= SkipIndent ? 0 : 1; 931 } 932 nextToken(); 933 } 934 935 void UnwrappedLineParser::parsePPDirective() { 936 assert(FormatTok->is(tok::hash) && "'#' expected"); 937 ScopedMacroState MacroState(*Line, Tokens, FormatTok); 938 939 nextToken(); 940 941 if (!FormatTok->Tok.getIdentifierInfo()) { 942 parsePPUnknown(); 943 return; 944 } 945 946 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) { 947 case tok::pp_define: 948 parsePPDefine(); 949 return; 950 case tok::pp_if: 951 parsePPIf(/*IfDef=*/false); 952 break; 953 case tok::pp_ifdef: 954 case tok::pp_ifndef: 955 parsePPIf(/*IfDef=*/true); 956 break; 957 case tok::pp_else: 958 parsePPElse(); 959 break; 960 case tok::pp_elifdef: 961 case tok::pp_elifndef: 962 case tok::pp_elif: 963 parsePPElIf(); 964 break; 965 case tok::pp_endif: 966 parsePPEndIf(); 967 break; 968 default: 969 parsePPUnknown(); 970 break; 971 } 972 } 973 974 void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) { 975 size_t Line = CurrentLines->size(); 976 if (CurrentLines == &PreprocessorDirectives) 977 Line += Lines.size(); 978 979 if (Unreachable || 980 (!PPStack.empty() && PPStack.back().Kind == PP_Unreachable)) 981 PPStack.push_back({PP_Unreachable, Line}); 982 else 983 PPStack.push_back({PP_Conditional, Line}); 984 } 985 986 void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) { 987 ++PPBranchLevel; 988 assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size()); 989 if (PPBranchLevel == (int)PPLevelBranchIndex.size()) { 990 PPLevelBranchIndex.push_back(0); 991 PPLevelBranchCount.push_back(0); 992 } 993 PPChainBranchIndex.push(0); 994 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0; 995 conditionalCompilationCondition(Unreachable || Skip); 996 } 997 998 void UnwrappedLineParser::conditionalCompilationAlternative() { 999 if (!PPStack.empty()) 1000 PPStack.pop_back(); 1001 assert(PPBranchLevel < (int)PPLevelBranchIndex.size()); 1002 if (!PPChainBranchIndex.empty()) 1003 ++PPChainBranchIndex.top(); 1004 conditionalCompilationCondition( 1005 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() && 1006 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top()); 1007 } 1008 1009 void UnwrappedLineParser::conditionalCompilationEnd() { 1010 assert(PPBranchLevel < (int)PPLevelBranchIndex.size()); 1011 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) { 1012 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) 1013 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1; 1014 } 1015 // Guard against #endif's without #if. 1016 if (PPBranchLevel > -1) 1017 --PPBranchLevel; 1018 if (!PPChainBranchIndex.empty()) 1019 PPChainBranchIndex.pop(); 1020 if (!PPStack.empty()) 1021 PPStack.pop_back(); 1022 } 1023 1024 void UnwrappedLineParser::parsePPIf(bool IfDef) { 1025 bool IfNDef = FormatTok->is(tok::pp_ifndef); 1026 nextToken(); 1027 bool Unreachable = false; 1028 if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText == "0")) 1029 Unreachable = true; 1030 if (IfDef && !IfNDef && FormatTok->TokenText == "SWIG") 1031 Unreachable = true; 1032 conditionalCompilationStart(Unreachable); 1033 FormatToken *IfCondition = FormatTok; 1034 // If there's a #ifndef on the first line, and the only lines before it are 1035 // comments, it could be an include guard. 1036 bool MaybeIncludeGuard = IfNDef; 1037 if (IncludeGuard == IG_Inited && MaybeIncludeGuard) 1038 for (auto &Line : Lines) { 1039 if (!Line.Tokens.front().Tok->is(tok::comment)) { 1040 MaybeIncludeGuard = false; 1041 IncludeGuard = IG_Rejected; 1042 break; 1043 } 1044 } 1045 --PPBranchLevel; 1046 parsePPUnknown(); 1047 ++PPBranchLevel; 1048 if (IncludeGuard == IG_Inited && MaybeIncludeGuard) { 1049 IncludeGuard = IG_IfNdefed; 1050 IncludeGuardToken = IfCondition; 1051 } 1052 } 1053 1054 void UnwrappedLineParser::parsePPElse() { 1055 // If a potential include guard has an #else, it's not an include guard. 1056 if (IncludeGuard == IG_Defined && PPBranchLevel == 0) 1057 IncludeGuard = IG_Rejected; 1058 conditionalCompilationAlternative(); 1059 if (PPBranchLevel > -1) 1060 --PPBranchLevel; 1061 parsePPUnknown(); 1062 ++PPBranchLevel; 1063 } 1064 1065 void UnwrappedLineParser::parsePPElIf() { parsePPElse(); } 1066 1067 void UnwrappedLineParser::parsePPEndIf() { 1068 conditionalCompilationEnd(); 1069 parsePPUnknown(); 1070 // If the #endif of a potential include guard is the last thing in the file, 1071 // then we found an include guard. 1072 if (IncludeGuard == IG_Defined && PPBranchLevel == -1 && Tokens->isEOF() && 1073 Style.IndentPPDirectives != FormatStyle::PPDIS_None) 1074 IncludeGuard = IG_Found; 1075 } 1076 1077 void UnwrappedLineParser::parsePPDefine() { 1078 nextToken(); 1079 1080 if (!FormatTok->Tok.getIdentifierInfo()) { 1081 IncludeGuard = IG_Rejected; 1082 IncludeGuardToken = nullptr; 1083 parsePPUnknown(); 1084 return; 1085 } 1086 1087 if (IncludeGuard == IG_IfNdefed && 1088 IncludeGuardToken->TokenText == FormatTok->TokenText) { 1089 IncludeGuard = IG_Defined; 1090 IncludeGuardToken = nullptr; 1091 for (auto &Line : Lines) { 1092 if (!Line.Tokens.front().Tok->isOneOf(tok::comment, tok::hash)) { 1093 IncludeGuard = IG_Rejected; 1094 break; 1095 } 1096 } 1097 } 1098 1099 // In the context of a define, even keywords should be treated as normal 1100 // identifiers. Setting the kind to identifier is not enough, because we need 1101 // to treat additional keywords like __except as well, which are already 1102 // identifiers. Setting the identifier info to null interferes with include 1103 // guard processing above, and changes preprocessing nesting. 1104 FormatTok->Tok.setKind(tok::identifier); 1105 FormatTok->Tok.setIdentifierInfo(Keywords.kw_internal_ident_after_define); 1106 nextToken(); 1107 if (FormatTok->Tok.getKind() == tok::l_paren && 1108 !FormatTok->hasWhitespaceBefore()) 1109 parseParens(); 1110 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None) 1111 Line->Level += PPBranchLevel + 1; 1112 addUnwrappedLine(); 1113 ++Line->Level; 1114 1115 // Errors during a preprocessor directive can only affect the layout of the 1116 // preprocessor directive, and thus we ignore them. An alternative approach 1117 // would be to use the same approach we use on the file level (no 1118 // re-indentation if there was a structural error) within the macro 1119 // definition. 1120 parseFile(); 1121 } 1122 1123 void UnwrappedLineParser::parsePPUnknown() { 1124 do { 1125 nextToken(); 1126 } while (!eof()); 1127 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None) 1128 Line->Level += PPBranchLevel + 1; 1129 addUnwrappedLine(); 1130 } 1131 1132 // Here we exclude certain tokens that are not usually the first token in an 1133 // unwrapped line. This is used in attempt to distinguish macro calls without 1134 // trailing semicolons from other constructs split to several lines. 1135 static bool tokenCanStartNewLine(const FormatToken &Tok) { 1136 // Semicolon can be a null-statement, l_square can be a start of a macro or 1137 // a C++11 attribute, but this doesn't seem to be common. 1138 return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) && 1139 Tok.isNot(TT_AttributeSquare) && 1140 // Tokens that can only be used as binary operators and a part of 1141 // overloaded operator names. 1142 Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) && 1143 Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) && 1144 Tok.isNot(tok::less) && Tok.isNot(tok::greater) && 1145 Tok.isNot(tok::slash) && Tok.isNot(tok::percent) && 1146 Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) && 1147 Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) && 1148 Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) && 1149 Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) && 1150 Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) && 1151 Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) && 1152 Tok.isNot(tok::lesslessequal) && 1153 // Colon is used in labels, base class lists, initializer lists, 1154 // range-based for loops, ternary operator, but should never be the 1155 // first token in an unwrapped line. 1156 Tok.isNot(tok::colon) && 1157 // 'noexcept' is a trailing annotation. 1158 Tok.isNot(tok::kw_noexcept); 1159 } 1160 1161 static bool mustBeJSIdent(const AdditionalKeywords &Keywords, 1162 const FormatToken *FormatTok) { 1163 // FIXME: This returns true for C/C++ keywords like 'struct'. 1164 return FormatTok->is(tok::identifier) && 1165 (FormatTok->Tok.getIdentifierInfo() == nullptr || 1166 !FormatTok->isOneOf( 1167 Keywords.kw_in, Keywords.kw_of, Keywords.kw_as, Keywords.kw_async, 1168 Keywords.kw_await, Keywords.kw_yield, Keywords.kw_finally, 1169 Keywords.kw_function, Keywords.kw_import, Keywords.kw_is, 1170 Keywords.kw_let, Keywords.kw_var, tok::kw_const, 1171 Keywords.kw_abstract, Keywords.kw_extends, Keywords.kw_implements, 1172 Keywords.kw_instanceof, Keywords.kw_interface, 1173 Keywords.kw_override, Keywords.kw_throws, Keywords.kw_from)); 1174 } 1175 1176 static bool mustBeJSIdentOrValue(const AdditionalKeywords &Keywords, 1177 const FormatToken *FormatTok) { 1178 return FormatTok->Tok.isLiteral() || 1179 FormatTok->isOneOf(tok::kw_true, tok::kw_false) || 1180 mustBeJSIdent(Keywords, FormatTok); 1181 } 1182 1183 // isJSDeclOrStmt returns true if |FormatTok| starts a declaration or statement 1184 // when encountered after a value (see mustBeJSIdentOrValue). 1185 static bool isJSDeclOrStmt(const AdditionalKeywords &Keywords, 1186 const FormatToken *FormatTok) { 1187 return FormatTok->isOneOf( 1188 tok::kw_return, Keywords.kw_yield, 1189 // conditionals 1190 tok::kw_if, tok::kw_else, 1191 // loops 1192 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break, 1193 // switch/case 1194 tok::kw_switch, tok::kw_case, 1195 // exceptions 1196 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.kw_finally, 1197 // declaration 1198 tok::kw_const, tok::kw_class, Keywords.kw_var, Keywords.kw_let, 1199 Keywords.kw_async, Keywords.kw_function, 1200 // import/export 1201 Keywords.kw_import, tok::kw_export); 1202 } 1203 1204 // Checks whether a token is a type in K&R C (aka C78). 1205 static bool isC78Type(const FormatToken &Tok) { 1206 return Tok.isOneOf(tok::kw_char, tok::kw_short, tok::kw_int, tok::kw_long, 1207 tok::kw_unsigned, tok::kw_float, tok::kw_double, 1208 tok::identifier); 1209 } 1210 1211 // This function checks whether a token starts the first parameter declaration 1212 // in a K&R C (aka C78) function definition, e.g.: 1213 // int f(a, b) 1214 // short a, b; 1215 // { 1216 // return a + b; 1217 // } 1218 static bool isC78ParameterDecl(const FormatToken *Tok, const FormatToken *Next, 1219 const FormatToken *FuncName) { 1220 assert(Tok); 1221 assert(Next); 1222 assert(FuncName); 1223 1224 if (FuncName->isNot(tok::identifier)) 1225 return false; 1226 1227 const FormatToken *Prev = FuncName->Previous; 1228 if (!Prev || (Prev->isNot(tok::star) && !isC78Type(*Prev))) 1229 return false; 1230 1231 if (!isC78Type(*Tok) && 1232 !Tok->isOneOf(tok::kw_register, tok::kw_struct, tok::kw_union)) 1233 return false; 1234 1235 if (Next->isNot(tok::star) && !Next->Tok.getIdentifierInfo()) 1236 return false; 1237 1238 Tok = Tok->Previous; 1239 if (!Tok || Tok->isNot(tok::r_paren)) 1240 return false; 1241 1242 Tok = Tok->Previous; 1243 if (!Tok || Tok->isNot(tok::identifier)) 1244 return false; 1245 1246 return Tok->Previous && Tok->Previous->isOneOf(tok::l_paren, tok::comma); 1247 } 1248 1249 void UnwrappedLineParser::parseModuleImport() { 1250 nextToken(); 1251 while (!eof()) { 1252 if (FormatTok->is(tok::colon)) { 1253 FormatTok->setFinalizedType(TT_ModulePartitionColon); 1254 } 1255 // Handle import <foo/bar.h> as we would an include statement. 1256 else if (FormatTok->is(tok::less)) { 1257 nextToken(); 1258 while (!FormatTok->isOneOf(tok::semi, tok::greater, tok::eof)) { 1259 // Mark tokens up to the trailing line comments as implicit string 1260 // literals. 1261 if (FormatTok->isNot(tok::comment) && 1262 !FormatTok->TokenText.startswith("//")) 1263 FormatTok->setFinalizedType(TT_ImplicitStringLiteral); 1264 nextToken(); 1265 } 1266 } 1267 if (FormatTok->is(tok::semi)) { 1268 nextToken(); 1269 break; 1270 } 1271 nextToken(); 1272 } 1273 1274 addUnwrappedLine(); 1275 } 1276 1277 // readTokenWithJavaScriptASI reads the next token and terminates the current 1278 // line if JavaScript Automatic Semicolon Insertion must 1279 // happen between the current token and the next token. 1280 // 1281 // This method is conservative - it cannot cover all edge cases of JavaScript, 1282 // but only aims to correctly handle certain well known cases. It *must not* 1283 // return true in speculative cases. 1284 void UnwrappedLineParser::readTokenWithJavaScriptASI() { 1285 FormatToken *Previous = FormatTok; 1286 readToken(); 1287 FormatToken *Next = FormatTok; 1288 1289 bool IsOnSameLine = 1290 CommentsBeforeNextToken.empty() 1291 ? Next->NewlinesBefore == 0 1292 : CommentsBeforeNextToken.front()->NewlinesBefore == 0; 1293 if (IsOnSameLine) 1294 return; 1295 1296 bool PreviousMustBeValue = mustBeJSIdentOrValue(Keywords, Previous); 1297 bool PreviousStartsTemplateExpr = 1298 Previous->is(TT_TemplateString) && Previous->TokenText.endswith("${"); 1299 if (PreviousMustBeValue || Previous->is(tok::r_paren)) { 1300 // If the line contains an '@' sign, the previous token might be an 1301 // annotation, which can precede another identifier/value. 1302 bool HasAt = llvm::any_of(Line->Tokens, [](UnwrappedLineNode &LineNode) { 1303 return LineNode.Tok->is(tok::at); 1304 }); 1305 if (HasAt) 1306 return; 1307 } 1308 if (Next->is(tok::exclaim) && PreviousMustBeValue) 1309 return addUnwrappedLine(); 1310 bool NextMustBeValue = mustBeJSIdentOrValue(Keywords, Next); 1311 bool NextEndsTemplateExpr = 1312 Next->is(TT_TemplateString) && Next->TokenText.startswith("}"); 1313 if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr && 1314 (PreviousMustBeValue || 1315 Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus, 1316 tok::minusminus))) 1317 return addUnwrappedLine(); 1318 if ((PreviousMustBeValue || Previous->is(tok::r_paren)) && 1319 isJSDeclOrStmt(Keywords, Next)) 1320 return addUnwrappedLine(); 1321 } 1322 1323 void UnwrappedLineParser::parseStructuralElement(IfStmtKind *IfKind, 1324 bool IsTopLevel, 1325 TokenType NextLBracesType, 1326 bool *HasLabel) { 1327 if (Style.Language == FormatStyle::LK_TableGen && 1328 FormatTok->is(tok::pp_include)) { 1329 nextToken(); 1330 if (FormatTok->is(tok::string_literal)) 1331 nextToken(); 1332 addUnwrappedLine(); 1333 return; 1334 } 1335 switch (FormatTok->Tok.getKind()) { 1336 case tok::kw_asm: 1337 nextToken(); 1338 if (FormatTok->is(tok::l_brace)) { 1339 FormatTok->setFinalizedType(TT_InlineASMBrace); 1340 nextToken(); 1341 while (FormatTok && FormatTok->isNot(tok::eof)) { 1342 if (FormatTok->is(tok::r_brace)) { 1343 FormatTok->setFinalizedType(TT_InlineASMBrace); 1344 nextToken(); 1345 addUnwrappedLine(); 1346 break; 1347 } 1348 FormatTok->Finalized = true; 1349 nextToken(); 1350 } 1351 } 1352 break; 1353 case tok::kw_namespace: 1354 parseNamespace(); 1355 return; 1356 case tok::kw_public: 1357 case tok::kw_protected: 1358 case tok::kw_private: 1359 if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() || 1360 Style.isCSharp()) 1361 nextToken(); 1362 else 1363 parseAccessSpecifier(); 1364 return; 1365 case tok::kw_if: 1366 if (Style.isJavaScript() && Line->MustBeDeclaration) 1367 // field/method declaration. 1368 break; 1369 parseIfThenElse(IfKind); 1370 return; 1371 case tok::kw_for: 1372 case tok::kw_while: 1373 if (Style.isJavaScript() && Line->MustBeDeclaration) 1374 // field/method declaration. 1375 break; 1376 parseForOrWhileLoop(); 1377 return; 1378 case tok::kw_do: 1379 if (Style.isJavaScript() && Line->MustBeDeclaration) 1380 // field/method declaration. 1381 break; 1382 parseDoWhile(); 1383 return; 1384 case tok::kw_switch: 1385 if (Style.isJavaScript() && Line->MustBeDeclaration) 1386 // 'switch: string' field declaration. 1387 break; 1388 parseSwitch(); 1389 return; 1390 case tok::kw_default: 1391 if (Style.isJavaScript() && Line->MustBeDeclaration) 1392 // 'default: string' field declaration. 1393 break; 1394 nextToken(); 1395 if (FormatTok->is(tok::colon)) { 1396 parseLabel(); 1397 return; 1398 } 1399 // e.g. "default void f() {}" in a Java interface. 1400 break; 1401 case tok::kw_case: 1402 if (Style.isJavaScript() && Line->MustBeDeclaration) { 1403 // 'case: string' field declaration. 1404 nextToken(); 1405 break; 1406 } 1407 parseCaseLabel(); 1408 return; 1409 case tok::kw_try: 1410 case tok::kw___try: 1411 if (Style.isJavaScript() && Line->MustBeDeclaration) 1412 // field/method declaration. 1413 break; 1414 parseTryCatch(); 1415 return; 1416 case tok::kw_extern: 1417 nextToken(); 1418 if (FormatTok->is(tok::string_literal)) { 1419 nextToken(); 1420 if (FormatTok->is(tok::l_brace)) { 1421 if (Style.BraceWrapping.AfterExternBlock) 1422 addUnwrappedLine(); 1423 // Either we indent or for backwards compatibility we follow the 1424 // AfterExternBlock style. 1425 unsigned AddLevels = 1426 (Style.IndentExternBlock == FormatStyle::IEBS_Indent) || 1427 (Style.BraceWrapping.AfterExternBlock && 1428 Style.IndentExternBlock == 1429 FormatStyle::IEBS_AfterExternBlock) 1430 ? 1u 1431 : 0u; 1432 parseBlock(/*MustBeDeclaration=*/true, AddLevels); 1433 addUnwrappedLine(); 1434 return; 1435 } 1436 } 1437 break; 1438 case tok::kw_export: 1439 if (Style.isJavaScript()) { 1440 parseJavaScriptEs6ImportExport(); 1441 return; 1442 } 1443 if (!Style.isCpp()) 1444 break; 1445 // Handle C++ "(inline|export) namespace". 1446 LLVM_FALLTHROUGH; 1447 case tok::kw_inline: 1448 nextToken(); 1449 if (FormatTok->is(tok::kw_namespace)) { 1450 parseNamespace(); 1451 return; 1452 } 1453 break; 1454 case tok::identifier: 1455 if (FormatTok->is(TT_ForEachMacro)) { 1456 parseForOrWhileLoop(); 1457 return; 1458 } 1459 if (FormatTok->is(TT_MacroBlockBegin)) { 1460 parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u, 1461 /*MunchSemi=*/false); 1462 return; 1463 } 1464 if (FormatTok->is(Keywords.kw_import)) { 1465 if (Style.isJavaScript()) { 1466 parseJavaScriptEs6ImportExport(); 1467 return; 1468 } 1469 if (Style.Language == FormatStyle::LK_Proto) { 1470 nextToken(); 1471 if (FormatTok->is(tok::kw_public)) 1472 nextToken(); 1473 if (!FormatTok->is(tok::string_literal)) 1474 return; 1475 nextToken(); 1476 if (FormatTok->is(tok::semi)) 1477 nextToken(); 1478 addUnwrappedLine(); 1479 return; 1480 } 1481 if (Style.isCpp()) { 1482 parseModuleImport(); 1483 return; 1484 } 1485 } 1486 if (Style.isCpp() && 1487 FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals, 1488 Keywords.kw_slots, Keywords.kw_qslots)) { 1489 nextToken(); 1490 if (FormatTok->is(tok::colon)) { 1491 nextToken(); 1492 addUnwrappedLine(); 1493 return; 1494 } 1495 } 1496 if (Style.isCpp() && FormatTok->is(TT_StatementMacro)) { 1497 parseStatementMacro(); 1498 return; 1499 } 1500 if (Style.isCpp() && FormatTok->is(TT_NamespaceMacro)) { 1501 parseNamespace(); 1502 return; 1503 } 1504 // In all other cases, parse the declaration. 1505 break; 1506 default: 1507 break; 1508 } 1509 do { 1510 const FormatToken *Previous = FormatTok->Previous; 1511 switch (FormatTok->Tok.getKind()) { 1512 case tok::at: 1513 nextToken(); 1514 if (FormatTok->is(tok::l_brace)) { 1515 nextToken(); 1516 parseBracedList(); 1517 break; 1518 } else if (Style.Language == FormatStyle::LK_Java && 1519 FormatTok->is(Keywords.kw_interface)) { 1520 nextToken(); 1521 break; 1522 } 1523 switch (FormatTok->Tok.getObjCKeywordID()) { 1524 case tok::objc_public: 1525 case tok::objc_protected: 1526 case tok::objc_package: 1527 case tok::objc_private: 1528 return parseAccessSpecifier(); 1529 case tok::objc_interface: 1530 case tok::objc_implementation: 1531 return parseObjCInterfaceOrImplementation(); 1532 case tok::objc_protocol: 1533 if (parseObjCProtocol()) 1534 return; 1535 break; 1536 case tok::objc_end: 1537 return; // Handled by the caller. 1538 case tok::objc_optional: 1539 case tok::objc_required: 1540 nextToken(); 1541 addUnwrappedLine(); 1542 return; 1543 case tok::objc_autoreleasepool: 1544 nextToken(); 1545 if (FormatTok->is(tok::l_brace)) { 1546 if (Style.BraceWrapping.AfterControlStatement == 1547 FormatStyle::BWACS_Always) 1548 addUnwrappedLine(); 1549 parseBlock(); 1550 } 1551 addUnwrappedLine(); 1552 return; 1553 case tok::objc_synchronized: 1554 nextToken(); 1555 if (FormatTok->is(tok::l_paren)) 1556 // Skip synchronization object 1557 parseParens(); 1558 if (FormatTok->is(tok::l_brace)) { 1559 if (Style.BraceWrapping.AfterControlStatement == 1560 FormatStyle::BWACS_Always) 1561 addUnwrappedLine(); 1562 parseBlock(); 1563 } 1564 addUnwrappedLine(); 1565 return; 1566 case tok::objc_try: 1567 // This branch isn't strictly necessary (the kw_try case below would 1568 // do this too after the tok::at is parsed above). But be explicit. 1569 parseTryCatch(); 1570 return; 1571 default: 1572 break; 1573 } 1574 break; 1575 case tok::kw_concept: 1576 parseConcept(); 1577 return; 1578 case tok::kw_requires: { 1579 if (Style.isCpp()) { 1580 bool ParsedClause = parseRequires(); 1581 if (ParsedClause) 1582 return; 1583 } else { 1584 nextToken(); 1585 } 1586 break; 1587 } 1588 case tok::kw_enum: 1589 // Ignore if this is part of "template <enum ...". 1590 if (Previous && Previous->is(tok::less)) { 1591 nextToken(); 1592 break; 1593 } 1594 1595 // parseEnum falls through and does not yet add an unwrapped line as an 1596 // enum definition can start a structural element. 1597 if (!parseEnum()) 1598 break; 1599 // This only applies for C++. 1600 if (!Style.isCpp()) { 1601 addUnwrappedLine(); 1602 return; 1603 } 1604 break; 1605 case tok::kw_typedef: 1606 nextToken(); 1607 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS, 1608 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS, 1609 Keywords.kw_CF_CLOSED_ENUM, 1610 Keywords.kw_NS_CLOSED_ENUM)) 1611 parseEnum(); 1612 break; 1613 case tok::kw_struct: 1614 case tok::kw_union: 1615 case tok::kw_class: 1616 if (parseStructLike()) 1617 return; 1618 break; 1619 case tok::period: 1620 nextToken(); 1621 // In Java, classes have an implicit static member "class". 1622 if (Style.Language == FormatStyle::LK_Java && FormatTok && 1623 FormatTok->is(tok::kw_class)) 1624 nextToken(); 1625 if (Style.isJavaScript() && FormatTok && 1626 FormatTok->Tok.getIdentifierInfo()) 1627 // JavaScript only has pseudo keywords, all keywords are allowed to 1628 // appear in "IdentifierName" positions. See http://es5.github.io/#x7.6 1629 nextToken(); 1630 break; 1631 case tok::semi: 1632 nextToken(); 1633 addUnwrappedLine(); 1634 return; 1635 case tok::r_brace: 1636 addUnwrappedLine(); 1637 return; 1638 case tok::l_paren: { 1639 parseParens(); 1640 // Break the unwrapped line if a K&R C function definition has a parameter 1641 // declaration. 1642 if (!IsTopLevel || !Style.isCpp() || !Previous || FormatTok->is(tok::eof)) 1643 break; 1644 if (isC78ParameterDecl(FormatTok, Tokens->peekNextToken(), Previous)) { 1645 addUnwrappedLine(); 1646 return; 1647 } 1648 break; 1649 } 1650 case tok::kw_operator: 1651 nextToken(); 1652 if (FormatTok->isBinaryOperator()) 1653 nextToken(); 1654 break; 1655 case tok::caret: 1656 nextToken(); 1657 if (FormatTok->Tok.isAnyIdentifier() || 1658 FormatTok->isSimpleTypeSpecifier()) 1659 nextToken(); 1660 if (FormatTok->is(tok::l_paren)) 1661 parseParens(); 1662 if (FormatTok->is(tok::l_brace)) 1663 parseChildBlock(); 1664 break; 1665 case tok::l_brace: 1666 if (NextLBracesType != TT_Unknown) 1667 FormatTok->setFinalizedType(NextLBracesType); 1668 if (!tryToParsePropertyAccessor() && !tryToParseBracedList()) { 1669 // A block outside of parentheses must be the last part of a 1670 // structural element. 1671 // FIXME: Figure out cases where this is not true, and add projections 1672 // for them (the one we know is missing are lambdas). 1673 if (Style.Language == FormatStyle::LK_Java && 1674 Line->Tokens.front().Tok->is(Keywords.kw_synchronized)) { 1675 // If necessary, we could set the type to something different than 1676 // TT_FunctionLBrace. 1677 if (Style.BraceWrapping.AfterControlStatement == 1678 FormatStyle::BWACS_Always) 1679 addUnwrappedLine(); 1680 } else if (Style.BraceWrapping.AfterFunction) { 1681 addUnwrappedLine(); 1682 } 1683 if (!Line->InPPDirective) 1684 FormatTok->setFinalizedType(TT_FunctionLBrace); 1685 parseBlock(); 1686 addUnwrappedLine(); 1687 return; 1688 } 1689 // Otherwise this was a braced init list, and the structural 1690 // element continues. 1691 break; 1692 case tok::kw_try: 1693 if (Style.isJavaScript() && Line->MustBeDeclaration) { 1694 // field/method declaration. 1695 nextToken(); 1696 break; 1697 } 1698 // We arrive here when parsing function-try blocks. 1699 if (Style.BraceWrapping.AfterFunction) 1700 addUnwrappedLine(); 1701 parseTryCatch(); 1702 return; 1703 case tok::identifier: { 1704 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where) && 1705 Line->MustBeDeclaration) { 1706 addUnwrappedLine(); 1707 parseCSharpGenericTypeConstraint(); 1708 break; 1709 } 1710 if (FormatTok->is(TT_MacroBlockEnd)) { 1711 addUnwrappedLine(); 1712 return; 1713 } 1714 1715 // Function declarations (as opposed to function expressions) are parsed 1716 // on their own unwrapped line by continuing this loop. Function 1717 // expressions (functions that are not on their own line) must not create 1718 // a new unwrapped line, so they are special cased below. 1719 size_t TokenCount = Line->Tokens.size(); 1720 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_function) && 1721 (TokenCount > 1 || (TokenCount == 1 && !Line->Tokens.front().Tok->is( 1722 Keywords.kw_async)))) { 1723 tryToParseJSFunction(); 1724 break; 1725 } 1726 if ((Style.isJavaScript() || Style.Language == FormatStyle::LK_Java) && 1727 FormatTok->is(Keywords.kw_interface)) { 1728 if (Style.isJavaScript()) { 1729 // In JavaScript/TypeScript, "interface" can be used as a standalone 1730 // identifier, e.g. in `var interface = 1;`. If "interface" is 1731 // followed by another identifier, it is very like to be an actual 1732 // interface declaration. 1733 unsigned StoredPosition = Tokens->getPosition(); 1734 FormatToken *Next = Tokens->getNextToken(); 1735 FormatTok = Tokens->setPosition(StoredPosition); 1736 if (!mustBeJSIdent(Keywords, Next)) { 1737 nextToken(); 1738 break; 1739 } 1740 } 1741 parseRecord(); 1742 addUnwrappedLine(); 1743 return; 1744 } 1745 1746 if (FormatTok->is(Keywords.kw_interface)) { 1747 if (parseStructLike()) 1748 return; 1749 break; 1750 } 1751 1752 if (Style.isCpp() && FormatTok->is(TT_StatementMacro)) { 1753 parseStatementMacro(); 1754 return; 1755 } 1756 1757 // See if the following token should start a new unwrapped line. 1758 StringRef Text = FormatTok->TokenText; 1759 1760 FormatToken *PreviousToken = FormatTok; 1761 nextToken(); 1762 1763 // JS doesn't have macros, and within classes colons indicate fields, not 1764 // labels. 1765 if (Style.isJavaScript()) 1766 break; 1767 1768 TokenCount = Line->Tokens.size(); 1769 if (TokenCount == 1 || 1770 (TokenCount == 2 && Line->Tokens.front().Tok->is(tok::comment))) { 1771 if (FormatTok->is(tok::colon) && !Line->MustBeDeclaration) { 1772 Line->Tokens.begin()->Tok->MustBreakBefore = true; 1773 parseLabel(!Style.IndentGotoLabels); 1774 if (HasLabel) 1775 *HasLabel = true; 1776 return; 1777 } 1778 // Recognize function-like macro usages without trailing semicolon as 1779 // well as free-standing macros like Q_OBJECT. 1780 bool FunctionLike = FormatTok->is(tok::l_paren); 1781 if (FunctionLike) 1782 parseParens(); 1783 1784 bool FollowedByNewline = 1785 CommentsBeforeNextToken.empty() 1786 ? FormatTok->NewlinesBefore > 0 1787 : CommentsBeforeNextToken.front()->NewlinesBefore > 0; 1788 1789 if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) && 1790 tokenCanStartNewLine(*FormatTok) && Text == Text.upper()) { 1791 PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro); 1792 addUnwrappedLine(); 1793 return; 1794 } 1795 } 1796 break; 1797 } 1798 case tok::equal: 1799 if ((Style.isJavaScript() || Style.isCSharp()) && 1800 FormatTok->is(TT_FatArrow)) { 1801 tryToParseChildBlock(); 1802 break; 1803 } 1804 1805 nextToken(); 1806 if (FormatTok->is(tok::l_brace)) { 1807 // Block kind should probably be set to BK_BracedInit for any language. 1808 // C# needs this change to ensure that array initialisers and object 1809 // initialisers are indented the same way. 1810 if (Style.isCSharp()) 1811 FormatTok->setBlockKind(BK_BracedInit); 1812 nextToken(); 1813 parseBracedList(); 1814 } else if (Style.Language == FormatStyle::LK_Proto && 1815 FormatTok->is(tok::less)) { 1816 nextToken(); 1817 parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false, 1818 /*ClosingBraceKind=*/tok::greater); 1819 } 1820 break; 1821 case tok::l_square: 1822 parseSquare(); 1823 break; 1824 case tok::kw_new: 1825 parseNew(); 1826 break; 1827 case tok::kw_case: 1828 if (Style.isJavaScript() && Line->MustBeDeclaration) { 1829 // 'case: string' field declaration. 1830 nextToken(); 1831 break; 1832 } 1833 parseCaseLabel(); 1834 break; 1835 default: 1836 nextToken(); 1837 break; 1838 } 1839 } while (!eof()); 1840 } 1841 1842 bool UnwrappedLineParser::tryToParsePropertyAccessor() { 1843 assert(FormatTok->is(tok::l_brace)); 1844 if (!Style.isCSharp()) 1845 return false; 1846 // See if it's a property accessor. 1847 if (FormatTok->Previous->isNot(tok::identifier)) 1848 return false; 1849 1850 // See if we are inside a property accessor. 1851 // 1852 // Record the current tokenPosition so that we can advance and 1853 // reset the current token. `Next` is not set yet so we need 1854 // another way to advance along the token stream. 1855 unsigned int StoredPosition = Tokens->getPosition(); 1856 FormatToken *Tok = Tokens->getNextToken(); 1857 1858 // A trivial property accessor is of the form: 1859 // { [ACCESS_SPECIFIER] [get]; [ACCESS_SPECIFIER] [set|init] } 1860 // Track these as they do not require line breaks to be introduced. 1861 bool HasSpecialAccessor = false; 1862 bool IsTrivialPropertyAccessor = true; 1863 while (!eof()) { 1864 if (Tok->isOneOf(tok::semi, tok::kw_public, tok::kw_private, 1865 tok::kw_protected, Keywords.kw_internal, Keywords.kw_get, 1866 Keywords.kw_init, Keywords.kw_set)) { 1867 if (Tok->isOneOf(Keywords.kw_get, Keywords.kw_init, Keywords.kw_set)) 1868 HasSpecialAccessor = true; 1869 Tok = Tokens->getNextToken(); 1870 continue; 1871 } 1872 if (Tok->isNot(tok::r_brace)) 1873 IsTrivialPropertyAccessor = false; 1874 break; 1875 } 1876 1877 if (!HasSpecialAccessor) { 1878 Tokens->setPosition(StoredPosition); 1879 return false; 1880 } 1881 1882 // Try to parse the property accessor: 1883 // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties 1884 Tokens->setPosition(StoredPosition); 1885 if (!IsTrivialPropertyAccessor && Style.BraceWrapping.AfterFunction) 1886 addUnwrappedLine(); 1887 nextToken(); 1888 do { 1889 switch (FormatTok->Tok.getKind()) { 1890 case tok::r_brace: 1891 nextToken(); 1892 if (FormatTok->is(tok::equal)) { 1893 while (!eof() && FormatTok->isNot(tok::semi)) 1894 nextToken(); 1895 nextToken(); 1896 } 1897 addUnwrappedLine(); 1898 return true; 1899 case tok::l_brace: 1900 ++Line->Level; 1901 parseBlock(/*MustBeDeclaration=*/true); 1902 addUnwrappedLine(); 1903 --Line->Level; 1904 break; 1905 case tok::equal: 1906 if (FormatTok->is(TT_FatArrow)) { 1907 ++Line->Level; 1908 do { 1909 nextToken(); 1910 } while (!eof() && FormatTok->isNot(tok::semi)); 1911 nextToken(); 1912 addUnwrappedLine(); 1913 --Line->Level; 1914 break; 1915 } 1916 nextToken(); 1917 break; 1918 default: 1919 if (FormatTok->isOneOf(Keywords.kw_get, Keywords.kw_init, 1920 Keywords.kw_set) && 1921 !IsTrivialPropertyAccessor) { 1922 // Non-trivial get/set needs to be on its own line. 1923 addUnwrappedLine(); 1924 } 1925 nextToken(); 1926 } 1927 } while (!eof()); 1928 1929 // Unreachable for well-formed code (paired '{' and '}'). 1930 return true; 1931 } 1932 1933 bool UnwrappedLineParser::tryToParseLambda() { 1934 if (!Style.isCpp()) { 1935 nextToken(); 1936 return false; 1937 } 1938 assert(FormatTok->is(tok::l_square)); 1939 FormatToken &LSquare = *FormatTok; 1940 if (!tryToParseLambdaIntroducer()) 1941 return false; 1942 1943 bool SeenArrow = false; 1944 bool InTemplateParameterList = false; 1945 1946 while (FormatTok->isNot(tok::l_brace)) { 1947 if (FormatTok->isSimpleTypeSpecifier()) { 1948 nextToken(); 1949 continue; 1950 } 1951 switch (FormatTok->Tok.getKind()) { 1952 case tok::l_brace: 1953 break; 1954 case tok::l_paren: 1955 parseParens(); 1956 break; 1957 case tok::l_square: 1958 parseSquare(); 1959 break; 1960 case tok::kw_class: 1961 case tok::kw_template: 1962 case tok::kw_typename: 1963 assert(FormatTok->Previous); 1964 if (FormatTok->Previous->is(tok::less)) 1965 InTemplateParameterList = true; 1966 nextToken(); 1967 break; 1968 case tok::amp: 1969 case tok::star: 1970 case tok::kw_const: 1971 case tok::comma: 1972 case tok::less: 1973 case tok::greater: 1974 case tok::identifier: 1975 case tok::numeric_constant: 1976 case tok::coloncolon: 1977 case tok::kw_mutable: 1978 case tok::kw_noexcept: 1979 nextToken(); 1980 break; 1981 // Specialization of a template with an integer parameter can contain 1982 // arithmetic, logical, comparison and ternary operators. 1983 // 1984 // FIXME: This also accepts sequences of operators that are not in the scope 1985 // of a template argument list. 1986 // 1987 // In a C++ lambda a template type can only occur after an arrow. We use 1988 // this as an heuristic to distinguish between Objective-C expressions 1989 // followed by an `a->b` expression, such as: 1990 // ([obj func:arg] + a->b) 1991 // Otherwise the code below would parse as a lambda. 1992 // 1993 // FIXME: This heuristic is incorrect for C++20 generic lambdas with 1994 // explicit template lists: []<bool b = true && false>(U &&u){} 1995 case tok::plus: 1996 case tok::minus: 1997 case tok::exclaim: 1998 case tok::tilde: 1999 case tok::slash: 2000 case tok::percent: 2001 case tok::lessless: 2002 case tok::pipe: 2003 case tok::pipepipe: 2004 case tok::ampamp: 2005 case tok::caret: 2006 case tok::equalequal: 2007 case tok::exclaimequal: 2008 case tok::greaterequal: 2009 case tok::lessequal: 2010 case tok::question: 2011 case tok::colon: 2012 case tok::ellipsis: 2013 case tok::kw_true: 2014 case tok::kw_false: 2015 if (SeenArrow || InTemplateParameterList) { 2016 nextToken(); 2017 break; 2018 } 2019 return true; 2020 case tok::arrow: 2021 // This might or might not actually be a lambda arrow (this could be an 2022 // ObjC method invocation followed by a dereferencing arrow). We might 2023 // reset this back to TT_Unknown in TokenAnnotator. 2024 FormatTok->setFinalizedType(TT_LambdaArrow); 2025 SeenArrow = true; 2026 nextToken(); 2027 break; 2028 default: 2029 return true; 2030 } 2031 } 2032 FormatTok->setFinalizedType(TT_LambdaLBrace); 2033 LSquare.setFinalizedType(TT_LambdaLSquare); 2034 parseChildBlock(); 2035 return true; 2036 } 2037 2038 bool UnwrappedLineParser::tryToParseLambdaIntroducer() { 2039 const FormatToken *Previous = FormatTok->Previous; 2040 if (Previous && 2041 (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new, 2042 tok::kw_delete, tok::l_square) || 2043 FormatTok->isCppStructuredBinding(Style) || Previous->closesScope() || 2044 Previous->isSimpleTypeSpecifier())) { 2045 nextToken(); 2046 return false; 2047 } 2048 nextToken(); 2049 if (FormatTok->is(tok::l_square)) 2050 return false; 2051 parseSquare(/*LambdaIntroducer=*/true); 2052 return true; 2053 } 2054 2055 void UnwrappedLineParser::tryToParseJSFunction() { 2056 assert(FormatTok->is(Keywords.kw_function) || 2057 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)); 2058 if (FormatTok->is(Keywords.kw_async)) 2059 nextToken(); 2060 // Consume "function". 2061 nextToken(); 2062 2063 // Consume * (generator function). Treat it like C++'s overloaded operators. 2064 if (FormatTok->is(tok::star)) { 2065 FormatTok->setFinalizedType(TT_OverloadedOperator); 2066 nextToken(); 2067 } 2068 2069 // Consume function name. 2070 if (FormatTok->is(tok::identifier)) 2071 nextToken(); 2072 2073 if (FormatTok->isNot(tok::l_paren)) 2074 return; 2075 2076 // Parse formal parameter list. 2077 parseParens(); 2078 2079 if (FormatTok->is(tok::colon)) { 2080 // Parse a type definition. 2081 nextToken(); 2082 2083 // Eat the type declaration. For braced inline object types, balance braces, 2084 // otherwise just parse until finding an l_brace for the function body. 2085 if (FormatTok->is(tok::l_brace)) 2086 tryToParseBracedList(); 2087 else 2088 while (!FormatTok->isOneOf(tok::l_brace, tok::semi) && !eof()) 2089 nextToken(); 2090 } 2091 2092 if (FormatTok->is(tok::semi)) 2093 return; 2094 2095 parseChildBlock(); 2096 } 2097 2098 bool UnwrappedLineParser::tryToParseBracedList() { 2099 if (FormatTok->is(BK_Unknown)) 2100 calculateBraceTypes(); 2101 assert(FormatTok->isNot(BK_Unknown)); 2102 if (FormatTok->is(BK_Block)) 2103 return false; 2104 nextToken(); 2105 parseBracedList(); 2106 return true; 2107 } 2108 2109 bool UnwrappedLineParser::tryToParseChildBlock() { 2110 assert(Style.isJavaScript() || Style.isCSharp()); 2111 assert(FormatTok->is(TT_FatArrow)); 2112 // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType TT_FatArrow. 2113 // They always start an expression or a child block if followed by a curly 2114 // brace. 2115 nextToken(); 2116 if (FormatTok->isNot(tok::l_brace)) 2117 return false; 2118 parseChildBlock(); 2119 return true; 2120 } 2121 2122 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons, 2123 bool IsEnum, 2124 tok::TokenKind ClosingBraceKind) { 2125 bool HasError = false; 2126 2127 // FIXME: Once we have an expression parser in the UnwrappedLineParser, 2128 // replace this by using parseAssignmentExpression() inside. 2129 do { 2130 if (Style.isCSharp() && FormatTok->is(TT_FatArrow) && 2131 tryToParseChildBlock()) 2132 continue; 2133 if (Style.isJavaScript()) { 2134 if (FormatTok->is(Keywords.kw_function) || 2135 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) { 2136 tryToParseJSFunction(); 2137 continue; 2138 } 2139 if (FormatTok->is(tok::l_brace)) { 2140 // Could be a method inside of a braced list `{a() { return 1; }}`. 2141 if (tryToParseBracedList()) 2142 continue; 2143 parseChildBlock(); 2144 } 2145 } 2146 if (FormatTok->Tok.getKind() == ClosingBraceKind) { 2147 if (IsEnum && !Style.AllowShortEnumsOnASingleLine) 2148 addUnwrappedLine(); 2149 nextToken(); 2150 return !HasError; 2151 } 2152 switch (FormatTok->Tok.getKind()) { 2153 case tok::l_square: 2154 if (Style.isCSharp()) 2155 parseSquare(); 2156 else 2157 tryToParseLambda(); 2158 break; 2159 case tok::l_paren: 2160 parseParens(); 2161 // JavaScript can just have free standing methods and getters/setters in 2162 // object literals. Detect them by a "{" following ")". 2163 if (Style.isJavaScript()) { 2164 if (FormatTok->is(tok::l_brace)) 2165 parseChildBlock(); 2166 break; 2167 } 2168 break; 2169 case tok::l_brace: 2170 // Assume there are no blocks inside a braced init list apart 2171 // from the ones we explicitly parse out (like lambdas). 2172 FormatTok->setBlockKind(BK_BracedInit); 2173 nextToken(); 2174 parseBracedList(); 2175 break; 2176 case tok::less: 2177 if (Style.Language == FormatStyle::LK_Proto) { 2178 nextToken(); 2179 parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false, 2180 /*ClosingBraceKind=*/tok::greater); 2181 } else { 2182 nextToken(); 2183 } 2184 break; 2185 case tok::semi: 2186 // JavaScript (or more precisely TypeScript) can have semicolons in braced 2187 // lists (in so-called TypeMemberLists). Thus, the semicolon cannot be 2188 // used for error recovery if we have otherwise determined that this is 2189 // a braced list. 2190 if (Style.isJavaScript()) { 2191 nextToken(); 2192 break; 2193 } 2194 HasError = true; 2195 if (!ContinueOnSemicolons) 2196 return !HasError; 2197 nextToken(); 2198 break; 2199 case tok::comma: 2200 nextToken(); 2201 if (IsEnum && !Style.AllowShortEnumsOnASingleLine) 2202 addUnwrappedLine(); 2203 break; 2204 default: 2205 nextToken(); 2206 break; 2207 } 2208 } while (!eof()); 2209 return false; 2210 } 2211 2212 /// \brief Parses a pair of parentheses (and everything between them). 2213 /// \param AmpAmpTokenType If different than TT_Unknown sets this type for all 2214 /// double ampersands. This only counts for the current parens scope. 2215 void UnwrappedLineParser::parseParens(TokenType AmpAmpTokenType) { 2216 assert(FormatTok->is(tok::l_paren) && "'(' expected."); 2217 nextToken(); 2218 do { 2219 switch (FormatTok->Tok.getKind()) { 2220 case tok::l_paren: 2221 parseParens(); 2222 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace)) 2223 parseChildBlock(); 2224 break; 2225 case tok::r_paren: 2226 nextToken(); 2227 return; 2228 case tok::r_brace: 2229 // A "}" inside parenthesis is an error if there wasn't a matching "{". 2230 return; 2231 case tok::l_square: 2232 tryToParseLambda(); 2233 break; 2234 case tok::l_brace: 2235 if (!tryToParseBracedList()) 2236 parseChildBlock(); 2237 break; 2238 case tok::at: 2239 nextToken(); 2240 if (FormatTok->is(tok::l_brace)) { 2241 nextToken(); 2242 parseBracedList(); 2243 } 2244 break; 2245 case tok::equal: 2246 if (Style.isCSharp() && FormatTok->is(TT_FatArrow)) 2247 tryToParseChildBlock(); 2248 else 2249 nextToken(); 2250 break; 2251 case tok::kw_class: 2252 if (Style.isJavaScript()) 2253 parseRecord(/*ParseAsExpr=*/true); 2254 else 2255 nextToken(); 2256 break; 2257 case tok::identifier: 2258 if (Style.isJavaScript() && 2259 (FormatTok->is(Keywords.kw_function) || 2260 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function))) 2261 tryToParseJSFunction(); 2262 else 2263 nextToken(); 2264 break; 2265 case tok::kw_requires: { 2266 auto RequiresToken = FormatTok; 2267 nextToken(); 2268 parseRequiresExpression(RequiresToken); 2269 break; 2270 } 2271 case tok::ampamp: 2272 if (AmpAmpTokenType != TT_Unknown) 2273 FormatTok->setFinalizedType(AmpAmpTokenType); 2274 LLVM_FALLTHROUGH; 2275 default: 2276 nextToken(); 2277 break; 2278 } 2279 } while (!eof()); 2280 } 2281 2282 void UnwrappedLineParser::parseSquare(bool LambdaIntroducer) { 2283 if (!LambdaIntroducer) { 2284 assert(FormatTok->is(tok::l_square) && "'[' expected."); 2285 if (tryToParseLambda()) 2286 return; 2287 } 2288 do { 2289 switch (FormatTok->Tok.getKind()) { 2290 case tok::l_paren: 2291 parseParens(); 2292 break; 2293 case tok::r_square: 2294 nextToken(); 2295 return; 2296 case tok::r_brace: 2297 // A "}" inside parenthesis is an error if there wasn't a matching "{". 2298 return; 2299 case tok::l_square: 2300 parseSquare(); 2301 break; 2302 case tok::l_brace: { 2303 if (!tryToParseBracedList()) 2304 parseChildBlock(); 2305 break; 2306 } 2307 case tok::at: 2308 nextToken(); 2309 if (FormatTok->is(tok::l_brace)) { 2310 nextToken(); 2311 parseBracedList(); 2312 } 2313 break; 2314 default: 2315 nextToken(); 2316 break; 2317 } 2318 } while (!eof()); 2319 } 2320 2321 void UnwrappedLineParser::keepAncestorBraces() { 2322 if (!Style.RemoveBracesLLVM) 2323 return; 2324 2325 const int MaxNestingLevels = 2; 2326 const int Size = NestedTooDeep.size(); 2327 if (Size >= MaxNestingLevels) 2328 NestedTooDeep[Size - MaxNestingLevels] = true; 2329 NestedTooDeep.push_back(false); 2330 } 2331 2332 static FormatToken *getLastNonComment(const UnwrappedLine &Line) { 2333 for (const auto &Token : llvm::reverse(Line.Tokens)) 2334 if (Token.Tok->isNot(tok::comment)) 2335 return Token.Tok; 2336 2337 return nullptr; 2338 } 2339 2340 void UnwrappedLineParser::parseUnbracedBody(bool CheckEOF) { 2341 FormatToken *Tok = nullptr; 2342 2343 if (Style.InsertBraces && !Line->InPPDirective && !Line->Tokens.empty() && 2344 PreprocessorDirectives.empty()) { 2345 Tok = getLastNonComment(*Line); 2346 assert(Tok); 2347 if (Tok->BraceCount < 0) { 2348 assert(Tok->BraceCount == -1); 2349 Tok = nullptr; 2350 } else { 2351 Tok->BraceCount = -1; 2352 } 2353 } 2354 2355 addUnwrappedLine(); 2356 ++Line->Level; 2357 parseStructuralElement(); 2358 2359 if (Tok) { 2360 assert(!Line->InPPDirective); 2361 Tok = nullptr; 2362 for (const auto &L : llvm::reverse(*CurrentLines)) { 2363 if (!L.InPPDirective && getLastNonComment(L)) { 2364 Tok = L.Tokens.back().Tok; 2365 break; 2366 } 2367 } 2368 assert(Tok); 2369 ++Tok->BraceCount; 2370 } 2371 2372 if (CheckEOF && FormatTok->is(tok::eof)) 2373 addUnwrappedLine(); 2374 2375 --Line->Level; 2376 } 2377 2378 static void markOptionalBraces(FormatToken *LeftBrace) { 2379 if (!LeftBrace) 2380 return; 2381 2382 assert(LeftBrace->is(tok::l_brace)); 2383 2384 FormatToken *RightBrace = LeftBrace->MatchingParen; 2385 if (!RightBrace) { 2386 assert(!LeftBrace->Optional); 2387 return; 2388 } 2389 2390 assert(RightBrace->is(tok::r_brace)); 2391 assert(RightBrace->MatchingParen == LeftBrace); 2392 assert(LeftBrace->Optional == RightBrace->Optional); 2393 2394 LeftBrace->Optional = true; 2395 RightBrace->Optional = true; 2396 } 2397 2398 void UnwrappedLineParser::handleAttributes() { 2399 // Handle AttributeMacro, e.g. `if (x) UNLIKELY`. 2400 if (FormatTok->is(TT_AttributeMacro)) 2401 nextToken(); 2402 handleCppAttributes(); 2403 } 2404 2405 bool UnwrappedLineParser::handleCppAttributes() { 2406 // Handle [[likely]] / [[unlikely]] attributes. 2407 if (FormatTok->is(tok::l_square) && tryToParseSimpleAttribute()) { 2408 parseSquare(); 2409 return true; 2410 } 2411 return false; 2412 } 2413 2414 FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind, 2415 bool KeepBraces) { 2416 assert(FormatTok->is(tok::kw_if) && "'if' expected"); 2417 nextToken(); 2418 if (FormatTok->is(tok::exclaim)) 2419 nextToken(); 2420 if (FormatTok->is(tok::kw_consteval)) { 2421 nextToken(); 2422 } else { 2423 if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier)) 2424 nextToken(); 2425 if (FormatTok->is(tok::l_paren)) 2426 parseParens(); 2427 } 2428 handleAttributes(); 2429 2430 bool NeedsUnwrappedLine = false; 2431 keepAncestorBraces(); 2432 2433 FormatToken *IfLeftBrace = nullptr; 2434 IfStmtKind IfBlockKind = IfStmtKind::NotIf; 2435 2436 if (FormatTok->is(tok::l_brace)) { 2437 IfLeftBrace = FormatTok; 2438 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2439 IfBlockKind = parseBlock(); 2440 if (Style.BraceWrapping.BeforeElse) 2441 addUnwrappedLine(); 2442 else 2443 NeedsUnwrappedLine = true; 2444 } else { 2445 parseUnbracedBody(); 2446 } 2447 2448 bool KeepIfBraces = false; 2449 if (Style.RemoveBracesLLVM) { 2450 assert(!NestedTooDeep.empty()); 2451 KeepIfBraces = (IfLeftBrace && !IfLeftBrace->MatchingParen) || 2452 NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly || 2453 IfBlockKind == IfStmtKind::IfElseIf; 2454 } 2455 2456 FormatToken *ElseLeftBrace = nullptr; 2457 IfStmtKind Kind = IfStmtKind::IfOnly; 2458 2459 if (FormatTok->is(tok::kw_else)) { 2460 if (Style.RemoveBracesLLVM) { 2461 NestedTooDeep.back() = false; 2462 Kind = IfStmtKind::IfElse; 2463 } 2464 nextToken(); 2465 handleAttributes(); 2466 if (FormatTok->is(tok::l_brace)) { 2467 ElseLeftBrace = FormatTok; 2468 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2469 if (parseBlock() == IfStmtKind::IfOnly) 2470 Kind = IfStmtKind::IfElseIf; 2471 addUnwrappedLine(); 2472 } else if (FormatTok->is(tok::kw_if)) { 2473 FormatToken *Previous = Tokens->getPreviousToken(); 2474 const bool IsPrecededByComment = Previous && Previous->is(tok::comment); 2475 if (IsPrecededByComment) { 2476 addUnwrappedLine(); 2477 ++Line->Level; 2478 } 2479 bool TooDeep = true; 2480 if (Style.RemoveBracesLLVM) { 2481 Kind = IfStmtKind::IfElseIf; 2482 TooDeep = NestedTooDeep.pop_back_val(); 2483 } 2484 ElseLeftBrace = 2485 parseIfThenElse(/*IfKind=*/nullptr, KeepBraces || KeepIfBraces); 2486 if (Style.RemoveBracesLLVM) 2487 NestedTooDeep.push_back(TooDeep); 2488 if (IsPrecededByComment) 2489 --Line->Level; 2490 } else { 2491 parseUnbracedBody(/*CheckEOF=*/true); 2492 } 2493 } else { 2494 if (Style.RemoveBracesLLVM) 2495 KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse; 2496 if (NeedsUnwrappedLine) 2497 addUnwrappedLine(); 2498 } 2499 2500 if (!Style.RemoveBracesLLVM) 2501 return nullptr; 2502 2503 assert(!NestedTooDeep.empty()); 2504 const bool KeepElseBraces = 2505 (ElseLeftBrace && !ElseLeftBrace->MatchingParen) || NestedTooDeep.back(); 2506 2507 NestedTooDeep.pop_back(); 2508 2509 if (!KeepBraces && !KeepIfBraces && !KeepElseBraces) { 2510 markOptionalBraces(IfLeftBrace); 2511 markOptionalBraces(ElseLeftBrace); 2512 } else if (IfLeftBrace) { 2513 FormatToken *IfRightBrace = IfLeftBrace->MatchingParen; 2514 if (IfRightBrace) { 2515 assert(IfRightBrace->MatchingParen == IfLeftBrace); 2516 assert(!IfLeftBrace->Optional); 2517 assert(!IfRightBrace->Optional); 2518 IfLeftBrace->MatchingParen = nullptr; 2519 IfRightBrace->MatchingParen = nullptr; 2520 } 2521 } 2522 2523 if (IfKind) 2524 *IfKind = Kind; 2525 2526 return IfLeftBrace; 2527 } 2528 2529 void UnwrappedLineParser::parseTryCatch() { 2530 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected"); 2531 nextToken(); 2532 bool NeedsUnwrappedLine = false; 2533 if (FormatTok->is(tok::colon)) { 2534 // We are in a function try block, what comes is an initializer list. 2535 nextToken(); 2536 2537 // In case identifiers were removed by clang-tidy, what might follow is 2538 // multiple commas in sequence - before the first identifier. 2539 while (FormatTok->is(tok::comma)) 2540 nextToken(); 2541 2542 while (FormatTok->is(tok::identifier)) { 2543 nextToken(); 2544 if (FormatTok->is(tok::l_paren)) 2545 parseParens(); 2546 if (FormatTok->Previous && FormatTok->Previous->is(tok::identifier) && 2547 FormatTok->is(tok::l_brace)) { 2548 do { 2549 nextToken(); 2550 } while (!FormatTok->is(tok::r_brace)); 2551 nextToken(); 2552 } 2553 2554 // In case identifiers were removed by clang-tidy, what might follow is 2555 // multiple commas in sequence - after the first identifier. 2556 while (FormatTok->is(tok::comma)) 2557 nextToken(); 2558 } 2559 } 2560 // Parse try with resource. 2561 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) 2562 parseParens(); 2563 2564 keepAncestorBraces(); 2565 2566 if (FormatTok->is(tok::l_brace)) { 2567 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2568 parseBlock(); 2569 if (Style.BraceWrapping.BeforeCatch) 2570 addUnwrappedLine(); 2571 else 2572 NeedsUnwrappedLine = true; 2573 } else if (!FormatTok->is(tok::kw_catch)) { 2574 // The C++ standard requires a compound-statement after a try. 2575 // If there's none, we try to assume there's a structuralElement 2576 // and try to continue. 2577 addUnwrappedLine(); 2578 ++Line->Level; 2579 parseStructuralElement(); 2580 --Line->Level; 2581 } 2582 while (true) { 2583 if (FormatTok->is(tok::at)) 2584 nextToken(); 2585 if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except, 2586 tok::kw___finally) || 2587 ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) && 2588 FormatTok->is(Keywords.kw_finally)) || 2589 (FormatTok->isObjCAtKeyword(tok::objc_catch) || 2590 FormatTok->isObjCAtKeyword(tok::objc_finally)))) 2591 break; 2592 nextToken(); 2593 while (FormatTok->isNot(tok::l_brace)) { 2594 if (FormatTok->is(tok::l_paren)) { 2595 parseParens(); 2596 continue; 2597 } 2598 if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof)) { 2599 if (Style.RemoveBracesLLVM) 2600 NestedTooDeep.pop_back(); 2601 return; 2602 } 2603 nextToken(); 2604 } 2605 NeedsUnwrappedLine = false; 2606 Line->MustBeDeclaration = false; 2607 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2608 parseBlock(); 2609 if (Style.BraceWrapping.BeforeCatch) 2610 addUnwrappedLine(); 2611 else 2612 NeedsUnwrappedLine = true; 2613 } 2614 2615 if (Style.RemoveBracesLLVM) 2616 NestedTooDeep.pop_back(); 2617 2618 if (NeedsUnwrappedLine) 2619 addUnwrappedLine(); 2620 } 2621 2622 void UnwrappedLineParser::parseNamespace() { 2623 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) && 2624 "'namespace' expected"); 2625 2626 const FormatToken &InitialToken = *FormatTok; 2627 nextToken(); 2628 if (InitialToken.is(TT_NamespaceMacro)) { 2629 parseParens(); 2630 } else { 2631 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline, 2632 tok::l_square, tok::period, tok::l_paren) || 2633 (Style.isCSharp() && FormatTok->is(tok::kw_union))) 2634 if (FormatTok->is(tok::l_square)) 2635 parseSquare(); 2636 else if (FormatTok->is(tok::l_paren)) 2637 parseParens(); 2638 else 2639 nextToken(); 2640 } 2641 if (FormatTok->is(tok::l_brace)) { 2642 if (ShouldBreakBeforeBrace(Style, InitialToken)) 2643 addUnwrappedLine(); 2644 2645 unsigned AddLevels = 2646 Style.NamespaceIndentation == FormatStyle::NI_All || 2647 (Style.NamespaceIndentation == FormatStyle::NI_Inner && 2648 DeclarationScopeStack.size() > 1) 2649 ? 1u 2650 : 0u; 2651 bool ManageWhitesmithsBraces = 2652 AddLevels == 0u && 2653 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths; 2654 2655 // If we're in Whitesmiths mode, indent the brace if we're not indenting 2656 // the whole block. 2657 if (ManageWhitesmithsBraces) 2658 ++Line->Level; 2659 2660 parseBlock(/*MustBeDeclaration=*/true, AddLevels, 2661 /*MunchSemi=*/true, 2662 /*UnindentWhitesmithsBraces=*/ManageWhitesmithsBraces); 2663 2664 // Munch the semicolon after a namespace. This is more common than one would 2665 // think. Putting the semicolon into its own line is very ugly. 2666 if (FormatTok->is(tok::semi)) 2667 nextToken(); 2668 2669 addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep); 2670 2671 if (ManageWhitesmithsBraces) 2672 --Line->Level; 2673 } 2674 // FIXME: Add error handling. 2675 } 2676 2677 void UnwrappedLineParser::parseNew() { 2678 assert(FormatTok->is(tok::kw_new) && "'new' expected"); 2679 nextToken(); 2680 2681 if (Style.isCSharp()) { 2682 do { 2683 if (FormatTok->is(tok::l_brace)) 2684 parseBracedList(); 2685 2686 if (FormatTok->isOneOf(tok::semi, tok::comma)) 2687 return; 2688 2689 nextToken(); 2690 } while (!eof()); 2691 } 2692 2693 if (Style.Language != FormatStyle::LK_Java) 2694 return; 2695 2696 // In Java, we can parse everything up to the parens, which aren't optional. 2697 do { 2698 // There should not be a ;, { or } before the new's open paren. 2699 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace)) 2700 return; 2701 2702 // Consume the parens. 2703 if (FormatTok->is(tok::l_paren)) { 2704 parseParens(); 2705 2706 // If there is a class body of an anonymous class, consume that as child. 2707 if (FormatTok->is(tok::l_brace)) 2708 parseChildBlock(); 2709 return; 2710 } 2711 nextToken(); 2712 } while (!eof()); 2713 } 2714 2715 void UnwrappedLineParser::parseForOrWhileLoop() { 2716 assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) && 2717 "'for', 'while' or foreach macro expected"); 2718 nextToken(); 2719 // JS' for await ( ... 2720 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await)) 2721 nextToken(); 2722 if (Style.isCpp() && FormatTok->is(tok::kw_co_await)) 2723 nextToken(); 2724 if (FormatTok->is(tok::l_paren)) 2725 parseParens(); 2726 2727 keepAncestorBraces(); 2728 2729 if (FormatTok->is(tok::l_brace)) { 2730 FormatToken *LeftBrace = FormatTok; 2731 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2732 parseBlock(); 2733 if (Style.RemoveBracesLLVM) { 2734 assert(!NestedTooDeep.empty()); 2735 if (!NestedTooDeep.back()) 2736 markOptionalBraces(LeftBrace); 2737 } 2738 addUnwrappedLine(); 2739 } else { 2740 parseUnbracedBody(); 2741 } 2742 2743 if (Style.RemoveBracesLLVM) 2744 NestedTooDeep.pop_back(); 2745 } 2746 2747 void UnwrappedLineParser::parseDoWhile() { 2748 assert(FormatTok->is(tok::kw_do) && "'do' expected"); 2749 nextToken(); 2750 2751 keepAncestorBraces(); 2752 2753 if (FormatTok->is(tok::l_brace)) { 2754 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2755 parseBlock(); 2756 if (Style.BraceWrapping.BeforeWhile) 2757 addUnwrappedLine(); 2758 } else { 2759 parseUnbracedBody(); 2760 } 2761 2762 if (Style.RemoveBracesLLVM) 2763 NestedTooDeep.pop_back(); 2764 2765 // FIXME: Add error handling. 2766 if (!FormatTok->is(tok::kw_while)) { 2767 addUnwrappedLine(); 2768 return; 2769 } 2770 2771 // If in Whitesmiths mode, the line with the while() needs to be indented 2772 // to the same level as the block. 2773 if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) 2774 ++Line->Level; 2775 2776 nextToken(); 2777 parseStructuralElement(); 2778 } 2779 2780 void UnwrappedLineParser::parseLabel(bool LeftAlignLabel) { 2781 nextToken(); 2782 unsigned OldLineLevel = Line->Level; 2783 if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0)) 2784 --Line->Level; 2785 if (LeftAlignLabel) 2786 Line->Level = 0; 2787 2788 if (!Style.IndentCaseBlocks && CommentsBeforeNextToken.empty() && 2789 FormatTok->is(tok::l_brace)) { 2790 2791 CompoundStatementIndenter Indenter(this, Line->Level, 2792 Style.BraceWrapping.AfterCaseLabel, 2793 Style.BraceWrapping.IndentBraces); 2794 parseBlock(); 2795 if (FormatTok->is(tok::kw_break)) { 2796 if (Style.BraceWrapping.AfterControlStatement == 2797 FormatStyle::BWACS_Always) { 2798 addUnwrappedLine(); 2799 if (!Style.IndentCaseBlocks && 2800 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) 2801 ++Line->Level; 2802 } 2803 parseStructuralElement(); 2804 } 2805 addUnwrappedLine(); 2806 } else { 2807 if (FormatTok->is(tok::semi)) 2808 nextToken(); 2809 addUnwrappedLine(); 2810 } 2811 Line->Level = OldLineLevel; 2812 if (FormatTok->isNot(tok::l_brace)) { 2813 parseStructuralElement(); 2814 addUnwrappedLine(); 2815 } 2816 } 2817 2818 void UnwrappedLineParser::parseCaseLabel() { 2819 assert(FormatTok->is(tok::kw_case) && "'case' expected"); 2820 2821 // FIXME: fix handling of complex expressions here. 2822 do { 2823 nextToken(); 2824 } while (!eof() && !FormatTok->is(tok::colon)); 2825 parseLabel(); 2826 } 2827 2828 void UnwrappedLineParser::parseSwitch() { 2829 assert(FormatTok->is(tok::kw_switch) && "'switch' expected"); 2830 nextToken(); 2831 if (FormatTok->is(tok::l_paren)) 2832 parseParens(); 2833 2834 keepAncestorBraces(); 2835 2836 if (FormatTok->is(tok::l_brace)) { 2837 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2838 parseBlock(); 2839 addUnwrappedLine(); 2840 } else { 2841 addUnwrappedLine(); 2842 ++Line->Level; 2843 parseStructuralElement(); 2844 --Line->Level; 2845 } 2846 2847 if (Style.RemoveBracesLLVM) 2848 NestedTooDeep.pop_back(); 2849 } 2850 2851 // Operators that can follow a C variable. 2852 static bool isCOperatorFollowingVar(tok::TokenKind kind) { 2853 switch (kind) { 2854 case tok::ampamp: 2855 case tok::ampequal: 2856 case tok::arrow: 2857 case tok::caret: 2858 case tok::caretequal: 2859 case tok::comma: 2860 case tok::ellipsis: 2861 case tok::equal: 2862 case tok::equalequal: 2863 case tok::exclaim: 2864 case tok::exclaimequal: 2865 case tok::greater: 2866 case tok::greaterequal: 2867 case tok::greatergreater: 2868 case tok::greatergreaterequal: 2869 case tok::l_paren: 2870 case tok::l_square: 2871 case tok::less: 2872 case tok::lessequal: 2873 case tok::lessless: 2874 case tok::lesslessequal: 2875 case tok::minus: 2876 case tok::minusequal: 2877 case tok::minusminus: 2878 case tok::percent: 2879 case tok::percentequal: 2880 case tok::period: 2881 case tok::pipe: 2882 case tok::pipeequal: 2883 case tok::pipepipe: 2884 case tok::plus: 2885 case tok::plusequal: 2886 case tok::plusplus: 2887 case tok::question: 2888 case tok::r_brace: 2889 case tok::r_paren: 2890 case tok::r_square: 2891 case tok::semi: 2892 case tok::slash: 2893 case tok::slashequal: 2894 case tok::star: 2895 case tok::starequal: 2896 return true; 2897 default: 2898 return false; 2899 } 2900 } 2901 2902 void UnwrappedLineParser::parseAccessSpecifier() { 2903 FormatToken *AccessSpecifierCandidate = FormatTok; 2904 nextToken(); 2905 // Understand Qt's slots. 2906 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots)) 2907 nextToken(); 2908 // Otherwise, we don't know what it is, and we'd better keep the next token. 2909 if (FormatTok->is(tok::colon)) { 2910 nextToken(); 2911 addUnwrappedLine(); 2912 } else if (!FormatTok->is(tok::coloncolon) && 2913 !isCOperatorFollowingVar(FormatTok->Tok.getKind())) { 2914 // Not a variable name nor namespace name. 2915 addUnwrappedLine(); 2916 } else if (AccessSpecifierCandidate) { 2917 // Consider the access specifier to be a C identifier. 2918 AccessSpecifierCandidate->Tok.setKind(tok::identifier); 2919 } 2920 } 2921 2922 /// \brief Parses a concept definition. 2923 /// \pre The current token has to be the concept keyword. 2924 /// 2925 /// Returns if either the concept has been completely parsed, or if it detects 2926 /// that the concept definition is incorrect. 2927 void UnwrappedLineParser::parseConcept() { 2928 assert(FormatTok->is(tok::kw_concept) && "'concept' expected"); 2929 nextToken(); 2930 if (!FormatTok->is(tok::identifier)) 2931 return; 2932 nextToken(); 2933 if (!FormatTok->is(tok::equal)) 2934 return; 2935 nextToken(); 2936 parseConstraintExpression(); 2937 if (FormatTok->is(tok::semi)) 2938 nextToken(); 2939 addUnwrappedLine(); 2940 } 2941 2942 /// \brief Parses a requires, decides if it is a clause or an expression. 2943 /// \pre The current token has to be the requires keyword. 2944 /// \returns true if it parsed a clause. 2945 bool clang::format::UnwrappedLineParser::parseRequires() { 2946 assert(FormatTok->is(tok::kw_requires) && "'requires' expected"); 2947 auto RequiresToken = FormatTok; 2948 2949 // We try to guess if it is a requires clause, or a requires expression. For 2950 // that we first consume the keyword and check the next token. 2951 nextToken(); 2952 2953 switch (FormatTok->Tok.getKind()) { 2954 case tok::l_brace: 2955 // This can only be an expression, never a clause. 2956 parseRequiresExpression(RequiresToken); 2957 return false; 2958 case tok::l_paren: 2959 // Clauses and expression can start with a paren, it's unclear what we have. 2960 break; 2961 default: 2962 // All other tokens can only be a clause. 2963 parseRequiresClause(RequiresToken); 2964 return true; 2965 } 2966 2967 // Looking forward we would have to decide if there are function declaration 2968 // like arguments to the requires expression: 2969 // requires (T t) { 2970 // Or there is a constraint expression for the requires clause: 2971 // requires (C<T> && ... 2972 2973 // But first let's look behind. 2974 auto *PreviousNonComment = RequiresToken->getPreviousNonComment(); 2975 2976 if (!PreviousNonComment || 2977 PreviousNonComment->is(TT_RequiresExpressionLBrace)) { 2978 // If there is no token, or an expression left brace, we are a requires 2979 // clause within a requires expression. 2980 parseRequiresClause(RequiresToken); 2981 return true; 2982 } 2983 2984 switch (PreviousNonComment->Tok.getKind()) { 2985 case tok::greater: 2986 case tok::r_paren: 2987 case tok::kw_noexcept: 2988 case tok::kw_const: 2989 // This is a requires clause. 2990 parseRequiresClause(RequiresToken); 2991 return true; 2992 case tok::amp: 2993 case tok::ampamp: { 2994 // This can be either: 2995 // if (... && requires (T t) ...) 2996 // Or 2997 // void member(...) && requires (C<T> ... 2998 // We check the one token before that for a const: 2999 // void member(...) const && requires (C<T> ... 3000 auto PrevPrev = PreviousNonComment->getPreviousNonComment(); 3001 if (PrevPrev && PrevPrev->is(tok::kw_const)) { 3002 parseRequiresClause(RequiresToken); 3003 return true; 3004 } 3005 break; 3006 } 3007 default: 3008 // It's an expression. 3009 parseRequiresExpression(RequiresToken); 3010 return false; 3011 } 3012 3013 // Now we look forward and try to check if the paren content is a parameter 3014 // list. The parameters can be cv-qualified and contain references or 3015 // pointers. 3016 // So we want basically to check for TYPE NAME, but TYPE can contain all kinds 3017 // of stuff: typename, const, *, &, &&, ::, identifiers. 3018 3019 int NextTokenOffset = 1; 3020 auto NextToken = Tokens->peekNextToken(NextTokenOffset); 3021 auto PeekNext = [&NextTokenOffset, &NextToken, this] { 3022 ++NextTokenOffset; 3023 NextToken = Tokens->peekNextToken(NextTokenOffset); 3024 }; 3025 3026 bool FoundType = false; 3027 bool LastWasColonColon = false; 3028 int OpenAngles = 0; 3029 3030 for (; NextTokenOffset < 50; PeekNext()) { 3031 switch (NextToken->Tok.getKind()) { 3032 case tok::kw_volatile: 3033 case tok::kw_const: 3034 case tok::comma: 3035 parseRequiresExpression(RequiresToken); 3036 return false; 3037 case tok::r_paren: 3038 case tok::pipepipe: 3039 parseRequiresClause(RequiresToken); 3040 return true; 3041 case tok::eof: 3042 // Break out of the loop. 3043 NextTokenOffset = 50; 3044 break; 3045 case tok::coloncolon: 3046 LastWasColonColon = true; 3047 break; 3048 case tok::identifier: 3049 if (FoundType && !LastWasColonColon && OpenAngles == 0) { 3050 parseRequiresExpression(RequiresToken); 3051 return false; 3052 } 3053 FoundType = true; 3054 LastWasColonColon = false; 3055 break; 3056 case tok::less: 3057 ++OpenAngles; 3058 break; 3059 case tok::greater: 3060 --OpenAngles; 3061 break; 3062 default: 3063 if (NextToken->isSimpleTypeSpecifier()) { 3064 parseRequiresExpression(RequiresToken); 3065 return false; 3066 } 3067 break; 3068 } 3069 } 3070 3071 // This seems to be a complicated expression, just assume it's a clause. 3072 parseRequiresClause(RequiresToken); 3073 return true; 3074 } 3075 3076 /// \brief Parses a requires clause. 3077 /// \param RequiresToken The requires keyword token, which starts this clause. 3078 /// \pre We need to be on the next token after the requires keyword. 3079 /// \sa parseRequiresExpression 3080 /// 3081 /// Returns if it either has finished parsing the clause, or it detects, that 3082 /// the clause is incorrect. 3083 void UnwrappedLineParser::parseRequiresClause(FormatToken *RequiresToken) { 3084 assert(FormatTok->getPreviousNonComment() == RequiresToken); 3085 assert(RequiresToken->is(tok::kw_requires) && "'requires' expected"); 3086 3087 // If there is no previous token, we are within a requires expression, 3088 // otherwise we will always have the template or function declaration in front 3089 // of it. 3090 bool InRequiresExpression = 3091 !RequiresToken->Previous || 3092 RequiresToken->Previous->is(TT_RequiresExpressionLBrace); 3093 3094 RequiresToken->setFinalizedType(InRequiresExpression 3095 ? TT_RequiresClauseInARequiresExpression 3096 : TT_RequiresClause); 3097 3098 parseConstraintExpression(); 3099 3100 if (!InRequiresExpression) 3101 FormatTok->Previous->ClosesRequiresClause = true; 3102 } 3103 3104 /// \brief Parses a requires expression. 3105 /// \param RequiresToken The requires keyword token, which starts this clause. 3106 /// \pre We need to be on the next token after the requires keyword. 3107 /// \sa parseRequiresClause 3108 /// 3109 /// Returns if it either has finished parsing the expression, or it detects, 3110 /// that the expression is incorrect. 3111 void UnwrappedLineParser::parseRequiresExpression(FormatToken *RequiresToken) { 3112 assert(FormatTok->getPreviousNonComment() == RequiresToken); 3113 assert(RequiresToken->is(tok::kw_requires) && "'requires' expected"); 3114 3115 RequiresToken->setFinalizedType(TT_RequiresExpression); 3116 3117 if (FormatTok->is(tok::l_paren)) { 3118 FormatTok->setFinalizedType(TT_RequiresExpressionLParen); 3119 parseParens(); 3120 } 3121 3122 if (FormatTok->is(tok::l_brace)) { 3123 FormatTok->setFinalizedType(TT_RequiresExpressionLBrace); 3124 parseChildBlock(/*CanContainBracedList=*/false, 3125 /*NextLBracesType=*/TT_CompoundRequirementLBrace); 3126 } 3127 } 3128 3129 /// \brief Parses a constraint expression. 3130 /// 3131 /// This is either the definition of a concept, or the body of a requires 3132 /// clause. It returns, when the parsing is complete, or the expression is 3133 /// incorrect. 3134 void UnwrappedLineParser::parseConstraintExpression() { 3135 // The special handling for lambdas is needed since tryToParseLambda() eats a 3136 // token and if a requires expression is the last part of a requires clause 3137 // and followed by an attribute like [[nodiscard]] the ClosesRequiresClause is 3138 // not set on the correct token. Thus we need to be aware if we even expect a 3139 // lambda to be possible. 3140 // template <typename T> requires requires { ... } [[nodiscard]] ...; 3141 bool LambdaNextTimeAllowed = true; 3142 do { 3143 bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed, false); 3144 3145 switch (FormatTok->Tok.getKind()) { 3146 case tok::kw_requires: { 3147 auto RequiresToken = FormatTok; 3148 nextToken(); 3149 parseRequiresExpression(RequiresToken); 3150 break; 3151 } 3152 3153 case tok::l_paren: 3154 parseParens(/*AmpAmpTokenType=*/TT_BinaryOperator); 3155 break; 3156 3157 case tok::l_square: 3158 if (!LambdaThisTimeAllowed || !tryToParseLambda()) 3159 return; 3160 break; 3161 3162 case tok::kw_const: 3163 case tok::semi: 3164 case tok::kw_class: 3165 case tok::kw_struct: 3166 case tok::kw_union: 3167 return; 3168 3169 case tok::l_brace: 3170 // Potential function body. 3171 return; 3172 3173 case tok::ampamp: 3174 case tok::pipepipe: 3175 FormatTok->setFinalizedType(TT_BinaryOperator); 3176 nextToken(); 3177 LambdaNextTimeAllowed = true; 3178 break; 3179 3180 case tok::comma: 3181 case tok::comment: 3182 LambdaNextTimeAllowed = LambdaThisTimeAllowed; 3183 nextToken(); 3184 break; 3185 3186 case tok::kw_sizeof: 3187 case tok::greater: 3188 case tok::greaterequal: 3189 case tok::greatergreater: 3190 case tok::less: 3191 case tok::lessequal: 3192 case tok::lessless: 3193 case tok::equalequal: 3194 case tok::exclaim: 3195 case tok::exclaimequal: 3196 case tok::plus: 3197 case tok::minus: 3198 case tok::star: 3199 case tok::slash: 3200 case tok::kw_decltype: 3201 LambdaNextTimeAllowed = true; 3202 // Just eat them. 3203 nextToken(); 3204 break; 3205 3206 case tok::numeric_constant: 3207 case tok::coloncolon: 3208 case tok::kw_true: 3209 case tok::kw_false: 3210 // Just eat them. 3211 nextToken(); 3212 break; 3213 3214 case tok::kw_static_cast: 3215 case tok::kw_const_cast: 3216 case tok::kw_reinterpret_cast: 3217 case tok::kw_dynamic_cast: 3218 nextToken(); 3219 if (!FormatTok->is(tok::less)) 3220 return; 3221 3222 parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false, 3223 /*ClosingBraceKind=*/tok::greater); 3224 break; 3225 3226 case tok::kw_bool: 3227 // bool is only allowed if it is directly followed by a paren for a cast: 3228 // concept C = bool(...); 3229 // and bool is the only type, all other types as cast must be inside a 3230 // cast to bool an thus are handled by the other cases. 3231 nextToken(); 3232 if (FormatTok->isNot(tok::l_paren)) 3233 return; 3234 parseParens(); 3235 break; 3236 3237 default: 3238 if (!FormatTok->Tok.getIdentifierInfo()) { 3239 // Identifiers are part of the default case, we check for more then 3240 // tok::identifier to handle builtin type traits. 3241 return; 3242 } 3243 3244 // We need to differentiate identifiers for a template deduction guide, 3245 // variables, or function return types (the constraint expression has 3246 // ended before that), and basically all other cases. But it's easier to 3247 // check the other way around. 3248 assert(FormatTok->Previous); 3249 switch (FormatTok->Previous->Tok.getKind()) { 3250 case tok::coloncolon: // Nested identifier. 3251 case tok::ampamp: // Start of a function or variable for the 3252 case tok::pipepipe: // constraint expression. 3253 case tok::kw_requires: // Initial identifier of a requires clause. 3254 case tok::equal: // Initial identifier of a concept declaration. 3255 break; 3256 default: 3257 return; 3258 } 3259 3260 // Read identifier with optional template declaration. 3261 nextToken(); 3262 if (FormatTok->is(tok::less)) 3263 parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false, 3264 /*ClosingBraceKind=*/tok::greater); 3265 break; 3266 } 3267 } while (!eof()); 3268 } 3269 3270 bool UnwrappedLineParser::parseEnum() { 3271 const FormatToken &InitialToken = *FormatTok; 3272 3273 // Won't be 'enum' for NS_ENUMs. 3274 if (FormatTok->is(tok::kw_enum)) 3275 nextToken(); 3276 3277 // In TypeScript, "enum" can also be used as property name, e.g. in interface 3278 // declarations. An "enum" keyword followed by a colon would be a syntax 3279 // error and thus assume it is just an identifier. 3280 if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question)) 3281 return false; 3282 3283 // In protobuf, "enum" can be used as a field name. 3284 if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal)) 3285 return false; 3286 3287 // Eat up enum class ... 3288 if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct)) 3289 nextToken(); 3290 3291 while (FormatTok->Tok.getIdentifierInfo() || 3292 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less, 3293 tok::greater, tok::comma, tok::question)) { 3294 nextToken(); 3295 // We can have macros or attributes in between 'enum' and the enum name. 3296 if (FormatTok->is(tok::l_paren)) 3297 parseParens(); 3298 if (FormatTok->is(tok::identifier)) { 3299 nextToken(); 3300 // If there are two identifiers in a row, this is likely an elaborate 3301 // return type. In Java, this can be "implements", etc. 3302 if (Style.isCpp() && FormatTok->is(tok::identifier)) 3303 return false; 3304 } 3305 } 3306 3307 // Just a declaration or something is wrong. 3308 if (FormatTok->isNot(tok::l_brace)) 3309 return true; 3310 FormatTok->setFinalizedType(TT_EnumLBrace); 3311 FormatTok->setBlockKind(BK_Block); 3312 3313 if (Style.Language == FormatStyle::LK_Java) { 3314 // Java enums are different. 3315 parseJavaEnumBody(); 3316 return true; 3317 } 3318 if (Style.Language == FormatStyle::LK_Proto) { 3319 parseBlock(/*MustBeDeclaration=*/true); 3320 return true; 3321 } 3322 3323 if (!Style.AllowShortEnumsOnASingleLine && 3324 ShouldBreakBeforeBrace(Style, InitialToken)) 3325 addUnwrappedLine(); 3326 // Parse enum body. 3327 nextToken(); 3328 if (!Style.AllowShortEnumsOnASingleLine) { 3329 addUnwrappedLine(); 3330 Line->Level += 1; 3331 } 3332 bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true, 3333 /*IsEnum=*/true); 3334 if (!Style.AllowShortEnumsOnASingleLine) 3335 Line->Level -= 1; 3336 if (HasError) { 3337 if (FormatTok->is(tok::semi)) 3338 nextToken(); 3339 addUnwrappedLine(); 3340 } 3341 return true; 3342 3343 // There is no addUnwrappedLine() here so that we fall through to parsing a 3344 // structural element afterwards. Thus, in "enum A {} n, m;", 3345 // "} n, m;" will end up in one unwrapped line. 3346 } 3347 3348 bool UnwrappedLineParser::parseStructLike() { 3349 // parseRecord falls through and does not yet add an unwrapped line as a 3350 // record declaration or definition can start a structural element. 3351 parseRecord(); 3352 // This does not apply to Java, JavaScript and C#. 3353 if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() || 3354 Style.isCSharp()) { 3355 if (FormatTok->is(tok::semi)) 3356 nextToken(); 3357 addUnwrappedLine(); 3358 return true; 3359 } 3360 return false; 3361 } 3362 3363 namespace { 3364 // A class used to set and restore the Token position when peeking 3365 // ahead in the token source. 3366 class ScopedTokenPosition { 3367 unsigned StoredPosition; 3368 FormatTokenSource *Tokens; 3369 3370 public: 3371 ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) { 3372 assert(Tokens && "Tokens expected to not be null"); 3373 StoredPosition = Tokens->getPosition(); 3374 } 3375 3376 ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); } 3377 }; 3378 } // namespace 3379 3380 // Look to see if we have [[ by looking ahead, if 3381 // its not then rewind to the original position. 3382 bool UnwrappedLineParser::tryToParseSimpleAttribute() { 3383 ScopedTokenPosition AutoPosition(Tokens); 3384 FormatToken *Tok = Tokens->getNextToken(); 3385 // We already read the first [ check for the second. 3386 if (!Tok->is(tok::l_square)) 3387 return false; 3388 // Double check that the attribute is just something 3389 // fairly simple. 3390 while (Tok->isNot(tok::eof)) { 3391 if (Tok->is(tok::r_square)) 3392 break; 3393 Tok = Tokens->getNextToken(); 3394 } 3395 if (Tok->is(tok::eof)) 3396 return false; 3397 Tok = Tokens->getNextToken(); 3398 if (!Tok->is(tok::r_square)) 3399 return false; 3400 Tok = Tokens->getNextToken(); 3401 if (Tok->is(tok::semi)) 3402 return false; 3403 return true; 3404 } 3405 3406 void UnwrappedLineParser::parseJavaEnumBody() { 3407 // Determine whether the enum is simple, i.e. does not have a semicolon or 3408 // constants with class bodies. Simple enums can be formatted like braced 3409 // lists, contracted to a single line, etc. 3410 unsigned StoredPosition = Tokens->getPosition(); 3411 bool IsSimple = true; 3412 FormatToken *Tok = Tokens->getNextToken(); 3413 while (!Tok->is(tok::eof)) { 3414 if (Tok->is(tok::r_brace)) 3415 break; 3416 if (Tok->isOneOf(tok::l_brace, tok::semi)) { 3417 IsSimple = false; 3418 break; 3419 } 3420 // FIXME: This will also mark enums with braces in the arguments to enum 3421 // constants as "not simple". This is probably fine in practice, though. 3422 Tok = Tokens->getNextToken(); 3423 } 3424 FormatTok = Tokens->setPosition(StoredPosition); 3425 3426 if (IsSimple) { 3427 nextToken(); 3428 parseBracedList(); 3429 addUnwrappedLine(); 3430 return; 3431 } 3432 3433 // Parse the body of a more complex enum. 3434 // First add a line for everything up to the "{". 3435 nextToken(); 3436 addUnwrappedLine(); 3437 ++Line->Level; 3438 3439 // Parse the enum constants. 3440 while (FormatTok) { 3441 if (FormatTok->is(tok::l_brace)) { 3442 // Parse the constant's class body. 3443 parseBlock(/*MustBeDeclaration=*/true, /*AddLevels=*/1u, 3444 /*MunchSemi=*/false); 3445 } else if (FormatTok->is(tok::l_paren)) { 3446 parseParens(); 3447 } else if (FormatTok->is(tok::comma)) { 3448 nextToken(); 3449 addUnwrappedLine(); 3450 } else if (FormatTok->is(tok::semi)) { 3451 nextToken(); 3452 addUnwrappedLine(); 3453 break; 3454 } else if (FormatTok->is(tok::r_brace)) { 3455 addUnwrappedLine(); 3456 break; 3457 } else { 3458 nextToken(); 3459 } 3460 } 3461 3462 // Parse the class body after the enum's ";" if any. 3463 parseLevel(/*HasOpeningBrace=*/true, /*CanContainBracedList=*/true); 3464 nextToken(); 3465 --Line->Level; 3466 addUnwrappedLine(); 3467 } 3468 3469 void UnwrappedLineParser::parseRecord(bool ParseAsExpr) { 3470 const FormatToken &InitialToken = *FormatTok; 3471 nextToken(); 3472 3473 // The actual identifier can be a nested name specifier, and in macros 3474 // it is often token-pasted. 3475 // An [[attribute]] can be before the identifier. 3476 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash, 3477 tok::kw___attribute, tok::kw___declspec, 3478 tok::kw_alignas, tok::l_square, tok::r_square) || 3479 ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) && 3480 FormatTok->isOneOf(tok::period, tok::comma))) { 3481 if (Style.isJavaScript() && 3482 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) { 3483 // JavaScript/TypeScript supports inline object types in 3484 // extends/implements positions: 3485 // class Foo implements {bar: number} { } 3486 nextToken(); 3487 if (FormatTok->is(tok::l_brace)) { 3488 tryToParseBracedList(); 3489 continue; 3490 } 3491 } 3492 bool IsNonMacroIdentifier = 3493 FormatTok->is(tok::identifier) && 3494 FormatTok->TokenText != FormatTok->TokenText.upper(); 3495 nextToken(); 3496 // We can have macros or attributes in between 'class' and the class name. 3497 if (!IsNonMacroIdentifier) { 3498 if (FormatTok->is(tok::l_paren)) { 3499 parseParens(); 3500 } else if (FormatTok->is(TT_AttributeSquare)) { 3501 parseSquare(); 3502 // Consume the closing TT_AttributeSquare. 3503 if (FormatTok->Next && FormatTok->is(TT_AttributeSquare)) 3504 nextToken(); 3505 } 3506 } 3507 } 3508 3509 // Note that parsing away template declarations here leads to incorrectly 3510 // accepting function declarations as record declarations. 3511 // In general, we cannot solve this problem. Consider: 3512 // class A<int> B() {} 3513 // which can be a function definition or a class definition when B() is a 3514 // macro. If we find enough real-world cases where this is a problem, we 3515 // can parse for the 'template' keyword in the beginning of the statement, 3516 // and thus rule out the record production in case there is no template 3517 // (this would still leave us with an ambiguity between template function 3518 // and class declarations). 3519 if (FormatTok->isOneOf(tok::colon, tok::less)) { 3520 do { 3521 if (FormatTok->is(tok::l_brace)) { 3522 calculateBraceTypes(/*ExpectClassBody=*/true); 3523 if (!tryToParseBracedList()) 3524 break; 3525 } 3526 if (FormatTok->is(tok::l_square)) { 3527 FormatToken *Previous = FormatTok->Previous; 3528 if (!Previous || 3529 !(Previous->is(tok::r_paren) || Previous->isTypeOrIdentifier())) { 3530 // Don't try parsing a lambda if we had a closing parenthesis before, 3531 // it was probably a pointer to an array: int (*)[]. 3532 if (!tryToParseLambda()) 3533 break; 3534 } else { 3535 parseSquare(); 3536 continue; 3537 } 3538 } 3539 if (FormatTok->is(tok::semi)) 3540 return; 3541 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) { 3542 addUnwrappedLine(); 3543 nextToken(); 3544 parseCSharpGenericTypeConstraint(); 3545 break; 3546 } 3547 nextToken(); 3548 } while (!eof()); 3549 } 3550 3551 auto GetBraceType = [](const FormatToken &RecordTok) { 3552 switch (RecordTok.Tok.getKind()) { 3553 case tok::kw_class: 3554 return TT_ClassLBrace; 3555 case tok::kw_struct: 3556 return TT_StructLBrace; 3557 case tok::kw_union: 3558 return TT_UnionLBrace; 3559 default: 3560 // Useful for e.g. interface. 3561 return TT_RecordLBrace; 3562 } 3563 }; 3564 if (FormatTok->is(tok::l_brace)) { 3565 FormatTok->setFinalizedType(GetBraceType(InitialToken)); 3566 if (ParseAsExpr) { 3567 parseChildBlock(); 3568 } else { 3569 if (ShouldBreakBeforeBrace(Style, InitialToken)) 3570 addUnwrappedLine(); 3571 3572 unsigned AddLevels = Style.IndentAccessModifiers ? 2u : 1u; 3573 parseBlock(/*MustBeDeclaration=*/true, AddLevels, /*MunchSemi=*/false); 3574 } 3575 } 3576 // There is no addUnwrappedLine() here so that we fall through to parsing a 3577 // structural element afterwards. Thus, in "class A {} n, m;", 3578 // "} n, m;" will end up in one unwrapped line. 3579 } 3580 3581 void UnwrappedLineParser::parseObjCMethod() { 3582 assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) && 3583 "'(' or identifier expected."); 3584 do { 3585 if (FormatTok->is(tok::semi)) { 3586 nextToken(); 3587 addUnwrappedLine(); 3588 return; 3589 } else if (FormatTok->is(tok::l_brace)) { 3590 if (Style.BraceWrapping.AfterFunction) 3591 addUnwrappedLine(); 3592 parseBlock(); 3593 addUnwrappedLine(); 3594 return; 3595 } else { 3596 nextToken(); 3597 } 3598 } while (!eof()); 3599 } 3600 3601 void UnwrappedLineParser::parseObjCProtocolList() { 3602 assert(FormatTok->is(tok::less) && "'<' expected."); 3603 do { 3604 nextToken(); 3605 // Early exit in case someone forgot a close angle. 3606 if (FormatTok->isOneOf(tok::semi, tok::l_brace) || 3607 FormatTok->isObjCAtKeyword(tok::objc_end)) 3608 return; 3609 } while (!eof() && FormatTok->isNot(tok::greater)); 3610 nextToken(); // Skip '>'. 3611 } 3612 3613 void UnwrappedLineParser::parseObjCUntilAtEnd() { 3614 do { 3615 if (FormatTok->isObjCAtKeyword(tok::objc_end)) { 3616 nextToken(); 3617 addUnwrappedLine(); 3618 break; 3619 } 3620 if (FormatTok->is(tok::l_brace)) { 3621 parseBlock(); 3622 // In ObjC interfaces, nothing should be following the "}". 3623 addUnwrappedLine(); 3624 } else if (FormatTok->is(tok::r_brace)) { 3625 // Ignore stray "}". parseStructuralElement doesn't consume them. 3626 nextToken(); 3627 addUnwrappedLine(); 3628 } else if (FormatTok->isOneOf(tok::minus, tok::plus)) { 3629 nextToken(); 3630 parseObjCMethod(); 3631 } else { 3632 parseStructuralElement(); 3633 } 3634 } while (!eof()); 3635 } 3636 3637 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() { 3638 assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_interface || 3639 FormatTok->Tok.getObjCKeywordID() == tok::objc_implementation); 3640 nextToken(); 3641 nextToken(); // interface name 3642 3643 // @interface can be followed by a lightweight generic 3644 // specialization list, then either a base class or a category. 3645 if (FormatTok->is(tok::less)) 3646 parseObjCLightweightGenerics(); 3647 if (FormatTok->is(tok::colon)) { 3648 nextToken(); 3649 nextToken(); // base class name 3650 // The base class can also have lightweight generics applied to it. 3651 if (FormatTok->is(tok::less)) 3652 parseObjCLightweightGenerics(); 3653 } else if (FormatTok->is(tok::l_paren)) 3654 // Skip category, if present. 3655 parseParens(); 3656 3657 if (FormatTok->is(tok::less)) 3658 parseObjCProtocolList(); 3659 3660 if (FormatTok->is(tok::l_brace)) { 3661 if (Style.BraceWrapping.AfterObjCDeclaration) 3662 addUnwrappedLine(); 3663 parseBlock(/*MustBeDeclaration=*/true); 3664 } 3665 3666 // With instance variables, this puts '}' on its own line. Without instance 3667 // variables, this ends the @interface line. 3668 addUnwrappedLine(); 3669 3670 parseObjCUntilAtEnd(); 3671 } 3672 3673 void UnwrappedLineParser::parseObjCLightweightGenerics() { 3674 assert(FormatTok->is(tok::less)); 3675 // Unlike protocol lists, generic parameterizations support 3676 // nested angles: 3677 // 3678 // @interface Foo<ValueType : id <NSCopying, NSSecureCoding>> : 3679 // NSObject <NSCopying, NSSecureCoding> 3680 // 3681 // so we need to count how many open angles we have left. 3682 unsigned NumOpenAngles = 1; 3683 do { 3684 nextToken(); 3685 // Early exit in case someone forgot a close angle. 3686 if (FormatTok->isOneOf(tok::semi, tok::l_brace) || 3687 FormatTok->isObjCAtKeyword(tok::objc_end)) 3688 break; 3689 if (FormatTok->is(tok::less)) 3690 ++NumOpenAngles; 3691 else if (FormatTok->is(tok::greater)) { 3692 assert(NumOpenAngles > 0 && "'>' makes NumOpenAngles negative"); 3693 --NumOpenAngles; 3694 } 3695 } while (!eof() && NumOpenAngles != 0); 3696 nextToken(); // Skip '>'. 3697 } 3698 3699 // Returns true for the declaration/definition form of @protocol, 3700 // false for the expression form. 3701 bool UnwrappedLineParser::parseObjCProtocol() { 3702 assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_protocol); 3703 nextToken(); 3704 3705 if (FormatTok->is(tok::l_paren)) 3706 // The expression form of @protocol, e.g. "Protocol* p = @protocol(foo);". 3707 return false; 3708 3709 // The definition/declaration form, 3710 // @protocol Foo 3711 // - (int)someMethod; 3712 // @end 3713 3714 nextToken(); // protocol name 3715 3716 if (FormatTok->is(tok::less)) 3717 parseObjCProtocolList(); 3718 3719 // Check for protocol declaration. 3720 if (FormatTok->is(tok::semi)) { 3721 nextToken(); 3722 addUnwrappedLine(); 3723 return true; 3724 } 3725 3726 addUnwrappedLine(); 3727 parseObjCUntilAtEnd(); 3728 return true; 3729 } 3730 3731 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() { 3732 bool IsImport = FormatTok->is(Keywords.kw_import); 3733 assert(IsImport || FormatTok->is(tok::kw_export)); 3734 nextToken(); 3735 3736 // Consume the "default" in "export default class/function". 3737 if (FormatTok->is(tok::kw_default)) 3738 nextToken(); 3739 3740 // Consume "async function", "function" and "default function", so that these 3741 // get parsed as free-standing JS functions, i.e. do not require a trailing 3742 // semicolon. 3743 if (FormatTok->is(Keywords.kw_async)) 3744 nextToken(); 3745 if (FormatTok->is(Keywords.kw_function)) { 3746 nextToken(); 3747 return; 3748 } 3749 3750 // For imports, `export *`, `export {...}`, consume the rest of the line up 3751 // to the terminating `;`. For everything else, just return and continue 3752 // parsing the structural element, i.e. the declaration or expression for 3753 // `export default`. 3754 if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) && 3755 !FormatTok->isStringLiteral()) 3756 return; 3757 3758 while (!eof()) { 3759 if (FormatTok->is(tok::semi)) 3760 return; 3761 if (Line->Tokens.empty()) { 3762 // Common issue: Automatic Semicolon Insertion wrapped the line, so the 3763 // import statement should terminate. 3764 return; 3765 } 3766 if (FormatTok->is(tok::l_brace)) { 3767 FormatTok->setBlockKind(BK_Block); 3768 nextToken(); 3769 parseBracedList(); 3770 } else { 3771 nextToken(); 3772 } 3773 } 3774 } 3775 3776 void UnwrappedLineParser::parseStatementMacro() { 3777 nextToken(); 3778 if (FormatTok->is(tok::l_paren)) 3779 parseParens(); 3780 if (FormatTok->is(tok::semi)) 3781 nextToken(); 3782 addUnwrappedLine(); 3783 } 3784 3785 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line, 3786 StringRef Prefix = "") { 3787 llvm::dbgs() << Prefix << "Line(" << Line.Level 3788 << ", FSC=" << Line.FirstStartColumn << ")" 3789 << (Line.InPPDirective ? " MACRO" : "") << ": "; 3790 for (const auto &Node : Line.Tokens) { 3791 llvm::dbgs() << Node.Tok->Tok.getName() << "[" 3792 << "T=" << static_cast<unsigned>(Node.Tok->getType()) 3793 << ", OC=" << Node.Tok->OriginalColumn << "] "; 3794 } 3795 for (const auto &Node : Line.Tokens) 3796 for (const auto &ChildNode : Node.Children) 3797 printDebugInfo(ChildNode, "\nChild: "); 3798 3799 llvm::dbgs() << "\n"; 3800 } 3801 3802 void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) { 3803 if (Line->Tokens.empty()) 3804 return; 3805 LLVM_DEBUG({ 3806 if (CurrentLines == &Lines) 3807 printDebugInfo(*Line); 3808 }); 3809 3810 // If this line closes a block when in Whitesmiths mode, remember that 3811 // information so that the level can be decreased after the line is added. 3812 // This has to happen after the addition of the line since the line itself 3813 // needs to be indented. 3814 bool ClosesWhitesmithsBlock = 3815 Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex && 3816 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths; 3817 3818 CurrentLines->push_back(std::move(*Line)); 3819 Line->Tokens.clear(); 3820 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex; 3821 Line->FirstStartColumn = 0; 3822 3823 if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove) 3824 --Line->Level; 3825 if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) { 3826 CurrentLines->append( 3827 std::make_move_iterator(PreprocessorDirectives.begin()), 3828 std::make_move_iterator(PreprocessorDirectives.end())); 3829 PreprocessorDirectives.clear(); 3830 } 3831 // Disconnect the current token from the last token on the previous line. 3832 FormatTok->Previous = nullptr; 3833 } 3834 3835 bool UnwrappedLineParser::eof() const { return FormatTok->is(tok::eof); } 3836 3837 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) { 3838 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) && 3839 FormatTok.NewlinesBefore > 0; 3840 } 3841 3842 // Checks if \p FormatTok is a line comment that continues the line comment 3843 // section on \p Line. 3844 static bool 3845 continuesLineCommentSection(const FormatToken &FormatTok, 3846 const UnwrappedLine &Line, 3847 const llvm::Regex &CommentPragmasRegex) { 3848 if (Line.Tokens.empty()) 3849 return false; 3850 3851 StringRef IndentContent = FormatTok.TokenText; 3852 if (FormatTok.TokenText.startswith("//") || 3853 FormatTok.TokenText.startswith("/*")) 3854 IndentContent = FormatTok.TokenText.substr(2); 3855 if (CommentPragmasRegex.match(IndentContent)) 3856 return false; 3857 3858 // If Line starts with a line comment, then FormatTok continues the comment 3859 // section if its original column is greater or equal to the original start 3860 // column of the line. 3861 // 3862 // Define the min column token of a line as follows: if a line ends in '{' or 3863 // contains a '{' followed by a line comment, then the min column token is 3864 // that '{'. Otherwise, the min column token of the line is the first token of 3865 // the line. 3866 // 3867 // If Line starts with a token other than a line comment, then FormatTok 3868 // continues the comment section if its original column is greater than the 3869 // original start column of the min column token of the line. 3870 // 3871 // For example, the second line comment continues the first in these cases: 3872 // 3873 // // first line 3874 // // second line 3875 // 3876 // and: 3877 // 3878 // // first line 3879 // // second line 3880 // 3881 // and: 3882 // 3883 // int i; // first line 3884 // // second line 3885 // 3886 // and: 3887 // 3888 // do { // first line 3889 // // second line 3890 // int i; 3891 // } while (true); 3892 // 3893 // and: 3894 // 3895 // enum { 3896 // a, // first line 3897 // // second line 3898 // b 3899 // }; 3900 // 3901 // The second line comment doesn't continue the first in these cases: 3902 // 3903 // // first line 3904 // // second line 3905 // 3906 // and: 3907 // 3908 // int i; // first line 3909 // // second line 3910 // 3911 // and: 3912 // 3913 // do { // first line 3914 // // second line 3915 // int i; 3916 // } while (true); 3917 // 3918 // and: 3919 // 3920 // enum { 3921 // a, // first line 3922 // // second line 3923 // }; 3924 const FormatToken *MinColumnToken = Line.Tokens.front().Tok; 3925 3926 // Scan for '{//'. If found, use the column of '{' as a min column for line 3927 // comment section continuation. 3928 const FormatToken *PreviousToken = nullptr; 3929 for (const UnwrappedLineNode &Node : Line.Tokens) { 3930 if (PreviousToken && PreviousToken->is(tok::l_brace) && 3931 isLineComment(*Node.Tok)) { 3932 MinColumnToken = PreviousToken; 3933 break; 3934 } 3935 PreviousToken = Node.Tok; 3936 3937 // Grab the last newline preceding a token in this unwrapped line. 3938 if (Node.Tok->NewlinesBefore > 0) 3939 MinColumnToken = Node.Tok; 3940 } 3941 if (PreviousToken && PreviousToken->is(tok::l_brace)) 3942 MinColumnToken = PreviousToken; 3943 3944 return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok, 3945 MinColumnToken); 3946 } 3947 3948 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) { 3949 bool JustComments = Line->Tokens.empty(); 3950 for (FormatToken *Tok : CommentsBeforeNextToken) { 3951 // Line comments that belong to the same line comment section are put on the 3952 // same line since later we might want to reflow content between them. 3953 // Additional fine-grained breaking of line comment sections is controlled 3954 // by the class BreakableLineCommentSection in case it is desirable to keep 3955 // several line comment sections in the same unwrapped line. 3956 // 3957 // FIXME: Consider putting separate line comment sections as children to the 3958 // unwrapped line instead. 3959 Tok->ContinuesLineCommentSection = 3960 continuesLineCommentSection(*Tok, *Line, CommentPragmasRegex); 3961 if (isOnNewLine(*Tok) && JustComments && !Tok->ContinuesLineCommentSection) 3962 addUnwrappedLine(); 3963 pushToken(Tok); 3964 } 3965 if (NewlineBeforeNext && JustComments) 3966 addUnwrappedLine(); 3967 CommentsBeforeNextToken.clear(); 3968 } 3969 3970 void UnwrappedLineParser::nextToken(int LevelDifference) { 3971 if (eof()) 3972 return; 3973 flushComments(isOnNewLine(*FormatTok)); 3974 pushToken(FormatTok); 3975 FormatToken *Previous = FormatTok; 3976 if (!Style.isJavaScript()) 3977 readToken(LevelDifference); 3978 else 3979 readTokenWithJavaScriptASI(); 3980 FormatTok->Previous = Previous; 3981 } 3982 3983 void UnwrappedLineParser::distributeComments( 3984 const SmallVectorImpl<FormatToken *> &Comments, 3985 const FormatToken *NextTok) { 3986 // Whether or not a line comment token continues a line is controlled by 3987 // the method continuesLineCommentSection, with the following caveat: 3988 // 3989 // Define a trail of Comments to be a nonempty proper postfix of Comments such 3990 // that each comment line from the trail is aligned with the next token, if 3991 // the next token exists. If a trail exists, the beginning of the maximal 3992 // trail is marked as a start of a new comment section. 3993 // 3994 // For example in this code: 3995 // 3996 // int a; // line about a 3997 // // line 1 about b 3998 // // line 2 about b 3999 // int b; 4000 // 4001 // the two lines about b form a maximal trail, so there are two sections, the 4002 // first one consisting of the single comment "// line about a" and the 4003 // second one consisting of the next two comments. 4004 if (Comments.empty()) 4005 return; 4006 bool ShouldPushCommentsInCurrentLine = true; 4007 bool HasTrailAlignedWithNextToken = false; 4008 unsigned StartOfTrailAlignedWithNextToken = 0; 4009 if (NextTok) { 4010 // We are skipping the first element intentionally. 4011 for (unsigned i = Comments.size() - 1; i > 0; --i) { 4012 if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) { 4013 HasTrailAlignedWithNextToken = true; 4014 StartOfTrailAlignedWithNextToken = i; 4015 } 4016 } 4017 } 4018 for (unsigned i = 0, e = Comments.size(); i < e; ++i) { 4019 FormatToken *FormatTok = Comments[i]; 4020 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) { 4021 FormatTok->ContinuesLineCommentSection = false; 4022 } else { 4023 FormatTok->ContinuesLineCommentSection = 4024 continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex); 4025 } 4026 if (!FormatTok->ContinuesLineCommentSection && 4027 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) 4028 ShouldPushCommentsInCurrentLine = false; 4029 if (ShouldPushCommentsInCurrentLine) 4030 pushToken(FormatTok); 4031 else 4032 CommentsBeforeNextToken.push_back(FormatTok); 4033 } 4034 } 4035 4036 void UnwrappedLineParser::readToken(int LevelDifference) { 4037 SmallVector<FormatToken *, 1> Comments; 4038 bool PreviousWasComment = false; 4039 bool FirstNonCommentOnLine = false; 4040 do { 4041 FormatTok = Tokens->getNextToken(); 4042 assert(FormatTok); 4043 while (FormatTok->getType() == TT_ConflictStart || 4044 FormatTok->getType() == TT_ConflictEnd || 4045 FormatTok->getType() == TT_ConflictAlternative) { 4046 if (FormatTok->getType() == TT_ConflictStart) 4047 conditionalCompilationStart(/*Unreachable=*/false); 4048 else if (FormatTok->getType() == TT_ConflictAlternative) 4049 conditionalCompilationAlternative(); 4050 else if (FormatTok->getType() == TT_ConflictEnd) 4051 conditionalCompilationEnd(); 4052 FormatTok = Tokens->getNextToken(); 4053 FormatTok->MustBreakBefore = true; 4054 } 4055 4056 auto IsFirstNonCommentOnLine = [](bool FirstNonCommentOnLine, 4057 const FormatToken &Tok, 4058 bool PreviousWasComment) { 4059 auto IsFirstOnLine = [](const FormatToken &Tok) { 4060 return Tok.HasUnescapedNewline || Tok.IsFirst; 4061 }; 4062 4063 // Consider preprocessor directives preceded by block comments as first 4064 // on line. 4065 if (PreviousWasComment) 4066 return FirstNonCommentOnLine || IsFirstOnLine(Tok); 4067 return IsFirstOnLine(Tok); 4068 }; 4069 4070 FirstNonCommentOnLine = IsFirstNonCommentOnLine( 4071 FirstNonCommentOnLine, *FormatTok, PreviousWasComment); 4072 PreviousWasComment = FormatTok->is(tok::comment); 4073 4074 while (!Line->InPPDirective && FormatTok->is(tok::hash) && 4075 FirstNonCommentOnLine) { 4076 distributeComments(Comments, FormatTok); 4077 Comments.clear(); 4078 // If there is an unfinished unwrapped line, we flush the preprocessor 4079 // directives only after that unwrapped line was finished later. 4080 bool SwitchToPreprocessorLines = !Line->Tokens.empty(); 4081 ScopedLineState BlockState(*this, SwitchToPreprocessorLines); 4082 assert((LevelDifference >= 0 || 4083 static_cast<unsigned>(-LevelDifference) <= Line->Level) && 4084 "LevelDifference makes Line->Level negative"); 4085 Line->Level += LevelDifference; 4086 // Comments stored before the preprocessor directive need to be output 4087 // before the preprocessor directive, at the same level as the 4088 // preprocessor directive, as we consider them to apply to the directive. 4089 if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash && 4090 PPBranchLevel > 0) 4091 Line->Level += PPBranchLevel; 4092 flushComments(isOnNewLine(*FormatTok)); 4093 parsePPDirective(); 4094 PreviousWasComment = FormatTok->is(tok::comment); 4095 FirstNonCommentOnLine = IsFirstNonCommentOnLine( 4096 FirstNonCommentOnLine, *FormatTok, PreviousWasComment); 4097 } 4098 4099 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) && 4100 !Line->InPPDirective) 4101 continue; 4102 4103 if (!FormatTok->is(tok::comment)) { 4104 distributeComments(Comments, FormatTok); 4105 Comments.clear(); 4106 return; 4107 } 4108 4109 Comments.push_back(FormatTok); 4110 } while (!eof()); 4111 4112 distributeComments(Comments, nullptr); 4113 Comments.clear(); 4114 } 4115 4116 void UnwrappedLineParser::pushToken(FormatToken *Tok) { 4117 Line->Tokens.push_back(UnwrappedLineNode(Tok)); 4118 if (MustBreakBeforeNextToken) { 4119 Line->Tokens.back().Tok->MustBreakBefore = true; 4120 MustBreakBeforeNextToken = false; 4121 } 4122 } 4123 4124 } // end namespace format 4125 } // end namespace clang 4126