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