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