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 --Line->Level; 1434 } 1435 } else if (NeedsUnwrappedLine) { 1436 addUnwrappedLine(); 1437 } 1438 } 1439 1440 void UnwrappedLineParser::parseTryCatch() { 1441 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected"); 1442 nextToken(); 1443 bool NeedsUnwrappedLine = false; 1444 if (FormatTok->is(tok::colon)) { 1445 // We are in a function try block, what comes is an initializer list. 1446 nextToken(); 1447 while (FormatTok->is(tok::identifier)) { 1448 nextToken(); 1449 if (FormatTok->is(tok::l_paren)) 1450 parseParens(); 1451 if (FormatTok->is(tok::comma)) 1452 nextToken(); 1453 } 1454 } 1455 // Parse try with resource. 1456 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) { 1457 parseParens(); 1458 } 1459 if (FormatTok->is(tok::l_brace)) { 1460 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1461 parseBlock(/*MustBeDeclaration=*/false); 1462 if (Style.BraceWrapping.BeforeCatch) { 1463 addUnwrappedLine(); 1464 } else { 1465 NeedsUnwrappedLine = true; 1466 } 1467 } else if (!FormatTok->is(tok::kw_catch)) { 1468 // The C++ standard requires a compound-statement after a try. 1469 // If there's none, we try to assume there's a structuralElement 1470 // and try to continue. 1471 addUnwrappedLine(); 1472 ++Line->Level; 1473 parseStructuralElement(); 1474 --Line->Level; 1475 } 1476 while (1) { 1477 if (FormatTok->is(tok::at)) 1478 nextToken(); 1479 if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except, 1480 tok::kw___finally) || 1481 ((Style.Language == FormatStyle::LK_Java || 1482 Style.Language == FormatStyle::LK_JavaScript) && 1483 FormatTok->is(Keywords.kw_finally)) || 1484 (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) || 1485 FormatTok->Tok.isObjCAtKeyword(tok::objc_finally)))) 1486 break; 1487 nextToken(); 1488 while (FormatTok->isNot(tok::l_brace)) { 1489 if (FormatTok->is(tok::l_paren)) { 1490 parseParens(); 1491 continue; 1492 } 1493 if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof)) 1494 return; 1495 nextToken(); 1496 } 1497 NeedsUnwrappedLine = false; 1498 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1499 parseBlock(/*MustBeDeclaration=*/false); 1500 if (Style.BraceWrapping.BeforeCatch) 1501 addUnwrappedLine(); 1502 else 1503 NeedsUnwrappedLine = true; 1504 } 1505 if (NeedsUnwrappedLine) 1506 addUnwrappedLine(); 1507 } 1508 1509 void UnwrappedLineParser::parseNamespace() { 1510 assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected"); 1511 1512 const FormatToken &InitialToken = *FormatTok; 1513 nextToken(); 1514 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon)) 1515 nextToken(); 1516 if (FormatTok->Tok.is(tok::l_brace)) { 1517 if (ShouldBreakBeforeBrace(Style, InitialToken)) 1518 addUnwrappedLine(); 1519 1520 bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All || 1521 (Style.NamespaceIndentation == FormatStyle::NI_Inner && 1522 DeclarationScopeStack.size() > 1); 1523 parseBlock(/*MustBeDeclaration=*/true, AddLevel); 1524 // Munch the semicolon after a namespace. This is more common than one would 1525 // think. Puttin the semicolon into its own line is very ugly. 1526 if (FormatTok->Tok.is(tok::semi)) 1527 nextToken(); 1528 addUnwrappedLine(); 1529 } 1530 // FIXME: Add error handling. 1531 } 1532 1533 void UnwrappedLineParser::parseNew() { 1534 assert(FormatTok->is(tok::kw_new) && "'new' expected"); 1535 nextToken(); 1536 if (Style.Language != FormatStyle::LK_Java) 1537 return; 1538 1539 // In Java, we can parse everything up to the parens, which aren't optional. 1540 do { 1541 // There should not be a ;, { or } before the new's open paren. 1542 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace)) 1543 return; 1544 1545 // Consume the parens. 1546 if (FormatTok->is(tok::l_paren)) { 1547 parseParens(); 1548 1549 // If there is a class body of an anonymous class, consume that as child. 1550 if (FormatTok->is(tok::l_brace)) 1551 parseChildBlock(); 1552 return; 1553 } 1554 nextToken(); 1555 } while (!eof()); 1556 } 1557 1558 void UnwrappedLineParser::parseForOrWhileLoop() { 1559 assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) && 1560 "'for', 'while' or foreach macro expected"); 1561 nextToken(); 1562 if (FormatTok->Tok.is(tok::l_paren)) 1563 parseParens(); 1564 if (FormatTok->Tok.is(tok::l_brace)) { 1565 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1566 parseBlock(/*MustBeDeclaration=*/false); 1567 addUnwrappedLine(); 1568 } else { 1569 addUnwrappedLine(); 1570 ++Line->Level; 1571 parseStructuralElement(); 1572 --Line->Level; 1573 } 1574 } 1575 1576 void UnwrappedLineParser::parseDoWhile() { 1577 assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected"); 1578 nextToken(); 1579 if (FormatTok->Tok.is(tok::l_brace)) { 1580 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1581 parseBlock(/*MustBeDeclaration=*/false); 1582 if (Style.BraceWrapping.IndentBraces) 1583 addUnwrappedLine(); 1584 } else { 1585 addUnwrappedLine(); 1586 ++Line->Level; 1587 parseStructuralElement(); 1588 --Line->Level; 1589 } 1590 1591 // FIXME: Add error handling. 1592 if (!FormatTok->Tok.is(tok::kw_while)) { 1593 addUnwrappedLine(); 1594 return; 1595 } 1596 1597 nextToken(); 1598 parseStructuralElement(); 1599 } 1600 1601 void UnwrappedLineParser::parseLabel() { 1602 nextToken(); 1603 unsigned OldLineLevel = Line->Level; 1604 if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0)) 1605 --Line->Level; 1606 if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) { 1607 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1608 parseBlock(/*MustBeDeclaration=*/false); 1609 if (FormatTok->Tok.is(tok::kw_break)) { 1610 if (Style.BraceWrapping.AfterControlStatement) 1611 addUnwrappedLine(); 1612 parseStructuralElement(); 1613 } 1614 addUnwrappedLine(); 1615 } else { 1616 if (FormatTok->is(tok::semi)) 1617 nextToken(); 1618 addUnwrappedLine(); 1619 } 1620 Line->Level = OldLineLevel; 1621 if (FormatTok->isNot(tok::l_brace)) { 1622 parseStructuralElement(); 1623 addUnwrappedLine(); 1624 } 1625 } 1626 1627 void UnwrappedLineParser::parseCaseLabel() { 1628 assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected"); 1629 // FIXME: fix handling of complex expressions here. 1630 do { 1631 nextToken(); 1632 } while (!eof() && !FormatTok->Tok.is(tok::colon)); 1633 parseLabel(); 1634 } 1635 1636 void UnwrappedLineParser::parseSwitch() { 1637 assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected"); 1638 nextToken(); 1639 if (FormatTok->Tok.is(tok::l_paren)) 1640 parseParens(); 1641 if (FormatTok->Tok.is(tok::l_brace)) { 1642 CompoundStatementIndenter Indenter(this, Style, Line->Level); 1643 parseBlock(/*MustBeDeclaration=*/false); 1644 addUnwrappedLine(); 1645 } else { 1646 addUnwrappedLine(); 1647 ++Line->Level; 1648 parseStructuralElement(); 1649 --Line->Level; 1650 } 1651 } 1652 1653 void UnwrappedLineParser::parseAccessSpecifier() { 1654 nextToken(); 1655 // Understand Qt's slots. 1656 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots)) 1657 nextToken(); 1658 // Otherwise, we don't know what it is, and we'd better keep the next token. 1659 if (FormatTok->Tok.is(tok::colon)) 1660 nextToken(); 1661 addUnwrappedLine(); 1662 } 1663 1664 bool UnwrappedLineParser::parseEnum() { 1665 // Won't be 'enum' for NS_ENUMs. 1666 if (FormatTok->Tok.is(tok::kw_enum)) 1667 nextToken(); 1668 1669 // In TypeScript, "enum" can also be used as property name, e.g. in interface 1670 // declarations. An "enum" keyword followed by a colon would be a syntax 1671 // error and thus assume it is just an identifier. 1672 if (Style.Language == FormatStyle::LK_JavaScript && 1673 FormatTok->isOneOf(tok::colon, tok::question)) 1674 return false; 1675 1676 // Eat up enum class ... 1677 if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct)) 1678 nextToken(); 1679 1680 while (FormatTok->Tok.getIdentifierInfo() || 1681 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less, 1682 tok::greater, tok::comma, tok::question)) { 1683 nextToken(); 1684 // We can have macros or attributes in between 'enum' and the enum name. 1685 if (FormatTok->is(tok::l_paren)) 1686 parseParens(); 1687 if (FormatTok->is(tok::identifier)) { 1688 nextToken(); 1689 // If there are two identifiers in a row, this is likely an elaborate 1690 // return type. In Java, this can be "implements", etc. 1691 if (Style.Language == FormatStyle::LK_Cpp && 1692 FormatTok->is(tok::identifier)) 1693 return false; 1694 } 1695 } 1696 1697 // Just a declaration or something is wrong. 1698 if (FormatTok->isNot(tok::l_brace)) 1699 return true; 1700 FormatTok->BlockKind = BK_Block; 1701 1702 if (Style.Language == FormatStyle::LK_Java) { 1703 // Java enums are different. 1704 parseJavaEnumBody(); 1705 return true; 1706 } 1707 if (Style.Language == FormatStyle::LK_Proto) { 1708 parseBlock(/*MustBeDeclaration=*/true); 1709 return true; 1710 } 1711 1712 // Parse enum body. 1713 bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true); 1714 if (HasError) { 1715 if (FormatTok->is(tok::semi)) 1716 nextToken(); 1717 addUnwrappedLine(); 1718 } 1719 return true; 1720 1721 // There is no addUnwrappedLine() here so that we fall through to parsing a 1722 // structural element afterwards. Thus, in "enum A {} n, m;", 1723 // "} n, m;" will end up in one unwrapped line. 1724 } 1725 1726 void UnwrappedLineParser::parseJavaEnumBody() { 1727 // Determine whether the enum is simple, i.e. does not have a semicolon or 1728 // constants with class bodies. Simple enums can be formatted like braced 1729 // lists, contracted to a single line, etc. 1730 unsigned StoredPosition = Tokens->getPosition(); 1731 bool IsSimple = true; 1732 FormatToken *Tok = Tokens->getNextToken(); 1733 while (Tok) { 1734 if (Tok->is(tok::r_brace)) 1735 break; 1736 if (Tok->isOneOf(tok::l_brace, tok::semi)) { 1737 IsSimple = false; 1738 break; 1739 } 1740 // FIXME: This will also mark enums with braces in the arguments to enum 1741 // constants as "not simple". This is probably fine in practice, though. 1742 Tok = Tokens->getNextToken(); 1743 } 1744 FormatTok = Tokens->setPosition(StoredPosition); 1745 1746 if (IsSimple) { 1747 parseBracedList(); 1748 addUnwrappedLine(); 1749 return; 1750 } 1751 1752 // Parse the body of a more complex enum. 1753 // First add a line for everything up to the "{". 1754 nextToken(); 1755 addUnwrappedLine(); 1756 ++Line->Level; 1757 1758 // Parse the enum constants. 1759 while (FormatTok) { 1760 if (FormatTok->is(tok::l_brace)) { 1761 // Parse the constant's class body. 1762 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true, 1763 /*MunchSemi=*/false); 1764 } else if (FormatTok->is(tok::l_paren)) { 1765 parseParens(); 1766 } else if (FormatTok->is(tok::comma)) { 1767 nextToken(); 1768 addUnwrappedLine(); 1769 } else if (FormatTok->is(tok::semi)) { 1770 nextToken(); 1771 addUnwrappedLine(); 1772 break; 1773 } else if (FormatTok->is(tok::r_brace)) { 1774 addUnwrappedLine(); 1775 break; 1776 } else { 1777 nextToken(); 1778 } 1779 } 1780 1781 // Parse the class body after the enum's ";" if any. 1782 parseLevel(/*HasOpeningBrace=*/true); 1783 nextToken(); 1784 --Line->Level; 1785 addUnwrappedLine(); 1786 } 1787 1788 void UnwrappedLineParser::parseRecord() { 1789 const FormatToken &InitialToken = *FormatTok; 1790 nextToken(); 1791 1792 // The actual identifier can be a nested name specifier, and in macros 1793 // it is often token-pasted. 1794 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash, 1795 tok::kw___attribute, tok::kw___declspec, 1796 tok::kw_alignas) || 1797 ((Style.Language == FormatStyle::LK_Java || 1798 Style.Language == FormatStyle::LK_JavaScript) && 1799 FormatTok->isOneOf(tok::period, tok::comma))) { 1800 bool IsNonMacroIdentifier = 1801 FormatTok->is(tok::identifier) && 1802 FormatTok->TokenText != FormatTok->TokenText.upper(); 1803 nextToken(); 1804 // We can have macros or attributes in between 'class' and the class name. 1805 if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren)) 1806 parseParens(); 1807 } 1808 1809 // Note that parsing away template declarations here leads to incorrectly 1810 // accepting function declarations as record declarations. 1811 // In general, we cannot solve this problem. Consider: 1812 // class A<int> B() {} 1813 // which can be a function definition or a class definition when B() is a 1814 // macro. If we find enough real-world cases where this is a problem, we 1815 // can parse for the 'template' keyword in the beginning of the statement, 1816 // and thus rule out the record production in case there is no template 1817 // (this would still leave us with an ambiguity between template function 1818 // and class declarations). 1819 if (FormatTok->isOneOf(tok::colon, tok::less)) { 1820 while (!eof()) { 1821 if (FormatTok->is(tok::l_brace)) { 1822 calculateBraceTypes(/*ExpectClassBody=*/true); 1823 if (!tryToParseBracedList()) 1824 break; 1825 } 1826 if (FormatTok->Tok.is(tok::semi)) 1827 return; 1828 nextToken(); 1829 } 1830 } 1831 if (FormatTok->Tok.is(tok::l_brace)) { 1832 if (ShouldBreakBeforeBrace(Style, InitialToken)) 1833 addUnwrappedLine(); 1834 1835 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true, 1836 /*MunchSemi=*/false); 1837 } 1838 // There is no addUnwrappedLine() here so that we fall through to parsing a 1839 // structural element afterwards. Thus, in "class A {} n, m;", 1840 // "} n, m;" will end up in one unwrapped line. 1841 } 1842 1843 void UnwrappedLineParser::parseObjCProtocolList() { 1844 assert(FormatTok->Tok.is(tok::less) && "'<' expected."); 1845 do 1846 nextToken(); 1847 while (!eof() && FormatTok->Tok.isNot(tok::greater)); 1848 nextToken(); // Skip '>'. 1849 } 1850 1851 void UnwrappedLineParser::parseObjCUntilAtEnd() { 1852 do { 1853 if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) { 1854 nextToken(); 1855 addUnwrappedLine(); 1856 break; 1857 } 1858 if (FormatTok->is(tok::l_brace)) { 1859 parseBlock(/*MustBeDeclaration=*/false); 1860 // In ObjC interfaces, nothing should be following the "}". 1861 addUnwrappedLine(); 1862 } else if (FormatTok->is(tok::r_brace)) { 1863 // Ignore stray "}". parseStructuralElement doesn't consume them. 1864 nextToken(); 1865 addUnwrappedLine(); 1866 } else { 1867 parseStructuralElement(); 1868 } 1869 } while (!eof()); 1870 } 1871 1872 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() { 1873 nextToken(); 1874 nextToken(); // interface name 1875 1876 // @interface can be followed by either a base class, or a category. 1877 if (FormatTok->Tok.is(tok::colon)) { 1878 nextToken(); 1879 nextToken(); // base class name 1880 } else if (FormatTok->Tok.is(tok::l_paren)) 1881 // Skip category, if present. 1882 parseParens(); 1883 1884 if (FormatTok->Tok.is(tok::less)) 1885 parseObjCProtocolList(); 1886 1887 if (FormatTok->Tok.is(tok::l_brace)) { 1888 if (Style.BraceWrapping.AfterObjCDeclaration) 1889 addUnwrappedLine(); 1890 parseBlock(/*MustBeDeclaration=*/true); 1891 } 1892 1893 // With instance variables, this puts '}' on its own line. Without instance 1894 // variables, this ends the @interface line. 1895 addUnwrappedLine(); 1896 1897 parseObjCUntilAtEnd(); 1898 } 1899 1900 void UnwrappedLineParser::parseObjCProtocol() { 1901 nextToken(); 1902 nextToken(); // protocol name 1903 1904 if (FormatTok->Tok.is(tok::less)) 1905 parseObjCProtocolList(); 1906 1907 // Check for protocol declaration. 1908 if (FormatTok->Tok.is(tok::semi)) { 1909 nextToken(); 1910 return addUnwrappedLine(); 1911 } 1912 1913 addUnwrappedLine(); 1914 parseObjCUntilAtEnd(); 1915 } 1916 1917 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() { 1918 bool IsImport = FormatTok->is(Keywords.kw_import); 1919 assert(IsImport || FormatTok->is(tok::kw_export)); 1920 nextToken(); 1921 1922 // Consume the "default" in "export default class/function". 1923 if (FormatTok->is(tok::kw_default)) 1924 nextToken(); 1925 1926 // Consume "async function", "function" and "default function", so that these 1927 // get parsed as free-standing JS functions, i.e. do not require a trailing 1928 // semicolon. 1929 if (FormatTok->is(Keywords.kw_async)) 1930 nextToken(); 1931 if (FormatTok->is(Keywords.kw_function)) { 1932 nextToken(); 1933 return; 1934 } 1935 1936 // For imports, `export *`, `export {...}`, consume the rest of the line up 1937 // to the terminating `;`. For everything else, just return and continue 1938 // parsing the structural element, i.e. the declaration or expression for 1939 // `export default`. 1940 if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) && 1941 !FormatTok->isStringLiteral()) 1942 return; 1943 1944 while (!eof() && FormatTok->isNot(tok::semi)) { 1945 if (FormatTok->is(tok::l_brace)) { 1946 FormatTok->BlockKind = BK_Block; 1947 parseBracedList(); 1948 } else { 1949 nextToken(); 1950 } 1951 } 1952 } 1953 1954 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line, 1955 StringRef Prefix = "") { 1956 llvm::dbgs() << Prefix << "Line(" << Line.Level << ")" 1957 << (Line.InPPDirective ? " MACRO" : "") << ": "; 1958 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(), 1959 E = Line.Tokens.end(); 1960 I != E; ++I) { 1961 llvm::dbgs() << I->Tok->Tok.getName() << "[" << I->Tok->Type << "] "; 1962 } 1963 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(), 1964 E = Line.Tokens.end(); 1965 I != E; ++I) { 1966 const UnwrappedLineNode &Node = *I; 1967 for (SmallVectorImpl<UnwrappedLine>::const_iterator 1968 I = Node.Children.begin(), 1969 E = Node.Children.end(); 1970 I != E; ++I) { 1971 printDebugInfo(*I, "\nChild: "); 1972 } 1973 } 1974 llvm::dbgs() << "\n"; 1975 } 1976 1977 void UnwrappedLineParser::addUnwrappedLine() { 1978 if (Line->Tokens.empty()) 1979 return; 1980 DEBUG({ 1981 if (CurrentLines == &Lines) 1982 printDebugInfo(*Line); 1983 }); 1984 CurrentLines->push_back(std::move(*Line)); 1985 Line->Tokens.clear(); 1986 if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) { 1987 CurrentLines->append( 1988 std::make_move_iterator(PreprocessorDirectives.begin()), 1989 std::make_move_iterator(PreprocessorDirectives.end())); 1990 PreprocessorDirectives.clear(); 1991 } 1992 } 1993 1994 bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); } 1995 1996 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) { 1997 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) && 1998 FormatTok.NewlinesBefore > 0; 1999 } 2000 2001 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) { 2002 bool JustComments = Line->Tokens.empty(); 2003 for (SmallVectorImpl<FormatToken *>::const_iterator 2004 I = CommentsBeforeNextToken.begin(), 2005 E = CommentsBeforeNextToken.end(); 2006 I != E; ++I) { 2007 if (isOnNewLine(**I) && JustComments) 2008 addUnwrappedLine(); 2009 pushToken(*I); 2010 } 2011 if (NewlineBeforeNext && JustComments) 2012 addUnwrappedLine(); 2013 CommentsBeforeNextToken.clear(); 2014 } 2015 2016 void UnwrappedLineParser::nextToken() { 2017 if (eof()) 2018 return; 2019 flushComments(isOnNewLine(*FormatTok)); 2020 pushToken(FormatTok); 2021 if (Style.Language != FormatStyle::LK_JavaScript) 2022 readToken(); 2023 else 2024 readTokenWithJavaScriptASI(); 2025 } 2026 2027 const FormatToken *UnwrappedLineParser::getPreviousToken() { 2028 // FIXME: This is a dirty way to access the previous token. Find a better 2029 // solution. 2030 if (!Line || Line->Tokens.empty()) 2031 return nullptr; 2032 return Line->Tokens.back().Tok; 2033 } 2034 2035 void UnwrappedLineParser::readToken() { 2036 bool CommentsInCurrentLine = true; 2037 do { 2038 FormatTok = Tokens->getNextToken(); 2039 assert(FormatTok); 2040 while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) && 2041 (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) { 2042 // If there is an unfinished unwrapped line, we flush the preprocessor 2043 // directives only after that unwrapped line was finished later. 2044 bool SwitchToPreprocessorLines = !Line->Tokens.empty(); 2045 ScopedLineState BlockState(*this, SwitchToPreprocessorLines); 2046 // Comments stored before the preprocessor directive need to be output 2047 // before the preprocessor directive, at the same level as the 2048 // preprocessor directive, as we consider them to apply to the directive. 2049 flushComments(isOnNewLine(*FormatTok)); 2050 parsePPDirective(); 2051 } 2052 while (FormatTok->Type == TT_ConflictStart || 2053 FormatTok->Type == TT_ConflictEnd || 2054 FormatTok->Type == TT_ConflictAlternative) { 2055 if (FormatTok->Type == TT_ConflictStart) { 2056 conditionalCompilationStart(/*Unreachable=*/false); 2057 } else if (FormatTok->Type == TT_ConflictAlternative) { 2058 conditionalCompilationAlternative(); 2059 } else if (FormatTok->Type == TT_ConflictEnd) { 2060 conditionalCompilationEnd(); 2061 } 2062 FormatTok = Tokens->getNextToken(); 2063 FormatTok->MustBreakBefore = true; 2064 } 2065 2066 if (!PPStack.empty() && (PPStack.back() == PP_Unreachable) && 2067 !Line->InPPDirective) { 2068 continue; 2069 } 2070 2071 if (!FormatTok->Tok.is(tok::comment)) 2072 return; 2073 if (isOnNewLine(*FormatTok) || FormatTok->IsFirst) { 2074 CommentsInCurrentLine = false; 2075 } 2076 if (CommentsInCurrentLine) { 2077 pushToken(FormatTok); 2078 } else { 2079 CommentsBeforeNextToken.push_back(FormatTok); 2080 } 2081 } while (!eof()); 2082 } 2083 2084 void UnwrappedLineParser::pushToken(FormatToken *Tok) { 2085 Line->Tokens.push_back(UnwrappedLineNode(Tok)); 2086 if (MustBreakBeforeNextToken) { 2087 Line->Tokens.back().Tok->MustBreakBefore = true; 2088 MustBreakBeforeNextToken = false; 2089 } 2090 } 2091 2092 } // end namespace format 2093 } // end namespace clang 2094