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