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