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