1 //===--- UnwrappedLineParser.cpp - Format C++ code ------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// 10 /// \file 11 /// \brief This file contains the implementation of the UnwrappedLineParser, 12 /// which turns a stream of tokens into UnwrappedLines. 13 /// 14 //===----------------------------------------------------------------------===// 15 16 #include "UnwrappedLineParser.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 TokenSource = this; 87 Line.Level = 0; 88 Line.InPPDirective = true; 89 } 90 91 ~ScopedMacroState() override { 92 TokenSource = PreviousTokenSource; 93 ResetToken = Token; 94 Line.InPPDirective = false; 95 Line.Level = PreviousLineLevel; 96 } 97 98 FormatToken *getNextToken() override { 99 // The \c UnwrappedLineParser guards against this by never calling 100 // \c getNextToken() after it has encountered the first eof token. 101 assert(!eof()); 102 PreviousToken = Token; 103 Token = PreviousTokenSource->getNextToken(); 104 if (eof()) 105 return getFakeEOF(); 106 return Token; 107 } 108 109 unsigned getPosition() override { return PreviousTokenSource->getPosition(); } 110 111 FormatToken *setPosition(unsigned Position) override { 112 PreviousToken = nullptr; 113 Token = PreviousTokenSource->setPosition(Position); 114 return Token; 115 } 116 117 private: 118 bool eof() { 119 return Token && Token->HasUnescapedNewline && 120 !continuesLineComment(*Token, PreviousToken, 121 /*MinColumnToken=*/PreviousToken); 122 } 123 124 FormatToken *getFakeEOF() { 125 static bool EOFInitialized = false; 126 static FormatToken FormatTok; 127 if (!EOFInitialized) { 128 FormatTok.Tok.startToken(); 129 FormatTok.Tok.setKind(tok::eof); 130 EOFInitialized = true; 131 } 132 return &FormatTok; 133 } 134 135 UnwrappedLine &Line; 136 FormatTokenSource *&TokenSource; 137 FormatToken *&ResetToken; 138 unsigned PreviousLineLevel; 139 FormatTokenSource *PreviousTokenSource; 140 141 FormatToken *Token; 142 FormatToken *PreviousToken; 143 }; 144 145 } // end anonymous namespace 146 147 class ScopedLineState { 148 public: 149 ScopedLineState(UnwrappedLineParser &Parser, 150 bool SwitchToPreprocessorLines = false) 151 : Parser(Parser), OriginalLines(Parser.CurrentLines) { 152 if (SwitchToPreprocessorLines) 153 Parser.CurrentLines = &Parser.PreprocessorDirectives; 154 else if (!Parser.Line->Tokens.empty()) 155 Parser.CurrentLines = &Parser.Line->Tokens.back().Children; 156 PreBlockLine = std::move(Parser.Line); 157 Parser.Line = llvm::make_unique<UnwrappedLine>(); 158 Parser.Line->Level = PreBlockLine->Level; 159 Parser.Line->InPPDirective = PreBlockLine->InPPDirective; 160 } 161 162 ~ScopedLineState() { 163 if (!Parser.Line->Tokens.empty()) { 164 Parser.addUnwrappedLine(); 165 } 166 assert(Parser.Line->Tokens.empty()); 167 Parser.Line = std::move(PreBlockLine); 168 if (Parser.CurrentLines == &Parser.PreprocessorDirectives) 169 Parser.MustBreakBeforeNextToken = true; 170 Parser.CurrentLines = OriginalLines; 171 } 172 173 private: 174 UnwrappedLineParser &Parser; 175 176 std::unique_ptr<UnwrappedLine> PreBlockLine; 177 SmallVectorImpl<UnwrappedLine> *OriginalLines; 178 }; 179 180 class CompoundStatementIndenter { 181 public: 182 CompoundStatementIndenter(UnwrappedLineParser *Parser, 183 const FormatStyle &Style, unsigned &LineLevel) 184 : LineLevel(LineLevel), OldLineLevel(LineLevel) { 185 if (Style.BraceWrapping.AfterControlStatement) 186 Parser->addUnwrappedLine(); 187 if (Style.BraceWrapping.IndentBraces) 188 ++LineLevel; 189 } 190 ~CompoundStatementIndenter() { LineLevel = OldLineLevel; } 191 192 private: 193 unsigned &LineLevel; 194 unsigned OldLineLevel; 195 }; 196 197 namespace { 198 199 class IndexedTokenSource : public FormatTokenSource { 200 public: 201 IndexedTokenSource(ArrayRef<FormatToken *> Tokens) 202 : Tokens(Tokens), Position(-1) {} 203 204 FormatToken *getNextToken() override { 205 ++Position; 206 return Tokens[Position]; 207 } 208 209 unsigned getPosition() override { 210 assert(Position >= 0); 211 return Position; 212 } 213 214 FormatToken *setPosition(unsigned P) override { 215 Position = P; 216 return Tokens[Position]; 217 } 218 219 void reset() { Position = -1; } 220 221 private: 222 ArrayRef<FormatToken *> Tokens; 223 int Position; 224 }; 225 226 } // end anonymous namespace 227 228 UnwrappedLineParser::UnwrappedLineParser(const FormatStyle &Style, 229 const AdditionalKeywords &Keywords, 230 unsigned FirstStartColumn, 231 ArrayRef<FormatToken *> Tokens, 232 UnwrappedLineConsumer &Callback) 233 : Line(new UnwrappedLine), MustBreakBeforeNextToken(false), 234 CurrentLines(&Lines), Style(Style), Keywords(Keywords), 235 CommentPragmasRegex(Style.CommentPragmas), Tokens(nullptr), 236 Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1), 237 IncludeGuard(Style.IndentPPDirectives == FormatStyle::PPDIS_None 238 ? IG_Rejected 239 : IG_Inited), 240 IncludeGuardToken(nullptr), FirstStartColumn(FirstStartColumn) {} 241 242 void UnwrappedLineParser::reset() { 243 PPBranchLevel = -1; 244 IncludeGuard = Style.IndentPPDirectives == FormatStyle::PPDIS_None 245 ? IG_Rejected 246 : IG_Inited; 247 IncludeGuardToken = nullptr; 248 Line.reset(new UnwrappedLine); 249 CommentsBeforeNextToken.clear(); 250 FormatTok = nullptr; 251 MustBreakBeforeNextToken = false; 252 PreprocessorDirectives.clear(); 253 CurrentLines = &Lines; 254 DeclarationScopeStack.clear(); 255 PPStack.clear(); 256 Line->FirstStartColumn = FirstStartColumn; 257 } 258 259 void UnwrappedLineParser::parse() { 260 IndexedTokenSource TokenSource(AllTokens); 261 Line->FirstStartColumn = FirstStartColumn; 262 do { 263 DEBUG(llvm::dbgs() << "----\n"); 264 reset(); 265 Tokens = &TokenSource; 266 TokenSource.reset(); 267 268 readToken(); 269 parseFile(); 270 271 // If we found an include guard then all preprocessor directives (other than 272 // the guard) are over-indented by one. 273 if (IncludeGuard == IG_Found) 274 for (auto &Line : Lines) 275 if (Line.InPPDirective && Line.Level > 0) 276 --Line.Level; 277 278 // Create line with eof token. 279 pushToken(FormatTok); 280 addUnwrappedLine(); 281 282 for (SmallVectorImpl<UnwrappedLine>::iterator I = Lines.begin(), 283 E = Lines.end(); 284 I != E; ++I) { 285 Callback.consumeUnwrappedLine(*I); 286 } 287 Callback.finishRun(); 288 Lines.clear(); 289 while (!PPLevelBranchIndex.empty() && 290 PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) { 291 PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1); 292 PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1); 293 } 294 if (!PPLevelBranchIndex.empty()) { 295 ++PPLevelBranchIndex.back(); 296 assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size()); 297 assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back()); 298 } 299 } while (!PPLevelBranchIndex.empty()); 300 } 301 302 void UnwrappedLineParser::parseFile() { 303 // The top-level context in a file always has declarations, except for pre- 304 // processor directives and JavaScript files. 305 bool MustBeDeclaration = 306 !Line->InPPDirective && Style.Language != FormatStyle::LK_JavaScript; 307 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack, 308 MustBeDeclaration); 309 if (Style.Language == FormatStyle::LK_TextProto) 310 parseBracedList(); 311 else 312 parseLevel(/*HasOpeningBrace=*/false); 313 // Make sure to format the remaining tokens. 314 flushComments(true); 315 addUnwrappedLine(); 316 } 317 318 void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) { 319 bool SwitchLabelEncountered = false; 320 do { 321 tok::TokenKind kind = FormatTok->Tok.getKind(); 322 if (FormatTok->Type == TT_MacroBlockBegin) { 323 kind = tok::l_brace; 324 } else if (FormatTok->Type == TT_MacroBlockEnd) { 325 kind = tok::r_brace; 326 } 327 328 switch (kind) { 329 case tok::comment: 330 nextToken(); 331 addUnwrappedLine(); 332 break; 333 case tok::l_brace: 334 // FIXME: Add parameter whether this can happen - if this happens, we must 335 // be in a non-declaration context. 336 if (!FormatTok->is(TT_MacroBlockBegin) && tryToParseBracedList()) 337 continue; 338 parseBlock(/*MustBeDeclaration=*/false); 339 addUnwrappedLine(); 340 break; 341 case tok::r_brace: 342 if (HasOpeningBrace) 343 return; 344 nextToken(); 345 addUnwrappedLine(); 346 break; 347 case tok::kw_default: { 348 unsigned StoredPosition = Tokens->getPosition(); 349 FormatToken *Next = Tokens->getNextToken(); 350 FormatTok = Tokens->setPosition(StoredPosition); 351 if (Next && Next->isNot(tok::colon)) { 352 // default not followed by ':' is not a case label; treat it like 353 // an identifier. 354 parseStructuralElement(); 355 break; 356 } 357 // Else, if it is 'default:', fall through to the case handling. 358 LLVM_FALLTHROUGH; 359 } 360 case tok::kw_case: 361 if (Style.Language == FormatStyle::LK_JavaScript && 362 Line->MustBeDeclaration) { 363 // A 'case: string' style field declaration. 364 parseStructuralElement(); 365 break; 366 } 367 if (!SwitchLabelEncountered && 368 (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1))) 369 ++Line->Level; 370 SwitchLabelEncountered = true; 371 parseStructuralElement(); 372 break; 373 default: 374 parseStructuralElement(); 375 break; 376 } 377 } while (!eof()); 378 } 379 380 void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) { 381 // We'll parse forward through the tokens until we hit 382 // a closing brace or eof - note that getNextToken() will 383 // parse macros, so this will magically work inside macro 384 // definitions, too. 385 unsigned StoredPosition = Tokens->getPosition(); 386 FormatToken *Tok = FormatTok; 387 const FormatToken *PrevTok = Tok->Previous; 388 // Keep a stack of positions of lbrace tokens. We will 389 // update information about whether an lbrace starts a 390 // braced init list or a different block during the loop. 391 SmallVector<FormatToken *, 8> LBraceStack; 392 assert(Tok->Tok.is(tok::l_brace)); 393 do { 394 // Get next non-comment token. 395 FormatToken *NextTok; 396 unsigned ReadTokens = 0; 397 do { 398 NextTok = Tokens->getNextToken(); 399 ++ReadTokens; 400 } while (NextTok->is(tok::comment)); 401 402 switch (Tok->Tok.getKind()) { 403 case tok::l_brace: 404 if (Style.Language == FormatStyle::LK_JavaScript && PrevTok) { 405 if (PrevTok->isOneOf(tok::colon, tok::less)) 406 // A ':' indicates this code is in a type, or a braced list 407 // following a label in an object literal ({a: {b: 1}}). 408 // A '<' could be an object used in a comparison, but that is nonsense 409 // code (can never return true), so more likely it is a generic type 410 // argument (`X<{a: string; b: number}>`). 411 // The code below could be confused by semicolons between the 412 // individual members in a type member list, which would normally 413 // trigger BK_Block. In both cases, this must be parsed as an inline 414 // braced init. 415 Tok->BlockKind = BK_BracedInit; 416 else if (PrevTok->is(tok::r_paren)) 417 // `) { }` can only occur in function or method declarations in JS. 418 Tok->BlockKind = BK_Block; 419 } else { 420 Tok->BlockKind = BK_Unknown; 421 } 422 LBraceStack.push_back(Tok); 423 break; 424 case tok::r_brace: 425 if (LBraceStack.empty()) 426 break; 427 if (LBraceStack.back()->BlockKind == BK_Unknown) { 428 bool ProbablyBracedList = false; 429 if (Style.Language == FormatStyle::LK_Proto) { 430 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square); 431 } else { 432 // Using OriginalColumn to distinguish between ObjC methods and 433 // binary operators is a bit hacky. 434 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) && 435 NextTok->OriginalColumn == 0; 436 437 // If there is a comma, semicolon or right paren after the closing 438 // brace, we assume this is a braced initializer list. Note that 439 // regardless how we mark inner braces here, we will overwrite the 440 // BlockKind later if we parse a braced list (where all blocks 441 // inside are by default braced lists), or when we explicitly detect 442 // blocks (for example while parsing lambdas). 443 // FIXME: Some of these do not apply to JS, e.g. "} {" can never be a 444 // braced list in JS. 445 ProbablyBracedList = 446 (Style.Language == FormatStyle::LK_JavaScript && 447 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in, 448 Keywords.kw_as)) || 449 (Style.isCpp() && NextTok->is(tok::l_paren)) || 450 NextTok->isOneOf(tok::comma, tok::period, tok::colon, 451 tok::r_paren, tok::r_square, tok::l_brace, 452 tok::l_square, tok::ellipsis) || 453 (NextTok->is(tok::identifier) && 454 !PrevTok->isOneOf(tok::semi, tok::r_brace, tok::l_brace)) || 455 (NextTok->is(tok::semi) && 456 (!ExpectClassBody || LBraceStack.size() != 1)) || 457 (NextTok->isBinaryOperator() && !NextIsObjCMethod); 458 } 459 if (ProbablyBracedList) { 460 Tok->BlockKind = BK_BracedInit; 461 LBraceStack.back()->BlockKind = BK_BracedInit; 462 } else { 463 Tok->BlockKind = BK_Block; 464 LBraceStack.back()->BlockKind = BK_Block; 465 } 466 } 467 LBraceStack.pop_back(); 468 break; 469 case tok::at: 470 case tok::semi: 471 case tok::kw_if: 472 case tok::kw_while: 473 case tok::kw_for: 474 case tok::kw_switch: 475 case tok::kw_try: 476 case tok::kw___try: 477 if (!LBraceStack.empty() && LBraceStack.back()->BlockKind == BK_Unknown) 478 LBraceStack.back()->BlockKind = BK_Block; 479 break; 480 default: 481 break; 482 } 483 PrevTok = Tok; 484 Tok = NextTok; 485 } while (Tok->Tok.isNot(tok::eof) && !LBraceStack.empty()); 486 487 // Assume other blocks for all unclosed opening braces. 488 for (unsigned i = 0, e = LBraceStack.size(); i != e; ++i) { 489 if (LBraceStack[i]->BlockKind == BK_Unknown) 490 LBraceStack[i]->BlockKind = BK_Block; 491 } 492 493 FormatTok = Tokens->setPosition(StoredPosition); 494 } 495 496 template <class T> 497 static inline void hash_combine(std::size_t &seed, const T &v) { 498 std::hash<T> hasher; 499 seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); 500 } 501 502 size_t UnwrappedLineParser::computePPHash() const { 503 size_t h = 0; 504 for (const auto &i : PPStack) { 505 hash_combine(h, size_t(i.Kind)); 506 hash_combine(h, i.Line); 507 } 508 return h; 509 } 510 511 void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel, 512 bool MunchSemi) { 513 assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) && 514 "'{' or macro block token expected"); 515 const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin); 516 FormatTok->BlockKind = BK_Block; 517 518 size_t PPStartHash = computePPHash(); 519 520 unsigned InitialLevel = Line->Level; 521 nextToken(/*LevelDifference=*/AddLevel ? 1 : 0); 522 523 if (MacroBlock && FormatTok->is(tok::l_paren)) 524 parseParens(); 525 526 size_t NbPreprocessorDirectives = 527 CurrentLines == &Lines ? PreprocessorDirectives.size() : 0; 528 addUnwrappedLine(); 529 size_t OpeningLineIndex = 530 CurrentLines->empty() 531 ? (UnwrappedLine::kInvalidIndex) 532 : (CurrentLines->size() - 1 - NbPreprocessorDirectives); 533 534 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack, 535 MustBeDeclaration); 536 if (AddLevel) 537 ++Line->Level; 538 parseLevel(/*HasOpeningBrace=*/true); 539 540 if (eof()) 541 return; 542 543 if (MacroBlock ? !FormatTok->is(TT_MacroBlockEnd) 544 : !FormatTok->is(tok::r_brace)) { 545 Line->Level = InitialLevel; 546 FormatTok->BlockKind = BK_Block; 547 return; 548 } 549 550 size_t PPEndHash = computePPHash(); 551 552 // Munch the closing brace. 553 nextToken(/*LevelDifference=*/AddLevel ? -1 : 0); 554 555 if (MacroBlock && FormatTok->is(tok::l_paren)) 556 parseParens(); 557 558 if (MunchSemi && FormatTok->Tok.is(tok::semi)) 559 nextToken(); 560 Line->Level = InitialLevel; 561 562 if (PPStartHash == PPEndHash) { 563 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex; 564 if (OpeningLineIndex != UnwrappedLine::kInvalidIndex) { 565 // Update the opening line to add the forward reference as well 566 (*CurrentLines)[OpeningLineIndex].MatchingOpeningBlockLineIndex = 567 CurrentLines->size() - 1; 568 } 569 } 570 } 571 572 static bool isGoogScope(const UnwrappedLine &Line) { 573 // FIXME: Closure-library specific stuff should not be hard-coded but be 574 // configurable. 575 if (Line.Tokens.size() < 4) 576 return false; 577 auto I = Line.Tokens.begin(); 578 if (I->Tok->TokenText != "goog") 579 return false; 580 ++I; 581 if (I->Tok->isNot(tok::period)) 582 return false; 583 ++I; 584 if (I->Tok->TokenText != "scope") 585 return false; 586 ++I; 587 return I->Tok->is(tok::l_paren); 588 } 589 590 static bool isIIFE(const UnwrappedLine &Line, 591 const AdditionalKeywords &Keywords) { 592 // Look for the start of an immediately invoked anonymous function. 593 // https://en.wikipedia.org/wiki/Immediately-invoked_function_expression 594 // This is commonly done in JavaScript to create a new, anonymous scope. 595 // Example: (function() { ... })() 596 if (Line.Tokens.size() < 3) 597 return false; 598 auto I = Line.Tokens.begin(); 599 if (I->Tok->isNot(tok::l_paren)) 600 return false; 601 ++I; 602 if (I->Tok->isNot(Keywords.kw_function)) 603 return false; 604 ++I; 605 return I->Tok->is(tok::l_paren); 606 } 607 608 static bool ShouldBreakBeforeBrace(const FormatStyle &Style, 609 const FormatToken &InitialToken) { 610 if (InitialToken.is(tok::kw_namespace)) 611 return Style.BraceWrapping.AfterNamespace; 612 if (InitialToken.is(tok::kw_class)) 613 return Style.BraceWrapping.AfterClass; 614 if (InitialToken.is(tok::kw_union)) 615 return Style.BraceWrapping.AfterUnion; 616 if (InitialToken.is(tok::kw_struct)) 617 return Style.BraceWrapping.AfterStruct; 618 return false; 619 } 620 621 void UnwrappedLineParser::parseChildBlock() { 622 FormatTok->BlockKind = BK_Block; 623 nextToken(); 624 { 625 bool SkipIndent = (Style.Language == FormatStyle::LK_JavaScript && 626 (isGoogScope(*Line) || isIIFE(*Line, Keywords))); 627 ScopedLineState LineState(*this); 628 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack, 629 /*MustBeDeclaration=*/false); 630 Line->Level += SkipIndent ? 0 : 1; 631 parseLevel(/*HasOpeningBrace=*/true); 632 flushComments(isOnNewLine(*FormatTok)); 633 Line->Level -= SkipIndent ? 0 : 1; 634 } 635 nextToken(); 636 } 637 638 void UnwrappedLineParser::parsePPDirective() { 639 assert(FormatTok->Tok.is(tok::hash) && "'#' expected"); 640 ScopedMacroState MacroState(*Line, Tokens, FormatTok); 641 nextToken(); 642 643 if (!FormatTok->Tok.getIdentifierInfo()) { 644 parsePPUnknown(); 645 return; 646 } 647 648 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) { 649 case tok::pp_define: 650 parsePPDefine(); 651 return; 652 case tok::pp_if: 653 parsePPIf(/*IfDef=*/false); 654 break; 655 case tok::pp_ifdef: 656 case tok::pp_ifndef: 657 parsePPIf(/*IfDef=*/true); 658 break; 659 case tok::pp_else: 660 parsePPElse(); 661 break; 662 case tok::pp_elif: 663 parsePPElIf(); 664 break; 665 case tok::pp_endif: 666 parsePPEndIf(); 667 break; 668 default: 669 parsePPUnknown(); 670 break; 671 } 672 } 673 674 void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) { 675 size_t Line = CurrentLines->size(); 676 if (CurrentLines == &PreprocessorDirectives) 677 Line += Lines.size(); 678 679 if (Unreachable || 680 (!PPStack.empty() && PPStack.back().Kind == PP_Unreachable)) 681 PPStack.push_back({PP_Unreachable, Line}); 682 else 683 PPStack.push_back({PP_Conditional, Line}); 684 } 685 686 void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) { 687 ++PPBranchLevel; 688 assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size()); 689 if (PPBranchLevel == (int)PPLevelBranchIndex.size()) { 690 PPLevelBranchIndex.push_back(0); 691 PPLevelBranchCount.push_back(0); 692 } 693 PPChainBranchIndex.push(0); 694 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0; 695 conditionalCompilationCondition(Unreachable || Skip); 696 } 697 698 void UnwrappedLineParser::conditionalCompilationAlternative() { 699 if (!PPStack.empty()) 700 PPStack.pop_back(); 701 assert(PPBranchLevel < (int)PPLevelBranchIndex.size()); 702 if (!PPChainBranchIndex.empty()) 703 ++PPChainBranchIndex.top(); 704 conditionalCompilationCondition( 705 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() && 706 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top()); 707 } 708 709 void UnwrappedLineParser::conditionalCompilationEnd() { 710 assert(PPBranchLevel < (int)PPLevelBranchIndex.size()); 711 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) { 712 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) { 713 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1; 714 } 715 } 716 // Guard against #endif's without #if. 717 if (PPBranchLevel > -1) 718 --PPBranchLevel; 719 if (!PPChainBranchIndex.empty()) 720 PPChainBranchIndex.pop(); 721 if (!PPStack.empty()) 722 PPStack.pop_back(); 723 } 724 725 void UnwrappedLineParser::parsePPIf(bool IfDef) { 726 bool IfNDef = FormatTok->is(tok::pp_ifndef); 727 nextToken(); 728 bool Unreachable = false; 729 if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText == "0")) 730 Unreachable = true; 731 if (IfDef && !IfNDef && FormatTok->TokenText == "SWIG") 732 Unreachable = true; 733 conditionalCompilationStart(Unreachable); 734 FormatToken *IfCondition = FormatTok; 735 // If there's a #ifndef on the first line, and the only lines before it are 736 // comments, it could be an include guard. 737 bool MaybeIncludeGuard = IfNDef; 738 if (IncludeGuard == IG_Inited && MaybeIncludeGuard) 739 for (auto &Line : Lines) { 740 if (!Line.Tokens.front().Tok->is(tok::comment)) { 741 MaybeIncludeGuard = false; 742 IncludeGuard = IG_Rejected; 743 break; 744 } 745 } 746 --PPBranchLevel; 747 parsePPUnknown(); 748 ++PPBranchLevel; 749 if (IncludeGuard == IG_Inited && MaybeIncludeGuard) { 750 IncludeGuard = IG_IfNdefed; 751 IncludeGuardToken = IfCondition; 752 } 753 } 754 755 void UnwrappedLineParser::parsePPElse() { 756 // If a potential include guard has an #else, it's not an include guard. 757 if (IncludeGuard == IG_Defined && PPBranchLevel == 0) 758 IncludeGuard = IG_Rejected; 759 conditionalCompilationAlternative(); 760 if (PPBranchLevel > -1) 761 --PPBranchLevel; 762 parsePPUnknown(); 763 ++PPBranchLevel; 764 } 765 766 void UnwrappedLineParser::parsePPElIf() { parsePPElse(); } 767 768 void UnwrappedLineParser::parsePPEndIf() { 769 conditionalCompilationEnd(); 770 parsePPUnknown(); 771 // If the #endif of a potential include guard is the last thing in the file, 772 // then we found an include guard. 773 unsigned TokenPosition = Tokens->getPosition(); 774 FormatToken *PeekNext = AllTokens[TokenPosition]; 775 if (IncludeGuard == IG_Defined && PPBranchLevel == -1 && 776 PeekNext->is(tok::eof) && 777 Style.IndentPPDirectives != FormatStyle::PPDIS_None) 778 IncludeGuard = IG_Found; 779 } 780 781 void UnwrappedLineParser::parsePPDefine() { 782 nextToken(); 783 784 if (FormatTok->Tok.getKind() != tok::identifier) { 785 IncludeGuard = IG_Rejected; 786 IncludeGuardToken = nullptr; 787 parsePPUnknown(); 788 return; 789 } 790 791 if (IncludeGuard == IG_IfNdefed && 792 IncludeGuardToken->TokenText == FormatTok->TokenText) { 793 IncludeGuard = IG_Defined; 794 IncludeGuardToken = nullptr; 795 for (auto &Line : Lines) { 796 if (!Line.Tokens.front().Tok->isOneOf(tok::comment, tok::hash)) { 797 IncludeGuard = IG_Rejected; 798 break; 799 } 800 } 801 } 802 803 nextToken(); 804 if (FormatTok->Tok.getKind() == tok::l_paren && 805 FormatTok->WhitespaceRange.getBegin() == 806 FormatTok->WhitespaceRange.getEnd()) { 807 parseParens(); 808 } 809 if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash) 810 Line->Level += PPBranchLevel + 1; 811 addUnwrappedLine(); 812 ++Line->Level; 813 814 // Errors during a preprocessor directive can only affect the layout of the 815 // preprocessor directive, and thus we ignore them. An alternative approach 816 // would be to use the same approach we use on the file level (no 817 // re-indentation if there was a structural error) within the macro 818 // definition. 819 parseFile(); 820 } 821 822 void UnwrappedLineParser::parsePPUnknown() { 823 do { 824 nextToken(); 825 } while (!eof()); 826 if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash) 827 Line->Level += PPBranchLevel + 1; 828 addUnwrappedLine(); 829 } 830 831 // Here we blacklist certain tokens that are not usually the first token in an 832 // unwrapped line. This is used in attempt to distinguish macro calls without 833 // trailing semicolons from other constructs split to several lines. 834 static bool tokenCanStartNewLine(const clang::Token &Tok) { 835 // Semicolon can be a null-statement, l_square can be a start of a macro or 836 // a C++11 attribute, but this doesn't seem to be common. 837 return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) && 838 Tok.isNot(tok::l_square) && 839 // Tokens that can only be used as binary operators and a part of 840 // overloaded operator names. 841 Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) && 842 Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) && 843 Tok.isNot(tok::less) && Tok.isNot(tok::greater) && 844 Tok.isNot(tok::slash) && Tok.isNot(tok::percent) && 845 Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) && 846 Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) && 847 Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) && 848 Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) && 849 Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) && 850 Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) && 851 Tok.isNot(tok::lesslessequal) && 852 // Colon is used in labels, base class lists, initializer lists, 853 // range-based for loops, ternary operator, but should never be the 854 // first token in an unwrapped line. 855 Tok.isNot(tok::colon) && 856 // 'noexcept' is a trailing annotation. 857 Tok.isNot(tok::kw_noexcept); 858 } 859 860 static bool mustBeJSIdent(const AdditionalKeywords &Keywords, 861 const FormatToken *FormatTok) { 862 // FIXME: This returns true for C/C++ keywords like 'struct'. 863 return FormatTok->is(tok::identifier) && 864 (FormatTok->Tok.getIdentifierInfo() == nullptr || 865 !FormatTok->isOneOf( 866 Keywords.kw_in, Keywords.kw_of, Keywords.kw_as, Keywords.kw_async, 867 Keywords.kw_await, Keywords.kw_yield, Keywords.kw_finally, 868 Keywords.kw_function, Keywords.kw_import, Keywords.kw_is, 869 Keywords.kw_let, Keywords.kw_var, tok::kw_const, 870 Keywords.kw_abstract, Keywords.kw_extends, Keywords.kw_implements, 871 Keywords.kw_instanceof, Keywords.kw_interface, Keywords.kw_throws, 872 Keywords.kw_from)); 873 } 874 875 static bool mustBeJSIdentOrValue(const AdditionalKeywords &Keywords, 876 const FormatToken *FormatTok) { 877 return FormatTok->Tok.isLiteral() || 878 FormatTok->isOneOf(tok::kw_true, tok::kw_false) || 879 mustBeJSIdent(Keywords, FormatTok); 880 } 881 882 // isJSDeclOrStmt returns true if |FormatTok| starts a declaration or statement 883 // when encountered after a value (see mustBeJSIdentOrValue). 884 static bool isJSDeclOrStmt(const AdditionalKeywords &Keywords, 885 const FormatToken *FormatTok) { 886 return FormatTok->isOneOf( 887 tok::kw_return, Keywords.kw_yield, 888 // conditionals 889 tok::kw_if, tok::kw_else, 890 // loops 891 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break, 892 // switch/case 893 tok::kw_switch, tok::kw_case, 894 // exceptions 895 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.kw_finally, 896 // declaration 897 tok::kw_const, tok::kw_class, Keywords.kw_var, Keywords.kw_let, 898 Keywords.kw_async, Keywords.kw_function, 899 // import/export 900 Keywords.kw_import, tok::kw_export); 901 } 902 903 // readTokenWithJavaScriptASI reads the next token and terminates the current 904 // line if JavaScript Automatic Semicolon Insertion must 905 // happen between the current token and the next token. 906 // 907 // This method is conservative - it cannot cover all edge cases of JavaScript, 908 // but only aims to correctly handle certain well known cases. It *must not* 909 // return true in speculative cases. 910 void UnwrappedLineParser::readTokenWithJavaScriptASI() { 911 FormatToken *Previous = FormatTok; 912 readToken(); 913 FormatToken *Next = FormatTok; 914 915 bool IsOnSameLine = 916 CommentsBeforeNextToken.empty() 917 ? Next->NewlinesBefore == 0 918 : CommentsBeforeNextToken.front()->NewlinesBefore == 0; 919 if (IsOnSameLine) 920 return; 921 922 bool PreviousMustBeValue = mustBeJSIdentOrValue(Keywords, Previous); 923 bool PreviousStartsTemplateExpr = 924 Previous->is(TT_TemplateString) && Previous->TokenText.endswith("${"); 925 if (PreviousMustBeValue || Previous->is(tok::r_paren)) { 926 // If the line contains an '@' sign, the previous token might be an 927 // annotation, which can precede another identifier/value. 928 bool HasAt = std::find_if(Line->Tokens.begin(), Line->Tokens.end(), 929 [](UnwrappedLineNode &LineNode) { 930 return LineNode.Tok->is(tok::at); 931 }) != Line->Tokens.end(); 932 if (HasAt) 933 return; 934 } 935 if (Next->is(tok::exclaim) && PreviousMustBeValue) 936 return addUnwrappedLine(); 937 bool NextMustBeValue = mustBeJSIdentOrValue(Keywords, Next); 938 bool NextEndsTemplateExpr = 939 Next->is(TT_TemplateString) && Next->TokenText.startswith("}"); 940 if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr && 941 (PreviousMustBeValue || 942 Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus, 943 tok::minusminus))) 944 return addUnwrappedLine(); 945 if ((PreviousMustBeValue || Previous->is(tok::r_paren)) && 946 isJSDeclOrStmt(Keywords, Next)) 947 return addUnwrappedLine(); 948 } 949 950 void UnwrappedLineParser::parseStructuralElement() { 951 assert(!FormatTok->is(tok::l_brace)); 952 if (Style.Language == FormatStyle::LK_TableGen && 953 FormatTok->is(tok::pp_include)) { 954 nextToken(); 955 if (FormatTok->is(tok::string_literal)) 956 nextToken(); 957 addUnwrappedLine(); 958 return; 959 } 960 switch (FormatTok->Tok.getKind()) { 961 case tok::kw_asm: 962 nextToken(); 963 if (FormatTok->is(tok::l_brace)) { 964 FormatTok->Type = TT_InlineASMBrace; 965 nextToken(); 966 while (FormatTok && FormatTok->isNot(tok::eof)) { 967 if (FormatTok->is(tok::r_brace)) { 968 FormatTok->Type = TT_InlineASMBrace; 969 nextToken(); 970 addUnwrappedLine(); 971 break; 972 } 973 FormatTok->Finalized = true; 974 nextToken(); 975 } 976 } 977 break; 978 case tok::kw_namespace: 979 parseNamespace(); 980 return; 981 case tok::kw_inline: 982 nextToken(); 983 if (FormatTok->Tok.is(tok::kw_namespace)) { 984 parseNamespace(); 985 return; 986 } 987 break; 988 case tok::kw_public: 989 case tok::kw_protected: 990 case tok::kw_private: 991 if (Style.Language == FormatStyle::LK_Java || 992 Style.Language == FormatStyle::LK_JavaScript) 993 nextToken(); 994 else 995 parseAccessSpecifier(); 996 return; 997 case tok::kw_if: 998 parseIfThenElse(); 999 return; 1000 case tok::kw_for: 1001 case tok::kw_while: 1002 parseForOrWhileLoop(); 1003 return; 1004 case tok::kw_do: 1005 parseDoWhile(); 1006 return; 1007 case tok::kw_switch: 1008 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration) 1009 // 'switch: string' field declaration. 1010 break; 1011 parseSwitch(); 1012 return; 1013 case tok::kw_default: 1014 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration) 1015 // 'default: string' field declaration. 1016 break; 1017 nextToken(); 1018 if (FormatTok->is(tok::colon)) { 1019 parseLabel(); 1020 return; 1021 } 1022 // e.g. "default void f() {}" in a Java interface. 1023 break; 1024 case tok::kw_case: 1025 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration) 1026 // 'case: string' field declaration. 1027 break; 1028 parseCaseLabel(); 1029 return; 1030 case tok::kw_try: 1031 case tok::kw___try: 1032 parseTryCatch(); 1033 return; 1034 case tok::kw_extern: 1035 nextToken(); 1036 if (FormatTok->Tok.is(tok::string_literal)) { 1037 nextToken(); 1038 if (FormatTok->Tok.is(tok::l_brace)) { 1039 if (Style.BraceWrapping.AfterExternBlock) { 1040 addUnwrappedLine(); 1041 parseBlock(/*MustBeDeclaration=*/true); 1042 } else { 1043 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false); 1044 } 1045 addUnwrappedLine(); 1046 return; 1047 } 1048 } 1049 break; 1050 case tok::kw_export: 1051 if (Style.Language == FormatStyle::LK_JavaScript) { 1052 parseJavaScriptEs6ImportExport(); 1053 return; 1054 } 1055 break; 1056 case tok::identifier: 1057 if (FormatTok->is(TT_ForEachMacro)) { 1058 parseForOrWhileLoop(); 1059 return; 1060 } 1061 if (FormatTok->is(TT_MacroBlockBegin)) { 1062 parseBlock(/*MustBeDeclaration=*/false, /*AddLevel=*/true, 1063 /*MunchSemi=*/false); 1064 return; 1065 } 1066 if (FormatTok->is(Keywords.kw_import)) { 1067 if (Style.Language == FormatStyle::LK_JavaScript) { 1068 parseJavaScriptEs6ImportExport(); 1069 return; 1070 } 1071 if (Style.Language == FormatStyle::LK_Proto) { 1072 nextToken(); 1073 if (FormatTok->is(tok::kw_public)) 1074 nextToken(); 1075 if (!FormatTok->is(tok::string_literal)) 1076 return; 1077 nextToken(); 1078 if (FormatTok->is(tok::semi)) 1079 nextToken(); 1080 addUnwrappedLine(); 1081 return; 1082 } 1083 } 1084 if (Style.isCpp() && 1085 FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals, 1086 Keywords.kw_slots, Keywords.kw_qslots)) { 1087 nextToken(); 1088 if (FormatTok->is(tok::colon)) { 1089 nextToken(); 1090 addUnwrappedLine(); 1091 return; 1092 } 1093 } 1094 // In all other cases, parse the declaration. 1095 break; 1096 default: 1097 break; 1098 } 1099 do { 1100 const FormatToken *Previous = FormatTok->Previous; 1101 switch (FormatTok->Tok.getKind()) { 1102 case tok::at: 1103 nextToken(); 1104 if (FormatTok->Tok.is(tok::l_brace)) { 1105 nextToken(); 1106 parseBracedList(); 1107 break; 1108 } 1109 switch (FormatTok->Tok.getObjCKeywordID()) { 1110 case tok::objc_public: 1111 case tok::objc_protected: 1112 case tok::objc_package: 1113 case tok::objc_private: 1114 return parseAccessSpecifier(); 1115 case tok::objc_interface: 1116 case tok::objc_implementation: 1117 return parseObjCInterfaceOrImplementation(); 1118 case tok::objc_protocol: 1119 if (parseObjCProtocol()) 1120 return; 1121 break; 1122 case tok::objc_end: 1123 return; // Handled by the caller. 1124 case tok::objc_optional: 1125 case tok::objc_required: 1126 nextToken(); 1127 addUnwrappedLine(); 1128 return; 1129 case tok::objc_autoreleasepool: 1130 nextToken(); 1131 if (FormatTok->Tok.is(tok::l_brace)) { 1132 if (Style.BraceWrapping.AfterControlStatement) 1133 addUnwrappedLine(); 1134 parseBlock(/*MustBeDeclaration=*/false); 1135 } 1136 addUnwrappedLine(); 1137 return; 1138 case tok::objc_synchronized: 1139 nextToken(); 1140 if (FormatTok->Tok.is(tok::l_paren)) 1141 // Skip synchronization object 1142 parseParens(); 1143 if (FormatTok->Tok.is(tok::l_brace)) { 1144 if (Style.BraceWrapping.AfterControlStatement) 1145 addUnwrappedLine(); 1146 parseBlock(/*MustBeDeclaration=*/false); 1147 } 1148 addUnwrappedLine(); 1149 return; 1150 case tok::objc_try: 1151 // This branch isn't strictly necessary (the kw_try case below would 1152 // do this too after the tok::at is parsed above). But be explicit. 1153 parseTryCatch(); 1154 return; 1155 default: 1156 break; 1157 } 1158 break; 1159 case tok::kw_enum: 1160 // Ignore if this is part of "template <enum ...". 1161 if (Previous && Previous->is(tok::less)) { 1162 nextToken(); 1163 break; 1164 } 1165 1166 // parseEnum falls through and does not yet add an unwrapped line as an 1167 // enum definition can start a structural element. 1168 if (!parseEnum()) 1169 break; 1170 // This only applies for C++. 1171 if (!Style.isCpp()) { 1172 addUnwrappedLine(); 1173 return; 1174 } 1175 break; 1176 case tok::kw_typedef: 1177 nextToken(); 1178 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS, 1179 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS)) 1180 parseEnum(); 1181 break; 1182 case tok::kw_struct: 1183 case tok::kw_union: 1184 case tok::kw_class: 1185 // parseRecord falls through and does not yet add an unwrapped line as a 1186 // record declaration or definition can start a structural element. 1187 parseRecord(); 1188 // This does not apply for Java and JavaScript. 1189 if (Style.Language == FormatStyle::LK_Java || 1190 Style.Language == FormatStyle::LK_JavaScript) { 1191 if (FormatTok->is(tok::semi)) 1192 nextToken(); 1193 addUnwrappedLine(); 1194 return; 1195 } 1196 break; 1197 case tok::period: 1198 nextToken(); 1199 // In Java, classes have an implicit static member "class". 1200 if (Style.Language == FormatStyle::LK_Java && FormatTok && 1201 FormatTok->is(tok::kw_class)) 1202 nextToken(); 1203 if (Style.Language == FormatStyle::LK_JavaScript && FormatTok && 1204 FormatTok->Tok.getIdentifierInfo()) 1205 // JavaScript only has pseudo keywords, all keywords are allowed to 1206 // appear in "IdentifierName" positions. See http://es5.github.io/#x7.6 1207 nextToken(); 1208 break; 1209 case tok::semi: 1210 nextToken(); 1211 addUnwrappedLine(); 1212 return; 1213 case tok::r_brace: 1214 addUnwrappedLine(); 1215 return; 1216 case tok::l_paren: 1217 parseParens(); 1218 break; 1219 case tok::kw_operator: 1220 nextToken(); 1221 if (FormatTok->isBinaryOperator()) 1222 nextToken(); 1223 break; 1224 case tok::caret: 1225 nextToken(); 1226 if (FormatTok->Tok.isAnyIdentifier() || 1227 FormatTok->isSimpleTypeSpecifier()) 1228 nextToken(); 1229 if (FormatTok->is(tok::l_paren)) 1230 parseParens(); 1231 if (FormatTok->is(tok::l_brace)) 1232 parseChildBlock(); 1233 break; 1234 case tok::l_brace: 1235 if (!tryToParseBracedList()) { 1236 // A block outside of parentheses must be the last part of a 1237 // structural element. 1238 // FIXME: Figure out cases where this is not true, and add projections 1239 // for them (the one we know is missing are lambdas). 1240 if (Style.BraceWrapping.AfterFunction) 1241 addUnwrappedLine(); 1242 FormatTok->Type = TT_FunctionLBrace; 1243 parseBlock(/*MustBeDeclaration=*/false); 1244 addUnwrappedLine(); 1245 return; 1246 } 1247 // Otherwise this was a braced init list, and the structural 1248 // element continues. 1249 break; 1250 case tok::kw_try: 1251 // We arrive here when parsing function-try blocks. 1252 parseTryCatch(); 1253 return; 1254 case tok::identifier: { 1255 if (FormatTok->is(TT_MacroBlockEnd)) { 1256 addUnwrappedLine(); 1257 return; 1258 } 1259 1260 // Function declarations (as opposed to function expressions) are parsed 1261 // on their own unwrapped line by continuing this loop. Function 1262 // expressions (functions that are not on their own line) must not create 1263 // a new unwrapped line, so they are special cased below. 1264 size_t TokenCount = Line->Tokens.size(); 1265 if (Style.Language == FormatStyle::LK_JavaScript && 1266 FormatTok->is(Keywords.kw_function) && 1267 (TokenCount > 1 || (TokenCount == 1 && !Line->Tokens.front().Tok->is( 1268 Keywords.kw_async)))) { 1269 tryToParseJSFunction(); 1270 break; 1271 } 1272 if ((Style.Language == FormatStyle::LK_JavaScript || 1273 Style.Language == FormatStyle::LK_Java) && 1274 FormatTok->is(Keywords.kw_interface)) { 1275 if (Style.Language == FormatStyle::LK_JavaScript) { 1276 // In JavaScript/TypeScript, "interface" can be used as a standalone 1277 // identifier, e.g. in `var interface = 1;`. If "interface" is 1278 // followed by another identifier, it is very like to be an actual 1279 // interface declaration. 1280 unsigned StoredPosition = Tokens->getPosition(); 1281 FormatToken *Next = Tokens->getNextToken(); 1282 FormatTok = Tokens->setPosition(StoredPosition); 1283 if (Next && !mustBeJSIdent(Keywords, Next)) { 1284 nextToken(); 1285 break; 1286 } 1287 } 1288 parseRecord(); 1289 addUnwrappedLine(); 1290 return; 1291 } 1292 1293 // See if the following token should start a new unwrapped line. 1294 StringRef Text = FormatTok->TokenText; 1295 nextToken(); 1296 if (Line->Tokens.size() == 1 && 1297 // JS doesn't have macros, and within classes colons indicate fields, 1298 // not labels. 1299 Style.Language != FormatStyle::LK_JavaScript) { 1300 if (FormatTok->Tok.is(tok::colon) && !Line->MustBeDeclaration) { 1301 Line->Tokens.begin()->Tok->MustBreakBefore = true; 1302 parseLabel(); 1303 return; 1304 } 1305 // Recognize function-like macro usages without trailing semicolon as 1306 // well as free-standing macros like Q_OBJECT. 1307 bool FunctionLike = FormatTok->is(tok::l_paren); 1308 if (FunctionLike) 1309 parseParens(); 1310 1311 bool FollowedByNewline = 1312 CommentsBeforeNextToken.empty() 1313 ? FormatTok->NewlinesBefore > 0 1314 : CommentsBeforeNextToken.front()->NewlinesBefore > 0; 1315 1316 if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) && 1317 tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) { 1318 addUnwrappedLine(); 1319 return; 1320 } 1321 } 1322 break; 1323 } 1324 case tok::equal: 1325 // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType 1326 // TT_JsFatArrow. The always start an expression or a child block if 1327 // followed by a curly. 1328 if (FormatTok->is(TT_JsFatArrow)) { 1329 nextToken(); 1330 if (FormatTok->is(tok::l_brace)) 1331 parseChildBlock(); 1332 break; 1333 } 1334 1335 nextToken(); 1336 if (FormatTok->Tok.is(tok::l_brace)) { 1337 nextToken(); 1338 parseBracedList(); 1339 } else if (Style.Language == FormatStyle::LK_Proto && 1340 FormatTok->Tok.is(tok::less)) { 1341 nextToken(); 1342 parseBracedList(/*ContinueOnSemicolons=*/false, 1343 /*ClosingBraceKind=*/tok::greater); 1344 } 1345 break; 1346 case tok::l_square: 1347 parseSquare(); 1348 break; 1349 case tok::kw_new: 1350 parseNew(); 1351 break; 1352 default: 1353 nextToken(); 1354 break; 1355 } 1356 } while (!eof()); 1357 } 1358 1359 bool UnwrappedLineParser::tryToParseLambda() { 1360 if (!Style.isCpp()) { 1361 nextToken(); 1362 return false; 1363 } 1364 assert(FormatTok->is(tok::l_square)); 1365 FormatToken &LSquare = *FormatTok; 1366 if (!tryToParseLambdaIntroducer()) 1367 return false; 1368 1369 while (FormatTok->isNot(tok::l_brace)) { 1370 if (FormatTok->isSimpleTypeSpecifier()) { 1371 nextToken(); 1372 continue; 1373 } 1374 switch (FormatTok->Tok.getKind()) { 1375 case tok::l_brace: 1376 break; 1377 case tok::l_paren: 1378 parseParens(); 1379 break; 1380 case tok::amp: 1381 case tok::star: 1382 case tok::kw_const: 1383 case tok::comma: 1384 case tok::less: 1385 case tok::greater: 1386 case tok::identifier: 1387 case tok::numeric_constant: 1388 case tok::coloncolon: 1389 case tok::kw_mutable: 1390 nextToken(); 1391 break; 1392 case tok::arrow: 1393 FormatTok->Type = TT_LambdaArrow; 1394 nextToken(); 1395 break; 1396 default: 1397 return true; 1398 } 1399 } 1400 LSquare.Type = TT_LambdaLSquare; 1401 parseChildBlock(); 1402 return true; 1403 } 1404 1405 bool UnwrappedLineParser::tryToParseLambdaIntroducer() { 1406 const FormatToken *Previous = FormatTok->Previous; 1407 if (Previous && 1408 (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new, 1409 tok::kw_delete) || 1410 FormatTok->isCppStructuredBinding(Style) || Previous->closesScope() || 1411 Previous->isSimpleTypeSpecifier())) { 1412 nextToken(); 1413 return false; 1414 } 1415 nextToken(); 1416 parseSquare(/*LambdaIntroducer=*/true); 1417 return true; 1418 } 1419 1420 void UnwrappedLineParser::tryToParseJSFunction() { 1421 assert(FormatTok->is(Keywords.kw_function) || 1422 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)); 1423 if (FormatTok->is(Keywords.kw_async)) 1424 nextToken(); 1425 // Consume "function". 1426 nextToken(); 1427 1428 // Consume * (generator function). Treat it like C++'s overloaded operators. 1429 if (FormatTok->is(tok::star)) { 1430 FormatTok->Type = TT_OverloadedOperator; 1431 nextToken(); 1432 } 1433 1434 // Consume function name. 1435 if (FormatTok->is(tok::identifier)) 1436 nextToken(); 1437 1438 if (FormatTok->isNot(tok::l_paren)) 1439 return; 1440 1441 // Parse formal parameter list. 1442 parseParens(); 1443 1444 if (FormatTok->is(tok::colon)) { 1445 // Parse a type definition. 1446 nextToken(); 1447 1448 // Eat the type declaration. For braced inline object types, balance braces, 1449 // otherwise just parse until finding an l_brace for the function body. 1450 if (FormatTok->is(tok::l_brace)) 1451 tryToParseBracedList(); 1452 else 1453 while (!FormatTok->isOneOf(tok::l_brace, tok::semi) && !eof()) 1454 nextToken(); 1455 } 1456 1457 if (FormatTok->is(tok::semi)) 1458 return; 1459 1460 parseChildBlock(); 1461 } 1462 1463 bool UnwrappedLineParser::tryToParseBracedList() { 1464 if (FormatTok->BlockKind == BK_Unknown) 1465 calculateBraceTypes(); 1466 assert(FormatTok->BlockKind != BK_Unknown); 1467 if (FormatTok->BlockKind == BK_Block) 1468 return false; 1469 nextToken(); 1470 parseBracedList(); 1471 return true; 1472 } 1473 1474 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons, 1475 tok::TokenKind ClosingBraceKind) { 1476 bool HasError = false; 1477 1478 // FIXME: Once we have an expression parser in the UnwrappedLineParser, 1479 // replace this by using parseAssigmentExpression() inside. 1480 do { 1481 if (Style.Language == FormatStyle::LK_JavaScript) { 1482 if (FormatTok->is(Keywords.kw_function) || 1483 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) { 1484 tryToParseJSFunction(); 1485 continue; 1486 } 1487 if (FormatTok->is(TT_JsFatArrow)) { 1488 nextToken(); 1489 // Fat arrows can be followed by simple expressions or by child blocks 1490 // in curly braces. 1491 if (FormatTok->is(tok::l_brace)) { 1492 parseChildBlock(); 1493 continue; 1494 } 1495 } 1496 if (FormatTok->is(tok::l_brace)) { 1497 // Could be a method inside of a braced list `{a() { return 1; }}`. 1498 if (tryToParseBracedList()) 1499 continue; 1500 parseChildBlock(); 1501 } 1502 } 1503 if (FormatTok->Tok.getKind() == ClosingBraceKind) { 1504 nextToken(); 1505 return !HasError; 1506 } 1507 switch (FormatTok->Tok.getKind()) { 1508 case tok::caret: 1509 nextToken(); 1510 if (FormatTok->is(tok::l_brace)) { 1511 parseChildBlock(); 1512 } 1513 break; 1514 case tok::l_square: 1515 tryToParseLambda(); 1516 break; 1517 case tok::l_paren: 1518 parseParens(); 1519 // JavaScript can just have free standing methods and getters/setters in 1520 // object literals. Detect them by a "{" following ")". 1521 if (Style.Language == FormatStyle::LK_JavaScript) { 1522 if (FormatTok->is(tok::l_brace)) 1523 parseChildBlock(); 1524 break; 1525 } 1526 break; 1527 case tok::l_brace: 1528 // Assume there are no blocks inside a braced init list apart 1529 // from the ones we explicitly parse out (like lambdas). 1530 FormatTok->BlockKind = BK_BracedInit; 1531 nextToken(); 1532 parseBracedList(); 1533 break; 1534 case tok::less: 1535 if (Style.Language == FormatStyle::LK_Proto) { 1536 nextToken(); 1537 parseBracedList(/*ContinueOnSemicolons=*/false, 1538 /*ClosingBraceKind=*/tok::greater); 1539 } else { 1540 nextToken(); 1541 } 1542 break; 1543 case tok::semi: 1544 // JavaScript (or more precisely TypeScript) can have semicolons in braced 1545 // lists (in so-called TypeMemberLists). Thus, the semicolon cannot be 1546 // used for error recovery if we have otherwise determined that this is 1547 // a braced list. 1548 if (Style.Language == FormatStyle::LK_JavaScript) { 1549 nextToken(); 1550 break; 1551 } 1552 HasError = true; 1553 if (!ContinueOnSemicolons) 1554 return !HasError; 1555 nextToken(); 1556 break; 1557 case tok::comma: 1558 nextToken(); 1559 break; 1560 default: 1561 nextToken(); 1562 break; 1563 } 1564 } while (!eof()); 1565 return false; 1566 } 1567 1568 void UnwrappedLineParser::parseParens() { 1569 assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected."); 1570 nextToken(); 1571 do { 1572 switch (FormatTok->Tok.getKind()) { 1573 case tok::l_paren: 1574 parseParens(); 1575 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace)) 1576 parseChildBlock(); 1577 break; 1578 case tok::r_paren: 1579 nextToken(); 1580 return; 1581 case tok::r_brace: 1582 // A "}" inside parenthesis is an error if there wasn't a matching "{". 1583 return; 1584 case tok::l_square: 1585 tryToParseLambda(); 1586 break; 1587 case tok::l_brace: 1588 if (!tryToParseBracedList()) 1589 parseChildBlock(); 1590 break; 1591 case tok::at: 1592 nextToken(); 1593 if (FormatTok->Tok.is(tok::l_brace)) { 1594 nextToken(); 1595 parseBracedList(); 1596 } 1597 break; 1598 case tok::kw_class: 1599 if (Style.Language == FormatStyle::LK_JavaScript) 1600 parseRecord(/*ParseAsExpr=*/true); 1601 else 1602 nextToken(); 1603 break; 1604 case tok::identifier: 1605 if (Style.Language == FormatStyle::LK_JavaScript && 1606 (FormatTok->is(Keywords.kw_function) || 1607 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function))) 1608 tryToParseJSFunction(); 1609 else 1610 nextToken(); 1611 break; 1612 default: 1613 nextToken(); 1614 break; 1615 } 1616 } while (!eof()); 1617 } 1618 1619 void UnwrappedLineParser::parseSquare(bool LambdaIntroducer) { 1620 if (!LambdaIntroducer) { 1621 assert(FormatTok->Tok.is(tok::l_square) && "'[' expected."); 1622 if (tryToParseLambda()) 1623 return; 1624 } 1625 do { 1626 switch (FormatTok->Tok.getKind()) { 1627 case tok::l_paren: 1628 parseParens(); 1629 break; 1630 case tok::r_square: 1631 nextToken(); 1632 return; 1633 case tok::r_brace: 1634 // A "}" inside parenthesis is an error if there wasn't a matching "{". 1635 return; 1636 case tok::l_square: 1637 parseSquare(); 1638 break; 1639 case tok::l_brace: { 1640 if (!tryToParseBracedList()) 1641 parseChildBlock(); 1642 break; 1643 } 1644 case tok::at: 1645 nextToken(); 1646 if (FormatTok->Tok.is(tok::l_brace)) { 1647 nextToken(); 1648 parseBracedList(); 1649 } 1650 break; 1651 default: 1652 nextToken(); 1653 break; 1654 } 1655 } while (!eof()); 1656 } 1657 1658 void UnwrappedLineParser::parseIfThenElse() { 1659 assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected"); 1660 nextToken(); 1661 if (FormatTok->Tok.is(tok::kw_constexpr)) 1662 nextToken(); 1663 if (FormatTok->Tok.is(tok::l_paren)) 1664 parseParens(); 1665 bool NeedsUnwrappedLine = false; 1666 if (FormatTok->Tok.is(tok::l_brace)) { 1667 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1668 parseBlock(/*MustBeDeclaration=*/false); 1669 if (Style.BraceWrapping.BeforeElse) 1670 addUnwrappedLine(); 1671 else 1672 NeedsUnwrappedLine = true; 1673 } else { 1674 addUnwrappedLine(); 1675 ++Line->Level; 1676 parseStructuralElement(); 1677 --Line->Level; 1678 } 1679 if (FormatTok->Tok.is(tok::kw_else)) { 1680 nextToken(); 1681 if (FormatTok->Tok.is(tok::l_brace)) { 1682 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1683 parseBlock(/*MustBeDeclaration=*/false); 1684 addUnwrappedLine(); 1685 } else if (FormatTok->Tok.is(tok::kw_if)) { 1686 parseIfThenElse(); 1687 } else { 1688 addUnwrappedLine(); 1689 ++Line->Level; 1690 parseStructuralElement(); 1691 if (FormatTok->is(tok::eof)) 1692 addUnwrappedLine(); 1693 --Line->Level; 1694 } 1695 } else if (NeedsUnwrappedLine) { 1696 addUnwrappedLine(); 1697 } 1698 } 1699 1700 void UnwrappedLineParser::parseTryCatch() { 1701 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected"); 1702 nextToken(); 1703 bool NeedsUnwrappedLine = false; 1704 if (FormatTok->is(tok::colon)) { 1705 // We are in a function try block, what comes is an initializer list. 1706 nextToken(); 1707 while (FormatTok->is(tok::identifier)) { 1708 nextToken(); 1709 if (FormatTok->is(tok::l_paren)) 1710 parseParens(); 1711 if (FormatTok->is(tok::comma)) 1712 nextToken(); 1713 } 1714 } 1715 // Parse try with resource. 1716 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) { 1717 parseParens(); 1718 } 1719 if (FormatTok->is(tok::l_brace)) { 1720 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1721 parseBlock(/*MustBeDeclaration=*/false); 1722 if (Style.BraceWrapping.BeforeCatch) { 1723 addUnwrappedLine(); 1724 } else { 1725 NeedsUnwrappedLine = true; 1726 } 1727 } else if (!FormatTok->is(tok::kw_catch)) { 1728 // The C++ standard requires a compound-statement after a try. 1729 // If there's none, we try to assume there's a structuralElement 1730 // and try to continue. 1731 addUnwrappedLine(); 1732 ++Line->Level; 1733 parseStructuralElement(); 1734 --Line->Level; 1735 } 1736 while (1) { 1737 if (FormatTok->is(tok::at)) 1738 nextToken(); 1739 if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except, 1740 tok::kw___finally) || 1741 ((Style.Language == FormatStyle::LK_Java || 1742 Style.Language == FormatStyle::LK_JavaScript) && 1743 FormatTok->is(Keywords.kw_finally)) || 1744 (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) || 1745 FormatTok->Tok.isObjCAtKeyword(tok::objc_finally)))) 1746 break; 1747 nextToken(); 1748 while (FormatTok->isNot(tok::l_brace)) { 1749 if (FormatTok->is(tok::l_paren)) { 1750 parseParens(); 1751 continue; 1752 } 1753 if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof)) 1754 return; 1755 nextToken(); 1756 } 1757 NeedsUnwrappedLine = false; 1758 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1759 parseBlock(/*MustBeDeclaration=*/false); 1760 if (Style.BraceWrapping.BeforeCatch) 1761 addUnwrappedLine(); 1762 else 1763 NeedsUnwrappedLine = true; 1764 } 1765 if (NeedsUnwrappedLine) 1766 addUnwrappedLine(); 1767 } 1768 1769 void UnwrappedLineParser::parseNamespace() { 1770 assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected"); 1771 1772 const FormatToken &InitialToken = *FormatTok; 1773 nextToken(); 1774 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon)) 1775 nextToken(); 1776 if (FormatTok->Tok.is(tok::l_brace)) { 1777 if (ShouldBreakBeforeBrace(Style, InitialToken)) 1778 addUnwrappedLine(); 1779 1780 bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All || 1781 (Style.NamespaceIndentation == FormatStyle::NI_Inner && 1782 DeclarationScopeStack.size() > 1); 1783 parseBlock(/*MustBeDeclaration=*/true, AddLevel); 1784 // Munch the semicolon after a namespace. This is more common than one would 1785 // think. Puttin the semicolon into its own line is very ugly. 1786 if (FormatTok->Tok.is(tok::semi)) 1787 nextToken(); 1788 addUnwrappedLine(); 1789 } 1790 // FIXME: Add error handling. 1791 } 1792 1793 void UnwrappedLineParser::parseNew() { 1794 assert(FormatTok->is(tok::kw_new) && "'new' expected"); 1795 nextToken(); 1796 if (Style.Language != FormatStyle::LK_Java) 1797 return; 1798 1799 // In Java, we can parse everything up to the parens, which aren't optional. 1800 do { 1801 // There should not be a ;, { or } before the new's open paren. 1802 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace)) 1803 return; 1804 1805 // Consume the parens. 1806 if (FormatTok->is(tok::l_paren)) { 1807 parseParens(); 1808 1809 // If there is a class body of an anonymous class, consume that as child. 1810 if (FormatTok->is(tok::l_brace)) 1811 parseChildBlock(); 1812 return; 1813 } 1814 nextToken(); 1815 } while (!eof()); 1816 } 1817 1818 void UnwrappedLineParser::parseForOrWhileLoop() { 1819 assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) && 1820 "'for', 'while' or foreach macro expected"); 1821 nextToken(); 1822 // JS' for await ( ... 1823 if (Style.Language == FormatStyle::LK_JavaScript && 1824 FormatTok->is(Keywords.kw_await)) 1825 nextToken(); 1826 if (FormatTok->Tok.is(tok::l_paren)) 1827 parseParens(); 1828 if (FormatTok->Tok.is(tok::l_brace)) { 1829 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1830 parseBlock(/*MustBeDeclaration=*/false); 1831 addUnwrappedLine(); 1832 } else { 1833 addUnwrappedLine(); 1834 ++Line->Level; 1835 parseStructuralElement(); 1836 --Line->Level; 1837 } 1838 } 1839 1840 void UnwrappedLineParser::parseDoWhile() { 1841 assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected"); 1842 nextToken(); 1843 if (FormatTok->Tok.is(tok::l_brace)) { 1844 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1845 parseBlock(/*MustBeDeclaration=*/false); 1846 if (Style.BraceWrapping.IndentBraces) 1847 addUnwrappedLine(); 1848 } else { 1849 addUnwrappedLine(); 1850 ++Line->Level; 1851 parseStructuralElement(); 1852 --Line->Level; 1853 } 1854 1855 // FIXME: Add error handling. 1856 if (!FormatTok->Tok.is(tok::kw_while)) { 1857 addUnwrappedLine(); 1858 return; 1859 } 1860 1861 nextToken(); 1862 parseStructuralElement(); 1863 } 1864 1865 void UnwrappedLineParser::parseLabel() { 1866 nextToken(); 1867 unsigned OldLineLevel = Line->Level; 1868 if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0)) 1869 --Line->Level; 1870 if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) { 1871 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1872 parseBlock(/*MustBeDeclaration=*/false); 1873 if (FormatTok->Tok.is(tok::kw_break)) { 1874 if (Style.BraceWrapping.AfterControlStatement) 1875 addUnwrappedLine(); 1876 parseStructuralElement(); 1877 } 1878 addUnwrappedLine(); 1879 } else { 1880 if (FormatTok->is(tok::semi)) 1881 nextToken(); 1882 addUnwrappedLine(); 1883 } 1884 Line->Level = OldLineLevel; 1885 if (FormatTok->isNot(tok::l_brace)) { 1886 parseStructuralElement(); 1887 addUnwrappedLine(); 1888 } 1889 } 1890 1891 void UnwrappedLineParser::parseCaseLabel() { 1892 assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected"); 1893 // FIXME: fix handling of complex expressions here. 1894 do { 1895 nextToken(); 1896 } while (!eof() && !FormatTok->Tok.is(tok::colon)); 1897 parseLabel(); 1898 } 1899 1900 void UnwrappedLineParser::parseSwitch() { 1901 assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected"); 1902 nextToken(); 1903 if (FormatTok->Tok.is(tok::l_paren)) 1904 parseParens(); 1905 if (FormatTok->Tok.is(tok::l_brace)) { 1906 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1907 parseBlock(/*MustBeDeclaration=*/false); 1908 addUnwrappedLine(); 1909 } else { 1910 addUnwrappedLine(); 1911 ++Line->Level; 1912 parseStructuralElement(); 1913 --Line->Level; 1914 } 1915 } 1916 1917 void UnwrappedLineParser::parseAccessSpecifier() { 1918 nextToken(); 1919 // Understand Qt's slots. 1920 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots)) 1921 nextToken(); 1922 // Otherwise, we don't know what it is, and we'd better keep the next token. 1923 if (FormatTok->Tok.is(tok::colon)) 1924 nextToken(); 1925 addUnwrappedLine(); 1926 } 1927 1928 bool UnwrappedLineParser::parseEnum() { 1929 // Won't be 'enum' for NS_ENUMs. 1930 if (FormatTok->Tok.is(tok::kw_enum)) 1931 nextToken(); 1932 1933 // In TypeScript, "enum" can also be used as property name, e.g. in interface 1934 // declarations. An "enum" keyword followed by a colon would be a syntax 1935 // error and thus assume it is just an identifier. 1936 if (Style.Language == FormatStyle::LK_JavaScript && 1937 FormatTok->isOneOf(tok::colon, tok::question)) 1938 return false; 1939 1940 // Eat up enum class ... 1941 if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct)) 1942 nextToken(); 1943 1944 while (FormatTok->Tok.getIdentifierInfo() || 1945 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less, 1946 tok::greater, tok::comma, tok::question)) { 1947 nextToken(); 1948 // We can have macros or attributes in between 'enum' and the enum name. 1949 if (FormatTok->is(tok::l_paren)) 1950 parseParens(); 1951 if (FormatTok->is(tok::identifier)) { 1952 nextToken(); 1953 // If there are two identifiers in a row, this is likely an elaborate 1954 // return type. In Java, this can be "implements", etc. 1955 if (Style.isCpp() && FormatTok->is(tok::identifier)) 1956 return false; 1957 } 1958 } 1959 1960 // Just a declaration or something is wrong. 1961 if (FormatTok->isNot(tok::l_brace)) 1962 return true; 1963 FormatTok->BlockKind = BK_Block; 1964 1965 if (Style.Language == FormatStyle::LK_Java) { 1966 // Java enums are different. 1967 parseJavaEnumBody(); 1968 return true; 1969 } 1970 if (Style.Language == FormatStyle::LK_Proto) { 1971 parseBlock(/*MustBeDeclaration=*/true); 1972 return true; 1973 } 1974 1975 // Parse enum body. 1976 nextToken(); 1977 bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true); 1978 if (HasError) { 1979 if (FormatTok->is(tok::semi)) 1980 nextToken(); 1981 addUnwrappedLine(); 1982 } 1983 return true; 1984 1985 // There is no addUnwrappedLine() here so that we fall through to parsing a 1986 // structural element afterwards. Thus, in "enum A {} n, m;", 1987 // "} n, m;" will end up in one unwrapped line. 1988 } 1989 1990 void UnwrappedLineParser::parseJavaEnumBody() { 1991 // Determine whether the enum is simple, i.e. does not have a semicolon or 1992 // constants with class bodies. Simple enums can be formatted like braced 1993 // lists, contracted to a single line, etc. 1994 unsigned StoredPosition = Tokens->getPosition(); 1995 bool IsSimple = true; 1996 FormatToken *Tok = Tokens->getNextToken(); 1997 while (Tok) { 1998 if (Tok->is(tok::r_brace)) 1999 break; 2000 if (Tok->isOneOf(tok::l_brace, tok::semi)) { 2001 IsSimple = false; 2002 break; 2003 } 2004 // FIXME: This will also mark enums with braces in the arguments to enum 2005 // constants as "not simple". This is probably fine in practice, though. 2006 Tok = Tokens->getNextToken(); 2007 } 2008 FormatTok = Tokens->setPosition(StoredPosition); 2009 2010 if (IsSimple) { 2011 nextToken(); 2012 parseBracedList(); 2013 addUnwrappedLine(); 2014 return; 2015 } 2016 2017 // Parse the body of a more complex enum. 2018 // First add a line for everything up to the "{". 2019 nextToken(); 2020 addUnwrappedLine(); 2021 ++Line->Level; 2022 2023 // Parse the enum constants. 2024 while (FormatTok) { 2025 if (FormatTok->is(tok::l_brace)) { 2026 // Parse the constant's class body. 2027 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true, 2028 /*MunchSemi=*/false); 2029 } else if (FormatTok->is(tok::l_paren)) { 2030 parseParens(); 2031 } else if (FormatTok->is(tok::comma)) { 2032 nextToken(); 2033 addUnwrappedLine(); 2034 } else if (FormatTok->is(tok::semi)) { 2035 nextToken(); 2036 addUnwrappedLine(); 2037 break; 2038 } else if (FormatTok->is(tok::r_brace)) { 2039 addUnwrappedLine(); 2040 break; 2041 } else { 2042 nextToken(); 2043 } 2044 } 2045 2046 // Parse the class body after the enum's ";" if any. 2047 parseLevel(/*HasOpeningBrace=*/true); 2048 nextToken(); 2049 --Line->Level; 2050 addUnwrappedLine(); 2051 } 2052 2053 void UnwrappedLineParser::parseRecord(bool ParseAsExpr) { 2054 const FormatToken &InitialToken = *FormatTok; 2055 nextToken(); 2056 2057 // The actual identifier can be a nested name specifier, and in macros 2058 // it is often token-pasted. 2059 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash, 2060 tok::kw___attribute, tok::kw___declspec, 2061 tok::kw_alignas) || 2062 ((Style.Language == FormatStyle::LK_Java || 2063 Style.Language == FormatStyle::LK_JavaScript) && 2064 FormatTok->isOneOf(tok::period, tok::comma))) { 2065 if (Style.Language == FormatStyle::LK_JavaScript && 2066 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) { 2067 // JavaScript/TypeScript supports inline object types in 2068 // extends/implements positions: 2069 // class Foo implements {bar: number} { } 2070 nextToken(); 2071 if (FormatTok->is(tok::l_brace)) { 2072 tryToParseBracedList(); 2073 continue; 2074 } 2075 } 2076 bool IsNonMacroIdentifier = 2077 FormatTok->is(tok::identifier) && 2078 FormatTok->TokenText != FormatTok->TokenText.upper(); 2079 nextToken(); 2080 // We can have macros or attributes in between 'class' and the class name. 2081 if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren)) 2082 parseParens(); 2083 } 2084 2085 // Note that parsing away template declarations here leads to incorrectly 2086 // accepting function declarations as record declarations. 2087 // In general, we cannot solve this problem. Consider: 2088 // class A<int> B() {} 2089 // which can be a function definition or a class definition when B() is a 2090 // macro. If we find enough real-world cases where this is a problem, we 2091 // can parse for the 'template' keyword in the beginning of the statement, 2092 // and thus rule out the record production in case there is no template 2093 // (this would still leave us with an ambiguity between template function 2094 // and class declarations). 2095 if (FormatTok->isOneOf(tok::colon, tok::less)) { 2096 while (!eof()) { 2097 if (FormatTok->is(tok::l_brace)) { 2098 calculateBraceTypes(/*ExpectClassBody=*/true); 2099 if (!tryToParseBracedList()) 2100 break; 2101 } 2102 if (FormatTok->Tok.is(tok::semi)) 2103 return; 2104 nextToken(); 2105 } 2106 } 2107 if (FormatTok->Tok.is(tok::l_brace)) { 2108 if (ParseAsExpr) { 2109 parseChildBlock(); 2110 } else { 2111 if (ShouldBreakBeforeBrace(Style, InitialToken)) 2112 addUnwrappedLine(); 2113 2114 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true, 2115 /*MunchSemi=*/false); 2116 } 2117 } 2118 // There is no addUnwrappedLine() here so that we fall through to parsing a 2119 // structural element afterwards. Thus, in "class A {} n, m;", 2120 // "} n, m;" will end up in one unwrapped line. 2121 } 2122 2123 void UnwrappedLineParser::parseObjCProtocolList() { 2124 assert(FormatTok->Tok.is(tok::less) && "'<' expected."); 2125 do 2126 nextToken(); 2127 while (!eof() && FormatTok->Tok.isNot(tok::greater)); 2128 nextToken(); // Skip '>'. 2129 } 2130 2131 void UnwrappedLineParser::parseObjCUntilAtEnd() { 2132 do { 2133 if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) { 2134 nextToken(); 2135 addUnwrappedLine(); 2136 break; 2137 } 2138 if (FormatTok->is(tok::l_brace)) { 2139 parseBlock(/*MustBeDeclaration=*/false); 2140 // In ObjC interfaces, nothing should be following the "}". 2141 addUnwrappedLine(); 2142 } else if (FormatTok->is(tok::r_brace)) { 2143 // Ignore stray "}". parseStructuralElement doesn't consume them. 2144 nextToken(); 2145 addUnwrappedLine(); 2146 } else { 2147 parseStructuralElement(); 2148 } 2149 } while (!eof()); 2150 } 2151 2152 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() { 2153 assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_interface || 2154 FormatTok->Tok.getObjCKeywordID() == tok::objc_implementation); 2155 nextToken(); 2156 nextToken(); // interface name 2157 2158 // @interface can be followed by either a base class, or a category. 2159 if (FormatTok->Tok.is(tok::colon)) { 2160 nextToken(); 2161 nextToken(); // base class name 2162 } else if (FormatTok->Tok.is(tok::l_paren)) 2163 // Skip category, if present. 2164 parseParens(); 2165 2166 if (FormatTok->Tok.is(tok::less)) 2167 parseObjCProtocolList(); 2168 2169 if (FormatTok->Tok.is(tok::l_brace)) { 2170 if (Style.BraceWrapping.AfterObjCDeclaration) 2171 addUnwrappedLine(); 2172 parseBlock(/*MustBeDeclaration=*/true); 2173 } 2174 2175 // With instance variables, this puts '}' on its own line. Without instance 2176 // variables, this ends the @interface line. 2177 addUnwrappedLine(); 2178 2179 parseObjCUntilAtEnd(); 2180 } 2181 2182 // Returns true for the declaration/definition form of @protocol, 2183 // false for the expression form. 2184 bool UnwrappedLineParser::parseObjCProtocol() { 2185 assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_protocol); 2186 nextToken(); 2187 2188 if (FormatTok->is(tok::l_paren)) 2189 // The expression form of @protocol, e.g. "Protocol* p = @protocol(foo);". 2190 return false; 2191 2192 // The definition/declaration form, 2193 // @protocol Foo 2194 // - (int)someMethod; 2195 // @end 2196 2197 nextToken(); // protocol name 2198 2199 if (FormatTok->Tok.is(tok::less)) 2200 parseObjCProtocolList(); 2201 2202 // Check for protocol declaration. 2203 if (FormatTok->Tok.is(tok::semi)) { 2204 nextToken(); 2205 addUnwrappedLine(); 2206 return true; 2207 } 2208 2209 addUnwrappedLine(); 2210 parseObjCUntilAtEnd(); 2211 return true; 2212 } 2213 2214 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() { 2215 bool IsImport = FormatTok->is(Keywords.kw_import); 2216 assert(IsImport || FormatTok->is(tok::kw_export)); 2217 nextToken(); 2218 2219 // Consume the "default" in "export default class/function". 2220 if (FormatTok->is(tok::kw_default)) 2221 nextToken(); 2222 2223 // Consume "async function", "function" and "default function", so that these 2224 // get parsed as free-standing JS functions, i.e. do not require a trailing 2225 // semicolon. 2226 if (FormatTok->is(Keywords.kw_async)) 2227 nextToken(); 2228 if (FormatTok->is(Keywords.kw_function)) { 2229 nextToken(); 2230 return; 2231 } 2232 2233 // For imports, `export *`, `export {...}`, consume the rest of the line up 2234 // to the terminating `;`. For everything else, just return and continue 2235 // parsing the structural element, i.e. the declaration or expression for 2236 // `export default`. 2237 if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) && 2238 !FormatTok->isStringLiteral()) 2239 return; 2240 2241 while (!eof()) { 2242 if (FormatTok->is(tok::semi)) 2243 return; 2244 if (Line->Tokens.empty()) { 2245 // Common issue: Automatic Semicolon Insertion wrapped the line, so the 2246 // import statement should terminate. 2247 return; 2248 } 2249 if (FormatTok->is(tok::l_brace)) { 2250 FormatTok->BlockKind = BK_Block; 2251 nextToken(); 2252 parseBracedList(); 2253 } else { 2254 nextToken(); 2255 } 2256 } 2257 } 2258 2259 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line, 2260 StringRef Prefix = "") { 2261 llvm::dbgs() << Prefix << "Line(" << Line.Level 2262 << ", FSC=" << Line.FirstStartColumn << ")" 2263 << (Line.InPPDirective ? " MACRO" : "") << ": "; 2264 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(), 2265 E = Line.Tokens.end(); 2266 I != E; ++I) { 2267 llvm::dbgs() << I->Tok->Tok.getName() << "[" 2268 << "T=" << I->Tok->Type << ", OC=" << I->Tok->OriginalColumn 2269 << "] "; 2270 } 2271 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(), 2272 E = Line.Tokens.end(); 2273 I != E; ++I) { 2274 const UnwrappedLineNode &Node = *I; 2275 for (SmallVectorImpl<UnwrappedLine>::const_iterator 2276 I = Node.Children.begin(), 2277 E = Node.Children.end(); 2278 I != E; ++I) { 2279 printDebugInfo(*I, "\nChild: "); 2280 } 2281 } 2282 llvm::dbgs() << "\n"; 2283 } 2284 2285 void UnwrappedLineParser::addUnwrappedLine() { 2286 if (Line->Tokens.empty()) 2287 return; 2288 DEBUG({ 2289 if (CurrentLines == &Lines) 2290 printDebugInfo(*Line); 2291 }); 2292 CurrentLines->push_back(std::move(*Line)); 2293 Line->Tokens.clear(); 2294 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex; 2295 Line->FirstStartColumn = 0; 2296 if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) { 2297 CurrentLines->append( 2298 std::make_move_iterator(PreprocessorDirectives.begin()), 2299 std::make_move_iterator(PreprocessorDirectives.end())); 2300 PreprocessorDirectives.clear(); 2301 } 2302 // Disconnect the current token from the last token on the previous line. 2303 FormatTok->Previous = nullptr; 2304 } 2305 2306 bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); } 2307 2308 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) { 2309 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) && 2310 FormatTok.NewlinesBefore > 0; 2311 } 2312 2313 // Checks if \p FormatTok is a line comment that continues the line comment 2314 // section on \p Line. 2315 static bool continuesLineCommentSection(const FormatToken &FormatTok, 2316 const UnwrappedLine &Line, 2317 llvm::Regex &CommentPragmasRegex) { 2318 if (Line.Tokens.empty()) 2319 return false; 2320 2321 StringRef IndentContent = FormatTok.TokenText; 2322 if (FormatTok.TokenText.startswith("//") || 2323 FormatTok.TokenText.startswith("/*")) 2324 IndentContent = FormatTok.TokenText.substr(2); 2325 if (CommentPragmasRegex.match(IndentContent)) 2326 return false; 2327 2328 // If Line starts with a line comment, then FormatTok continues the comment 2329 // section if its original column is greater or equal to the original start 2330 // column of the line. 2331 // 2332 // Define the min column token of a line as follows: if a line ends in '{' or 2333 // contains a '{' followed by a line comment, then the min column token is 2334 // that '{'. Otherwise, the min column token of the line is the first token of 2335 // the line. 2336 // 2337 // If Line starts with a token other than a line comment, then FormatTok 2338 // continues the comment section if its original column is greater than the 2339 // original start column of the min column token of the line. 2340 // 2341 // For example, the second line comment continues the first in these cases: 2342 // 2343 // // first line 2344 // // second line 2345 // 2346 // and: 2347 // 2348 // // first line 2349 // // second line 2350 // 2351 // and: 2352 // 2353 // int i; // first line 2354 // // second line 2355 // 2356 // and: 2357 // 2358 // do { // first line 2359 // // second line 2360 // int i; 2361 // } while (true); 2362 // 2363 // and: 2364 // 2365 // enum { 2366 // a, // first line 2367 // // second line 2368 // b 2369 // }; 2370 // 2371 // The second line comment doesn't continue the first in these cases: 2372 // 2373 // // first line 2374 // // second line 2375 // 2376 // and: 2377 // 2378 // int i; // first line 2379 // // second line 2380 // 2381 // and: 2382 // 2383 // do { // first line 2384 // // second line 2385 // int i; 2386 // } while (true); 2387 // 2388 // and: 2389 // 2390 // enum { 2391 // a, // first line 2392 // // second line 2393 // }; 2394 const FormatToken *MinColumnToken = Line.Tokens.front().Tok; 2395 2396 // Scan for '{//'. If found, use the column of '{' as a min column for line 2397 // comment section continuation. 2398 const FormatToken *PreviousToken = nullptr; 2399 for (const UnwrappedLineNode &Node : Line.Tokens) { 2400 if (PreviousToken && PreviousToken->is(tok::l_brace) && 2401 isLineComment(*Node.Tok)) { 2402 MinColumnToken = PreviousToken; 2403 break; 2404 } 2405 PreviousToken = Node.Tok; 2406 2407 // Grab the last newline preceding a token in this unwrapped line. 2408 if (Node.Tok->NewlinesBefore > 0) { 2409 MinColumnToken = Node.Tok; 2410 } 2411 } 2412 if (PreviousToken && PreviousToken->is(tok::l_brace)) { 2413 MinColumnToken = PreviousToken; 2414 } 2415 2416 return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok, 2417 MinColumnToken); 2418 } 2419 2420 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) { 2421 bool JustComments = Line->Tokens.empty(); 2422 for (SmallVectorImpl<FormatToken *>::const_iterator 2423 I = CommentsBeforeNextToken.begin(), 2424 E = CommentsBeforeNextToken.end(); 2425 I != E; ++I) { 2426 // Line comments that belong to the same line comment section are put on the 2427 // same line since later we might want to reflow content between them. 2428 // Additional fine-grained breaking of line comment sections is controlled 2429 // by the class BreakableLineCommentSection in case it is desirable to keep 2430 // several line comment sections in the same unwrapped line. 2431 // 2432 // FIXME: Consider putting separate line comment sections as children to the 2433 // unwrapped line instead. 2434 (*I)->ContinuesLineCommentSection = 2435 continuesLineCommentSection(**I, *Line, CommentPragmasRegex); 2436 if (isOnNewLine(**I) && JustComments && !(*I)->ContinuesLineCommentSection) 2437 addUnwrappedLine(); 2438 pushToken(*I); 2439 } 2440 if (NewlineBeforeNext && JustComments) 2441 addUnwrappedLine(); 2442 CommentsBeforeNextToken.clear(); 2443 } 2444 2445 void UnwrappedLineParser::nextToken(int LevelDifference) { 2446 if (eof()) 2447 return; 2448 flushComments(isOnNewLine(*FormatTok)); 2449 pushToken(FormatTok); 2450 FormatToken *Previous = FormatTok; 2451 if (Style.Language != FormatStyle::LK_JavaScript) 2452 readToken(LevelDifference); 2453 else 2454 readTokenWithJavaScriptASI(); 2455 FormatTok->Previous = Previous; 2456 } 2457 2458 void UnwrappedLineParser::distributeComments( 2459 const SmallVectorImpl<FormatToken *> &Comments, 2460 const FormatToken *NextTok) { 2461 // Whether or not a line comment token continues a line is controlled by 2462 // the method continuesLineCommentSection, with the following caveat: 2463 // 2464 // Define a trail of Comments to be a nonempty proper postfix of Comments such 2465 // that each comment line from the trail is aligned with the next token, if 2466 // the next token exists. If a trail exists, the beginning of the maximal 2467 // trail is marked as a start of a new comment section. 2468 // 2469 // For example in this code: 2470 // 2471 // int a; // line about a 2472 // // line 1 about b 2473 // // line 2 about b 2474 // int b; 2475 // 2476 // the two lines about b form a maximal trail, so there are two sections, the 2477 // first one consisting of the single comment "// line about a" and the 2478 // second one consisting of the next two comments. 2479 if (Comments.empty()) 2480 return; 2481 bool ShouldPushCommentsInCurrentLine = true; 2482 bool HasTrailAlignedWithNextToken = false; 2483 unsigned StartOfTrailAlignedWithNextToken = 0; 2484 if (NextTok) { 2485 // We are skipping the first element intentionally. 2486 for (unsigned i = Comments.size() - 1; i > 0; --i) { 2487 if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) { 2488 HasTrailAlignedWithNextToken = true; 2489 StartOfTrailAlignedWithNextToken = i; 2490 } 2491 } 2492 } 2493 for (unsigned i = 0, e = Comments.size(); i < e; ++i) { 2494 FormatToken *FormatTok = Comments[i]; 2495 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) { 2496 FormatTok->ContinuesLineCommentSection = false; 2497 } else { 2498 FormatTok->ContinuesLineCommentSection = 2499 continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex); 2500 } 2501 if (!FormatTok->ContinuesLineCommentSection && 2502 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) { 2503 ShouldPushCommentsInCurrentLine = false; 2504 } 2505 if (ShouldPushCommentsInCurrentLine) { 2506 pushToken(FormatTok); 2507 } else { 2508 CommentsBeforeNextToken.push_back(FormatTok); 2509 } 2510 } 2511 } 2512 2513 void UnwrappedLineParser::readToken(int LevelDifference) { 2514 SmallVector<FormatToken *, 1> Comments; 2515 do { 2516 FormatTok = Tokens->getNextToken(); 2517 assert(FormatTok); 2518 while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) && 2519 (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) { 2520 distributeComments(Comments, FormatTok); 2521 Comments.clear(); 2522 // If there is an unfinished unwrapped line, we flush the preprocessor 2523 // directives only after that unwrapped line was finished later. 2524 bool SwitchToPreprocessorLines = !Line->Tokens.empty(); 2525 ScopedLineState BlockState(*this, SwitchToPreprocessorLines); 2526 assert((LevelDifference >= 0 || 2527 static_cast<unsigned>(-LevelDifference) <= Line->Level) && 2528 "LevelDifference makes Line->Level negative"); 2529 Line->Level += LevelDifference; 2530 // Comments stored before the preprocessor directive need to be output 2531 // before the preprocessor directive, at the same level as the 2532 // preprocessor directive, as we consider them to apply to the directive. 2533 flushComments(isOnNewLine(*FormatTok)); 2534 parsePPDirective(); 2535 } 2536 while (FormatTok->Type == TT_ConflictStart || 2537 FormatTok->Type == TT_ConflictEnd || 2538 FormatTok->Type == TT_ConflictAlternative) { 2539 if (FormatTok->Type == TT_ConflictStart) { 2540 conditionalCompilationStart(/*Unreachable=*/false); 2541 } else if (FormatTok->Type == TT_ConflictAlternative) { 2542 conditionalCompilationAlternative(); 2543 } else if (FormatTok->Type == TT_ConflictEnd) { 2544 conditionalCompilationEnd(); 2545 } 2546 FormatTok = Tokens->getNextToken(); 2547 FormatTok->MustBreakBefore = true; 2548 } 2549 2550 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) && 2551 !Line->InPPDirective) { 2552 continue; 2553 } 2554 2555 if (!FormatTok->Tok.is(tok::comment)) { 2556 distributeComments(Comments, FormatTok); 2557 Comments.clear(); 2558 return; 2559 } 2560 2561 Comments.push_back(FormatTok); 2562 } while (!eof()); 2563 2564 distributeComments(Comments, nullptr); 2565 Comments.clear(); 2566 } 2567 2568 void UnwrappedLineParser::pushToken(FormatToken *Tok) { 2569 Line->Tokens.push_back(UnwrappedLineNode(Tok)); 2570 if (MustBreakBeforeNextToken) { 2571 Line->Tokens.back().Tok->MustBreakBefore = true; 2572 MustBreakBeforeNextToken = false; 2573 } 2574 } 2575 2576 } // end namespace format 2577 } // end namespace clang 2578