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