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