1 //===--- UnwrappedLineParser.cpp - Format C++ code ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief This file contains the implementation of the UnwrappedLineParser,
12 /// which turns a stream of tokens into UnwrappedLines.
14 //===----------------------------------------------------------------------===//
16 #include "UnwrappedLineParser.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/raw_ostream.h"
23 #define DEBUG_TYPE "format-parser"
28 class FormatTokenSource {
30 virtual ~FormatTokenSource() {}
31 virtual FormatToken *getNextToken() = 0;
33 virtual unsigned getPosition() = 0;
34 virtual FormatToken *setPosition(unsigned Position) = 0;
39 class ScopedDeclarationState {
41 ScopedDeclarationState(UnwrappedLine &Line, std::vector<bool> &Stack,
42 bool MustBeDeclaration)
43 : Line(Line), Stack(Stack) {
44 Line.MustBeDeclaration = MustBeDeclaration;
45 Stack.push_back(MustBeDeclaration);
47 ~ScopedDeclarationState() {
50 Line.MustBeDeclaration = Stack.back();
52 Line.MustBeDeclaration = true;
57 std::vector<bool> &Stack;
60 static bool isLineComment(const FormatToken &FormatTok) {
61 return FormatTok.is(tok::comment) && !FormatTok.TokenText.startswith("/*");
64 // Checks if \p FormatTok is a line comment that continues the line comment
65 // \p Previous. The original column of \p MinColumnToken is used to determine
66 // whether \p FormatTok is indented enough to the right to continue \p Previous.
67 static bool continuesLineComment(const FormatToken &FormatTok,
68 const FormatToken *Previous,
69 const FormatToken *MinColumnToken) {
70 if (!Previous || !MinColumnToken)
72 unsigned MinContinueColumn =
73 MinColumnToken->OriginalColumn + (isLineComment(*MinColumnToken) ? 0 : 1);
74 return isLineComment(FormatTok) && FormatTok.NewlinesBefore == 1 &&
75 isLineComment(*Previous) &&
76 FormatTok.OriginalColumn >= MinContinueColumn;
79 class ScopedMacroState : public FormatTokenSource {
81 ScopedMacroState(UnwrappedLine &Line, FormatTokenSource *&TokenSource,
82 FormatToken *&ResetToken)
83 : Line(Line), TokenSource(TokenSource), ResetToken(ResetToken),
84 PreviousLineLevel(Line.Level), PreviousTokenSource(TokenSource),
85 Token(nullptr), PreviousToken(nullptr) {
88 Line.InPPDirective = true;
91 ~ScopedMacroState() override {
92 TokenSource = PreviousTokenSource;
94 Line.InPPDirective = false;
95 Line.Level = PreviousLineLevel;
98 FormatToken *getNextToken() override {
99 // The \c UnwrappedLineParser guards against this by never calling
100 // \c getNextToken() after it has encountered the first eof token.
102 PreviousToken = Token;
103 Token = PreviousTokenSource->getNextToken();
109 unsigned getPosition() override { return PreviousTokenSource->getPosition(); }
111 FormatToken *setPosition(unsigned Position) override {
112 PreviousToken = nullptr;
113 Token = PreviousTokenSource->setPosition(Position);
119 return Token && Token->HasUnescapedNewline &&
120 !continuesLineComment(*Token, PreviousToken,
121 /*MinColumnToken=*/PreviousToken);
124 FormatToken *getFakeEOF() {
125 static bool EOFInitialized = false;
126 static FormatToken FormatTok;
127 if (!EOFInitialized) {
128 FormatTok.Tok.startToken();
129 FormatTok.Tok.setKind(tok::eof);
130 EOFInitialized = true;
136 FormatTokenSource *&TokenSource;
137 FormatToken *&ResetToken;
138 unsigned PreviousLineLevel;
139 FormatTokenSource *PreviousTokenSource;
142 FormatToken *PreviousToken;
145 } // end anonymous namespace
147 class ScopedLineState {
149 ScopedLineState(UnwrappedLineParser &Parser,
150 bool SwitchToPreprocessorLines = false)
151 : Parser(Parser), OriginalLines(Parser.CurrentLines) {
152 if (SwitchToPreprocessorLines)
153 Parser.CurrentLines = &Parser.PreprocessorDirectives;
154 else if (!Parser.Line->Tokens.empty())
155 Parser.CurrentLines = &Parser.Line->Tokens.back().Children;
156 PreBlockLine = std::move(Parser.Line);
157 Parser.Line = llvm::make_unique<UnwrappedLine>();
158 Parser.Line->Level = PreBlockLine->Level;
159 Parser.Line->InPPDirective = PreBlockLine->InPPDirective;
163 if (!Parser.Line->Tokens.empty()) {
164 Parser.addUnwrappedLine();
166 assert(Parser.Line->Tokens.empty());
167 Parser.Line = std::move(PreBlockLine);
168 if (Parser.CurrentLines == &Parser.PreprocessorDirectives)
169 Parser.MustBreakBeforeNextToken = true;
170 Parser.CurrentLines = OriginalLines;
174 UnwrappedLineParser &Parser;
176 std::unique_ptr<UnwrappedLine> PreBlockLine;
177 SmallVectorImpl<UnwrappedLine> *OriginalLines;
180 class CompoundStatementIndenter {
182 CompoundStatementIndenter(UnwrappedLineParser *Parser,
183 const FormatStyle &Style, unsigned &LineLevel)
184 : LineLevel(LineLevel), OldLineLevel(LineLevel) {
185 if (Style.BraceWrapping.AfterControlStatement)
186 Parser->addUnwrappedLine();
187 if (Style.BraceWrapping.IndentBraces)
190 ~CompoundStatementIndenter() { LineLevel = OldLineLevel; }
194 unsigned OldLineLevel;
199 class IndexedTokenSource : public FormatTokenSource {
201 IndexedTokenSource(ArrayRef<FormatToken *> Tokens)
202 : Tokens(Tokens), Position(-1) {}
204 FormatToken *getNextToken() override {
206 return Tokens[Position];
209 unsigned getPosition() override {
210 assert(Position >= 0);
214 FormatToken *setPosition(unsigned P) override {
216 return Tokens[Position];
219 void reset() { Position = -1; }
222 ArrayRef<FormatToken *> Tokens;
226 } // end anonymous namespace
228 UnwrappedLineParser::UnwrappedLineParser(const FormatStyle &Style,
229 const AdditionalKeywords &Keywords,
230 unsigned FirstStartColumn,
231 ArrayRef<FormatToken *> Tokens,
232 UnwrappedLineConsumer &Callback)
233 : Line(new UnwrappedLine), MustBreakBeforeNextToken(false),
234 CurrentLines(&Lines), Style(Style), Keywords(Keywords),
235 CommentPragmasRegex(Style.CommentPragmas), Tokens(nullptr),
236 Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1),
237 IfNdefCondition(nullptr), FoundIncludeGuardStart(false),
238 IncludeGuardRejected(false), FirstStartColumn(FirstStartColumn) {}
240 void UnwrappedLineParser::reset() {
242 IfNdefCondition = nullptr;
243 FoundIncludeGuardStart = false;
244 IncludeGuardRejected = false;
245 Line.reset(new UnwrappedLine);
246 CommentsBeforeNextToken.clear();
248 MustBreakBeforeNextToken = false;
249 PreprocessorDirectives.clear();
250 CurrentLines = &Lines;
251 DeclarationScopeStack.clear();
253 Line->FirstStartColumn = FirstStartColumn;
256 void UnwrappedLineParser::parse() {
257 IndexedTokenSource TokenSource(AllTokens);
258 Line->FirstStartColumn = FirstStartColumn;
260 DEBUG(llvm::dbgs() << "----\n");
262 Tokens = &TokenSource;
267 // Create line with eof token.
268 pushToken(FormatTok);
271 for (SmallVectorImpl<UnwrappedLine>::iterator I = Lines.begin(),
274 Callback.consumeUnwrappedLine(*I);
276 Callback.finishRun();
278 while (!PPLevelBranchIndex.empty() &&
279 PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) {
280 PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1);
281 PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1);
283 if (!PPLevelBranchIndex.empty()) {
284 ++PPLevelBranchIndex.back();
285 assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size());
286 assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back());
288 } while (!PPLevelBranchIndex.empty());
291 void UnwrappedLineParser::parseFile() {
292 // The top-level context in a file always has declarations, except for pre-
293 // processor directives and JavaScript files.
294 bool MustBeDeclaration =
295 !Line->InPPDirective && Style.Language != FormatStyle::LK_JavaScript;
296 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
298 if (Style.Language == FormatStyle::LK_TextProto)
301 parseLevel(/*HasOpeningBrace=*/false);
302 // Make sure to format the remaining tokens.
307 void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) {
308 bool SwitchLabelEncountered = false;
310 tok::TokenKind kind = FormatTok->Tok.getKind();
311 if (FormatTok->Type == TT_MacroBlockBegin) {
313 } else if (FormatTok->Type == TT_MacroBlockEnd) {
323 // FIXME: Add parameter whether this can happen - if this happens, we must
324 // be in a non-declaration context.
325 if (!FormatTok->is(TT_MacroBlockBegin) && tryToParseBracedList())
327 parseBlock(/*MustBeDeclaration=*/false);
336 case tok::kw_default:
338 if (Style.Language == FormatStyle::LK_JavaScript &&
339 Line->MustBeDeclaration) {
340 // A 'case: string' style field declaration.
341 parseStructuralElement();
344 if (!SwitchLabelEncountered &&
345 (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1)))
347 SwitchLabelEncountered = true;
348 parseStructuralElement();
351 parseStructuralElement();
357 void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) {
358 // We'll parse forward through the tokens until we hit
359 // a closing brace or eof - note that getNextToken() will
360 // parse macros, so this will magically work inside macro
362 unsigned StoredPosition = Tokens->getPosition();
363 FormatToken *Tok = FormatTok;
364 const FormatToken *PrevTok = Tok->Previous;
365 // Keep a stack of positions of lbrace tokens. We will
366 // update information about whether an lbrace starts a
367 // braced init list or a different block during the loop.
368 SmallVector<FormatToken *, 8> LBraceStack;
369 assert(Tok->Tok.is(tok::l_brace));
371 // Get next non-comment token.
372 FormatToken *NextTok;
373 unsigned ReadTokens = 0;
375 NextTok = Tokens->getNextToken();
377 } while (NextTok->is(tok::comment));
379 switch (Tok->Tok.getKind()) {
381 if (Style.Language == FormatStyle::LK_JavaScript && PrevTok) {
382 if (PrevTok->isOneOf(tok::colon, tok::less))
383 // A ':' indicates this code is in a type, or a braced list
384 // following a label in an object literal ({a: {b: 1}}).
385 // A '<' could be an object used in a comparison, but that is nonsense
386 // code (can never return true), so more likely it is a generic type
387 // argument (`X<{a: string; b: number}>`).
388 // The code below could be confused by semicolons between the
389 // individual members in a type member list, which would normally
390 // trigger BK_Block. In both cases, this must be parsed as an inline
392 Tok->BlockKind = BK_BracedInit;
393 else if (PrevTok->is(tok::r_paren))
394 // `) { }` can only occur in function or method declarations in JS.
395 Tok->BlockKind = BK_Block;
397 Tok->BlockKind = BK_Unknown;
399 LBraceStack.push_back(Tok);
402 if (LBraceStack.empty())
404 if (LBraceStack.back()->BlockKind == BK_Unknown) {
405 bool ProbablyBracedList = false;
406 if (Style.Language == FormatStyle::LK_Proto) {
407 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
409 // Using OriginalColumn to distinguish between ObjC methods and
410 // binary operators is a bit hacky.
411 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
412 NextTok->OriginalColumn == 0;
414 // If there is a comma, semicolon or right paren after the closing
415 // brace, we assume this is a braced initializer list. Note that
416 // regardless how we mark inner braces here, we will overwrite the
417 // BlockKind later if we parse a braced list (where all blocks
418 // inside are by default braced lists), or when we explicitly detect
419 // blocks (for example while parsing lambdas).
420 // FIXME: Some of these do not apply to JS, e.g. "} {" can never be a
421 // braced list in JS.
423 (Style.Language == FormatStyle::LK_JavaScript &&
424 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
426 (Style.isCpp() && NextTok->is(tok::l_paren)) ||
427 NextTok->isOneOf(tok::comma, tok::period, tok::colon,
428 tok::r_paren, tok::r_square, tok::l_brace,
429 tok::l_square, tok::ellipsis) ||
430 (NextTok->is(tok::identifier) &&
431 !PrevTok->isOneOf(tok::semi, tok::r_brace, tok::l_brace)) ||
432 (NextTok->is(tok::semi) &&
433 (!ExpectClassBody || LBraceStack.size() != 1)) ||
434 (NextTok->isBinaryOperator() && !NextIsObjCMethod);
436 if (ProbablyBracedList) {
437 Tok->BlockKind = BK_BracedInit;
438 LBraceStack.back()->BlockKind = BK_BracedInit;
440 Tok->BlockKind = BK_Block;
441 LBraceStack.back()->BlockKind = BK_Block;
444 LBraceStack.pop_back();
454 if (!LBraceStack.empty() && LBraceStack.back()->BlockKind == BK_Unknown)
455 LBraceStack.back()->BlockKind = BK_Block;
462 } while (Tok->Tok.isNot(tok::eof) && !LBraceStack.empty());
464 // Assume other blocks for all unclosed opening braces.
465 for (unsigned i = 0, e = LBraceStack.size(); i != e; ++i) {
466 if (LBraceStack[i]->BlockKind == BK_Unknown)
467 LBraceStack[i]->BlockKind = BK_Block;
470 FormatTok = Tokens->setPosition(StoredPosition);
474 static inline void hash_combine(std::size_t &seed, const T &v) {
476 seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
479 size_t UnwrappedLineParser::computePPHash() const {
481 for (const auto &i : PPStack) {
482 hash_combine(h, size_t(i.Kind));
483 hash_combine(h, i.Line);
488 void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel,
490 assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) &&
491 "'{' or macro block token expected");
492 const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
493 FormatTok->BlockKind = BK_Block;
495 size_t PPStartHash = computePPHash();
497 unsigned InitialLevel = Line->Level;
498 nextToken(/*LevelDifference=*/AddLevel ? 1 : 0);
500 if (MacroBlock && FormatTok->is(tok::l_paren))
503 size_t NbPreprocessorDirectives =
504 CurrentLines == &Lines ? PreprocessorDirectives.size() : 0;
506 size_t OpeningLineIndex =
507 CurrentLines->empty()
508 ? (UnwrappedLine::kInvalidIndex)
509 : (CurrentLines->size() - 1 - NbPreprocessorDirectives);
511 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
515 parseLevel(/*HasOpeningBrace=*/true);
520 if (MacroBlock ? !FormatTok->is(TT_MacroBlockEnd)
521 : !FormatTok->is(tok::r_brace)) {
522 Line->Level = InitialLevel;
523 FormatTok->BlockKind = BK_Block;
527 size_t PPEndHash = computePPHash();
529 // Munch the closing brace.
530 nextToken(/*LevelDifference=*/AddLevel ? -1 : 0);
532 if (MacroBlock && FormatTok->is(tok::l_paren))
535 if (MunchSemi && FormatTok->Tok.is(tok::semi))
537 Line->Level = InitialLevel;
539 if (PPStartHash == PPEndHash) {
540 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
541 if (OpeningLineIndex != UnwrappedLine::kInvalidIndex) {
542 // Update the opening line to add the forward reference as well
543 (*CurrentLines)[OpeningLineIndex].MatchingOpeningBlockLineIndex =
544 CurrentLines->size() - 1;
549 static bool isGoogScope(const UnwrappedLine &Line) {
550 // FIXME: Closure-library specific stuff should not be hard-coded but be
552 if (Line.Tokens.size() < 4)
554 auto I = Line.Tokens.begin();
555 if (I->Tok->TokenText != "goog")
558 if (I->Tok->isNot(tok::period))
561 if (I->Tok->TokenText != "scope")
564 return I->Tok->is(tok::l_paren);
567 static bool isIIFE(const UnwrappedLine &Line,
568 const AdditionalKeywords &Keywords) {
569 // Look for the start of an immediately invoked anonymous function.
570 // https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
571 // This is commonly done in JavaScript to create a new, anonymous scope.
572 // Example: (function() { ... })()
573 if (Line.Tokens.size() < 3)
575 auto I = Line.Tokens.begin();
576 if (I->Tok->isNot(tok::l_paren))
579 if (I->Tok->isNot(Keywords.kw_function))
582 return I->Tok->is(tok::l_paren);
585 static bool ShouldBreakBeforeBrace(const FormatStyle &Style,
586 const FormatToken &InitialToken) {
587 if (InitialToken.is(tok::kw_namespace))
588 return Style.BraceWrapping.AfterNamespace;
589 if (InitialToken.is(tok::kw_class))
590 return Style.BraceWrapping.AfterClass;
591 if (InitialToken.is(tok::kw_union))
592 return Style.BraceWrapping.AfterUnion;
593 if (InitialToken.is(tok::kw_struct))
594 return Style.BraceWrapping.AfterStruct;
598 void UnwrappedLineParser::parseChildBlock() {
599 FormatTok->BlockKind = BK_Block;
602 bool SkipIndent = (Style.Language == FormatStyle::LK_JavaScript &&
603 (isGoogScope(*Line) || isIIFE(*Line, Keywords)));
604 ScopedLineState LineState(*this);
605 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
606 /*MustBeDeclaration=*/false);
607 Line->Level += SkipIndent ? 0 : 1;
608 parseLevel(/*HasOpeningBrace=*/true);
609 flushComments(isOnNewLine(*FormatTok));
610 Line->Level -= SkipIndent ? 0 : 1;
615 void UnwrappedLineParser::parsePPDirective() {
616 assert(FormatTok->Tok.is(tok::hash) && "'#' expected");
617 ScopedMacroState MacroState(*Line, Tokens, FormatTok);
620 if (!FormatTok->Tok.getIdentifierInfo()) {
625 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
630 parsePPIf(/*IfDef=*/false);
634 parsePPIf(/*IfDef=*/true);
651 void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) {
652 size_t Line = CurrentLines->size();
653 if (CurrentLines == &PreprocessorDirectives)
654 Line += Lines.size();
657 (!PPStack.empty() && PPStack.back().Kind == PP_Unreachable))
658 PPStack.push_back({PP_Unreachable, Line});
660 PPStack.push_back({PP_Conditional, Line});
663 void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) {
665 assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
666 if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
667 PPLevelBranchIndex.push_back(0);
668 PPLevelBranchCount.push_back(0);
670 PPChainBranchIndex.push(0);
671 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
672 conditionalCompilationCondition(Unreachable || Skip);
675 void UnwrappedLineParser::conditionalCompilationAlternative() {
676 if (!PPStack.empty())
678 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
679 if (!PPChainBranchIndex.empty())
680 ++PPChainBranchIndex.top();
681 conditionalCompilationCondition(
682 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
683 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
686 void UnwrappedLineParser::conditionalCompilationEnd() {
687 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
688 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
689 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) {
690 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
693 // Guard against #endif's without #if.
694 if (PPBranchLevel > -1)
696 if (!PPChainBranchIndex.empty())
697 PPChainBranchIndex.pop();
698 if (!PPStack.empty())
702 void UnwrappedLineParser::parsePPIf(bool IfDef) {
703 bool IfNDef = FormatTok->is(tok::pp_ifndef);
705 bool Unreachable = false;
706 if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText == "0"))
708 if (IfDef && !IfNDef && FormatTok->TokenText == "SWIG")
710 conditionalCompilationStart(Unreachable);
711 FormatToken *IfCondition = FormatTok;
712 // If there's a #ifndef on the first line, and the only lines before it are
713 // comments, it could be an include guard.
714 bool MaybeIncludeGuard = IfNDef;
715 if (!IncludeGuardRejected && !FoundIncludeGuardStart && MaybeIncludeGuard) {
716 for (auto &Line : Lines) {
717 if (!Line.Tokens.front().Tok->is(tok::comment)) {
718 MaybeIncludeGuard = false;
719 IncludeGuardRejected = true;
727 if (!IncludeGuardRejected && !FoundIncludeGuardStart && MaybeIncludeGuard)
728 IfNdefCondition = IfCondition;
731 void UnwrappedLineParser::parsePPElse() {
732 // If a potential include guard has an #else, it's not an include guard.
733 if (FoundIncludeGuardStart && PPBranchLevel == 0)
734 FoundIncludeGuardStart = false;
735 conditionalCompilationAlternative();
736 if (PPBranchLevel > -1)
742 void UnwrappedLineParser::parsePPElIf() { parsePPElse(); }
744 void UnwrappedLineParser::parsePPEndIf() {
745 conditionalCompilationEnd();
747 // If the #endif of a potential include guard is the last thing in the file,
748 // then we count it as a real include guard and subtract one from every
749 // preprocessor indent.
750 unsigned TokenPosition = Tokens->getPosition();
751 FormatToken *PeekNext = AllTokens[TokenPosition];
752 if (FoundIncludeGuardStart && PPBranchLevel == -1 && PeekNext->is(tok::eof) &&
753 Style.IndentPPDirectives != FormatStyle::PPDIS_None)
754 for (auto &Line : Lines)
755 if (Line.InPPDirective && Line.Level > 0)
759 void UnwrappedLineParser::parsePPDefine() {
762 if (FormatTok->Tok.getKind() != tok::identifier) {
766 if (IfNdefCondition && IfNdefCondition->TokenText == FormatTok->TokenText) {
767 FoundIncludeGuardStart = true;
768 for (auto &Line : Lines) {
769 if (!Line.Tokens.front().Tok->isOneOf(tok::comment, tok::hash)) {
770 FoundIncludeGuardStart = false;
775 IfNdefCondition = nullptr;
777 if (FormatTok->Tok.getKind() == tok::l_paren &&
778 FormatTok->WhitespaceRange.getBegin() ==
779 FormatTok->WhitespaceRange.getEnd()) {
782 if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash)
783 Line->Level += PPBranchLevel + 1;
787 // Errors during a preprocessor directive can only affect the layout of the
788 // preprocessor directive, and thus we ignore them. An alternative approach
789 // would be to use the same approach we use on the file level (no
790 // re-indentation if there was a structural error) within the macro
795 void UnwrappedLineParser::parsePPUnknown() {
799 if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash)
800 Line->Level += PPBranchLevel + 1;
802 IfNdefCondition = nullptr;
805 // Here we blacklist certain tokens that are not usually the first token in an
806 // unwrapped line. This is used in attempt to distinguish macro calls without
807 // trailing semicolons from other constructs split to several lines.
808 static bool tokenCanStartNewLine(const clang::Token &Tok) {
809 // Semicolon can be a null-statement, l_square can be a start of a macro or
810 // a C++11 attribute, but this doesn't seem to be common.
811 return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) &&
812 Tok.isNot(tok::l_square) &&
813 // Tokens that can only be used as binary operators and a part of
814 // overloaded operator names.
815 Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) &&
816 Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) &&
817 Tok.isNot(tok::less) && Tok.isNot(tok::greater) &&
818 Tok.isNot(tok::slash) && Tok.isNot(tok::percent) &&
819 Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) &&
820 Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) &&
821 Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) &&
822 Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) &&
823 Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) &&
824 Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) &&
825 Tok.isNot(tok::lesslessequal) &&
826 // Colon is used in labels, base class lists, initializer lists,
827 // range-based for loops, ternary operator, but should never be the
828 // first token in an unwrapped line.
829 Tok.isNot(tok::colon) &&
830 // 'noexcept' is a trailing annotation.
831 Tok.isNot(tok::kw_noexcept);
834 static bool mustBeJSIdent(const AdditionalKeywords &Keywords,
835 const FormatToken *FormatTok) {
836 // FIXME: This returns true for C/C++ keywords like 'struct'.
837 return FormatTok->is(tok::identifier) &&
838 (FormatTok->Tok.getIdentifierInfo() == nullptr ||
840 Keywords.kw_in, Keywords.kw_of, Keywords.kw_as, Keywords.kw_async,
841 Keywords.kw_await, Keywords.kw_yield, Keywords.kw_finally,
842 Keywords.kw_function, Keywords.kw_import, Keywords.kw_is,
843 Keywords.kw_let, Keywords.kw_var, tok::kw_const,
844 Keywords.kw_abstract, Keywords.kw_extends, Keywords.kw_implements,
845 Keywords.kw_instanceof, Keywords.kw_interface, Keywords.kw_throws,
849 static bool mustBeJSIdentOrValue(const AdditionalKeywords &Keywords,
850 const FormatToken *FormatTok) {
851 return FormatTok->Tok.isLiteral() ||
852 FormatTok->isOneOf(tok::kw_true, tok::kw_false) ||
853 mustBeJSIdent(Keywords, FormatTok);
856 // isJSDeclOrStmt returns true if |FormatTok| starts a declaration or statement
857 // when encountered after a value (see mustBeJSIdentOrValue).
858 static bool isJSDeclOrStmt(const AdditionalKeywords &Keywords,
859 const FormatToken *FormatTok) {
860 return FormatTok->isOneOf(
861 tok::kw_return, Keywords.kw_yield,
863 tok::kw_if, tok::kw_else,
865 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
867 tok::kw_switch, tok::kw_case,
869 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.kw_finally,
871 tok::kw_const, tok::kw_class, Keywords.kw_var, Keywords.kw_let,
872 Keywords.kw_async, Keywords.kw_function,
874 Keywords.kw_import, tok::kw_export);
877 // readTokenWithJavaScriptASI reads the next token and terminates the current
878 // line if JavaScript Automatic Semicolon Insertion must
879 // happen between the current token and the next token.
881 // This method is conservative - it cannot cover all edge cases of JavaScript,
882 // but only aims to correctly handle certain well known cases. It *must not*
883 // return true in speculative cases.
884 void UnwrappedLineParser::readTokenWithJavaScriptASI() {
885 FormatToken *Previous = FormatTok;
887 FormatToken *Next = FormatTok;
890 CommentsBeforeNextToken.empty()
891 ? Next->NewlinesBefore == 0
892 : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
896 bool PreviousMustBeValue = mustBeJSIdentOrValue(Keywords, Previous);
897 bool PreviousStartsTemplateExpr =
898 Previous->is(TT_TemplateString) && Previous->TokenText.endswith("${");
899 if (PreviousMustBeValue || Previous->is(tok::r_paren)) {
900 // If the line contains an '@' sign, the previous token might be an
901 // annotation, which can precede another identifier/value.
902 bool HasAt = std::find_if(Line->Tokens.begin(), Line->Tokens.end(),
903 [](UnwrappedLineNode &LineNode) {
904 return LineNode.Tok->is(tok::at);
905 }) != Line->Tokens.end();
909 if (Next->is(tok::exclaim) && PreviousMustBeValue)
910 return addUnwrappedLine();
911 bool NextMustBeValue = mustBeJSIdentOrValue(Keywords, Next);
912 bool NextEndsTemplateExpr =
913 Next->is(TT_TemplateString) && Next->TokenText.startswith("}");
914 if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
915 (PreviousMustBeValue ||
916 Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
918 return addUnwrappedLine();
919 if ((PreviousMustBeValue || Previous->is(tok::r_paren)) &&
920 isJSDeclOrStmt(Keywords, Next))
921 return addUnwrappedLine();
924 void UnwrappedLineParser::parseStructuralElement() {
925 assert(!FormatTok->is(tok::l_brace));
926 if (Style.Language == FormatStyle::LK_TableGen &&
927 FormatTok->is(tok::pp_include)) {
929 if (FormatTok->is(tok::string_literal))
934 switch (FormatTok->Tok.getKind()) {
937 if (FormatTok->Tok.is(tok::l_brace)) {
942 switch (FormatTok->Tok.getObjCKeywordID()) {
943 case tok::objc_public:
944 case tok::objc_protected:
945 case tok::objc_package:
946 case tok::objc_private:
947 return parseAccessSpecifier();
948 case tok::objc_interface:
949 case tok::objc_implementation:
950 return parseObjCInterfaceOrImplementation();
951 case tok::objc_protocol:
952 return parseObjCProtocol();
954 return; // Handled by the caller.
955 case tok::objc_optional:
956 case tok::objc_required:
960 case tok::objc_autoreleasepool:
962 if (FormatTok->Tok.is(tok::l_brace)) {
963 if (Style.BraceWrapping.AfterObjCDeclaration)
965 parseBlock(/*MustBeDeclaration=*/false);
970 // This branch isn't strictly necessary (the kw_try case below would
971 // do this too after the tok::at is parsed above). But be explicit.
980 if (FormatTok->is(tok::l_brace)) {
981 FormatTok->Type = TT_InlineASMBrace;
983 while (FormatTok && FormatTok->isNot(tok::eof)) {
984 if (FormatTok->is(tok::r_brace)) {
985 FormatTok->Type = TT_InlineASMBrace;
990 FormatTok->Finalized = true;
995 case tok::kw_namespace:
1000 if (FormatTok->Tok.is(tok::kw_namespace)) {
1005 case tok::kw_public:
1006 case tok::kw_protected:
1007 case tok::kw_private:
1008 if (Style.Language == FormatStyle::LK_Java ||
1009 Style.Language == FormatStyle::LK_JavaScript)
1012 parseAccessSpecifier();
1019 parseForOrWhileLoop();
1024 case tok::kw_switch:
1025 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1026 // 'switch: string' field declaration.
1030 case tok::kw_default:
1031 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1032 // 'default: string' field declaration.
1038 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1039 // 'case: string' field declaration.
1047 case tok::kw_extern:
1049 if (FormatTok->Tok.is(tok::string_literal)) {
1051 if (FormatTok->Tok.is(tok::l_brace)) {
1052 if (Style.BraceWrapping.AfterExternBlock) {
1054 parseBlock(/*MustBeDeclaration=*/true);
1056 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false);
1063 case tok::kw_export:
1064 if (Style.Language == FormatStyle::LK_JavaScript) {
1065 parseJavaScriptEs6ImportExport();
1069 case tok::identifier:
1070 if (FormatTok->is(TT_ForEachMacro)) {
1071 parseForOrWhileLoop();
1074 if (FormatTok->is(TT_MacroBlockBegin)) {
1075 parseBlock(/*MustBeDeclaration=*/false, /*AddLevel=*/true,
1076 /*MunchSemi=*/false);
1079 if (FormatTok->is(Keywords.kw_import)) {
1080 if (Style.Language == FormatStyle::LK_JavaScript) {
1081 parseJavaScriptEs6ImportExport();
1084 if (Style.Language == FormatStyle::LK_Proto) {
1086 if (FormatTok->is(tok::kw_public))
1088 if (!FormatTok->is(tok::string_literal))
1091 if (FormatTok->is(tok::semi))
1097 if (Style.isCpp() &&
1098 FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
1099 Keywords.kw_slots, Keywords.kw_qslots)) {
1101 if (FormatTok->is(tok::colon)) {
1107 // In all other cases, parse the declaration.
1113 const FormatToken *Previous = FormatTok->Previous;
1114 switch (FormatTok->Tok.getKind()) {
1117 if (FormatTok->Tok.is(tok::l_brace)) {
1123 // Ignore if this is part of "template <enum ...".
1124 if (Previous && Previous->is(tok::less)) {
1129 // parseEnum falls through and does not yet add an unwrapped line as an
1130 // enum definition can start a structural element.
1133 // This only applies for C++.
1134 if (!Style.isCpp()) {
1139 case tok::kw_typedef:
1141 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1142 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS))
1145 case tok::kw_struct:
1148 // parseRecord falls through and does not yet add an unwrapped line as a
1149 // record declaration or definition can start a structural element.
1151 // This does not apply for Java and JavaScript.
1152 if (Style.Language == FormatStyle::LK_Java ||
1153 Style.Language == FormatStyle::LK_JavaScript) {
1154 if (FormatTok->is(tok::semi))
1162 // In Java, classes have an implicit static member "class".
1163 if (Style.Language == FormatStyle::LK_Java && FormatTok &&
1164 FormatTok->is(tok::kw_class))
1166 if (Style.Language == FormatStyle::LK_JavaScript && FormatTok &&
1167 FormatTok->Tok.getIdentifierInfo())
1168 // JavaScript only has pseudo keywords, all keywords are allowed to
1169 // appear in "IdentifierName" positions. See http://es5.github.io/#x7.6
1182 case tok::kw_operator:
1184 if (FormatTok->isBinaryOperator())
1189 if (FormatTok->Tok.isAnyIdentifier() ||
1190 FormatTok->isSimpleTypeSpecifier())
1192 if (FormatTok->is(tok::l_paren))
1194 if (FormatTok->is(tok::l_brace))
1198 if (!tryToParseBracedList()) {
1199 // A block outside of parentheses must be the last part of a
1200 // structural element.
1201 // FIXME: Figure out cases where this is not true, and add projections
1202 // for them (the one we know is missing are lambdas).
1203 if (Style.BraceWrapping.AfterFunction)
1205 FormatTok->Type = TT_FunctionLBrace;
1206 parseBlock(/*MustBeDeclaration=*/false);
1210 // Otherwise this was a braced init list, and the structural
1211 // element continues.
1214 // We arrive here when parsing function-try blocks.
1217 case tok::identifier: {
1218 if (FormatTok->is(TT_MacroBlockEnd)) {
1223 // Function declarations (as opposed to function expressions) are parsed
1224 // on their own unwrapped line by continuing this loop. Function
1225 // expressions (functions that are not on their own line) must not create
1226 // a new unwrapped line, so they are special cased below.
1227 size_t TokenCount = Line->Tokens.size();
1228 if (Style.Language == FormatStyle::LK_JavaScript &&
1229 FormatTok->is(Keywords.kw_function) &&
1230 (TokenCount > 1 || (TokenCount == 1 && !Line->Tokens.front().Tok->is(
1231 Keywords.kw_async)))) {
1232 tryToParseJSFunction();
1235 if ((Style.Language == FormatStyle::LK_JavaScript ||
1236 Style.Language == FormatStyle::LK_Java) &&
1237 FormatTok->is(Keywords.kw_interface)) {
1238 if (Style.Language == FormatStyle::LK_JavaScript) {
1239 // In JavaScript/TypeScript, "interface" can be used as a standalone
1240 // identifier, e.g. in `var interface = 1;`. If "interface" is
1241 // followed by another identifier, it is very like to be an actual
1242 // interface declaration.
1243 unsigned StoredPosition = Tokens->getPosition();
1244 FormatToken *Next = Tokens->getNextToken();
1245 FormatTok = Tokens->setPosition(StoredPosition);
1246 if (Next && !mustBeJSIdent(Keywords, Next)) {
1256 // See if the following token should start a new unwrapped line.
1257 StringRef Text = FormatTok->TokenText;
1259 if (Line->Tokens.size() == 1 &&
1260 // JS doesn't have macros, and within classes colons indicate fields,
1262 Style.Language != FormatStyle::LK_JavaScript) {
1263 if (FormatTok->Tok.is(tok::colon) && !Line->MustBeDeclaration) {
1264 Line->Tokens.begin()->Tok->MustBreakBefore = true;
1268 // Recognize function-like macro usages without trailing semicolon as
1269 // well as free-standing macros like Q_OBJECT.
1270 bool FunctionLike = FormatTok->is(tok::l_paren);
1274 bool FollowedByNewline =
1275 CommentsBeforeNextToken.empty()
1276 ? FormatTok->NewlinesBefore > 0
1277 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
1279 if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
1280 tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) {
1288 // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType
1289 // TT_JsFatArrow. The always start an expression or a child block if
1290 // followed by a curly.
1291 if (FormatTok->is(TT_JsFatArrow)) {
1293 if (FormatTok->is(tok::l_brace))
1299 if (FormatTok->Tok.is(tok::l_brace)) {
1302 } else if (Style.Language == FormatStyle::LK_Proto &&
1303 FormatTok->Tok.is(tok::less)) {
1305 parseBracedList(/*ContinueOnSemicolons=*/false,
1306 /*ClosingBraceKind=*/tok::greater);
1322 bool UnwrappedLineParser::tryToParseLambda() {
1323 if (!Style.isCpp()) {
1327 assert(FormatTok->is(tok::l_square));
1328 FormatToken &LSquare = *FormatTok;
1329 if (!tryToParseLambdaIntroducer())
1332 while (FormatTok->isNot(tok::l_brace)) {
1333 if (FormatTok->isSimpleTypeSpecifier()) {
1337 switch (FormatTok->Tok.getKind()) {
1349 case tok::identifier:
1350 case tok::numeric_constant:
1351 case tok::coloncolon:
1352 case tok::kw_mutable:
1356 FormatTok->Type = TT_LambdaArrow;
1363 LSquare.Type = TT_LambdaLSquare;
1368 bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
1369 const FormatToken *Previous = FormatTok->Previous;
1371 (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new,
1373 FormatTok->isCppStructuredBinding(Style) || Previous->closesScope() ||
1374 Previous->isSimpleTypeSpecifier())) {
1379 parseSquare(/*LambdaIntroducer=*/true);
1383 void UnwrappedLineParser::tryToParseJSFunction() {
1384 assert(FormatTok->is(Keywords.kw_function) ||
1385 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function));
1386 if (FormatTok->is(Keywords.kw_async))
1388 // Consume "function".
1391 // Consume * (generator function). Treat it like C++'s overloaded operators.
1392 if (FormatTok->is(tok::star)) {
1393 FormatTok->Type = TT_OverloadedOperator;
1397 // Consume function name.
1398 if (FormatTok->is(tok::identifier))
1401 if (FormatTok->isNot(tok::l_paren))
1404 // Parse formal parameter list.
1407 if (FormatTok->is(tok::colon)) {
1408 // Parse a type definition.
1411 // Eat the type declaration. For braced inline object types, balance braces,
1412 // otherwise just parse until finding an l_brace for the function body.
1413 if (FormatTok->is(tok::l_brace))
1414 tryToParseBracedList();
1416 while (!FormatTok->isOneOf(tok::l_brace, tok::semi) && !eof())
1420 if (FormatTok->is(tok::semi))
1426 bool UnwrappedLineParser::tryToParseBracedList() {
1427 if (FormatTok->BlockKind == BK_Unknown)
1428 calculateBraceTypes();
1429 assert(FormatTok->BlockKind != BK_Unknown);
1430 if (FormatTok->BlockKind == BK_Block)
1437 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
1438 tok::TokenKind ClosingBraceKind) {
1439 bool HasError = false;
1441 // FIXME: Once we have an expression parser in the UnwrappedLineParser,
1442 // replace this by using parseAssigmentExpression() inside.
1444 if (Style.Language == FormatStyle::LK_JavaScript) {
1445 if (FormatTok->is(Keywords.kw_function) ||
1446 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) {
1447 tryToParseJSFunction();
1450 if (FormatTok->is(TT_JsFatArrow)) {
1452 // Fat arrows can be followed by simple expressions or by child blocks
1454 if (FormatTok->is(tok::l_brace)) {
1459 if (FormatTok->is(tok::l_brace)) {
1460 // Could be a method inside of a braced list `{a() { return 1; }}`.
1461 if (tryToParseBracedList())
1466 if (FormatTok->Tok.getKind() == ClosingBraceKind) {
1470 switch (FormatTok->Tok.getKind()) {
1473 if (FormatTok->is(tok::l_brace)) {
1482 // JavaScript can just have free standing methods and getters/setters in
1483 // object literals. Detect them by a "{" following ")".
1484 if (Style.Language == FormatStyle::LK_JavaScript) {
1485 if (FormatTok->is(tok::l_brace))
1491 // Assume there are no blocks inside a braced init list apart
1492 // from the ones we explicitly parse out (like lambdas).
1493 FormatTok->BlockKind = BK_BracedInit;
1498 if (Style.Language == FormatStyle::LK_Proto) {
1500 parseBracedList(/*ContinueOnSemicolons=*/false,
1501 /*ClosingBraceKind=*/tok::greater);
1507 // JavaScript (or more precisely TypeScript) can have semicolons in braced
1508 // lists (in so-called TypeMemberLists). Thus, the semicolon cannot be
1509 // used for error recovery if we have otherwise determined that this is
1511 if (Style.Language == FormatStyle::LK_JavaScript) {
1516 if (!ContinueOnSemicolons)
1531 void UnwrappedLineParser::parseParens() {
1532 assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected.");
1535 switch (FormatTok->Tok.getKind()) {
1538 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace))
1545 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1551 if (!tryToParseBracedList())
1556 if (FormatTok->Tok.is(tok::l_brace)) {
1562 if (Style.Language == FormatStyle::LK_JavaScript)
1563 parseRecord(/*ParseAsExpr=*/true);
1567 case tok::identifier:
1568 if (Style.Language == FormatStyle::LK_JavaScript &&
1569 (FormatTok->is(Keywords.kw_function) ||
1570 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)))
1571 tryToParseJSFunction();
1582 void UnwrappedLineParser::parseSquare(bool LambdaIntroducer) {
1583 if (!LambdaIntroducer) {
1584 assert(FormatTok->Tok.is(tok::l_square) && "'[' expected.");
1585 if (tryToParseLambda())
1589 switch (FormatTok->Tok.getKind()) {
1597 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1602 case tok::l_brace: {
1603 if (!tryToParseBracedList())
1609 if (FormatTok->Tok.is(tok::l_brace)) {
1621 void UnwrappedLineParser::parseIfThenElse() {
1622 assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected");
1624 if (FormatTok->Tok.is(tok::kw_constexpr))
1626 if (FormatTok->Tok.is(tok::l_paren))
1628 bool NeedsUnwrappedLine = false;
1629 if (FormatTok->Tok.is(tok::l_brace)) {
1630 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1631 parseBlock(/*MustBeDeclaration=*/false);
1632 if (Style.BraceWrapping.BeforeElse)
1635 NeedsUnwrappedLine = true;
1639 parseStructuralElement();
1642 if (FormatTok->Tok.is(tok::kw_else)) {
1644 if (FormatTok->Tok.is(tok::l_brace)) {
1645 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1646 parseBlock(/*MustBeDeclaration=*/false);
1648 } else if (FormatTok->Tok.is(tok::kw_if)) {
1653 parseStructuralElement();
1654 if (FormatTok->is(tok::eof))
1658 } else if (NeedsUnwrappedLine) {
1663 void UnwrappedLineParser::parseTryCatch() {
1664 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
1666 bool NeedsUnwrappedLine = false;
1667 if (FormatTok->is(tok::colon)) {
1668 // We are in a function try block, what comes is an initializer list.
1670 while (FormatTok->is(tok::identifier)) {
1672 if (FormatTok->is(tok::l_paren))
1674 if (FormatTok->is(tok::comma))
1678 // Parse try with resource.
1679 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
1682 if (FormatTok->is(tok::l_brace)) {
1683 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1684 parseBlock(/*MustBeDeclaration=*/false);
1685 if (Style.BraceWrapping.BeforeCatch) {
1688 NeedsUnwrappedLine = true;
1690 } else if (!FormatTok->is(tok::kw_catch)) {
1691 // The C++ standard requires a compound-statement after a try.
1692 // If there's none, we try to assume there's a structuralElement
1693 // and try to continue.
1696 parseStructuralElement();
1700 if (FormatTok->is(tok::at))
1702 if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
1703 tok::kw___finally) ||
1704 ((Style.Language == FormatStyle::LK_Java ||
1705 Style.Language == FormatStyle::LK_JavaScript) &&
1706 FormatTok->is(Keywords.kw_finally)) ||
1707 (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) ||
1708 FormatTok->Tok.isObjCAtKeyword(tok::objc_finally))))
1711 while (FormatTok->isNot(tok::l_brace)) {
1712 if (FormatTok->is(tok::l_paren)) {
1716 if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof))
1720 NeedsUnwrappedLine = false;
1721 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1722 parseBlock(/*MustBeDeclaration=*/false);
1723 if (Style.BraceWrapping.BeforeCatch)
1726 NeedsUnwrappedLine = true;
1728 if (NeedsUnwrappedLine)
1732 void UnwrappedLineParser::parseNamespace() {
1733 assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected");
1735 const FormatToken &InitialToken = *FormatTok;
1737 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon))
1739 if (FormatTok->Tok.is(tok::l_brace)) {
1740 if (ShouldBreakBeforeBrace(Style, InitialToken))
1743 bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All ||
1744 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
1745 DeclarationScopeStack.size() > 1);
1746 parseBlock(/*MustBeDeclaration=*/true, AddLevel);
1747 // Munch the semicolon after a namespace. This is more common than one would
1748 // think. Puttin the semicolon into its own line is very ugly.
1749 if (FormatTok->Tok.is(tok::semi))
1753 // FIXME: Add error handling.
1756 void UnwrappedLineParser::parseNew() {
1757 assert(FormatTok->is(tok::kw_new) && "'new' expected");
1759 if (Style.Language != FormatStyle::LK_Java)
1762 // In Java, we can parse everything up to the parens, which aren't optional.
1764 // There should not be a ;, { or } before the new's open paren.
1765 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
1768 // Consume the parens.
1769 if (FormatTok->is(tok::l_paren)) {
1772 // If there is a class body of an anonymous class, consume that as child.
1773 if (FormatTok->is(tok::l_brace))
1781 void UnwrappedLineParser::parseForOrWhileLoop() {
1782 assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
1783 "'for', 'while' or foreach macro expected");
1785 // JS' for await ( ...
1786 if (Style.Language == FormatStyle::LK_JavaScript &&
1787 FormatTok->is(Keywords.kw_await))
1789 if (FormatTok->Tok.is(tok::l_paren))
1791 if (FormatTok->Tok.is(tok::l_brace)) {
1792 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1793 parseBlock(/*MustBeDeclaration=*/false);
1798 parseStructuralElement();
1803 void UnwrappedLineParser::parseDoWhile() {
1804 assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
1806 if (FormatTok->Tok.is(tok::l_brace)) {
1807 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1808 parseBlock(/*MustBeDeclaration=*/false);
1809 if (Style.BraceWrapping.IndentBraces)
1814 parseStructuralElement();
1818 // FIXME: Add error handling.
1819 if (!FormatTok->Tok.is(tok::kw_while)) {
1825 parseStructuralElement();
1828 void UnwrappedLineParser::parseLabel() {
1830 unsigned OldLineLevel = Line->Level;
1831 if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
1833 if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) {
1834 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1835 parseBlock(/*MustBeDeclaration=*/false);
1836 if (FormatTok->Tok.is(tok::kw_break)) {
1837 if (Style.BraceWrapping.AfterControlStatement)
1839 parseStructuralElement();
1843 if (FormatTok->is(tok::semi))
1847 Line->Level = OldLineLevel;
1848 if (FormatTok->isNot(tok::l_brace)) {
1849 parseStructuralElement();
1854 void UnwrappedLineParser::parseCaseLabel() {
1855 assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
1856 // FIXME: fix handling of complex expressions here.
1859 } while (!eof() && !FormatTok->Tok.is(tok::colon));
1863 void UnwrappedLineParser::parseSwitch() {
1864 assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
1866 if (FormatTok->Tok.is(tok::l_paren))
1868 if (FormatTok->Tok.is(tok::l_brace)) {
1869 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1870 parseBlock(/*MustBeDeclaration=*/false);
1875 parseStructuralElement();
1880 void UnwrappedLineParser::parseAccessSpecifier() {
1882 // Understand Qt's slots.
1883 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
1885 // Otherwise, we don't know what it is, and we'd better keep the next token.
1886 if (FormatTok->Tok.is(tok::colon))
1891 bool UnwrappedLineParser::parseEnum() {
1892 // Won't be 'enum' for NS_ENUMs.
1893 if (FormatTok->Tok.is(tok::kw_enum))
1896 // In TypeScript, "enum" can also be used as property name, e.g. in interface
1897 // declarations. An "enum" keyword followed by a colon would be a syntax
1898 // error and thus assume it is just an identifier.
1899 if (Style.Language == FormatStyle::LK_JavaScript &&
1900 FormatTok->isOneOf(tok::colon, tok::question))
1903 // Eat up enum class ...
1904 if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct))
1907 while (FormatTok->Tok.getIdentifierInfo() ||
1908 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
1909 tok::greater, tok::comma, tok::question)) {
1911 // We can have macros or attributes in between 'enum' and the enum name.
1912 if (FormatTok->is(tok::l_paren))
1914 if (FormatTok->is(tok::identifier)) {
1916 // If there are two identifiers in a row, this is likely an elaborate
1917 // return type. In Java, this can be "implements", etc.
1918 if (Style.isCpp() && FormatTok->is(tok::identifier))
1923 // Just a declaration or something is wrong.
1924 if (FormatTok->isNot(tok::l_brace))
1926 FormatTok->BlockKind = BK_Block;
1928 if (Style.Language == FormatStyle::LK_Java) {
1929 // Java enums are different.
1930 parseJavaEnumBody();
1933 if (Style.Language == FormatStyle::LK_Proto) {
1934 parseBlock(/*MustBeDeclaration=*/true);
1940 bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true);
1942 if (FormatTok->is(tok::semi))
1948 // There is no addUnwrappedLine() here so that we fall through to parsing a
1949 // structural element afterwards. Thus, in "enum A {} n, m;",
1950 // "} n, m;" will end up in one unwrapped line.
1953 void UnwrappedLineParser::parseJavaEnumBody() {
1954 // Determine whether the enum is simple, i.e. does not have a semicolon or
1955 // constants with class bodies. Simple enums can be formatted like braced
1956 // lists, contracted to a single line, etc.
1957 unsigned StoredPosition = Tokens->getPosition();
1958 bool IsSimple = true;
1959 FormatToken *Tok = Tokens->getNextToken();
1961 if (Tok->is(tok::r_brace))
1963 if (Tok->isOneOf(tok::l_brace, tok::semi)) {
1967 // FIXME: This will also mark enums with braces in the arguments to enum
1968 // constants as "not simple". This is probably fine in practice, though.
1969 Tok = Tokens->getNextToken();
1971 FormatTok = Tokens->setPosition(StoredPosition);
1980 // Parse the body of a more complex enum.
1981 // First add a line for everything up to the "{".
1986 // Parse the enum constants.
1988 if (FormatTok->is(tok::l_brace)) {
1989 // Parse the constant's class body.
1990 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1991 /*MunchSemi=*/false);
1992 } else if (FormatTok->is(tok::l_paren)) {
1994 } else if (FormatTok->is(tok::comma)) {
1997 } else if (FormatTok->is(tok::semi)) {
2001 } else if (FormatTok->is(tok::r_brace)) {
2009 // Parse the class body after the enum's ";" if any.
2010 parseLevel(/*HasOpeningBrace=*/true);
2016 void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
2017 const FormatToken &InitialToken = *FormatTok;
2020 // The actual identifier can be a nested name specifier, and in macros
2021 // it is often token-pasted.
2022 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
2023 tok::kw___attribute, tok::kw___declspec,
2025 ((Style.Language == FormatStyle::LK_Java ||
2026 Style.Language == FormatStyle::LK_JavaScript) &&
2027 FormatTok->isOneOf(tok::period, tok::comma))) {
2028 if (Style.Language == FormatStyle::LK_JavaScript &&
2029 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
2030 // JavaScript/TypeScript supports inline object types in
2031 // extends/implements positions:
2032 // class Foo implements {bar: number} { }
2034 if (FormatTok->is(tok::l_brace)) {
2035 tryToParseBracedList();
2039 bool IsNonMacroIdentifier =
2040 FormatTok->is(tok::identifier) &&
2041 FormatTok->TokenText != FormatTok->TokenText.upper();
2043 // We can have macros or attributes in between 'class' and the class name.
2044 if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren))
2048 // Note that parsing away template declarations here leads to incorrectly
2049 // accepting function declarations as record declarations.
2050 // In general, we cannot solve this problem. Consider:
2051 // class A<int> B() {}
2052 // which can be a function definition or a class definition when B() is a
2053 // macro. If we find enough real-world cases where this is a problem, we
2054 // can parse for the 'template' keyword in the beginning of the statement,
2055 // and thus rule out the record production in case there is no template
2056 // (this would still leave us with an ambiguity between template function
2057 // and class declarations).
2058 if (FormatTok->isOneOf(tok::colon, tok::less)) {
2060 if (FormatTok->is(tok::l_brace)) {
2061 calculateBraceTypes(/*ExpectClassBody=*/true);
2062 if (!tryToParseBracedList())
2065 if (FormatTok->Tok.is(tok::semi))
2070 if (FormatTok->Tok.is(tok::l_brace)) {
2074 if (ShouldBreakBeforeBrace(Style, InitialToken))
2077 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
2078 /*MunchSemi=*/false);
2081 // There is no addUnwrappedLine() here so that we fall through to parsing a
2082 // structural element afterwards. Thus, in "class A {} n, m;",
2083 // "} n, m;" will end up in one unwrapped line.
2086 void UnwrappedLineParser::parseObjCProtocolList() {
2087 assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
2090 while (!eof() && FormatTok->Tok.isNot(tok::greater));
2091 nextToken(); // Skip '>'.
2094 void UnwrappedLineParser::parseObjCUntilAtEnd() {
2096 if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
2101 if (FormatTok->is(tok::l_brace)) {
2102 parseBlock(/*MustBeDeclaration=*/false);
2103 // In ObjC interfaces, nothing should be following the "}".
2105 } else if (FormatTok->is(tok::r_brace)) {
2106 // Ignore stray "}". parseStructuralElement doesn't consume them.
2110 parseStructuralElement();
2115 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
2117 nextToken(); // interface name
2119 // @interface can be followed by either a base class, or a category.
2120 if (FormatTok->Tok.is(tok::colon)) {
2122 nextToken(); // base class name
2123 } else if (FormatTok->Tok.is(tok::l_paren))
2124 // Skip category, if present.
2127 if (FormatTok->Tok.is(tok::less))
2128 parseObjCProtocolList();
2130 if (FormatTok->Tok.is(tok::l_brace)) {
2131 if (Style.BraceWrapping.AfterObjCDeclaration)
2133 parseBlock(/*MustBeDeclaration=*/true);
2136 // With instance variables, this puts '}' on its own line. Without instance
2137 // variables, this ends the @interface line.
2140 parseObjCUntilAtEnd();
2143 void UnwrappedLineParser::parseObjCProtocol() {
2145 nextToken(); // protocol name
2147 if (FormatTok->Tok.is(tok::less))
2148 parseObjCProtocolList();
2150 // Check for protocol declaration.
2151 if (FormatTok->Tok.is(tok::semi)) {
2153 return addUnwrappedLine();
2157 parseObjCUntilAtEnd();
2160 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
2161 bool IsImport = FormatTok->is(Keywords.kw_import);
2162 assert(IsImport || FormatTok->is(tok::kw_export));
2165 // Consume the "default" in "export default class/function".
2166 if (FormatTok->is(tok::kw_default))
2169 // Consume "async function", "function" and "default function", so that these
2170 // get parsed as free-standing JS functions, i.e. do not require a trailing
2172 if (FormatTok->is(Keywords.kw_async))
2174 if (FormatTok->is(Keywords.kw_function)) {
2179 // For imports, `export *`, `export {...}`, consume the rest of the line up
2180 // to the terminating `;`. For everything else, just return and continue
2181 // parsing the structural element, i.e. the declaration or expression for
2182 // `export default`.
2183 if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) &&
2184 !FormatTok->isStringLiteral())
2188 if (FormatTok->is(tok::semi))
2190 if (Line->Tokens.empty()) {
2191 // Common issue: Automatic Semicolon Insertion wrapped the line, so the
2192 // import statement should terminate.
2195 if (FormatTok->is(tok::l_brace)) {
2196 FormatTok->BlockKind = BK_Block;
2205 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
2206 StringRef Prefix = "") {
2207 llvm::dbgs() << Prefix << "Line(" << Line.Level
2208 << ", FSC=" << Line.FirstStartColumn << ")"
2209 << (Line.InPPDirective ? " MACRO" : "") << ": ";
2210 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2211 E = Line.Tokens.end();
2213 llvm::dbgs() << I->Tok->Tok.getName() << "["
2214 << "T=" << I->Tok->Type << ", OC=" << I->Tok->OriginalColumn
2217 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2218 E = Line.Tokens.end();
2220 const UnwrappedLineNode &Node = *I;
2221 for (SmallVectorImpl<UnwrappedLine>::const_iterator
2222 I = Node.Children.begin(),
2223 E = Node.Children.end();
2225 printDebugInfo(*I, "\nChild: ");
2228 llvm::dbgs() << "\n";
2231 void UnwrappedLineParser::addUnwrappedLine() {
2232 if (Line->Tokens.empty())
2235 if (CurrentLines == &Lines)
2236 printDebugInfo(*Line);
2238 CurrentLines->push_back(std::move(*Line));
2239 Line->Tokens.clear();
2240 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
2241 Line->FirstStartColumn = 0;
2242 if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
2243 CurrentLines->append(
2244 std::make_move_iterator(PreprocessorDirectives.begin()),
2245 std::make_move_iterator(PreprocessorDirectives.end()));
2246 PreprocessorDirectives.clear();
2248 // Disconnect the current token from the last token on the previous line.
2249 FormatTok->Previous = nullptr;
2252 bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
2254 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
2255 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
2256 FormatTok.NewlinesBefore > 0;
2259 // Checks if \p FormatTok is a line comment that continues the line comment
2260 // section on \p Line.
2261 static bool continuesLineCommentSection(const FormatToken &FormatTok,
2262 const UnwrappedLine &Line,
2263 llvm::Regex &CommentPragmasRegex) {
2264 if (Line.Tokens.empty())
2267 StringRef IndentContent = FormatTok.TokenText;
2268 if (FormatTok.TokenText.startswith("//") ||
2269 FormatTok.TokenText.startswith("/*"))
2270 IndentContent = FormatTok.TokenText.substr(2);
2271 if (CommentPragmasRegex.match(IndentContent))
2274 // If Line starts with a line comment, then FormatTok continues the comment
2275 // section if its original column is greater or equal to the original start
2276 // column of the line.
2278 // Define the min column token of a line as follows: if a line ends in '{' or
2279 // contains a '{' followed by a line comment, then the min column token is
2280 // that '{'. Otherwise, the min column token of the line is the first token of
2283 // If Line starts with a token other than a line comment, then FormatTok
2284 // continues the comment section if its original column is greater than the
2285 // original start column of the min column token of the line.
2287 // For example, the second line comment continues the first in these cases:
2299 // int i; // first line
2304 // do { // first line
2317 // The second line comment doesn't continue the first in these cases:
2324 // int i; // first line
2329 // do { // first line
2340 const FormatToken *MinColumnToken = Line.Tokens.front().Tok;
2342 // Scan for '{//'. If found, use the column of '{' as a min column for line
2343 // comment section continuation.
2344 const FormatToken *PreviousToken = nullptr;
2345 for (const UnwrappedLineNode &Node : Line.Tokens) {
2346 if (PreviousToken && PreviousToken->is(tok::l_brace) &&
2347 isLineComment(*Node.Tok)) {
2348 MinColumnToken = PreviousToken;
2351 PreviousToken = Node.Tok;
2353 // Grab the last newline preceding a token in this unwrapped line.
2354 if (Node.Tok->NewlinesBefore > 0) {
2355 MinColumnToken = Node.Tok;
2358 if (PreviousToken && PreviousToken->is(tok::l_brace)) {
2359 MinColumnToken = PreviousToken;
2362 return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok,
2366 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
2367 bool JustComments = Line->Tokens.empty();
2368 for (SmallVectorImpl<FormatToken *>::const_iterator
2369 I = CommentsBeforeNextToken.begin(),
2370 E = CommentsBeforeNextToken.end();
2372 // Line comments that belong to the same line comment section are put on the
2373 // same line since later we might want to reflow content between them.
2374 // Additional fine-grained breaking of line comment sections is controlled
2375 // by the class BreakableLineCommentSection in case it is desirable to keep
2376 // several line comment sections in the same unwrapped line.
2378 // FIXME: Consider putting separate line comment sections as children to the
2379 // unwrapped line instead.
2380 (*I)->ContinuesLineCommentSection =
2381 continuesLineCommentSection(**I, *Line, CommentPragmasRegex);
2382 if (isOnNewLine(**I) && JustComments && !(*I)->ContinuesLineCommentSection)
2386 if (NewlineBeforeNext && JustComments)
2388 CommentsBeforeNextToken.clear();
2391 void UnwrappedLineParser::nextToken(int LevelDifference) {
2394 flushComments(isOnNewLine(*FormatTok));
2395 pushToken(FormatTok);
2396 FormatToken *Previous = FormatTok;
2397 if (Style.Language != FormatStyle::LK_JavaScript)
2398 readToken(LevelDifference);
2400 readTokenWithJavaScriptASI();
2401 FormatTok->Previous = Previous;
2404 void UnwrappedLineParser::distributeComments(
2405 const SmallVectorImpl<FormatToken *> &Comments,
2406 const FormatToken *NextTok) {
2407 // Whether or not a line comment token continues a line is controlled by
2408 // the method continuesLineCommentSection, with the following caveat:
2410 // Define a trail of Comments to be a nonempty proper postfix of Comments such
2411 // that each comment line from the trail is aligned with the next token, if
2412 // the next token exists. If a trail exists, the beginning of the maximal
2413 // trail is marked as a start of a new comment section.
2415 // For example in this code:
2417 // int a; // line about a
2418 // // line 1 about b
2419 // // line 2 about b
2422 // the two lines about b form a maximal trail, so there are two sections, the
2423 // first one consisting of the single comment "// line about a" and the
2424 // second one consisting of the next two comments.
2425 if (Comments.empty())
2427 bool ShouldPushCommentsInCurrentLine = true;
2428 bool HasTrailAlignedWithNextToken = false;
2429 unsigned StartOfTrailAlignedWithNextToken = 0;
2431 // We are skipping the first element intentionally.
2432 for (unsigned i = Comments.size() - 1; i > 0; --i) {
2433 if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) {
2434 HasTrailAlignedWithNextToken = true;
2435 StartOfTrailAlignedWithNextToken = i;
2439 for (unsigned i = 0, e = Comments.size(); i < e; ++i) {
2440 FormatToken *FormatTok = Comments[i];
2441 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
2442 FormatTok->ContinuesLineCommentSection = false;
2444 FormatTok->ContinuesLineCommentSection =
2445 continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex);
2447 if (!FormatTok->ContinuesLineCommentSection &&
2448 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
2449 ShouldPushCommentsInCurrentLine = false;
2451 if (ShouldPushCommentsInCurrentLine) {
2452 pushToken(FormatTok);
2454 CommentsBeforeNextToken.push_back(FormatTok);
2459 void UnwrappedLineParser::readToken(int LevelDifference) {
2460 SmallVector<FormatToken *, 1> Comments;
2462 FormatTok = Tokens->getNextToken();
2464 while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
2465 (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
2466 distributeComments(Comments, FormatTok);
2468 // If there is an unfinished unwrapped line, we flush the preprocessor
2469 // directives only after that unwrapped line was finished later.
2470 bool SwitchToPreprocessorLines = !Line->Tokens.empty();
2471 ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
2472 assert((LevelDifference >= 0 ||
2473 static_cast<unsigned>(-LevelDifference) <= Line->Level) &&
2474 "LevelDifference makes Line->Level negative");
2475 Line->Level += LevelDifference;
2476 // Comments stored before the preprocessor directive need to be output
2477 // before the preprocessor directive, at the same level as the
2478 // preprocessor directive, as we consider them to apply to the directive.
2479 flushComments(isOnNewLine(*FormatTok));
2482 while (FormatTok->Type == TT_ConflictStart ||
2483 FormatTok->Type == TT_ConflictEnd ||
2484 FormatTok->Type == TT_ConflictAlternative) {
2485 if (FormatTok->Type == TT_ConflictStart) {
2486 conditionalCompilationStart(/*Unreachable=*/false);
2487 } else if (FormatTok->Type == TT_ConflictAlternative) {
2488 conditionalCompilationAlternative();
2489 } else if (FormatTok->Type == TT_ConflictEnd) {
2490 conditionalCompilationEnd();
2492 FormatTok = Tokens->getNextToken();
2493 FormatTok->MustBreakBefore = true;
2496 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
2497 !Line->InPPDirective) {
2501 if (!FormatTok->Tok.is(tok::comment)) {
2502 distributeComments(Comments, FormatTok);
2507 Comments.push_back(FormatTok);
2510 distributeComments(Comments, nullptr);
2514 void UnwrappedLineParser::pushToken(FormatToken *Tok) {
2515 Line->Tokens.push_back(UnwrappedLineNode(Tok));
2516 if (MustBreakBeforeNextToken) {
2517 Line->Tokens.back().Tok->MustBreakBefore = true;
2518 MustBreakBeforeNextToken = false;
2522 } // end namespace format
2523 } // end namespace clang