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