1 //===--- UnwrappedLineParser.cpp - Format C++ code ------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// 10 /// \file 11 /// \brief This file contains the implementation of the UnwrappedLineParser, 12 /// which turns a stream of tokens into UnwrappedLines. 13 /// 14 //===----------------------------------------------------------------------===// 15 16 #include "UnwrappedLineParser.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/Support/Debug.h" 19 #include "llvm/Support/raw_ostream.h" 20 21 #define DEBUG_TYPE "format-parser" 22 23 namespace clang { 24 namespace format { 25 26 class FormatTokenSource { 27 public: 28 virtual ~FormatTokenSource() {} 29 virtual FormatToken *getNextToken() = 0; 30 31 virtual unsigned getPosition() = 0; 32 virtual FormatToken *setPosition(unsigned Position) = 0; 33 }; 34 35 namespace { 36 37 class ScopedDeclarationState { 38 public: 39 ScopedDeclarationState(UnwrappedLine &Line, std::vector<bool> &Stack, 40 bool MustBeDeclaration) 41 : Line(Line), Stack(Stack) { 42 Line.MustBeDeclaration = MustBeDeclaration; 43 Stack.push_back(MustBeDeclaration); 44 } 45 ~ScopedDeclarationState() { 46 Stack.pop_back(); 47 if (!Stack.empty()) 48 Line.MustBeDeclaration = Stack.back(); 49 else 50 Line.MustBeDeclaration = true; 51 } 52 53 private: 54 UnwrappedLine &Line; 55 std::vector<bool> &Stack; 56 }; 57 58 class ScopedMacroState : public FormatTokenSource { 59 public: 60 ScopedMacroState(UnwrappedLine &Line, FormatTokenSource *&TokenSource, 61 FormatToken *&ResetToken) 62 : Line(Line), TokenSource(TokenSource), ResetToken(ResetToken), 63 PreviousLineLevel(Line.Level), PreviousTokenSource(TokenSource), 64 Token(nullptr) { 65 TokenSource = this; 66 Line.Level = 0; 67 Line.InPPDirective = true; 68 } 69 70 ~ScopedMacroState() override { 71 TokenSource = PreviousTokenSource; 72 ResetToken = Token; 73 Line.InPPDirective = false; 74 Line.Level = PreviousLineLevel; 75 } 76 77 FormatToken *getNextToken() override { 78 // The \c UnwrappedLineParser guards against this by never calling 79 // \c getNextToken() after it has encountered the first eof token. 80 assert(!eof()); 81 Token = PreviousTokenSource->getNextToken(); 82 if (eof()) 83 return getFakeEOF(); 84 return Token; 85 } 86 87 unsigned getPosition() override { return PreviousTokenSource->getPosition(); } 88 89 FormatToken *setPosition(unsigned Position) override { 90 Token = PreviousTokenSource->setPosition(Position); 91 return Token; 92 } 93 94 private: 95 bool eof() { return Token && Token->HasUnescapedNewline; } 96 97 FormatToken *getFakeEOF() { 98 static bool EOFInitialized = false; 99 static FormatToken FormatTok; 100 if (!EOFInitialized) { 101 FormatTok.Tok.startToken(); 102 FormatTok.Tok.setKind(tok::eof); 103 EOFInitialized = true; 104 } 105 return &FormatTok; 106 } 107 108 UnwrappedLine &Line; 109 FormatTokenSource *&TokenSource; 110 FormatToken *&ResetToken; 111 unsigned PreviousLineLevel; 112 FormatTokenSource *PreviousTokenSource; 113 114 FormatToken *Token; 115 }; 116 117 } // end anonymous namespace 118 119 class ScopedLineState { 120 public: 121 ScopedLineState(UnwrappedLineParser &Parser, 122 bool SwitchToPreprocessorLines = false) 123 : Parser(Parser), OriginalLines(Parser.CurrentLines) { 124 if (SwitchToPreprocessorLines) 125 Parser.CurrentLines = &Parser.PreprocessorDirectives; 126 else if (!Parser.Line->Tokens.empty()) 127 Parser.CurrentLines = &Parser.Line->Tokens.back().Children; 128 PreBlockLine = std::move(Parser.Line); 129 Parser.Line = llvm::make_unique<UnwrappedLine>(); 130 Parser.Line->Level = PreBlockLine->Level; 131 Parser.Line->InPPDirective = PreBlockLine->InPPDirective; 132 } 133 134 ~ScopedLineState() { 135 if (!Parser.Line->Tokens.empty()) { 136 Parser.addUnwrappedLine(); 137 } 138 assert(Parser.Line->Tokens.empty()); 139 Parser.Line = std::move(PreBlockLine); 140 if (Parser.CurrentLines == &Parser.PreprocessorDirectives) 141 Parser.MustBreakBeforeNextToken = true; 142 Parser.CurrentLines = OriginalLines; 143 } 144 145 private: 146 UnwrappedLineParser &Parser; 147 148 std::unique_ptr<UnwrappedLine> PreBlockLine; 149 SmallVectorImpl<UnwrappedLine> *OriginalLines; 150 }; 151 152 class CompoundStatementIndenter { 153 public: 154 CompoundStatementIndenter(UnwrappedLineParser *Parser, 155 const FormatStyle &Style, unsigned &LineLevel) 156 : LineLevel(LineLevel), OldLineLevel(LineLevel) { 157 if (Style.BraceWrapping.AfterControlStatement) 158 Parser->addUnwrappedLine(); 159 if (Style.BraceWrapping.IndentBraces) 160 ++LineLevel; 161 } 162 ~CompoundStatementIndenter() { LineLevel = OldLineLevel; } 163 164 private: 165 unsigned &LineLevel; 166 unsigned OldLineLevel; 167 }; 168 169 namespace { 170 171 class IndexedTokenSource : public FormatTokenSource { 172 public: 173 IndexedTokenSource(ArrayRef<FormatToken *> Tokens) 174 : Tokens(Tokens), Position(-1) {} 175 176 FormatToken *getNextToken() override { 177 ++Position; 178 return Tokens[Position]; 179 } 180 181 unsigned getPosition() override { 182 assert(Position >= 0); 183 return Position; 184 } 185 186 FormatToken *setPosition(unsigned P) override { 187 Position = P; 188 return Tokens[Position]; 189 } 190 191 void reset() { Position = -1; } 192 193 private: 194 ArrayRef<FormatToken *> Tokens; 195 int Position; 196 }; 197 198 } // end anonymous namespace 199 200 UnwrappedLineParser::UnwrappedLineParser(const FormatStyle &Style, 201 const AdditionalKeywords &Keywords, 202 ArrayRef<FormatToken *> Tokens, 203 UnwrappedLineConsumer &Callback) 204 : Line(new UnwrappedLine), MustBreakBeforeNextToken(false), 205 CurrentLines(&Lines), Style(Style), Keywords(Keywords), Tokens(nullptr), 206 Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1) {} 207 208 void UnwrappedLineParser::reset() { 209 PPBranchLevel = -1; 210 Line.reset(new UnwrappedLine); 211 CommentsBeforeNextToken.clear(); 212 FormatTok = nullptr; 213 MustBreakBeforeNextToken = false; 214 PreprocessorDirectives.clear(); 215 CurrentLines = &Lines; 216 DeclarationScopeStack.clear(); 217 PPStack.clear(); 218 } 219 220 void UnwrappedLineParser::parse() { 221 IndexedTokenSource TokenSource(AllTokens); 222 do { 223 DEBUG(llvm::dbgs() << "----\n"); 224 reset(); 225 Tokens = &TokenSource; 226 TokenSource.reset(); 227 228 readToken(); 229 parseFile(); 230 // Create line with eof token. 231 pushToken(FormatTok); 232 addUnwrappedLine(); 233 234 for (SmallVectorImpl<UnwrappedLine>::iterator I = Lines.begin(), 235 E = Lines.end(); 236 I != E; ++I) { 237 Callback.consumeUnwrappedLine(*I); 238 } 239 Callback.finishRun(); 240 Lines.clear(); 241 while (!PPLevelBranchIndex.empty() && 242 PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) { 243 PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1); 244 PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1); 245 } 246 if (!PPLevelBranchIndex.empty()) { 247 ++PPLevelBranchIndex.back(); 248 assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size()); 249 assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back()); 250 } 251 } while (!PPLevelBranchIndex.empty()); 252 } 253 254 void UnwrappedLineParser::parseFile() { 255 // The top-level context in a file always has declarations, except for pre- 256 // processor directives and JavaScript files. 257 bool MustBeDeclaration = 258 !Line->InPPDirective && Style.Language != FormatStyle::LK_JavaScript; 259 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack, 260 MustBeDeclaration); 261 parseLevel(/*HasOpeningBrace=*/false); 262 // Make sure to format the remaining tokens. 263 flushComments(true); 264 addUnwrappedLine(); 265 } 266 267 void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) { 268 bool SwitchLabelEncountered = false; 269 do { 270 tok::TokenKind kind = FormatTok->Tok.getKind(); 271 if (FormatTok->Type == TT_MacroBlockBegin) { 272 kind = tok::l_brace; 273 } else if (FormatTok->Type == TT_MacroBlockEnd) { 274 kind = tok::r_brace; 275 } 276 277 switch (kind) { 278 case tok::comment: 279 nextToken(); 280 addUnwrappedLine(); 281 break; 282 case tok::l_brace: 283 // FIXME: Add parameter whether this can happen - if this happens, we must 284 // be in a non-declaration context. 285 if (!FormatTok->is(TT_MacroBlockBegin) && tryToParseBracedList()) 286 continue; 287 parseBlock(/*MustBeDeclaration=*/false); 288 addUnwrappedLine(); 289 break; 290 case tok::r_brace: 291 if (HasOpeningBrace) 292 return; 293 nextToken(); 294 addUnwrappedLine(); 295 break; 296 case tok::kw_default: 297 case tok::kw_case: 298 if (!SwitchLabelEncountered && 299 (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1))) 300 ++Line->Level; 301 SwitchLabelEncountered = true; 302 parseStructuralElement(); 303 break; 304 default: 305 parseStructuralElement(); 306 break; 307 } 308 } while (!eof()); 309 } 310 311 void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) { 312 // We'll parse forward through the tokens until we hit 313 // a closing brace or eof - note that getNextToken() will 314 // parse macros, so this will magically work inside macro 315 // definitions, too. 316 unsigned StoredPosition = Tokens->getPosition(); 317 FormatToken *Tok = FormatTok; 318 const FormatToken *PrevTok = getPreviousToken(); 319 // Keep a stack of positions of lbrace tokens. We will 320 // update information about whether an lbrace starts a 321 // braced init list or a different block during the loop. 322 SmallVector<FormatToken *, 8> LBraceStack; 323 assert(Tok->Tok.is(tok::l_brace)); 324 do { 325 // Get next non-comment token. 326 FormatToken *NextTok; 327 unsigned ReadTokens = 0; 328 do { 329 NextTok = Tokens->getNextToken(); 330 ++ReadTokens; 331 } while (NextTok->is(tok::comment)); 332 333 switch (Tok->Tok.getKind()) { 334 case tok::l_brace: 335 if (Style.Language == FormatStyle::LK_JavaScript && PrevTok && 336 PrevTok->is(tok::colon)) 337 // In TypeScript's TypeMemberLists, there can be semicolons between the 338 // individual members. 339 Tok->BlockKind = BK_BracedInit; 340 else 341 Tok->BlockKind = BK_Unknown; 342 LBraceStack.push_back(Tok); 343 break; 344 case tok::r_brace: 345 if (LBraceStack.empty()) 346 break; 347 if (LBraceStack.back()->BlockKind == BK_Unknown) { 348 bool ProbablyBracedList = false; 349 if (Style.Language == FormatStyle::LK_Proto) { 350 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square); 351 } else { 352 // Using OriginalColumn to distinguish between ObjC methods and 353 // binary operators is a bit hacky. 354 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) && 355 NextTok->OriginalColumn == 0; 356 357 // If there is a comma, semicolon or right paren after the closing 358 // brace, we assume this is a braced initializer list. Note that 359 // regardless how we mark inner braces here, we will overwrite the 360 // BlockKind later if we parse a braced list (where all blocks 361 // inside are by default braced lists), or when we explicitly detect 362 // blocks (for example while parsing lambdas). 363 // 364 // We exclude + and - as they can be ObjC visibility modifiers. 365 ProbablyBracedList = 366 (Style.Language == FormatStyle::LK_JavaScript && 367 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in)) || 368 NextTok->isOneOf(tok::comma, tok::period, tok::colon, 369 tok::r_paren, tok::r_square, tok::l_brace, 370 tok::l_square, tok::l_paren, tok::ellipsis) || 371 (NextTok->is(tok::semi) && 372 (!ExpectClassBody || LBraceStack.size() != 1)) || 373 (NextTok->isBinaryOperator() && !NextIsObjCMethod); 374 } 375 if (ProbablyBracedList) { 376 Tok->BlockKind = BK_BracedInit; 377 LBraceStack.back()->BlockKind = BK_BracedInit; 378 } else { 379 Tok->BlockKind = BK_Block; 380 LBraceStack.back()->BlockKind = BK_Block; 381 } 382 } 383 LBraceStack.pop_back(); 384 break; 385 case tok::at: 386 case tok::semi: 387 case tok::kw_if: 388 case tok::kw_while: 389 case tok::kw_for: 390 case tok::kw_switch: 391 case tok::kw_try: 392 case tok::kw___try: 393 if (!LBraceStack.empty() && LBraceStack.back()->BlockKind == BK_Unknown) 394 LBraceStack.back()->BlockKind = BK_Block; 395 break; 396 default: 397 break; 398 } 399 PrevTok = Tok; 400 Tok = NextTok; 401 } while (Tok->Tok.isNot(tok::eof) && !LBraceStack.empty()); 402 403 // Assume other blocks for all unclosed opening braces. 404 for (unsigned i = 0, e = LBraceStack.size(); i != e; ++i) { 405 if (LBraceStack[i]->BlockKind == BK_Unknown) 406 LBraceStack[i]->BlockKind = BK_Block; 407 } 408 409 FormatTok = Tokens->setPosition(StoredPosition); 410 } 411 412 void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel, 413 bool MunchSemi) { 414 assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) && 415 "'{' or macro block token expected"); 416 const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin); 417 FormatTok->BlockKind = BK_Block; 418 419 unsigned InitialLevel = Line->Level; 420 nextToken(); 421 422 if (MacroBlock && FormatTok->is(tok::l_paren)) 423 parseParens(); 424 425 addUnwrappedLine(); 426 427 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack, 428 MustBeDeclaration); 429 if (AddLevel) 430 ++Line->Level; 431 parseLevel(/*HasOpeningBrace=*/true); 432 433 if (MacroBlock ? !FormatTok->is(TT_MacroBlockEnd) 434 : !FormatTok->is(tok::r_brace)) { 435 Line->Level = InitialLevel; 436 FormatTok->BlockKind = BK_Block; 437 return; 438 } 439 440 nextToken(); // Munch the closing brace. 441 442 if (MacroBlock && FormatTok->is(tok::l_paren)) 443 parseParens(); 444 445 if (MunchSemi && FormatTok->Tok.is(tok::semi)) 446 nextToken(); 447 Line->Level = InitialLevel; 448 } 449 450 static bool isGoogScope(const UnwrappedLine &Line) { 451 // FIXME: Closure-library specific stuff should not be hard-coded but be 452 // configurable. 453 if (Line.Tokens.size() < 4) 454 return false; 455 auto I = Line.Tokens.begin(); 456 if (I->Tok->TokenText != "goog") 457 return false; 458 ++I; 459 if (I->Tok->isNot(tok::period)) 460 return false; 461 ++I; 462 if (I->Tok->TokenText != "scope") 463 return false; 464 ++I; 465 return I->Tok->is(tok::l_paren); 466 } 467 468 static bool ShouldBreakBeforeBrace(const FormatStyle &Style, 469 const FormatToken &InitialToken) { 470 if (InitialToken.is(tok::kw_namespace)) 471 return Style.BraceWrapping.AfterNamespace; 472 if (InitialToken.is(tok::kw_class)) 473 return Style.BraceWrapping.AfterClass; 474 if (InitialToken.is(tok::kw_union)) 475 return Style.BraceWrapping.AfterUnion; 476 if (InitialToken.is(tok::kw_struct)) 477 return Style.BraceWrapping.AfterStruct; 478 return false; 479 } 480 481 void UnwrappedLineParser::parseChildBlock() { 482 FormatTok->BlockKind = BK_Block; 483 nextToken(); 484 { 485 bool GoogScope = 486 Style.Language == FormatStyle::LK_JavaScript && isGoogScope(*Line); 487 ScopedLineState LineState(*this); 488 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack, 489 /*MustBeDeclaration=*/false); 490 Line->Level += GoogScope ? 0 : 1; 491 parseLevel(/*HasOpeningBrace=*/true); 492 flushComments(isOnNewLine(*FormatTok)); 493 Line->Level -= GoogScope ? 0 : 1; 494 } 495 nextToken(); 496 } 497 498 void UnwrappedLineParser::parsePPDirective() { 499 assert(FormatTok->Tok.is(tok::hash) && "'#' expected"); 500 ScopedMacroState MacroState(*Line, Tokens, FormatTok); 501 nextToken(); 502 503 if (!FormatTok->Tok.getIdentifierInfo()) { 504 parsePPUnknown(); 505 return; 506 } 507 508 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) { 509 case tok::pp_define: 510 parsePPDefine(); 511 return; 512 case tok::pp_if: 513 parsePPIf(/*IfDef=*/false); 514 break; 515 case tok::pp_ifdef: 516 case tok::pp_ifndef: 517 parsePPIf(/*IfDef=*/true); 518 break; 519 case tok::pp_else: 520 parsePPElse(); 521 break; 522 case tok::pp_elif: 523 parsePPElIf(); 524 break; 525 case tok::pp_endif: 526 parsePPEndIf(); 527 break; 528 default: 529 parsePPUnknown(); 530 break; 531 } 532 } 533 534 void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) { 535 if (Unreachable || (!PPStack.empty() && PPStack.back() == PP_Unreachable)) 536 PPStack.push_back(PP_Unreachable); 537 else 538 PPStack.push_back(PP_Conditional); 539 } 540 541 void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) { 542 ++PPBranchLevel; 543 assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size()); 544 if (PPBranchLevel == (int)PPLevelBranchIndex.size()) { 545 PPLevelBranchIndex.push_back(0); 546 PPLevelBranchCount.push_back(0); 547 } 548 PPChainBranchIndex.push(0); 549 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0; 550 conditionalCompilationCondition(Unreachable || Skip); 551 } 552 553 void UnwrappedLineParser::conditionalCompilationAlternative() { 554 if (!PPStack.empty()) 555 PPStack.pop_back(); 556 assert(PPBranchLevel < (int)PPLevelBranchIndex.size()); 557 if (!PPChainBranchIndex.empty()) 558 ++PPChainBranchIndex.top(); 559 conditionalCompilationCondition( 560 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() && 561 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top()); 562 } 563 564 void UnwrappedLineParser::conditionalCompilationEnd() { 565 assert(PPBranchLevel < (int)PPLevelBranchIndex.size()); 566 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) { 567 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) { 568 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1; 569 } 570 } 571 // Guard against #endif's without #if. 572 if (PPBranchLevel > 0) 573 --PPBranchLevel; 574 if (!PPChainBranchIndex.empty()) 575 PPChainBranchIndex.pop(); 576 if (!PPStack.empty()) 577 PPStack.pop_back(); 578 } 579 580 void UnwrappedLineParser::parsePPIf(bool IfDef) { 581 nextToken(); 582 bool IsLiteralFalse = (FormatTok->Tok.isLiteral() && 583 FormatTok->Tok.getLiteralData() != nullptr && 584 StringRef(FormatTok->Tok.getLiteralData(), 585 FormatTok->Tok.getLength()) == "0") || 586 FormatTok->Tok.is(tok::kw_false); 587 conditionalCompilationStart(!IfDef && IsLiteralFalse); 588 parsePPUnknown(); 589 } 590 591 void UnwrappedLineParser::parsePPElse() { 592 conditionalCompilationAlternative(); 593 parsePPUnknown(); 594 } 595 596 void UnwrappedLineParser::parsePPElIf() { parsePPElse(); } 597 598 void UnwrappedLineParser::parsePPEndIf() { 599 conditionalCompilationEnd(); 600 parsePPUnknown(); 601 } 602 603 void UnwrappedLineParser::parsePPDefine() { 604 nextToken(); 605 606 if (FormatTok->Tok.getKind() != tok::identifier) { 607 parsePPUnknown(); 608 return; 609 } 610 nextToken(); 611 if (FormatTok->Tok.getKind() == tok::l_paren && 612 FormatTok->WhitespaceRange.getBegin() == 613 FormatTok->WhitespaceRange.getEnd()) { 614 parseParens(); 615 } 616 addUnwrappedLine(); 617 Line->Level = 1; 618 619 // Errors during a preprocessor directive can only affect the layout of the 620 // preprocessor directive, and thus we ignore them. An alternative approach 621 // would be to use the same approach we use on the file level (no 622 // re-indentation if there was a structural error) within the macro 623 // definition. 624 parseFile(); 625 } 626 627 void UnwrappedLineParser::parsePPUnknown() { 628 do { 629 nextToken(); 630 } while (!eof()); 631 addUnwrappedLine(); 632 } 633 634 // Here we blacklist certain tokens that are not usually the first token in an 635 // unwrapped line. This is used in attempt to distinguish macro calls without 636 // trailing semicolons from other constructs split to several lines. 637 static bool tokenCanStartNewLine(const clang::Token &Tok) { 638 // Semicolon can be a null-statement, l_square can be a start of a macro or 639 // a C++11 attribute, but this doesn't seem to be common. 640 return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) && 641 Tok.isNot(tok::l_square) && 642 // Tokens that can only be used as binary operators and a part of 643 // overloaded operator names. 644 Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) && 645 Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) && 646 Tok.isNot(tok::less) && Tok.isNot(tok::greater) && 647 Tok.isNot(tok::slash) && Tok.isNot(tok::percent) && 648 Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) && 649 Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) && 650 Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) && 651 Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) && 652 Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) && 653 Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) && 654 Tok.isNot(tok::lesslessequal) && 655 // Colon is used in labels, base class lists, initializer lists, 656 // range-based for loops, ternary operator, but should never be the 657 // first token in an unwrapped line. 658 Tok.isNot(tok::colon) && 659 // 'noexcept' is a trailing annotation. 660 Tok.isNot(tok::kw_noexcept); 661 } 662 663 static bool mustBeJSIdentOrValue(const AdditionalKeywords &Keywords, 664 const FormatToken *FormatTok) { 665 if (FormatTok->Tok.isLiteral()) 666 return true; 667 // FIXME: This returns true for C/C++ keywords like 'struct'. 668 return FormatTok->is(tok::identifier) && 669 (FormatTok->Tok.getIdentifierInfo() == nullptr || 670 !FormatTok->isOneOf(Keywords.kw_in, Keywords.kw_of, 671 Keywords.kw_finally, Keywords.kw_function, 672 Keywords.kw_import, Keywords.kw_is, 673 Keywords.kw_let, Keywords.kw_var, 674 Keywords.kw_abstract, Keywords.kw_extends, 675 Keywords.kw_implements, Keywords.kw_instanceof, 676 Keywords.kw_interface, Keywords.kw_throws)); 677 } 678 679 // isJSDeclOrStmt returns true if |FormatTok| starts a declaration or statement 680 // when encountered after a value (see mustBeJSIdentOrValue). 681 static bool isJSDeclOrStmt(const AdditionalKeywords &Keywords, 682 const FormatToken *FormatTok) { 683 return FormatTok->isOneOf( 684 tok::kw_return, 685 // conditionals 686 tok::kw_if, tok::kw_else, 687 // loops 688 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break, 689 // switch/case 690 tok::kw_switch, tok::kw_case, 691 // exceptions 692 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.kw_finally, 693 // declaration 694 tok::kw_const, tok::kw_class, Keywords.kw_var, Keywords.kw_let, 695 Keywords.kw_function); 696 } 697 698 // readTokenWithJavaScriptASI reads the next token and terminates the current 699 // line if JavaScript Automatic Semicolon Insertion must 700 // happen between the current token and the next token. 701 // 702 // This method is conservative - it cannot cover all edge cases of JavaScript, 703 // but only aims to correctly handle certain well known cases. It *must not* 704 // return true in speculative cases. 705 void UnwrappedLineParser::readTokenWithJavaScriptASI() { 706 FormatToken *Previous = FormatTok; 707 readToken(); 708 FormatToken *Next = FormatTok; 709 710 bool IsOnSameLine = 711 CommentsBeforeNextToken.empty() 712 ? Next->NewlinesBefore == 0 713 : CommentsBeforeNextToken.front()->NewlinesBefore == 0; 714 if (IsOnSameLine) 715 return; 716 717 bool PreviousMustBeValue = mustBeJSIdentOrValue(Keywords, Previous); 718 if (Next->is(tok::exclaim) && PreviousMustBeValue) 719 addUnwrappedLine(); 720 bool NextMustBeValue = mustBeJSIdentOrValue(Keywords, Next); 721 if (NextMustBeValue && (PreviousMustBeValue || 722 Previous->isOneOf(tok::r_square, tok::r_paren, 723 tok::plusplus, tok::minusminus))) 724 addUnwrappedLine(); 725 if (PreviousMustBeValue && isJSDeclOrStmt(Keywords, Next)) 726 addUnwrappedLine(); 727 } 728 729 void UnwrappedLineParser::parseStructuralElement() { 730 assert(!FormatTok->is(tok::l_brace)); 731 if (Style.Language == FormatStyle::LK_TableGen && 732 FormatTok->is(tok::pp_include)) { 733 nextToken(); 734 if (FormatTok->is(tok::string_literal)) 735 nextToken(); 736 addUnwrappedLine(); 737 return; 738 } 739 switch (FormatTok->Tok.getKind()) { 740 case tok::at: 741 nextToken(); 742 if (FormatTok->Tok.is(tok::l_brace)) { 743 parseBracedList(); 744 break; 745 } 746 switch (FormatTok->Tok.getObjCKeywordID()) { 747 case tok::objc_public: 748 case tok::objc_protected: 749 case tok::objc_package: 750 case tok::objc_private: 751 return parseAccessSpecifier(); 752 case tok::objc_interface: 753 case tok::objc_implementation: 754 return parseObjCInterfaceOrImplementation(); 755 case tok::objc_protocol: 756 return parseObjCProtocol(); 757 case tok::objc_end: 758 return; // Handled by the caller. 759 case tok::objc_optional: 760 case tok::objc_required: 761 nextToken(); 762 addUnwrappedLine(); 763 return; 764 case tok::objc_autoreleasepool: 765 nextToken(); 766 if (FormatTok->Tok.is(tok::l_brace)) { 767 if (Style.BraceWrapping.AfterObjCDeclaration) 768 addUnwrappedLine(); 769 parseBlock(/*MustBeDeclaration=*/false); 770 } 771 addUnwrappedLine(); 772 return; 773 case tok::objc_try: 774 // This branch isn't strictly necessary (the kw_try case below would 775 // do this too after the tok::at is parsed above). But be explicit. 776 parseTryCatch(); 777 return; 778 default: 779 break; 780 } 781 break; 782 case tok::kw_asm: 783 nextToken(); 784 if (FormatTok->is(tok::l_brace)) { 785 FormatTok->Type = TT_InlineASMBrace; 786 nextToken(); 787 while (FormatTok && FormatTok->isNot(tok::eof)) { 788 if (FormatTok->is(tok::r_brace)) { 789 FormatTok->Type = TT_InlineASMBrace; 790 nextToken(); 791 addUnwrappedLine(); 792 break; 793 } 794 FormatTok->Finalized = true; 795 nextToken(); 796 } 797 } 798 break; 799 case tok::kw_namespace: 800 parseNamespace(); 801 return; 802 case tok::kw_inline: 803 nextToken(); 804 if (FormatTok->Tok.is(tok::kw_namespace)) { 805 parseNamespace(); 806 return; 807 } 808 break; 809 case tok::kw_public: 810 case tok::kw_protected: 811 case tok::kw_private: 812 if (Style.Language == FormatStyle::LK_Java || 813 Style.Language == FormatStyle::LK_JavaScript) 814 nextToken(); 815 else 816 parseAccessSpecifier(); 817 return; 818 case tok::kw_if: 819 parseIfThenElse(); 820 return; 821 case tok::kw_for: 822 case tok::kw_while: 823 parseForOrWhileLoop(); 824 return; 825 case tok::kw_do: 826 parseDoWhile(); 827 return; 828 case tok::kw_switch: 829 parseSwitch(); 830 return; 831 case tok::kw_default: 832 nextToken(); 833 parseLabel(); 834 return; 835 case tok::kw_case: 836 parseCaseLabel(); 837 return; 838 case tok::kw_try: 839 case tok::kw___try: 840 parseTryCatch(); 841 return; 842 case tok::kw_extern: 843 nextToken(); 844 if (FormatTok->Tok.is(tok::string_literal)) { 845 nextToken(); 846 if (FormatTok->Tok.is(tok::l_brace)) { 847 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false); 848 addUnwrappedLine(); 849 return; 850 } 851 } 852 break; 853 case tok::kw_export: 854 if (Style.Language == FormatStyle::LK_JavaScript) { 855 parseJavaScriptEs6ImportExport(); 856 return; 857 } 858 break; 859 case tok::identifier: 860 if (FormatTok->is(TT_ForEachMacro)) { 861 parseForOrWhileLoop(); 862 return; 863 } 864 if (FormatTok->is(TT_MacroBlockBegin)) { 865 parseBlock(/*MustBeDeclaration=*/false, /*AddLevel=*/true, 866 /*MunchSemi=*/false); 867 return; 868 } 869 if (Style.Language == FormatStyle::LK_JavaScript && 870 FormatTok->is(Keywords.kw_import)) { 871 parseJavaScriptEs6ImportExport(); 872 return; 873 } 874 if (FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals, 875 Keywords.kw_slots, Keywords.kw_qslots)) { 876 nextToken(); 877 if (FormatTok->is(tok::colon)) { 878 nextToken(); 879 addUnwrappedLine(); 880 } 881 return; 882 } 883 // In all other cases, parse the declaration. 884 break; 885 default: 886 break; 887 } 888 do { 889 switch (FormatTok->Tok.getKind()) { 890 case tok::at: 891 nextToken(); 892 if (FormatTok->Tok.is(tok::l_brace)) 893 parseBracedList(); 894 break; 895 case tok::kw_enum: 896 // parseEnum falls through and does not yet add an unwrapped line as an 897 // enum definition can start a structural element. 898 if (!parseEnum()) 899 break; 900 // This only applies for C++. 901 if (Style.Language != FormatStyle::LK_Cpp) { 902 addUnwrappedLine(); 903 return; 904 } 905 break; 906 case tok::kw_typedef: 907 nextToken(); 908 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS, 909 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS)) 910 parseEnum(); 911 break; 912 case tok::kw_struct: 913 case tok::kw_union: 914 case tok::kw_class: 915 // parseRecord falls through and does not yet add an unwrapped line as a 916 // record declaration or definition can start a structural element. 917 parseRecord(); 918 // This does not apply for Java and JavaScript. 919 if (Style.Language == FormatStyle::LK_Java || 920 Style.Language == FormatStyle::LK_JavaScript) { 921 if (FormatTok->is(tok::semi)) 922 nextToken(); 923 addUnwrappedLine(); 924 return; 925 } 926 break; 927 case tok::period: 928 nextToken(); 929 // In Java, classes have an implicit static member "class". 930 if (Style.Language == FormatStyle::LK_Java && FormatTok && 931 FormatTok->is(tok::kw_class)) 932 nextToken(); 933 if (Style.Language == FormatStyle::LK_JavaScript && FormatTok && 934 FormatTok->Tok.getIdentifierInfo()) 935 // JavaScript only has pseudo keywords, all keywords are allowed to 936 // appear in "IdentifierName" positions. See http://es5.github.io/#x7.6 937 nextToken(); 938 break; 939 case tok::semi: 940 nextToken(); 941 addUnwrappedLine(); 942 return; 943 case tok::r_brace: 944 addUnwrappedLine(); 945 return; 946 case tok::l_paren: 947 parseParens(); 948 break; 949 case tok::kw_operator: 950 nextToken(); 951 if (FormatTok->isBinaryOperator()) 952 nextToken(); 953 break; 954 case tok::caret: 955 nextToken(); 956 if (FormatTok->Tok.isAnyIdentifier() || 957 FormatTok->isSimpleTypeSpecifier()) 958 nextToken(); 959 if (FormatTok->is(tok::l_paren)) 960 parseParens(); 961 if (FormatTok->is(tok::l_brace)) 962 parseChildBlock(); 963 break; 964 case tok::l_brace: 965 if (!tryToParseBracedList()) { 966 // A block outside of parentheses must be the last part of a 967 // structural element. 968 // FIXME: Figure out cases where this is not true, and add projections 969 // for them (the one we know is missing are lambdas). 970 if (Style.BraceWrapping.AfterFunction) 971 addUnwrappedLine(); 972 FormatTok->Type = TT_FunctionLBrace; 973 parseBlock(/*MustBeDeclaration=*/false); 974 addUnwrappedLine(); 975 return; 976 } 977 // Otherwise this was a braced init list, and the structural 978 // element continues. 979 break; 980 case tok::kw_try: 981 // We arrive here when parsing function-try blocks. 982 parseTryCatch(); 983 return; 984 case tok::identifier: { 985 if (FormatTok->is(TT_MacroBlockEnd)) { 986 addUnwrappedLine(); 987 return; 988 } 989 990 // Parse function literal unless 'function' is the first token in a line 991 // in which case this should be treated as a free-standing function. 992 if (Style.Language == FormatStyle::LK_JavaScript && 993 FormatTok->is(Keywords.kw_function) && Line->Tokens.size() > 0) { 994 tryToParseJSFunction(); 995 break; 996 } 997 if ((Style.Language == FormatStyle::LK_JavaScript || 998 Style.Language == FormatStyle::LK_Java) && 999 FormatTok->is(Keywords.kw_interface)) { 1000 parseRecord(); 1001 addUnwrappedLine(); 1002 return; 1003 } 1004 1005 // See if the following token should start a new unwrapped line. 1006 StringRef Text = FormatTok->TokenText; 1007 nextToken(); 1008 if (Line->Tokens.size() == 1 && 1009 // JS doesn't have macros, and within classes colons indicate fields, 1010 // not labels. 1011 Style.Language != FormatStyle::LK_JavaScript) { 1012 if (FormatTok->Tok.is(tok::colon) && !Line->MustBeDeclaration) { 1013 parseLabel(); 1014 return; 1015 } 1016 // Recognize function-like macro usages without trailing semicolon as 1017 // well as free-standing macros like Q_OBJECT. 1018 bool FunctionLike = FormatTok->is(tok::l_paren); 1019 if (FunctionLike) 1020 parseParens(); 1021 1022 bool FollowedByNewline = 1023 CommentsBeforeNextToken.empty() 1024 ? FormatTok->NewlinesBefore > 0 1025 : CommentsBeforeNextToken.front()->NewlinesBefore > 0; 1026 1027 if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) && 1028 tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) { 1029 addUnwrappedLine(); 1030 return; 1031 } 1032 } 1033 break; 1034 } 1035 case tok::equal: 1036 // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType 1037 // TT_JsFatArrow. The always start an expression or a child block if 1038 // followed by a curly. 1039 if (FormatTok->is(TT_JsFatArrow)) { 1040 nextToken(); 1041 if (FormatTok->is(tok::l_brace)) 1042 parseChildBlock(); 1043 break; 1044 } 1045 1046 nextToken(); 1047 if (FormatTok->Tok.is(tok::l_brace)) { 1048 parseBracedList(); 1049 } 1050 break; 1051 case tok::l_square: 1052 parseSquare(); 1053 break; 1054 case tok::kw_new: 1055 parseNew(); 1056 break; 1057 default: 1058 nextToken(); 1059 break; 1060 } 1061 } while (!eof()); 1062 } 1063 1064 bool UnwrappedLineParser::tryToParseLambda() { 1065 if (Style.Language != FormatStyle::LK_Cpp) { 1066 nextToken(); 1067 return false; 1068 } 1069 const FormatToken* Previous = getPreviousToken(); 1070 if (Previous && 1071 (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new, 1072 tok::kw_delete) || 1073 Previous->closesScope() || Previous->isSimpleTypeSpecifier())) { 1074 nextToken(); 1075 return false; 1076 } 1077 assert(FormatTok->is(tok::l_square)); 1078 FormatToken &LSquare = *FormatTok; 1079 if (!tryToParseLambdaIntroducer()) 1080 return false; 1081 1082 while (FormatTok->isNot(tok::l_brace)) { 1083 if (FormatTok->isSimpleTypeSpecifier()) { 1084 nextToken(); 1085 continue; 1086 } 1087 switch (FormatTok->Tok.getKind()) { 1088 case tok::l_brace: 1089 break; 1090 case tok::l_paren: 1091 parseParens(); 1092 break; 1093 case tok::amp: 1094 case tok::star: 1095 case tok::kw_const: 1096 case tok::comma: 1097 case tok::less: 1098 case tok::greater: 1099 case tok::identifier: 1100 case tok::numeric_constant: 1101 case tok::coloncolon: 1102 case tok::kw_mutable: 1103 nextToken(); 1104 break; 1105 case tok::arrow: 1106 FormatTok->Type = TT_LambdaArrow; 1107 nextToken(); 1108 break; 1109 default: 1110 return true; 1111 } 1112 } 1113 LSquare.Type = TT_LambdaLSquare; 1114 parseChildBlock(); 1115 return true; 1116 } 1117 1118 bool UnwrappedLineParser::tryToParseLambdaIntroducer() { 1119 nextToken(); 1120 if (FormatTok->is(tok::equal)) { 1121 nextToken(); 1122 if (FormatTok->is(tok::r_square)) { 1123 nextToken(); 1124 return true; 1125 } 1126 if (FormatTok->isNot(tok::comma)) 1127 return false; 1128 nextToken(); 1129 } else if (FormatTok->is(tok::amp)) { 1130 nextToken(); 1131 if (FormatTok->is(tok::r_square)) { 1132 nextToken(); 1133 return true; 1134 } 1135 if (!FormatTok->isOneOf(tok::comma, tok::identifier)) { 1136 return false; 1137 } 1138 if (FormatTok->is(tok::comma)) 1139 nextToken(); 1140 } else if (FormatTok->is(tok::r_square)) { 1141 nextToken(); 1142 return true; 1143 } 1144 do { 1145 if (FormatTok->is(tok::amp)) 1146 nextToken(); 1147 if (!FormatTok->isOneOf(tok::identifier, tok::kw_this)) 1148 return false; 1149 nextToken(); 1150 if (FormatTok->is(tok::ellipsis)) 1151 nextToken(); 1152 if (FormatTok->is(tok::comma)) { 1153 nextToken(); 1154 } else if (FormatTok->is(tok::r_square)) { 1155 nextToken(); 1156 return true; 1157 } else { 1158 return false; 1159 } 1160 } while (!eof()); 1161 return false; 1162 } 1163 1164 void UnwrappedLineParser::tryToParseJSFunction() { 1165 nextToken(); 1166 1167 // Consume function name. 1168 if (FormatTok->is(tok::identifier)) 1169 nextToken(); 1170 1171 if (FormatTok->isNot(tok::l_paren)) 1172 return; 1173 1174 // Parse formal parameter list. 1175 parseParens(); 1176 1177 if (FormatTok->is(tok::colon)) { 1178 // Parse a type definition. 1179 nextToken(); 1180 1181 // Eat the type declaration. For braced inline object types, balance braces, 1182 // otherwise just parse until finding an l_brace for the function body. 1183 if (FormatTok->is(tok::l_brace)) 1184 tryToParseBracedList(); 1185 else 1186 while (FormatTok->isNot(tok::l_brace) && !eof()) 1187 nextToken(); 1188 } 1189 1190 parseChildBlock(); 1191 } 1192 1193 bool UnwrappedLineParser::tryToParseBracedList() { 1194 if (FormatTok->BlockKind == BK_Unknown) 1195 calculateBraceTypes(); 1196 assert(FormatTok->BlockKind != BK_Unknown); 1197 if (FormatTok->BlockKind == BK_Block) 1198 return false; 1199 parseBracedList(); 1200 return true; 1201 } 1202 1203 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons) { 1204 bool HasError = false; 1205 nextToken(); 1206 1207 // FIXME: Once we have an expression parser in the UnwrappedLineParser, 1208 // replace this by using parseAssigmentExpression() inside. 1209 do { 1210 if (Style.Language == FormatStyle::LK_JavaScript) { 1211 if (FormatTok->is(Keywords.kw_function)) { 1212 tryToParseJSFunction(); 1213 continue; 1214 } 1215 if (FormatTok->is(TT_JsFatArrow)) { 1216 nextToken(); 1217 // Fat arrows can be followed by simple expressions or by child blocks 1218 // in curly braces. 1219 if (FormatTok->is(tok::l_brace)) { 1220 parseChildBlock(); 1221 continue; 1222 } 1223 } 1224 } 1225 switch (FormatTok->Tok.getKind()) { 1226 case tok::caret: 1227 nextToken(); 1228 if (FormatTok->is(tok::l_brace)) { 1229 parseChildBlock(); 1230 } 1231 break; 1232 case tok::l_square: 1233 tryToParseLambda(); 1234 break; 1235 case tok::l_brace: 1236 // Assume there are no blocks inside a braced init list apart 1237 // from the ones we explicitly parse out (like lambdas). 1238 FormatTok->BlockKind = BK_BracedInit; 1239 parseBracedList(); 1240 break; 1241 case tok::l_paren: 1242 parseParens(); 1243 // JavaScript can just have free standing methods and getters/setters in 1244 // object literals. Detect them by a "{" following ")". 1245 if (Style.Language == FormatStyle::LK_JavaScript) { 1246 if (FormatTok->is(tok::l_brace)) 1247 parseChildBlock(); 1248 break; 1249 } 1250 break; 1251 case tok::r_brace: 1252 nextToken(); 1253 return !HasError; 1254 case tok::semi: 1255 // JavaScript (or more precisely TypeScript) can have semicolons in braced 1256 // lists (in so-called TypeMemberLists). Thus, the semicolon cannot be 1257 // used for error recovery if we have otherwise determined that this is 1258 // a braced list. 1259 if (Style.Language == FormatStyle::LK_JavaScript) { 1260 nextToken(); 1261 break; 1262 } 1263 HasError = true; 1264 if (!ContinueOnSemicolons) 1265 return !HasError; 1266 nextToken(); 1267 break; 1268 case tok::comma: 1269 nextToken(); 1270 break; 1271 default: 1272 nextToken(); 1273 break; 1274 } 1275 } while (!eof()); 1276 return false; 1277 } 1278 1279 void UnwrappedLineParser::parseParens() { 1280 assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected."); 1281 nextToken(); 1282 do { 1283 switch (FormatTok->Tok.getKind()) { 1284 case tok::l_paren: 1285 parseParens(); 1286 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace)) 1287 parseChildBlock(); 1288 break; 1289 case tok::r_paren: 1290 nextToken(); 1291 return; 1292 case tok::r_brace: 1293 // A "}" inside parenthesis is an error if there wasn't a matching "{". 1294 return; 1295 case tok::l_square: 1296 tryToParseLambda(); 1297 break; 1298 case tok::l_brace: 1299 if (!tryToParseBracedList()) 1300 parseChildBlock(); 1301 break; 1302 case tok::at: 1303 nextToken(); 1304 if (FormatTok->Tok.is(tok::l_brace)) 1305 parseBracedList(); 1306 break; 1307 case tok::identifier: 1308 if (Style.Language == FormatStyle::LK_JavaScript && 1309 FormatTok->is(Keywords.kw_function)) 1310 tryToParseJSFunction(); 1311 else 1312 nextToken(); 1313 break; 1314 default: 1315 nextToken(); 1316 break; 1317 } 1318 } while (!eof()); 1319 } 1320 1321 void UnwrappedLineParser::parseSquare() { 1322 assert(FormatTok->Tok.is(tok::l_square) && "'[' expected."); 1323 if (tryToParseLambda()) 1324 return; 1325 do { 1326 switch (FormatTok->Tok.getKind()) { 1327 case tok::l_paren: 1328 parseParens(); 1329 break; 1330 case tok::r_square: 1331 nextToken(); 1332 return; 1333 case tok::r_brace: 1334 // A "}" inside parenthesis is an error if there wasn't a matching "{". 1335 return; 1336 case tok::l_square: 1337 parseSquare(); 1338 break; 1339 case tok::l_brace: { 1340 if (!tryToParseBracedList()) 1341 parseChildBlock(); 1342 break; 1343 } 1344 case tok::at: 1345 nextToken(); 1346 if (FormatTok->Tok.is(tok::l_brace)) 1347 parseBracedList(); 1348 break; 1349 default: 1350 nextToken(); 1351 break; 1352 } 1353 } while (!eof()); 1354 } 1355 1356 void UnwrappedLineParser::parseIfThenElse() { 1357 assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected"); 1358 nextToken(); 1359 if (FormatTok->Tok.is(tok::l_paren)) 1360 parseParens(); 1361 bool NeedsUnwrappedLine = false; 1362 if (FormatTok->Tok.is(tok::l_brace)) { 1363 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1364 parseBlock(/*MustBeDeclaration=*/false); 1365 if (Style.BraceWrapping.BeforeElse) 1366 addUnwrappedLine(); 1367 else 1368 NeedsUnwrappedLine = true; 1369 } else { 1370 addUnwrappedLine(); 1371 ++Line->Level; 1372 parseStructuralElement(); 1373 --Line->Level; 1374 } 1375 if (FormatTok->Tok.is(tok::kw_else)) { 1376 nextToken(); 1377 if (FormatTok->Tok.is(tok::l_brace)) { 1378 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1379 parseBlock(/*MustBeDeclaration=*/false); 1380 addUnwrappedLine(); 1381 } else if (FormatTok->Tok.is(tok::kw_if)) { 1382 parseIfThenElse(); 1383 } else { 1384 addUnwrappedLine(); 1385 ++Line->Level; 1386 parseStructuralElement(); 1387 --Line->Level; 1388 } 1389 } else if (NeedsUnwrappedLine) { 1390 addUnwrappedLine(); 1391 } 1392 } 1393 1394 void UnwrappedLineParser::parseTryCatch() { 1395 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected"); 1396 nextToken(); 1397 bool NeedsUnwrappedLine = false; 1398 if (FormatTok->is(tok::colon)) { 1399 // We are in a function try block, what comes is an initializer list. 1400 nextToken(); 1401 while (FormatTok->is(tok::identifier)) { 1402 nextToken(); 1403 if (FormatTok->is(tok::l_paren)) 1404 parseParens(); 1405 if (FormatTok->is(tok::comma)) 1406 nextToken(); 1407 } 1408 } 1409 // Parse try with resource. 1410 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) { 1411 parseParens(); 1412 } 1413 if (FormatTok->is(tok::l_brace)) { 1414 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1415 parseBlock(/*MustBeDeclaration=*/false); 1416 if (Style.BraceWrapping.BeforeCatch) { 1417 addUnwrappedLine(); 1418 } else { 1419 NeedsUnwrappedLine = true; 1420 } 1421 } else if (!FormatTok->is(tok::kw_catch)) { 1422 // The C++ standard requires a compound-statement after a try. 1423 // If there's none, we try to assume there's a structuralElement 1424 // and try to continue. 1425 addUnwrappedLine(); 1426 ++Line->Level; 1427 parseStructuralElement(); 1428 --Line->Level; 1429 } 1430 while (1) { 1431 if (FormatTok->is(tok::at)) 1432 nextToken(); 1433 if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except, 1434 tok::kw___finally) || 1435 ((Style.Language == FormatStyle::LK_Java || 1436 Style.Language == FormatStyle::LK_JavaScript) && 1437 FormatTok->is(Keywords.kw_finally)) || 1438 (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) || 1439 FormatTok->Tok.isObjCAtKeyword(tok::objc_finally)))) 1440 break; 1441 nextToken(); 1442 while (FormatTok->isNot(tok::l_brace)) { 1443 if (FormatTok->is(tok::l_paren)) { 1444 parseParens(); 1445 continue; 1446 } 1447 if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof)) 1448 return; 1449 nextToken(); 1450 } 1451 NeedsUnwrappedLine = false; 1452 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1453 parseBlock(/*MustBeDeclaration=*/false); 1454 if (Style.BraceWrapping.BeforeCatch) 1455 addUnwrappedLine(); 1456 else 1457 NeedsUnwrappedLine = true; 1458 } 1459 if (NeedsUnwrappedLine) 1460 addUnwrappedLine(); 1461 } 1462 1463 void UnwrappedLineParser::parseNamespace() { 1464 assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected"); 1465 1466 const FormatToken &InitialToken = *FormatTok; 1467 nextToken(); 1468 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon)) 1469 nextToken(); 1470 if (FormatTok->Tok.is(tok::l_brace)) { 1471 if (ShouldBreakBeforeBrace(Style, InitialToken)) 1472 addUnwrappedLine(); 1473 1474 bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All || 1475 (Style.NamespaceIndentation == FormatStyle::NI_Inner && 1476 DeclarationScopeStack.size() > 1); 1477 parseBlock(/*MustBeDeclaration=*/true, AddLevel); 1478 // Munch the semicolon after a namespace. This is more common than one would 1479 // think. Puttin the semicolon into its own line is very ugly. 1480 if (FormatTok->Tok.is(tok::semi)) 1481 nextToken(); 1482 addUnwrappedLine(); 1483 } 1484 // FIXME: Add error handling. 1485 } 1486 1487 void UnwrappedLineParser::parseNew() { 1488 assert(FormatTok->is(tok::kw_new) && "'new' expected"); 1489 nextToken(); 1490 if (Style.Language != FormatStyle::LK_Java) 1491 return; 1492 1493 // In Java, we can parse everything up to the parens, which aren't optional. 1494 do { 1495 // There should not be a ;, { or } before the new's open paren. 1496 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace)) 1497 return; 1498 1499 // Consume the parens. 1500 if (FormatTok->is(tok::l_paren)) { 1501 parseParens(); 1502 1503 // If there is a class body of an anonymous class, consume that as child. 1504 if (FormatTok->is(tok::l_brace)) 1505 parseChildBlock(); 1506 return; 1507 } 1508 nextToken(); 1509 } while (!eof()); 1510 } 1511 1512 void UnwrappedLineParser::parseForOrWhileLoop() { 1513 assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) && 1514 "'for', 'while' or foreach macro expected"); 1515 nextToken(); 1516 if (FormatTok->Tok.is(tok::l_paren)) 1517 parseParens(); 1518 if (FormatTok->Tok.is(tok::l_brace)) { 1519 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1520 parseBlock(/*MustBeDeclaration=*/false); 1521 addUnwrappedLine(); 1522 } else { 1523 addUnwrappedLine(); 1524 ++Line->Level; 1525 parseStructuralElement(); 1526 --Line->Level; 1527 } 1528 } 1529 1530 void UnwrappedLineParser::parseDoWhile() { 1531 assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected"); 1532 nextToken(); 1533 if (FormatTok->Tok.is(tok::l_brace)) { 1534 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1535 parseBlock(/*MustBeDeclaration=*/false); 1536 if (Style.BraceWrapping.IndentBraces) 1537 addUnwrappedLine(); 1538 } else { 1539 addUnwrappedLine(); 1540 ++Line->Level; 1541 parseStructuralElement(); 1542 --Line->Level; 1543 } 1544 1545 // FIXME: Add error handling. 1546 if (!FormatTok->Tok.is(tok::kw_while)) { 1547 addUnwrappedLine(); 1548 return; 1549 } 1550 1551 nextToken(); 1552 parseStructuralElement(); 1553 } 1554 1555 void UnwrappedLineParser::parseLabel() { 1556 nextToken(); 1557 unsigned OldLineLevel = Line->Level; 1558 if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0)) 1559 --Line->Level; 1560 if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) { 1561 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1562 parseBlock(/*MustBeDeclaration=*/false); 1563 if (FormatTok->Tok.is(tok::kw_break)) { 1564 if (Style.BraceWrapping.AfterControlStatement) 1565 addUnwrappedLine(); 1566 parseStructuralElement(); 1567 } 1568 addUnwrappedLine(); 1569 } else { 1570 if (FormatTok->is(tok::semi)) 1571 nextToken(); 1572 addUnwrappedLine(); 1573 } 1574 Line->Level = OldLineLevel; 1575 } 1576 1577 void UnwrappedLineParser::parseCaseLabel() { 1578 assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected"); 1579 // FIXME: fix handling of complex expressions here. 1580 do { 1581 nextToken(); 1582 } while (!eof() && !FormatTok->Tok.is(tok::colon)); 1583 parseLabel(); 1584 } 1585 1586 void UnwrappedLineParser::parseSwitch() { 1587 assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected"); 1588 nextToken(); 1589 if (FormatTok->Tok.is(tok::l_paren)) 1590 parseParens(); 1591 if (FormatTok->Tok.is(tok::l_brace)) { 1592 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1593 parseBlock(/*MustBeDeclaration=*/false); 1594 addUnwrappedLine(); 1595 } else { 1596 addUnwrappedLine(); 1597 ++Line->Level; 1598 parseStructuralElement(); 1599 --Line->Level; 1600 } 1601 } 1602 1603 void UnwrappedLineParser::parseAccessSpecifier() { 1604 nextToken(); 1605 // Understand Qt's slots. 1606 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots)) 1607 nextToken(); 1608 // Otherwise, we don't know what it is, and we'd better keep the next token. 1609 if (FormatTok->Tok.is(tok::colon)) 1610 nextToken(); 1611 addUnwrappedLine(); 1612 } 1613 1614 bool UnwrappedLineParser::parseEnum() { 1615 // Won't be 'enum' for NS_ENUMs. 1616 if (FormatTok->Tok.is(tok::kw_enum)) 1617 nextToken(); 1618 1619 // In TypeScript, "enum" can also be used as property name, e.g. in interface 1620 // declarations. An "enum" keyword followed by a colon would be a syntax 1621 // error and thus assume it is just an identifier. 1622 if (Style.Language == FormatStyle::LK_JavaScript && 1623 FormatTok->isOneOf(tok::colon, tok::question)) 1624 return false; 1625 1626 // Eat up enum class ... 1627 if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct)) 1628 nextToken(); 1629 1630 while (FormatTok->Tok.getIdentifierInfo() || 1631 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less, 1632 tok::greater, tok::comma, tok::question)) { 1633 nextToken(); 1634 // We can have macros or attributes in between 'enum' and the enum name. 1635 if (FormatTok->is(tok::l_paren)) 1636 parseParens(); 1637 if (FormatTok->is(tok::identifier)) { 1638 nextToken(); 1639 // If there are two identifiers in a row, this is likely an elaborate 1640 // return type. In Java, this can be "implements", etc. 1641 if (Style.Language == FormatStyle::LK_Cpp && 1642 FormatTok->is(tok::identifier)) 1643 return false; 1644 } 1645 } 1646 1647 // Just a declaration or something is wrong. 1648 if (FormatTok->isNot(tok::l_brace)) 1649 return true; 1650 FormatTok->BlockKind = BK_Block; 1651 1652 if (Style.Language == FormatStyle::LK_Java) { 1653 // Java enums are different. 1654 parseJavaEnumBody(); 1655 return true; 1656 } 1657 if (Style.Language == FormatStyle::LK_Proto) { 1658 parseBlock(/*MustBeDeclaration=*/true); 1659 return true; 1660 } 1661 1662 // Parse enum body. 1663 bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true); 1664 if (HasError) { 1665 if (FormatTok->is(tok::semi)) 1666 nextToken(); 1667 addUnwrappedLine(); 1668 } 1669 return true; 1670 1671 // There is no addUnwrappedLine() here so that we fall through to parsing a 1672 // structural element afterwards. Thus, in "enum A {} n, m;", 1673 // "} n, m;" will end up in one unwrapped line. 1674 } 1675 1676 void UnwrappedLineParser::parseJavaEnumBody() { 1677 // Determine whether the enum is simple, i.e. does not have a semicolon or 1678 // constants with class bodies. Simple enums can be formatted like braced 1679 // lists, contracted to a single line, etc. 1680 unsigned StoredPosition = Tokens->getPosition(); 1681 bool IsSimple = true; 1682 FormatToken *Tok = Tokens->getNextToken(); 1683 while (Tok) { 1684 if (Tok->is(tok::r_brace)) 1685 break; 1686 if (Tok->isOneOf(tok::l_brace, tok::semi)) { 1687 IsSimple = false; 1688 break; 1689 } 1690 // FIXME: This will also mark enums with braces in the arguments to enum 1691 // constants as "not simple". This is probably fine in practice, though. 1692 Tok = Tokens->getNextToken(); 1693 } 1694 FormatTok = Tokens->setPosition(StoredPosition); 1695 1696 if (IsSimple) { 1697 parseBracedList(); 1698 addUnwrappedLine(); 1699 return; 1700 } 1701 1702 // Parse the body of a more complex enum. 1703 // First add a line for everything up to the "{". 1704 nextToken(); 1705 addUnwrappedLine(); 1706 ++Line->Level; 1707 1708 // Parse the enum constants. 1709 while (FormatTok) { 1710 if (FormatTok->is(tok::l_brace)) { 1711 // Parse the constant's class body. 1712 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true, 1713 /*MunchSemi=*/false); 1714 } else if (FormatTok->is(tok::l_paren)) { 1715 parseParens(); 1716 } else if (FormatTok->is(tok::comma)) { 1717 nextToken(); 1718 addUnwrappedLine(); 1719 } else if (FormatTok->is(tok::semi)) { 1720 nextToken(); 1721 addUnwrappedLine(); 1722 break; 1723 } else if (FormatTok->is(tok::r_brace)) { 1724 addUnwrappedLine(); 1725 break; 1726 } else { 1727 nextToken(); 1728 } 1729 } 1730 1731 // Parse the class body after the enum's ";" if any. 1732 parseLevel(/*HasOpeningBrace=*/true); 1733 nextToken(); 1734 --Line->Level; 1735 addUnwrappedLine(); 1736 } 1737 1738 void UnwrappedLineParser::parseRecord() { 1739 const FormatToken &InitialToken = *FormatTok; 1740 nextToken(); 1741 1742 // The actual identifier can be a nested name specifier, and in macros 1743 // it is often token-pasted. 1744 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash, 1745 tok::kw___attribute, tok::kw___declspec, 1746 tok::kw_alignas) || 1747 ((Style.Language == FormatStyle::LK_Java || 1748 Style.Language == FormatStyle::LK_JavaScript) && 1749 FormatTok->isOneOf(tok::period, tok::comma))) { 1750 bool IsNonMacroIdentifier = 1751 FormatTok->is(tok::identifier) && 1752 FormatTok->TokenText != FormatTok->TokenText.upper(); 1753 nextToken(); 1754 // We can have macros or attributes in between 'class' and the class name. 1755 if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren)) 1756 parseParens(); 1757 } 1758 1759 // Note that parsing away template declarations here leads to incorrectly 1760 // accepting function declarations as record declarations. 1761 // In general, we cannot solve this problem. Consider: 1762 // class A<int> B() {} 1763 // which can be a function definition or a class definition when B() is a 1764 // macro. If we find enough real-world cases where this is a problem, we 1765 // can parse for the 'template' keyword in the beginning of the statement, 1766 // and thus rule out the record production in case there is no template 1767 // (this would still leave us with an ambiguity between template function 1768 // and class declarations). 1769 if (FormatTok->isOneOf(tok::colon, tok::less)) { 1770 while (!eof()) { 1771 if (FormatTok->is(tok::l_brace)) { 1772 calculateBraceTypes(/*ExpectClassBody=*/true); 1773 if (!tryToParseBracedList()) 1774 break; 1775 } 1776 if (FormatTok->Tok.is(tok::semi)) 1777 return; 1778 nextToken(); 1779 } 1780 } 1781 if (FormatTok->Tok.is(tok::l_brace)) { 1782 if (ShouldBreakBeforeBrace(Style, InitialToken)) 1783 addUnwrappedLine(); 1784 1785 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true, 1786 /*MunchSemi=*/false); 1787 } 1788 // There is no addUnwrappedLine() here so that we fall through to parsing a 1789 // structural element afterwards. Thus, in "class A {} n, m;", 1790 // "} n, m;" will end up in one unwrapped line. 1791 } 1792 1793 void UnwrappedLineParser::parseObjCProtocolList() { 1794 assert(FormatTok->Tok.is(tok::less) && "'<' expected."); 1795 do 1796 nextToken(); 1797 while (!eof() && FormatTok->Tok.isNot(tok::greater)); 1798 nextToken(); // Skip '>'. 1799 } 1800 1801 void UnwrappedLineParser::parseObjCUntilAtEnd() { 1802 do { 1803 if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) { 1804 nextToken(); 1805 addUnwrappedLine(); 1806 break; 1807 } 1808 if (FormatTok->is(tok::l_brace)) { 1809 parseBlock(/*MustBeDeclaration=*/false); 1810 // In ObjC interfaces, nothing should be following the "}". 1811 addUnwrappedLine(); 1812 } else if (FormatTok->is(tok::r_brace)) { 1813 // Ignore stray "}". parseStructuralElement doesn't consume them. 1814 nextToken(); 1815 addUnwrappedLine(); 1816 } else { 1817 parseStructuralElement(); 1818 } 1819 } while (!eof()); 1820 } 1821 1822 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() { 1823 nextToken(); 1824 nextToken(); // interface name 1825 1826 // @interface can be followed by either a base class, or a category. 1827 if (FormatTok->Tok.is(tok::colon)) { 1828 nextToken(); 1829 nextToken(); // base class name 1830 } else if (FormatTok->Tok.is(tok::l_paren)) 1831 // Skip category, if present. 1832 parseParens(); 1833 1834 if (FormatTok->Tok.is(tok::less)) 1835 parseObjCProtocolList(); 1836 1837 if (FormatTok->Tok.is(tok::l_brace)) { 1838 if (Style.BraceWrapping.AfterObjCDeclaration) 1839 addUnwrappedLine(); 1840 parseBlock(/*MustBeDeclaration=*/true); 1841 } 1842 1843 // With instance variables, this puts '}' on its own line. Without instance 1844 // variables, this ends the @interface line. 1845 addUnwrappedLine(); 1846 1847 parseObjCUntilAtEnd(); 1848 } 1849 1850 void UnwrappedLineParser::parseObjCProtocol() { 1851 nextToken(); 1852 nextToken(); // protocol name 1853 1854 if (FormatTok->Tok.is(tok::less)) 1855 parseObjCProtocolList(); 1856 1857 // Check for protocol declaration. 1858 if (FormatTok->Tok.is(tok::semi)) { 1859 nextToken(); 1860 return addUnwrappedLine(); 1861 } 1862 1863 addUnwrappedLine(); 1864 parseObjCUntilAtEnd(); 1865 } 1866 1867 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() { 1868 assert(FormatTok->isOneOf(Keywords.kw_import, tok::kw_export)); 1869 nextToken(); 1870 1871 // Consume the "default" in "export default class/function". 1872 if (FormatTok->is(tok::kw_default)) 1873 nextToken(); 1874 1875 // Consume "function" and "default function", so that these get parsed as 1876 // free-standing JS functions, i.e. do not require a trailing semicolon. 1877 if (FormatTok->is(Keywords.kw_function)) { 1878 nextToken(); 1879 return; 1880 } 1881 1882 // Consume the "abstract" in "export abstract class". 1883 if (FormatTok->is(Keywords.kw_abstract)) 1884 nextToken(); 1885 1886 if (FormatTok->isOneOf(tok::kw_const, tok::kw_class, tok::kw_enum, 1887 Keywords.kw_interface, Keywords.kw_let, 1888 Keywords.kw_var)) 1889 return; // Fall through to parsing the corresponding structure. 1890 1891 while (!eof() && FormatTok->isNot(tok::semi)) { 1892 if (FormatTok->is(tok::l_brace)) { 1893 FormatTok->BlockKind = BK_Block; 1894 parseBracedList(); 1895 } else { 1896 nextToken(); 1897 } 1898 } 1899 } 1900 1901 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line, 1902 StringRef Prefix = "") { 1903 llvm::dbgs() << Prefix << "Line(" << Line.Level << ")" 1904 << (Line.InPPDirective ? " MACRO" : "") << ": "; 1905 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(), 1906 E = Line.Tokens.end(); 1907 I != E; ++I) { 1908 llvm::dbgs() << I->Tok->Tok.getName() << "[" << I->Tok->Type << "] "; 1909 } 1910 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(), 1911 E = Line.Tokens.end(); 1912 I != E; ++I) { 1913 const UnwrappedLineNode &Node = *I; 1914 for (SmallVectorImpl<UnwrappedLine>::const_iterator 1915 I = Node.Children.begin(), 1916 E = Node.Children.end(); 1917 I != E; ++I) { 1918 printDebugInfo(*I, "\nChild: "); 1919 } 1920 } 1921 llvm::dbgs() << "\n"; 1922 } 1923 1924 void UnwrappedLineParser::addUnwrappedLine() { 1925 if (Line->Tokens.empty()) 1926 return; 1927 DEBUG({ 1928 if (CurrentLines == &Lines) 1929 printDebugInfo(*Line); 1930 }); 1931 CurrentLines->push_back(std::move(*Line)); 1932 Line->Tokens.clear(); 1933 if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) { 1934 CurrentLines->append( 1935 std::make_move_iterator(PreprocessorDirectives.begin()), 1936 std::make_move_iterator(PreprocessorDirectives.end())); 1937 PreprocessorDirectives.clear(); 1938 } 1939 } 1940 1941 bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); } 1942 1943 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) { 1944 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) && 1945 FormatTok.NewlinesBefore > 0; 1946 } 1947 1948 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) { 1949 bool JustComments = Line->Tokens.empty(); 1950 for (SmallVectorImpl<FormatToken *>::const_iterator 1951 I = CommentsBeforeNextToken.begin(), 1952 E = CommentsBeforeNextToken.end(); 1953 I != E; ++I) { 1954 if (isOnNewLine(**I) && JustComments) 1955 addUnwrappedLine(); 1956 pushToken(*I); 1957 } 1958 if (NewlineBeforeNext && JustComments) 1959 addUnwrappedLine(); 1960 CommentsBeforeNextToken.clear(); 1961 } 1962 1963 void UnwrappedLineParser::nextToken() { 1964 if (eof()) 1965 return; 1966 flushComments(isOnNewLine(*FormatTok)); 1967 pushToken(FormatTok); 1968 if (Style.Language != FormatStyle::LK_JavaScript) 1969 readToken(); 1970 else 1971 readTokenWithJavaScriptASI(); 1972 } 1973 1974 const FormatToken *UnwrappedLineParser::getPreviousToken() { 1975 // FIXME: This is a dirty way to access the previous token. Find a better 1976 // solution. 1977 if (!Line || Line->Tokens.empty()) 1978 return nullptr; 1979 return Line->Tokens.back().Tok; 1980 } 1981 1982 void UnwrappedLineParser::readToken() { 1983 bool CommentsInCurrentLine = true; 1984 do { 1985 FormatTok = Tokens->getNextToken(); 1986 assert(FormatTok); 1987 while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) && 1988 (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) { 1989 // If there is an unfinished unwrapped line, we flush the preprocessor 1990 // directives only after that unwrapped line was finished later. 1991 bool SwitchToPreprocessorLines = !Line->Tokens.empty(); 1992 ScopedLineState BlockState(*this, SwitchToPreprocessorLines); 1993 // Comments stored before the preprocessor directive need to be output 1994 // before the preprocessor directive, at the same level as the 1995 // preprocessor directive, as we consider them to apply to the directive. 1996 flushComments(isOnNewLine(*FormatTok)); 1997 parsePPDirective(); 1998 } 1999 while (FormatTok->Type == TT_ConflictStart || 2000 FormatTok->Type == TT_ConflictEnd || 2001 FormatTok->Type == TT_ConflictAlternative) { 2002 if (FormatTok->Type == TT_ConflictStart) { 2003 conditionalCompilationStart(/*Unreachable=*/false); 2004 } else if (FormatTok->Type == TT_ConflictAlternative) { 2005 conditionalCompilationAlternative(); 2006 } else if (FormatTok->Type == TT_ConflictEnd) { 2007 conditionalCompilationEnd(); 2008 } 2009 FormatTok = Tokens->getNextToken(); 2010 FormatTok->MustBreakBefore = true; 2011 } 2012 2013 if (!PPStack.empty() && (PPStack.back() == PP_Unreachable) && 2014 !Line->InPPDirective) { 2015 continue; 2016 } 2017 2018 if (!FormatTok->Tok.is(tok::comment)) 2019 return; 2020 if (isOnNewLine(*FormatTok) || FormatTok->IsFirst) { 2021 CommentsInCurrentLine = false; 2022 } 2023 if (CommentsInCurrentLine) { 2024 pushToken(FormatTok); 2025 } else { 2026 CommentsBeforeNextToken.push_back(FormatTok); 2027 } 2028 } while (!eof()); 2029 } 2030 2031 void UnwrappedLineParser::pushToken(FormatToken *Tok) { 2032 Line->Tokens.push_back(UnwrappedLineNode(Tok)); 2033 if (MustBreakBeforeNextToken) { 2034 Line->Tokens.back().Tok->MustBreakBefore = true; 2035 MustBreakBeforeNextToken = false; 2036 } 2037 } 2038 2039 } // end namespace format 2040 } // end namespace clang 2041