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