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 // `[something] >` is not a lambda, but an array type in a template parameter 1944 // list. 1945 if (FormatTok->is(tok::greater)) 1946 return false; 1947 1948 bool SeenArrow = false; 1949 bool InTemplateParameterList = false; 1950 1951 while (FormatTok->isNot(tok::l_brace)) { 1952 if (FormatTok->isSimpleTypeSpecifier()) { 1953 nextToken(); 1954 continue; 1955 } 1956 switch (FormatTok->Tok.getKind()) { 1957 case tok::l_brace: 1958 break; 1959 case tok::l_paren: 1960 parseParens(); 1961 break; 1962 case tok::l_square: 1963 parseSquare(); 1964 break; 1965 case tok::kw_class: 1966 case tok::kw_template: 1967 case tok::kw_typename: 1968 assert(FormatTok->Previous); 1969 if (FormatTok->Previous->is(tok::less)) 1970 InTemplateParameterList = true; 1971 nextToken(); 1972 break; 1973 case tok::amp: 1974 case tok::star: 1975 case tok::kw_const: 1976 case tok::comma: 1977 case tok::less: 1978 case tok::greater: 1979 case tok::identifier: 1980 case tok::numeric_constant: 1981 case tok::coloncolon: 1982 case tok::kw_mutable: 1983 case tok::kw_noexcept: 1984 nextToken(); 1985 break; 1986 // Specialization of a template with an integer parameter can contain 1987 // arithmetic, logical, comparison and ternary operators. 1988 // 1989 // FIXME: This also accepts sequences of operators that are not in the scope 1990 // of a template argument list. 1991 // 1992 // In a C++ lambda a template type can only occur after an arrow. We use 1993 // this as an heuristic to distinguish between Objective-C expressions 1994 // followed by an `a->b` expression, such as: 1995 // ([obj func:arg] + a->b) 1996 // Otherwise the code below would parse as a lambda. 1997 // 1998 // FIXME: This heuristic is incorrect for C++20 generic lambdas with 1999 // explicit template lists: []<bool b = true && false>(U &&u){} 2000 case tok::plus: 2001 case tok::minus: 2002 case tok::exclaim: 2003 case tok::tilde: 2004 case tok::slash: 2005 case tok::percent: 2006 case tok::lessless: 2007 case tok::pipe: 2008 case tok::pipepipe: 2009 case tok::ampamp: 2010 case tok::caret: 2011 case tok::equalequal: 2012 case tok::exclaimequal: 2013 case tok::greaterequal: 2014 case tok::lessequal: 2015 case tok::question: 2016 case tok::colon: 2017 case tok::ellipsis: 2018 case tok::kw_true: 2019 case tok::kw_false: 2020 if (SeenArrow || InTemplateParameterList) { 2021 nextToken(); 2022 break; 2023 } 2024 return true; 2025 case tok::arrow: 2026 // This might or might not actually be a lambda arrow (this could be an 2027 // ObjC method invocation followed by a dereferencing arrow). We might 2028 // reset this back to TT_Unknown in TokenAnnotator. 2029 FormatTok->setFinalizedType(TT_LambdaArrow); 2030 SeenArrow = true; 2031 nextToken(); 2032 break; 2033 default: 2034 return true; 2035 } 2036 } 2037 FormatTok->setFinalizedType(TT_LambdaLBrace); 2038 LSquare.setFinalizedType(TT_LambdaLSquare); 2039 parseChildBlock(); 2040 return true; 2041 } 2042 2043 bool UnwrappedLineParser::tryToParseLambdaIntroducer() { 2044 const FormatToken *Previous = FormatTok->Previous; 2045 if (Previous && 2046 (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new, 2047 tok::kw_delete, tok::l_square) || 2048 FormatTok->isCppStructuredBinding(Style) || Previous->closesScope() || 2049 Previous->isSimpleTypeSpecifier())) { 2050 nextToken(); 2051 return false; 2052 } 2053 nextToken(); 2054 if (FormatTok->is(tok::l_square)) 2055 return false; 2056 parseSquare(/*LambdaIntroducer=*/true); 2057 return true; 2058 } 2059 2060 void UnwrappedLineParser::tryToParseJSFunction() { 2061 assert(FormatTok->is(Keywords.kw_function) || 2062 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)); 2063 if (FormatTok->is(Keywords.kw_async)) 2064 nextToken(); 2065 // Consume "function". 2066 nextToken(); 2067 2068 // Consume * (generator function). Treat it like C++'s overloaded operators. 2069 if (FormatTok->is(tok::star)) { 2070 FormatTok->setFinalizedType(TT_OverloadedOperator); 2071 nextToken(); 2072 } 2073 2074 // Consume function name. 2075 if (FormatTok->is(tok::identifier)) 2076 nextToken(); 2077 2078 if (FormatTok->isNot(tok::l_paren)) 2079 return; 2080 2081 // Parse formal parameter list. 2082 parseParens(); 2083 2084 if (FormatTok->is(tok::colon)) { 2085 // Parse a type definition. 2086 nextToken(); 2087 2088 // Eat the type declaration. For braced inline object types, balance braces, 2089 // otherwise just parse until finding an l_brace for the function body. 2090 if (FormatTok->is(tok::l_brace)) 2091 tryToParseBracedList(); 2092 else 2093 while (!FormatTok->isOneOf(tok::l_brace, tok::semi) && !eof()) 2094 nextToken(); 2095 } 2096 2097 if (FormatTok->is(tok::semi)) 2098 return; 2099 2100 parseChildBlock(); 2101 } 2102 2103 bool UnwrappedLineParser::tryToParseBracedList() { 2104 if (FormatTok->is(BK_Unknown)) 2105 calculateBraceTypes(); 2106 assert(FormatTok->isNot(BK_Unknown)); 2107 if (FormatTok->is(BK_Block)) 2108 return false; 2109 nextToken(); 2110 parseBracedList(); 2111 return true; 2112 } 2113 2114 bool UnwrappedLineParser::tryToParseChildBlock() { 2115 assert(Style.isJavaScript() || Style.isCSharp()); 2116 assert(FormatTok->is(TT_FatArrow)); 2117 // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType TT_FatArrow. 2118 // They always start an expression or a child block if followed by a curly 2119 // brace. 2120 nextToken(); 2121 if (FormatTok->isNot(tok::l_brace)) 2122 return false; 2123 parseChildBlock(); 2124 return true; 2125 } 2126 2127 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons, 2128 bool IsEnum, 2129 tok::TokenKind ClosingBraceKind) { 2130 bool HasError = false; 2131 2132 // FIXME: Once we have an expression parser in the UnwrappedLineParser, 2133 // replace this by using parseAssignmentExpression() inside. 2134 do { 2135 if (Style.isCSharp() && FormatTok->is(TT_FatArrow) && 2136 tryToParseChildBlock()) 2137 continue; 2138 if (Style.isJavaScript()) { 2139 if (FormatTok->is(Keywords.kw_function) || 2140 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) { 2141 tryToParseJSFunction(); 2142 continue; 2143 } 2144 if (FormatTok->is(tok::l_brace)) { 2145 // Could be a method inside of a braced list `{a() { return 1; }}`. 2146 if (tryToParseBracedList()) 2147 continue; 2148 parseChildBlock(); 2149 } 2150 } 2151 if (FormatTok->Tok.getKind() == ClosingBraceKind) { 2152 if (IsEnum && !Style.AllowShortEnumsOnASingleLine) 2153 addUnwrappedLine(); 2154 nextToken(); 2155 return !HasError; 2156 } 2157 switch (FormatTok->Tok.getKind()) { 2158 case tok::l_square: 2159 if (Style.isCSharp()) 2160 parseSquare(); 2161 else 2162 tryToParseLambda(); 2163 break; 2164 case tok::l_paren: 2165 parseParens(); 2166 // JavaScript can just have free standing methods and getters/setters in 2167 // object literals. Detect them by a "{" following ")". 2168 if (Style.isJavaScript()) { 2169 if (FormatTok->is(tok::l_brace)) 2170 parseChildBlock(); 2171 break; 2172 } 2173 break; 2174 case tok::l_brace: 2175 // Assume there are no blocks inside a braced init list apart 2176 // from the ones we explicitly parse out (like lambdas). 2177 FormatTok->setBlockKind(BK_BracedInit); 2178 nextToken(); 2179 parseBracedList(); 2180 break; 2181 case tok::less: 2182 if (Style.Language == FormatStyle::LK_Proto) { 2183 nextToken(); 2184 parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false, 2185 /*ClosingBraceKind=*/tok::greater); 2186 } else { 2187 nextToken(); 2188 } 2189 break; 2190 case tok::semi: 2191 // JavaScript (or more precisely TypeScript) can have semicolons in braced 2192 // lists (in so-called TypeMemberLists). Thus, the semicolon cannot be 2193 // used for error recovery if we have otherwise determined that this is 2194 // a braced list. 2195 if (Style.isJavaScript()) { 2196 nextToken(); 2197 break; 2198 } 2199 HasError = true; 2200 if (!ContinueOnSemicolons) 2201 return !HasError; 2202 nextToken(); 2203 break; 2204 case tok::comma: 2205 nextToken(); 2206 if (IsEnum && !Style.AllowShortEnumsOnASingleLine) 2207 addUnwrappedLine(); 2208 break; 2209 default: 2210 nextToken(); 2211 break; 2212 } 2213 } while (!eof()); 2214 return false; 2215 } 2216 2217 /// \brief Parses a pair of parentheses (and everything between them). 2218 /// \param AmpAmpTokenType If different than TT_Unknown sets this type for all 2219 /// double ampersands. This only counts for the current parens scope. 2220 void UnwrappedLineParser::parseParens(TokenType AmpAmpTokenType) { 2221 assert(FormatTok->is(tok::l_paren) && "'(' expected."); 2222 nextToken(); 2223 do { 2224 switch (FormatTok->Tok.getKind()) { 2225 case tok::l_paren: 2226 parseParens(); 2227 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace)) 2228 parseChildBlock(); 2229 break; 2230 case tok::r_paren: 2231 nextToken(); 2232 return; 2233 case tok::r_brace: 2234 // A "}" inside parenthesis is an error if there wasn't a matching "{". 2235 return; 2236 case tok::l_square: 2237 tryToParseLambda(); 2238 break; 2239 case tok::l_brace: 2240 if (!tryToParseBracedList()) 2241 parseChildBlock(); 2242 break; 2243 case tok::at: 2244 nextToken(); 2245 if (FormatTok->is(tok::l_brace)) { 2246 nextToken(); 2247 parseBracedList(); 2248 } 2249 break; 2250 case tok::equal: 2251 if (Style.isCSharp() && FormatTok->is(TT_FatArrow)) 2252 tryToParseChildBlock(); 2253 else 2254 nextToken(); 2255 break; 2256 case tok::kw_class: 2257 if (Style.isJavaScript()) 2258 parseRecord(/*ParseAsExpr=*/true); 2259 else 2260 nextToken(); 2261 break; 2262 case tok::identifier: 2263 if (Style.isJavaScript() && 2264 (FormatTok->is(Keywords.kw_function) || 2265 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function))) 2266 tryToParseJSFunction(); 2267 else 2268 nextToken(); 2269 break; 2270 case tok::kw_requires: { 2271 auto RequiresToken = FormatTok; 2272 nextToken(); 2273 parseRequiresExpression(RequiresToken); 2274 break; 2275 } 2276 case tok::ampamp: 2277 if (AmpAmpTokenType != TT_Unknown) 2278 FormatTok->setFinalizedType(AmpAmpTokenType); 2279 LLVM_FALLTHROUGH; 2280 default: 2281 nextToken(); 2282 break; 2283 } 2284 } while (!eof()); 2285 } 2286 2287 void UnwrappedLineParser::parseSquare(bool LambdaIntroducer) { 2288 if (!LambdaIntroducer) { 2289 assert(FormatTok->is(tok::l_square) && "'[' expected."); 2290 if (tryToParseLambda()) 2291 return; 2292 } 2293 do { 2294 switch (FormatTok->Tok.getKind()) { 2295 case tok::l_paren: 2296 parseParens(); 2297 break; 2298 case tok::r_square: 2299 nextToken(); 2300 return; 2301 case tok::r_brace: 2302 // A "}" inside parenthesis is an error if there wasn't a matching "{". 2303 return; 2304 case tok::l_square: 2305 parseSquare(); 2306 break; 2307 case tok::l_brace: { 2308 if (!tryToParseBracedList()) 2309 parseChildBlock(); 2310 break; 2311 } 2312 case tok::at: 2313 nextToken(); 2314 if (FormatTok->is(tok::l_brace)) { 2315 nextToken(); 2316 parseBracedList(); 2317 } 2318 break; 2319 default: 2320 nextToken(); 2321 break; 2322 } 2323 } while (!eof()); 2324 } 2325 2326 void UnwrappedLineParser::keepAncestorBraces() { 2327 if (!Style.RemoveBracesLLVM) 2328 return; 2329 2330 const int MaxNestingLevels = 2; 2331 const int Size = NestedTooDeep.size(); 2332 if (Size >= MaxNestingLevels) 2333 NestedTooDeep[Size - MaxNestingLevels] = true; 2334 NestedTooDeep.push_back(false); 2335 } 2336 2337 static FormatToken *getLastNonComment(const UnwrappedLine &Line) { 2338 for (const auto &Token : llvm::reverse(Line.Tokens)) 2339 if (Token.Tok->isNot(tok::comment)) 2340 return Token.Tok; 2341 2342 return nullptr; 2343 } 2344 2345 void UnwrappedLineParser::parseUnbracedBody(bool CheckEOF) { 2346 FormatToken *Tok = nullptr; 2347 2348 if (Style.InsertBraces && !Line->InPPDirective && !Line->Tokens.empty() && 2349 PreprocessorDirectives.empty()) { 2350 Tok = getLastNonComment(*Line); 2351 assert(Tok); 2352 if (Tok->BraceCount < 0) { 2353 assert(Tok->BraceCount == -1); 2354 Tok = nullptr; 2355 } else { 2356 Tok->BraceCount = -1; 2357 } 2358 } 2359 2360 addUnwrappedLine(); 2361 ++Line->Level; 2362 parseStructuralElement(); 2363 2364 if (Tok) { 2365 assert(!Line->InPPDirective); 2366 Tok = nullptr; 2367 for (const auto &L : llvm::reverse(*CurrentLines)) { 2368 if (!L.InPPDirective && getLastNonComment(L)) { 2369 Tok = L.Tokens.back().Tok; 2370 break; 2371 } 2372 } 2373 assert(Tok); 2374 ++Tok->BraceCount; 2375 } 2376 2377 if (CheckEOF && FormatTok->is(tok::eof)) 2378 addUnwrappedLine(); 2379 2380 --Line->Level; 2381 } 2382 2383 static void markOptionalBraces(FormatToken *LeftBrace) { 2384 if (!LeftBrace) 2385 return; 2386 2387 assert(LeftBrace->is(tok::l_brace)); 2388 2389 FormatToken *RightBrace = LeftBrace->MatchingParen; 2390 if (!RightBrace) { 2391 assert(!LeftBrace->Optional); 2392 return; 2393 } 2394 2395 assert(RightBrace->is(tok::r_brace)); 2396 assert(RightBrace->MatchingParen == LeftBrace); 2397 assert(LeftBrace->Optional == RightBrace->Optional); 2398 2399 LeftBrace->Optional = true; 2400 RightBrace->Optional = true; 2401 } 2402 2403 void UnwrappedLineParser::handleAttributes() { 2404 // Handle AttributeMacro, e.g. `if (x) UNLIKELY`. 2405 if (FormatTok->is(TT_AttributeMacro)) 2406 nextToken(); 2407 handleCppAttributes(); 2408 } 2409 2410 bool UnwrappedLineParser::handleCppAttributes() { 2411 // Handle [[likely]] / [[unlikely]] attributes. 2412 if (FormatTok->is(tok::l_square) && tryToParseSimpleAttribute()) { 2413 parseSquare(); 2414 return true; 2415 } 2416 return false; 2417 } 2418 2419 FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind, 2420 bool KeepBraces) { 2421 assert(FormatTok->is(tok::kw_if) && "'if' expected"); 2422 nextToken(); 2423 if (FormatTok->is(tok::exclaim)) 2424 nextToken(); 2425 if (FormatTok->is(tok::kw_consteval)) { 2426 nextToken(); 2427 } else { 2428 if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier)) 2429 nextToken(); 2430 if (FormatTok->is(tok::l_paren)) 2431 parseParens(); 2432 } 2433 handleAttributes(); 2434 2435 bool NeedsUnwrappedLine = false; 2436 keepAncestorBraces(); 2437 2438 FormatToken *IfLeftBrace = nullptr; 2439 IfStmtKind IfBlockKind = IfStmtKind::NotIf; 2440 2441 if (FormatTok->is(tok::l_brace)) { 2442 IfLeftBrace = FormatTok; 2443 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2444 IfBlockKind = parseBlock(); 2445 if (Style.BraceWrapping.BeforeElse) 2446 addUnwrappedLine(); 2447 else 2448 NeedsUnwrappedLine = true; 2449 } else { 2450 parseUnbracedBody(); 2451 } 2452 2453 bool KeepIfBraces = false; 2454 if (Style.RemoveBracesLLVM) { 2455 assert(!NestedTooDeep.empty()); 2456 KeepIfBraces = (IfLeftBrace && !IfLeftBrace->MatchingParen) || 2457 NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly || 2458 IfBlockKind == IfStmtKind::IfElseIf; 2459 } 2460 2461 FormatToken *ElseLeftBrace = nullptr; 2462 IfStmtKind Kind = IfStmtKind::IfOnly; 2463 2464 if (FormatTok->is(tok::kw_else)) { 2465 if (Style.RemoveBracesLLVM) { 2466 NestedTooDeep.back() = false; 2467 Kind = IfStmtKind::IfElse; 2468 } 2469 nextToken(); 2470 handleAttributes(); 2471 if (FormatTok->is(tok::l_brace)) { 2472 ElseLeftBrace = FormatTok; 2473 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2474 if (parseBlock() == IfStmtKind::IfOnly) 2475 Kind = IfStmtKind::IfElseIf; 2476 addUnwrappedLine(); 2477 } else if (FormatTok->is(tok::kw_if)) { 2478 FormatToken *Previous = Tokens->getPreviousToken(); 2479 const bool IsPrecededByComment = Previous && Previous->is(tok::comment); 2480 if (IsPrecededByComment) { 2481 addUnwrappedLine(); 2482 ++Line->Level; 2483 } 2484 bool TooDeep = true; 2485 if (Style.RemoveBracesLLVM) { 2486 Kind = IfStmtKind::IfElseIf; 2487 TooDeep = NestedTooDeep.pop_back_val(); 2488 } 2489 ElseLeftBrace = 2490 parseIfThenElse(/*IfKind=*/nullptr, KeepBraces || KeepIfBraces); 2491 if (Style.RemoveBracesLLVM) 2492 NestedTooDeep.push_back(TooDeep); 2493 if (IsPrecededByComment) 2494 --Line->Level; 2495 } else { 2496 parseUnbracedBody(/*CheckEOF=*/true); 2497 } 2498 } else { 2499 if (Style.RemoveBracesLLVM) 2500 KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse; 2501 if (NeedsUnwrappedLine) 2502 addUnwrappedLine(); 2503 } 2504 2505 if (!Style.RemoveBracesLLVM) 2506 return nullptr; 2507 2508 assert(!NestedTooDeep.empty()); 2509 const bool KeepElseBraces = 2510 (ElseLeftBrace && !ElseLeftBrace->MatchingParen) || NestedTooDeep.back(); 2511 2512 NestedTooDeep.pop_back(); 2513 2514 if (!KeepBraces && !KeepIfBraces && !KeepElseBraces) { 2515 markOptionalBraces(IfLeftBrace); 2516 markOptionalBraces(ElseLeftBrace); 2517 } else if (IfLeftBrace) { 2518 FormatToken *IfRightBrace = IfLeftBrace->MatchingParen; 2519 if (IfRightBrace) { 2520 assert(IfRightBrace->MatchingParen == IfLeftBrace); 2521 assert(!IfLeftBrace->Optional); 2522 assert(!IfRightBrace->Optional); 2523 IfLeftBrace->MatchingParen = nullptr; 2524 IfRightBrace->MatchingParen = nullptr; 2525 } 2526 } 2527 2528 if (IfKind) 2529 *IfKind = Kind; 2530 2531 return IfLeftBrace; 2532 } 2533 2534 void UnwrappedLineParser::parseTryCatch() { 2535 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected"); 2536 nextToken(); 2537 bool NeedsUnwrappedLine = false; 2538 if (FormatTok->is(tok::colon)) { 2539 // We are in a function try block, what comes is an initializer list. 2540 nextToken(); 2541 2542 // In case identifiers were removed by clang-tidy, what might follow is 2543 // multiple commas in sequence - before the first identifier. 2544 while (FormatTok->is(tok::comma)) 2545 nextToken(); 2546 2547 while (FormatTok->is(tok::identifier)) { 2548 nextToken(); 2549 if (FormatTok->is(tok::l_paren)) 2550 parseParens(); 2551 if (FormatTok->Previous && FormatTok->Previous->is(tok::identifier) && 2552 FormatTok->is(tok::l_brace)) { 2553 do { 2554 nextToken(); 2555 } while (!FormatTok->is(tok::r_brace)); 2556 nextToken(); 2557 } 2558 2559 // In case identifiers were removed by clang-tidy, what might follow is 2560 // multiple commas in sequence - after the first identifier. 2561 while (FormatTok->is(tok::comma)) 2562 nextToken(); 2563 } 2564 } 2565 // Parse try with resource. 2566 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) 2567 parseParens(); 2568 2569 keepAncestorBraces(); 2570 2571 if (FormatTok->is(tok::l_brace)) { 2572 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2573 parseBlock(); 2574 if (Style.BraceWrapping.BeforeCatch) 2575 addUnwrappedLine(); 2576 else 2577 NeedsUnwrappedLine = true; 2578 } else if (!FormatTok->is(tok::kw_catch)) { 2579 // The C++ standard requires a compound-statement after a try. 2580 // If there's none, we try to assume there's a structuralElement 2581 // and try to continue. 2582 addUnwrappedLine(); 2583 ++Line->Level; 2584 parseStructuralElement(); 2585 --Line->Level; 2586 } 2587 while (true) { 2588 if (FormatTok->is(tok::at)) 2589 nextToken(); 2590 if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except, 2591 tok::kw___finally) || 2592 ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) && 2593 FormatTok->is(Keywords.kw_finally)) || 2594 (FormatTok->isObjCAtKeyword(tok::objc_catch) || 2595 FormatTok->isObjCAtKeyword(tok::objc_finally)))) 2596 break; 2597 nextToken(); 2598 while (FormatTok->isNot(tok::l_brace)) { 2599 if (FormatTok->is(tok::l_paren)) { 2600 parseParens(); 2601 continue; 2602 } 2603 if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof)) { 2604 if (Style.RemoveBracesLLVM) 2605 NestedTooDeep.pop_back(); 2606 return; 2607 } 2608 nextToken(); 2609 } 2610 NeedsUnwrappedLine = false; 2611 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2612 parseBlock(); 2613 if (Style.BraceWrapping.BeforeCatch) 2614 addUnwrappedLine(); 2615 else 2616 NeedsUnwrappedLine = true; 2617 } 2618 2619 if (Style.RemoveBracesLLVM) 2620 NestedTooDeep.pop_back(); 2621 2622 if (NeedsUnwrappedLine) 2623 addUnwrappedLine(); 2624 } 2625 2626 void UnwrappedLineParser::parseNamespace() { 2627 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) && 2628 "'namespace' expected"); 2629 2630 const FormatToken &InitialToken = *FormatTok; 2631 nextToken(); 2632 if (InitialToken.is(TT_NamespaceMacro)) { 2633 parseParens(); 2634 } else { 2635 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline, 2636 tok::l_square, tok::period, tok::l_paren) || 2637 (Style.isCSharp() && FormatTok->is(tok::kw_union))) 2638 if (FormatTok->is(tok::l_square)) 2639 parseSquare(); 2640 else if (FormatTok->is(tok::l_paren)) 2641 parseParens(); 2642 else 2643 nextToken(); 2644 } 2645 if (FormatTok->is(tok::l_brace)) { 2646 if (ShouldBreakBeforeBrace(Style, InitialToken)) 2647 addUnwrappedLine(); 2648 2649 unsigned AddLevels = 2650 Style.NamespaceIndentation == FormatStyle::NI_All || 2651 (Style.NamespaceIndentation == FormatStyle::NI_Inner && 2652 DeclarationScopeStack.size() > 1) 2653 ? 1u 2654 : 0u; 2655 bool ManageWhitesmithsBraces = 2656 AddLevels == 0u && 2657 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths; 2658 2659 // If we're in Whitesmiths mode, indent the brace if we're not indenting 2660 // the whole block. 2661 if (ManageWhitesmithsBraces) 2662 ++Line->Level; 2663 2664 parseBlock(/*MustBeDeclaration=*/true, AddLevels, 2665 /*MunchSemi=*/true, 2666 /*UnindentWhitesmithsBraces=*/ManageWhitesmithsBraces); 2667 2668 // Munch the semicolon after a namespace. This is more common than one would 2669 // think. Putting the semicolon into its own line is very ugly. 2670 if (FormatTok->is(tok::semi)) 2671 nextToken(); 2672 2673 addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep); 2674 2675 if (ManageWhitesmithsBraces) 2676 --Line->Level; 2677 } 2678 // FIXME: Add error handling. 2679 } 2680 2681 void UnwrappedLineParser::parseNew() { 2682 assert(FormatTok->is(tok::kw_new) && "'new' expected"); 2683 nextToken(); 2684 2685 if (Style.isCSharp()) { 2686 do { 2687 if (FormatTok->is(tok::l_brace)) 2688 parseBracedList(); 2689 2690 if (FormatTok->isOneOf(tok::semi, tok::comma)) 2691 return; 2692 2693 nextToken(); 2694 } while (!eof()); 2695 } 2696 2697 if (Style.Language != FormatStyle::LK_Java) 2698 return; 2699 2700 // In Java, we can parse everything up to the parens, which aren't optional. 2701 do { 2702 // There should not be a ;, { or } before the new's open paren. 2703 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace)) 2704 return; 2705 2706 // Consume the parens. 2707 if (FormatTok->is(tok::l_paren)) { 2708 parseParens(); 2709 2710 // If there is a class body of an anonymous class, consume that as child. 2711 if (FormatTok->is(tok::l_brace)) 2712 parseChildBlock(); 2713 return; 2714 } 2715 nextToken(); 2716 } while (!eof()); 2717 } 2718 2719 void UnwrappedLineParser::parseForOrWhileLoop() { 2720 assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) && 2721 "'for', 'while' or foreach macro expected"); 2722 nextToken(); 2723 // JS' for await ( ... 2724 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await)) 2725 nextToken(); 2726 if (Style.isCpp() && FormatTok->is(tok::kw_co_await)) 2727 nextToken(); 2728 if (FormatTok->is(tok::l_paren)) 2729 parseParens(); 2730 2731 keepAncestorBraces(); 2732 2733 if (FormatTok->is(tok::l_brace)) { 2734 FormatToken *LeftBrace = FormatTok; 2735 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2736 parseBlock(); 2737 if (Style.RemoveBracesLLVM) { 2738 assert(!NestedTooDeep.empty()); 2739 if (!NestedTooDeep.back()) 2740 markOptionalBraces(LeftBrace); 2741 } 2742 addUnwrappedLine(); 2743 } else { 2744 parseUnbracedBody(); 2745 } 2746 2747 if (Style.RemoveBracesLLVM) 2748 NestedTooDeep.pop_back(); 2749 } 2750 2751 void UnwrappedLineParser::parseDoWhile() { 2752 assert(FormatTok->is(tok::kw_do) && "'do' expected"); 2753 nextToken(); 2754 2755 keepAncestorBraces(); 2756 2757 if (FormatTok->is(tok::l_brace)) { 2758 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2759 parseBlock(); 2760 if (Style.BraceWrapping.BeforeWhile) 2761 addUnwrappedLine(); 2762 } else { 2763 parseUnbracedBody(); 2764 } 2765 2766 if (Style.RemoveBracesLLVM) 2767 NestedTooDeep.pop_back(); 2768 2769 // FIXME: Add error handling. 2770 if (!FormatTok->is(tok::kw_while)) { 2771 addUnwrappedLine(); 2772 return; 2773 } 2774 2775 // If in Whitesmiths mode, the line with the while() needs to be indented 2776 // to the same level as the block. 2777 if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) 2778 ++Line->Level; 2779 2780 nextToken(); 2781 parseStructuralElement(); 2782 } 2783 2784 void UnwrappedLineParser::parseLabel(bool LeftAlignLabel) { 2785 nextToken(); 2786 unsigned OldLineLevel = Line->Level; 2787 if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0)) 2788 --Line->Level; 2789 if (LeftAlignLabel) 2790 Line->Level = 0; 2791 2792 if (!Style.IndentCaseBlocks && CommentsBeforeNextToken.empty() && 2793 FormatTok->is(tok::l_brace)) { 2794 2795 CompoundStatementIndenter Indenter(this, Line->Level, 2796 Style.BraceWrapping.AfterCaseLabel, 2797 Style.BraceWrapping.IndentBraces); 2798 parseBlock(); 2799 if (FormatTok->is(tok::kw_break)) { 2800 if (Style.BraceWrapping.AfterControlStatement == 2801 FormatStyle::BWACS_Always) { 2802 addUnwrappedLine(); 2803 if (!Style.IndentCaseBlocks && 2804 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) 2805 ++Line->Level; 2806 } 2807 parseStructuralElement(); 2808 } 2809 addUnwrappedLine(); 2810 } else { 2811 if (FormatTok->is(tok::semi)) 2812 nextToken(); 2813 addUnwrappedLine(); 2814 } 2815 Line->Level = OldLineLevel; 2816 if (FormatTok->isNot(tok::l_brace)) { 2817 parseStructuralElement(); 2818 addUnwrappedLine(); 2819 } 2820 } 2821 2822 void UnwrappedLineParser::parseCaseLabel() { 2823 assert(FormatTok->is(tok::kw_case) && "'case' expected"); 2824 2825 // FIXME: fix handling of complex expressions here. 2826 do { 2827 nextToken(); 2828 } while (!eof() && !FormatTok->is(tok::colon)); 2829 parseLabel(); 2830 } 2831 2832 void UnwrappedLineParser::parseSwitch() { 2833 assert(FormatTok->is(tok::kw_switch) && "'switch' expected"); 2834 nextToken(); 2835 if (FormatTok->is(tok::l_paren)) 2836 parseParens(); 2837 2838 keepAncestorBraces(); 2839 2840 if (FormatTok->is(tok::l_brace)) { 2841 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2842 parseBlock(); 2843 addUnwrappedLine(); 2844 } else { 2845 addUnwrappedLine(); 2846 ++Line->Level; 2847 parseStructuralElement(); 2848 --Line->Level; 2849 } 2850 2851 if (Style.RemoveBracesLLVM) 2852 NestedTooDeep.pop_back(); 2853 } 2854 2855 // Operators that can follow a C variable. 2856 static bool isCOperatorFollowingVar(tok::TokenKind kind) { 2857 switch (kind) { 2858 case tok::ampamp: 2859 case tok::ampequal: 2860 case tok::arrow: 2861 case tok::caret: 2862 case tok::caretequal: 2863 case tok::comma: 2864 case tok::ellipsis: 2865 case tok::equal: 2866 case tok::equalequal: 2867 case tok::exclaim: 2868 case tok::exclaimequal: 2869 case tok::greater: 2870 case tok::greaterequal: 2871 case tok::greatergreater: 2872 case tok::greatergreaterequal: 2873 case tok::l_paren: 2874 case tok::l_square: 2875 case tok::less: 2876 case tok::lessequal: 2877 case tok::lessless: 2878 case tok::lesslessequal: 2879 case tok::minus: 2880 case tok::minusequal: 2881 case tok::minusminus: 2882 case tok::percent: 2883 case tok::percentequal: 2884 case tok::period: 2885 case tok::pipe: 2886 case tok::pipeequal: 2887 case tok::pipepipe: 2888 case tok::plus: 2889 case tok::plusequal: 2890 case tok::plusplus: 2891 case tok::question: 2892 case tok::r_brace: 2893 case tok::r_paren: 2894 case tok::r_square: 2895 case tok::semi: 2896 case tok::slash: 2897 case tok::slashequal: 2898 case tok::star: 2899 case tok::starequal: 2900 return true; 2901 default: 2902 return false; 2903 } 2904 } 2905 2906 void UnwrappedLineParser::parseAccessSpecifier() { 2907 FormatToken *AccessSpecifierCandidate = FormatTok; 2908 nextToken(); 2909 // Understand Qt's slots. 2910 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots)) 2911 nextToken(); 2912 // Otherwise, we don't know what it is, and we'd better keep the next token. 2913 if (FormatTok->is(tok::colon)) { 2914 nextToken(); 2915 addUnwrappedLine(); 2916 } else if (!FormatTok->is(tok::coloncolon) && 2917 !isCOperatorFollowingVar(FormatTok->Tok.getKind())) { 2918 // Not a variable name nor namespace name. 2919 addUnwrappedLine(); 2920 } else if (AccessSpecifierCandidate) { 2921 // Consider the access specifier to be a C identifier. 2922 AccessSpecifierCandidate->Tok.setKind(tok::identifier); 2923 } 2924 } 2925 2926 /// \brief Parses a concept definition. 2927 /// \pre The current token has to be the concept keyword. 2928 /// 2929 /// Returns if either the concept has been completely parsed, or if it detects 2930 /// that the concept definition is incorrect. 2931 void UnwrappedLineParser::parseConcept() { 2932 assert(FormatTok->is(tok::kw_concept) && "'concept' expected"); 2933 nextToken(); 2934 if (!FormatTok->is(tok::identifier)) 2935 return; 2936 nextToken(); 2937 if (!FormatTok->is(tok::equal)) 2938 return; 2939 nextToken(); 2940 parseConstraintExpression(); 2941 if (FormatTok->is(tok::semi)) 2942 nextToken(); 2943 addUnwrappedLine(); 2944 } 2945 2946 /// \brief Parses a requires, decides if it is a clause or an expression. 2947 /// \pre The current token has to be the requires keyword. 2948 /// \returns true if it parsed a clause. 2949 bool clang::format::UnwrappedLineParser::parseRequires() { 2950 assert(FormatTok->is(tok::kw_requires) && "'requires' expected"); 2951 auto RequiresToken = FormatTok; 2952 2953 // We try to guess if it is a requires clause, or a requires expression. For 2954 // that we first consume the keyword and check the next token. 2955 nextToken(); 2956 2957 switch (FormatTok->Tok.getKind()) { 2958 case tok::l_brace: 2959 // This can only be an expression, never a clause. 2960 parseRequiresExpression(RequiresToken); 2961 return false; 2962 case tok::l_paren: 2963 // Clauses and expression can start with a paren, it's unclear what we have. 2964 break; 2965 default: 2966 // All other tokens can only be a clause. 2967 parseRequiresClause(RequiresToken); 2968 return true; 2969 } 2970 2971 // Looking forward we would have to decide if there are function declaration 2972 // like arguments to the requires expression: 2973 // requires (T t) { 2974 // Or there is a constraint expression for the requires clause: 2975 // requires (C<T> && ... 2976 2977 // But first let's look behind. 2978 auto *PreviousNonComment = RequiresToken->getPreviousNonComment(); 2979 2980 if (!PreviousNonComment || 2981 PreviousNonComment->is(TT_RequiresExpressionLBrace)) { 2982 // If there is no token, or an expression left brace, we are a requires 2983 // clause within a requires expression. 2984 parseRequiresClause(RequiresToken); 2985 return true; 2986 } 2987 2988 switch (PreviousNonComment->Tok.getKind()) { 2989 case tok::greater: 2990 case tok::r_paren: 2991 case tok::kw_noexcept: 2992 case tok::kw_const: 2993 // This is a requires clause. 2994 parseRequiresClause(RequiresToken); 2995 return true; 2996 case tok::amp: 2997 case tok::ampamp: { 2998 // This can be either: 2999 // if (... && requires (T t) ...) 3000 // Or 3001 // void member(...) && requires (C<T> ... 3002 // We check the one token before that for a const: 3003 // void member(...) const && requires (C<T> ... 3004 auto PrevPrev = PreviousNonComment->getPreviousNonComment(); 3005 if (PrevPrev && PrevPrev->is(tok::kw_const)) { 3006 parseRequiresClause(RequiresToken); 3007 return true; 3008 } 3009 break; 3010 } 3011 default: 3012 // It's an expression. 3013 parseRequiresExpression(RequiresToken); 3014 return false; 3015 } 3016 3017 // Now we look forward and try to check if the paren content is a parameter 3018 // list. The parameters can be cv-qualified and contain references or 3019 // pointers. 3020 // So we want basically to check for TYPE NAME, but TYPE can contain all kinds 3021 // of stuff: typename, const, *, &, &&, ::, identifiers. 3022 3023 int NextTokenOffset = 1; 3024 auto NextToken = Tokens->peekNextToken(NextTokenOffset); 3025 auto PeekNext = [&NextTokenOffset, &NextToken, this] { 3026 ++NextTokenOffset; 3027 NextToken = Tokens->peekNextToken(NextTokenOffset); 3028 }; 3029 3030 bool FoundType = false; 3031 bool LastWasColonColon = false; 3032 int OpenAngles = 0; 3033 3034 for (; NextTokenOffset < 50; PeekNext()) { 3035 switch (NextToken->Tok.getKind()) { 3036 case tok::kw_volatile: 3037 case tok::kw_const: 3038 case tok::comma: 3039 parseRequiresExpression(RequiresToken); 3040 return false; 3041 case tok::r_paren: 3042 case tok::pipepipe: 3043 parseRequiresClause(RequiresToken); 3044 return true; 3045 case tok::eof: 3046 // Break out of the loop. 3047 NextTokenOffset = 50; 3048 break; 3049 case tok::coloncolon: 3050 LastWasColonColon = true; 3051 break; 3052 case tok::identifier: 3053 if (FoundType && !LastWasColonColon && OpenAngles == 0) { 3054 parseRequiresExpression(RequiresToken); 3055 return false; 3056 } 3057 FoundType = true; 3058 LastWasColonColon = false; 3059 break; 3060 case tok::less: 3061 ++OpenAngles; 3062 break; 3063 case tok::greater: 3064 --OpenAngles; 3065 break; 3066 default: 3067 if (NextToken->isSimpleTypeSpecifier()) { 3068 parseRequiresExpression(RequiresToken); 3069 return false; 3070 } 3071 break; 3072 } 3073 } 3074 3075 // This seems to be a complicated expression, just assume it's a clause. 3076 parseRequiresClause(RequiresToken); 3077 return true; 3078 } 3079 3080 /// \brief Parses a requires clause. 3081 /// \param RequiresToken The requires keyword token, which starts this clause. 3082 /// \pre We need to be on the next token after the requires keyword. 3083 /// \sa parseRequiresExpression 3084 /// 3085 /// Returns if it either has finished parsing the clause, or it detects, that 3086 /// the clause is incorrect. 3087 void UnwrappedLineParser::parseRequiresClause(FormatToken *RequiresToken) { 3088 assert(FormatTok->getPreviousNonComment() == RequiresToken); 3089 assert(RequiresToken->is(tok::kw_requires) && "'requires' expected"); 3090 3091 // If there is no previous token, we are within a requires expression, 3092 // otherwise we will always have the template or function declaration in front 3093 // of it. 3094 bool InRequiresExpression = 3095 !RequiresToken->Previous || 3096 RequiresToken->Previous->is(TT_RequiresExpressionLBrace); 3097 3098 RequiresToken->setFinalizedType(InRequiresExpression 3099 ? TT_RequiresClauseInARequiresExpression 3100 : TT_RequiresClause); 3101 3102 parseConstraintExpression(); 3103 3104 if (!InRequiresExpression) 3105 FormatTok->Previous->ClosesRequiresClause = true; 3106 } 3107 3108 /// \brief Parses a requires expression. 3109 /// \param RequiresToken The requires keyword token, which starts this clause. 3110 /// \pre We need to be on the next token after the requires keyword. 3111 /// \sa parseRequiresClause 3112 /// 3113 /// Returns if it either has finished parsing the expression, or it detects, 3114 /// that the expression is incorrect. 3115 void UnwrappedLineParser::parseRequiresExpression(FormatToken *RequiresToken) { 3116 assert(FormatTok->getPreviousNonComment() == RequiresToken); 3117 assert(RequiresToken->is(tok::kw_requires) && "'requires' expected"); 3118 3119 RequiresToken->setFinalizedType(TT_RequiresExpression); 3120 3121 if (FormatTok->is(tok::l_paren)) { 3122 FormatTok->setFinalizedType(TT_RequiresExpressionLParen); 3123 parseParens(); 3124 } 3125 3126 if (FormatTok->is(tok::l_brace)) { 3127 FormatTok->setFinalizedType(TT_RequiresExpressionLBrace); 3128 parseChildBlock(/*CanContainBracedList=*/false, 3129 /*NextLBracesType=*/TT_CompoundRequirementLBrace); 3130 } 3131 } 3132 3133 /// \brief Parses a constraint expression. 3134 /// 3135 /// This is either the definition of a concept, or the body of a requires 3136 /// clause. It returns, when the parsing is complete, or the expression is 3137 /// incorrect. 3138 void UnwrappedLineParser::parseConstraintExpression() { 3139 // The special handling for lambdas is needed since tryToParseLambda() eats a 3140 // token and if a requires expression is the last part of a requires clause 3141 // and followed by an attribute like [[nodiscard]] the ClosesRequiresClause is 3142 // not set on the correct token. Thus we need to be aware if we even expect a 3143 // lambda to be possible. 3144 // template <typename T> requires requires { ... } [[nodiscard]] ...; 3145 bool LambdaNextTimeAllowed = true; 3146 do { 3147 bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed, false); 3148 3149 switch (FormatTok->Tok.getKind()) { 3150 case tok::kw_requires: { 3151 auto RequiresToken = FormatTok; 3152 nextToken(); 3153 parseRequiresExpression(RequiresToken); 3154 break; 3155 } 3156 3157 case tok::l_paren: 3158 parseParens(/*AmpAmpTokenType=*/TT_BinaryOperator); 3159 break; 3160 3161 case tok::l_square: 3162 if (!LambdaThisTimeAllowed || !tryToParseLambda()) 3163 return; 3164 break; 3165 3166 case tok::kw_const: 3167 case tok::semi: 3168 case tok::kw_class: 3169 case tok::kw_struct: 3170 case tok::kw_union: 3171 return; 3172 3173 case tok::l_brace: 3174 // Potential function body. 3175 return; 3176 3177 case tok::ampamp: 3178 case tok::pipepipe: 3179 FormatTok->setFinalizedType(TT_BinaryOperator); 3180 nextToken(); 3181 LambdaNextTimeAllowed = true; 3182 break; 3183 3184 case tok::comma: 3185 case tok::comment: 3186 LambdaNextTimeAllowed = LambdaThisTimeAllowed; 3187 nextToken(); 3188 break; 3189 3190 case tok::kw_sizeof: 3191 case tok::greater: 3192 case tok::greaterequal: 3193 case tok::greatergreater: 3194 case tok::less: 3195 case tok::lessequal: 3196 case tok::lessless: 3197 case tok::equalequal: 3198 case tok::exclaim: 3199 case tok::exclaimequal: 3200 case tok::plus: 3201 case tok::minus: 3202 case tok::star: 3203 case tok::slash: 3204 case tok::kw_decltype: 3205 LambdaNextTimeAllowed = true; 3206 // Just eat them. 3207 nextToken(); 3208 break; 3209 3210 case tok::numeric_constant: 3211 case tok::coloncolon: 3212 case tok::kw_true: 3213 case tok::kw_false: 3214 // Just eat them. 3215 nextToken(); 3216 break; 3217 3218 case tok::kw_static_cast: 3219 case tok::kw_const_cast: 3220 case tok::kw_reinterpret_cast: 3221 case tok::kw_dynamic_cast: 3222 nextToken(); 3223 if (!FormatTok->is(tok::less)) 3224 return; 3225 3226 parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false, 3227 /*ClosingBraceKind=*/tok::greater); 3228 break; 3229 3230 case tok::kw_bool: 3231 // bool is only allowed if it is directly followed by a paren for a cast: 3232 // concept C = bool(...); 3233 // and bool is the only type, all other types as cast must be inside a 3234 // cast to bool an thus are handled by the other cases. 3235 nextToken(); 3236 if (FormatTok->isNot(tok::l_paren)) 3237 return; 3238 parseParens(); 3239 break; 3240 3241 default: 3242 if (!FormatTok->Tok.getIdentifierInfo()) { 3243 // Identifiers are part of the default case, we check for more then 3244 // tok::identifier to handle builtin type traits. 3245 return; 3246 } 3247 3248 // We need to differentiate identifiers for a template deduction guide, 3249 // variables, or function return types (the constraint expression has 3250 // ended before that), and basically all other cases. But it's easier to 3251 // check the other way around. 3252 assert(FormatTok->Previous); 3253 switch (FormatTok->Previous->Tok.getKind()) { 3254 case tok::coloncolon: // Nested identifier. 3255 case tok::ampamp: // Start of a function or variable for the 3256 case tok::pipepipe: // constraint expression. 3257 case tok::kw_requires: // Initial identifier of a requires clause. 3258 case tok::equal: // Initial identifier of a concept declaration. 3259 break; 3260 default: 3261 return; 3262 } 3263 3264 // Read identifier with optional template declaration. 3265 nextToken(); 3266 if (FormatTok->is(tok::less)) 3267 parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false, 3268 /*ClosingBraceKind=*/tok::greater); 3269 break; 3270 } 3271 } while (!eof()); 3272 } 3273 3274 bool UnwrappedLineParser::parseEnum() { 3275 const FormatToken &InitialToken = *FormatTok; 3276 3277 // Won't be 'enum' for NS_ENUMs. 3278 if (FormatTok->is(tok::kw_enum)) 3279 nextToken(); 3280 3281 // In TypeScript, "enum" can also be used as property name, e.g. in interface 3282 // declarations. An "enum" keyword followed by a colon would be a syntax 3283 // error and thus assume it is just an identifier. 3284 if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question)) 3285 return false; 3286 3287 // In protobuf, "enum" can be used as a field name. 3288 if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal)) 3289 return false; 3290 3291 // Eat up enum class ... 3292 if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct)) 3293 nextToken(); 3294 3295 while (FormatTok->Tok.getIdentifierInfo() || 3296 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less, 3297 tok::greater, tok::comma, tok::question)) { 3298 nextToken(); 3299 // We can have macros or attributes in between 'enum' and the enum name. 3300 if (FormatTok->is(tok::l_paren)) 3301 parseParens(); 3302 if (FormatTok->is(tok::identifier)) { 3303 nextToken(); 3304 // If there are two identifiers in a row, this is likely an elaborate 3305 // return type. In Java, this can be "implements", etc. 3306 if (Style.isCpp() && FormatTok->is(tok::identifier)) 3307 return false; 3308 } 3309 } 3310 3311 // Just a declaration or something is wrong. 3312 if (FormatTok->isNot(tok::l_brace)) 3313 return true; 3314 FormatTok->setFinalizedType(TT_EnumLBrace); 3315 FormatTok->setBlockKind(BK_Block); 3316 3317 if (Style.Language == FormatStyle::LK_Java) { 3318 // Java enums are different. 3319 parseJavaEnumBody(); 3320 return true; 3321 } 3322 if (Style.Language == FormatStyle::LK_Proto) { 3323 parseBlock(/*MustBeDeclaration=*/true); 3324 return true; 3325 } 3326 3327 if (!Style.AllowShortEnumsOnASingleLine && 3328 ShouldBreakBeforeBrace(Style, InitialToken)) 3329 addUnwrappedLine(); 3330 // Parse enum body. 3331 nextToken(); 3332 if (!Style.AllowShortEnumsOnASingleLine) { 3333 addUnwrappedLine(); 3334 Line->Level += 1; 3335 } 3336 bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true, 3337 /*IsEnum=*/true); 3338 if (!Style.AllowShortEnumsOnASingleLine) 3339 Line->Level -= 1; 3340 if (HasError) { 3341 if (FormatTok->is(tok::semi)) 3342 nextToken(); 3343 addUnwrappedLine(); 3344 } 3345 return true; 3346 3347 // There is no addUnwrappedLine() here so that we fall through to parsing a 3348 // structural element afterwards. Thus, in "enum A {} n, m;", 3349 // "} n, m;" will end up in one unwrapped line. 3350 } 3351 3352 bool UnwrappedLineParser::parseStructLike() { 3353 // parseRecord falls through and does not yet add an unwrapped line as a 3354 // record declaration or definition can start a structural element. 3355 parseRecord(); 3356 // This does not apply to Java, JavaScript and C#. 3357 if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() || 3358 Style.isCSharp()) { 3359 if (FormatTok->is(tok::semi)) 3360 nextToken(); 3361 addUnwrappedLine(); 3362 return true; 3363 } 3364 return false; 3365 } 3366 3367 namespace { 3368 // A class used to set and restore the Token position when peeking 3369 // ahead in the token source. 3370 class ScopedTokenPosition { 3371 unsigned StoredPosition; 3372 FormatTokenSource *Tokens; 3373 3374 public: 3375 ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) { 3376 assert(Tokens && "Tokens expected to not be null"); 3377 StoredPosition = Tokens->getPosition(); 3378 } 3379 3380 ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); } 3381 }; 3382 } // namespace 3383 3384 // Look to see if we have [[ by looking ahead, if 3385 // its not then rewind to the original position. 3386 bool UnwrappedLineParser::tryToParseSimpleAttribute() { 3387 ScopedTokenPosition AutoPosition(Tokens); 3388 FormatToken *Tok = Tokens->getNextToken(); 3389 // We already read the first [ check for the second. 3390 if (!Tok->is(tok::l_square)) 3391 return false; 3392 // Double check that the attribute is just something 3393 // fairly simple. 3394 while (Tok->isNot(tok::eof)) { 3395 if (Tok->is(tok::r_square)) 3396 break; 3397 Tok = Tokens->getNextToken(); 3398 } 3399 if (Tok->is(tok::eof)) 3400 return false; 3401 Tok = Tokens->getNextToken(); 3402 if (!Tok->is(tok::r_square)) 3403 return false; 3404 Tok = Tokens->getNextToken(); 3405 if (Tok->is(tok::semi)) 3406 return false; 3407 return true; 3408 } 3409 3410 void UnwrappedLineParser::parseJavaEnumBody() { 3411 // Determine whether the enum is simple, i.e. does not have a semicolon or 3412 // constants with class bodies. Simple enums can be formatted like braced 3413 // lists, contracted to a single line, etc. 3414 unsigned StoredPosition = Tokens->getPosition(); 3415 bool IsSimple = true; 3416 FormatToken *Tok = Tokens->getNextToken(); 3417 while (!Tok->is(tok::eof)) { 3418 if (Tok->is(tok::r_brace)) 3419 break; 3420 if (Tok->isOneOf(tok::l_brace, tok::semi)) { 3421 IsSimple = false; 3422 break; 3423 } 3424 // FIXME: This will also mark enums with braces in the arguments to enum 3425 // constants as "not simple". This is probably fine in practice, though. 3426 Tok = Tokens->getNextToken(); 3427 } 3428 FormatTok = Tokens->setPosition(StoredPosition); 3429 3430 if (IsSimple) { 3431 nextToken(); 3432 parseBracedList(); 3433 addUnwrappedLine(); 3434 return; 3435 } 3436 3437 // Parse the body of a more complex enum. 3438 // First add a line for everything up to the "{". 3439 nextToken(); 3440 addUnwrappedLine(); 3441 ++Line->Level; 3442 3443 // Parse the enum constants. 3444 while (FormatTok) { 3445 if (FormatTok->is(tok::l_brace)) { 3446 // Parse the constant's class body. 3447 parseBlock(/*MustBeDeclaration=*/true, /*AddLevels=*/1u, 3448 /*MunchSemi=*/false); 3449 } else if (FormatTok->is(tok::l_paren)) { 3450 parseParens(); 3451 } else if (FormatTok->is(tok::comma)) { 3452 nextToken(); 3453 addUnwrappedLine(); 3454 } else if (FormatTok->is(tok::semi)) { 3455 nextToken(); 3456 addUnwrappedLine(); 3457 break; 3458 } else if (FormatTok->is(tok::r_brace)) { 3459 addUnwrappedLine(); 3460 break; 3461 } else { 3462 nextToken(); 3463 } 3464 } 3465 3466 // Parse the class body after the enum's ";" if any. 3467 parseLevel(/*HasOpeningBrace=*/true, /*CanContainBracedList=*/true); 3468 nextToken(); 3469 --Line->Level; 3470 addUnwrappedLine(); 3471 } 3472 3473 void UnwrappedLineParser::parseRecord(bool ParseAsExpr) { 3474 const FormatToken &InitialToken = *FormatTok; 3475 nextToken(); 3476 3477 // The actual identifier can be a nested name specifier, and in macros 3478 // it is often token-pasted. 3479 // An [[attribute]] can be before the identifier. 3480 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash, 3481 tok::kw___attribute, tok::kw___declspec, 3482 tok::kw_alignas, tok::l_square, tok::r_square) || 3483 ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) && 3484 FormatTok->isOneOf(tok::period, tok::comma))) { 3485 if (Style.isJavaScript() && 3486 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) { 3487 // JavaScript/TypeScript supports inline object types in 3488 // extends/implements positions: 3489 // class Foo implements {bar: number} { } 3490 nextToken(); 3491 if (FormatTok->is(tok::l_brace)) { 3492 tryToParseBracedList(); 3493 continue; 3494 } 3495 } 3496 bool IsNonMacroIdentifier = 3497 FormatTok->is(tok::identifier) && 3498 FormatTok->TokenText != FormatTok->TokenText.upper(); 3499 nextToken(); 3500 // We can have macros or attributes in between 'class' and the class name. 3501 if (!IsNonMacroIdentifier) { 3502 if (FormatTok->is(tok::l_paren)) { 3503 parseParens(); 3504 } else if (FormatTok->is(TT_AttributeSquare)) { 3505 parseSquare(); 3506 // Consume the closing TT_AttributeSquare. 3507 if (FormatTok->Next && FormatTok->is(TT_AttributeSquare)) 3508 nextToken(); 3509 } 3510 } 3511 } 3512 3513 // Note that parsing away template declarations here leads to incorrectly 3514 // accepting function declarations as record declarations. 3515 // In general, we cannot solve this problem. Consider: 3516 // class A<int> B() {} 3517 // which can be a function definition or a class definition when B() is a 3518 // macro. If we find enough real-world cases where this is a problem, we 3519 // can parse for the 'template' keyword in the beginning of the statement, 3520 // and thus rule out the record production in case there is no template 3521 // (this would still leave us with an ambiguity between template function 3522 // and class declarations). 3523 if (FormatTok->isOneOf(tok::colon, tok::less)) { 3524 do { 3525 if (FormatTok->is(tok::l_brace)) { 3526 calculateBraceTypes(/*ExpectClassBody=*/true); 3527 if (!tryToParseBracedList()) 3528 break; 3529 } 3530 if (FormatTok->is(tok::l_square)) { 3531 FormatToken *Previous = FormatTok->Previous; 3532 if (!Previous || 3533 !(Previous->is(tok::r_paren) || Previous->isTypeOrIdentifier())) { 3534 // Don't try parsing a lambda if we had a closing parenthesis before, 3535 // it was probably a pointer to an array: int (*)[]. 3536 if (!tryToParseLambda()) 3537 continue; 3538 } else { 3539 parseSquare(); 3540 continue; 3541 } 3542 } 3543 if (FormatTok->is(tok::semi)) 3544 return; 3545 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) { 3546 addUnwrappedLine(); 3547 nextToken(); 3548 parseCSharpGenericTypeConstraint(); 3549 break; 3550 } 3551 nextToken(); 3552 } while (!eof()); 3553 } 3554 3555 auto GetBraceType = [](const FormatToken &RecordTok) { 3556 switch (RecordTok.Tok.getKind()) { 3557 case tok::kw_class: 3558 return TT_ClassLBrace; 3559 case tok::kw_struct: 3560 return TT_StructLBrace; 3561 case tok::kw_union: 3562 return TT_UnionLBrace; 3563 default: 3564 // Useful for e.g. interface. 3565 return TT_RecordLBrace; 3566 } 3567 }; 3568 if (FormatTok->is(tok::l_brace)) { 3569 FormatTok->setFinalizedType(GetBraceType(InitialToken)); 3570 if (ParseAsExpr) { 3571 parseChildBlock(); 3572 } else { 3573 if (ShouldBreakBeforeBrace(Style, InitialToken)) 3574 addUnwrappedLine(); 3575 3576 unsigned AddLevels = Style.IndentAccessModifiers ? 2u : 1u; 3577 parseBlock(/*MustBeDeclaration=*/true, AddLevels, /*MunchSemi=*/false); 3578 } 3579 } 3580 // There is no addUnwrappedLine() here so that we fall through to parsing a 3581 // structural element afterwards. Thus, in "class A {} n, m;", 3582 // "} n, m;" will end up in one unwrapped line. 3583 } 3584 3585 void UnwrappedLineParser::parseObjCMethod() { 3586 assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) && 3587 "'(' or identifier expected."); 3588 do { 3589 if (FormatTok->is(tok::semi)) { 3590 nextToken(); 3591 addUnwrappedLine(); 3592 return; 3593 } else if (FormatTok->is(tok::l_brace)) { 3594 if (Style.BraceWrapping.AfterFunction) 3595 addUnwrappedLine(); 3596 parseBlock(); 3597 addUnwrappedLine(); 3598 return; 3599 } else { 3600 nextToken(); 3601 } 3602 } while (!eof()); 3603 } 3604 3605 void UnwrappedLineParser::parseObjCProtocolList() { 3606 assert(FormatTok->is(tok::less) && "'<' expected."); 3607 do { 3608 nextToken(); 3609 // Early exit in case someone forgot a close angle. 3610 if (FormatTok->isOneOf(tok::semi, tok::l_brace) || 3611 FormatTok->isObjCAtKeyword(tok::objc_end)) 3612 return; 3613 } while (!eof() && FormatTok->isNot(tok::greater)); 3614 nextToken(); // Skip '>'. 3615 } 3616 3617 void UnwrappedLineParser::parseObjCUntilAtEnd() { 3618 do { 3619 if (FormatTok->isObjCAtKeyword(tok::objc_end)) { 3620 nextToken(); 3621 addUnwrappedLine(); 3622 break; 3623 } 3624 if (FormatTok->is(tok::l_brace)) { 3625 parseBlock(); 3626 // In ObjC interfaces, nothing should be following the "}". 3627 addUnwrappedLine(); 3628 } else if (FormatTok->is(tok::r_brace)) { 3629 // Ignore stray "}". parseStructuralElement doesn't consume them. 3630 nextToken(); 3631 addUnwrappedLine(); 3632 } else if (FormatTok->isOneOf(tok::minus, tok::plus)) { 3633 nextToken(); 3634 parseObjCMethod(); 3635 } else { 3636 parseStructuralElement(); 3637 } 3638 } while (!eof()); 3639 } 3640 3641 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() { 3642 assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_interface || 3643 FormatTok->Tok.getObjCKeywordID() == tok::objc_implementation); 3644 nextToken(); 3645 nextToken(); // interface name 3646 3647 // @interface can be followed by a lightweight generic 3648 // specialization list, then either a base class or a category. 3649 if (FormatTok->is(tok::less)) 3650 parseObjCLightweightGenerics(); 3651 if (FormatTok->is(tok::colon)) { 3652 nextToken(); 3653 nextToken(); // base class name 3654 // The base class can also have lightweight generics applied to it. 3655 if (FormatTok->is(tok::less)) 3656 parseObjCLightweightGenerics(); 3657 } else if (FormatTok->is(tok::l_paren)) 3658 // Skip category, if present. 3659 parseParens(); 3660 3661 if (FormatTok->is(tok::less)) 3662 parseObjCProtocolList(); 3663 3664 if (FormatTok->is(tok::l_brace)) { 3665 if (Style.BraceWrapping.AfterObjCDeclaration) 3666 addUnwrappedLine(); 3667 parseBlock(/*MustBeDeclaration=*/true); 3668 } 3669 3670 // With instance variables, this puts '}' on its own line. Without instance 3671 // variables, this ends the @interface line. 3672 addUnwrappedLine(); 3673 3674 parseObjCUntilAtEnd(); 3675 } 3676 3677 void UnwrappedLineParser::parseObjCLightweightGenerics() { 3678 assert(FormatTok->is(tok::less)); 3679 // Unlike protocol lists, generic parameterizations support 3680 // nested angles: 3681 // 3682 // @interface Foo<ValueType : id <NSCopying, NSSecureCoding>> : 3683 // NSObject <NSCopying, NSSecureCoding> 3684 // 3685 // so we need to count how many open angles we have left. 3686 unsigned NumOpenAngles = 1; 3687 do { 3688 nextToken(); 3689 // Early exit in case someone forgot a close angle. 3690 if (FormatTok->isOneOf(tok::semi, tok::l_brace) || 3691 FormatTok->isObjCAtKeyword(tok::objc_end)) 3692 break; 3693 if (FormatTok->is(tok::less)) 3694 ++NumOpenAngles; 3695 else if (FormatTok->is(tok::greater)) { 3696 assert(NumOpenAngles > 0 && "'>' makes NumOpenAngles negative"); 3697 --NumOpenAngles; 3698 } 3699 } while (!eof() && NumOpenAngles != 0); 3700 nextToken(); // Skip '>'. 3701 } 3702 3703 // Returns true for the declaration/definition form of @protocol, 3704 // false for the expression form. 3705 bool UnwrappedLineParser::parseObjCProtocol() { 3706 assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_protocol); 3707 nextToken(); 3708 3709 if (FormatTok->is(tok::l_paren)) 3710 // The expression form of @protocol, e.g. "Protocol* p = @protocol(foo);". 3711 return false; 3712 3713 // The definition/declaration form, 3714 // @protocol Foo 3715 // - (int)someMethod; 3716 // @end 3717 3718 nextToken(); // protocol name 3719 3720 if (FormatTok->is(tok::less)) 3721 parseObjCProtocolList(); 3722 3723 // Check for protocol declaration. 3724 if (FormatTok->is(tok::semi)) { 3725 nextToken(); 3726 addUnwrappedLine(); 3727 return true; 3728 } 3729 3730 addUnwrappedLine(); 3731 parseObjCUntilAtEnd(); 3732 return true; 3733 } 3734 3735 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() { 3736 bool IsImport = FormatTok->is(Keywords.kw_import); 3737 assert(IsImport || FormatTok->is(tok::kw_export)); 3738 nextToken(); 3739 3740 // Consume the "default" in "export default class/function". 3741 if (FormatTok->is(tok::kw_default)) 3742 nextToken(); 3743 3744 // Consume "async function", "function" and "default function", so that these 3745 // get parsed as free-standing JS functions, i.e. do not require a trailing 3746 // semicolon. 3747 if (FormatTok->is(Keywords.kw_async)) 3748 nextToken(); 3749 if (FormatTok->is(Keywords.kw_function)) { 3750 nextToken(); 3751 return; 3752 } 3753 3754 // For imports, `export *`, `export {...}`, consume the rest of the line up 3755 // to the terminating `;`. For everything else, just return and continue 3756 // parsing the structural element, i.e. the declaration or expression for 3757 // `export default`. 3758 if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) && 3759 !FormatTok->isStringLiteral()) 3760 return; 3761 3762 while (!eof()) { 3763 if (FormatTok->is(tok::semi)) 3764 return; 3765 if (Line->Tokens.empty()) { 3766 // Common issue: Automatic Semicolon Insertion wrapped the line, so the 3767 // import statement should terminate. 3768 return; 3769 } 3770 if (FormatTok->is(tok::l_brace)) { 3771 FormatTok->setBlockKind(BK_Block); 3772 nextToken(); 3773 parseBracedList(); 3774 } else { 3775 nextToken(); 3776 } 3777 } 3778 } 3779 3780 void UnwrappedLineParser::parseStatementMacro() { 3781 nextToken(); 3782 if (FormatTok->is(tok::l_paren)) 3783 parseParens(); 3784 if (FormatTok->is(tok::semi)) 3785 nextToken(); 3786 addUnwrappedLine(); 3787 } 3788 3789 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line, 3790 StringRef Prefix = "") { 3791 llvm::dbgs() << Prefix << "Line(" << Line.Level 3792 << ", FSC=" << Line.FirstStartColumn << ")" 3793 << (Line.InPPDirective ? " MACRO" : "") << ": "; 3794 for (const auto &Node : Line.Tokens) { 3795 llvm::dbgs() << Node.Tok->Tok.getName() << "[" 3796 << "T=" << static_cast<unsigned>(Node.Tok->getType()) 3797 << ", OC=" << Node.Tok->OriginalColumn << "] "; 3798 } 3799 for (const auto &Node : Line.Tokens) 3800 for (const auto &ChildNode : Node.Children) 3801 printDebugInfo(ChildNode, "\nChild: "); 3802 3803 llvm::dbgs() << "\n"; 3804 } 3805 3806 void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) { 3807 if (Line->Tokens.empty()) 3808 return; 3809 LLVM_DEBUG({ 3810 if (CurrentLines == &Lines) 3811 printDebugInfo(*Line); 3812 }); 3813 3814 // If this line closes a block when in Whitesmiths mode, remember that 3815 // information so that the level can be decreased after the line is added. 3816 // This has to happen after the addition of the line since the line itself 3817 // needs to be indented. 3818 bool ClosesWhitesmithsBlock = 3819 Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex && 3820 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths; 3821 3822 CurrentLines->push_back(std::move(*Line)); 3823 Line->Tokens.clear(); 3824 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex; 3825 Line->FirstStartColumn = 0; 3826 3827 if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove) 3828 --Line->Level; 3829 if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) { 3830 CurrentLines->append( 3831 std::make_move_iterator(PreprocessorDirectives.begin()), 3832 std::make_move_iterator(PreprocessorDirectives.end())); 3833 PreprocessorDirectives.clear(); 3834 } 3835 // Disconnect the current token from the last token on the previous line. 3836 FormatTok->Previous = nullptr; 3837 } 3838 3839 bool UnwrappedLineParser::eof() const { return FormatTok->is(tok::eof); } 3840 3841 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) { 3842 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) && 3843 FormatTok.NewlinesBefore > 0; 3844 } 3845 3846 // Checks if \p FormatTok is a line comment that continues the line comment 3847 // section on \p Line. 3848 static bool 3849 continuesLineCommentSection(const FormatToken &FormatTok, 3850 const UnwrappedLine &Line, 3851 const llvm::Regex &CommentPragmasRegex) { 3852 if (Line.Tokens.empty()) 3853 return false; 3854 3855 StringRef IndentContent = FormatTok.TokenText; 3856 if (FormatTok.TokenText.startswith("//") || 3857 FormatTok.TokenText.startswith("/*")) 3858 IndentContent = FormatTok.TokenText.substr(2); 3859 if (CommentPragmasRegex.match(IndentContent)) 3860 return false; 3861 3862 // If Line starts with a line comment, then FormatTok continues the comment 3863 // section if its original column is greater or equal to the original start 3864 // column of the line. 3865 // 3866 // Define the min column token of a line as follows: if a line ends in '{' or 3867 // contains a '{' followed by a line comment, then the min column token is 3868 // that '{'. Otherwise, the min column token of the line is the first token of 3869 // the line. 3870 // 3871 // If Line starts with a token other than a line comment, then FormatTok 3872 // continues the comment section if its original column is greater than the 3873 // original start column of the min column token of the line. 3874 // 3875 // For example, the second line comment continues the first in these cases: 3876 // 3877 // // first line 3878 // // second line 3879 // 3880 // and: 3881 // 3882 // // first line 3883 // // second line 3884 // 3885 // and: 3886 // 3887 // int i; // first line 3888 // // second line 3889 // 3890 // and: 3891 // 3892 // do { // first line 3893 // // second line 3894 // int i; 3895 // } while (true); 3896 // 3897 // and: 3898 // 3899 // enum { 3900 // a, // first line 3901 // // second line 3902 // b 3903 // }; 3904 // 3905 // The second line comment doesn't continue the first in these cases: 3906 // 3907 // // first line 3908 // // second line 3909 // 3910 // and: 3911 // 3912 // int i; // first line 3913 // // second line 3914 // 3915 // and: 3916 // 3917 // do { // first line 3918 // // second line 3919 // int i; 3920 // } while (true); 3921 // 3922 // and: 3923 // 3924 // enum { 3925 // a, // first line 3926 // // second line 3927 // }; 3928 const FormatToken *MinColumnToken = Line.Tokens.front().Tok; 3929 3930 // Scan for '{//'. If found, use the column of '{' as a min column for line 3931 // comment section continuation. 3932 const FormatToken *PreviousToken = nullptr; 3933 for (const UnwrappedLineNode &Node : Line.Tokens) { 3934 if (PreviousToken && PreviousToken->is(tok::l_brace) && 3935 isLineComment(*Node.Tok)) { 3936 MinColumnToken = PreviousToken; 3937 break; 3938 } 3939 PreviousToken = Node.Tok; 3940 3941 // Grab the last newline preceding a token in this unwrapped line. 3942 if (Node.Tok->NewlinesBefore > 0) 3943 MinColumnToken = Node.Tok; 3944 } 3945 if (PreviousToken && PreviousToken->is(tok::l_brace)) 3946 MinColumnToken = PreviousToken; 3947 3948 return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok, 3949 MinColumnToken); 3950 } 3951 3952 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) { 3953 bool JustComments = Line->Tokens.empty(); 3954 for (FormatToken *Tok : CommentsBeforeNextToken) { 3955 // Line comments that belong to the same line comment section are put on the 3956 // same line since later we might want to reflow content between them. 3957 // Additional fine-grained breaking of line comment sections is controlled 3958 // by the class BreakableLineCommentSection in case it is desirable to keep 3959 // several line comment sections in the same unwrapped line. 3960 // 3961 // FIXME: Consider putting separate line comment sections as children to the 3962 // unwrapped line instead. 3963 Tok->ContinuesLineCommentSection = 3964 continuesLineCommentSection(*Tok, *Line, CommentPragmasRegex); 3965 if (isOnNewLine(*Tok) && JustComments && !Tok->ContinuesLineCommentSection) 3966 addUnwrappedLine(); 3967 pushToken(Tok); 3968 } 3969 if (NewlineBeforeNext && JustComments) 3970 addUnwrappedLine(); 3971 CommentsBeforeNextToken.clear(); 3972 } 3973 3974 void UnwrappedLineParser::nextToken(int LevelDifference) { 3975 if (eof()) 3976 return; 3977 flushComments(isOnNewLine(*FormatTok)); 3978 pushToken(FormatTok); 3979 FormatToken *Previous = FormatTok; 3980 if (!Style.isJavaScript()) 3981 readToken(LevelDifference); 3982 else 3983 readTokenWithJavaScriptASI(); 3984 FormatTok->Previous = Previous; 3985 } 3986 3987 void UnwrappedLineParser::distributeComments( 3988 const SmallVectorImpl<FormatToken *> &Comments, 3989 const FormatToken *NextTok) { 3990 // Whether or not a line comment token continues a line is controlled by 3991 // the method continuesLineCommentSection, with the following caveat: 3992 // 3993 // Define a trail of Comments to be a nonempty proper postfix of Comments such 3994 // that each comment line from the trail is aligned with the next token, if 3995 // the next token exists. If a trail exists, the beginning of the maximal 3996 // trail is marked as a start of a new comment section. 3997 // 3998 // For example in this code: 3999 // 4000 // int a; // line about a 4001 // // line 1 about b 4002 // // line 2 about b 4003 // int b; 4004 // 4005 // the two lines about b form a maximal trail, so there are two sections, the 4006 // first one consisting of the single comment "// line about a" and the 4007 // second one consisting of the next two comments. 4008 if (Comments.empty()) 4009 return; 4010 bool ShouldPushCommentsInCurrentLine = true; 4011 bool HasTrailAlignedWithNextToken = false; 4012 unsigned StartOfTrailAlignedWithNextToken = 0; 4013 if (NextTok) { 4014 // We are skipping the first element intentionally. 4015 for (unsigned i = Comments.size() - 1; i > 0; --i) { 4016 if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) { 4017 HasTrailAlignedWithNextToken = true; 4018 StartOfTrailAlignedWithNextToken = i; 4019 } 4020 } 4021 } 4022 for (unsigned i = 0, e = Comments.size(); i < e; ++i) { 4023 FormatToken *FormatTok = Comments[i]; 4024 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) { 4025 FormatTok->ContinuesLineCommentSection = false; 4026 } else { 4027 FormatTok->ContinuesLineCommentSection = 4028 continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex); 4029 } 4030 if (!FormatTok->ContinuesLineCommentSection && 4031 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) 4032 ShouldPushCommentsInCurrentLine = false; 4033 if (ShouldPushCommentsInCurrentLine) 4034 pushToken(FormatTok); 4035 else 4036 CommentsBeforeNextToken.push_back(FormatTok); 4037 } 4038 } 4039 4040 void UnwrappedLineParser::readToken(int LevelDifference) { 4041 SmallVector<FormatToken *, 1> Comments; 4042 bool PreviousWasComment = false; 4043 bool FirstNonCommentOnLine = false; 4044 do { 4045 FormatTok = Tokens->getNextToken(); 4046 assert(FormatTok); 4047 while (FormatTok->getType() == TT_ConflictStart || 4048 FormatTok->getType() == TT_ConflictEnd || 4049 FormatTok->getType() == TT_ConflictAlternative) { 4050 if (FormatTok->getType() == TT_ConflictStart) 4051 conditionalCompilationStart(/*Unreachable=*/false); 4052 else if (FormatTok->getType() == TT_ConflictAlternative) 4053 conditionalCompilationAlternative(); 4054 else if (FormatTok->getType() == TT_ConflictEnd) 4055 conditionalCompilationEnd(); 4056 FormatTok = Tokens->getNextToken(); 4057 FormatTok->MustBreakBefore = true; 4058 } 4059 4060 auto IsFirstNonCommentOnLine = [](bool FirstNonCommentOnLine, 4061 const FormatToken &Tok, 4062 bool PreviousWasComment) { 4063 auto IsFirstOnLine = [](const FormatToken &Tok) { 4064 return Tok.HasUnescapedNewline || Tok.IsFirst; 4065 }; 4066 4067 // Consider preprocessor directives preceded by block comments as first 4068 // on line. 4069 if (PreviousWasComment) 4070 return FirstNonCommentOnLine || IsFirstOnLine(Tok); 4071 return IsFirstOnLine(Tok); 4072 }; 4073 4074 FirstNonCommentOnLine = IsFirstNonCommentOnLine( 4075 FirstNonCommentOnLine, *FormatTok, PreviousWasComment); 4076 PreviousWasComment = FormatTok->is(tok::comment); 4077 4078 while (!Line->InPPDirective && FormatTok->is(tok::hash) && 4079 FirstNonCommentOnLine) { 4080 distributeComments(Comments, FormatTok); 4081 Comments.clear(); 4082 // If there is an unfinished unwrapped line, we flush the preprocessor 4083 // directives only after that unwrapped line was finished later. 4084 bool SwitchToPreprocessorLines = !Line->Tokens.empty(); 4085 ScopedLineState BlockState(*this, SwitchToPreprocessorLines); 4086 assert((LevelDifference >= 0 || 4087 static_cast<unsigned>(-LevelDifference) <= Line->Level) && 4088 "LevelDifference makes Line->Level negative"); 4089 Line->Level += LevelDifference; 4090 // Comments stored before the preprocessor directive need to be output 4091 // before the preprocessor directive, at the same level as the 4092 // preprocessor directive, as we consider them to apply to the directive. 4093 if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash && 4094 PPBranchLevel > 0) 4095 Line->Level += PPBranchLevel; 4096 flushComments(isOnNewLine(*FormatTok)); 4097 parsePPDirective(); 4098 PreviousWasComment = FormatTok->is(tok::comment); 4099 FirstNonCommentOnLine = IsFirstNonCommentOnLine( 4100 FirstNonCommentOnLine, *FormatTok, PreviousWasComment); 4101 } 4102 4103 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) && 4104 !Line->InPPDirective) 4105 continue; 4106 4107 if (!FormatTok->is(tok::comment)) { 4108 distributeComments(Comments, FormatTok); 4109 Comments.clear(); 4110 return; 4111 } 4112 4113 Comments.push_back(FormatTok); 4114 } while (!eof()); 4115 4116 distributeComments(Comments, nullptr); 4117 Comments.clear(); 4118 } 4119 4120 void UnwrappedLineParser::pushToken(FormatToken *Tok) { 4121 Line->Tokens.push_back(UnwrappedLineNode(Tok)); 4122 if (MustBreakBeforeNextToken) { 4123 Line->Tokens.back().Tok->MustBreakBefore = true; 4124 MustBreakBeforeNextToken = false; 4125 } 4126 } 4127 4128 } // end namespace format 4129 } // end namespace clang 4130