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