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. They always start an expression or a child block if 1486 // followed by a curly brace. 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 parseAssignmentExpression() inside. 1794 do { 1795 if (Style.isCSharp()) { 1796 // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType 1797 // TT_FatArrow. They always start an expression or a child block if 1798 // followed by a curly brace. 1799 if (FormatTok->is(TT_FatArrow)) { 1800 nextToken(); 1801 if (FormatTok->is(tok::l_brace)) { 1802 // C# may break after => if the next character is a newline. 1803 if (Style.isCSharp() && Style.BraceWrapping.AfterFunction == true) { 1804 // calling `addUnwrappedLine()` here causes odd parsing errors. 1805 FormatTok->MustBreakBefore = true; 1806 } 1807 parseChildBlock(); 1808 continue; 1809 } 1810 } 1811 } 1812 if (Style.Language == FormatStyle::LK_JavaScript) { 1813 if (FormatTok->is(Keywords.kw_function) || 1814 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) { 1815 tryToParseJSFunction(); 1816 continue; 1817 } 1818 if (FormatTok->is(TT_FatArrow)) { 1819 nextToken(); 1820 // Fat arrows can be followed by simple expressions or by child blocks 1821 // in curly braces. 1822 if (FormatTok->is(tok::l_brace)) { 1823 parseChildBlock(); 1824 continue; 1825 } 1826 } 1827 if (FormatTok->is(tok::l_brace)) { 1828 // Could be a method inside of a braced list `{a() { return 1; }}`. 1829 if (tryToParseBracedList()) 1830 continue; 1831 parseChildBlock(); 1832 } 1833 } 1834 if (FormatTok->Tok.getKind() == ClosingBraceKind) { 1835 if (IsEnum && !Style.AllowShortEnumsOnASingleLine) 1836 addUnwrappedLine(); 1837 nextToken(); 1838 return !HasError; 1839 } 1840 switch (FormatTok->Tok.getKind()) { 1841 case tok::caret: 1842 nextToken(); 1843 if (FormatTok->is(tok::l_brace)) { 1844 parseChildBlock(); 1845 } 1846 break; 1847 case tok::l_square: 1848 if (Style.isCSharp()) 1849 parseSquare(); 1850 else 1851 tryToParseLambda(); 1852 break; 1853 case tok::l_paren: 1854 parseParens(); 1855 // JavaScript can just have free standing methods and getters/setters in 1856 // object literals. Detect them by a "{" following ")". 1857 if (Style.Language == FormatStyle::LK_JavaScript) { 1858 if (FormatTok->is(tok::l_brace)) 1859 parseChildBlock(); 1860 break; 1861 } 1862 break; 1863 case tok::l_brace: 1864 // Assume there are no blocks inside a braced init list apart 1865 // from the ones we explicitly parse out (like lambdas). 1866 FormatTok->setBlockKind(BK_BracedInit); 1867 nextToken(); 1868 parseBracedList(); 1869 break; 1870 case tok::less: 1871 if (Style.Language == FormatStyle::LK_Proto) { 1872 nextToken(); 1873 parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false, 1874 /*ClosingBraceKind=*/tok::greater); 1875 } else { 1876 nextToken(); 1877 } 1878 break; 1879 case tok::semi: 1880 // JavaScript (or more precisely TypeScript) can have semicolons in braced 1881 // lists (in so-called TypeMemberLists). Thus, the semicolon cannot be 1882 // used for error recovery if we have otherwise determined that this is 1883 // a braced list. 1884 if (Style.Language == FormatStyle::LK_JavaScript) { 1885 nextToken(); 1886 break; 1887 } 1888 HasError = true; 1889 if (!ContinueOnSemicolons) 1890 return !HasError; 1891 nextToken(); 1892 break; 1893 case tok::comma: 1894 nextToken(); 1895 if (IsEnum && !Style.AllowShortEnumsOnASingleLine) 1896 addUnwrappedLine(); 1897 break; 1898 default: 1899 nextToken(); 1900 break; 1901 } 1902 } while (!eof()); 1903 return false; 1904 } 1905 1906 void UnwrappedLineParser::parseParens() { 1907 assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected."); 1908 nextToken(); 1909 do { 1910 switch (FormatTok->Tok.getKind()) { 1911 case tok::l_paren: 1912 parseParens(); 1913 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace)) 1914 parseChildBlock(); 1915 break; 1916 case tok::r_paren: 1917 nextToken(); 1918 return; 1919 case tok::r_brace: 1920 // A "}" inside parenthesis is an error if there wasn't a matching "{". 1921 return; 1922 case tok::l_square: 1923 tryToParseLambda(); 1924 break; 1925 case tok::l_brace: 1926 if (!tryToParseBracedList()) 1927 parseChildBlock(); 1928 break; 1929 case tok::at: 1930 nextToken(); 1931 if (FormatTok->Tok.is(tok::l_brace)) { 1932 nextToken(); 1933 parseBracedList(); 1934 } 1935 break; 1936 case tok::equal: 1937 if (Style.isCSharp() && FormatTok->is(TT_FatArrow)) 1938 parseStructuralElement(); 1939 else 1940 nextToken(); 1941 break; 1942 case tok::kw_class: 1943 if (Style.Language == FormatStyle::LK_JavaScript) 1944 parseRecord(/*ParseAsExpr=*/true); 1945 else 1946 nextToken(); 1947 break; 1948 case tok::identifier: 1949 if (Style.Language == FormatStyle::LK_JavaScript && 1950 (FormatTok->is(Keywords.kw_function) || 1951 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function))) 1952 tryToParseJSFunction(); 1953 else 1954 nextToken(); 1955 break; 1956 default: 1957 nextToken(); 1958 break; 1959 } 1960 } while (!eof()); 1961 } 1962 1963 void UnwrappedLineParser::parseSquare(bool LambdaIntroducer) { 1964 if (!LambdaIntroducer) { 1965 assert(FormatTok->Tok.is(tok::l_square) && "'[' expected."); 1966 if (tryToParseLambda()) 1967 return; 1968 } 1969 do { 1970 switch (FormatTok->Tok.getKind()) { 1971 case tok::l_paren: 1972 parseParens(); 1973 break; 1974 case tok::r_square: 1975 nextToken(); 1976 return; 1977 case tok::r_brace: 1978 // A "}" inside parenthesis is an error if there wasn't a matching "{". 1979 return; 1980 case tok::l_square: 1981 parseSquare(); 1982 break; 1983 case tok::l_brace: { 1984 if (!tryToParseBracedList()) 1985 parseChildBlock(); 1986 break; 1987 } 1988 case tok::at: 1989 nextToken(); 1990 if (FormatTok->Tok.is(tok::l_brace)) { 1991 nextToken(); 1992 parseBracedList(); 1993 } 1994 break; 1995 default: 1996 nextToken(); 1997 break; 1998 } 1999 } while (!eof()); 2000 } 2001 2002 void UnwrappedLineParser::parseIfThenElse() { 2003 assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected"); 2004 nextToken(); 2005 if (FormatTok->Tok.isOneOf(tok::kw_constexpr, tok::identifier)) 2006 nextToken(); 2007 if (FormatTok->Tok.is(tok::l_paren)) 2008 parseParens(); 2009 // handle [[likely]] / [[unlikely]] 2010 if (FormatTok->is(tok::l_square) && tryToParseSimpleAttribute()) 2011 parseSquare(); 2012 bool NeedsUnwrappedLine = false; 2013 if (FormatTok->Tok.is(tok::l_brace)) { 2014 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2015 parseBlock(/*MustBeDeclaration=*/false); 2016 if (Style.BraceWrapping.BeforeElse) 2017 addUnwrappedLine(); 2018 else 2019 NeedsUnwrappedLine = true; 2020 } else { 2021 addUnwrappedLine(); 2022 ++Line->Level; 2023 parseStructuralElement(); 2024 --Line->Level; 2025 } 2026 if (FormatTok->Tok.is(tok::kw_else)) { 2027 nextToken(); 2028 // handle [[likely]] / [[unlikely]] 2029 if (FormatTok->Tok.is(tok::l_square) && tryToParseSimpleAttribute()) 2030 parseSquare(); 2031 if (FormatTok->Tok.is(tok::l_brace)) { 2032 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2033 parseBlock(/*MustBeDeclaration=*/false); 2034 addUnwrappedLine(); 2035 } else if (FormatTok->Tok.is(tok::kw_if)) { 2036 FormatToken *Previous = AllTokens[Tokens->getPosition() - 1]; 2037 bool PrecededByComment = Previous->is(tok::comment); 2038 if (PrecededByComment) { 2039 addUnwrappedLine(); 2040 ++Line->Level; 2041 } 2042 parseIfThenElse(); 2043 if (PrecededByComment) 2044 --Line->Level; 2045 } else { 2046 addUnwrappedLine(); 2047 ++Line->Level; 2048 parseStructuralElement(); 2049 if (FormatTok->is(tok::eof)) 2050 addUnwrappedLine(); 2051 --Line->Level; 2052 } 2053 } else if (NeedsUnwrappedLine) { 2054 addUnwrappedLine(); 2055 } 2056 } 2057 2058 void UnwrappedLineParser::parseTryCatch() { 2059 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected"); 2060 nextToken(); 2061 bool NeedsUnwrappedLine = false; 2062 if (FormatTok->is(tok::colon)) { 2063 // We are in a function try block, what comes is an initializer list. 2064 nextToken(); 2065 2066 // In case identifiers were removed by clang-tidy, what might follow is 2067 // multiple commas in sequence - before the first identifier. 2068 while (FormatTok->is(tok::comma)) 2069 nextToken(); 2070 2071 while (FormatTok->is(tok::identifier)) { 2072 nextToken(); 2073 if (FormatTok->is(tok::l_paren)) 2074 parseParens(); 2075 if (FormatTok->Previous && FormatTok->Previous->is(tok::identifier) && 2076 FormatTok->is(tok::l_brace)) { 2077 do { 2078 nextToken(); 2079 } while (!FormatTok->is(tok::r_brace)); 2080 nextToken(); 2081 } 2082 2083 // In case identifiers were removed by clang-tidy, what might follow is 2084 // multiple commas in sequence - after the first identifier. 2085 while (FormatTok->is(tok::comma)) 2086 nextToken(); 2087 } 2088 } 2089 // Parse try with resource. 2090 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) { 2091 parseParens(); 2092 } 2093 if (FormatTok->is(tok::l_brace)) { 2094 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2095 parseBlock(/*MustBeDeclaration=*/false); 2096 if (Style.BraceWrapping.BeforeCatch) { 2097 addUnwrappedLine(); 2098 } else { 2099 NeedsUnwrappedLine = true; 2100 } 2101 } else if (!FormatTok->is(tok::kw_catch)) { 2102 // The C++ standard requires a compound-statement after a try. 2103 // If there's none, we try to assume there's a structuralElement 2104 // and try to continue. 2105 addUnwrappedLine(); 2106 ++Line->Level; 2107 parseStructuralElement(); 2108 --Line->Level; 2109 } 2110 while (1) { 2111 if (FormatTok->is(tok::at)) 2112 nextToken(); 2113 if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except, 2114 tok::kw___finally) || 2115 ((Style.Language == FormatStyle::LK_Java || 2116 Style.Language == FormatStyle::LK_JavaScript) && 2117 FormatTok->is(Keywords.kw_finally)) || 2118 (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) || 2119 FormatTok->Tok.isObjCAtKeyword(tok::objc_finally)))) 2120 break; 2121 nextToken(); 2122 while (FormatTok->isNot(tok::l_brace)) { 2123 if (FormatTok->is(tok::l_paren)) { 2124 parseParens(); 2125 continue; 2126 } 2127 if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof)) 2128 return; 2129 nextToken(); 2130 } 2131 NeedsUnwrappedLine = false; 2132 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2133 parseBlock(/*MustBeDeclaration=*/false); 2134 if (Style.BraceWrapping.BeforeCatch) 2135 addUnwrappedLine(); 2136 else 2137 NeedsUnwrappedLine = true; 2138 } 2139 if (NeedsUnwrappedLine) 2140 addUnwrappedLine(); 2141 } 2142 2143 void UnwrappedLineParser::parseNamespace() { 2144 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) && 2145 "'namespace' expected"); 2146 2147 const FormatToken &InitialToken = *FormatTok; 2148 nextToken(); 2149 if (InitialToken.is(TT_NamespaceMacro)) { 2150 parseParens(); 2151 } else { 2152 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline, 2153 tok::l_square)) { 2154 if (FormatTok->is(tok::l_square)) 2155 parseSquare(); 2156 else 2157 nextToken(); 2158 } 2159 } 2160 if (FormatTok->Tok.is(tok::l_brace)) { 2161 if (ShouldBreakBeforeBrace(Style, InitialToken)) 2162 addUnwrappedLine(); 2163 2164 unsigned AddLevels = 2165 Style.NamespaceIndentation == FormatStyle::NI_All || 2166 (Style.NamespaceIndentation == FormatStyle::NI_Inner && 2167 DeclarationScopeStack.size() > 1) 2168 ? 1u 2169 : 0u; 2170 bool ManageWhitesmithsBraces = 2171 AddLevels == 0u && 2172 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths; 2173 2174 // If we're in Whitesmiths mode, indent the brace if we're not indenting 2175 // the whole block. 2176 if (ManageWhitesmithsBraces) 2177 ++Line->Level; 2178 2179 parseBlock(/*MustBeDeclaration=*/true, AddLevels, 2180 /*MunchSemi=*/true, 2181 /*UnindentWhitesmithsBraces=*/ManageWhitesmithsBraces); 2182 2183 // Munch the semicolon after a namespace. This is more common than one would 2184 // think. Putting the semicolon into its own line is very ugly. 2185 if (FormatTok->Tok.is(tok::semi)) 2186 nextToken(); 2187 2188 addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep); 2189 2190 if (ManageWhitesmithsBraces) 2191 --Line->Level; 2192 } 2193 // FIXME: Add error handling. 2194 } 2195 2196 void UnwrappedLineParser::parseNew() { 2197 assert(FormatTok->is(tok::kw_new) && "'new' expected"); 2198 nextToken(); 2199 2200 if (Style.isCSharp()) { 2201 do { 2202 if (FormatTok->is(tok::l_brace)) 2203 parseBracedList(); 2204 2205 if (FormatTok->isOneOf(tok::semi, tok::comma)) 2206 return; 2207 2208 nextToken(); 2209 } while (!eof()); 2210 } 2211 2212 if (Style.Language != FormatStyle::LK_Java) 2213 return; 2214 2215 // In Java, we can parse everything up to the parens, which aren't optional. 2216 do { 2217 // There should not be a ;, { or } before the new's open paren. 2218 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace)) 2219 return; 2220 2221 // Consume the parens. 2222 if (FormatTok->is(tok::l_paren)) { 2223 parseParens(); 2224 2225 // If there is a class body of an anonymous class, consume that as child. 2226 if (FormatTok->is(tok::l_brace)) 2227 parseChildBlock(); 2228 return; 2229 } 2230 nextToken(); 2231 } while (!eof()); 2232 } 2233 2234 void UnwrappedLineParser::parseForOrWhileLoop() { 2235 assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) && 2236 "'for', 'while' or foreach macro expected"); 2237 nextToken(); 2238 // JS' for await ( ... 2239 if (Style.Language == FormatStyle::LK_JavaScript && 2240 FormatTok->is(Keywords.kw_await)) 2241 nextToken(); 2242 if (FormatTok->Tok.is(tok::l_paren)) 2243 parseParens(); 2244 if (FormatTok->Tok.is(tok::l_brace)) { 2245 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2246 parseBlock(/*MustBeDeclaration=*/false); 2247 addUnwrappedLine(); 2248 } else { 2249 addUnwrappedLine(); 2250 ++Line->Level; 2251 parseStructuralElement(); 2252 --Line->Level; 2253 } 2254 } 2255 2256 void UnwrappedLineParser::parseDoWhile() { 2257 assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected"); 2258 nextToken(); 2259 if (FormatTok->Tok.is(tok::l_brace)) { 2260 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2261 parseBlock(/*MustBeDeclaration=*/false); 2262 if (Style.BraceWrapping.BeforeWhile) 2263 addUnwrappedLine(); 2264 } else { 2265 addUnwrappedLine(); 2266 ++Line->Level; 2267 parseStructuralElement(); 2268 --Line->Level; 2269 } 2270 2271 // FIXME: Add error handling. 2272 if (!FormatTok->Tok.is(tok::kw_while)) { 2273 addUnwrappedLine(); 2274 return; 2275 } 2276 2277 // If in Whitesmiths mode, the line with the while() needs to be indented 2278 // to the same level as the block. 2279 if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) 2280 ++Line->Level; 2281 2282 nextToken(); 2283 parseStructuralElement(); 2284 } 2285 2286 void UnwrappedLineParser::parseLabel(bool LeftAlignLabel) { 2287 nextToken(); 2288 unsigned OldLineLevel = Line->Level; 2289 if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0)) 2290 --Line->Level; 2291 if (LeftAlignLabel) 2292 Line->Level = 0; 2293 2294 if (!Style.IndentCaseBlocks && CommentsBeforeNextToken.empty() && 2295 FormatTok->Tok.is(tok::l_brace)) { 2296 2297 CompoundStatementIndenter Indenter(this, Line->Level, 2298 Style.BraceWrapping.AfterCaseLabel, 2299 Style.BraceWrapping.IndentBraces); 2300 parseBlock(/*MustBeDeclaration=*/false); 2301 if (FormatTok->Tok.is(tok::kw_break)) { 2302 if (Style.BraceWrapping.AfterControlStatement == 2303 FormatStyle::BWACS_Always) { 2304 addUnwrappedLine(); 2305 if (!Style.IndentCaseBlocks && 2306 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) { 2307 Line->Level++; 2308 } 2309 } 2310 parseStructuralElement(); 2311 } 2312 addUnwrappedLine(); 2313 } else { 2314 if (FormatTok->is(tok::semi)) 2315 nextToken(); 2316 addUnwrappedLine(); 2317 } 2318 Line->Level = OldLineLevel; 2319 if (FormatTok->isNot(tok::l_brace)) { 2320 parseStructuralElement(); 2321 addUnwrappedLine(); 2322 } 2323 } 2324 2325 void UnwrappedLineParser::parseCaseLabel() { 2326 assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected"); 2327 2328 // FIXME: fix handling of complex expressions here. 2329 do { 2330 nextToken(); 2331 } while (!eof() && !FormatTok->Tok.is(tok::colon)); 2332 parseLabel(); 2333 } 2334 2335 void UnwrappedLineParser::parseSwitch() { 2336 assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected"); 2337 nextToken(); 2338 if (FormatTok->Tok.is(tok::l_paren)) 2339 parseParens(); 2340 if (FormatTok->Tok.is(tok::l_brace)) { 2341 CompoundStatementIndenter Indenter(this, Style, Line->Level); 2342 parseBlock(/*MustBeDeclaration=*/false); 2343 addUnwrappedLine(); 2344 } else { 2345 addUnwrappedLine(); 2346 ++Line->Level; 2347 parseStructuralElement(); 2348 --Line->Level; 2349 } 2350 } 2351 2352 void UnwrappedLineParser::parseAccessSpecifier() { 2353 nextToken(); 2354 // Understand Qt's slots. 2355 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots)) 2356 nextToken(); 2357 // Otherwise, we don't know what it is, and we'd better keep the next token. 2358 if (FormatTok->Tok.is(tok::colon)) 2359 nextToken(); 2360 addUnwrappedLine(); 2361 } 2362 2363 void UnwrappedLineParser::parseConcept() { 2364 assert(FormatTok->Tok.is(tok::kw_concept) && "'concept' expected"); 2365 nextToken(); 2366 if (!FormatTok->Tok.is(tok::identifier)) 2367 return; 2368 nextToken(); 2369 if (!FormatTok->Tok.is(tok::equal)) 2370 return; 2371 nextToken(); 2372 if (FormatTok->Tok.is(tok::kw_requires)) { 2373 nextToken(); 2374 parseRequiresExpression(Line->Level); 2375 } else { 2376 parseConstraintExpression(Line->Level); 2377 } 2378 } 2379 2380 void UnwrappedLineParser::parseRequiresExpression(unsigned int OriginalLevel) { 2381 // requires (R range) 2382 if (FormatTok->Tok.is(tok::l_paren)) { 2383 parseParens(); 2384 if (Style.IndentRequires && OriginalLevel != Line->Level) { 2385 addUnwrappedLine(); 2386 --Line->Level; 2387 } 2388 } 2389 2390 if (FormatTok->Tok.is(tok::l_brace)) { 2391 if (Style.BraceWrapping.AfterFunction) 2392 addUnwrappedLine(); 2393 FormatTok->setType(TT_FunctionLBrace); 2394 parseBlock(/*MustBeDeclaration=*/false); 2395 addUnwrappedLine(); 2396 } else { 2397 parseConstraintExpression(OriginalLevel); 2398 } 2399 } 2400 2401 void UnwrappedLineParser::parseConstraintExpression( 2402 unsigned int OriginalLevel) { 2403 // requires Id<T> && Id<T> || Id<T> 2404 while ( 2405 FormatTok->isOneOf(tok::identifier, tok::kw_requires, tok::coloncolon)) { 2406 nextToken(); 2407 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::less, 2408 tok::greater, tok::comma, tok::ellipsis)) { 2409 if (FormatTok->Tok.is(tok::less)) { 2410 parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false, 2411 /*ClosingBraceKind=*/tok::greater); 2412 continue; 2413 } 2414 nextToken(); 2415 } 2416 if (FormatTok->Tok.is(tok::kw_requires)) { 2417 parseRequiresExpression(OriginalLevel); 2418 } 2419 if (FormatTok->Tok.is(tok::less)) { 2420 parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false, 2421 /*ClosingBraceKind=*/tok::greater); 2422 } 2423 2424 if (FormatTok->Tok.is(tok::l_paren)) { 2425 parseParens(); 2426 } 2427 if (FormatTok->Tok.is(tok::l_brace)) { 2428 if (Style.BraceWrapping.AfterFunction) 2429 addUnwrappedLine(); 2430 FormatTok->setType(TT_FunctionLBrace); 2431 parseBlock(/*MustBeDeclaration=*/false); 2432 } 2433 if (FormatTok->Tok.is(tok::semi)) { 2434 // Eat any trailing semi. 2435 nextToken(); 2436 addUnwrappedLine(); 2437 } 2438 if (FormatTok->Tok.is(tok::colon)) { 2439 return; 2440 } 2441 if (!FormatTok->Tok.isOneOf(tok::ampamp, tok::pipepipe)) { 2442 if (FormatTok->Previous && 2443 !FormatTok->Previous->isOneOf(tok::identifier, tok::kw_requires, 2444 tok::coloncolon)) { 2445 addUnwrappedLine(); 2446 } 2447 if (Style.IndentRequires && OriginalLevel != Line->Level) { 2448 --Line->Level; 2449 } 2450 break; 2451 } else { 2452 FormatTok->setType(TT_ConstraintJunctions); 2453 } 2454 2455 nextToken(); 2456 } 2457 } 2458 2459 void UnwrappedLineParser::parseRequires() { 2460 assert(FormatTok->Tok.is(tok::kw_requires) && "'requires' expected"); 2461 2462 unsigned OriginalLevel = Line->Level; 2463 if (FormatTok->Previous && FormatTok->Previous->is(tok::greater)) { 2464 addUnwrappedLine(); 2465 if (Style.IndentRequires) { 2466 Line->Level++; 2467 } 2468 } 2469 nextToken(); 2470 2471 parseRequiresExpression(OriginalLevel); 2472 } 2473 2474 bool UnwrappedLineParser::parseEnum() { 2475 // Won't be 'enum' for NS_ENUMs. 2476 if (FormatTok->Tok.is(tok::kw_enum)) 2477 nextToken(); 2478 2479 // In TypeScript, "enum" can also be used as property name, e.g. in interface 2480 // declarations. An "enum" keyword followed by a colon would be a syntax 2481 // error and thus assume it is just an identifier. 2482 if (Style.Language == FormatStyle::LK_JavaScript && 2483 FormatTok->isOneOf(tok::colon, tok::question)) 2484 return false; 2485 2486 // In protobuf, "enum" can be used as a field name. 2487 if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal)) 2488 return false; 2489 2490 // Eat up enum class ... 2491 if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct)) 2492 nextToken(); 2493 2494 while (FormatTok->Tok.getIdentifierInfo() || 2495 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less, 2496 tok::greater, tok::comma, tok::question)) { 2497 nextToken(); 2498 // We can have macros or attributes in between 'enum' and the enum name. 2499 if (FormatTok->is(tok::l_paren)) 2500 parseParens(); 2501 if (FormatTok->is(tok::identifier)) { 2502 nextToken(); 2503 // If there are two identifiers in a row, this is likely an elaborate 2504 // return type. In Java, this can be "implements", etc. 2505 if (Style.isCpp() && FormatTok->is(tok::identifier)) 2506 return false; 2507 } 2508 } 2509 2510 // Just a declaration or something is wrong. 2511 if (FormatTok->isNot(tok::l_brace)) 2512 return true; 2513 FormatTok->setBlockKind(BK_Block); 2514 2515 if (Style.Language == FormatStyle::LK_Java) { 2516 // Java enums are different. 2517 parseJavaEnumBody(); 2518 return true; 2519 } 2520 if (Style.Language == FormatStyle::LK_Proto) { 2521 parseBlock(/*MustBeDeclaration=*/true); 2522 return true; 2523 } 2524 2525 if (!Style.AllowShortEnumsOnASingleLine) 2526 addUnwrappedLine(); 2527 // Parse enum body. 2528 nextToken(); 2529 if (!Style.AllowShortEnumsOnASingleLine) { 2530 addUnwrappedLine(); 2531 Line->Level += 1; 2532 } 2533 bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true, 2534 /*IsEnum=*/true); 2535 if (!Style.AllowShortEnumsOnASingleLine) 2536 Line->Level -= 1; 2537 if (HasError) { 2538 if (FormatTok->is(tok::semi)) 2539 nextToken(); 2540 addUnwrappedLine(); 2541 } 2542 return true; 2543 2544 // There is no addUnwrappedLine() here so that we fall through to parsing a 2545 // structural element afterwards. Thus, in "enum A {} n, m;", 2546 // "} n, m;" will end up in one unwrapped line. 2547 } 2548 2549 bool UnwrappedLineParser::parseStructLike() { 2550 // parseRecord falls through and does not yet add an unwrapped line as a 2551 // record declaration or definition can start a structural element. 2552 parseRecord(); 2553 // This does not apply to Java, JavaScript and C#. 2554 if (Style.Language == FormatStyle::LK_Java || 2555 Style.Language == FormatStyle::LK_JavaScript || Style.isCSharp()) { 2556 if (FormatTok->is(tok::semi)) 2557 nextToken(); 2558 addUnwrappedLine(); 2559 return true; 2560 } 2561 return false; 2562 } 2563 2564 namespace { 2565 // A class used to set and restore the Token position when peeking 2566 // ahead in the token source. 2567 class ScopedTokenPosition { 2568 unsigned StoredPosition; 2569 FormatTokenSource *Tokens; 2570 2571 public: 2572 ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) { 2573 assert(Tokens && "Tokens expected to not be null"); 2574 StoredPosition = Tokens->getPosition(); 2575 } 2576 2577 ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); } 2578 }; 2579 } // namespace 2580 2581 // Look to see if we have [[ by looking ahead, if 2582 // its not then rewind to the original position. 2583 bool UnwrappedLineParser::tryToParseSimpleAttribute() { 2584 ScopedTokenPosition AutoPosition(Tokens); 2585 FormatToken *Tok = Tokens->getNextToken(); 2586 // We already read the first [ check for the second. 2587 if (Tok && !Tok->is(tok::l_square)) { 2588 return false; 2589 } 2590 // Double check that the attribute is just something 2591 // fairly simple. 2592 while (Tok) { 2593 if (Tok->is(tok::r_square)) { 2594 break; 2595 } 2596 Tok = Tokens->getNextToken(); 2597 } 2598 Tok = Tokens->getNextToken(); 2599 if (Tok && !Tok->is(tok::r_square)) { 2600 return false; 2601 } 2602 Tok = Tokens->getNextToken(); 2603 if (Tok && Tok->is(tok::semi)) { 2604 return false; 2605 } 2606 return true; 2607 } 2608 2609 void UnwrappedLineParser::parseJavaEnumBody() { 2610 // Determine whether the enum is simple, i.e. does not have a semicolon or 2611 // constants with class bodies. Simple enums can be formatted like braced 2612 // lists, contracted to a single line, etc. 2613 unsigned StoredPosition = Tokens->getPosition(); 2614 bool IsSimple = true; 2615 FormatToken *Tok = Tokens->getNextToken(); 2616 while (Tok) { 2617 if (Tok->is(tok::r_brace)) 2618 break; 2619 if (Tok->isOneOf(tok::l_brace, tok::semi)) { 2620 IsSimple = false; 2621 break; 2622 } 2623 // FIXME: This will also mark enums with braces in the arguments to enum 2624 // constants as "not simple". This is probably fine in practice, though. 2625 Tok = Tokens->getNextToken(); 2626 } 2627 FormatTok = Tokens->setPosition(StoredPosition); 2628 2629 if (IsSimple) { 2630 nextToken(); 2631 parseBracedList(); 2632 addUnwrappedLine(); 2633 return; 2634 } 2635 2636 // Parse the body of a more complex enum. 2637 // First add a line for everything up to the "{". 2638 nextToken(); 2639 addUnwrappedLine(); 2640 ++Line->Level; 2641 2642 // Parse the enum constants. 2643 while (FormatTok) { 2644 if (FormatTok->is(tok::l_brace)) { 2645 // Parse the constant's class body. 2646 parseBlock(/*MustBeDeclaration=*/true, /*AddLevels=*/1u, 2647 /*MunchSemi=*/false); 2648 } else if (FormatTok->is(tok::l_paren)) { 2649 parseParens(); 2650 } else if (FormatTok->is(tok::comma)) { 2651 nextToken(); 2652 addUnwrappedLine(); 2653 } else if (FormatTok->is(tok::semi)) { 2654 nextToken(); 2655 addUnwrappedLine(); 2656 break; 2657 } else if (FormatTok->is(tok::r_brace)) { 2658 addUnwrappedLine(); 2659 break; 2660 } else { 2661 nextToken(); 2662 } 2663 } 2664 2665 // Parse the class body after the enum's ";" if any. 2666 parseLevel(/*HasOpeningBrace=*/true); 2667 nextToken(); 2668 --Line->Level; 2669 addUnwrappedLine(); 2670 } 2671 2672 void UnwrappedLineParser::parseRecord(bool ParseAsExpr) { 2673 const FormatToken &InitialToken = *FormatTok; 2674 nextToken(); 2675 2676 // The actual identifier can be a nested name specifier, and in macros 2677 // it is often token-pasted. 2678 // An [[attribute]] can be before the identifier. 2679 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash, 2680 tok::kw___attribute, tok::kw___declspec, 2681 tok::kw_alignas, tok::l_square, tok::r_square) || 2682 ((Style.Language == FormatStyle::LK_Java || 2683 Style.Language == FormatStyle::LK_JavaScript) && 2684 FormatTok->isOneOf(tok::period, tok::comma))) { 2685 if (Style.Language == FormatStyle::LK_JavaScript && 2686 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) { 2687 // JavaScript/TypeScript supports inline object types in 2688 // extends/implements positions: 2689 // class Foo implements {bar: number} { } 2690 nextToken(); 2691 if (FormatTok->is(tok::l_brace)) { 2692 tryToParseBracedList(); 2693 continue; 2694 } 2695 } 2696 bool IsNonMacroIdentifier = 2697 FormatTok->is(tok::identifier) && 2698 FormatTok->TokenText != FormatTok->TokenText.upper(); 2699 nextToken(); 2700 // We can have macros or attributes in between 'class' and the class name. 2701 if (!IsNonMacroIdentifier) { 2702 if (FormatTok->Tok.is(tok::l_paren)) { 2703 parseParens(); 2704 } else if (FormatTok->is(TT_AttributeSquare)) { 2705 parseSquare(); 2706 // Consume the closing TT_AttributeSquare. 2707 if (FormatTok->Next && FormatTok->is(TT_AttributeSquare)) 2708 nextToken(); 2709 } 2710 } 2711 } 2712 2713 // Note that parsing away template declarations here leads to incorrectly 2714 // accepting function declarations as record declarations. 2715 // In general, we cannot solve this problem. Consider: 2716 // class A<int> B() {} 2717 // which can be a function definition or a class definition when B() is a 2718 // macro. If we find enough real-world cases where this is a problem, we 2719 // can parse for the 'template' keyword in the beginning of the statement, 2720 // and thus rule out the record production in case there is no template 2721 // (this would still leave us with an ambiguity between template function 2722 // and class declarations). 2723 if (FormatTok->isOneOf(tok::colon, tok::less)) { 2724 while (!eof()) { 2725 if (FormatTok->is(tok::l_brace)) { 2726 calculateBraceTypes(/*ExpectClassBody=*/true); 2727 if (!tryToParseBracedList()) 2728 break; 2729 } 2730 if (FormatTok->Tok.is(tok::semi)) 2731 return; 2732 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) { 2733 addUnwrappedLine(); 2734 nextToken(); 2735 parseCSharpGenericTypeConstraint(); 2736 break; 2737 } 2738 nextToken(); 2739 } 2740 } 2741 if (FormatTok->Tok.is(tok::l_brace)) { 2742 if (ParseAsExpr) { 2743 parseChildBlock(); 2744 } else { 2745 if (ShouldBreakBeforeBrace(Style, InitialToken)) 2746 addUnwrappedLine(); 2747 2748 unsigned AddLevels = Style.IndentAccessModifiers ? 2u : 1u; 2749 parseBlock(/*MustBeDeclaration=*/true, AddLevels, /*MunchSemi=*/false); 2750 } 2751 } 2752 // There is no addUnwrappedLine() here so that we fall through to parsing a 2753 // structural element afterwards. Thus, in "class A {} n, m;", 2754 // "} n, m;" will end up in one unwrapped line. 2755 } 2756 2757 void UnwrappedLineParser::parseObjCMethod() { 2758 assert(FormatTok->Tok.isOneOf(tok::l_paren, tok::identifier) && 2759 "'(' or identifier expected."); 2760 do { 2761 if (FormatTok->Tok.is(tok::semi)) { 2762 nextToken(); 2763 addUnwrappedLine(); 2764 return; 2765 } else if (FormatTok->Tok.is(tok::l_brace)) { 2766 if (Style.BraceWrapping.AfterFunction) 2767 addUnwrappedLine(); 2768 parseBlock(/*MustBeDeclaration=*/false); 2769 addUnwrappedLine(); 2770 return; 2771 } else { 2772 nextToken(); 2773 } 2774 } while (!eof()); 2775 } 2776 2777 void UnwrappedLineParser::parseObjCProtocolList() { 2778 assert(FormatTok->Tok.is(tok::less) && "'<' expected."); 2779 do { 2780 nextToken(); 2781 // Early exit in case someone forgot a close angle. 2782 if (FormatTok->isOneOf(tok::semi, tok::l_brace) || 2783 FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) 2784 return; 2785 } while (!eof() && FormatTok->Tok.isNot(tok::greater)); 2786 nextToken(); // Skip '>'. 2787 } 2788 2789 void UnwrappedLineParser::parseObjCUntilAtEnd() { 2790 do { 2791 if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) { 2792 nextToken(); 2793 addUnwrappedLine(); 2794 break; 2795 } 2796 if (FormatTok->is(tok::l_brace)) { 2797 parseBlock(/*MustBeDeclaration=*/false); 2798 // In ObjC interfaces, nothing should be following the "}". 2799 addUnwrappedLine(); 2800 } else if (FormatTok->is(tok::r_brace)) { 2801 // Ignore stray "}". parseStructuralElement doesn't consume them. 2802 nextToken(); 2803 addUnwrappedLine(); 2804 } else if (FormatTok->isOneOf(tok::minus, tok::plus)) { 2805 nextToken(); 2806 parseObjCMethod(); 2807 } else { 2808 parseStructuralElement(); 2809 } 2810 } while (!eof()); 2811 } 2812 2813 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() { 2814 assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_interface || 2815 FormatTok->Tok.getObjCKeywordID() == tok::objc_implementation); 2816 nextToken(); 2817 nextToken(); // interface name 2818 2819 // @interface can be followed by a lightweight generic 2820 // specialization list, then either a base class or a category. 2821 if (FormatTok->Tok.is(tok::less)) { 2822 parseObjCLightweightGenerics(); 2823 } 2824 if (FormatTok->Tok.is(tok::colon)) { 2825 nextToken(); 2826 nextToken(); // base class name 2827 // The base class can also have lightweight generics applied to it. 2828 if (FormatTok->Tok.is(tok::less)) { 2829 parseObjCLightweightGenerics(); 2830 } 2831 } else if (FormatTok->Tok.is(tok::l_paren)) 2832 // Skip category, if present. 2833 parseParens(); 2834 2835 if (FormatTok->Tok.is(tok::less)) 2836 parseObjCProtocolList(); 2837 2838 if (FormatTok->Tok.is(tok::l_brace)) { 2839 if (Style.BraceWrapping.AfterObjCDeclaration) 2840 addUnwrappedLine(); 2841 parseBlock(/*MustBeDeclaration=*/true); 2842 } 2843 2844 // With instance variables, this puts '}' on its own line. Without instance 2845 // variables, this ends the @interface line. 2846 addUnwrappedLine(); 2847 2848 parseObjCUntilAtEnd(); 2849 } 2850 2851 void UnwrappedLineParser::parseObjCLightweightGenerics() { 2852 assert(FormatTok->Tok.is(tok::less)); 2853 // Unlike protocol lists, generic parameterizations support 2854 // nested angles: 2855 // 2856 // @interface Foo<ValueType : id <NSCopying, NSSecureCoding>> : 2857 // NSObject <NSCopying, NSSecureCoding> 2858 // 2859 // so we need to count how many open angles we have left. 2860 unsigned NumOpenAngles = 1; 2861 do { 2862 nextToken(); 2863 // Early exit in case someone forgot a close angle. 2864 if (FormatTok->isOneOf(tok::semi, tok::l_brace) || 2865 FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) 2866 break; 2867 if (FormatTok->Tok.is(tok::less)) 2868 ++NumOpenAngles; 2869 else if (FormatTok->Tok.is(tok::greater)) { 2870 assert(NumOpenAngles > 0 && "'>' makes NumOpenAngles negative"); 2871 --NumOpenAngles; 2872 } 2873 } while (!eof() && NumOpenAngles != 0); 2874 nextToken(); // Skip '>'. 2875 } 2876 2877 // Returns true for the declaration/definition form of @protocol, 2878 // false for the expression form. 2879 bool UnwrappedLineParser::parseObjCProtocol() { 2880 assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_protocol); 2881 nextToken(); 2882 2883 if (FormatTok->is(tok::l_paren)) 2884 // The expression form of @protocol, e.g. "Protocol* p = @protocol(foo);". 2885 return false; 2886 2887 // The definition/declaration form, 2888 // @protocol Foo 2889 // - (int)someMethod; 2890 // @end 2891 2892 nextToken(); // protocol name 2893 2894 if (FormatTok->Tok.is(tok::less)) 2895 parseObjCProtocolList(); 2896 2897 // Check for protocol declaration. 2898 if (FormatTok->Tok.is(tok::semi)) { 2899 nextToken(); 2900 addUnwrappedLine(); 2901 return true; 2902 } 2903 2904 addUnwrappedLine(); 2905 parseObjCUntilAtEnd(); 2906 return true; 2907 } 2908 2909 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() { 2910 bool IsImport = FormatTok->is(Keywords.kw_import); 2911 assert(IsImport || FormatTok->is(tok::kw_export)); 2912 nextToken(); 2913 2914 // Consume the "default" in "export default class/function". 2915 if (FormatTok->is(tok::kw_default)) 2916 nextToken(); 2917 2918 // Consume "async function", "function" and "default function", so that these 2919 // get parsed as free-standing JS functions, i.e. do not require a trailing 2920 // semicolon. 2921 if (FormatTok->is(Keywords.kw_async)) 2922 nextToken(); 2923 if (FormatTok->is(Keywords.kw_function)) { 2924 nextToken(); 2925 return; 2926 } 2927 2928 // For imports, `export *`, `export {...}`, consume the rest of the line up 2929 // to the terminating `;`. For everything else, just return and continue 2930 // parsing the structural element, i.e. the declaration or expression for 2931 // `export default`. 2932 if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) && 2933 !FormatTok->isStringLiteral()) 2934 return; 2935 2936 while (!eof()) { 2937 if (FormatTok->is(tok::semi)) 2938 return; 2939 if (Line->Tokens.empty()) { 2940 // Common issue: Automatic Semicolon Insertion wrapped the line, so the 2941 // import statement should terminate. 2942 return; 2943 } 2944 if (FormatTok->is(tok::l_brace)) { 2945 FormatTok->setBlockKind(BK_Block); 2946 nextToken(); 2947 parseBracedList(); 2948 } else { 2949 nextToken(); 2950 } 2951 } 2952 } 2953 2954 void UnwrappedLineParser::parseStatementMacro() { 2955 nextToken(); 2956 if (FormatTok->is(tok::l_paren)) 2957 parseParens(); 2958 if (FormatTok->is(tok::semi)) 2959 nextToken(); 2960 addUnwrappedLine(); 2961 } 2962 2963 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line, 2964 StringRef Prefix = "") { 2965 llvm::dbgs() << Prefix << "Line(" << Line.Level 2966 << ", FSC=" << Line.FirstStartColumn << ")" 2967 << (Line.InPPDirective ? " MACRO" : "") << ": "; 2968 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(), 2969 E = Line.Tokens.end(); 2970 I != E; ++I) { 2971 llvm::dbgs() << I->Tok->Tok.getName() << "[" 2972 << "T=" << (unsigned)I->Tok->getType() 2973 << ", OC=" << I->Tok->OriginalColumn << "] "; 2974 } 2975 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(), 2976 E = Line.Tokens.end(); 2977 I != E; ++I) { 2978 const UnwrappedLineNode &Node = *I; 2979 for (SmallVectorImpl<UnwrappedLine>::const_iterator 2980 I = Node.Children.begin(), 2981 E = Node.Children.end(); 2982 I != E; ++I) { 2983 printDebugInfo(*I, "\nChild: "); 2984 } 2985 } 2986 llvm::dbgs() << "\n"; 2987 } 2988 2989 void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) { 2990 if (Line->Tokens.empty()) 2991 return; 2992 LLVM_DEBUG({ 2993 if (CurrentLines == &Lines) 2994 printDebugInfo(*Line); 2995 }); 2996 2997 // If this line closes a block when in Whitesmiths mode, remember that 2998 // information so that the level can be decreased after the line is added. 2999 // This has to happen after the addition of the line since the line itself 3000 // needs to be indented. 3001 bool ClosesWhitesmithsBlock = 3002 Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex && 3003 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths; 3004 3005 CurrentLines->push_back(std::move(*Line)); 3006 Line->Tokens.clear(); 3007 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex; 3008 Line->FirstStartColumn = 0; 3009 3010 if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove) 3011 --Line->Level; 3012 if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) { 3013 CurrentLines->append( 3014 std::make_move_iterator(PreprocessorDirectives.begin()), 3015 std::make_move_iterator(PreprocessorDirectives.end())); 3016 PreprocessorDirectives.clear(); 3017 } 3018 // Disconnect the current token from the last token on the previous line. 3019 FormatTok->Previous = nullptr; 3020 } 3021 3022 bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); } 3023 3024 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) { 3025 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) && 3026 FormatTok.NewlinesBefore > 0; 3027 } 3028 3029 // Checks if \p FormatTok is a line comment that continues the line comment 3030 // section on \p Line. 3031 static bool 3032 continuesLineCommentSection(const FormatToken &FormatTok, 3033 const UnwrappedLine &Line, 3034 const llvm::Regex &CommentPragmasRegex) { 3035 if (Line.Tokens.empty()) 3036 return false; 3037 3038 StringRef IndentContent = FormatTok.TokenText; 3039 if (FormatTok.TokenText.startswith("//") || 3040 FormatTok.TokenText.startswith("/*")) 3041 IndentContent = FormatTok.TokenText.substr(2); 3042 if (CommentPragmasRegex.match(IndentContent)) 3043 return false; 3044 3045 // If Line starts with a line comment, then FormatTok continues the comment 3046 // section if its original column is greater or equal to the original start 3047 // column of the line. 3048 // 3049 // Define the min column token of a line as follows: if a line ends in '{' or 3050 // contains a '{' followed by a line comment, then the min column token is 3051 // that '{'. Otherwise, the min column token of the line is the first token of 3052 // the line. 3053 // 3054 // If Line starts with a token other than a line comment, then FormatTok 3055 // continues the comment section if its original column is greater than the 3056 // original start column of the min column token of the line. 3057 // 3058 // For example, the second line comment continues the first in these cases: 3059 // 3060 // // first line 3061 // // second line 3062 // 3063 // and: 3064 // 3065 // // first line 3066 // // second line 3067 // 3068 // and: 3069 // 3070 // int i; // first line 3071 // // second line 3072 // 3073 // and: 3074 // 3075 // do { // first line 3076 // // second line 3077 // int i; 3078 // } while (true); 3079 // 3080 // and: 3081 // 3082 // enum { 3083 // a, // first line 3084 // // second line 3085 // b 3086 // }; 3087 // 3088 // The second line comment doesn't continue the first in these cases: 3089 // 3090 // // first line 3091 // // second line 3092 // 3093 // and: 3094 // 3095 // int i; // first line 3096 // // second line 3097 // 3098 // and: 3099 // 3100 // do { // first line 3101 // // second line 3102 // int i; 3103 // } while (true); 3104 // 3105 // and: 3106 // 3107 // enum { 3108 // a, // first line 3109 // // second line 3110 // }; 3111 const FormatToken *MinColumnToken = Line.Tokens.front().Tok; 3112 3113 // Scan for '{//'. If found, use the column of '{' as a min column for line 3114 // comment section continuation. 3115 const FormatToken *PreviousToken = nullptr; 3116 for (const UnwrappedLineNode &Node : Line.Tokens) { 3117 if (PreviousToken && PreviousToken->is(tok::l_brace) && 3118 isLineComment(*Node.Tok)) { 3119 MinColumnToken = PreviousToken; 3120 break; 3121 } 3122 PreviousToken = Node.Tok; 3123 3124 // Grab the last newline preceding a token in this unwrapped line. 3125 if (Node.Tok->NewlinesBefore > 0) { 3126 MinColumnToken = Node.Tok; 3127 } 3128 } 3129 if (PreviousToken && PreviousToken->is(tok::l_brace)) { 3130 MinColumnToken = PreviousToken; 3131 } 3132 3133 return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok, 3134 MinColumnToken); 3135 } 3136 3137 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) { 3138 bool JustComments = Line->Tokens.empty(); 3139 for (SmallVectorImpl<FormatToken *>::const_iterator 3140 I = CommentsBeforeNextToken.begin(), 3141 E = CommentsBeforeNextToken.end(); 3142 I != E; ++I) { 3143 // Line comments that belong to the same line comment section are put on the 3144 // same line since later we might want to reflow content between them. 3145 // Additional fine-grained breaking of line comment sections is controlled 3146 // by the class BreakableLineCommentSection in case it is desirable to keep 3147 // several line comment sections in the same unwrapped line. 3148 // 3149 // FIXME: Consider putting separate line comment sections as children to the 3150 // unwrapped line instead. 3151 (*I)->ContinuesLineCommentSection = 3152 continuesLineCommentSection(**I, *Line, CommentPragmasRegex); 3153 if (isOnNewLine(**I) && JustComments && !(*I)->ContinuesLineCommentSection) 3154 addUnwrappedLine(); 3155 pushToken(*I); 3156 } 3157 if (NewlineBeforeNext && JustComments) 3158 addUnwrappedLine(); 3159 CommentsBeforeNextToken.clear(); 3160 } 3161 3162 void UnwrappedLineParser::nextToken(int LevelDifference) { 3163 if (eof()) 3164 return; 3165 flushComments(isOnNewLine(*FormatTok)); 3166 pushToken(FormatTok); 3167 FormatToken *Previous = FormatTok; 3168 if (Style.Language != FormatStyle::LK_JavaScript) 3169 readToken(LevelDifference); 3170 else 3171 readTokenWithJavaScriptASI(); 3172 FormatTok->Previous = Previous; 3173 } 3174 3175 void UnwrappedLineParser::distributeComments( 3176 const SmallVectorImpl<FormatToken *> &Comments, 3177 const FormatToken *NextTok) { 3178 // Whether or not a line comment token continues a line is controlled by 3179 // the method continuesLineCommentSection, with the following caveat: 3180 // 3181 // Define a trail of Comments to be a nonempty proper postfix of Comments such 3182 // that each comment line from the trail is aligned with the next token, if 3183 // the next token exists. If a trail exists, the beginning of the maximal 3184 // trail is marked as a start of a new comment section. 3185 // 3186 // For example in this code: 3187 // 3188 // int a; // line about a 3189 // // line 1 about b 3190 // // line 2 about b 3191 // int b; 3192 // 3193 // the two lines about b form a maximal trail, so there are two sections, the 3194 // first one consisting of the single comment "// line about a" and the 3195 // second one consisting of the next two comments. 3196 if (Comments.empty()) 3197 return; 3198 bool ShouldPushCommentsInCurrentLine = true; 3199 bool HasTrailAlignedWithNextToken = false; 3200 unsigned StartOfTrailAlignedWithNextToken = 0; 3201 if (NextTok) { 3202 // We are skipping the first element intentionally. 3203 for (unsigned i = Comments.size() - 1; i > 0; --i) { 3204 if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) { 3205 HasTrailAlignedWithNextToken = true; 3206 StartOfTrailAlignedWithNextToken = i; 3207 } 3208 } 3209 } 3210 for (unsigned i = 0, e = Comments.size(); i < e; ++i) { 3211 FormatToken *FormatTok = Comments[i]; 3212 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) { 3213 FormatTok->ContinuesLineCommentSection = false; 3214 } else { 3215 FormatTok->ContinuesLineCommentSection = 3216 continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex); 3217 } 3218 if (!FormatTok->ContinuesLineCommentSection && 3219 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) { 3220 ShouldPushCommentsInCurrentLine = false; 3221 } 3222 if (ShouldPushCommentsInCurrentLine) { 3223 pushToken(FormatTok); 3224 } else { 3225 CommentsBeforeNextToken.push_back(FormatTok); 3226 } 3227 } 3228 } 3229 3230 void UnwrappedLineParser::readToken(int LevelDifference) { 3231 SmallVector<FormatToken *, 1> Comments; 3232 do { 3233 FormatTok = Tokens->getNextToken(); 3234 assert(FormatTok); 3235 while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) && 3236 (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) { 3237 distributeComments(Comments, FormatTok); 3238 Comments.clear(); 3239 // If there is an unfinished unwrapped line, we flush the preprocessor 3240 // directives only after that unwrapped line was finished later. 3241 bool SwitchToPreprocessorLines = !Line->Tokens.empty(); 3242 ScopedLineState BlockState(*this, SwitchToPreprocessorLines); 3243 assert((LevelDifference >= 0 || 3244 static_cast<unsigned>(-LevelDifference) <= Line->Level) && 3245 "LevelDifference makes Line->Level negative"); 3246 Line->Level += LevelDifference; 3247 // Comments stored before the preprocessor directive need to be output 3248 // before the preprocessor directive, at the same level as the 3249 // preprocessor directive, as we consider them to apply to the directive. 3250 if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash && 3251 PPBranchLevel > 0) 3252 Line->Level += PPBranchLevel; 3253 flushComments(isOnNewLine(*FormatTok)); 3254 parsePPDirective(); 3255 } 3256 while (FormatTok->getType() == TT_ConflictStart || 3257 FormatTok->getType() == TT_ConflictEnd || 3258 FormatTok->getType() == TT_ConflictAlternative) { 3259 if (FormatTok->getType() == TT_ConflictStart) { 3260 conditionalCompilationStart(/*Unreachable=*/false); 3261 } else if (FormatTok->getType() == TT_ConflictAlternative) { 3262 conditionalCompilationAlternative(); 3263 } else if (FormatTok->getType() == TT_ConflictEnd) { 3264 conditionalCompilationEnd(); 3265 } 3266 FormatTok = Tokens->getNextToken(); 3267 FormatTok->MustBreakBefore = true; 3268 } 3269 3270 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) && 3271 !Line->InPPDirective) { 3272 continue; 3273 } 3274 3275 if (!FormatTok->Tok.is(tok::comment)) { 3276 distributeComments(Comments, FormatTok); 3277 Comments.clear(); 3278 return; 3279 } 3280 3281 Comments.push_back(FormatTok); 3282 } while (!eof()); 3283 3284 distributeComments(Comments, nullptr); 3285 Comments.clear(); 3286 } 3287 3288 void UnwrappedLineParser::pushToken(FormatToken *Tok) { 3289 Line->Tokens.push_back(UnwrappedLineNode(Tok)); 3290 if (MustBreakBeforeNextToken) { 3291 Line->Tokens.back().Tok->MustBreakBefore = true; 3292 MustBreakBeforeNextToken = false; 3293 } 3294 } 3295 3296 } // end namespace format 3297 } // end namespace clang 3298