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