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/Support/Debug.h" 18 19 #define DEBUG_TYPE "format-parser" 20 21 namespace clang { 22 namespace format { 23 24 class FormatTokenSource { 25 public: 26 virtual ~FormatTokenSource() {} 27 virtual FormatToken *getNextToken() = 0; 28 29 virtual unsigned getPosition() = 0; 30 virtual FormatToken *setPosition(unsigned Position) = 0; 31 }; 32 33 namespace { 34 35 class ScopedDeclarationState { 36 public: 37 ScopedDeclarationState(UnwrappedLine &Line, std::vector<bool> &Stack, 38 bool MustBeDeclaration) 39 : Line(Line), Stack(Stack) { 40 Line.MustBeDeclaration = MustBeDeclaration; 41 Stack.push_back(MustBeDeclaration); 42 } 43 ~ScopedDeclarationState() { 44 Stack.pop_back(); 45 if (!Stack.empty()) 46 Line.MustBeDeclaration = Stack.back(); 47 else 48 Line.MustBeDeclaration = true; 49 } 50 51 private: 52 UnwrappedLine &Line; 53 std::vector<bool> &Stack; 54 }; 55 56 class ScopedMacroState : public FormatTokenSource { 57 public: 58 ScopedMacroState(UnwrappedLine &Line, FormatTokenSource *&TokenSource, 59 FormatToken *&ResetToken, bool &StructuralError) 60 : Line(Line), TokenSource(TokenSource), ResetToken(ResetToken), 61 PreviousLineLevel(Line.Level), PreviousTokenSource(TokenSource), 62 StructuralError(StructuralError), 63 PreviousStructuralError(StructuralError), Token(nullptr) { 64 TokenSource = this; 65 Line.Level = 0; 66 Line.InPPDirective = true; 67 } 68 69 ~ScopedMacroState() { 70 TokenSource = PreviousTokenSource; 71 ResetToken = Token; 72 Line.InPPDirective = false; 73 Line.Level = PreviousLineLevel; 74 StructuralError = PreviousStructuralError; 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 bool &StructuralError; 114 bool PreviousStructuralError; 115 116 FormatToken *Token; 117 }; 118 119 } // end anonymous namespace 120 121 class ScopedLineState { 122 public: 123 ScopedLineState(UnwrappedLineParser &Parser, 124 bool SwitchToPreprocessorLines = false) 125 : Parser(Parser), OriginalLines(Parser.CurrentLines) { 126 if (SwitchToPreprocessorLines) 127 Parser.CurrentLines = &Parser.PreprocessorDirectives; 128 else if (!Parser.Line->Tokens.empty()) 129 Parser.CurrentLines = &Parser.Line->Tokens.back().Children; 130 PreBlockLine = std::move(Parser.Line); 131 Parser.Line = llvm::make_unique<UnwrappedLine>(); 132 Parser.Line->Level = PreBlockLine->Level; 133 Parser.Line->InPPDirective = PreBlockLine->InPPDirective; 134 } 135 136 ~ScopedLineState() { 137 if (!Parser.Line->Tokens.empty()) { 138 Parser.addUnwrappedLine(); 139 } 140 assert(Parser.Line->Tokens.empty()); 141 Parser.Line = std::move(PreBlockLine); 142 if (Parser.CurrentLines == &Parser.PreprocessorDirectives) 143 Parser.MustBreakBeforeNextToken = true; 144 Parser.CurrentLines = OriginalLines; 145 } 146 147 private: 148 UnwrappedLineParser &Parser; 149 150 std::unique_ptr<UnwrappedLine> PreBlockLine; 151 SmallVectorImpl<UnwrappedLine> *OriginalLines; 152 }; 153 154 class CompoundStatementIndenter { 155 public: 156 CompoundStatementIndenter(UnwrappedLineParser *Parser, 157 const FormatStyle &Style, unsigned &LineLevel) 158 : LineLevel(LineLevel), OldLineLevel(LineLevel) { 159 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman) { 160 Parser->addUnwrappedLine(); 161 } else if (Style.BreakBeforeBraces == FormatStyle::BS_GNU) { 162 Parser->addUnwrappedLine(); 163 ++LineLevel; 164 } 165 } 166 ~CompoundStatementIndenter() { LineLevel = OldLineLevel; } 167 168 private: 169 unsigned &LineLevel; 170 unsigned OldLineLevel; 171 }; 172 173 namespace { 174 175 class IndexedTokenSource : public FormatTokenSource { 176 public: 177 IndexedTokenSource(ArrayRef<FormatToken *> Tokens) 178 : Tokens(Tokens), Position(-1) {} 179 180 FormatToken *getNextToken() override { 181 ++Position; 182 return Tokens[Position]; 183 } 184 185 unsigned getPosition() override { 186 assert(Position >= 0); 187 return Position; 188 } 189 190 FormatToken *setPosition(unsigned P) override { 191 Position = P; 192 return Tokens[Position]; 193 } 194 195 void reset() { Position = -1; } 196 197 private: 198 ArrayRef<FormatToken *> Tokens; 199 int Position; 200 }; 201 202 } // end anonymous namespace 203 204 UnwrappedLineParser::UnwrappedLineParser(const FormatStyle &Style, 205 ArrayRef<FormatToken *> Tokens, 206 UnwrappedLineConsumer &Callback) 207 : Line(new UnwrappedLine), MustBreakBeforeNextToken(false), 208 CurrentLines(&Lines), StructuralError(false), Style(Style), 209 Tokens(nullptr), Callback(Callback), AllTokens(Tokens), 210 PPBranchLevel(-1) {} 211 212 void UnwrappedLineParser::reset() { 213 PPBranchLevel = -1; 214 Line.reset(new UnwrappedLine); 215 CommentsBeforeNextToken.clear(); 216 FormatTok = nullptr; 217 MustBreakBeforeNextToken = false; 218 PreprocessorDirectives.clear(); 219 CurrentLines = &Lines; 220 DeclarationScopeStack.clear(); 221 StructuralError = false; 222 PPStack.clear(); 223 } 224 225 bool UnwrappedLineParser::parse() { 226 IndexedTokenSource TokenSource(AllTokens); 227 do { 228 DEBUG(llvm::dbgs() << "----\n"); 229 reset(); 230 Tokens = &TokenSource; 231 TokenSource.reset(); 232 233 readToken(); 234 parseFile(); 235 // Create line with eof token. 236 pushToken(FormatTok); 237 addUnwrappedLine(); 238 239 for (SmallVectorImpl<UnwrappedLine>::iterator I = Lines.begin(), 240 E = Lines.end(); 241 I != E; ++I) { 242 Callback.consumeUnwrappedLine(*I); 243 } 244 Callback.finishRun(); 245 Lines.clear(); 246 while (!PPLevelBranchIndex.empty() && 247 PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) { 248 PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1); 249 PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1); 250 } 251 if (!PPLevelBranchIndex.empty()) { 252 ++PPLevelBranchIndex.back(); 253 assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size()); 254 assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back()); 255 } 256 } while (!PPLevelBranchIndex.empty()); 257 258 return StructuralError; 259 } 260 261 void UnwrappedLineParser::parseFile() { 262 ScopedDeclarationState DeclarationState( 263 *Line, DeclarationScopeStack, 264 /*MustBeDeclaration=*/ !Line->InPPDirective); 265 parseLevel(/*HasOpeningBrace=*/false); 266 // Make sure to format the remaining tokens. 267 flushComments(true); 268 addUnwrappedLine(); 269 } 270 271 void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) { 272 bool SwitchLabelEncountered = false; 273 do { 274 switch (FormatTok->Tok.getKind()) { 275 case tok::comment: 276 nextToken(); 277 addUnwrappedLine(); 278 break; 279 case tok::l_brace: 280 // FIXME: Add parameter whether this can happen - if this happens, we must 281 // be in a non-declaration context. 282 parseBlock(/*MustBeDeclaration=*/false); 283 addUnwrappedLine(); 284 break; 285 case tok::r_brace: 286 if (HasOpeningBrace) 287 return; 288 StructuralError = true; 289 nextToken(); 290 addUnwrappedLine(); 291 break; 292 case tok::kw_default: 293 case tok::kw_case: 294 if (!SwitchLabelEncountered && 295 (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1))) 296 ++Line->Level; 297 SwitchLabelEncountered = true; 298 parseStructuralElement(); 299 break; 300 default: 301 parseStructuralElement(); 302 break; 303 } 304 } while (!eof()); 305 } 306 307 void UnwrappedLineParser::calculateBraceTypes() { 308 // We'll parse forward through the tokens until we hit 309 // a closing brace or eof - note that getNextToken() will 310 // parse macros, so this will magically work inside macro 311 // definitions, too. 312 unsigned StoredPosition = Tokens->getPosition(); 313 unsigned Position = StoredPosition; 314 FormatToken *Tok = FormatTok; 315 // Keep a stack of positions of lbrace tokens. We will 316 // update information about whether an lbrace starts a 317 // braced init list or a different block during the loop. 318 SmallVector<FormatToken *, 8> LBraceStack; 319 assert(Tok->Tok.is(tok::l_brace)); 320 do { 321 // Get next none-comment token. 322 FormatToken *NextTok; 323 unsigned ReadTokens = 0; 324 do { 325 NextTok = Tokens->getNextToken(); 326 ++ReadTokens; 327 } while (NextTok->is(tok::comment)); 328 329 switch (Tok->Tok.getKind()) { 330 case tok::l_brace: 331 LBraceStack.push_back(Tok); 332 break; 333 case tok::r_brace: 334 if (!LBraceStack.empty()) { 335 if (LBraceStack.back()->BlockKind == BK_Unknown) { 336 bool ProbablyBracedList = false; 337 if (Style.Language == FormatStyle::LK_Proto) { 338 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square); 339 } else { 340 // Using OriginalColumn to distinguish between ObjC methods and 341 // binary operators is a bit hacky. 342 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) && 343 NextTok->OriginalColumn == 0; 344 345 // If there is a comma, semicolon or right paren after the closing 346 // brace, we assume this is a braced initializer list. Note that 347 // regardless how we mark inner braces here, we will overwrite the 348 // BlockKind later if we parse a braced list (where all blocks 349 // inside are by default braced lists), or when we explicitly detect 350 // blocks (for example while parsing lambdas). 351 // 352 // We exclude + and - as they can be ObjC visibility modifiers. 353 ProbablyBracedList = 354 NextTok->isOneOf(tok::comma, tok::semi, tok::period, tok::colon, 355 tok::r_paren, tok::r_square, tok::l_brace, 356 tok::l_paren, tok::ellipsis) || 357 (NextTok->isBinaryOperator() && !NextIsObjCMethod); 358 } 359 if (ProbablyBracedList) { 360 Tok->BlockKind = BK_BracedInit; 361 LBraceStack.back()->BlockKind = BK_BracedInit; 362 } else { 363 Tok->BlockKind = BK_Block; 364 LBraceStack.back()->BlockKind = BK_Block; 365 } 366 } 367 LBraceStack.pop_back(); 368 } 369 break; 370 case tok::at: 371 case tok::semi: 372 case tok::kw_if: 373 case tok::kw_while: 374 case tok::kw_for: 375 case tok::kw_switch: 376 case tok::kw_try: 377 if (!LBraceStack.empty()) 378 LBraceStack.back()->BlockKind = BK_Block; 379 break; 380 default: 381 break; 382 } 383 Tok = NextTok; 384 Position += ReadTokens; 385 } while (Tok->Tok.isNot(tok::eof) && !LBraceStack.empty()); 386 // Assume other blocks for all unclosed opening braces. 387 for (unsigned i = 0, e = LBraceStack.size(); i != e; ++i) { 388 if (LBraceStack[i]->BlockKind == BK_Unknown) 389 LBraceStack[i]->BlockKind = BK_Block; 390 } 391 392 FormatTok = Tokens->setPosition(StoredPosition); 393 } 394 395 void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel, 396 bool MunchSemi) { 397 assert(FormatTok->Tok.is(tok::l_brace) && "'{' expected"); 398 unsigned InitialLevel = Line->Level; 399 nextToken(); 400 401 addUnwrappedLine(); 402 403 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack, 404 MustBeDeclaration); 405 if (AddLevel) 406 ++Line->Level; 407 parseLevel(/*HasOpeningBrace=*/true); 408 409 if (!FormatTok->Tok.is(tok::r_brace)) { 410 Line->Level = InitialLevel; 411 StructuralError = true; 412 return; 413 } 414 415 nextToken(); // Munch the closing brace. 416 if (MunchSemi && FormatTok->Tok.is(tok::semi)) 417 nextToken(); 418 Line->Level = InitialLevel; 419 } 420 421 static bool IsGoogScope(const UnwrappedLine &Line) { 422 if (Line.Tokens.size() < 4) 423 return false; 424 auto I = Line.Tokens.begin(); 425 if (I->Tok->TokenText != "goog") 426 return false; 427 ++I; 428 if (I->Tok->isNot(tok::period)) 429 return false; 430 ++I; 431 if (I->Tok->TokenText != "scope") 432 return false; 433 ++I; 434 return I->Tok->is(tok::l_paren); 435 } 436 437 static bool ShouldBreakBeforeBrace(const FormatStyle &Style, 438 const FormatToken &InitialToken) { 439 switch (Style.BreakBeforeBraces) { 440 case FormatStyle::BS_Linux: 441 return InitialToken.isOneOf(tok::kw_namespace, tok::kw_class); 442 case FormatStyle::BS_Allman: 443 case FormatStyle::BS_GNU: 444 return true; 445 default: 446 return false; 447 } 448 } 449 450 void UnwrappedLineParser::parseChildBlock() { 451 FormatTok->BlockKind = BK_Block; 452 nextToken(); 453 { 454 bool GoogScope = 455 Style.Language == FormatStyle::LK_JavaScript && IsGoogScope(*Line); 456 ScopedLineState LineState(*this); 457 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack, 458 /*MustBeDeclaration=*/false); 459 Line->Level += GoogScope ? 0 : 1; 460 parseLevel(/*HasOpeningBrace=*/true); 461 Line->Level -= GoogScope ? 0 : 1; 462 } 463 nextToken(); 464 } 465 466 void UnwrappedLineParser::parsePPDirective() { 467 assert(FormatTok->Tok.is(tok::hash) && "'#' expected"); 468 ScopedMacroState MacroState(*Line, Tokens, FormatTok, StructuralError); 469 nextToken(); 470 471 if (!FormatTok->Tok.getIdentifierInfo()) { 472 parsePPUnknown(); 473 return; 474 } 475 476 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) { 477 case tok::pp_define: 478 parsePPDefine(); 479 return; 480 case tok::pp_if: 481 parsePPIf(/*IfDef=*/false); 482 break; 483 case tok::pp_ifdef: 484 case tok::pp_ifndef: 485 parsePPIf(/*IfDef=*/true); 486 break; 487 case tok::pp_else: 488 parsePPElse(); 489 break; 490 case tok::pp_elif: 491 parsePPElIf(); 492 break; 493 case tok::pp_endif: 494 parsePPEndIf(); 495 break; 496 default: 497 parsePPUnknown(); 498 break; 499 } 500 } 501 502 void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) { 503 if (Unreachable || (!PPStack.empty() && PPStack.back() == PP_Unreachable)) 504 PPStack.push_back(PP_Unreachable); 505 else 506 PPStack.push_back(PP_Conditional); 507 } 508 509 void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) { 510 ++PPBranchLevel; 511 assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size()); 512 if (PPBranchLevel == (int)PPLevelBranchIndex.size()) { 513 PPLevelBranchIndex.push_back(0); 514 PPLevelBranchCount.push_back(0); 515 } 516 PPChainBranchIndex.push(0); 517 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0; 518 conditionalCompilationCondition(Unreachable || Skip); 519 } 520 521 void UnwrappedLineParser::conditionalCompilationAlternative() { 522 if (!PPStack.empty()) 523 PPStack.pop_back(); 524 assert(PPBranchLevel < (int)PPLevelBranchIndex.size()); 525 if (!PPChainBranchIndex.empty()) 526 ++PPChainBranchIndex.top(); 527 conditionalCompilationCondition( 528 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() && 529 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top()); 530 } 531 532 void UnwrappedLineParser::conditionalCompilationEnd() { 533 assert(PPBranchLevel < (int)PPLevelBranchIndex.size()); 534 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) { 535 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) { 536 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1; 537 } 538 } 539 // Guard against #endif's without #if. 540 if (PPBranchLevel > 0) 541 --PPBranchLevel; 542 if (!PPChainBranchIndex.empty()) 543 PPChainBranchIndex.pop(); 544 if (!PPStack.empty()) 545 PPStack.pop_back(); 546 } 547 548 void UnwrappedLineParser::parsePPIf(bool IfDef) { 549 nextToken(); 550 bool IsLiteralFalse = (FormatTok->Tok.isLiteral() && 551 StringRef(FormatTok->Tok.getLiteralData(), 552 FormatTok->Tok.getLength()) == "0") || 553 FormatTok->Tok.is(tok::kw_false); 554 conditionalCompilationStart(!IfDef && IsLiteralFalse); 555 parsePPUnknown(); 556 } 557 558 void UnwrappedLineParser::parsePPElse() { 559 conditionalCompilationAlternative(); 560 parsePPUnknown(); 561 } 562 563 void UnwrappedLineParser::parsePPElIf() { parsePPElse(); } 564 565 void UnwrappedLineParser::parsePPEndIf() { 566 conditionalCompilationEnd(); 567 parsePPUnknown(); 568 } 569 570 void UnwrappedLineParser::parsePPDefine() { 571 nextToken(); 572 573 if (FormatTok->Tok.getKind() != tok::identifier) { 574 parsePPUnknown(); 575 return; 576 } 577 nextToken(); 578 if (FormatTok->Tok.getKind() == tok::l_paren && 579 FormatTok->WhitespaceRange.getBegin() == 580 FormatTok->WhitespaceRange.getEnd()) { 581 parseParens(); 582 } 583 addUnwrappedLine(); 584 Line->Level = 1; 585 586 // Errors during a preprocessor directive can only affect the layout of the 587 // preprocessor directive, and thus we ignore them. An alternative approach 588 // would be to use the same approach we use on the file level (no 589 // re-indentation if there was a structural error) within the macro 590 // definition. 591 parseFile(); 592 } 593 594 void UnwrappedLineParser::parsePPUnknown() { 595 do { 596 nextToken(); 597 } while (!eof()); 598 addUnwrappedLine(); 599 } 600 601 // Here we blacklist certain tokens that are not usually the first token in an 602 // unwrapped line. This is used in attempt to distinguish macro calls without 603 // trailing semicolons from other constructs split to several lines. 604 bool tokenCanStartNewLine(clang::Token Tok) { 605 // Semicolon can be a null-statement, l_square can be a start of a macro or 606 // a C++11 attribute, but this doesn't seem to be common. 607 return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) && 608 Tok.isNot(tok::l_square) && 609 // Tokens that can only be used as binary operators and a part of 610 // overloaded operator names. 611 Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) && 612 Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) && 613 Tok.isNot(tok::less) && Tok.isNot(tok::greater) && 614 Tok.isNot(tok::slash) && Tok.isNot(tok::percent) && 615 Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) && 616 Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) && 617 Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) && 618 Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) && 619 Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) && 620 Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) && 621 Tok.isNot(tok::lesslessequal) && 622 // Colon is used in labels, base class lists, initializer lists, 623 // range-based for loops, ternary operator, but should never be the 624 // first token in an unwrapped line. 625 Tok.isNot(tok::colon) && 626 // 'noexcept' is a trailing annotation. 627 Tok.isNot(tok::kw_noexcept); 628 } 629 630 void UnwrappedLineParser::parseStructuralElement() { 631 assert(!FormatTok->Tok.is(tok::l_brace)); 632 switch (FormatTok->Tok.getKind()) { 633 case tok::at: 634 nextToken(); 635 if (FormatTok->Tok.is(tok::l_brace)) { 636 parseBracedList(); 637 break; 638 } 639 switch (FormatTok->Tok.getObjCKeywordID()) { 640 case tok::objc_public: 641 case tok::objc_protected: 642 case tok::objc_package: 643 case tok::objc_private: 644 return parseAccessSpecifier(); 645 case tok::objc_interface: 646 case tok::objc_implementation: 647 return parseObjCInterfaceOrImplementation(); 648 case tok::objc_protocol: 649 return parseObjCProtocol(); 650 case tok::objc_end: 651 return; // Handled by the caller. 652 case tok::objc_optional: 653 case tok::objc_required: 654 nextToken(); 655 addUnwrappedLine(); 656 return; 657 default: 658 break; 659 } 660 break; 661 case tok::kw_namespace: 662 parseNamespace(); 663 return; 664 case tok::kw_inline: 665 nextToken(); 666 if (FormatTok->Tok.is(tok::kw_namespace)) { 667 parseNamespace(); 668 return; 669 } 670 break; 671 case tok::kw_public: 672 case tok::kw_protected: 673 case tok::kw_private: 674 parseAccessSpecifier(); 675 return; 676 case tok::kw_if: 677 parseIfThenElse(); 678 return; 679 case tok::kw_for: 680 case tok::kw_while: 681 parseForOrWhileLoop(); 682 return; 683 case tok::kw_do: 684 parseDoWhile(); 685 return; 686 case tok::kw_switch: 687 parseSwitch(); 688 return; 689 case tok::kw_default: 690 nextToken(); 691 parseLabel(); 692 return; 693 case tok::kw_case: 694 parseCaseLabel(); 695 return; 696 case tok::kw_try: 697 parseTryCatch(); 698 return; 699 case tok::kw_extern: 700 nextToken(); 701 if (FormatTok->Tok.is(tok::string_literal)) { 702 nextToken(); 703 if (FormatTok->Tok.is(tok::l_brace)) { 704 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false); 705 addUnwrappedLine(); 706 return; 707 } 708 } 709 break; 710 case tok::identifier: 711 if (FormatTok->IsForEachMacro) { 712 parseForOrWhileLoop(); 713 return; 714 } 715 // In all other cases, parse the declaration. 716 break; 717 default: 718 break; 719 } 720 do { 721 switch (FormatTok->Tok.getKind()) { 722 case tok::at: 723 nextToken(); 724 if (FormatTok->Tok.is(tok::l_brace)) 725 parseBracedList(); 726 break; 727 case tok::kw_enum: 728 parseEnum(); 729 break; 730 case tok::kw_typedef: 731 nextToken(); 732 // FIXME: Use the IdentifierTable instead. 733 if (FormatTok->TokenText == "NS_ENUM") 734 parseEnum(); 735 break; 736 case tok::kw_struct: 737 case tok::kw_union: 738 case tok::kw_class: 739 parseRecord(); 740 // A record declaration or definition is always the start of a structural 741 // element. 742 break; 743 case tok::semi: 744 nextToken(); 745 addUnwrappedLine(); 746 return; 747 case tok::r_brace: 748 addUnwrappedLine(); 749 return; 750 case tok::l_paren: 751 parseParens(); 752 break; 753 case tok::caret: 754 nextToken(); 755 if (FormatTok->Tok.isAnyIdentifier() || 756 FormatTok->isSimpleTypeSpecifier()) 757 nextToken(); 758 if (FormatTok->is(tok::l_paren)) 759 parseParens(); 760 if (FormatTok->is(tok::l_brace)) 761 parseChildBlock(); 762 break; 763 case tok::l_brace: 764 if (!tryToParseBracedList()) { 765 // A block outside of parentheses must be the last part of a 766 // structural element. 767 // FIXME: Figure out cases where this is not true, and add projections 768 // for them (the one we know is missing are lambdas). 769 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach) 770 addUnwrappedLine(); 771 FormatTok->Type = TT_FunctionLBrace; 772 parseBlock(/*MustBeDeclaration=*/false); 773 addUnwrappedLine(); 774 return; 775 } 776 // Otherwise this was a braced init list, and the structural 777 // element continues. 778 break; 779 case tok::kw_try: 780 // We arrive here when parsing function-try blocks. 781 parseTryCatch(); 782 return; 783 case tok::identifier: { 784 StringRef Text = FormatTok->TokenText; 785 // Parse function literal unless 'function' is the first token in a line 786 // in which case this should be treated as a free-standing function. 787 if (Style.Language == FormatStyle::LK_JavaScript && Text == "function" && 788 Line->Tokens.size() > 0) { 789 tryToParseJSFunction(); 790 break; 791 } 792 nextToken(); 793 if (Line->Tokens.size() == 1) { 794 if (FormatTok->Tok.is(tok::colon)) { 795 parseLabel(); 796 return; 797 } 798 // Recognize function-like macro usages without trailing semicolon. 799 if (FormatTok->Tok.is(tok::l_paren)) { 800 parseParens(); 801 if (FormatTok->NewlinesBefore > 0 && 802 tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) { 803 addUnwrappedLine(); 804 return; 805 } 806 } else if (FormatTok->HasUnescapedNewline && Text.size() >= 5 && 807 Text == Text.upper()) { 808 // Recognize free-standing macros like Q_OBJECT. 809 addUnwrappedLine(); 810 return; 811 } 812 } 813 break; 814 } 815 case tok::equal: 816 nextToken(); 817 if (FormatTok->Tok.is(tok::l_brace)) { 818 parseBracedList(); 819 } 820 break; 821 case tok::l_square: 822 parseSquare(); 823 break; 824 default: 825 nextToken(); 826 break; 827 } 828 } while (!eof()); 829 } 830 831 bool UnwrappedLineParser::tryToParseLambda() { 832 // FIXME: This is a dirty way to access the previous token. Find a better 833 // solution. 834 if (!Line->Tokens.empty() && 835 (Line->Tokens.back().Tok->isOneOf(tok::identifier, tok::kw_operator) || 836 Line->Tokens.back().Tok->closesScope() || 837 Line->Tokens.back().Tok->isSimpleTypeSpecifier())) { 838 nextToken(); 839 return false; 840 } 841 assert(FormatTok->is(tok::l_square)); 842 FormatToken &LSquare = *FormatTok; 843 if (!tryToParseLambdaIntroducer()) 844 return false; 845 846 while (FormatTok->isNot(tok::l_brace)) { 847 if (FormatTok->isSimpleTypeSpecifier()) { 848 nextToken(); 849 continue; 850 } 851 switch (FormatTok->Tok.getKind()) { 852 case tok::l_brace: 853 break; 854 case tok::l_paren: 855 parseParens(); 856 break; 857 case tok::less: 858 case tok::greater: 859 case tok::identifier: 860 case tok::coloncolon: 861 case tok::kw_mutable: 862 nextToken(); 863 break; 864 case tok::arrow: 865 FormatTok->Type = TT_TrailingReturnArrow; 866 nextToken(); 867 break; 868 default: 869 return true; 870 } 871 } 872 LSquare.Type = TT_LambdaLSquare; 873 parseChildBlock(); 874 return true; 875 } 876 877 bool UnwrappedLineParser::tryToParseLambdaIntroducer() { 878 nextToken(); 879 if (FormatTok->is(tok::equal)) { 880 nextToken(); 881 if (FormatTok->is(tok::r_square)) { 882 nextToken(); 883 return true; 884 } 885 if (FormatTok->isNot(tok::comma)) 886 return false; 887 nextToken(); 888 } else if (FormatTok->is(tok::amp)) { 889 nextToken(); 890 if (FormatTok->is(tok::r_square)) { 891 nextToken(); 892 return true; 893 } 894 if (!FormatTok->isOneOf(tok::comma, tok::identifier)) { 895 return false; 896 } 897 if (FormatTok->is(tok::comma)) 898 nextToken(); 899 } else if (FormatTok->is(tok::r_square)) { 900 nextToken(); 901 return true; 902 } 903 do { 904 if (FormatTok->is(tok::amp)) 905 nextToken(); 906 if (!FormatTok->isOneOf(tok::identifier, tok::kw_this)) 907 return false; 908 nextToken(); 909 if (FormatTok->is(tok::ellipsis)) 910 nextToken(); 911 if (FormatTok->is(tok::comma)) { 912 nextToken(); 913 } else if (FormatTok->is(tok::r_square)) { 914 nextToken(); 915 return true; 916 } else { 917 return false; 918 } 919 } while (!eof()); 920 return false; 921 } 922 923 void UnwrappedLineParser::tryToParseJSFunction() { 924 nextToken(); 925 926 // Consume function name. 927 if (FormatTok->is(tok::identifier)) 928 nextToken(); 929 930 if (FormatTok->isNot(tok::l_paren)) 931 return; 932 nextToken(); 933 while (FormatTok->isNot(tok::l_brace)) { 934 // Err on the side of caution in order to avoid consuming the full file in 935 // case of incomplete code. 936 if (!FormatTok->isOneOf(tok::identifier, tok::comma, tok::r_paren, 937 tok::comment)) 938 return; 939 nextToken(); 940 } 941 parseChildBlock(); 942 } 943 944 bool UnwrappedLineParser::tryToParseBracedList() { 945 if (FormatTok->BlockKind == BK_Unknown) 946 calculateBraceTypes(); 947 assert(FormatTok->BlockKind != BK_Unknown); 948 if (FormatTok->BlockKind == BK_Block) 949 return false; 950 parseBracedList(); 951 return true; 952 } 953 954 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons) { 955 bool HasError = false; 956 nextToken(); 957 958 // FIXME: Once we have an expression parser in the UnwrappedLineParser, 959 // replace this by using parseAssigmentExpression() inside. 960 do { 961 if (Style.Language == FormatStyle::LK_JavaScript && 962 FormatTok->TokenText == "function") { 963 tryToParseJSFunction(); 964 continue; 965 } 966 switch (FormatTok->Tok.getKind()) { 967 case tok::caret: 968 nextToken(); 969 if (FormatTok->is(tok::l_brace)) { 970 parseChildBlock(); 971 } 972 break; 973 case tok::l_square: 974 tryToParseLambda(); 975 break; 976 case tok::l_brace: 977 // Assume there are no blocks inside a braced init list apart 978 // from the ones we explicitly parse out (like lambdas). 979 FormatTok->BlockKind = BK_BracedInit; 980 parseBracedList(); 981 break; 982 case tok::r_brace: 983 nextToken(); 984 return !HasError; 985 case tok::semi: 986 HasError = true; 987 if (!ContinueOnSemicolons) 988 return !HasError; 989 nextToken(); 990 break; 991 case tok::comma: 992 nextToken(); 993 break; 994 default: 995 nextToken(); 996 break; 997 } 998 } while (!eof()); 999 return false; 1000 } 1001 1002 void UnwrappedLineParser::parseParens() { 1003 assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected."); 1004 nextToken(); 1005 do { 1006 switch (FormatTok->Tok.getKind()) { 1007 case tok::l_paren: 1008 parseParens(); 1009 break; 1010 case tok::r_paren: 1011 nextToken(); 1012 return; 1013 case tok::r_brace: 1014 // A "}" inside parenthesis is an error if there wasn't a matching "{". 1015 return; 1016 case tok::l_square: 1017 tryToParseLambda(); 1018 break; 1019 case tok::l_brace: { 1020 if (!tryToParseBracedList()) { 1021 parseChildBlock(); 1022 } 1023 break; 1024 } 1025 case tok::at: 1026 nextToken(); 1027 if (FormatTok->Tok.is(tok::l_brace)) 1028 parseBracedList(); 1029 break; 1030 default: 1031 nextToken(); 1032 break; 1033 } 1034 } while (!eof()); 1035 } 1036 1037 void UnwrappedLineParser::parseSquare() { 1038 assert(FormatTok->Tok.is(tok::l_square) && "'[' expected."); 1039 if (tryToParseLambda()) 1040 return; 1041 do { 1042 switch (FormatTok->Tok.getKind()) { 1043 case tok::l_paren: 1044 parseParens(); 1045 break; 1046 case tok::r_square: 1047 nextToken(); 1048 return; 1049 case tok::r_brace: 1050 // A "}" inside parenthesis is an error if there wasn't a matching "{". 1051 return; 1052 case tok::l_square: 1053 parseSquare(); 1054 break; 1055 case tok::l_brace: { 1056 if (!tryToParseBracedList()) { 1057 parseChildBlock(); 1058 } 1059 break; 1060 } 1061 case tok::at: 1062 nextToken(); 1063 if (FormatTok->Tok.is(tok::l_brace)) 1064 parseBracedList(); 1065 break; 1066 default: 1067 nextToken(); 1068 break; 1069 } 1070 } while (!eof()); 1071 } 1072 1073 void UnwrappedLineParser::parseIfThenElse() { 1074 assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected"); 1075 nextToken(); 1076 if (FormatTok->Tok.is(tok::l_paren)) 1077 parseParens(); 1078 bool NeedsUnwrappedLine = false; 1079 if (FormatTok->Tok.is(tok::l_brace)) { 1080 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1081 parseBlock(/*MustBeDeclaration=*/false); 1082 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman || 1083 Style.BreakBeforeBraces == FormatStyle::BS_GNU) { 1084 addUnwrappedLine(); 1085 } else { 1086 NeedsUnwrappedLine = true; 1087 } 1088 } else { 1089 addUnwrappedLine(); 1090 ++Line->Level; 1091 parseStructuralElement(); 1092 --Line->Level; 1093 } 1094 if (FormatTok->Tok.is(tok::kw_else)) { 1095 if (Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup) 1096 addUnwrappedLine(); 1097 nextToken(); 1098 if (FormatTok->Tok.is(tok::l_brace)) { 1099 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1100 parseBlock(/*MustBeDeclaration=*/false); 1101 addUnwrappedLine(); 1102 } else if (FormatTok->Tok.is(tok::kw_if)) { 1103 parseIfThenElse(); 1104 } else { 1105 addUnwrappedLine(); 1106 ++Line->Level; 1107 parseStructuralElement(); 1108 --Line->Level; 1109 } 1110 } else if (NeedsUnwrappedLine) { 1111 addUnwrappedLine(); 1112 } 1113 } 1114 1115 void UnwrappedLineParser::parseTryCatch() { 1116 assert(FormatTok->is(tok::kw_try) && "'try' expected"); 1117 nextToken(); 1118 bool NeedsUnwrappedLine = false; 1119 if (FormatTok->is(tok::colon)) { 1120 // We are in a function try block, what comes is an initializer list. 1121 nextToken(); 1122 while (FormatTok->is(tok::identifier)) { 1123 nextToken(); 1124 if (FormatTok->is(tok::l_paren)) 1125 parseParens(); 1126 else 1127 StructuralError = true; 1128 if (FormatTok->is(tok::comma)) 1129 nextToken(); 1130 } 1131 } 1132 if (FormatTok->is(tok::l_brace)) { 1133 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1134 parseBlock(/*MustBeDeclaration=*/false); 1135 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman || 1136 Style.BreakBeforeBraces == FormatStyle::BS_GNU || 1137 Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup) { 1138 addUnwrappedLine(); 1139 } else { 1140 NeedsUnwrappedLine = true; 1141 } 1142 } else if (!FormatTok->is(tok::kw_catch)) { 1143 // The C++ standard requires a compound-statement after a try. 1144 // If there's none, we try to assume there's a structuralElement 1145 // and try to continue. 1146 StructuralError = true; 1147 addUnwrappedLine(); 1148 ++Line->Level; 1149 parseStructuralElement(); 1150 --Line->Level; 1151 } 1152 while (FormatTok->is(tok::kw_catch) || 1153 (Style.Language == FormatStyle::LK_JavaScript && 1154 FormatTok->TokenText == "finally")) { 1155 nextToken(); 1156 while (FormatTok->isNot(tok::l_brace)) { 1157 if (FormatTok->is(tok::l_paren)) { 1158 parseParens(); 1159 continue; 1160 } 1161 if (FormatTok->isOneOf(tok::semi, tok::r_brace)) 1162 return; 1163 nextToken(); 1164 } 1165 NeedsUnwrappedLine = false; 1166 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1167 parseBlock(/*MustBeDeclaration=*/false); 1168 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman || 1169 Style.BreakBeforeBraces == FormatStyle::BS_GNU || 1170 Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup) { 1171 addUnwrappedLine(); 1172 } else { 1173 NeedsUnwrappedLine = true; 1174 } 1175 } 1176 if (NeedsUnwrappedLine) { 1177 addUnwrappedLine(); 1178 } 1179 } 1180 1181 void UnwrappedLineParser::parseNamespace() { 1182 assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected"); 1183 1184 const FormatToken &InitialToken = *FormatTok; 1185 nextToken(); 1186 if (FormatTok->Tok.is(tok::identifier)) 1187 nextToken(); 1188 if (FormatTok->Tok.is(tok::l_brace)) { 1189 if (ShouldBreakBeforeBrace(Style, InitialToken)) 1190 addUnwrappedLine(); 1191 1192 bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All || 1193 (Style.NamespaceIndentation == FormatStyle::NI_Inner && 1194 DeclarationScopeStack.size() > 1); 1195 parseBlock(/*MustBeDeclaration=*/true, AddLevel); 1196 // Munch the semicolon after a namespace. This is more common than one would 1197 // think. Puttin the semicolon into its own line is very ugly. 1198 if (FormatTok->Tok.is(tok::semi)) 1199 nextToken(); 1200 addUnwrappedLine(); 1201 } 1202 // FIXME: Add error handling. 1203 } 1204 1205 void UnwrappedLineParser::parseForOrWhileLoop() { 1206 assert((FormatTok->Tok.is(tok::kw_for) || FormatTok->Tok.is(tok::kw_while) || 1207 FormatTok->IsForEachMacro) && 1208 "'for', 'while' or foreach macro expected"); 1209 nextToken(); 1210 if (FormatTok->Tok.is(tok::l_paren)) 1211 parseParens(); 1212 if (FormatTok->Tok.is(tok::l_brace)) { 1213 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1214 parseBlock(/*MustBeDeclaration=*/false); 1215 addUnwrappedLine(); 1216 } else { 1217 addUnwrappedLine(); 1218 ++Line->Level; 1219 parseStructuralElement(); 1220 --Line->Level; 1221 } 1222 } 1223 1224 void UnwrappedLineParser::parseDoWhile() { 1225 assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected"); 1226 nextToken(); 1227 if (FormatTok->Tok.is(tok::l_brace)) { 1228 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1229 parseBlock(/*MustBeDeclaration=*/false); 1230 if (Style.BreakBeforeBraces == FormatStyle::BS_GNU) 1231 addUnwrappedLine(); 1232 } else { 1233 addUnwrappedLine(); 1234 ++Line->Level; 1235 parseStructuralElement(); 1236 --Line->Level; 1237 } 1238 1239 // FIXME: Add error handling. 1240 if (!FormatTok->Tok.is(tok::kw_while)) { 1241 addUnwrappedLine(); 1242 return; 1243 } 1244 1245 nextToken(); 1246 parseStructuralElement(); 1247 } 1248 1249 void UnwrappedLineParser::parseLabel() { 1250 nextToken(); 1251 unsigned OldLineLevel = Line->Level; 1252 if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0)) 1253 --Line->Level; 1254 if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) { 1255 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1256 parseBlock(/*MustBeDeclaration=*/false); 1257 if (FormatTok->Tok.is(tok::kw_break)) { 1258 // "break;" after "}" on its own line only for BS_Allman and BS_GNU 1259 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman || 1260 Style.BreakBeforeBraces == FormatStyle::BS_GNU) { 1261 addUnwrappedLine(); 1262 } 1263 parseStructuralElement(); 1264 } 1265 addUnwrappedLine(); 1266 } else { 1267 addUnwrappedLine(); 1268 } 1269 Line->Level = OldLineLevel; 1270 } 1271 1272 void UnwrappedLineParser::parseCaseLabel() { 1273 assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected"); 1274 // FIXME: fix handling of complex expressions here. 1275 do { 1276 nextToken(); 1277 } while (!eof() && !FormatTok->Tok.is(tok::colon)); 1278 parseLabel(); 1279 } 1280 1281 void UnwrappedLineParser::parseSwitch() { 1282 assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected"); 1283 nextToken(); 1284 if (FormatTok->Tok.is(tok::l_paren)) 1285 parseParens(); 1286 if (FormatTok->Tok.is(tok::l_brace)) { 1287 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1288 parseBlock(/*MustBeDeclaration=*/false); 1289 addUnwrappedLine(); 1290 } else { 1291 addUnwrappedLine(); 1292 ++Line->Level; 1293 parseStructuralElement(); 1294 --Line->Level; 1295 } 1296 } 1297 1298 void UnwrappedLineParser::parseAccessSpecifier() { 1299 nextToken(); 1300 // Understand Qt's slots. 1301 if (FormatTok->is(tok::identifier) && 1302 (FormatTok->TokenText == "slots" || FormatTok->TokenText == "Q_SLOTS")) 1303 nextToken(); 1304 // Otherwise, we don't know what it is, and we'd better keep the next token. 1305 if (FormatTok->Tok.is(tok::colon)) 1306 nextToken(); 1307 addUnwrappedLine(); 1308 } 1309 1310 void UnwrappedLineParser::parseEnum() { 1311 if (FormatTok->Tok.is(tok::kw_enum)) { 1312 // Won't be 'enum' for NS_ENUMs. 1313 nextToken(); 1314 } 1315 // Eat up enum class ... 1316 if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct)) 1317 nextToken(); 1318 while (FormatTok->Tok.getIdentifierInfo() || 1319 FormatTok->isOneOf(tok::colon, tok::coloncolon)) { 1320 nextToken(); 1321 // We can have macros or attributes in between 'enum' and the enum name. 1322 if (FormatTok->Tok.is(tok::l_paren)) { 1323 parseParens(); 1324 } 1325 if (FormatTok->Tok.is(tok::identifier)) 1326 nextToken(); 1327 } 1328 if (FormatTok->Tok.is(tok::l_brace)) { 1329 FormatTok->BlockKind = BK_Block; 1330 bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true); 1331 if (HasError) { 1332 if (FormatTok->is(tok::semi)) 1333 nextToken(); 1334 addUnwrappedLine(); 1335 } 1336 } 1337 // We fall through to parsing a structural element afterwards, so that in 1338 // enum A {} n, m; 1339 // "} n, m;" will end up in one unwrapped line. 1340 } 1341 1342 void UnwrappedLineParser::parseRecord() { 1343 const FormatToken &InitialToken = *FormatTok; 1344 nextToken(); 1345 if (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw___attribute, 1346 tok::kw___declspec, tok::kw_alignas)) { 1347 nextToken(); 1348 // We can have macros or attributes in between 'class' and the class name. 1349 if (FormatTok->Tok.is(tok::l_paren)) { 1350 parseParens(); 1351 } 1352 // The actual identifier can be a nested name specifier, and in macros 1353 // it is often token-pasted. 1354 while (FormatTok->Tok.is(tok::identifier) || 1355 FormatTok->Tok.is(tok::coloncolon) || 1356 FormatTok->Tok.is(tok::hashhash)) 1357 nextToken(); 1358 1359 // Note that parsing away template declarations here leads to incorrectly 1360 // accepting function declarations as record declarations. 1361 // In general, we cannot solve this problem. Consider: 1362 // class A<int> B() {} 1363 // which can be a function definition or a class definition when B() is a 1364 // macro. If we find enough real-world cases where this is a problem, we 1365 // can parse for the 'template' keyword in the beginning of the statement, 1366 // and thus rule out the record production in case there is no template 1367 // (this would still leave us with an ambiguity between template function 1368 // and class declarations). 1369 if (FormatTok->Tok.is(tok::colon) || FormatTok->Tok.is(tok::less)) { 1370 while (!eof() && FormatTok->Tok.isNot(tok::l_brace)) { 1371 if (FormatTok->Tok.is(tok::semi)) 1372 return; 1373 nextToken(); 1374 } 1375 } 1376 } 1377 if (FormatTok->Tok.is(tok::l_brace)) { 1378 if (ShouldBreakBeforeBrace(Style, InitialToken)) 1379 addUnwrappedLine(); 1380 1381 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true, 1382 /*MunchSemi=*/false); 1383 } 1384 // We fall through to parsing a structural element afterwards, so 1385 // class A {} n, m; 1386 // will end up in one unwrapped line. 1387 } 1388 1389 void UnwrappedLineParser::parseObjCProtocolList() { 1390 assert(FormatTok->Tok.is(tok::less) && "'<' expected."); 1391 do 1392 nextToken(); 1393 while (!eof() && FormatTok->Tok.isNot(tok::greater)); 1394 nextToken(); // Skip '>'. 1395 } 1396 1397 void UnwrappedLineParser::parseObjCUntilAtEnd() { 1398 do { 1399 if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) { 1400 nextToken(); 1401 addUnwrappedLine(); 1402 break; 1403 } 1404 if (FormatTok->is(tok::l_brace)) { 1405 parseBlock(/*MustBeDeclaration=*/false); 1406 // In ObjC interfaces, nothing should be following the "}". 1407 addUnwrappedLine(); 1408 } else if (FormatTok->is(tok::r_brace)) { 1409 // Ignore stray "}". parseStructuralElement doesn't consume them. 1410 nextToken(); 1411 addUnwrappedLine(); 1412 } else { 1413 parseStructuralElement(); 1414 } 1415 } while (!eof()); 1416 } 1417 1418 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() { 1419 nextToken(); 1420 nextToken(); // interface name 1421 1422 // @interface can be followed by either a base class, or a category. 1423 if (FormatTok->Tok.is(tok::colon)) { 1424 nextToken(); 1425 nextToken(); // base class name 1426 } else if (FormatTok->Tok.is(tok::l_paren)) 1427 // Skip category, if present. 1428 parseParens(); 1429 1430 if (FormatTok->Tok.is(tok::less)) 1431 parseObjCProtocolList(); 1432 1433 if (FormatTok->Tok.is(tok::l_brace)) { 1434 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman || 1435 Style.BreakBeforeBraces == FormatStyle::BS_GNU) 1436 addUnwrappedLine(); 1437 parseBlock(/*MustBeDeclaration=*/true); 1438 } 1439 1440 // With instance variables, this puts '}' on its own line. Without instance 1441 // variables, this ends the @interface line. 1442 addUnwrappedLine(); 1443 1444 parseObjCUntilAtEnd(); 1445 } 1446 1447 void UnwrappedLineParser::parseObjCProtocol() { 1448 nextToken(); 1449 nextToken(); // protocol name 1450 1451 if (FormatTok->Tok.is(tok::less)) 1452 parseObjCProtocolList(); 1453 1454 // Check for protocol declaration. 1455 if (FormatTok->Tok.is(tok::semi)) { 1456 nextToken(); 1457 return addUnwrappedLine(); 1458 } 1459 1460 addUnwrappedLine(); 1461 parseObjCUntilAtEnd(); 1462 } 1463 1464 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line, 1465 StringRef Prefix = "") { 1466 llvm::dbgs() << Prefix << "Line(" << Line.Level << ")" 1467 << (Line.InPPDirective ? " MACRO" : "") << ": "; 1468 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(), 1469 E = Line.Tokens.end(); 1470 I != E; ++I) { 1471 llvm::dbgs() << I->Tok->Tok.getName() << "[" << I->Tok->Type << "] "; 1472 } 1473 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(), 1474 E = Line.Tokens.end(); 1475 I != E; ++I) { 1476 const UnwrappedLineNode &Node = *I; 1477 for (SmallVectorImpl<UnwrappedLine>::const_iterator 1478 I = Node.Children.begin(), 1479 E = Node.Children.end(); 1480 I != E; ++I) { 1481 printDebugInfo(*I, "\nChild: "); 1482 } 1483 } 1484 llvm::dbgs() << "\n"; 1485 } 1486 1487 void UnwrappedLineParser::addUnwrappedLine() { 1488 if (Line->Tokens.empty()) 1489 return; 1490 DEBUG({ 1491 if (CurrentLines == &Lines) 1492 printDebugInfo(*Line); 1493 }); 1494 CurrentLines->push_back(*Line); 1495 Line->Tokens.clear(); 1496 if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) { 1497 for (SmallVectorImpl<UnwrappedLine>::iterator 1498 I = PreprocessorDirectives.begin(), 1499 E = PreprocessorDirectives.end(); 1500 I != E; ++I) { 1501 CurrentLines->push_back(*I); 1502 } 1503 PreprocessorDirectives.clear(); 1504 } 1505 } 1506 1507 bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); } 1508 1509 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) { 1510 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) && 1511 FormatTok.NewlinesBefore > 0; 1512 } 1513 1514 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) { 1515 bool JustComments = Line->Tokens.empty(); 1516 for (SmallVectorImpl<FormatToken *>::const_iterator 1517 I = CommentsBeforeNextToken.begin(), 1518 E = CommentsBeforeNextToken.end(); 1519 I != E; ++I) { 1520 if (isOnNewLine(**I) && JustComments) { 1521 addUnwrappedLine(); 1522 } 1523 pushToken(*I); 1524 } 1525 if (NewlineBeforeNext && JustComments) { 1526 addUnwrappedLine(); 1527 } 1528 CommentsBeforeNextToken.clear(); 1529 } 1530 1531 void UnwrappedLineParser::nextToken() { 1532 if (eof()) 1533 return; 1534 flushComments(isOnNewLine(*FormatTok)); 1535 pushToken(FormatTok); 1536 readToken(); 1537 } 1538 1539 void UnwrappedLineParser::readToken() { 1540 bool CommentsInCurrentLine = true; 1541 do { 1542 FormatTok = Tokens->getNextToken(); 1543 assert(FormatTok); 1544 while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) && 1545 (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) { 1546 // If there is an unfinished unwrapped line, we flush the preprocessor 1547 // directives only after that unwrapped line was finished later. 1548 bool SwitchToPreprocessorLines = 1549 !Line->Tokens.empty() && CurrentLines == &Lines; 1550 ScopedLineState BlockState(*this, SwitchToPreprocessorLines); 1551 // Comments stored before the preprocessor directive need to be output 1552 // before the preprocessor directive, at the same level as the 1553 // preprocessor directive, as we consider them to apply to the directive. 1554 flushComments(isOnNewLine(*FormatTok)); 1555 parsePPDirective(); 1556 } 1557 while (FormatTok->Type == TT_ConflictStart || 1558 FormatTok->Type == TT_ConflictEnd || 1559 FormatTok->Type == TT_ConflictAlternative) { 1560 if (FormatTok->Type == TT_ConflictStart) { 1561 conditionalCompilationStart(/*Unreachable=*/false); 1562 } else if (FormatTok->Type == TT_ConflictAlternative) { 1563 conditionalCompilationAlternative(); 1564 } else if (FormatTok->Type == TT_ConflictEnd) { 1565 conditionalCompilationEnd(); 1566 } 1567 FormatTok = Tokens->getNextToken(); 1568 FormatTok->MustBreakBefore = true; 1569 } 1570 1571 if (!PPStack.empty() && (PPStack.back() == PP_Unreachable) && 1572 !Line->InPPDirective) { 1573 continue; 1574 } 1575 1576 if (!FormatTok->Tok.is(tok::comment)) 1577 return; 1578 if (isOnNewLine(*FormatTok) || FormatTok->IsFirst) { 1579 CommentsInCurrentLine = false; 1580 } 1581 if (CommentsInCurrentLine) { 1582 pushToken(FormatTok); 1583 } else { 1584 CommentsBeforeNextToken.push_back(FormatTok); 1585 } 1586 } while (!eof()); 1587 } 1588 1589 void UnwrappedLineParser::pushToken(FormatToken *Tok) { 1590 Line->Tokens.push_back(UnwrappedLineNode(Tok)); 1591 if (MustBreakBeforeNextToken) { 1592 Line->Tokens.back().Tok->MustBreakBefore = true; 1593 MustBreakBeforeNextToken = false; 1594 } 1595 } 1596 1597 } // end namespace format 1598 } // end namespace clang 1599