1 //===--- UnwrappedLineParser.cpp - Format C++ code ------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 /// This file contains the implementation of the UnwrappedLineParser,
11 /// which turns a stream of tokens into UnwrappedLines.
13 //===----------------------------------------------------------------------===//
15 #include "UnwrappedLineParser.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/raw_ostream.h"
22 #define DEBUG_TYPE "format-parser"
27 class FormatTokenSource {
29 virtual ~FormatTokenSource() {}
30 virtual FormatToken *getNextToken() = 0;
32 virtual unsigned getPosition() = 0;
33 virtual FormatToken *setPosition(unsigned Position) = 0;
38 class ScopedDeclarationState {
40 ScopedDeclarationState(UnwrappedLine &Line, std::vector<bool> &Stack,
41 bool MustBeDeclaration)
42 : Line(Line), Stack(Stack) {
43 Line.MustBeDeclaration = MustBeDeclaration;
44 Stack.push_back(MustBeDeclaration);
46 ~ScopedDeclarationState() {
49 Line.MustBeDeclaration = Stack.back();
51 Line.MustBeDeclaration = true;
56 std::vector<bool> &Stack;
59 static bool isLineComment(const FormatToken &FormatTok) {
60 return FormatTok.is(tok::comment) && !FormatTok.TokenText.startswith("/*");
63 // Checks if \p FormatTok is a line comment that continues the line comment
64 // \p Previous. The original column of \p MinColumnToken is used to determine
65 // whether \p FormatTok is indented enough to the right to continue \p Previous.
66 static bool continuesLineComment(const FormatToken &FormatTok,
67 const FormatToken *Previous,
68 const FormatToken *MinColumnToken) {
69 if (!Previous || !MinColumnToken)
71 unsigned MinContinueColumn =
72 MinColumnToken->OriginalColumn + (isLineComment(*MinColumnToken) ? 0 : 1);
73 return isLineComment(FormatTok) && FormatTok.NewlinesBefore == 1 &&
74 isLineComment(*Previous) &&
75 FormatTok.OriginalColumn >= MinContinueColumn;
78 class ScopedMacroState : public FormatTokenSource {
80 ScopedMacroState(UnwrappedLine &Line, FormatTokenSource *&TokenSource,
81 FormatToken *&ResetToken)
82 : Line(Line), TokenSource(TokenSource), ResetToken(ResetToken),
83 PreviousLineLevel(Line.Level), PreviousTokenSource(TokenSource),
84 Token(nullptr), PreviousToken(nullptr) {
85 FakeEOF.Tok.startToken();
86 FakeEOF.Tok.setKind(tok::eof);
89 Line.InPPDirective = true;
92 ~ScopedMacroState() override {
93 TokenSource = PreviousTokenSource;
95 Line.InPPDirective = false;
96 Line.Level = PreviousLineLevel;
99 FormatToken *getNextToken() override {
100 // The \c UnwrappedLineParser guards against this by never calling
101 // \c getNextToken() after it has encountered the first eof token.
103 PreviousToken = Token;
104 Token = PreviousTokenSource->getNextToken();
110 unsigned getPosition() override { return PreviousTokenSource->getPosition(); }
112 FormatToken *setPosition(unsigned Position) override {
113 PreviousToken = nullptr;
114 Token = PreviousTokenSource->setPosition(Position);
120 return Token && Token->HasUnescapedNewline &&
121 !continuesLineComment(*Token, PreviousToken,
122 /*MinColumnToken=*/PreviousToken);
127 FormatTokenSource *&TokenSource;
128 FormatToken *&ResetToken;
129 unsigned PreviousLineLevel;
130 FormatTokenSource *PreviousTokenSource;
133 FormatToken *PreviousToken;
136 } // end anonymous namespace
138 class ScopedLineState {
140 ScopedLineState(UnwrappedLineParser &Parser,
141 bool SwitchToPreprocessorLines = false)
142 : Parser(Parser), OriginalLines(Parser.CurrentLines) {
143 if (SwitchToPreprocessorLines)
144 Parser.CurrentLines = &Parser.PreprocessorDirectives;
145 else if (!Parser.Line->Tokens.empty())
146 Parser.CurrentLines = &Parser.Line->Tokens.back().Children;
147 PreBlockLine = std::move(Parser.Line);
148 Parser.Line = std::make_unique<UnwrappedLine>();
149 Parser.Line->Level = PreBlockLine->Level;
150 Parser.Line->InPPDirective = PreBlockLine->InPPDirective;
154 if (!Parser.Line->Tokens.empty()) {
155 Parser.addUnwrappedLine();
157 assert(Parser.Line->Tokens.empty());
158 Parser.Line = std::move(PreBlockLine);
159 if (Parser.CurrentLines == &Parser.PreprocessorDirectives)
160 Parser.MustBreakBeforeNextToken = true;
161 Parser.CurrentLines = OriginalLines;
165 UnwrappedLineParser &Parser;
167 std::unique_ptr<UnwrappedLine> PreBlockLine;
168 SmallVectorImpl<UnwrappedLine> *OriginalLines;
171 class CompoundStatementIndenter {
173 CompoundStatementIndenter(UnwrappedLineParser *Parser,
174 const FormatStyle &Style, unsigned &LineLevel)
175 : CompoundStatementIndenter(Parser, LineLevel,
176 Style.BraceWrapping.AfterControlStatement,
177 Style.BraceWrapping.IndentBraces) {}
178 CompoundStatementIndenter(UnwrappedLineParser *Parser, unsigned &LineLevel,
179 bool WrapBrace, bool IndentBrace)
180 : LineLevel(LineLevel), OldLineLevel(LineLevel) {
182 Parser->addUnwrappedLine();
186 ~CompoundStatementIndenter() { LineLevel = OldLineLevel; }
190 unsigned OldLineLevel;
195 class IndexedTokenSource : public FormatTokenSource {
197 IndexedTokenSource(ArrayRef<FormatToken *> Tokens)
198 : Tokens(Tokens), Position(-1) {}
200 FormatToken *getNextToken() override {
202 return Tokens[Position];
205 unsigned getPosition() override {
206 assert(Position >= 0);
210 FormatToken *setPosition(unsigned P) override {
212 return Tokens[Position];
215 void reset() { Position = -1; }
218 ArrayRef<FormatToken *> Tokens;
222 } // end anonymous namespace
224 UnwrappedLineParser::UnwrappedLineParser(const FormatStyle &Style,
225 const AdditionalKeywords &Keywords,
226 unsigned FirstStartColumn,
227 ArrayRef<FormatToken *> Tokens,
228 UnwrappedLineConsumer &Callback)
229 : Line(new UnwrappedLine), MustBreakBeforeNextToken(false),
230 CurrentLines(&Lines), Style(Style), Keywords(Keywords),
231 CommentPragmasRegex(Style.CommentPragmas), Tokens(nullptr),
232 Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1),
233 IncludeGuard(Style.IndentPPDirectives == FormatStyle::PPDIS_None
236 IncludeGuardToken(nullptr), FirstStartColumn(FirstStartColumn) {}
238 void UnwrappedLineParser::reset() {
240 IncludeGuard = Style.IndentPPDirectives == FormatStyle::PPDIS_None
243 IncludeGuardToken = nullptr;
244 Line.reset(new UnwrappedLine);
245 CommentsBeforeNextToken.clear();
247 MustBreakBeforeNextToken = false;
248 PreprocessorDirectives.clear();
249 CurrentLines = &Lines;
250 DeclarationScopeStack.clear();
252 Line->FirstStartColumn = FirstStartColumn;
255 void UnwrappedLineParser::parse() {
256 IndexedTokenSource TokenSource(AllTokens);
257 Line->FirstStartColumn = FirstStartColumn;
259 LLVM_DEBUG(llvm::dbgs() << "----\n");
261 Tokens = &TokenSource;
267 // If we found an include guard then all preprocessor directives (other than
268 // the guard) are over-indented by one.
269 if (IncludeGuard == IG_Found)
270 for (auto &Line : Lines)
271 if (Line.InPPDirective && Line.Level > 0)
274 // Create line with eof token.
275 pushToken(FormatTok);
278 for (SmallVectorImpl<UnwrappedLine>::iterator I = Lines.begin(),
281 Callback.consumeUnwrappedLine(*I);
283 Callback.finishRun();
285 while (!PPLevelBranchIndex.empty() &&
286 PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) {
287 PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1);
288 PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1);
290 if (!PPLevelBranchIndex.empty()) {
291 ++PPLevelBranchIndex.back();
292 assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size());
293 assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back());
295 } while (!PPLevelBranchIndex.empty());
298 void UnwrappedLineParser::parseFile() {
299 // The top-level context in a file always has declarations, except for pre-
300 // processor directives and JavaScript files.
301 bool MustBeDeclaration =
302 !Line->InPPDirective && Style.Language != FormatStyle::LK_JavaScript;
303 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
305 if (Style.Language == FormatStyle::LK_TextProto)
308 parseLevel(/*HasOpeningBrace=*/false);
309 // Make sure to format the remaining tokens.
311 // LK_TextProto is special since its top-level is parsed as the body of a
312 // braced list, which does not necessarily have natural line separators such
313 // as a semicolon. Comments after the last entry that have been determined to
314 // not belong to that line, as in:
316 // // endfile comment
317 // do not have a chance to be put on a line of their own until this point.
318 // Here we add this newline before end-of-file comments.
319 if (Style.Language == FormatStyle::LK_TextProto &&
320 !CommentsBeforeNextToken.empty())
326 void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) {
327 bool SwitchLabelEncountered = false;
329 tok::TokenKind kind = FormatTok->Tok.getKind();
330 if (FormatTok->Type == TT_MacroBlockBegin) {
332 } else if (FormatTok->Type == TT_MacroBlockEnd) {
342 // FIXME: Add parameter whether this can happen - if this happens, we must
343 // be in a non-declaration context.
344 if (!FormatTok->is(TT_MacroBlockBegin) && tryToParseBracedList())
346 parseBlock(/*MustBeDeclaration=*/false);
355 case tok::kw_default: {
356 unsigned StoredPosition = Tokens->getPosition();
359 Next = Tokens->getNextToken();
360 } while (Next && Next->is(tok::comment));
361 FormatTok = Tokens->setPosition(StoredPosition);
362 if (Next && Next->isNot(tok::colon)) {
363 // default not followed by ':' is not a case label; treat it like
365 parseStructuralElement();
368 // Else, if it is 'default:', fall through to the case handling.
372 if (Style.Language == FormatStyle::LK_JavaScript &&
373 Line->MustBeDeclaration) {
374 // A 'case: string' style field declaration.
375 parseStructuralElement();
378 if (!SwitchLabelEncountered &&
379 (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1)))
381 SwitchLabelEncountered = true;
382 parseStructuralElement();
385 parseStructuralElement();
391 void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) {
392 // We'll parse forward through the tokens until we hit
393 // a closing brace or eof - note that getNextToken() will
394 // parse macros, so this will magically work inside macro
396 unsigned StoredPosition = Tokens->getPosition();
397 FormatToken *Tok = FormatTok;
398 const FormatToken *PrevTok = Tok->Previous;
399 // Keep a stack of positions of lbrace tokens. We will
400 // update information about whether an lbrace starts a
401 // braced init list or a different block during the loop.
402 SmallVector<FormatToken *, 8> LBraceStack;
403 assert(Tok->Tok.is(tok::l_brace));
405 // Get next non-comment token.
406 FormatToken *NextTok;
407 unsigned ReadTokens = 0;
409 NextTok = Tokens->getNextToken();
411 } while (NextTok->is(tok::comment));
413 switch (Tok->Tok.getKind()) {
415 if (Style.Language == FormatStyle::LK_JavaScript && PrevTok) {
416 if (PrevTok->isOneOf(tok::colon, tok::less))
417 // A ':' indicates this code is in a type, or a braced list
418 // following a label in an object literal ({a: {b: 1}}).
419 // A '<' could be an object used in a comparison, but that is nonsense
420 // code (can never return true), so more likely it is a generic type
421 // argument (`X<{a: string; b: number}>`).
422 // The code below could be confused by semicolons between the
423 // individual members in a type member list, which would normally
424 // trigger BK_Block. In both cases, this must be parsed as an inline
426 Tok->BlockKind = BK_BracedInit;
427 else if (PrevTok->is(tok::r_paren))
428 // `) { }` can only occur in function or method declarations in JS.
429 Tok->BlockKind = BK_Block;
431 Tok->BlockKind = BK_Unknown;
433 LBraceStack.push_back(Tok);
436 if (LBraceStack.empty())
438 if (LBraceStack.back()->BlockKind == BK_Unknown) {
439 bool ProbablyBracedList = false;
440 if (Style.Language == FormatStyle::LK_Proto) {
441 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
443 // Using OriginalColumn to distinguish between ObjC methods and
444 // binary operators is a bit hacky.
445 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
446 NextTok->OriginalColumn == 0;
448 // If there is a comma, semicolon or right paren after the closing
449 // brace, we assume this is a braced initializer list. Note that
450 // regardless how we mark inner braces here, we will overwrite the
451 // BlockKind later if we parse a braced list (where all blocks
452 // inside are by default braced lists), or when we explicitly detect
453 // blocks (for example while parsing lambdas).
454 // FIXME: Some of these do not apply to JS, e.g. "} {" can never be a
455 // braced list in JS.
457 (Style.Language == FormatStyle::LK_JavaScript &&
458 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
460 (Style.isCpp() && NextTok->is(tok::l_paren)) ||
461 NextTok->isOneOf(tok::comma, tok::period, tok::colon,
462 tok::r_paren, tok::r_square, tok::l_brace,
464 (NextTok->is(tok::identifier) &&
465 !PrevTok->isOneOf(tok::semi, tok::r_brace, tok::l_brace)) ||
466 (NextTok->is(tok::semi) &&
467 (!ExpectClassBody || LBraceStack.size() != 1)) ||
468 (NextTok->isBinaryOperator() && !NextIsObjCMethod);
469 if (NextTok->is(tok::l_square)) {
470 // We can have an array subscript after a braced init
471 // list, but C++11 attributes are expected after blocks.
472 NextTok = Tokens->getNextToken();
474 ProbablyBracedList = NextTok->isNot(tok::l_square);
477 if (ProbablyBracedList) {
478 Tok->BlockKind = BK_BracedInit;
479 LBraceStack.back()->BlockKind = BK_BracedInit;
481 Tok->BlockKind = BK_Block;
482 LBraceStack.back()->BlockKind = BK_Block;
485 LBraceStack.pop_back();
487 case tok::identifier:
488 if (!Tok->is(TT_StatementMacro))
499 if (!LBraceStack.empty() && LBraceStack.back()->BlockKind == BK_Unknown)
500 LBraceStack.back()->BlockKind = BK_Block;
507 } while (Tok->Tok.isNot(tok::eof) && !LBraceStack.empty());
509 // Assume other blocks for all unclosed opening braces.
510 for (unsigned i = 0, e = LBraceStack.size(); i != e; ++i) {
511 if (LBraceStack[i]->BlockKind == BK_Unknown)
512 LBraceStack[i]->BlockKind = BK_Block;
515 FormatTok = Tokens->setPosition(StoredPosition);
519 static inline void hash_combine(std::size_t &seed, const T &v) {
521 seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
524 size_t UnwrappedLineParser::computePPHash() const {
526 for (const auto &i : PPStack) {
527 hash_combine(h, size_t(i.Kind));
528 hash_combine(h, i.Line);
533 void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel,
535 assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) &&
536 "'{' or macro block token expected");
537 const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
538 FormatTok->BlockKind = BK_Block;
540 size_t PPStartHash = computePPHash();
542 unsigned InitialLevel = Line->Level;
543 nextToken(/*LevelDifference=*/AddLevel ? 1 : 0);
545 if (MacroBlock && FormatTok->is(tok::l_paren))
548 size_t NbPreprocessorDirectives =
549 CurrentLines == &Lines ? PreprocessorDirectives.size() : 0;
551 size_t OpeningLineIndex =
552 CurrentLines->empty()
553 ? (UnwrappedLine::kInvalidIndex)
554 : (CurrentLines->size() - 1 - NbPreprocessorDirectives);
556 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
560 parseLevel(/*HasOpeningBrace=*/true);
565 if (MacroBlock ? !FormatTok->is(TT_MacroBlockEnd)
566 : !FormatTok->is(tok::r_brace)) {
567 Line->Level = InitialLevel;
568 FormatTok->BlockKind = BK_Block;
572 size_t PPEndHash = computePPHash();
574 // Munch the closing brace.
575 nextToken(/*LevelDifference=*/AddLevel ? -1 : 0);
577 if (MacroBlock && FormatTok->is(tok::l_paren))
580 if (MunchSemi && FormatTok->Tok.is(tok::semi))
582 Line->Level = InitialLevel;
584 if (PPStartHash == PPEndHash) {
585 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
586 if (OpeningLineIndex != UnwrappedLine::kInvalidIndex) {
587 // Update the opening line to add the forward reference as well
588 (*CurrentLines)[OpeningLineIndex].MatchingClosingBlockLineIndex =
589 CurrentLines->size() - 1;
594 static bool isGoogScope(const UnwrappedLine &Line) {
595 // FIXME: Closure-library specific stuff should not be hard-coded but be
597 if (Line.Tokens.size() < 4)
599 auto I = Line.Tokens.begin();
600 if (I->Tok->TokenText != "goog")
603 if (I->Tok->isNot(tok::period))
606 if (I->Tok->TokenText != "scope")
609 return I->Tok->is(tok::l_paren);
612 static bool isIIFE(const UnwrappedLine &Line,
613 const AdditionalKeywords &Keywords) {
614 // Look for the start of an immediately invoked anonymous function.
615 // https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
616 // This is commonly done in JavaScript to create a new, anonymous scope.
617 // Example: (function() { ... })()
618 if (Line.Tokens.size() < 3)
620 auto I = Line.Tokens.begin();
621 if (I->Tok->isNot(tok::l_paren))
624 if (I->Tok->isNot(Keywords.kw_function))
627 return I->Tok->is(tok::l_paren);
630 static bool ShouldBreakBeforeBrace(const FormatStyle &Style,
631 const FormatToken &InitialToken) {
632 if (InitialToken.isOneOf(tok::kw_namespace, TT_NamespaceMacro))
633 return Style.BraceWrapping.AfterNamespace;
634 if (InitialToken.is(tok::kw_class))
635 return Style.BraceWrapping.AfterClass;
636 if (InitialToken.is(tok::kw_union))
637 return Style.BraceWrapping.AfterUnion;
638 if (InitialToken.is(tok::kw_struct))
639 return Style.BraceWrapping.AfterStruct;
643 void UnwrappedLineParser::parseChildBlock() {
644 FormatTok->BlockKind = BK_Block;
647 bool SkipIndent = (Style.Language == FormatStyle::LK_JavaScript &&
648 (isGoogScope(*Line) || isIIFE(*Line, Keywords)));
649 ScopedLineState LineState(*this);
650 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
651 /*MustBeDeclaration=*/false);
652 Line->Level += SkipIndent ? 0 : 1;
653 parseLevel(/*HasOpeningBrace=*/true);
654 flushComments(isOnNewLine(*FormatTok));
655 Line->Level -= SkipIndent ? 0 : 1;
660 void UnwrappedLineParser::parsePPDirective() {
661 assert(FormatTok->Tok.is(tok::hash) && "'#' expected");
662 ScopedMacroState MacroState(*Line, Tokens, FormatTok);
666 if (!FormatTok->Tok.getIdentifierInfo()) {
671 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
676 parsePPIf(/*IfDef=*/false);
680 parsePPIf(/*IfDef=*/true);
697 void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) {
698 size_t Line = CurrentLines->size();
699 if (CurrentLines == &PreprocessorDirectives)
700 Line += Lines.size();
703 (!PPStack.empty() && PPStack.back().Kind == PP_Unreachable))
704 PPStack.push_back({PP_Unreachable, Line});
706 PPStack.push_back({PP_Conditional, Line});
709 void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) {
711 assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
712 if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
713 PPLevelBranchIndex.push_back(0);
714 PPLevelBranchCount.push_back(0);
716 PPChainBranchIndex.push(0);
717 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
718 conditionalCompilationCondition(Unreachable || Skip);
721 void UnwrappedLineParser::conditionalCompilationAlternative() {
722 if (!PPStack.empty())
724 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
725 if (!PPChainBranchIndex.empty())
726 ++PPChainBranchIndex.top();
727 conditionalCompilationCondition(
728 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
729 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
732 void UnwrappedLineParser::conditionalCompilationEnd() {
733 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
734 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
735 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) {
736 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
739 // Guard against #endif's without #if.
740 if (PPBranchLevel > -1)
742 if (!PPChainBranchIndex.empty())
743 PPChainBranchIndex.pop();
744 if (!PPStack.empty())
748 void UnwrappedLineParser::parsePPIf(bool IfDef) {
749 bool IfNDef = FormatTok->is(tok::pp_ifndef);
751 bool Unreachable = false;
752 if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText == "0"))
754 if (IfDef && !IfNDef && FormatTok->TokenText == "SWIG")
756 conditionalCompilationStart(Unreachable);
757 FormatToken *IfCondition = FormatTok;
758 // If there's a #ifndef on the first line, and the only lines before it are
759 // comments, it could be an include guard.
760 bool MaybeIncludeGuard = IfNDef;
761 if (IncludeGuard == IG_Inited && MaybeIncludeGuard)
762 for (auto &Line : Lines) {
763 if (!Line.Tokens.front().Tok->is(tok::comment)) {
764 MaybeIncludeGuard = false;
765 IncludeGuard = IG_Rejected;
772 if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
773 IncludeGuard = IG_IfNdefed;
774 IncludeGuardToken = IfCondition;
778 void UnwrappedLineParser::parsePPElse() {
779 // If a potential include guard has an #else, it's not an include guard.
780 if (IncludeGuard == IG_Defined && PPBranchLevel == 0)
781 IncludeGuard = IG_Rejected;
782 conditionalCompilationAlternative();
783 if (PPBranchLevel > -1)
789 void UnwrappedLineParser::parsePPElIf() { parsePPElse(); }
791 void UnwrappedLineParser::parsePPEndIf() {
792 conditionalCompilationEnd();
794 // If the #endif of a potential include guard is the last thing in the file,
795 // then we found an include guard.
796 unsigned TokenPosition = Tokens->getPosition();
797 FormatToken *PeekNext = AllTokens[TokenPosition];
798 if (IncludeGuard == IG_Defined && PPBranchLevel == -1 &&
799 PeekNext->is(tok::eof) &&
800 Style.IndentPPDirectives != FormatStyle::PPDIS_None)
801 IncludeGuard = IG_Found;
804 void UnwrappedLineParser::parsePPDefine() {
807 if (!FormatTok->Tok.getIdentifierInfo()) {
808 IncludeGuard = IG_Rejected;
809 IncludeGuardToken = nullptr;
814 if (IncludeGuard == IG_IfNdefed &&
815 IncludeGuardToken->TokenText == FormatTok->TokenText) {
816 IncludeGuard = IG_Defined;
817 IncludeGuardToken = nullptr;
818 for (auto &Line : Lines) {
819 if (!Line.Tokens.front().Tok->isOneOf(tok::comment, tok::hash)) {
820 IncludeGuard = IG_Rejected;
827 if (FormatTok->Tok.getKind() == tok::l_paren &&
828 FormatTok->WhitespaceRange.getBegin() ==
829 FormatTok->WhitespaceRange.getEnd()) {
832 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
833 Line->Level += PPBranchLevel + 1;
837 // Errors during a preprocessor directive can only affect the layout of the
838 // preprocessor directive, and thus we ignore them. An alternative approach
839 // would be to use the same approach we use on the file level (no
840 // re-indentation if there was a structural error) within the macro
845 void UnwrappedLineParser::parsePPUnknown() {
849 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
850 Line->Level += PPBranchLevel + 1;
854 // Here we blacklist certain tokens that are not usually the first token in an
855 // unwrapped line. This is used in attempt to distinguish macro calls without
856 // trailing semicolons from other constructs split to several lines.
857 static bool tokenCanStartNewLine(const clang::Token &Tok) {
858 // Semicolon can be a null-statement, l_square can be a start of a macro or
859 // a C++11 attribute, but this doesn't seem to be common.
860 return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) &&
861 Tok.isNot(tok::l_square) &&
862 // Tokens that can only be used as binary operators and a part of
863 // overloaded operator names.
864 Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) &&
865 Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) &&
866 Tok.isNot(tok::less) && Tok.isNot(tok::greater) &&
867 Tok.isNot(tok::slash) && Tok.isNot(tok::percent) &&
868 Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) &&
869 Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) &&
870 Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) &&
871 Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) &&
872 Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) &&
873 Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) &&
874 Tok.isNot(tok::lesslessequal) &&
875 // Colon is used in labels, base class lists, initializer lists,
876 // range-based for loops, ternary operator, but should never be the
877 // first token in an unwrapped line.
878 Tok.isNot(tok::colon) &&
879 // 'noexcept' is a trailing annotation.
880 Tok.isNot(tok::kw_noexcept);
883 static bool mustBeJSIdent(const AdditionalKeywords &Keywords,
884 const FormatToken *FormatTok) {
885 // FIXME: This returns true for C/C++ keywords like 'struct'.
886 return FormatTok->is(tok::identifier) &&
887 (FormatTok->Tok.getIdentifierInfo() == nullptr ||
889 Keywords.kw_in, Keywords.kw_of, Keywords.kw_as, Keywords.kw_async,
890 Keywords.kw_await, Keywords.kw_yield, Keywords.kw_finally,
891 Keywords.kw_function, Keywords.kw_import, Keywords.kw_is,
892 Keywords.kw_let, Keywords.kw_var, tok::kw_const,
893 Keywords.kw_abstract, Keywords.kw_extends, Keywords.kw_implements,
894 Keywords.kw_instanceof, Keywords.kw_interface, Keywords.kw_throws,
898 static bool mustBeJSIdentOrValue(const AdditionalKeywords &Keywords,
899 const FormatToken *FormatTok) {
900 return FormatTok->Tok.isLiteral() ||
901 FormatTok->isOneOf(tok::kw_true, tok::kw_false) ||
902 mustBeJSIdent(Keywords, FormatTok);
905 // isJSDeclOrStmt returns true if |FormatTok| starts a declaration or statement
906 // when encountered after a value (see mustBeJSIdentOrValue).
907 static bool isJSDeclOrStmt(const AdditionalKeywords &Keywords,
908 const FormatToken *FormatTok) {
909 return FormatTok->isOneOf(
910 tok::kw_return, Keywords.kw_yield,
912 tok::kw_if, tok::kw_else,
914 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
916 tok::kw_switch, tok::kw_case,
918 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.kw_finally,
920 tok::kw_const, tok::kw_class, Keywords.kw_var, Keywords.kw_let,
921 Keywords.kw_async, Keywords.kw_function,
923 Keywords.kw_import, tok::kw_export);
926 // readTokenWithJavaScriptASI reads the next token and terminates the current
927 // line if JavaScript Automatic Semicolon Insertion must
928 // happen between the current token and the next token.
930 // This method is conservative - it cannot cover all edge cases of JavaScript,
931 // but only aims to correctly handle certain well known cases. It *must not*
932 // return true in speculative cases.
933 void UnwrappedLineParser::readTokenWithJavaScriptASI() {
934 FormatToken *Previous = FormatTok;
936 FormatToken *Next = FormatTok;
939 CommentsBeforeNextToken.empty()
940 ? Next->NewlinesBefore == 0
941 : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
945 bool PreviousMustBeValue = mustBeJSIdentOrValue(Keywords, Previous);
946 bool PreviousStartsTemplateExpr =
947 Previous->is(TT_TemplateString) && Previous->TokenText.endswith("${");
948 if (PreviousMustBeValue || Previous->is(tok::r_paren)) {
949 // If the line contains an '@' sign, the previous token might be an
950 // annotation, which can precede another identifier/value.
951 bool HasAt = std::find_if(Line->Tokens.begin(), Line->Tokens.end(),
952 [](UnwrappedLineNode &LineNode) {
953 return LineNode.Tok->is(tok::at);
954 }) != Line->Tokens.end();
958 if (Next->is(tok::exclaim) && PreviousMustBeValue)
959 return addUnwrappedLine();
960 bool NextMustBeValue = mustBeJSIdentOrValue(Keywords, Next);
961 bool NextEndsTemplateExpr =
962 Next->is(TT_TemplateString) && Next->TokenText.startswith("}");
963 if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
964 (PreviousMustBeValue ||
965 Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
967 return addUnwrappedLine();
968 if ((PreviousMustBeValue || Previous->is(tok::r_paren)) &&
969 isJSDeclOrStmt(Keywords, Next))
970 return addUnwrappedLine();
973 void UnwrappedLineParser::parseStructuralElement() {
974 assert(!FormatTok->is(tok::l_brace));
975 if (Style.Language == FormatStyle::LK_TableGen &&
976 FormatTok->is(tok::pp_include)) {
978 if (FormatTok->is(tok::string_literal))
983 switch (FormatTok->Tok.getKind()) {
986 if (FormatTok->is(tok::l_brace)) {
987 FormatTok->Type = TT_InlineASMBrace;
989 while (FormatTok && FormatTok->isNot(tok::eof)) {
990 if (FormatTok->is(tok::r_brace)) {
991 FormatTok->Type = TT_InlineASMBrace;
996 FormatTok->Finalized = true;
1001 case tok::kw_namespace:
1004 case tok::kw_public:
1005 case tok::kw_protected:
1006 case tok::kw_private:
1007 if (Style.Language == FormatStyle::LK_Java ||
1008 Style.Language == FormatStyle::LK_JavaScript || Style.isCSharp())
1011 parseAccessSpecifier();
1018 parseForOrWhileLoop();
1023 case tok::kw_switch:
1024 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1025 // 'switch: string' field declaration.
1029 case tok::kw_default:
1030 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1031 // 'default: string' field declaration.
1034 if (FormatTok->is(tok::colon)) {
1038 // e.g. "default void f() {}" in a Java interface.
1041 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1042 // 'case: string' field declaration.
1050 case tok::kw_extern:
1052 if (FormatTok->Tok.is(tok::string_literal)) {
1054 if (FormatTok->Tok.is(tok::l_brace)) {
1055 if (Style.BraceWrapping.AfterExternBlock) {
1057 parseBlock(/*MustBeDeclaration=*/true);
1059 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false);
1066 case tok::kw_export:
1067 if (Style.Language == FormatStyle::LK_JavaScript) {
1068 parseJavaScriptEs6ImportExport();
1073 // Handle C++ "(inline|export) namespace".
1075 case tok::kw_inline:
1077 if (FormatTok->Tok.is(tok::kw_namespace)) {
1082 case tok::identifier:
1083 if (FormatTok->is(TT_ForEachMacro)) {
1084 parseForOrWhileLoop();
1087 if (FormatTok->is(TT_MacroBlockBegin)) {
1088 parseBlock(/*MustBeDeclaration=*/false, /*AddLevel=*/true,
1089 /*MunchSemi=*/false);
1092 if (FormatTok->is(Keywords.kw_import)) {
1093 if (Style.Language == FormatStyle::LK_JavaScript) {
1094 parseJavaScriptEs6ImportExport();
1097 if (Style.Language == FormatStyle::LK_Proto) {
1099 if (FormatTok->is(tok::kw_public))
1101 if (!FormatTok->is(tok::string_literal))
1104 if (FormatTok->is(tok::semi))
1110 if (Style.isCpp() &&
1111 FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
1112 Keywords.kw_slots, Keywords.kw_qslots)) {
1114 if (FormatTok->is(tok::colon)) {
1120 if (Style.isCpp() && FormatTok->is(TT_StatementMacro)) {
1121 parseStatementMacro();
1124 if (Style.isCpp() && FormatTok->is(TT_NamespaceMacro)) {
1128 // In all other cases, parse the declaration.
1134 const FormatToken *Previous = FormatTok->Previous;
1135 switch (FormatTok->Tok.getKind()) {
1138 if (FormatTok->Tok.is(tok::l_brace)) {
1142 } else if (Style.Language == FormatStyle::LK_Java &&
1143 FormatTok->is(Keywords.kw_interface)) {
1147 switch (FormatTok->Tok.getObjCKeywordID()) {
1148 case tok::objc_public:
1149 case tok::objc_protected:
1150 case tok::objc_package:
1151 case tok::objc_private:
1152 return parseAccessSpecifier();
1153 case tok::objc_interface:
1154 case tok::objc_implementation:
1155 return parseObjCInterfaceOrImplementation();
1156 case tok::objc_protocol:
1157 if (parseObjCProtocol())
1161 return; // Handled by the caller.
1162 case tok::objc_optional:
1163 case tok::objc_required:
1167 case tok::objc_autoreleasepool:
1169 if (FormatTok->Tok.is(tok::l_brace)) {
1170 if (Style.BraceWrapping.AfterControlStatement ==
1171 FormatStyle::BWACS_Always)
1173 parseBlock(/*MustBeDeclaration=*/false);
1177 case tok::objc_synchronized:
1179 if (FormatTok->Tok.is(tok::l_paren))
1180 // Skip synchronization object
1182 if (FormatTok->Tok.is(tok::l_brace)) {
1183 if (Style.BraceWrapping.AfterControlStatement ==
1184 FormatStyle::BWACS_Always)
1186 parseBlock(/*MustBeDeclaration=*/false);
1191 // This branch isn't strictly necessary (the kw_try case below would
1192 // do this too after the tok::at is parsed above). But be explicit.
1200 // Ignore if this is part of "template <enum ...".
1201 if (Previous && Previous->is(tok::less)) {
1206 // parseEnum falls through and does not yet add an unwrapped line as an
1207 // enum definition can start a structural element.
1210 // This only applies for C++.
1211 if (!Style.isCpp()) {
1216 case tok::kw_typedef:
1218 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1219 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS,
1220 Keywords.kw_CF_CLOSED_ENUM,
1221 Keywords.kw_NS_CLOSED_ENUM))
1224 case tok::kw_struct:
1227 // parseRecord falls through and does not yet add an unwrapped line as a
1228 // record declaration or definition can start a structural element.
1230 // This does not apply for Java, JavaScript and C#.
1231 if (Style.Language == FormatStyle::LK_Java ||
1232 Style.Language == FormatStyle::LK_JavaScript || Style.isCSharp()) {
1233 if (FormatTok->is(tok::semi))
1241 // In Java, classes have an implicit static member "class".
1242 if (Style.Language == FormatStyle::LK_Java && FormatTok &&
1243 FormatTok->is(tok::kw_class))
1245 if (Style.Language == FormatStyle::LK_JavaScript && FormatTok &&
1246 FormatTok->Tok.getIdentifierInfo())
1247 // JavaScript only has pseudo keywords, all keywords are allowed to
1248 // appear in "IdentifierName" positions. See http://es5.github.io/#x7.6
1261 case tok::kw_operator:
1263 if (FormatTok->isBinaryOperator())
1268 if (FormatTok->Tok.isAnyIdentifier() ||
1269 FormatTok->isSimpleTypeSpecifier())
1271 if (FormatTok->is(tok::l_paren))
1273 if (FormatTok->is(tok::l_brace))
1277 if (!tryToParseBracedList()) {
1278 // A block outside of parentheses must be the last part of a
1279 // structural element.
1280 // FIXME: Figure out cases where this is not true, and add projections
1281 // for them (the one we know is missing are lambdas).
1282 if (Style.BraceWrapping.AfterFunction)
1284 FormatTok->Type = TT_FunctionLBrace;
1285 parseBlock(/*MustBeDeclaration=*/false);
1289 // Otherwise this was a braced init list, and the structural
1290 // element continues.
1293 // We arrive here when parsing function-try blocks.
1294 if (Style.BraceWrapping.AfterFunction)
1298 case tok::identifier: {
1299 if (FormatTok->is(TT_MacroBlockEnd)) {
1304 // Function declarations (as opposed to function expressions) are parsed
1305 // on their own unwrapped line by continuing this loop. Function
1306 // expressions (functions that are not on their own line) must not create
1307 // a new unwrapped line, so they are special cased below.
1308 size_t TokenCount = Line->Tokens.size();
1309 if (Style.Language == FormatStyle::LK_JavaScript &&
1310 FormatTok->is(Keywords.kw_function) &&
1311 (TokenCount > 1 || (TokenCount == 1 && !Line->Tokens.front().Tok->is(
1312 Keywords.kw_async)))) {
1313 tryToParseJSFunction();
1316 if ((Style.Language == FormatStyle::LK_JavaScript ||
1317 Style.Language == FormatStyle::LK_Java) &&
1318 FormatTok->is(Keywords.kw_interface)) {
1319 if (Style.Language == FormatStyle::LK_JavaScript) {
1320 // In JavaScript/TypeScript, "interface" can be used as a standalone
1321 // identifier, e.g. in `var interface = 1;`. If "interface" is
1322 // followed by another identifier, it is very like to be an actual
1323 // interface declaration.
1324 unsigned StoredPosition = Tokens->getPosition();
1325 FormatToken *Next = Tokens->getNextToken();
1326 FormatTok = Tokens->setPosition(StoredPosition);
1327 if (Next && !mustBeJSIdent(Keywords, Next)) {
1337 if (Style.isCpp() && FormatTok->is(TT_StatementMacro)) {
1338 parseStatementMacro();
1342 // See if the following token should start a new unwrapped line.
1343 StringRef Text = FormatTok->TokenText;
1346 // JS doesn't have macros, and within classes colons indicate fields, not
1348 if (Style.Language == FormatStyle::LK_JavaScript)
1351 TokenCount = Line->Tokens.size();
1352 if (TokenCount == 1 ||
1353 (TokenCount == 2 && Line->Tokens.front().Tok->is(tok::comment))) {
1354 if (FormatTok->Tok.is(tok::colon) && !Line->MustBeDeclaration) {
1355 Line->Tokens.begin()->Tok->MustBreakBefore = true;
1356 parseLabel(!Style.IndentGotoLabels);
1359 // Recognize function-like macro usages without trailing semicolon as
1360 // well as free-standing macros like Q_OBJECT.
1361 bool FunctionLike = FormatTok->is(tok::l_paren);
1365 bool FollowedByNewline =
1366 CommentsBeforeNextToken.empty()
1367 ? FormatTok->NewlinesBefore > 0
1368 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
1370 if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
1371 tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) {
1379 // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType
1380 // TT_JsFatArrow. The always start an expression or a child block if
1381 // followed by a curly.
1382 if (FormatTok->is(TT_JsFatArrow)) {
1384 if (FormatTok->is(tok::l_brace))
1390 if (FormatTok->Tok.is(tok::l_brace)) {
1393 } else if (Style.Language == FormatStyle::LK_Proto &&
1394 FormatTok->Tok.is(tok::less)) {
1396 parseBracedList(/*ContinueOnSemicolons=*/false,
1397 /*ClosingBraceKind=*/tok::greater);
1413 bool UnwrappedLineParser::tryToParseLambda() {
1414 if (!Style.isCpp()) {
1418 assert(FormatTok->is(tok::l_square));
1419 FormatToken &LSquare = *FormatTok;
1420 if (!tryToParseLambdaIntroducer())
1423 bool SeenArrow = false;
1425 while (FormatTok->isNot(tok::l_brace)) {
1426 if (FormatTok->isSimpleTypeSpecifier()) {
1430 switch (FormatTok->Tok.getKind()) {
1442 case tok::identifier:
1443 case tok::numeric_constant:
1444 case tok::coloncolon:
1446 case tok::kw_mutable:
1447 case tok::kw_noexcept:
1448 case tok::kw_template:
1449 case tok::kw_typename:
1452 // Specialization of a template with an integer parameter can contain
1453 // arithmetic, logical, comparison and ternary operators.
1455 // FIXME: This also accepts sequences of operators that are not in the scope
1456 // of a template argument list.
1458 // In a C++ lambda a template type can only occur after an arrow. We use
1459 // this as an heuristic to distinguish between Objective-C expressions
1460 // followed by an `a->b` expression, such as:
1461 // ([obj func:arg] + a->b)
1462 // Otherwise the code below would parse as a lambda.
1464 // FIXME: This heuristic is incorrect for C++20 generic lambdas with
1465 // explicit template lists: []<bool b = true && false>(U &&u){}
1477 case tok::equalequal:
1478 case tok::exclaimequal:
1479 case tok::greaterequal:
1480 case tok::lessequal:
1491 // This might or might not actually be a lambda arrow (this could be an
1492 // ObjC method invocation followed by a dereferencing arrow). We might
1493 // reset this back to TT_Unknown in TokenAnnotator.
1494 FormatTok->Type = TT_LambdaArrow;
1502 FormatTok->Type = TT_LambdaLBrace;
1503 LSquare.Type = TT_LambdaLSquare;
1508 bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
1509 const FormatToken *Previous = FormatTok->Previous;
1511 (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new,
1512 tok::kw_delete, tok::l_square) ||
1513 FormatTok->isCppStructuredBinding(Style) || Previous->closesScope() ||
1514 Previous->isSimpleTypeSpecifier())) {
1519 if (FormatTok->is(tok::l_square)) {
1522 parseSquare(/*LambdaIntroducer=*/true);
1526 void UnwrappedLineParser::tryToParseJSFunction() {
1527 assert(FormatTok->is(Keywords.kw_function) ||
1528 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function));
1529 if (FormatTok->is(Keywords.kw_async))
1531 // Consume "function".
1534 // Consume * (generator function). Treat it like C++'s overloaded operators.
1535 if (FormatTok->is(tok::star)) {
1536 FormatTok->Type = TT_OverloadedOperator;
1540 // Consume function name.
1541 if (FormatTok->is(tok::identifier))
1544 if (FormatTok->isNot(tok::l_paren))
1547 // Parse formal parameter list.
1550 if (FormatTok->is(tok::colon)) {
1551 // Parse a type definition.
1554 // Eat the type declaration. For braced inline object types, balance braces,
1555 // otherwise just parse until finding an l_brace for the function body.
1556 if (FormatTok->is(tok::l_brace))
1557 tryToParseBracedList();
1559 while (!FormatTok->isOneOf(tok::l_brace, tok::semi) && !eof())
1563 if (FormatTok->is(tok::semi))
1569 bool UnwrappedLineParser::tryToParseBracedList() {
1570 if (FormatTok->BlockKind == BK_Unknown)
1571 calculateBraceTypes();
1572 assert(FormatTok->BlockKind != BK_Unknown);
1573 if (FormatTok->BlockKind == BK_Block)
1580 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
1581 tok::TokenKind ClosingBraceKind) {
1582 bool HasError = false;
1584 // FIXME: Once we have an expression parser in the UnwrappedLineParser,
1585 // replace this by using parseAssigmentExpression() inside.
1587 if (Style.Language == FormatStyle::LK_JavaScript) {
1588 if (FormatTok->is(Keywords.kw_function) ||
1589 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) {
1590 tryToParseJSFunction();
1593 if (FormatTok->is(TT_JsFatArrow)) {
1595 // Fat arrows can be followed by simple expressions or by child blocks
1597 if (FormatTok->is(tok::l_brace)) {
1602 if (FormatTok->is(tok::l_brace)) {
1603 // Could be a method inside of a braced list `{a() { return 1; }}`.
1604 if (tryToParseBracedList())
1609 if (FormatTok->Tok.getKind() == ClosingBraceKind) {
1613 switch (FormatTok->Tok.getKind()) {
1616 if (FormatTok->is(tok::l_brace)) {
1625 // JavaScript can just have free standing methods and getters/setters in
1626 // object literals. Detect them by a "{" following ")".
1627 if (Style.Language == FormatStyle::LK_JavaScript) {
1628 if (FormatTok->is(tok::l_brace))
1634 // Assume there are no blocks inside a braced init list apart
1635 // from the ones we explicitly parse out (like lambdas).
1636 FormatTok->BlockKind = BK_BracedInit;
1641 if (Style.Language == FormatStyle::LK_Proto) {
1643 parseBracedList(/*ContinueOnSemicolons=*/false,
1644 /*ClosingBraceKind=*/tok::greater);
1650 // JavaScript (or more precisely TypeScript) can have semicolons in braced
1651 // lists (in so-called TypeMemberLists). Thus, the semicolon cannot be
1652 // used for error recovery if we have otherwise determined that this is
1654 if (Style.Language == FormatStyle::LK_JavaScript) {
1659 if (!ContinueOnSemicolons)
1674 void UnwrappedLineParser::parseParens() {
1675 assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected.");
1678 switch (FormatTok->Tok.getKind()) {
1681 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace))
1688 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1694 if (!tryToParseBracedList())
1699 if (FormatTok->Tok.is(tok::l_brace)) {
1705 if (Style.Language == FormatStyle::LK_JavaScript)
1706 parseRecord(/*ParseAsExpr=*/true);
1710 case tok::identifier:
1711 if (Style.Language == FormatStyle::LK_JavaScript &&
1712 (FormatTok->is(Keywords.kw_function) ||
1713 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)))
1714 tryToParseJSFunction();
1725 void UnwrappedLineParser::parseSquare(bool LambdaIntroducer) {
1726 if (!LambdaIntroducer) {
1727 assert(FormatTok->Tok.is(tok::l_square) && "'[' expected.");
1728 if (tryToParseLambda())
1732 switch (FormatTok->Tok.getKind()) {
1740 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1745 case tok::l_brace: {
1746 if (!tryToParseBracedList())
1752 if (FormatTok->Tok.is(tok::l_brace)) {
1764 void UnwrappedLineParser::parseIfThenElse() {
1765 assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected");
1767 if (FormatTok->Tok.isOneOf(tok::kw_constexpr, tok::identifier))
1769 if (FormatTok->Tok.is(tok::l_paren))
1771 bool NeedsUnwrappedLine = false;
1772 if (FormatTok->Tok.is(tok::l_brace)) {
1773 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1774 parseBlock(/*MustBeDeclaration=*/false);
1775 if (Style.BraceWrapping.BeforeElse)
1778 NeedsUnwrappedLine = true;
1782 parseStructuralElement();
1785 if (FormatTok->Tok.is(tok::kw_else)) {
1787 if (FormatTok->Tok.is(tok::l_brace)) {
1788 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1789 parseBlock(/*MustBeDeclaration=*/false);
1791 } else if (FormatTok->Tok.is(tok::kw_if)) {
1796 parseStructuralElement();
1797 if (FormatTok->is(tok::eof))
1801 } else if (NeedsUnwrappedLine) {
1806 void UnwrappedLineParser::parseTryCatch() {
1807 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
1809 bool NeedsUnwrappedLine = false;
1810 if (FormatTok->is(tok::colon)) {
1811 // We are in a function try block, what comes is an initializer list.
1813 while (FormatTok->is(tok::identifier)) {
1815 if (FormatTok->is(tok::l_paren))
1817 if (FormatTok->is(tok::comma))
1821 // Parse try with resource.
1822 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
1825 if (FormatTok->is(tok::l_brace)) {
1826 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1827 parseBlock(/*MustBeDeclaration=*/false);
1828 if (Style.BraceWrapping.BeforeCatch) {
1831 NeedsUnwrappedLine = true;
1833 } else if (!FormatTok->is(tok::kw_catch)) {
1834 // The C++ standard requires a compound-statement after a try.
1835 // If there's none, we try to assume there's a structuralElement
1836 // and try to continue.
1839 parseStructuralElement();
1843 if (FormatTok->is(tok::at))
1845 if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
1846 tok::kw___finally) ||
1847 ((Style.Language == FormatStyle::LK_Java ||
1848 Style.Language == FormatStyle::LK_JavaScript) &&
1849 FormatTok->is(Keywords.kw_finally)) ||
1850 (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) ||
1851 FormatTok->Tok.isObjCAtKeyword(tok::objc_finally))))
1854 while (FormatTok->isNot(tok::l_brace)) {
1855 if (FormatTok->is(tok::l_paren)) {
1859 if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof))
1863 NeedsUnwrappedLine = false;
1864 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1865 parseBlock(/*MustBeDeclaration=*/false);
1866 if (Style.BraceWrapping.BeforeCatch)
1869 NeedsUnwrappedLine = true;
1871 if (NeedsUnwrappedLine)
1875 void UnwrappedLineParser::parseNamespace() {
1876 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
1877 "'namespace' expected");
1879 const FormatToken &InitialToken = *FormatTok;
1881 if (InitialToken.is(TT_NamespaceMacro)) {
1884 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
1886 if (FormatTok->is(tok::l_square))
1892 if (FormatTok->Tok.is(tok::l_brace)) {
1893 if (ShouldBreakBeforeBrace(Style, InitialToken))
1896 bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All ||
1897 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
1898 DeclarationScopeStack.size() > 1);
1899 parseBlock(/*MustBeDeclaration=*/true, AddLevel);
1900 // Munch the semicolon after a namespace. This is more common than one would
1901 // think. Puttin the semicolon into its own line is very ugly.
1902 if (FormatTok->Tok.is(tok::semi))
1906 // FIXME: Add error handling.
1909 void UnwrappedLineParser::parseNew() {
1910 assert(FormatTok->is(tok::kw_new) && "'new' expected");
1912 if (Style.Language != FormatStyle::LK_Java)
1915 // In Java, we can parse everything up to the parens, which aren't optional.
1917 // There should not be a ;, { or } before the new's open paren.
1918 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
1921 // Consume the parens.
1922 if (FormatTok->is(tok::l_paren)) {
1925 // If there is a class body of an anonymous class, consume that as child.
1926 if (FormatTok->is(tok::l_brace))
1934 void UnwrappedLineParser::parseForOrWhileLoop() {
1935 assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
1936 "'for', 'while' or foreach macro expected");
1938 // JS' for await ( ...
1939 if (Style.Language == FormatStyle::LK_JavaScript &&
1940 FormatTok->is(Keywords.kw_await))
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::parseDoWhile() {
1957 assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
1959 if (FormatTok->Tok.is(tok::l_brace)) {
1960 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1961 parseBlock(/*MustBeDeclaration=*/false);
1962 if (Style.BraceWrapping.IndentBraces)
1967 parseStructuralElement();
1971 // FIXME: Add error handling.
1972 if (!FormatTok->Tok.is(tok::kw_while)) {
1978 parseStructuralElement();
1981 void UnwrappedLineParser::parseLabel(bool LeftAlignLabel) {
1983 unsigned OldLineLevel = Line->Level;
1984 if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
1988 if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) {
1989 CompoundStatementIndenter Indenter(this, Line->Level,
1990 Style.BraceWrapping.AfterCaseLabel,
1991 Style.BraceWrapping.IndentBraces);
1992 parseBlock(/*MustBeDeclaration=*/false);
1993 if (FormatTok->Tok.is(tok::kw_break)) {
1994 if (Style.BraceWrapping.AfterControlStatement ==
1995 FormatStyle::BWACS_Always)
1997 parseStructuralElement();
2001 if (FormatTok->is(tok::semi))
2005 Line->Level = OldLineLevel;
2006 if (FormatTok->isNot(tok::l_brace)) {
2007 parseStructuralElement();
2012 void UnwrappedLineParser::parseCaseLabel() {
2013 assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
2014 // FIXME: fix handling of complex expressions here.
2017 } while (!eof() && !FormatTok->Tok.is(tok::colon));
2021 void UnwrappedLineParser::parseSwitch() {
2022 assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
2024 if (FormatTok->Tok.is(tok::l_paren))
2026 if (FormatTok->Tok.is(tok::l_brace)) {
2027 CompoundStatementIndenter Indenter(this, Style, Line->Level);
2028 parseBlock(/*MustBeDeclaration=*/false);
2033 parseStructuralElement();
2038 void UnwrappedLineParser::parseAccessSpecifier() {
2040 // Understand Qt's slots.
2041 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
2043 // Otherwise, we don't know what it is, and we'd better keep the next token.
2044 if (FormatTok->Tok.is(tok::colon))
2049 bool UnwrappedLineParser::parseEnum() {
2050 // Won't be 'enum' for NS_ENUMs.
2051 if (FormatTok->Tok.is(tok::kw_enum))
2054 // In TypeScript, "enum" can also be used as property name, e.g. in interface
2055 // declarations. An "enum" keyword followed by a colon would be a syntax
2056 // error and thus assume it is just an identifier.
2057 if (Style.Language == FormatStyle::LK_JavaScript &&
2058 FormatTok->isOneOf(tok::colon, tok::question))
2061 // In protobuf, "enum" can be used as a field name.
2062 if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal))
2065 // Eat up enum class ...
2066 if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct))
2069 while (FormatTok->Tok.getIdentifierInfo() ||
2070 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
2071 tok::greater, tok::comma, tok::question)) {
2073 // We can have macros or attributes in between 'enum' and the enum name.
2074 if (FormatTok->is(tok::l_paren))
2076 if (FormatTok->is(tok::identifier)) {
2078 // If there are two identifiers in a row, this is likely an elaborate
2079 // return type. In Java, this can be "implements", etc.
2080 if (Style.isCpp() && FormatTok->is(tok::identifier))
2085 // Just a declaration or something is wrong.
2086 if (FormatTok->isNot(tok::l_brace))
2088 FormatTok->BlockKind = BK_Block;
2090 if (Style.Language == FormatStyle::LK_Java) {
2091 // Java enums are different.
2092 parseJavaEnumBody();
2095 if (Style.Language == FormatStyle::LK_Proto) {
2096 parseBlock(/*MustBeDeclaration=*/true);
2102 bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true);
2104 if (FormatTok->is(tok::semi))
2110 // There is no addUnwrappedLine() here so that we fall through to parsing a
2111 // structural element afterwards. Thus, in "enum A {} n, m;",
2112 // "} n, m;" will end up in one unwrapped line.
2115 void UnwrappedLineParser::parseJavaEnumBody() {
2116 // Determine whether the enum is simple, i.e. does not have a semicolon or
2117 // constants with class bodies. Simple enums can be formatted like braced
2118 // lists, contracted to a single line, etc.
2119 unsigned StoredPosition = Tokens->getPosition();
2120 bool IsSimple = true;
2121 FormatToken *Tok = Tokens->getNextToken();
2123 if (Tok->is(tok::r_brace))
2125 if (Tok->isOneOf(tok::l_brace, tok::semi)) {
2129 // FIXME: This will also mark enums with braces in the arguments to enum
2130 // constants as "not simple". This is probably fine in practice, though.
2131 Tok = Tokens->getNextToken();
2133 FormatTok = Tokens->setPosition(StoredPosition);
2142 // Parse the body of a more complex enum.
2143 // First add a line for everything up to the "{".
2148 // Parse the enum constants.
2150 if (FormatTok->is(tok::l_brace)) {
2151 // Parse the constant's class body.
2152 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
2153 /*MunchSemi=*/false);
2154 } else if (FormatTok->is(tok::l_paren)) {
2156 } else if (FormatTok->is(tok::comma)) {
2159 } else if (FormatTok->is(tok::semi)) {
2163 } else if (FormatTok->is(tok::r_brace)) {
2171 // Parse the class body after the enum's ";" if any.
2172 parseLevel(/*HasOpeningBrace=*/true);
2178 void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
2179 const FormatToken &InitialToken = *FormatTok;
2182 // The actual identifier can be a nested name specifier, and in macros
2183 // it is often token-pasted.
2184 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
2185 tok::kw___attribute, tok::kw___declspec,
2187 ((Style.Language == FormatStyle::LK_Java ||
2188 Style.Language == FormatStyle::LK_JavaScript) &&
2189 FormatTok->isOneOf(tok::period, tok::comma))) {
2190 if (Style.Language == FormatStyle::LK_JavaScript &&
2191 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
2192 // JavaScript/TypeScript supports inline object types in
2193 // extends/implements positions:
2194 // class Foo implements {bar: number} { }
2196 if (FormatTok->is(tok::l_brace)) {
2197 tryToParseBracedList();
2201 bool IsNonMacroIdentifier =
2202 FormatTok->is(tok::identifier) &&
2203 FormatTok->TokenText != FormatTok->TokenText.upper();
2205 // We can have macros or attributes in between 'class' and the class name.
2206 if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren))
2210 // Note that parsing away template declarations here leads to incorrectly
2211 // accepting function declarations as record declarations.
2212 // In general, we cannot solve this problem. Consider:
2213 // class A<int> B() {}
2214 // which can be a function definition or a class definition when B() is a
2215 // macro. If we find enough real-world cases where this is a problem, we
2216 // can parse for the 'template' keyword in the beginning of the statement,
2217 // and thus rule out the record production in case there is no template
2218 // (this would still leave us with an ambiguity between template function
2219 // and class declarations).
2220 if (FormatTok->isOneOf(tok::colon, tok::less)) {
2222 if (FormatTok->is(tok::l_brace)) {
2223 calculateBraceTypes(/*ExpectClassBody=*/true);
2224 if (!tryToParseBracedList())
2227 if (FormatTok->Tok.is(tok::semi))
2232 if (FormatTok->Tok.is(tok::l_brace)) {
2236 if (ShouldBreakBeforeBrace(Style, InitialToken))
2239 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
2240 /*MunchSemi=*/false);
2243 // There is no addUnwrappedLine() here so that we fall through to parsing a
2244 // structural element afterwards. Thus, in "class A {} n, m;",
2245 // "} n, m;" will end up in one unwrapped line.
2248 void UnwrappedLineParser::parseObjCMethod() {
2249 assert(FormatTok->Tok.isOneOf(tok::l_paren, tok::identifier) &&
2250 "'(' or identifier expected.");
2252 if (FormatTok->Tok.is(tok::semi)) {
2256 } else if (FormatTok->Tok.is(tok::l_brace)) {
2257 if (Style.BraceWrapping.AfterFunction)
2259 parseBlock(/*MustBeDeclaration=*/false);
2268 void UnwrappedLineParser::parseObjCProtocolList() {
2269 assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
2272 // Early exit in case someone forgot a close angle.
2273 if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
2274 FormatTok->Tok.isObjCAtKeyword(tok::objc_end))
2276 } while (!eof() && FormatTok->Tok.isNot(tok::greater));
2277 nextToken(); // Skip '>'.
2280 void UnwrappedLineParser::parseObjCUntilAtEnd() {
2282 if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
2287 if (FormatTok->is(tok::l_brace)) {
2288 parseBlock(/*MustBeDeclaration=*/false);
2289 // In ObjC interfaces, nothing should be following the "}".
2291 } else if (FormatTok->is(tok::r_brace)) {
2292 // Ignore stray "}". parseStructuralElement doesn't consume them.
2295 } else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
2299 parseStructuralElement();
2304 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
2305 assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_interface ||
2306 FormatTok->Tok.getObjCKeywordID() == tok::objc_implementation);
2308 nextToken(); // interface name
2310 // @interface can be followed by a lightweight generic
2311 // specialization list, then either a base class or a category.
2312 if (FormatTok->Tok.is(tok::less)) {
2313 // Unlike protocol lists, generic parameterizations support
2316 // @interface Foo<ValueType : id <NSCopying, NSSecureCoding>> :
2317 // NSObject <NSCopying, NSSecureCoding>
2319 // so we need to count how many open angles we have left.
2320 unsigned NumOpenAngles = 1;
2323 // Early exit in case someone forgot a close angle.
2324 if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
2325 FormatTok->Tok.isObjCAtKeyword(tok::objc_end))
2327 if (FormatTok->Tok.is(tok::less))
2329 else if (FormatTok->Tok.is(tok::greater)) {
2330 assert(NumOpenAngles > 0 && "'>' makes NumOpenAngles negative");
2333 } while (!eof() && NumOpenAngles != 0);
2334 nextToken(); // Skip '>'.
2336 if (FormatTok->Tok.is(tok::colon)) {
2338 nextToken(); // base class name
2339 } else if (FormatTok->Tok.is(tok::l_paren))
2340 // Skip category, if present.
2343 if (FormatTok->Tok.is(tok::less))
2344 parseObjCProtocolList();
2346 if (FormatTok->Tok.is(tok::l_brace)) {
2347 if (Style.BraceWrapping.AfterObjCDeclaration)
2349 parseBlock(/*MustBeDeclaration=*/true);
2352 // With instance variables, this puts '}' on its own line. Without instance
2353 // variables, this ends the @interface line.
2356 parseObjCUntilAtEnd();
2359 // Returns true for the declaration/definition form of @protocol,
2360 // false for the expression form.
2361 bool UnwrappedLineParser::parseObjCProtocol() {
2362 assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_protocol);
2365 if (FormatTok->is(tok::l_paren))
2366 // The expression form of @protocol, e.g. "Protocol* p = @protocol(foo);".
2369 // The definition/declaration form,
2371 // - (int)someMethod;
2374 nextToken(); // protocol name
2376 if (FormatTok->Tok.is(tok::less))
2377 parseObjCProtocolList();
2379 // Check for protocol declaration.
2380 if (FormatTok->Tok.is(tok::semi)) {
2387 parseObjCUntilAtEnd();
2391 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
2392 bool IsImport = FormatTok->is(Keywords.kw_import);
2393 assert(IsImport || FormatTok->is(tok::kw_export));
2396 // Consume the "default" in "export default class/function".
2397 if (FormatTok->is(tok::kw_default))
2400 // Consume "async function", "function" and "default function", so that these
2401 // get parsed as free-standing JS functions, i.e. do not require a trailing
2403 if (FormatTok->is(Keywords.kw_async))
2405 if (FormatTok->is(Keywords.kw_function)) {
2410 // For imports, `export *`, `export {...}`, consume the rest of the line up
2411 // to the terminating `;`. For everything else, just return and continue
2412 // parsing the structural element, i.e. the declaration or expression for
2413 // `export default`.
2414 if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) &&
2415 !FormatTok->isStringLiteral())
2419 if (FormatTok->is(tok::semi))
2421 if (Line->Tokens.empty()) {
2422 // Common issue: Automatic Semicolon Insertion wrapped the line, so the
2423 // import statement should terminate.
2426 if (FormatTok->is(tok::l_brace)) {
2427 FormatTok->BlockKind = BK_Block;
2436 void UnwrappedLineParser::parseStatementMacro() {
2438 if (FormatTok->is(tok::l_paren))
2440 if (FormatTok->is(tok::semi))
2445 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
2446 StringRef Prefix = "") {
2447 llvm::dbgs() << Prefix << "Line(" << Line.Level
2448 << ", FSC=" << Line.FirstStartColumn << ")"
2449 << (Line.InPPDirective ? " MACRO" : "") << ": ";
2450 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2451 E = Line.Tokens.end();
2453 llvm::dbgs() << I->Tok->Tok.getName() << "["
2454 << "T=" << I->Tok->Type << ", OC=" << I->Tok->OriginalColumn
2457 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2458 E = Line.Tokens.end();
2460 const UnwrappedLineNode &Node = *I;
2461 for (SmallVectorImpl<UnwrappedLine>::const_iterator
2462 I = Node.Children.begin(),
2463 E = Node.Children.end();
2465 printDebugInfo(*I, "\nChild: ");
2468 llvm::dbgs() << "\n";
2471 void UnwrappedLineParser::addUnwrappedLine() {
2472 if (Line->Tokens.empty())
2475 if (CurrentLines == &Lines)
2476 printDebugInfo(*Line);
2478 CurrentLines->push_back(std::move(*Line));
2479 Line->Tokens.clear();
2480 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
2481 Line->FirstStartColumn = 0;
2482 if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
2483 CurrentLines->append(
2484 std::make_move_iterator(PreprocessorDirectives.begin()),
2485 std::make_move_iterator(PreprocessorDirectives.end()));
2486 PreprocessorDirectives.clear();
2488 // Disconnect the current token from the last token on the previous line.
2489 FormatTok->Previous = nullptr;
2492 bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
2494 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
2495 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
2496 FormatTok.NewlinesBefore > 0;
2499 // Checks if \p FormatTok is a line comment that continues the line comment
2500 // section on \p Line.
2501 static bool continuesLineCommentSection(const FormatToken &FormatTok,
2502 const UnwrappedLine &Line,
2503 llvm::Regex &CommentPragmasRegex) {
2504 if (Line.Tokens.empty())
2507 StringRef IndentContent = FormatTok.TokenText;
2508 if (FormatTok.TokenText.startswith("//") ||
2509 FormatTok.TokenText.startswith("/*"))
2510 IndentContent = FormatTok.TokenText.substr(2);
2511 if (CommentPragmasRegex.match(IndentContent))
2514 // If Line starts with a line comment, then FormatTok continues the comment
2515 // section if its original column is greater or equal to the original start
2516 // column of the line.
2518 // Define the min column token of a line as follows: if a line ends in '{' or
2519 // contains a '{' followed by a line comment, then the min column token is
2520 // that '{'. Otherwise, the min column token of the line is the first token of
2523 // If Line starts with a token other than a line comment, then FormatTok
2524 // continues the comment section if its original column is greater than the
2525 // original start column of the min column token of the line.
2527 // For example, the second line comment continues the first in these cases:
2539 // int i; // first line
2544 // do { // first line
2557 // The second line comment doesn't continue the first in these cases:
2564 // int i; // first line
2569 // do { // first line
2580 const FormatToken *MinColumnToken = Line.Tokens.front().Tok;
2582 // Scan for '{//'. If found, use the column of '{' as a min column for line
2583 // comment section continuation.
2584 const FormatToken *PreviousToken = nullptr;
2585 for (const UnwrappedLineNode &Node : Line.Tokens) {
2586 if (PreviousToken && PreviousToken->is(tok::l_brace) &&
2587 isLineComment(*Node.Tok)) {
2588 MinColumnToken = PreviousToken;
2591 PreviousToken = Node.Tok;
2593 // Grab the last newline preceding a token in this unwrapped line.
2594 if (Node.Tok->NewlinesBefore > 0) {
2595 MinColumnToken = Node.Tok;
2598 if (PreviousToken && PreviousToken->is(tok::l_brace)) {
2599 MinColumnToken = PreviousToken;
2602 return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok,
2606 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
2607 bool JustComments = Line->Tokens.empty();
2608 for (SmallVectorImpl<FormatToken *>::const_iterator
2609 I = CommentsBeforeNextToken.begin(),
2610 E = CommentsBeforeNextToken.end();
2612 // Line comments that belong to the same line comment section are put on the
2613 // same line since later we might want to reflow content between them.
2614 // Additional fine-grained breaking of line comment sections is controlled
2615 // by the class BreakableLineCommentSection in case it is desirable to keep
2616 // several line comment sections in the same unwrapped line.
2618 // FIXME: Consider putting separate line comment sections as children to the
2619 // unwrapped line instead.
2620 (*I)->ContinuesLineCommentSection =
2621 continuesLineCommentSection(**I, *Line, CommentPragmasRegex);
2622 if (isOnNewLine(**I) && JustComments && !(*I)->ContinuesLineCommentSection)
2626 if (NewlineBeforeNext && JustComments)
2628 CommentsBeforeNextToken.clear();
2631 void UnwrappedLineParser::nextToken(int LevelDifference) {
2634 flushComments(isOnNewLine(*FormatTok));
2635 pushToken(FormatTok);
2636 FormatToken *Previous = FormatTok;
2637 if (Style.Language != FormatStyle::LK_JavaScript)
2638 readToken(LevelDifference);
2640 readTokenWithJavaScriptASI();
2641 FormatTok->Previous = Previous;
2644 void UnwrappedLineParser::distributeComments(
2645 const SmallVectorImpl<FormatToken *> &Comments,
2646 const FormatToken *NextTok) {
2647 // Whether or not a line comment token continues a line is controlled by
2648 // the method continuesLineCommentSection, with the following caveat:
2650 // Define a trail of Comments to be a nonempty proper postfix of Comments such
2651 // that each comment line from the trail is aligned with the next token, if
2652 // the next token exists. If a trail exists, the beginning of the maximal
2653 // trail is marked as a start of a new comment section.
2655 // For example in this code:
2657 // int a; // line about a
2658 // // line 1 about b
2659 // // line 2 about b
2662 // the two lines about b form a maximal trail, so there are two sections, the
2663 // first one consisting of the single comment "// line about a" and the
2664 // second one consisting of the next two comments.
2665 if (Comments.empty())
2667 bool ShouldPushCommentsInCurrentLine = true;
2668 bool HasTrailAlignedWithNextToken = false;
2669 unsigned StartOfTrailAlignedWithNextToken = 0;
2671 // We are skipping the first element intentionally.
2672 for (unsigned i = Comments.size() - 1; i > 0; --i) {
2673 if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) {
2674 HasTrailAlignedWithNextToken = true;
2675 StartOfTrailAlignedWithNextToken = i;
2679 for (unsigned i = 0, e = Comments.size(); i < e; ++i) {
2680 FormatToken *FormatTok = Comments[i];
2681 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
2682 FormatTok->ContinuesLineCommentSection = false;
2684 FormatTok->ContinuesLineCommentSection =
2685 continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex);
2687 if (!FormatTok->ContinuesLineCommentSection &&
2688 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
2689 ShouldPushCommentsInCurrentLine = false;
2691 if (ShouldPushCommentsInCurrentLine) {
2692 pushToken(FormatTok);
2694 CommentsBeforeNextToken.push_back(FormatTok);
2699 void UnwrappedLineParser::readToken(int LevelDifference) {
2700 SmallVector<FormatToken *, 1> Comments;
2702 FormatTok = Tokens->getNextToken();
2704 while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
2705 (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
2706 distributeComments(Comments, FormatTok);
2708 // If there is an unfinished unwrapped line, we flush the preprocessor
2709 // directives only after that unwrapped line was finished later.
2710 bool SwitchToPreprocessorLines = !Line->Tokens.empty();
2711 ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
2712 assert((LevelDifference >= 0 ||
2713 static_cast<unsigned>(-LevelDifference) <= Line->Level) &&
2714 "LevelDifference makes Line->Level negative");
2715 Line->Level += LevelDifference;
2716 // Comments stored before the preprocessor directive need to be output
2717 // before the preprocessor directive, at the same level as the
2718 // preprocessor directive, as we consider them to apply to the directive.
2719 if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash &&
2721 Line->Level += PPBranchLevel;
2722 flushComments(isOnNewLine(*FormatTok));
2725 while (FormatTok->Type == TT_ConflictStart ||
2726 FormatTok->Type == TT_ConflictEnd ||
2727 FormatTok->Type == TT_ConflictAlternative) {
2728 if (FormatTok->Type == TT_ConflictStart) {
2729 conditionalCompilationStart(/*Unreachable=*/false);
2730 } else if (FormatTok->Type == TT_ConflictAlternative) {
2731 conditionalCompilationAlternative();
2732 } else if (FormatTok->Type == TT_ConflictEnd) {
2733 conditionalCompilationEnd();
2735 FormatTok = Tokens->getNextToken();
2736 FormatTok->MustBreakBefore = true;
2739 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
2740 !Line->InPPDirective) {
2744 if (!FormatTok->Tok.is(tok::comment)) {
2745 distributeComments(Comments, FormatTok);
2750 Comments.push_back(FormatTok);
2753 distributeComments(Comments, nullptr);
2757 void UnwrappedLineParser::pushToken(FormatToken *Tok) {
2758 Line->Tokens.push_back(UnwrappedLineNode(Tok));
2759 if (MustBreakBeforeNextToken) {
2760 Line->Tokens.back().Tok->MustBreakBefore = true;
2761 MustBreakBeforeNextToken = false;
2765 } // end namespace format
2766 } // end namespace clang