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