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