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 /// 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) {
86 FakeEOF.Tok.startToken();
87 FakeEOF.Tok.setKind(tok::eof);
90 Line.InPPDirective = true;
93 ~ScopedMacroState() override {
94 TokenSource = PreviousTokenSource;
96 Line.InPPDirective = false;
97 Line.Level = PreviousLineLevel;
100 FormatToken *getNextToken() override {
101 // The \c UnwrappedLineParser guards against this by never calling
102 // \c getNextToken() after it has encountered the first eof token.
104 PreviousToken = Token;
105 Token = PreviousTokenSource->getNextToken();
111 unsigned getPosition() override { return PreviousTokenSource->getPosition(); }
113 FormatToken *setPosition(unsigned Position) override {
114 PreviousToken = nullptr;
115 Token = PreviousTokenSource->setPosition(Position);
121 return Token && Token->HasUnescapedNewline &&
122 !continuesLineComment(*Token, PreviousToken,
123 /*MinColumnToken=*/PreviousToken);
128 FormatTokenSource *&TokenSource;
129 FormatToken *&ResetToken;
130 unsigned PreviousLineLevel;
131 FormatTokenSource *PreviousTokenSource;
134 FormatToken *PreviousToken;
137 } // end anonymous namespace
139 class ScopedLineState {
141 ScopedLineState(UnwrappedLineParser &Parser,
142 bool SwitchToPreprocessorLines = false)
143 : Parser(Parser), OriginalLines(Parser.CurrentLines) {
144 if (SwitchToPreprocessorLines)
145 Parser.CurrentLines = &Parser.PreprocessorDirectives;
146 else if (!Parser.Line->Tokens.empty())
147 Parser.CurrentLines = &Parser.Line->Tokens.back().Children;
148 PreBlockLine = std::move(Parser.Line);
149 Parser.Line = llvm::make_unique<UnwrappedLine>();
150 Parser.Line->Level = PreBlockLine->Level;
151 Parser.Line->InPPDirective = PreBlockLine->InPPDirective;
155 if (!Parser.Line->Tokens.empty()) {
156 Parser.addUnwrappedLine();
158 assert(Parser.Line->Tokens.empty());
159 Parser.Line = std::move(PreBlockLine);
160 if (Parser.CurrentLines == &Parser.PreprocessorDirectives)
161 Parser.MustBreakBeforeNextToken = true;
162 Parser.CurrentLines = OriginalLines;
166 UnwrappedLineParser &Parser;
168 std::unique_ptr<UnwrappedLine> PreBlockLine;
169 SmallVectorImpl<UnwrappedLine> *OriginalLines;
172 class CompoundStatementIndenter {
174 CompoundStatementIndenter(UnwrappedLineParser *Parser,
175 const FormatStyle &Style, unsigned &LineLevel)
176 : LineLevel(LineLevel), OldLineLevel(LineLevel) {
177 if (Style.BraceWrapping.AfterControlStatement)
178 Parser->addUnwrappedLine();
179 if (Style.BraceWrapping.IndentBraces)
182 ~CompoundStatementIndenter() { LineLevel = OldLineLevel; }
186 unsigned OldLineLevel;
191 class IndexedTokenSource : public FormatTokenSource {
193 IndexedTokenSource(ArrayRef<FormatToken *> Tokens)
194 : Tokens(Tokens), Position(-1) {}
196 FormatToken *getNextToken() override {
198 return Tokens[Position];
201 unsigned getPosition() override {
202 assert(Position >= 0);
206 FormatToken *setPosition(unsigned P) override {
208 return Tokens[Position];
211 void reset() { Position = -1; }
214 ArrayRef<FormatToken *> Tokens;
218 } // end anonymous namespace
220 UnwrappedLineParser::UnwrappedLineParser(const FormatStyle &Style,
221 const AdditionalKeywords &Keywords,
222 unsigned FirstStartColumn,
223 ArrayRef<FormatToken *> Tokens,
224 UnwrappedLineConsumer &Callback)
225 : Line(new UnwrappedLine), MustBreakBeforeNextToken(false),
226 CurrentLines(&Lines), Style(Style), Keywords(Keywords),
227 CommentPragmasRegex(Style.CommentPragmas), Tokens(nullptr),
228 Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1),
229 IncludeGuard(Style.IndentPPDirectives == FormatStyle::PPDIS_None
232 IncludeGuardToken(nullptr), FirstStartColumn(FirstStartColumn) {}
234 void UnwrappedLineParser::reset() {
236 IncludeGuard = Style.IndentPPDirectives == FormatStyle::PPDIS_None
239 IncludeGuardToken = nullptr;
240 Line.reset(new UnwrappedLine);
241 CommentsBeforeNextToken.clear();
243 MustBreakBeforeNextToken = false;
244 PreprocessorDirectives.clear();
245 CurrentLines = &Lines;
246 DeclarationScopeStack.clear();
248 Line->FirstStartColumn = FirstStartColumn;
251 void UnwrappedLineParser::parse() {
252 IndexedTokenSource TokenSource(AllTokens);
253 Line->FirstStartColumn = FirstStartColumn;
255 LLVM_DEBUG(llvm::dbgs() << "----\n");
257 Tokens = &TokenSource;
263 // If we found an include guard then all preprocessor directives (other than
264 // the guard) are over-indented by one.
265 if (IncludeGuard == IG_Found)
266 for (auto &Line : Lines)
267 if (Line.InPPDirective && Line.Level > 0)
270 // Create line with eof token.
271 pushToken(FormatTok);
274 for (SmallVectorImpl<UnwrappedLine>::iterator I = Lines.begin(),
277 Callback.consumeUnwrappedLine(*I);
279 Callback.finishRun();
281 while (!PPLevelBranchIndex.empty() &&
282 PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) {
283 PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1);
284 PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1);
286 if (!PPLevelBranchIndex.empty()) {
287 ++PPLevelBranchIndex.back();
288 assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size());
289 assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back());
291 } while (!PPLevelBranchIndex.empty());
294 void UnwrappedLineParser::parseFile() {
295 // The top-level context in a file always has declarations, except for pre-
296 // processor directives and JavaScript files.
297 bool MustBeDeclaration =
298 !Line->InPPDirective && Style.Language != FormatStyle::LK_JavaScript;
299 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
301 if (Style.Language == FormatStyle::LK_TextProto)
304 parseLevel(/*HasOpeningBrace=*/false);
305 // Make sure to format the remaining tokens.
307 // LK_TextProto is special since its top-level is parsed as the body of a
308 // braced list, which does not necessarily have natural line separators such
309 // as a semicolon. Comments after the last entry that have been determined to
310 // not belong to that line, as in:
312 // // endfile comment
313 // do not have a chance to be put on a line of their own until this point.
314 // Here we add this newline before end-of-file comments.
315 if (Style.Language == FormatStyle::LK_TextProto &&
316 !CommentsBeforeNextToken.empty())
322 void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) {
323 bool SwitchLabelEncountered = false;
325 tok::TokenKind kind = FormatTok->Tok.getKind();
326 if (FormatTok->Type == TT_MacroBlockBegin) {
328 } else if (FormatTok->Type == TT_MacroBlockEnd) {
338 // FIXME: Add parameter whether this can happen - if this happens, we must
339 // be in a non-declaration context.
340 if (!FormatTok->is(TT_MacroBlockBegin) && tryToParseBracedList())
342 parseBlock(/*MustBeDeclaration=*/false);
351 case tok::kw_default: {
352 unsigned StoredPosition = Tokens->getPosition();
355 Next = Tokens->getNextToken();
356 } while (Next && Next->is(tok::comment));
357 FormatTok = Tokens->setPosition(StoredPosition);
358 if (Next && Next->isNot(tok::colon)) {
359 // default not followed by ':' is not a case label; treat it like
361 parseStructuralElement();
364 // Else, if it is 'default:', fall through to the case handling.
368 if (Style.Language == FormatStyle::LK_JavaScript &&
369 Line->MustBeDeclaration) {
370 // A 'case: string' style field declaration.
371 parseStructuralElement();
374 if (!SwitchLabelEncountered &&
375 (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1)))
377 SwitchLabelEncountered = true;
378 parseStructuralElement();
381 parseStructuralElement();
387 void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) {
388 // We'll parse forward through the tokens until we hit
389 // a closing brace or eof - note that getNextToken() will
390 // parse macros, so this will magically work inside macro
392 unsigned StoredPosition = Tokens->getPosition();
393 FormatToken *Tok = FormatTok;
394 const FormatToken *PrevTok = Tok->Previous;
395 // Keep a stack of positions of lbrace tokens. We will
396 // update information about whether an lbrace starts a
397 // braced init list or a different block during the loop.
398 SmallVector<FormatToken *, 8> LBraceStack;
399 assert(Tok->Tok.is(tok::l_brace));
401 // Get next non-comment token.
402 FormatToken *NextTok;
403 unsigned ReadTokens = 0;
405 NextTok = Tokens->getNextToken();
407 } while (NextTok->is(tok::comment));
409 switch (Tok->Tok.getKind()) {
411 if (Style.Language == FormatStyle::LK_JavaScript && PrevTok) {
412 if (PrevTok->isOneOf(tok::colon, tok::less))
413 // A ':' indicates this code is in a type, or a braced list
414 // following a label in an object literal ({a: {b: 1}}).
415 // A '<' could be an object used in a comparison, but that is nonsense
416 // code (can never return true), so more likely it is a generic type
417 // argument (`X<{a: string; b: number}>`).
418 // The code below could be confused by semicolons between the
419 // individual members in a type member list, which would normally
420 // trigger BK_Block. In both cases, this must be parsed as an inline
422 Tok->BlockKind = BK_BracedInit;
423 else if (PrevTok->is(tok::r_paren))
424 // `) { }` can only occur in function or method declarations in JS.
425 Tok->BlockKind = BK_Block;
427 Tok->BlockKind = BK_Unknown;
429 LBraceStack.push_back(Tok);
432 if (LBraceStack.empty())
434 if (LBraceStack.back()->BlockKind == BK_Unknown) {
435 bool ProbablyBracedList = false;
436 if (Style.Language == FormatStyle::LK_Proto) {
437 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
439 // Using OriginalColumn to distinguish between ObjC methods and
440 // binary operators is a bit hacky.
441 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
442 NextTok->OriginalColumn == 0;
444 // If there is a comma, semicolon or right paren after the closing
445 // brace, we assume this is a braced initializer list. Note that
446 // regardless how we mark inner braces here, we will overwrite the
447 // BlockKind later if we parse a braced list (where all blocks
448 // inside are by default braced lists), or when we explicitly detect
449 // blocks (for example while parsing lambdas).
450 // FIXME: Some of these do not apply to JS, e.g. "} {" can never be a
451 // braced list in JS.
453 (Style.Language == FormatStyle::LK_JavaScript &&
454 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
456 (Style.isCpp() && NextTok->is(tok::l_paren)) ||
457 NextTok->isOneOf(tok::comma, tok::period, tok::colon,
458 tok::r_paren, tok::r_square, tok::l_brace,
460 (NextTok->is(tok::identifier) &&
461 !PrevTok->isOneOf(tok::semi, tok::r_brace, tok::l_brace)) ||
462 (NextTok->is(tok::semi) &&
463 (!ExpectClassBody || LBraceStack.size() != 1)) ||
464 (NextTok->isBinaryOperator() && !NextIsObjCMethod);
465 if (NextTok->is(tok::l_square)) {
466 // We can have an array subscript after a braced init
467 // list, but C++11 attributes are expected after blocks.
468 NextTok = Tokens->getNextToken();
470 ProbablyBracedList = NextTok->isNot(tok::l_square);
473 if (ProbablyBracedList) {
474 Tok->BlockKind = BK_BracedInit;
475 LBraceStack.back()->BlockKind = BK_BracedInit;
477 Tok->BlockKind = BK_Block;
478 LBraceStack.back()->BlockKind = BK_Block;
481 LBraceStack.pop_back();
483 case tok::identifier:
484 if (!Tok->is(TT_StatementMacro))
495 if (!LBraceStack.empty() && LBraceStack.back()->BlockKind == BK_Unknown)
496 LBraceStack.back()->BlockKind = BK_Block;
503 } while (Tok->Tok.isNot(tok::eof) && !LBraceStack.empty());
505 // Assume other blocks for all unclosed opening braces.
506 for (unsigned i = 0, e = LBraceStack.size(); i != e; ++i) {
507 if (LBraceStack[i]->BlockKind == BK_Unknown)
508 LBraceStack[i]->BlockKind = BK_Block;
511 FormatTok = Tokens->setPosition(StoredPosition);
515 static inline void hash_combine(std::size_t &seed, const T &v) {
517 seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
520 size_t UnwrappedLineParser::computePPHash() const {
522 for (const auto &i : PPStack) {
523 hash_combine(h, size_t(i.Kind));
524 hash_combine(h, i.Line);
529 void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel,
531 assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) &&
532 "'{' or macro block token expected");
533 const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
534 FormatTok->BlockKind = BK_Block;
536 size_t PPStartHash = computePPHash();
538 unsigned InitialLevel = Line->Level;
539 nextToken(/*LevelDifference=*/AddLevel ? 1 : 0);
541 if (MacroBlock && FormatTok->is(tok::l_paren))
544 size_t NbPreprocessorDirectives =
545 CurrentLines == &Lines ? PreprocessorDirectives.size() : 0;
547 size_t OpeningLineIndex =
548 CurrentLines->empty()
549 ? (UnwrappedLine::kInvalidIndex)
550 : (CurrentLines->size() - 1 - NbPreprocessorDirectives);
552 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
556 parseLevel(/*HasOpeningBrace=*/true);
561 if (MacroBlock ? !FormatTok->is(TT_MacroBlockEnd)
562 : !FormatTok->is(tok::r_brace)) {
563 Line->Level = InitialLevel;
564 FormatTok->BlockKind = BK_Block;
568 size_t PPEndHash = computePPHash();
570 // Munch the closing brace.
571 nextToken(/*LevelDifference=*/AddLevel ? -1 : 0);
573 if (MacroBlock && FormatTok->is(tok::l_paren))
576 if (MunchSemi && FormatTok->Tok.is(tok::semi))
578 Line->Level = InitialLevel;
580 if (PPStartHash == PPEndHash) {
581 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
582 if (OpeningLineIndex != UnwrappedLine::kInvalidIndex) {
583 // Update the opening line to add the forward reference as well
584 (*CurrentLines)[OpeningLineIndex].MatchingClosingBlockLineIndex =
585 CurrentLines->size() - 1;
590 static bool isGoogScope(const UnwrappedLine &Line) {
591 // FIXME: Closure-library specific stuff should not be hard-coded but be
593 if (Line.Tokens.size() < 4)
595 auto I = Line.Tokens.begin();
596 if (I->Tok->TokenText != "goog")
599 if (I->Tok->isNot(tok::period))
602 if (I->Tok->TokenText != "scope")
605 return I->Tok->is(tok::l_paren);
608 static bool isIIFE(const UnwrappedLine &Line,
609 const AdditionalKeywords &Keywords) {
610 // Look for the start of an immediately invoked anonymous function.
611 // https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
612 // This is commonly done in JavaScript to create a new, anonymous scope.
613 // Example: (function() { ... })()
614 if (Line.Tokens.size() < 3)
616 auto I = Line.Tokens.begin();
617 if (I->Tok->isNot(tok::l_paren))
620 if (I->Tok->isNot(Keywords.kw_function))
623 return I->Tok->is(tok::l_paren);
626 static bool ShouldBreakBeforeBrace(const FormatStyle &Style,
627 const FormatToken &InitialToken) {
628 if (InitialToken.is(tok::kw_namespace))
629 return Style.BraceWrapping.AfterNamespace;
630 if (InitialToken.is(tok::kw_class))
631 return Style.BraceWrapping.AfterClass;
632 if (InitialToken.is(tok::kw_union))
633 return Style.BraceWrapping.AfterUnion;
634 if (InitialToken.is(tok::kw_struct))
635 return Style.BraceWrapping.AfterStruct;
639 void UnwrappedLineParser::parseChildBlock() {
640 FormatTok->BlockKind = BK_Block;
643 bool SkipIndent = (Style.Language == FormatStyle::LK_JavaScript &&
644 (isGoogScope(*Line) || isIIFE(*Line, Keywords)));
645 ScopedLineState LineState(*this);
646 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
647 /*MustBeDeclaration=*/false);
648 Line->Level += SkipIndent ? 0 : 1;
649 parseLevel(/*HasOpeningBrace=*/true);
650 flushComments(isOnNewLine(*FormatTok));
651 Line->Level -= SkipIndent ? 0 : 1;
656 void UnwrappedLineParser::parsePPDirective() {
657 assert(FormatTok->Tok.is(tok::hash) && "'#' expected");
658 ScopedMacroState MacroState(*Line, Tokens, FormatTok);
661 if (!FormatTok->Tok.getIdentifierInfo()) {
666 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
671 parsePPIf(/*IfDef=*/false);
675 parsePPIf(/*IfDef=*/true);
692 void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) {
693 size_t Line = CurrentLines->size();
694 if (CurrentLines == &PreprocessorDirectives)
695 Line += Lines.size();
698 (!PPStack.empty() && PPStack.back().Kind == PP_Unreachable))
699 PPStack.push_back({PP_Unreachable, Line});
701 PPStack.push_back({PP_Conditional, Line});
704 void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) {
706 assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
707 if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
708 PPLevelBranchIndex.push_back(0);
709 PPLevelBranchCount.push_back(0);
711 PPChainBranchIndex.push(0);
712 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
713 conditionalCompilationCondition(Unreachable || Skip);
716 void UnwrappedLineParser::conditionalCompilationAlternative() {
717 if (!PPStack.empty())
719 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
720 if (!PPChainBranchIndex.empty())
721 ++PPChainBranchIndex.top();
722 conditionalCompilationCondition(
723 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
724 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
727 void UnwrappedLineParser::conditionalCompilationEnd() {
728 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
729 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
730 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) {
731 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
734 // Guard against #endif's without #if.
735 if (PPBranchLevel > -1)
737 if (!PPChainBranchIndex.empty())
738 PPChainBranchIndex.pop();
739 if (!PPStack.empty())
743 void UnwrappedLineParser::parsePPIf(bool IfDef) {
744 bool IfNDef = FormatTok->is(tok::pp_ifndef);
746 bool Unreachable = false;
747 if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText == "0"))
749 if (IfDef && !IfNDef && FormatTok->TokenText == "SWIG")
751 conditionalCompilationStart(Unreachable);
752 FormatToken *IfCondition = FormatTok;
753 // If there's a #ifndef on the first line, and the only lines before it are
754 // comments, it could be an include guard.
755 bool MaybeIncludeGuard = IfNDef;
756 if (IncludeGuard == IG_Inited && MaybeIncludeGuard)
757 for (auto &Line : Lines) {
758 if (!Line.Tokens.front().Tok->is(tok::comment)) {
759 MaybeIncludeGuard = false;
760 IncludeGuard = IG_Rejected;
767 if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
768 IncludeGuard = IG_IfNdefed;
769 IncludeGuardToken = IfCondition;
773 void UnwrappedLineParser::parsePPElse() {
774 // If a potential include guard has an #else, it's not an include guard.
775 if (IncludeGuard == IG_Defined && PPBranchLevel == 0)
776 IncludeGuard = IG_Rejected;
777 conditionalCompilationAlternative();
778 if (PPBranchLevel > -1)
784 void UnwrappedLineParser::parsePPElIf() { parsePPElse(); }
786 void UnwrappedLineParser::parsePPEndIf() {
787 conditionalCompilationEnd();
789 // If the #endif of a potential include guard is the last thing in the file,
790 // then we found an include guard.
791 unsigned TokenPosition = Tokens->getPosition();
792 FormatToken *PeekNext = AllTokens[TokenPosition];
793 if (IncludeGuard == IG_Defined && PPBranchLevel == -1 &&
794 PeekNext->is(tok::eof) &&
795 Style.IndentPPDirectives != FormatStyle::PPDIS_None)
796 IncludeGuard = IG_Found;
799 void UnwrappedLineParser::parsePPDefine() {
802 if (FormatTok->Tok.getKind() != tok::identifier) {
803 IncludeGuard = IG_Rejected;
804 IncludeGuardToken = nullptr;
809 if (IncludeGuard == IG_IfNdefed &&
810 IncludeGuardToken->TokenText == FormatTok->TokenText) {
811 IncludeGuard = IG_Defined;
812 IncludeGuardToken = nullptr;
813 for (auto &Line : Lines) {
814 if (!Line.Tokens.front().Tok->isOneOf(tok::comment, tok::hash)) {
815 IncludeGuard = IG_Rejected;
822 if (FormatTok->Tok.getKind() == tok::l_paren &&
823 FormatTok->WhitespaceRange.getBegin() ==
824 FormatTok->WhitespaceRange.getEnd()) {
827 if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash)
828 Line->Level += PPBranchLevel + 1;
832 // Errors during a preprocessor directive can only affect the layout of the
833 // preprocessor directive, and thus we ignore them. An alternative approach
834 // would be to use the same approach we use on the file level (no
835 // re-indentation if there was a structural error) within the macro
840 void UnwrappedLineParser::parsePPUnknown() {
844 if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash)
845 Line->Level += PPBranchLevel + 1;
849 // Here we blacklist certain tokens that are not usually the first token in an
850 // unwrapped line. This is used in attempt to distinguish macro calls without
851 // trailing semicolons from other constructs split to several lines.
852 static bool tokenCanStartNewLine(const clang::Token &Tok) {
853 // Semicolon can be a null-statement, l_square can be a start of a macro or
854 // a C++11 attribute, but this doesn't seem to be common.
855 return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) &&
856 Tok.isNot(tok::l_square) &&
857 // Tokens that can only be used as binary operators and a part of
858 // overloaded operator names.
859 Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) &&
860 Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) &&
861 Tok.isNot(tok::less) && Tok.isNot(tok::greater) &&
862 Tok.isNot(tok::slash) && Tok.isNot(tok::percent) &&
863 Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) &&
864 Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) &&
865 Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) &&
866 Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) &&
867 Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) &&
868 Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) &&
869 Tok.isNot(tok::lesslessequal) &&
870 // Colon is used in labels, base class lists, initializer lists,
871 // range-based for loops, ternary operator, but should never be the
872 // first token in an unwrapped line.
873 Tok.isNot(tok::colon) &&
874 // 'noexcept' is a trailing annotation.
875 Tok.isNot(tok::kw_noexcept);
878 static bool mustBeJSIdent(const AdditionalKeywords &Keywords,
879 const FormatToken *FormatTok) {
880 // FIXME: This returns true for C/C++ keywords like 'struct'.
881 return FormatTok->is(tok::identifier) &&
882 (FormatTok->Tok.getIdentifierInfo() == nullptr ||
884 Keywords.kw_in, Keywords.kw_of, Keywords.kw_as, Keywords.kw_async,
885 Keywords.kw_await, Keywords.kw_yield, Keywords.kw_finally,
886 Keywords.kw_function, Keywords.kw_import, Keywords.kw_is,
887 Keywords.kw_let, Keywords.kw_var, tok::kw_const,
888 Keywords.kw_abstract, Keywords.kw_extends, Keywords.kw_implements,
889 Keywords.kw_instanceof, Keywords.kw_interface, Keywords.kw_throws,
893 static bool mustBeJSIdentOrValue(const AdditionalKeywords &Keywords,
894 const FormatToken *FormatTok) {
895 return FormatTok->Tok.isLiteral() ||
896 FormatTok->isOneOf(tok::kw_true, tok::kw_false) ||
897 mustBeJSIdent(Keywords, FormatTok);
900 // isJSDeclOrStmt returns true if |FormatTok| starts a declaration or statement
901 // when encountered after a value (see mustBeJSIdentOrValue).
902 static bool isJSDeclOrStmt(const AdditionalKeywords &Keywords,
903 const FormatToken *FormatTok) {
904 return FormatTok->isOneOf(
905 tok::kw_return, Keywords.kw_yield,
907 tok::kw_if, tok::kw_else,
909 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
911 tok::kw_switch, tok::kw_case,
913 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.kw_finally,
915 tok::kw_const, tok::kw_class, Keywords.kw_var, Keywords.kw_let,
916 Keywords.kw_async, Keywords.kw_function,
918 Keywords.kw_import, tok::kw_export);
921 // readTokenWithJavaScriptASI reads the next token and terminates the current
922 // line if JavaScript Automatic Semicolon Insertion must
923 // happen between the current token and the next token.
925 // This method is conservative - it cannot cover all edge cases of JavaScript,
926 // but only aims to correctly handle certain well known cases. It *must not*
927 // return true in speculative cases.
928 void UnwrappedLineParser::readTokenWithJavaScriptASI() {
929 FormatToken *Previous = FormatTok;
931 FormatToken *Next = FormatTok;
934 CommentsBeforeNextToken.empty()
935 ? Next->NewlinesBefore == 0
936 : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
940 bool PreviousMustBeValue = mustBeJSIdentOrValue(Keywords, Previous);
941 bool PreviousStartsTemplateExpr =
942 Previous->is(TT_TemplateString) && Previous->TokenText.endswith("${");
943 if (PreviousMustBeValue || Previous->is(tok::r_paren)) {
944 // If the line contains an '@' sign, the previous token might be an
945 // annotation, which can precede another identifier/value.
946 bool HasAt = std::find_if(Line->Tokens.begin(), Line->Tokens.end(),
947 [](UnwrappedLineNode &LineNode) {
948 return LineNode.Tok->is(tok::at);
949 }) != Line->Tokens.end();
953 if (Next->is(tok::exclaim) && PreviousMustBeValue)
954 return addUnwrappedLine();
955 bool NextMustBeValue = mustBeJSIdentOrValue(Keywords, Next);
956 bool NextEndsTemplateExpr =
957 Next->is(TT_TemplateString) && Next->TokenText.startswith("}");
958 if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
959 (PreviousMustBeValue ||
960 Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
962 return addUnwrappedLine();
963 if ((PreviousMustBeValue || Previous->is(tok::r_paren)) &&
964 isJSDeclOrStmt(Keywords, Next))
965 return addUnwrappedLine();
968 void UnwrappedLineParser::parseStructuralElement() {
969 assert(!FormatTok->is(tok::l_brace));
970 if (Style.Language == FormatStyle::LK_TableGen &&
971 FormatTok->is(tok::pp_include)) {
973 if (FormatTok->is(tok::string_literal))
978 switch (FormatTok->Tok.getKind()) {
981 if (FormatTok->is(tok::l_brace)) {
982 FormatTok->Type = TT_InlineASMBrace;
984 while (FormatTok && FormatTok->isNot(tok::eof)) {
985 if (FormatTok->is(tok::r_brace)) {
986 FormatTok->Type = TT_InlineASMBrace;
991 FormatTok->Finalized = true;
996 case tok::kw_namespace:
1000 case tok::kw_protected:
1001 case tok::kw_private:
1002 if (Style.Language == FormatStyle::LK_Java ||
1003 Style.Language == FormatStyle::LK_JavaScript)
1006 parseAccessSpecifier();
1013 parseForOrWhileLoop();
1018 case tok::kw_switch:
1019 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1020 // 'switch: string' field declaration.
1024 case tok::kw_default:
1025 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1026 // 'default: string' field declaration.
1029 if (FormatTok->is(tok::colon)) {
1033 // e.g. "default void f() {}" in a Java interface.
1036 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1037 // 'case: string' field declaration.
1045 case tok::kw_extern:
1047 if (FormatTok->Tok.is(tok::string_literal)) {
1049 if (FormatTok->Tok.is(tok::l_brace)) {
1050 if (Style.BraceWrapping.AfterExternBlock) {
1052 parseBlock(/*MustBeDeclaration=*/true);
1054 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false);
1061 case tok::kw_export:
1062 if (Style.Language == FormatStyle::LK_JavaScript) {
1063 parseJavaScriptEs6ImportExport();
1068 // Handle C++ "(inline|export) namespace".
1070 case tok::kw_inline:
1072 if (FormatTok->Tok.is(tok::kw_namespace)) {
1077 case tok::identifier:
1078 if (FormatTok->is(TT_ForEachMacro)) {
1079 parseForOrWhileLoop();
1082 if (FormatTok->is(TT_MacroBlockBegin)) {
1083 parseBlock(/*MustBeDeclaration=*/false, /*AddLevel=*/true,
1084 /*MunchSemi=*/false);
1087 if (FormatTok->is(Keywords.kw_import)) {
1088 if (Style.Language == FormatStyle::LK_JavaScript) {
1089 parseJavaScriptEs6ImportExport();
1092 if (Style.Language == FormatStyle::LK_Proto) {
1094 if (FormatTok->is(tok::kw_public))
1096 if (!FormatTok->is(tok::string_literal))
1099 if (FormatTok->is(tok::semi))
1105 if (Style.isCpp() &&
1106 FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
1107 Keywords.kw_slots, Keywords.kw_qslots)) {
1109 if (FormatTok->is(tok::colon)) {
1115 if (Style.isCpp() && FormatTok->is(TT_StatementMacro)) {
1116 parseStatementMacro();
1119 // In all other cases, parse the declaration.
1125 const FormatToken *Previous = FormatTok->Previous;
1126 switch (FormatTok->Tok.getKind()) {
1129 if (FormatTok->Tok.is(tok::l_brace)) {
1133 } else if (Style.Language == FormatStyle::LK_Java &&
1134 FormatTok->is(Keywords.kw_interface)) {
1138 switch (FormatTok->Tok.getObjCKeywordID()) {
1139 case tok::objc_public:
1140 case tok::objc_protected:
1141 case tok::objc_package:
1142 case tok::objc_private:
1143 return parseAccessSpecifier();
1144 case tok::objc_interface:
1145 case tok::objc_implementation:
1146 return parseObjCInterfaceOrImplementation();
1147 case tok::objc_protocol:
1148 if (parseObjCProtocol())
1152 return; // Handled by the caller.
1153 case tok::objc_optional:
1154 case tok::objc_required:
1158 case tok::objc_autoreleasepool:
1160 if (FormatTok->Tok.is(tok::l_brace)) {
1161 if (Style.BraceWrapping.AfterControlStatement)
1163 parseBlock(/*MustBeDeclaration=*/false);
1167 case tok::objc_synchronized:
1169 if (FormatTok->Tok.is(tok::l_paren))
1170 // Skip synchronization object
1172 if (FormatTok->Tok.is(tok::l_brace)) {
1173 if (Style.BraceWrapping.AfterControlStatement)
1175 parseBlock(/*MustBeDeclaration=*/false);
1180 // This branch isn't strictly necessary (the kw_try case below would
1181 // do this too after the tok::at is parsed above). But be explicit.
1189 // Ignore if this is part of "template <enum ...".
1190 if (Previous && Previous->is(tok::less)) {
1195 // parseEnum falls through and does not yet add an unwrapped line as an
1196 // enum definition can start a structural element.
1199 // This only applies for C++.
1200 if (!Style.isCpp()) {
1205 case tok::kw_typedef:
1207 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1208 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS))
1211 case tok::kw_struct:
1214 // parseRecord falls through and does not yet add an unwrapped line as a
1215 // record declaration or definition can start a structural element.
1217 // This does not apply for Java and JavaScript.
1218 if (Style.Language == FormatStyle::LK_Java ||
1219 Style.Language == FormatStyle::LK_JavaScript) {
1220 if (FormatTok->is(tok::semi))
1228 // In Java, classes have an implicit static member "class".
1229 if (Style.Language == FormatStyle::LK_Java && FormatTok &&
1230 FormatTok->is(tok::kw_class))
1232 if (Style.Language == FormatStyle::LK_JavaScript && FormatTok &&
1233 FormatTok->Tok.getIdentifierInfo())
1234 // JavaScript only has pseudo keywords, all keywords are allowed to
1235 // appear in "IdentifierName" positions. See http://es5.github.io/#x7.6
1248 case tok::kw_operator:
1250 if (FormatTok->isBinaryOperator())
1255 if (FormatTok->Tok.isAnyIdentifier() ||
1256 FormatTok->isSimpleTypeSpecifier())
1258 if (FormatTok->is(tok::l_paren))
1260 if (FormatTok->is(tok::l_brace))
1264 if (!tryToParseBracedList()) {
1265 // A block outside of parentheses must be the last part of a
1266 // structural element.
1267 // FIXME: Figure out cases where this is not true, and add projections
1268 // for them (the one we know is missing are lambdas).
1269 if (Style.BraceWrapping.AfterFunction)
1271 FormatTok->Type = TT_FunctionLBrace;
1272 parseBlock(/*MustBeDeclaration=*/false);
1276 // Otherwise this was a braced init list, and the structural
1277 // element continues.
1280 // We arrive here when parsing function-try blocks.
1281 if (Style.BraceWrapping.AfterFunction)
1285 case tok::identifier: {
1286 if (FormatTok->is(TT_MacroBlockEnd)) {
1291 // Function declarations (as opposed to function expressions) are parsed
1292 // on their own unwrapped line by continuing this loop. Function
1293 // expressions (functions that are not on their own line) must not create
1294 // a new unwrapped line, so they are special cased below.
1295 size_t TokenCount = Line->Tokens.size();
1296 if (Style.Language == FormatStyle::LK_JavaScript &&
1297 FormatTok->is(Keywords.kw_function) &&
1298 (TokenCount > 1 || (TokenCount == 1 && !Line->Tokens.front().Tok->is(
1299 Keywords.kw_async)))) {
1300 tryToParseJSFunction();
1303 if ((Style.Language == FormatStyle::LK_JavaScript ||
1304 Style.Language == FormatStyle::LK_Java) &&
1305 FormatTok->is(Keywords.kw_interface)) {
1306 if (Style.Language == FormatStyle::LK_JavaScript) {
1307 // In JavaScript/TypeScript, "interface" can be used as a standalone
1308 // identifier, e.g. in `var interface = 1;`. If "interface" is
1309 // followed by another identifier, it is very like to be an actual
1310 // interface declaration.
1311 unsigned StoredPosition = Tokens->getPosition();
1312 FormatToken *Next = Tokens->getNextToken();
1313 FormatTok = Tokens->setPosition(StoredPosition);
1314 if (Next && !mustBeJSIdent(Keywords, Next)) {
1324 if (Style.isCpp() && FormatTok->is(TT_StatementMacro)) {
1325 parseStatementMacro();
1329 // See if the following token should start a new unwrapped line.
1330 StringRef Text = FormatTok->TokenText;
1332 if (Line->Tokens.size() == 1 &&
1333 // JS doesn't have macros, and within classes colons indicate fields,
1335 Style.Language != FormatStyle::LK_JavaScript) {
1336 if (FormatTok->Tok.is(tok::colon) && !Line->MustBeDeclaration) {
1337 Line->Tokens.begin()->Tok->MustBreakBefore = true;
1341 // Recognize function-like macro usages without trailing semicolon as
1342 // well as free-standing macros like Q_OBJECT.
1343 bool FunctionLike = FormatTok->is(tok::l_paren);
1347 bool FollowedByNewline =
1348 CommentsBeforeNextToken.empty()
1349 ? FormatTok->NewlinesBefore > 0
1350 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
1352 if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
1353 tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) {
1361 // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType
1362 // TT_JsFatArrow. The always start an expression or a child block if
1363 // followed by a curly.
1364 if (FormatTok->is(TT_JsFatArrow)) {
1366 if (FormatTok->is(tok::l_brace))
1372 if (FormatTok->Tok.is(tok::l_brace)) {
1375 } else if (Style.Language == FormatStyle::LK_Proto &&
1376 FormatTok->Tok.is(tok::less)) {
1378 parseBracedList(/*ContinueOnSemicolons=*/false,
1379 /*ClosingBraceKind=*/tok::greater);
1395 bool UnwrappedLineParser::tryToParseLambda() {
1396 if (!Style.isCpp()) {
1400 assert(FormatTok->is(tok::l_square));
1401 FormatToken &LSquare = *FormatTok;
1402 if (!tryToParseLambdaIntroducer())
1405 while (FormatTok->isNot(tok::l_brace)) {
1406 if (FormatTok->isSimpleTypeSpecifier()) {
1410 switch (FormatTok->Tok.getKind()) {
1422 case tok::identifier:
1423 case tok::numeric_constant:
1424 case tok::coloncolon:
1425 case tok::kw_mutable:
1429 FormatTok->Type = TT_LambdaArrow;
1436 LSquare.Type = TT_LambdaLSquare;
1441 bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
1442 const FormatToken *Previous = FormatTok->Previous;
1444 (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new,
1445 tok::kw_delete, tok::l_square) ||
1446 FormatTok->isCppStructuredBinding(Style) || Previous->closesScope() ||
1447 Previous->isSimpleTypeSpecifier())) {
1452 if (FormatTok->is(tok::l_square)) {
1455 parseSquare(/*LambdaIntroducer=*/true);
1459 void UnwrappedLineParser::tryToParseJSFunction() {
1460 assert(FormatTok->is(Keywords.kw_function) ||
1461 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function));
1462 if (FormatTok->is(Keywords.kw_async))
1464 // Consume "function".
1467 // Consume * (generator function). Treat it like C++'s overloaded operators.
1468 if (FormatTok->is(tok::star)) {
1469 FormatTok->Type = TT_OverloadedOperator;
1473 // Consume function name.
1474 if (FormatTok->is(tok::identifier))
1477 if (FormatTok->isNot(tok::l_paren))
1480 // Parse formal parameter list.
1483 if (FormatTok->is(tok::colon)) {
1484 // Parse a type definition.
1487 // Eat the type declaration. For braced inline object types, balance braces,
1488 // otherwise just parse until finding an l_brace for the function body.
1489 if (FormatTok->is(tok::l_brace))
1490 tryToParseBracedList();
1492 while (!FormatTok->isOneOf(tok::l_brace, tok::semi) && !eof())
1496 if (FormatTok->is(tok::semi))
1502 bool UnwrappedLineParser::tryToParseBracedList() {
1503 if (FormatTok->BlockKind == BK_Unknown)
1504 calculateBraceTypes();
1505 assert(FormatTok->BlockKind != BK_Unknown);
1506 if (FormatTok->BlockKind == BK_Block)
1513 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
1514 tok::TokenKind ClosingBraceKind) {
1515 bool HasError = false;
1517 // FIXME: Once we have an expression parser in the UnwrappedLineParser,
1518 // replace this by using parseAssigmentExpression() inside.
1520 if (Style.Language == FormatStyle::LK_JavaScript) {
1521 if (FormatTok->is(Keywords.kw_function) ||
1522 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) {
1523 tryToParseJSFunction();
1526 if (FormatTok->is(TT_JsFatArrow)) {
1528 // Fat arrows can be followed by simple expressions or by child blocks
1530 if (FormatTok->is(tok::l_brace)) {
1535 if (FormatTok->is(tok::l_brace)) {
1536 // Could be a method inside of a braced list `{a() { return 1; }}`.
1537 if (tryToParseBracedList())
1542 if (FormatTok->Tok.getKind() == ClosingBraceKind) {
1546 switch (FormatTok->Tok.getKind()) {
1549 if (FormatTok->is(tok::l_brace)) {
1558 // JavaScript can just have free standing methods and getters/setters in
1559 // object literals. Detect them by a "{" following ")".
1560 if (Style.Language == FormatStyle::LK_JavaScript) {
1561 if (FormatTok->is(tok::l_brace))
1567 // Assume there are no blocks inside a braced init list apart
1568 // from the ones we explicitly parse out (like lambdas).
1569 FormatTok->BlockKind = BK_BracedInit;
1574 if (Style.Language == FormatStyle::LK_Proto) {
1576 parseBracedList(/*ContinueOnSemicolons=*/false,
1577 /*ClosingBraceKind=*/tok::greater);
1583 // JavaScript (or more precisely TypeScript) can have semicolons in braced
1584 // lists (in so-called TypeMemberLists). Thus, the semicolon cannot be
1585 // used for error recovery if we have otherwise determined that this is
1587 if (Style.Language == FormatStyle::LK_JavaScript) {
1592 if (!ContinueOnSemicolons)
1607 void UnwrappedLineParser::parseParens() {
1608 assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected.");
1611 switch (FormatTok->Tok.getKind()) {
1614 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace))
1621 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1627 if (!tryToParseBracedList())
1632 if (FormatTok->Tok.is(tok::l_brace)) {
1638 if (Style.Language == FormatStyle::LK_JavaScript)
1639 parseRecord(/*ParseAsExpr=*/true);
1643 case tok::identifier:
1644 if (Style.Language == FormatStyle::LK_JavaScript &&
1645 (FormatTok->is(Keywords.kw_function) ||
1646 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)))
1647 tryToParseJSFunction();
1658 void UnwrappedLineParser::parseSquare(bool LambdaIntroducer) {
1659 if (!LambdaIntroducer) {
1660 assert(FormatTok->Tok.is(tok::l_square) && "'[' expected.");
1661 if (tryToParseLambda())
1665 switch (FormatTok->Tok.getKind()) {
1673 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1678 case tok::l_brace: {
1679 if (!tryToParseBracedList())
1685 if (FormatTok->Tok.is(tok::l_brace)) {
1697 void UnwrappedLineParser::parseIfThenElse() {
1698 assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected");
1700 if (FormatTok->Tok.is(tok::kw_constexpr))
1702 if (FormatTok->Tok.is(tok::l_paren))
1704 bool NeedsUnwrappedLine = false;
1705 if (FormatTok->Tok.is(tok::l_brace)) {
1706 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1707 parseBlock(/*MustBeDeclaration=*/false);
1708 if (Style.BraceWrapping.BeforeElse)
1711 NeedsUnwrappedLine = true;
1715 parseStructuralElement();
1718 if (FormatTok->Tok.is(tok::kw_else)) {
1720 if (FormatTok->Tok.is(tok::l_brace)) {
1721 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1722 parseBlock(/*MustBeDeclaration=*/false);
1724 } else if (FormatTok->Tok.is(tok::kw_if)) {
1729 parseStructuralElement();
1730 if (FormatTok->is(tok::eof))
1734 } else if (NeedsUnwrappedLine) {
1739 void UnwrappedLineParser::parseTryCatch() {
1740 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
1742 bool NeedsUnwrappedLine = false;
1743 if (FormatTok->is(tok::colon)) {
1744 // We are in a function try block, what comes is an initializer list.
1746 while (FormatTok->is(tok::identifier)) {
1748 if (FormatTok->is(tok::l_paren))
1750 if (FormatTok->is(tok::comma))
1754 // Parse try with resource.
1755 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
1758 if (FormatTok->is(tok::l_brace)) {
1759 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1760 parseBlock(/*MustBeDeclaration=*/false);
1761 if (Style.BraceWrapping.BeforeCatch) {
1764 NeedsUnwrappedLine = true;
1766 } else if (!FormatTok->is(tok::kw_catch)) {
1767 // The C++ standard requires a compound-statement after a try.
1768 // If there's none, we try to assume there's a structuralElement
1769 // and try to continue.
1772 parseStructuralElement();
1776 if (FormatTok->is(tok::at))
1778 if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
1779 tok::kw___finally) ||
1780 ((Style.Language == FormatStyle::LK_Java ||
1781 Style.Language == FormatStyle::LK_JavaScript) &&
1782 FormatTok->is(Keywords.kw_finally)) ||
1783 (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) ||
1784 FormatTok->Tok.isObjCAtKeyword(tok::objc_finally))))
1787 while (FormatTok->isNot(tok::l_brace)) {
1788 if (FormatTok->is(tok::l_paren)) {
1792 if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof))
1796 NeedsUnwrappedLine = false;
1797 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1798 parseBlock(/*MustBeDeclaration=*/false);
1799 if (Style.BraceWrapping.BeforeCatch)
1802 NeedsUnwrappedLine = true;
1804 if (NeedsUnwrappedLine)
1808 void UnwrappedLineParser::parseNamespace() {
1809 assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected");
1811 const FormatToken &InitialToken = *FormatTok;
1813 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon))
1815 if (FormatTok->Tok.is(tok::l_brace)) {
1816 if (ShouldBreakBeforeBrace(Style, InitialToken))
1819 bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All ||
1820 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
1821 DeclarationScopeStack.size() > 1);
1822 parseBlock(/*MustBeDeclaration=*/true, AddLevel);
1823 // Munch the semicolon after a namespace. This is more common than one would
1824 // think. Puttin the semicolon into its own line is very ugly.
1825 if (FormatTok->Tok.is(tok::semi))
1829 // FIXME: Add error handling.
1832 void UnwrappedLineParser::parseNew() {
1833 assert(FormatTok->is(tok::kw_new) && "'new' expected");
1835 if (Style.Language != FormatStyle::LK_Java)
1838 // In Java, we can parse everything up to the parens, which aren't optional.
1840 // There should not be a ;, { or } before the new's open paren.
1841 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
1844 // Consume the parens.
1845 if (FormatTok->is(tok::l_paren)) {
1848 // If there is a class body of an anonymous class, consume that as child.
1849 if (FormatTok->is(tok::l_brace))
1857 void UnwrappedLineParser::parseForOrWhileLoop() {
1858 assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
1859 "'for', 'while' or foreach macro expected");
1861 // JS' for await ( ...
1862 if (Style.Language == FormatStyle::LK_JavaScript &&
1863 FormatTok->is(Keywords.kw_await))
1865 if (FormatTok->Tok.is(tok::l_paren))
1867 if (FormatTok->Tok.is(tok::l_brace)) {
1868 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1869 parseBlock(/*MustBeDeclaration=*/false);
1874 parseStructuralElement();
1879 void UnwrappedLineParser::parseDoWhile() {
1880 assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
1882 if (FormatTok->Tok.is(tok::l_brace)) {
1883 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1884 parseBlock(/*MustBeDeclaration=*/false);
1885 if (Style.BraceWrapping.IndentBraces)
1890 parseStructuralElement();
1894 // FIXME: Add error handling.
1895 if (!FormatTok->Tok.is(tok::kw_while)) {
1901 parseStructuralElement();
1904 void UnwrappedLineParser::parseLabel() {
1906 unsigned OldLineLevel = Line->Level;
1907 if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
1909 if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) {
1910 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1911 parseBlock(/*MustBeDeclaration=*/false);
1912 if (FormatTok->Tok.is(tok::kw_break)) {
1913 if (Style.BraceWrapping.AfterControlStatement)
1915 parseStructuralElement();
1919 if (FormatTok->is(tok::semi))
1923 Line->Level = OldLineLevel;
1924 if (FormatTok->isNot(tok::l_brace)) {
1925 parseStructuralElement();
1930 void UnwrappedLineParser::parseCaseLabel() {
1931 assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
1932 // FIXME: fix handling of complex expressions here.
1935 } while (!eof() && !FormatTok->Tok.is(tok::colon));
1939 void UnwrappedLineParser::parseSwitch() {
1940 assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
1942 if (FormatTok->Tok.is(tok::l_paren))
1944 if (FormatTok->Tok.is(tok::l_brace)) {
1945 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1946 parseBlock(/*MustBeDeclaration=*/false);
1951 parseStructuralElement();
1956 void UnwrappedLineParser::parseAccessSpecifier() {
1958 // Understand Qt's slots.
1959 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
1961 // Otherwise, we don't know what it is, and we'd better keep the next token.
1962 if (FormatTok->Tok.is(tok::colon))
1967 bool UnwrappedLineParser::parseEnum() {
1968 // Won't be 'enum' for NS_ENUMs.
1969 if (FormatTok->Tok.is(tok::kw_enum))
1972 // In TypeScript, "enum" can also be used as property name, e.g. in interface
1973 // declarations. An "enum" keyword followed by a colon would be a syntax
1974 // error and thus assume it is just an identifier.
1975 if (Style.Language == FormatStyle::LK_JavaScript &&
1976 FormatTok->isOneOf(tok::colon, tok::question))
1979 // Eat up enum class ...
1980 if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct))
1983 while (FormatTok->Tok.getIdentifierInfo() ||
1984 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
1985 tok::greater, tok::comma, tok::question)) {
1987 // We can have macros or attributes in between 'enum' and the enum name.
1988 if (FormatTok->is(tok::l_paren))
1990 if (FormatTok->is(tok::identifier)) {
1992 // If there are two identifiers in a row, this is likely an elaborate
1993 // return type. In Java, this can be "implements", etc.
1994 if (Style.isCpp() && FormatTok->is(tok::identifier))
1999 // Just a declaration or something is wrong.
2000 if (FormatTok->isNot(tok::l_brace))
2002 FormatTok->BlockKind = BK_Block;
2004 if (Style.Language == FormatStyle::LK_Java) {
2005 // Java enums are different.
2006 parseJavaEnumBody();
2009 if (Style.Language == FormatStyle::LK_Proto) {
2010 parseBlock(/*MustBeDeclaration=*/true);
2016 bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true);
2018 if (FormatTok->is(tok::semi))
2024 // There is no addUnwrappedLine() here so that we fall through to parsing a
2025 // structural element afterwards. Thus, in "enum A {} n, m;",
2026 // "} n, m;" will end up in one unwrapped line.
2029 void UnwrappedLineParser::parseJavaEnumBody() {
2030 // Determine whether the enum is simple, i.e. does not have a semicolon or
2031 // constants with class bodies. Simple enums can be formatted like braced
2032 // lists, contracted to a single line, etc.
2033 unsigned StoredPosition = Tokens->getPosition();
2034 bool IsSimple = true;
2035 FormatToken *Tok = Tokens->getNextToken();
2037 if (Tok->is(tok::r_brace))
2039 if (Tok->isOneOf(tok::l_brace, tok::semi)) {
2043 // FIXME: This will also mark enums with braces in the arguments to enum
2044 // constants as "not simple". This is probably fine in practice, though.
2045 Tok = Tokens->getNextToken();
2047 FormatTok = Tokens->setPosition(StoredPosition);
2056 // Parse the body of a more complex enum.
2057 // First add a line for everything up to the "{".
2062 // Parse the enum constants.
2064 if (FormatTok->is(tok::l_brace)) {
2065 // Parse the constant's class body.
2066 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
2067 /*MunchSemi=*/false);
2068 } else if (FormatTok->is(tok::l_paren)) {
2070 } else if (FormatTok->is(tok::comma)) {
2073 } else if (FormatTok->is(tok::semi)) {
2077 } else if (FormatTok->is(tok::r_brace)) {
2085 // Parse the class body after the enum's ";" if any.
2086 parseLevel(/*HasOpeningBrace=*/true);
2092 void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
2093 const FormatToken &InitialToken = *FormatTok;
2096 // The actual identifier can be a nested name specifier, and in macros
2097 // it is often token-pasted.
2098 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
2099 tok::kw___attribute, tok::kw___declspec,
2101 ((Style.Language == FormatStyle::LK_Java ||
2102 Style.Language == FormatStyle::LK_JavaScript) &&
2103 FormatTok->isOneOf(tok::period, tok::comma))) {
2104 if (Style.Language == FormatStyle::LK_JavaScript &&
2105 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
2106 // JavaScript/TypeScript supports inline object types in
2107 // extends/implements positions:
2108 // class Foo implements {bar: number} { }
2110 if (FormatTok->is(tok::l_brace)) {
2111 tryToParseBracedList();
2115 bool IsNonMacroIdentifier =
2116 FormatTok->is(tok::identifier) &&
2117 FormatTok->TokenText != FormatTok->TokenText.upper();
2119 // We can have macros or attributes in between 'class' and the class name.
2120 if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren))
2124 // Note that parsing away template declarations here leads to incorrectly
2125 // accepting function declarations as record declarations.
2126 // In general, we cannot solve this problem. Consider:
2127 // class A<int> B() {}
2128 // which can be a function definition or a class definition when B() is a
2129 // macro. If we find enough real-world cases where this is a problem, we
2130 // can parse for the 'template' keyword in the beginning of the statement,
2131 // and thus rule out the record production in case there is no template
2132 // (this would still leave us with an ambiguity between template function
2133 // and class declarations).
2134 if (FormatTok->isOneOf(tok::colon, tok::less)) {
2136 if (FormatTok->is(tok::l_brace)) {
2137 calculateBraceTypes(/*ExpectClassBody=*/true);
2138 if (!tryToParseBracedList())
2141 if (FormatTok->Tok.is(tok::semi))
2146 if (FormatTok->Tok.is(tok::l_brace)) {
2150 if (ShouldBreakBeforeBrace(Style, InitialToken))
2153 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
2154 /*MunchSemi=*/false);
2157 // There is no addUnwrappedLine() here so that we fall through to parsing a
2158 // structural element afterwards. Thus, in "class A {} n, m;",
2159 // "} n, m;" will end up in one unwrapped line.
2162 void UnwrappedLineParser::parseObjCMethod() {
2163 assert(FormatTok->Tok.isOneOf(tok::l_paren, tok::identifier) &&
2164 "'(' or identifier expected.");
2166 if (FormatTok->Tok.is(tok::semi)) {
2170 } else if (FormatTok->Tok.is(tok::l_brace)) {
2171 if (Style.BraceWrapping.AfterFunction)
2173 parseBlock(/*MustBeDeclaration=*/false);
2182 void UnwrappedLineParser::parseObjCProtocolList() {
2183 assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
2186 // Early exit in case someone forgot a close angle.
2187 if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
2188 FormatTok->Tok.isObjCAtKeyword(tok::objc_end))
2190 } while (!eof() && FormatTok->Tok.isNot(tok::greater));
2191 nextToken(); // Skip '>'.
2194 void UnwrappedLineParser::parseObjCUntilAtEnd() {
2196 if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
2201 if (FormatTok->is(tok::l_brace)) {
2202 parseBlock(/*MustBeDeclaration=*/false);
2203 // In ObjC interfaces, nothing should be following the "}".
2205 } else if (FormatTok->is(tok::r_brace)) {
2206 // Ignore stray "}". parseStructuralElement doesn't consume them.
2209 } else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
2213 parseStructuralElement();
2218 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
2219 assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_interface ||
2220 FormatTok->Tok.getObjCKeywordID() == tok::objc_implementation);
2222 nextToken(); // interface name
2224 // @interface can be followed by a lightweight generic
2225 // specialization list, then either a base class or a category.
2226 if (FormatTok->Tok.is(tok::less)) {
2227 // Unlike protocol lists, generic parameterizations support
2230 // @interface Foo<ValueType : id <NSCopying, NSSecureCoding>> :
2231 // NSObject <NSCopying, NSSecureCoding>
2233 // so we need to count how many open angles we have left.
2234 unsigned NumOpenAngles = 1;
2237 // Early exit in case someone forgot a close angle.
2238 if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
2239 FormatTok->Tok.isObjCAtKeyword(tok::objc_end))
2241 if (FormatTok->Tok.is(tok::less))
2243 else if (FormatTok->Tok.is(tok::greater)) {
2244 assert(NumOpenAngles > 0 && "'>' makes NumOpenAngles negative");
2247 } while (!eof() && NumOpenAngles != 0);
2248 nextToken(); // Skip '>'.
2250 if (FormatTok->Tok.is(tok::colon)) {
2252 nextToken(); // base class name
2253 } else if (FormatTok->Tok.is(tok::l_paren))
2254 // Skip category, if present.
2257 if (FormatTok->Tok.is(tok::less))
2258 parseObjCProtocolList();
2260 if (FormatTok->Tok.is(tok::l_brace)) {
2261 if (Style.BraceWrapping.AfterObjCDeclaration)
2263 parseBlock(/*MustBeDeclaration=*/true);
2266 // With instance variables, this puts '}' on its own line. Without instance
2267 // variables, this ends the @interface line.
2270 parseObjCUntilAtEnd();
2273 // Returns true for the declaration/definition form of @protocol,
2274 // false for the expression form.
2275 bool UnwrappedLineParser::parseObjCProtocol() {
2276 assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_protocol);
2279 if (FormatTok->is(tok::l_paren))
2280 // The expression form of @protocol, e.g. "Protocol* p = @protocol(foo);".
2283 // The definition/declaration form,
2285 // - (int)someMethod;
2288 nextToken(); // protocol name
2290 if (FormatTok->Tok.is(tok::less))
2291 parseObjCProtocolList();
2293 // Check for protocol declaration.
2294 if (FormatTok->Tok.is(tok::semi)) {
2301 parseObjCUntilAtEnd();
2305 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
2306 bool IsImport = FormatTok->is(Keywords.kw_import);
2307 assert(IsImport || FormatTok->is(tok::kw_export));
2310 // Consume the "default" in "export default class/function".
2311 if (FormatTok->is(tok::kw_default))
2314 // Consume "async function", "function" and "default function", so that these
2315 // get parsed as free-standing JS functions, i.e. do not require a trailing
2317 if (FormatTok->is(Keywords.kw_async))
2319 if (FormatTok->is(Keywords.kw_function)) {
2324 // For imports, `export *`, `export {...}`, consume the rest of the line up
2325 // to the terminating `;`. For everything else, just return and continue
2326 // parsing the structural element, i.e. the declaration or expression for
2327 // `export default`.
2328 if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) &&
2329 !FormatTok->isStringLiteral())
2333 if (FormatTok->is(tok::semi))
2335 if (Line->Tokens.empty()) {
2336 // Common issue: Automatic Semicolon Insertion wrapped the line, so the
2337 // import statement should terminate.
2340 if (FormatTok->is(tok::l_brace)) {
2341 FormatTok->BlockKind = BK_Block;
2350 void UnwrappedLineParser::parseStatementMacro()
2353 if (FormatTok->is(tok::l_paren))
2355 if (FormatTok->is(tok::semi))
2360 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
2361 StringRef Prefix = "") {
2362 llvm::dbgs() << Prefix << "Line(" << Line.Level
2363 << ", FSC=" << Line.FirstStartColumn << ")"
2364 << (Line.InPPDirective ? " MACRO" : "") << ": ";
2365 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2366 E = Line.Tokens.end();
2368 llvm::dbgs() << I->Tok->Tok.getName() << "["
2369 << "T=" << I->Tok->Type << ", OC=" << I->Tok->OriginalColumn
2372 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2373 E = Line.Tokens.end();
2375 const UnwrappedLineNode &Node = *I;
2376 for (SmallVectorImpl<UnwrappedLine>::const_iterator
2377 I = Node.Children.begin(),
2378 E = Node.Children.end();
2380 printDebugInfo(*I, "\nChild: ");
2383 llvm::dbgs() << "\n";
2386 void UnwrappedLineParser::addUnwrappedLine() {
2387 if (Line->Tokens.empty())
2390 if (CurrentLines == &Lines)
2391 printDebugInfo(*Line);
2393 CurrentLines->push_back(std::move(*Line));
2394 Line->Tokens.clear();
2395 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
2396 Line->FirstStartColumn = 0;
2397 if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
2398 CurrentLines->append(
2399 std::make_move_iterator(PreprocessorDirectives.begin()),
2400 std::make_move_iterator(PreprocessorDirectives.end()));
2401 PreprocessorDirectives.clear();
2403 // Disconnect the current token from the last token on the previous line.
2404 FormatTok->Previous = nullptr;
2407 bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
2409 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
2410 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
2411 FormatTok.NewlinesBefore > 0;
2414 // Checks if \p FormatTok is a line comment that continues the line comment
2415 // section on \p Line.
2416 static bool continuesLineCommentSection(const FormatToken &FormatTok,
2417 const UnwrappedLine &Line,
2418 llvm::Regex &CommentPragmasRegex) {
2419 if (Line.Tokens.empty())
2422 StringRef IndentContent = FormatTok.TokenText;
2423 if (FormatTok.TokenText.startswith("//") ||
2424 FormatTok.TokenText.startswith("/*"))
2425 IndentContent = FormatTok.TokenText.substr(2);
2426 if (CommentPragmasRegex.match(IndentContent))
2429 // If Line starts with a line comment, then FormatTok continues the comment
2430 // section if its original column is greater or equal to the original start
2431 // column of the line.
2433 // Define the min column token of a line as follows: if a line ends in '{' or
2434 // contains a '{' followed by a line comment, then the min column token is
2435 // that '{'. Otherwise, the min column token of the line is the first token of
2438 // If Line starts with a token other than a line comment, then FormatTok
2439 // continues the comment section if its original column is greater than the
2440 // original start column of the min column token of the line.
2442 // For example, the second line comment continues the first in these cases:
2454 // int i; // first line
2459 // do { // first line
2472 // The second line comment doesn't continue the first in these cases:
2479 // int i; // first line
2484 // do { // first line
2495 const FormatToken *MinColumnToken = Line.Tokens.front().Tok;
2497 // Scan for '{//'. If found, use the column of '{' as a min column for line
2498 // comment section continuation.
2499 const FormatToken *PreviousToken = nullptr;
2500 for (const UnwrappedLineNode &Node : Line.Tokens) {
2501 if (PreviousToken && PreviousToken->is(tok::l_brace) &&
2502 isLineComment(*Node.Tok)) {
2503 MinColumnToken = PreviousToken;
2506 PreviousToken = Node.Tok;
2508 // Grab the last newline preceding a token in this unwrapped line.
2509 if (Node.Tok->NewlinesBefore > 0) {
2510 MinColumnToken = Node.Tok;
2513 if (PreviousToken && PreviousToken->is(tok::l_brace)) {
2514 MinColumnToken = PreviousToken;
2517 return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok,
2521 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
2522 bool JustComments = Line->Tokens.empty();
2523 for (SmallVectorImpl<FormatToken *>::const_iterator
2524 I = CommentsBeforeNextToken.begin(),
2525 E = CommentsBeforeNextToken.end();
2527 // Line comments that belong to the same line comment section are put on the
2528 // same line since later we might want to reflow content between them.
2529 // Additional fine-grained breaking of line comment sections is controlled
2530 // by the class BreakableLineCommentSection in case it is desirable to keep
2531 // several line comment sections in the same unwrapped line.
2533 // FIXME: Consider putting separate line comment sections as children to the
2534 // unwrapped line instead.
2535 (*I)->ContinuesLineCommentSection =
2536 continuesLineCommentSection(**I, *Line, CommentPragmasRegex);
2537 if (isOnNewLine(**I) && JustComments && !(*I)->ContinuesLineCommentSection)
2541 if (NewlineBeforeNext && JustComments)
2543 CommentsBeforeNextToken.clear();
2546 void UnwrappedLineParser::nextToken(int LevelDifference) {
2549 flushComments(isOnNewLine(*FormatTok));
2550 pushToken(FormatTok);
2551 FormatToken *Previous = FormatTok;
2552 if (Style.Language != FormatStyle::LK_JavaScript)
2553 readToken(LevelDifference);
2555 readTokenWithJavaScriptASI();
2556 FormatTok->Previous = Previous;
2559 void UnwrappedLineParser::distributeComments(
2560 const SmallVectorImpl<FormatToken *> &Comments,
2561 const FormatToken *NextTok) {
2562 // Whether or not a line comment token continues a line is controlled by
2563 // the method continuesLineCommentSection, with the following caveat:
2565 // Define a trail of Comments to be a nonempty proper postfix of Comments such
2566 // that each comment line from the trail is aligned with the next token, if
2567 // the next token exists. If a trail exists, the beginning of the maximal
2568 // trail is marked as a start of a new comment section.
2570 // For example in this code:
2572 // int a; // line about a
2573 // // line 1 about b
2574 // // line 2 about b
2577 // the two lines about b form a maximal trail, so there are two sections, the
2578 // first one consisting of the single comment "// line about a" and the
2579 // second one consisting of the next two comments.
2580 if (Comments.empty())
2582 bool ShouldPushCommentsInCurrentLine = true;
2583 bool HasTrailAlignedWithNextToken = false;
2584 unsigned StartOfTrailAlignedWithNextToken = 0;
2586 // We are skipping the first element intentionally.
2587 for (unsigned i = Comments.size() - 1; i > 0; --i) {
2588 if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) {
2589 HasTrailAlignedWithNextToken = true;
2590 StartOfTrailAlignedWithNextToken = i;
2594 for (unsigned i = 0, e = Comments.size(); i < e; ++i) {
2595 FormatToken *FormatTok = Comments[i];
2596 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
2597 FormatTok->ContinuesLineCommentSection = false;
2599 FormatTok->ContinuesLineCommentSection =
2600 continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex);
2602 if (!FormatTok->ContinuesLineCommentSection &&
2603 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
2604 ShouldPushCommentsInCurrentLine = false;
2606 if (ShouldPushCommentsInCurrentLine) {
2607 pushToken(FormatTok);
2609 CommentsBeforeNextToken.push_back(FormatTok);
2614 void UnwrappedLineParser::readToken(int LevelDifference) {
2615 SmallVector<FormatToken *, 1> Comments;
2617 FormatTok = Tokens->getNextToken();
2619 while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
2620 (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
2621 distributeComments(Comments, FormatTok);
2623 // If there is an unfinished unwrapped line, we flush the preprocessor
2624 // directives only after that unwrapped line was finished later.
2625 bool SwitchToPreprocessorLines = !Line->Tokens.empty();
2626 ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
2627 assert((LevelDifference >= 0 ||
2628 static_cast<unsigned>(-LevelDifference) <= Line->Level) &&
2629 "LevelDifference makes Line->Level negative");
2630 Line->Level += LevelDifference;
2631 // Comments stored before the preprocessor directive need to be output
2632 // before the preprocessor directive, at the same level as the
2633 // preprocessor directive, as we consider them to apply to the directive.
2634 flushComments(isOnNewLine(*FormatTok));
2637 while (FormatTok->Type == TT_ConflictStart ||
2638 FormatTok->Type == TT_ConflictEnd ||
2639 FormatTok->Type == TT_ConflictAlternative) {
2640 if (FormatTok->Type == TT_ConflictStart) {
2641 conditionalCompilationStart(/*Unreachable=*/false);
2642 } else if (FormatTok->Type == TT_ConflictAlternative) {
2643 conditionalCompilationAlternative();
2644 } else if (FormatTok->Type == TT_ConflictEnd) {
2645 conditionalCompilationEnd();
2647 FormatTok = Tokens->getNextToken();
2648 FormatTok->MustBreakBefore = true;
2651 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
2652 !Line->InPPDirective) {
2656 if (!FormatTok->Tok.is(tok::comment)) {
2657 distributeComments(Comments, FormatTok);
2662 Comments.push_back(FormatTok);
2665 distributeComments(Comments, nullptr);
2669 void UnwrappedLineParser::pushToken(FormatToken *Tok) {
2670 Line->Tokens.push_back(UnwrappedLineNode(Tok));
2671 if (MustBreakBeforeNextToken) {
2672 Line->Tokens.back().Tok->MustBreakBefore = true;
2673 MustBreakBeforeNextToken = false;
2677 } // end namespace format
2678 } // end namespace clang