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