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