21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/Support/raw_os_ostream.h"
25#include "llvm/Support/raw_ostream.h"
29#define DEBUG_TYPE "format-parser"
36void printLine(llvm::raw_ostream &OS,
const UnwrappedLine &
Line,
37 StringRef Prefix =
"",
bool PrintText =
false) {
38 OS << Prefix <<
"Line(" <<
Line.Level <<
", FSC=" <<
Line.FirstStartColumn
39 <<
")" << (
Line.InPPDirective ?
" MACRO" :
"") <<
": ";
41 for (std::list<UnwrappedLineNode>::const_iterator I =
Line.Tokens.begin(),
42 E =
Line.Tokens.end();
48 OS << I->Tok->Tok.getName() <<
"["
49 <<
"T=" << (
unsigned)I->Tok->getType()
50 <<
", OC=" << I->Tok->OriginalColumn <<
", \"" << I->Tok->TokenText
52 for (
const auto *CI = I->Children.begin(), *CE = I->Children.end();
55 printLine(OS, *CI, (Prefix +
" ").str());
63[[maybe_unused]]
static void printDebugInfo(
const UnwrappedLine &
Line) {
64 printLine(llvm::dbgs(),
Line);
67class ScopedDeclarationState {
69 ScopedDeclarationState(UnwrappedLine &
Line, llvm::BitVector &Stack,
70 bool MustBeDeclaration)
72 Line.MustBeDeclaration = MustBeDeclaration;
73 Stack.push_back(MustBeDeclaration);
75 ~ScopedDeclarationState() {
78 Line.MustBeDeclaration = Stack.back();
80 Line.MustBeDeclaration =
true;
85 llvm::BitVector &Stack;
91 llvm::raw_os_ostream OS(Stream);
99 bool SwitchToPreprocessorLines =
false)
100 : Parser(Parser), OriginalLines(Parser.CurrentLines) {
101 if (SwitchToPreprocessorLines)
102 Parser.CurrentLines = &Parser.PreprocessorDirectives;
103 else if (!Parser.Line->Tokens.empty())
104 Parser.CurrentLines = &Parser.Line->Tokens.back().Children;
105 PreBlockLine = std::move(Parser.Line);
106 Parser.Line = std::make_unique<UnwrappedLine>();
107 Parser.Line->Level = PreBlockLine->Level;
108 Parser.Line->PPLevel = PreBlockLine->PPLevel;
109 Parser.Line->InPPDirective = PreBlockLine->InPPDirective;
110 Parser.Line->InMacroBody = PreBlockLine->InMacroBody;
111 Parser.Line->UnbracedBodyLevel = PreBlockLine->UnbracedBodyLevel;
115 if (!Parser.Line->Tokens.empty())
116 Parser.addUnwrappedLine();
117 assert(Parser.Line->Tokens.empty());
118 Parser.Line = std::move(PreBlockLine);
119 if (Parser.CurrentLines == &Parser.PreprocessorDirectives)
120 Parser.AtEndOfPPLine =
true;
121 Parser.CurrentLines = OriginalLines;
127 std::unique_ptr<UnwrappedLine> PreBlockLine;
136 Style.BraceWrapping.AfterControlStatement ==
138 Style.BraceWrapping.IndentBraces) {}
140 bool WrapBrace,
bool IndentBrace)
141 : LineLevel(LineLevel), OldLineLevel(LineLevel) {
143 Parser->addUnwrappedLine();
151 unsigned OldLineLevel;
158 llvm::SpecificBumpPtrAllocator<FormatToken> &Allocator,
161 Style(Style), IsCpp(Style.isCpp()),
163 CommentPragmasRegex(Style.CommentPragmas), Tokens(
nullptr),
164 Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1),
165 IncludeGuard(getIncludeGuardState(Style.IndentPPDirectives)),
166 IncludeGuardToken(
nullptr), FirstStartColumn(FirstStartColumn),
167 Macros(Style.Macros, SourceMgr, Style, Allocator, IdentTable) {}
169void UnwrappedLineParser::reset() {
171 IncludeGuard = getIncludeGuardState(Style.IndentPPDirectives);
172 IncludeGuardToken =
nullptr;
174 CommentsBeforeNextToken.clear();
176 AtEndOfPPLine =
false;
177 IsDecltypeAutoFunction =
false;
178 PreprocessorDirectives.clear();
179 CurrentLines = &Lines;
180 DeclarationScopeStack.clear();
181 NestedTooDeep.clear();
182 NestedLambdas.clear();
184 Line->FirstStartColumn = FirstStartColumn;
186 if (!Unexpanded.empty())
188 Token->MacroCtx.reset();
189 CurrentExpandedLines.clear();
190 ExpandedLines.clear();
198 Line->FirstStartColumn = FirstStartColumn;
200 LLVM_DEBUG(llvm::dbgs() <<
"----\n");
202 Tokens = &TokenSource;
210 if (IncludeGuard == IG_Found) {
211 for (
auto &Line : Lines)
212 if (Line.InPPDirective && Line.Level > 0)
218 pushToken(FormatTok);
223 if (!ExpandedLines.empty()) {
224 LLVM_DEBUG(llvm::dbgs() <<
"Expanded lines:\n");
225 for (
const auto &Line : Lines) {
226 if (!Line.Tokens.empty()) {
227 auto it = ExpandedLines.find(Line.Tokens.begin()->Tok);
228 if (it != ExpandedLines.end()) {
229 for (
const auto &Expanded : it->second) {
230 LLVM_DEBUG(printDebugInfo(Expanded));
231 Callback.consumeUnwrappedLine(Expanded);
236 LLVM_DEBUG(printDebugInfo(Line));
237 Callback.consumeUnwrappedLine(Line);
239 Callback.finishRun();
242 LLVM_DEBUG(llvm::dbgs() <<
"Unwrapped lines:\n");
244 LLVM_DEBUG(printDebugInfo(Line));
245 Callback.consumeUnwrappedLine(Line);
247 Callback.finishRun();
249 while (!PPLevelBranchIndex.empty() &&
250 PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) {
251 PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1);
252 PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1);
254 if (!PPLevelBranchIndex.empty()) {
255 ++PPLevelBranchIndex.back();
256 assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size());
257 assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back());
259 }
while (!PPLevelBranchIndex.empty());
262void UnwrappedLineParser::parseFile() {
265 bool MustBeDeclaration = !
Line->InPPDirective && !Style.isJavaScript();
266 ScopedDeclarationState DeclarationState(*
Line, DeclarationScopeStack,
268 if (Style.isTextProto() || (Style.isJson() && FormatTok->
IsFirst))
282 if (Style.isTextProto() && !CommentsBeforeNextToken.empty())
288void UnwrappedLineParser::parseCSharpGenericTypeConstraint() {
298 parseCSharpGenericTypeConstraint();
307void UnwrappedLineParser::parseCSharpAttribute() {
308 int UnpairedSquareBrackets = 1;
310 switch (FormatTok->Tok.getKind()) {
313 --UnpairedSquareBrackets;
314 if (UnpairedSquareBrackets == 0) {
320 ++UnpairedSquareBrackets;
330bool UnwrappedLineParser::precededByCommentOrPPDirective()
const {
331 if (!Lines.empty() && Lines.back().InPPDirective)
345bool UnwrappedLineParser::parseLevel(
const FormatToken *OpeningBrace,
348 const bool InRequiresExpression =
349 OpeningBrace && OpeningBrace->is(TT_RequiresExpressionLBrace);
350 const bool IsPrecededByCommentOrPPDirective =
351 !Style.RemoveBracesLLVM || precededByCommentOrPPDirective();
353 bool HasDoWhile =
false;
354 bool HasLabel =
false;
355 unsigned StatementCount = 0;
356 bool SwitchLabelEncountered =
false;
359 if (FormatTok->isAttribute()) {
361 if (FormatTok->is(tok::l_paren))
366 if (FormatTok->is(TT_MacroBlockBegin))
368 else if (FormatTok->is(TT_MacroBlockEnd))
371 auto ParseDefault = [
this, OpeningBrace, IfKind, &IfLBrace, &HasDoWhile,
372 &HasLabel, &StatementCount] {
373 parseStructuralElement(OpeningBrace, IfKind, &IfLBrace,
374 HasDoWhile ?
nullptr : &HasDoWhile,
375 HasLabel ?
nullptr : &HasLabel);
377 assert(StatementCount > 0 &&
"StatementCount overflow!");
386 if (InRequiresExpression) {
387 FormatTok->setFinalizedType(TT_CompoundRequirementLBrace);
388 }
else if (FormatTok->Previous &&
389 FormatTok->Previous->ClosesRequiresClause) {
395 if (!InRequiresExpression && FormatTok->isNot(TT_MacroBlockBegin)) {
396 if (tryToParseBracedList())
398 FormatTok->setFinalizedType(TT_BlockLBrace);
402 assert(StatementCount > 0 &&
"StatementCount overflow!");
407 if (!Style.RemoveBracesLLVM || Line->InPPDirective ||
408 OpeningBrace->isNoneOf(TT_ControlStatementLBrace, TT_ElseLBrace)) {
411 if (FormatTok->isNot(tok::r_brace) || StatementCount != 1 || HasLabel ||
412 HasDoWhile || IsPrecededByCommentOrPPDirective ||
413 precededByCommentOrPPDirective()) {
417 if (
Next->is(tok::comment) &&
Next->NewlinesBefore == 0)
420 *IfLeftBrace = IfLBrace;
426 case tok::kw_default: {
427 unsigned StoredPosition = Tokens->getPosition();
428 auto *
Next = Tokens->getNextNonComment();
429 FormatTok = Tokens->setPosition(StoredPosition);
430 if (
Next->isNoneOf(tok::colon, tok::arrow)) {
433 parseStructuralElement();
441 (Style.isJavaScript() && Line->MustBeDeclaration)) {
449 if (!SwitchLabelEncountered &&
450 (Style.IndentCaseLabels ||
451 (OpeningBrace && OpeningBrace->is(TT_SwitchExpressionLBrace)) ||
452 (Line->InPPDirective && Line->Level == 1))) {
455 SwitchLabelEncountered =
true;
456 parseStructuralElement();
459 if (Style.isCSharp()) {
461 parseCSharpAttribute();
464 if (handleCppAttributes())
476void UnwrappedLineParser::calculateBraceTypes(
bool ExpectClassBody) {
481 unsigned StoredPosition = Tokens->getPosition();
491 SmallVector<StackEntry, 8> LBraceStack;
492 assert(
Tok->is(tok::l_brace));
495 auto *NextTok = Tokens->getNextNonComment();
497 if (!Line->InMacroBody && !Style.isTableGen()) {
499 while (NextTok->is(tok::hash)) {
500 NextTok = Tokens->getNextToken();
501 if (NextTok->isOneOf(tok::pp_not_keyword, tok::pp_define))
504 NextTok = Tokens->getNextToken();
505 }
while (!NextTok->HasUnescapedNewline && NextTok->isNot(tok::eof));
507 while (NextTok->is(tok::comment))
508 NextTok = Tokens->getNextToken();
512 switch (
Tok->Tok.getKind()) {
514 if (Style.isJavaScript() && PrevTok) {
515 if (PrevTok->isOneOf(tok::colon, tok::less)) {
526 }
else if (PrevTok->is(tok::r_paren)) {
530 }
else if (Style.isJava() && PrevTok && PrevTok->is(tok::arrow)) {
535 LBraceStack.push_back({
Tok, PrevTok});
538 if (LBraceStack.empty())
540 if (
auto *LBrace = LBraceStack.back().Tok; LBrace->is(
BK_Unknown)) {
541 bool ProbablyBracedList =
false;
543 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
544 }
else if (LBrace->isNot(TT_EnumLBrace)) {
547 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
548 NextTok->OriginalColumn == 0;
558 ProbablyBracedList = LBrace->is(TT_BracedListLBrace);
560 ProbablyBracedList = ProbablyBracedList ||
561 (Style.isJavaScript() &&
562 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
565 ProbablyBracedList ||
566 (IsCpp && (PrevTok->Tok.isLiteral() ||
567 NextTok->isOneOf(tok::l_paren, tok::arrow)));
574 ProbablyBracedList ||
575 NextTok->isOneOf(tok::comma, tok::period, tok::colon,
576 tok::r_paren, tok::r_square, tok::ellipsis);
581 ProbablyBracedList ||
582 (NextTok->is(tok::l_brace) && LBraceStack.back().PrevTok &&
583 LBraceStack.back().PrevTok->isOneOf(tok::identifier,
587 ProbablyBracedList ||
588 (NextTok->is(tok::identifier) &&
589 PrevTok->isNoneOf(tok::semi, tok::r_brace, tok::l_brace));
591 ProbablyBracedList = ProbablyBracedList ||
592 (NextTok->is(tok::semi) &&
593 (!ExpectClassBody || LBraceStack.size() != 1));
596 ProbablyBracedList ||
597 (NextTok->isBinaryOperator() && !NextIsObjCMethod);
599 if (!Style.isCSharp() && NextTok->is(tok::l_square)) {
602 NextTok = Tokens->getNextToken();
603 ProbablyBracedList = NextTok->isNot(tok::l_square);
607 if (IsCpp && Line->InMacroBody && PrevTok != FormatTok &&
608 !FormatTok->Previous && NextTok->is(tok::eof) &&
612 PrevTok->isNoneOf(tok::semi,
BK_Block, tok::colon)) {
613 ProbablyBracedList =
true;
617 Tok->setBlockKind(BlockKind);
618 LBrace->setBlockKind(BlockKind);
620 LBraceStack.pop_back();
622 case tok::identifier:
623 if (
Tok->isNot(TT_StatementMacro))
634 if (!LBraceStack.empty() && LBraceStack.back().Tok->is(
BK_Unknown))
635 LBraceStack.back().Tok->setBlockKind(
BK_Block);
643 }
while (
Tok->isNot(tok::eof) && !LBraceStack.empty());
646 for (
const auto &Entry : LBraceStack)
650 FormatTok = Tokens->setPosition(StoredPosition);
654void UnwrappedLineParser::setPreviousRBraceType(
TokenType Type) {
655 if (
auto Prev = FormatTok->getPreviousNonComment();
656 Prev && Prev->is(tok::r_brace)) {
657 Prev->setFinalizedType(
Type);
664 seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
667size_t UnwrappedLineParser::computePPHash()
const {
669 for (
const auto &i : PPStack) {
680bool UnwrappedLineParser::mightFitOnOneLine(
682 const auto ColumnLimit = Style.ColumnLimit;
683 if (ColumnLimit == 0)
686 auto &Tokens = ParsedLine.Tokens;
687 assert(!Tokens.empty());
689 const auto *LastToken = Tokens.back().Tok;
692 SmallVector<UnwrappedLineNode> SavedTokens(Tokens.size());
695 for (
const auto &Token : Tokens) {
697 auto &SavedToken = SavedTokens[Index++];
699 SavedToken.Tok->copyFrom(*Token.Tok);
700 SavedToken.Children = std::move(Token.Children);
703 AnnotatedLine
Line(ParsedLine);
704 assert(Line.Last == LastToken);
706 TokenAnnotator Annotator(Style, Keywords);
707 Annotator.annotate(Line);
708 Annotator.calculateFormattingInformation(Line);
710 auto Length = LastToken->TotalLength;
712 assert(OpeningBrace != Tokens.front().Tok);
713 if (
auto Prev = OpeningBrace->Previous;
714 Prev && Prev->TotalLength + ColumnLimit == OpeningBrace->TotalLength) {
715 Length -= ColumnLimit;
717 Length -= OpeningBrace->TokenText.size() + 1;
720 if (
const auto *FirstToken = Line.First; FirstToken->is(tok::r_brace)) {
721 assert(!OpeningBrace || OpeningBrace->is(TT_ControlStatementLBrace));
722 Length -= FirstToken->TokenText.size() + 1;
726 for (
auto &Token : Tokens) {
727 const auto &SavedToken = SavedTokens[Index++];
728 Token.Tok->copyFrom(*SavedToken.Tok);
729 Token.Children = std::move(SavedToken.Children);
730 delete SavedToken.Tok;
734 assert(!Line.InMacroBody);
735 assert(!Line.InPPDirective);
736 return Line.Level * Style.IndentWidth + Length <= ColumnLimit;
739FormatToken *UnwrappedLineParser::parseBlock(
bool MustBeDeclaration,
740 unsigned AddLevels,
bool MunchSemi,
743 bool UnindentWhitesmithsBraces) {
744 auto HandleVerilogBlockLabel = [
this]() {
746 if (Style.isVerilog() && FormatTok->is(tok::colon)) {
748 if (Keywords.isVerilogIdentifier(*FormatTok))
755 const bool VerilogHierarchy =
756 Style.isVerilog() && Keywords.isVerilogHierarchy(*FormatTok);
757 assert((FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) ||
758 (Style.isVerilog() &&
759 (Keywords.isVerilogBegin(*FormatTok) || VerilogHierarchy))) &&
760 "'{' or macro block token expected");
762 const bool FollowedByComment = Tokens->peekNextToken()->is(tok::comment);
763 auto Index = CurrentLines->size();
764 const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
767 const bool IsWhitesmiths =
772 if (!VerilogHierarchy && AddLevels > 0 && IsWhitesmiths)
775 size_t PPStartHash = computePPHash();
777 const unsigned InitialLevel = Line->Level;
778 if (VerilogHierarchy) {
779 AddLevels += parseVerilogHierarchyHeader();
781 nextToken(AddLevels);
782 HandleVerilogBlockLabel();
786 if (Line->Level > 300)
789 if (MacroBlock && FormatTok->is(tok::l_paren))
792 size_t NbPreprocessorDirectives =
793 !parsingPPDirective() ? PreprocessorDirectives.size() : 0;
795 size_t OpeningLineIndex =
796 CurrentLines->empty()
798 : (CurrentLines->size() - 1 - NbPreprocessorDirectives);
803 if (UnindentWhitesmithsBraces)
806 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
812 Line->Level += AddLevels - (IsWhitesmiths ? 1 : 0);
815 const bool SimpleBlock = parseLevel(
Tok, IfKind, &IfLBrace);
820 if (MacroBlock ? FormatTok->isNot(TT_MacroBlockEnd)
821 : FormatTok->isNot(tok::r_brace)) {
822 Line->Level = InitialLevel;
823 FormatTok->setBlockKind(BK_Block);
827 if (FormatTok->is(tok::r_brace)) {
828 FormatTok->setBlockKind(BK_Block);
829 if (Tok->is(TT_NamespaceLBrace))
830 FormatTok->setFinalizedType(TT_NamespaceRBrace);
833 const bool IsFunctionRBrace =
834 FormatTok->is(tok::r_brace) &&
Tok->is(TT_FunctionLBrace);
836 auto RemoveBraces = [=]()
mutable {
839 assert(Tok->isOneOf(TT_ControlStatementLBrace, TT_ElseLBrace));
840 assert(FormatTok->is(tok::r_brace));
841 const bool WrappedOpeningBrace = !Tok->Previous;
842 if (WrappedOpeningBrace && FollowedByComment)
844 const bool HasRequiredIfBraces = IfLBrace && !IfLBrace->Optional;
845 if (KeepBraces && !HasRequiredIfBraces)
847 if (Tok->isNot(TT_ElseLBrace) || !HasRequiredIfBraces) {
848 const FormatToken *Previous = Tokens->getPreviousToken();
850 if (Previous->is(tok::r_brace) && !Previous->Optional)
853 assert(!CurrentLines->empty());
854 auto &LastLine = CurrentLines->back();
855 if (LastLine.Level == InitialLevel + 1 && !mightFitOnOneLine(LastLine))
857 if (
Tok->is(TT_ElseLBrace))
859 if (WrappedOpeningBrace) {
864 return mightFitOnOneLine((*CurrentLines)[Index],
Tok);
866 if (RemoveBraces()) {
867 Tok->MatchingParen = FormatTok;
868 FormatTok->MatchingParen =
Tok;
871 size_t PPEndHash = computePPHash();
874 nextToken(-AddLevels);
879 if (Style.RemoveSemicolon && IsFunctionRBrace) {
880 while (FormatTok->is(tok::semi)) {
881 FormatTok->Optional =
true;
886 HandleVerilogBlockLabel();
888 if (MacroBlock && FormatTok->is(tok::l_paren))
891 Line->Level = InitialLevel;
893 if (FormatTok->is(tok::kw_noexcept)) {
898 if (FormatTok->is(tok::arrow)) {
902 parseStructuralElement();
905 if (MunchSemi && FormatTok->is(tok::semi))
908 if (PPStartHash == PPEndHash) {
909 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
912 (*CurrentLines)[OpeningLineIndex].MatchingClosingBlockLineIndex =
913 CurrentLines->size() - 1;
923 if (
Line.Tokens.size() < 4)
925 auto I =
Line.Tokens.begin();
926 if (I->Tok->TokenText !=
"goog")
929 if (I->Tok->isNot(tok::period))
932 if (I->Tok->TokenText !=
"scope")
935 return I->Tok->is(tok::l_paren);
944 if (
Line.Tokens.size() < 3)
946 auto I =
Line.Tokens.begin();
947 if (I->Tok->isNot(tok::l_paren))
953 return I->Tok->is(tok::l_paren);
959 bool IsJavaRecord =
false) {
961 return Style.BraceWrapping.AfterClass;
964 if (InitialToken.
is(TT_NamespaceMacro))
965 Kind = tok::kw_namespace;
967 const bool WrapRecordAllowed =
970 Style.BraceWrapping.SplitEmptyRecord;
973 case tok::kw_namespace:
974 return Style.BraceWrapping.AfterNamespace;
976 return Style.BraceWrapping.AfterClass && WrapRecordAllowed;
978 return Style.BraceWrapping.AfterUnion && WrapRecordAllowed;
980 return Style.BraceWrapping.AfterStruct && WrapRecordAllowed;
982 return Style.BraceWrapping.AfterEnum;
988void UnwrappedLineParser::parseChildBlock() {
989 assert(FormatTok->is(tok::l_brace));
990 FormatTok->setBlockKind(BK_Block);
994 bool SkipIndent = (Style.isJavaScript() &&
995 (isGoogScope(*
Line) || isIIFE(*
Line, Keywords)));
996 ScopedLineState LineState(*
this);
997 ScopedDeclarationState DeclarationState(*
Line, DeclarationScopeStack,
999 Line->Level += SkipIndent ? 0 : 1;
1000 parseLevel(OpeningBrace);
1001 flushComments(isOnNewLine(*FormatTok));
1002 Line->Level -= SkipIndent ? 0 : 1;
1007void UnwrappedLineParser::parsePPDirective() {
1008 assert(FormatTok->is(tok::hash) &&
"'#' expected");
1009 ScopedMacroState MacroState(*
Line, Tokens, FormatTok);
1013 if (!FormatTok->Tok.getIdentifierInfo()) {
1018 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
1019 case tok::pp_define:
1026 case tok::pp_ifndef:
1030 case tok::pp_elifdef:
1031 case tok::pp_elifndef:
1038 case tok::pp_pragma:
1042 case tok::pp_warning:
1044 if (!
eof() && Style.isCpp())
1045 FormatTok->setFinalizedType(TT_AfterPPDirective);
1053void UnwrappedLineParser::conditionalCompilationCondition(
bool Unreachable) {
1054 size_t Line = CurrentLines->size();
1055 if (CurrentLines == &PreprocessorDirectives)
1056 Line += Lines.size();
1059 (!PPStack.empty() && PPStack.back().Kind == PP_Unreachable)) {
1060 PPStack.push_back({PP_Unreachable,
Line});
1062 PPStack.push_back({PP_Conditional,
Line});
1066void UnwrappedLineParser::conditionalCompilationStart(
bool Unreachable) {
1068 assert(PPBranchLevel >= 0 && PPBranchLevel <= (
int)PPLevelBranchIndex.size());
1069 if (PPBranchLevel == (
int)PPLevelBranchIndex.size()) {
1070 PPLevelBranchIndex.push_back(0);
1071 PPLevelBranchCount.push_back(0);
1073 PPChainBranchIndex.push(Unreachable ? -1 : 0);
1074 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
1075 conditionalCompilationCondition(Unreachable ||
Skip);
1078void UnwrappedLineParser::conditionalCompilationAlternative() {
1079 if (!PPStack.empty())
1081 assert(PPBranchLevel < (
int)PPLevelBranchIndex.size());
1082 if (!PPChainBranchIndex.empty())
1083 ++PPChainBranchIndex.top();
1084 conditionalCompilationCondition(
1085 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
1086 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
1089void UnwrappedLineParser::conditionalCompilationEnd() {
1090 assert(PPBranchLevel < (
int)PPLevelBranchIndex.size());
1091 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
1092 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel])
1093 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
1096 if (PPBranchLevel > -1)
1098 if (!PPChainBranchIndex.empty())
1099 PPChainBranchIndex.pop();
1100 if (!PPStack.empty())
1104void UnwrappedLineParser::parsePPIf(
bool IfDef) {
1105 bool IfNDef = FormatTok->is(tok::pp_ifndef);
1107 bool Unreachable =
false;
1108 if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText ==
"0"))
1110 if (IfDef && !IfNDef && FormatTok->TokenText ==
"SWIG")
1112 conditionalCompilationStart(Unreachable);
1116 bool MaybeIncludeGuard = IfNDef;
1117 if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
1118 for (
auto &
Line : Lines) {
1119 if (
Line.Tokens.front().Tok->isNot(tok::comment)) {
1120 MaybeIncludeGuard =
false;
1121 IncludeGuard = IG_Rejected;
1129 if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
1130 IncludeGuard = IG_IfNdefed;
1131 IncludeGuardToken = IfCondition;
1135void UnwrappedLineParser::parsePPElse() {
1137 if (IncludeGuard == IG_Defined && PPBranchLevel == 0)
1138 IncludeGuard = IG_Rejected;
1140 assert(PPBranchLevel >= -1);
1141 if (PPBranchLevel == -1)
1142 conditionalCompilationStart(
true);
1143 conditionalCompilationAlternative();
1149void UnwrappedLineParser::parsePPEndIf() {
1150 conditionalCompilationEnd();
1154void UnwrappedLineParser::parsePPDefine() {
1157 if (!FormatTok->Tok.getIdentifierInfo()) {
1158 IncludeGuard = IG_Rejected;
1159 IncludeGuardToken =
nullptr;
1164 bool MaybeIncludeGuard =
false;
1165 if (IncludeGuard == IG_IfNdefed &&
1166 IncludeGuardToken->TokenText == FormatTok->TokenText) {
1167 IncludeGuard = IG_Defined;
1168 IncludeGuardToken =
nullptr;
1169 for (
auto &
Line : Lines) {
1170 if (
Line.Tokens.front().Tok->isNoneOf(tok::comment, tok::hash)) {
1171 IncludeGuard = IG_Rejected;
1175 MaybeIncludeGuard = IncludeGuard == IG_Defined;
1183 FormatTok->Tok.setKind(tok::identifier);
1184 FormatTok->Tok.setIdentifierInfo(Keywords.kw_internal_ident_after_define);
1188 if (MaybeIncludeGuard && !
eof())
1189 IncludeGuard = IG_Rejected;
1191 if (FormatTok->is(tok::l_paren) && !FormatTok->hasWhitespaceBefore())
1194 Line->Level += PPBranchLevel + 1;
1198 Line->PPLevel = PPBranchLevel + (IncludeGuard == IG_Defined ? 0 : 1);
1199 assert((
int)
Line->PPLevel >= 0);
1204 Line->InMacroBody =
true;
1206 if (!Style.SkipMacroDefinitionBody) {
1216 for (
auto *Comment : CommentsBeforeNextToken)
1217 Comment->Finalized =
true;
1220 FormatTok->Finalized =
true;
1221 FormatTok = Tokens->getNextToken();
1227void UnwrappedLineParser::parsePPPragma() {
1228 Line->InPragmaDirective =
true;
1232void UnwrappedLineParser::parsePPUnknown() {
1236 Line->Level += PPBranchLevel + 1;
1246 return Tok.isNoneOf(tok::semi, tok::l_brace,
1249 tok::period, tok::periodstar, tok::arrow, tok::arrowstar,
1250 tok::less, tok::greater, tok::slash, tok::percent,
1251 tok::lessless, tok::greatergreater, tok::equal,
1252 tok::plusequal, tok::minusequal, tok::starequal,
1253 tok::slashequal, tok::percentequal, tok::ampequal,
1254 tok::pipeequal, tok::caretequal, tok::greatergreaterequal,
1267 return FormatTok->
is(tok::identifier) &&
1282 FormatTok->
isOneOf(tok::kw_true, tok::kw_false) ||
1293 tok::kw_if, tok::kw_else,
1295 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
1297 tok::kw_switch, tok::kw_case,
1299 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.
kw_finally,
1301 tok::kw_const, tok::kw_class, Keywords.
kw_var, Keywords.
kw_let,
1309 return Tok.isOneOf(tok::kw_char, tok::kw_short, tok::kw_int, tok::kw_long,
1310 tok::kw_unsigned, tok::kw_float, tok::kw_double,
1327 if (FuncName->
isNot(tok::identifier))
1335 Tok->isNoneOf(tok::kw_register, tok::kw_struct, tok::kw_union)) {
1339 if (
Next->isNot(tok::star) && !
Next->Tok.getIdentifierInfo())
1343 if (!
Tok ||
Tok->isNot(tok::r_paren))
1347 if (!
Tok ||
Tok->isNot(tok::identifier))
1350 return Tok->Previous &&
Tok->Previous->isOneOf(tok::l_paren, tok::comma);
1353bool UnwrappedLineParser::parseModuleDecl() {
1355 assert(FormatTok->is(Keywords.kw_module));
1363 if (FormatTok->isNot(tok::identifier))
1366 for (nextToken(); FormatTok->isNoneOf(tok::semi, tok::eof); nextToken())
1367 if (FormatTok->is(tok::colon))
1368 FormatTok->setFinalizedType(TT_ModulePartitionColon);
1371 Line->IsModuleOrImportDecl =
true;
1376bool UnwrappedLineParser::parseImportDecl() {
1378 assert(FormatTok->is(Keywords.kw_import) &&
"'import' expected");
1386 if (FormatTok->is(tok::colon)) {
1387 FormatTok->setFinalizedType(TT_ModulePartitionColon);
1390 if (FormatTok->isNoneOf(tok::identifier, tok::less, tok::string_literal))
1393 for (; FormatTok->isNoneOf(tok::semi, tok::eof); nextToken()) {
1395 if (FormatTok->is(tok::less)) {
1396 for (nextToken(); FormatTok->isNoneOf(tok::greater, tok::semi, tok::eof);
1400 FormatTok->setFinalizedType(TT_ImplicitStringLiteral);
1406 Line->IsModuleOrImportDecl =
true;
1418void UnwrappedLineParser::readTokenWithJavaScriptASI() {
1424 CommentsBeforeNextToken.empty()
1425 ?
Next->NewlinesBefore == 0
1426 : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
1431 bool PreviousStartsTemplateExpr =
1433 if (PreviousMustBeValue ||
Previous->is(tok::r_paren)) {
1436 bool HasAt = llvm::any_of(
Line->Tokens, [](UnwrappedLineNode &LineNode) {
1437 return LineNode.Tok->is(tok::at);
1442 if (
Next->is(tok::exclaim) && PreviousMustBeValue)
1443 return addUnwrappedLine();
1445 bool NextEndsTemplateExpr =
1446 Next->is(TT_TemplateString) &&
Next->TokenText.starts_with(
"}");
1447 if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
1448 (PreviousMustBeValue ||
1449 Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
1450 tok::minusminus))) {
1451 return addUnwrappedLine();
1453 if ((PreviousMustBeValue ||
Previous->is(tok::r_paren)) &&
1455 return addUnwrappedLine();
1459void UnwrappedLineParser::parseStructuralElement(
1460 const FormatToken *OpeningBrace, IfStmtKind *IfKind,
1461 FormatToken **IfLeftBrace,
bool *HasDoWhile,
bool *HasLabel) {
1462 if (Style.isTableGen() && FormatTok->is(tok::pp_include)) {
1464 if (FormatTok->is(tok::string_literal))
1471 while (FormatTok->is(tok::l_square) && handleCppAttributes()) {
1473 }
else if (Style.isVerilog()) {
1475 while (FormatTok->is(tok::l_paren) &&
1476 Tokens->peekNextToken()->is(tok::star)) {
1479 skipVerilogQualifiers();
1481 if (FormatTok->isOneOf(Keywords.kw_priority, Keywords.kw_unique,
1482 Keywords.kw_unique0)) {
1486 if (Keywords.isVerilogStructuredProcedure(*FormatTok)) {
1487 parseForOrWhileLoop(
false);
1490 if (FormatTok->isOneOf(Keywords.kw_foreach, Keywords.kw_repeat)) {
1491 parseForOrWhileLoop();
1494 if (FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
1495 Keywords.kw_assume, Keywords.kw_cover)) {
1496 parseIfThenElse(IfKind,
false,
true);
1502 if (FormatTok->isAccessSpecifierKeyword()) {
1503 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp())
1506 parseAccessSpecifier();
1509 switch (FormatTok->Tok.getKind()) {
1514 bool DoNotFormat =
false;
1519 FormatTok->isOneOf(tok::kw_volatile, tok::kw_inline, tok::kw_goto)) {
1524 if (FormatTok->is(tok::l_brace)) {
1525 FormatTok->setFinalizedType(TT_InlineASMBrace);
1526 OpenType = tok::l_brace;
1527 CloseType = tok::r_brace;
1529 }
else if (FormatTok->is(tok::l_paren)) {
1530 OpenType = tok::l_paren;
1531 CloseType = tok::r_paren;
1532 FormatTok->setFinalizedType(TT_InlineASMParen);
1540 while (FormatTok && !
eof()) {
1541 if (FormatTok->is(OpenType)) {
1543 }
else if (FormatTok->is(CloseType)) {
1545 if (NestLevel < 1) {
1546 FormatTok->setFinalizedType(OpenTok->getType());
1552 FormatTok->Finalized =
true;
1558 case tok::kw_namespace:
1562 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1573 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1577 parseForOrWhileLoop();
1580 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1588 case tok::kw_switch:
1589 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1595 case tok::kw_default: {
1597 if (Style.isVerilog())
1599 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1605 if (FormatTok->is(tok::colon)) {
1606 FormatTok->setFinalizedType(TT_CaseLabelColon);
1610 if (FormatTok->is(tok::arrow)) {
1611 FormatTok->setFinalizedType(TT_CaseLabelArrow);
1612 Default->setFinalizedType(TT_SwitchExpressionLabel);
1625 if (Style.isVerilog()) {
1630 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1639 if (FormatTok->is(tok::kw_case))
1644 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1650 case tok::kw_extern:
1651 if (Style.isVerilog()) {
1654 parseVerilogExtern();
1658 if (FormatTok->is(tok::string_literal)) {
1660 if (FormatTok->is(tok::l_brace)) {
1661 if (Style.BraceWrapping.AfterExternBlock)
1665 unsigned AddLevels =
1667 (Style.BraceWrapping.AfterExternBlock &&
1668 Style.IndentExternBlock ==
1672 parseBlock(
true, AddLevels);
1678 case tok::kw_export:
1681 if (FormatTok->is(tok::kw_namespace)) {
1685 if (FormatTok->is(tok::l_brace)) {
1686 parseCppExportBlock();
1689 if (FormatTok->is(Keywords.kw_module) && parseModuleDecl())
1691 if (FormatTok->is(Keywords.kw_import) && parseImportDecl())
1695 if (Style.isJavaScript()) {
1696 parseJavaScriptEs6ImportExport();
1699 if (Style.isVerilog()) {
1700 parseVerilogExtern();
1704 case tok::kw_inline:
1706 if (FormatTok->is(tok::kw_namespace)) {
1711 case tok::identifier:
1712 if (FormatTok->is(TT_ForEachMacro)) {
1713 parseForOrWhileLoop();
1716 if (FormatTok->is(TT_MacroBlockBegin)) {
1717 parseBlock(
false, 1u,
1721 if (FormatTok->is(Keywords.kw_import)) {
1722 if (IsCpp && parseImportDecl())
1724 if (Style.isJavaScript()) {
1725 parseJavaScriptEs6ImportExport();
1730 if (FormatTok->is(tok::kw_public))
1732 if (FormatTok->isNot(tok::string_literal))
1735 if (FormatTok->is(tok::semi))
1740 if (Style.isVerilog()) {
1741 parseVerilogExtern();
1746 if (FormatTok->is(Keywords.kw_module) && parseModuleDecl())
1748 if (FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
1749 Keywords.kw_slots, Keywords.kw_qslots)) {
1751 if (FormatTok->is(tok::colon)) {
1757 if (FormatTok->is(TT_StatementMacro)) {
1758 parseStatementMacro();
1761 if (FormatTok->is(TT_NamespaceMacro)) {
1770 if (!Style.isJavaScript() && !Style.isVerilog() && !Style.isTableGen() &&
1771 Tokens->peekNextToken()->is(tok::colon) && !
Line->MustBeDeclaration) {
1773 if (!
Line->InMacroBody || CurrentLines->size() > 1)
1774 Line->Tokens.begin()->Tok->MustBreakBefore =
true;
1775 FormatTok->setFinalizedType(TT_GotoLabelColon);
1781 if (Style.isJava() && FormatTok->is(Keywords.kw_record)) {
1782 parseRecord(
false,
true);
1792 bool SeenEqual =
false;
1793 for (
const bool InRequiresExpression =
1794 OpeningBrace && OpeningBrace->isOneOf(TT_RequiresExpressionLBrace,
1795 TT_CompoundRequirementLBrace);
1798 switch (FormatTok->Tok.getKind()) {
1801 if (FormatTok->is(tok::l_brace)) {
1806 if (Style.isJava() && FormatTok->is(Keywords.kw_interface)) {
1810 switch (
bool IsAutoRelease =
false; FormatTok->Tok.getObjCKeywordID()) {
1811 case tok::objc_public:
1812 case tok::objc_protected:
1813 case tok::objc_package:
1814 case tok::objc_private:
1815 return parseAccessSpecifier();
1816 case tok::objc_interface:
1817 case tok::objc_implementation:
1818 return parseObjCInterfaceOrImplementation();
1819 case tok::objc_protocol:
1820 if (parseObjCProtocol())
1825 case tok::objc_optional:
1826 case tok::objc_required:
1830 case tok::objc_autoreleasepool:
1831 IsAutoRelease =
true;
1833 case tok::objc_synchronized:
1835 if (!IsAutoRelease && FormatTok->is(tok::l_paren)) {
1839 if (FormatTok->is(tok::l_brace)) {
1840 if (Style.BraceWrapping.AfterControlStatement ==
1857 case tok::kw_requires: {
1859 bool ParsedClause = parseRequires(SeenEqual);
1880 if (!IsCpp && !Style.isVerilog()) {
1885 case tok::kw_typedef:
1887 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1888 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS,
1889 Keywords.kw_CF_CLOSED_ENUM,
1890 Keywords.kw_NS_CLOSED_ENUM)) {
1895 if (Style.isVerilog()) {
1900 if (Style.isTableGen()) {
1907 case tok::kw_struct:
1909 if (parseStructLike())
1912 case tok::kw_decltype:
1914 if (FormatTok->is(tok::l_paren)) {
1916 if (FormatTok->Previous &&
1917 FormatTok->Previous->endsSequence(tok::r_paren, tok::kw_auto,
1919 Line->SeenDecltypeAuto =
true;
1926 if (Style.isJava() && FormatTok && FormatTok->is(tok::kw_class))
1928 if (Style.isJavaScript() && FormatTok &&
1929 FormatTok->Tok.getIdentifierInfo()) {
1942 case tok::string_literal:
1943 if (Style.isVerilog() && FormatTok->is(TT_VerilogProtected)) {
1944 FormatTok->Finalized =
true;
1951 case tok::l_paren: {
1958 Tokens->peekNextToken(
true),
1965 case tok::kw_operator:
1967 if (FormatTok->isBinaryOperator())
1971 const auto *Prev = FormatTok->getPreviousNonComment();
1973 if (Prev && Prev->is(tok::identifier))
1976 if (FormatTok->Tok.isAnyIdentifier() || FormatTok->isTypeName(LangOpts)) {
1979 while (FormatTok->is(tok::star))
1983 if (FormatTok->is(tok::l_paren))
1986 if (FormatTok->is(tok::l_brace))
1991 if (InRequiresExpression)
1992 FormatTok->setFinalizedType(TT_BracedListLBrace);
1993 if (!tryToParsePropertyAccessor() && !tryToParseBracedList()) {
1994 IsDecltypeAutoFunction =
Line->SeenDecltypeAuto;
1999 if (Style.isJava() &&
2000 Line->Tokens.front().Tok->is(Keywords.kw_synchronized)) {
2003 if (Style.BraceWrapping.AfterControlStatement ==
2007 }
else if (Style.BraceWrapping.AfterFunction) {
2011 FormatTok->setFinalizedType(TT_FunctionLBrace);
2013 IsDecltypeAutoFunction =
false;
2021 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
2027 if (Style.BraceWrapping.AfterFunction)
2031 case tok::identifier: {
2032 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where) &&
2033 Line->MustBeDeclaration) {
2035 parseCSharpGenericTypeConstraint();
2038 if (FormatTok->is(TT_MacroBlockEnd)) {
2047 size_t TokenCount =
Line->Tokens.size();
2048 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_function) &&
2051 Line->Tokens.front().Tok->isNot(Keywords.kw_async)))) {
2052 tryToParseJSFunction();
2055 if ((Style.isJavaScript() || Style.isJava()) &&
2056 FormatTok->is(Keywords.kw_interface)) {
2057 if (Style.isJavaScript()) {
2062 unsigned StoredPosition = Tokens->getPosition();
2064 FormatTok = Tokens->setPosition(StoredPosition);
2075 if (Style.isVerilog()) {
2076 if (FormatTok->is(Keywords.kw_table)) {
2077 parseVerilogTable();
2080 if (Keywords.isVerilogBegin(*FormatTok) ||
2081 Keywords.isVerilogHierarchy(*FormatTok)) {
2088 if (!IsCpp && FormatTok->is(Keywords.kw_interface)) {
2089 if (parseStructLike())
2094 if (IsCpp && FormatTok->is(TT_StatementMacro)) {
2095 parseStatementMacro();
2100 StringRef
Text = FormatTok->TokenText;
2107 if (Style.isJavaScript())
2110 auto OneTokenSoFar = [&]() {
2111 auto I =
Line->Tokens.begin(), E =
Line->Tokens.end();
2112 while (I != E && I->Tok->is(tok::comment))
2114 if (Style.isVerilog())
2115 while (I != E && I->Tok->is(tok::hash))
2117 return I != E && (++I == E);
2119 if (OneTokenSoFar()) {
2122 bool FunctionLike = FormatTok->is(tok::l_paren);
2126 bool FollowedByNewline =
2127 CommentsBeforeNextToken.empty()
2128 ? FormatTok->NewlinesBefore > 0
2129 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
2131 if (FollowedByNewline &&
2132 (
Text.size() >= 5 ||
2133 (FunctionLike && FormatTok->isNot(tok::l_paren))) &&
2135 if (PreviousToken->isNot(TT_UntouchableMacroFunc))
2136 PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro);
2144 if ((Style.isJavaScript() || Style.isCSharp()) &&
2145 FormatTok->is(TT_FatArrow)) {
2146 tryToParseChildBlock();
2152 if (FormatTok->is(tok::l_brace)) {
2156 if (!Style.isJavaScript())
2157 FormatTok->setBlockKind(BK_BracedInit);
2160 if (Style.isTableGen() &&
2161 Line->Tokens.begin()->Tok->is(Keywords.kw_defset)) {
2162 FormatTok->setFinalizedType(TT_FunctionLBrace);
2163 parseBlock(
false, 1u,
2171 FormatTok->is(tok::less)) {
2173 parseBracedList(
true);
2180 if (Style.isCSharp() &&
2181 (Tokens->peekNextToken()->isAccessSpecifierKeyword() ||
2188 case tok::kw_switch:
2201 if (Style.isVerilog()) {
2206 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
2213 case tok::kw_default:
2215 if (Style.isVerilog()) {
2216 if (FormatTok->is(tok::colon)) {
2220 if (FormatTok->is(Keywords.kw_clocking)) {
2226 parseVerilogCaseLabel();
2232 if (Style.isVerilog()) {
2233 parseVerilogCaseLabel();
2239 if (FormatTok->is(tok::l_brace))
2240 FormatTok->Previous->setFinalizedType(TT_TemplateCloser);
2249bool UnwrappedLineParser::tryToParsePropertyAccessor() {
2250 assert(FormatTok->is(tok::l_brace));
2251 if (!Style.isCSharp())
2254 if (!FormatTok->Previous || FormatTok->Previous->isNot(tok::identifier))
2262 unsigned int StoredPosition = Tokens->getPosition();
2268 bool HasSpecialAccessor =
false;
2269 bool IsTrivialPropertyAccessor =
true;
2272 if (
const bool IsAccessorKeyword =
2273 Tok->
isOneOf(Keywords.kw_get, Keywords.kw_init, Keywords.kw_set);
2274 IsAccessorKeyword ||
Tok->isAccessSpecifierKeyword() ||
2275 Tok->
isOneOf(tok::l_square, tok::semi, Keywords.kw_internal)) {
2276 if (IsAccessorKeyword)
2277 HasSpecialAccessor =
true;
2278 else if (
Tok->
is(tok::l_square))
2280 Tok = Tokens->getNextToken();
2284 IsTrivialPropertyAccessor =
false;
2289 Tokens->setPosition(StoredPosition);
2295 Tokens->setPosition(StoredPosition);
2296 if (!IsTrivialPropertyAccessor && Style.BraceWrapping.AfterFunction)
2300 switch (FormatTok->Tok.getKind()) {
2303 if (FormatTok->is(tok::equal)) {
2304 while (!
eof() && FormatTok->isNot(tok::semi))
2317 if (FormatTok->is(TT_FatArrow)) {
2321 }
while (!
eof() && FormatTok->isNot(tok::semi));
2330 if (FormatTok->isOneOf(Keywords.kw_get, Keywords.kw_init,
2332 !IsTrivialPropertyAccessor) {
2344bool UnwrappedLineParser::tryToParseLambda() {
2345 assert(FormatTok->is(tok::l_square));
2351 if (!tryToParseLambdaIntroducer())
2355 bool InTemplateParameterList =
false;
2357 while (FormatTok->isNot(tok::l_brace)) {
2358 if (FormatTok->isTypeName(LangOpts) || FormatTok->isAttribute()) {
2362 switch (FormatTok->Tok.getKind()) {
2366 parseParens(TT_PointerOrReference);
2372 assert(FormatTok->Previous);
2373 if (FormatTok->Previous->is(tok::r_square))
2374 InTemplateParameterList =
true;
2379 case tok::kw_struct:
2381 case tok::kw_template:
2382 case tok::kw_typename:
2386 case tok::kw_constexpr:
2387 case tok::kw_consteval:
2390 case tok::identifier:
2391 case tok::numeric_constant:
2392 case tok::coloncolon:
2393 case tok::kw_mutable:
2394 case tok::kw_noexcept:
2395 case tok::kw_static:
2420 case tok::equalequal:
2421 case tok::exclaimequal:
2422 case tok::greaterequal:
2423 case tok::lessequal:
2429 if (Arrow || InTemplateParameterList) {
2438 case tok::kw_requires:
2439 parseRequiresClause();
2442 if (!InTemplateParameterList)
2451 FormatTok->setFinalizedType(TT_LambdaLBrace);
2452 LSquare.setFinalizedType(TT_LambdaLSquare);
2455 Arrow->setFinalizedType(TT_LambdaArrow);
2457 NestedLambdas.push_back(
Line->SeenDecltypeAuto);
2459 assert(!NestedLambdas.empty());
2460 NestedLambdas.pop_back();
2465bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
2470 const auto *PrevPrev =
Previous->getPreviousNonComment();
2471 if (
Previous->is(tok::star) && PrevPrev && PrevPrev->isTypeName(LangOpts))
2479 if (!PrevPrev || PrevPrev->isNoneOf(tok::greater, tok::r_paren))
2483 Previous->isNoneOf(tok::kw_return, tok::kw_co_await, tok::kw_co_yield,
2484 tok::kw_co_return)) {
2488 if (LeftSquare->isCppStructuredBinding(IsCpp))
2490 if (FormatTok->is(tok::l_square) ||
tok::isLiteral(FormatTok->Tok.getKind()))
2492 if (FormatTok->is(tok::r_square)) {
2494 if (
Next->is(tok::greater))
2501void UnwrappedLineParser::tryToParseJSFunction() {
2502 assert(FormatTok->is(Keywords.kw_function));
2503 if (FormatTok->is(Keywords.kw_async))
2509 if (FormatTok->is(tok::star)) {
2510 FormatTok->setFinalizedType(TT_OverloadedOperator);
2515 if (FormatTok->is(tok::identifier))
2518 if (FormatTok->isNot(tok::l_paren))
2524 if (FormatTok->is(tok::colon)) {
2530 if (FormatTok->is(tok::l_brace))
2531 tryToParseBracedList();
2533 while (FormatTok->isNoneOf(tok::l_brace, tok::semi) && !
eof())
2537 if (FormatTok->is(tok::semi))
2543bool UnwrappedLineParser::tryToParseBracedList() {
2544 if (FormatTok->is(BK_Unknown))
2545 calculateBraceTypes();
2546 assert(FormatTok->isNot(BK_Unknown));
2547 if (FormatTok->is(BK_Block))
2554bool UnwrappedLineParser::tryToParseChildBlock() {
2555 assert(Style.isJavaScript() || Style.isCSharp());
2556 assert(FormatTok->is(TT_FatArrow));
2561 if (FormatTok->isNot(tok::l_brace))
2567bool UnwrappedLineParser::parseBracedList(
bool IsAngleBracket,
bool IsEnum) {
2568 assert(!IsAngleBracket || !IsEnum);
2569 bool HasError =
false;
2574 if (Style.isCSharp() && FormatTok->is(TT_FatArrow) &&
2575 tryToParseChildBlock()) {
2578 if (Style.isJavaScript()) {
2579 if (FormatTok->is(Keywords.kw_function)) {
2580 tryToParseJSFunction();
2583 if (FormatTok->is(tok::l_brace)) {
2585 if (tryToParseBracedList())
2590 if (FormatTok->is(IsAngleBracket ? tok::greater : tok::r_brace)) {
2592 FormatTok->setBlockKind(BK_Block);
2593 if (!Style.AllowShortEnumsOnASingleLine)
2599 switch (FormatTok->Tok.getKind()) {
2601 if (Style.isCSharp())
2610 if (Style.isJavaScript()) {
2611 if (FormatTok->is(tok::l_brace))
2619 FormatTok->setBlockKind(BK_BracedInit);
2620 if (!IsAngleBracket) {
2621 auto *Prev = FormatTok->Previous;
2622 if (Prev && Prev->is(tok::greater))
2623 Prev->setFinalizedType(TT_TemplateCloser);
2631 parseBracedList(
true);
2638 if (Style.isJavaScript()) {
2649 if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
2652 case tok::kw_requires:
2653 parseRequiresExpression();
2670bool UnwrappedLineParser::parseParens(TokenType StarAndAmpTokenType,
2672 assert(FormatTok->is(tok::l_paren) &&
"'(' expected.");
2673 auto *LParen = FormatTok;
2674 auto *Prev = FormatTok->Previous;
2675 bool SeenComma =
false;
2676 bool SeenEqual =
false;
2677 bool MightBeFoldExpr =
false;
2678 unsigned ExcessLess = 0;
2680 const bool MightBeStmtExpr = FormatTok->is(tok::l_brace);
2681 if (!InMacroCall && Prev && Prev->is(TT_FunctionLikeMacro))
2684 switch (FormatTok->Tok.getKind()) {
2686 if (parseParens(ExcessLess == 0 ? StarAndAmpTokenType : TT_Unknown,
2690 if (Style.isJava() && FormatTok->is(tok::l_brace))
2693 case tok::r_paren: {
2694 auto *RParen = FormatTok;
2697 auto OptionalParens = [&] {
2699 MightBeStmtExpr || MightBeFoldExpr || SeenComma || InMacroCall ||
2700 Line->InMacroBody || RParen->getPreviousNonComment() == LParen) {
2703 const bool DoubleParens =
2704 Prev->is(tok::l_paren) && FormatTok->is(tok::r_paren);
2706 const auto *PrevPrev = Prev->getPreviousNonComment();
2707 const bool Excluded =
2709 (PrevPrev->isOneOf(tok::kw___attribute, tok::kw_decltype) ||
2711 (PrevPrev->isOneOf(tok::kw_if, tok::kw_while) ||
2712 PrevPrev->endsSequence(tok::kw_constexpr, tok::kw_if))));
2716 const bool CommaSeparated =
2717 Prev->isOneOf(tok::l_paren, tok::comma) &&
2718 FormatTok->isOneOf(tok::comma, tok::r_paren);
2719 if (CommaSeparated &&
2721 !Prev->endsSequence(tok::comma, tok::ellipsis) &&
2723 !(FormatTok->is(tok::comma) &&
2724 Tokens->peekNextToken()->is(tok::ellipsis))) {
2727 const bool ReturnParens =
2729 ((NestedLambdas.empty() && !IsDecltypeAutoFunction) ||
2730 (!NestedLambdas.empty() && !NestedLambdas.back())) &&
2731 Prev->isOneOf(tok::kw_return, tok::kw_co_return) &&
2732 FormatTok->is(tok::semi);
2738 if (OptionalParens()) {
2739 LParen->Optional =
true;
2740 RParen->Optional =
true;
2741 }
else if (Prev->is(TT_TypenameMacro)) {
2742 LParen->setFinalizedType(TT_TypeDeclarationParen);
2743 RParen->setFinalizedType(TT_TypeDeclarationParen);
2744 }
else if (Prev->is(tok::greater) && RParen->Previous == LParen) {
2745 Prev->setFinalizedType(TT_TemplateCloser);
2746 }
else if (FormatTok->is(tok::l_brace) && Prev->is(tok::amp) &&
2748 FormatTok->setBlockKind(BK_BracedInit);
2760 if (!tryToParseBracedList())
2765 if (FormatTok->is(tok::l_brace)) {
2775 MightBeFoldExpr =
true;
2780 if (Style.isCSharp() && FormatTok->is(TT_FatArrow))
2781 tryToParseChildBlock();
2786 if (Style.isJavaScript())
2791 case tok::identifier:
2792 if (Style.isJavaScript() && (FormatTok->is(Keywords.kw_function)))
2793 tryToParseJSFunction();
2797 case tok::kw_switch:
2803 case tok::kw_requires:
2804 parseRequiresExpression();
2820 if (StarAndAmpTokenType != TT_Unknown && ExcessLess == 0)
2821 FormatTok->setFinalizedType(StarAndAmpTokenType);
2833 assert(FormatTok->is(tok::l_square) &&
"'[' expected.");
2834 if (tryToParseLambda())
2838 switch (FormatTok->Tok.getKind()) {
2851 case tok::l_brace: {
2852 if (!tryToParseBracedList())
2859 if (FormatTok->is(tok::l_brace)) {
2871void UnwrappedLineParser::keepAncestorBraces() {
2872 if (!Style.RemoveBracesLLVM)
2875 const int MaxNestingLevels = 2;
2876 const int Size = NestedTooDeep.size();
2877 if (Size >= MaxNestingLevels)
2878 NestedTooDeep[
Size - MaxNestingLevels] =
true;
2879 NestedTooDeep.push_back(
false);
2883 for (
const auto &
Token : llvm::reverse(
Line.Tokens))
2890void UnwrappedLineParser::parseUnbracedBody(
bool CheckEOF) {
2893 if (Style.InsertBraces && !
Line->InPPDirective && !
Line->Tokens.empty() &&
2894 PreprocessorDirectives.empty() && FormatTok->isNot(tok::semi)) {
2896 ? getLastNonComment(*
Line)
2899 if (
Tok->BraceCount < 0) {
2900 assert(
Tok->BraceCount == -1);
2903 Tok->BraceCount = -1;
2909 ++
Line->UnbracedBodyLevel;
2910 parseStructuralElement();
2911 --
Line->UnbracedBodyLevel;
2914 assert(!
Line->InPPDirective);
2916 for (
const auto &L : llvm::reverse(*CurrentLines)) {
2918 Tok = L.Tokens.back().Tok;
2926 if (CheckEOF &&
eof())
2936 assert(LeftBrace->
is(tok::l_brace));
2944 assert(RightBrace->
is(tok::r_brace));
2952void UnwrappedLineParser::handleAttributes() {
2954 if (FormatTok->isAttribute())
2956 else if (FormatTok->is(tok::l_square))
2957 handleCppAttributes();
2960bool UnwrappedLineParser::handleCppAttributes() {
2962 assert(FormatTok->is(tok::l_square));
2963 if (!tryToParseSimpleAttribute())
2970bool UnwrappedLineParser::isBlockBegin(
const FormatToken &
Tok)
const {
2973 return Style.isVerilog() ? Keywords.isVerilogBegin(
Tok)
2974 :
Tok.
is(tok::l_brace);
2977FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
2979 bool IsVerilogAssert) {
2980 assert((FormatTok->is(tok::kw_if) ||
2981 (Style.isVerilog() &&
2982 FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
2983 Keywords.kw_assume, Keywords.kw_cover))) &&
2987 if (IsVerilogAssert) {
2989 if (FormatTok->is(Keywords.kw_verilogHash)) {
2991 if (FormatTok->is(tok::numeric_constant))
2993 }
else if (FormatTok->isOneOf(Keywords.kw_final, Keywords.kw_property,
2994 Keywords.kw_sequence)) {
3000 if (Style.isTableGen()) {
3001 while (!
eof() && FormatTok->isNot(Keywords.kw_then)) {
3008 if (FormatTok->is(tok::exclaim))
3011 bool KeepIfBraces =
true;
3012 if (FormatTok->is(tok::kw_consteval)) {
3015 KeepIfBraces = !Style.RemoveBracesLLVM || KeepBraces;
3016 if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
3018 if (FormatTok->is(tok::l_paren)) {
3019 FormatTok->setFinalizedType(TT_ConditionLParen);
3025 if (IsVerilogAssert && FormatTok->is(tok::semi)) {
3031 bool NeedsUnwrappedLine =
false;
3032 keepAncestorBraces();
3035 IfStmtKind IfBlockKind = IfStmtKind::NotIf;
3037 if (isBlockBegin(*FormatTok)) {
3038 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3039 IfLeftBrace = FormatTok;
3040 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3041 parseBlock(
false, 1u,
3042 true, KeepIfBraces, &IfBlockKind);
3043 setPreviousRBraceType(TT_ControlStatementRBrace);
3044 if (Style.BraceWrapping.BeforeElse)
3047 NeedsUnwrappedLine =
true;
3048 }
else if (IsVerilogAssert && FormatTok->is(tok::kw_else)) {
3051 parseUnbracedBody();
3054 if (Style.RemoveBracesLLVM) {
3055 assert(!NestedTooDeep.empty());
3056 KeepIfBraces = KeepIfBraces ||
3057 (IfLeftBrace && !IfLeftBrace->MatchingParen) ||
3058 NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly ||
3059 IfBlockKind == IfStmtKind::IfElseIf;
3062 bool KeepElseBraces = KeepIfBraces;
3064 IfStmtKind
Kind = IfStmtKind::IfOnly;
3066 if (FormatTok->is(tok::kw_else)) {
3067 if (Style.RemoveBracesLLVM) {
3068 NestedTooDeep.back() =
false;
3069 Kind = IfStmtKind::IfElse;
3073 if (isBlockBegin(*FormatTok)) {
3074 const bool FollowedByIf = Tokens->peekNextToken()->is(tok::kw_if);
3075 FormatTok->setFinalizedType(TT_ElseLBrace);
3076 ElseLeftBrace = FormatTok;
3077 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3078 IfStmtKind ElseBlockKind = IfStmtKind::NotIf;
3080 parseBlock(
false, 1u,
3081 true, KeepElseBraces, &ElseBlockKind);
3082 setPreviousRBraceType(TT_ElseRBrace);
3083 if (FormatTok->is(tok::kw_else)) {
3084 KeepElseBraces = KeepElseBraces ||
3085 ElseBlockKind == IfStmtKind::IfOnly ||
3086 ElseBlockKind == IfStmtKind::IfElseIf;
3087 }
else if (FollowedByIf && IfLBrace && !IfLBrace->Optional) {
3088 KeepElseBraces =
true;
3089 assert(ElseLeftBrace->MatchingParen);
3093 }
else if (!IsVerilogAssert && FormatTok->is(tok::kw_if)) {
3096 const bool IsPrecededByComment =
Previous->is(tok::comment);
3097 if (IsPrecededByComment) {
3101 bool TooDeep =
true;
3102 if (Style.RemoveBracesLLVM) {
3103 Kind = IfStmtKind::IfElseIf;
3104 TooDeep = NestedTooDeep.pop_back_val();
3106 ElseLeftBrace = parseIfThenElse(
nullptr, KeepIfBraces);
3107 if (Style.RemoveBracesLLVM)
3108 NestedTooDeep.push_back(TooDeep);
3109 if (IsPrecededByComment)
3112 parseUnbracedBody(
true);
3115 KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse;
3116 if (NeedsUnwrappedLine)
3120 if (!Style.RemoveBracesLLVM)
3123 assert(!NestedTooDeep.empty());
3124 KeepElseBraces = KeepElseBraces ||
3125 (ElseLeftBrace && !ElseLeftBrace->MatchingParen) ||
3126 NestedTooDeep.back();
3128 NestedTooDeep.pop_back();
3130 if (!KeepIfBraces && !KeepElseBraces) {
3133 }
else if (IfLeftBrace) {
3134 FormatToken *IfRightBrace = IfLeftBrace->MatchingParen;
3136 assert(IfRightBrace->MatchingParen == IfLeftBrace);
3137 assert(!IfLeftBrace->Optional);
3138 assert(!IfRightBrace->Optional);
3139 IfLeftBrace->MatchingParen =
nullptr;
3140 IfRightBrace->MatchingParen =
nullptr;
3150void UnwrappedLineParser::parseTryCatch() {
3151 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) &&
"'try' expected");
3153 bool NeedsUnwrappedLine =
false;
3154 bool HasCtorInitializer =
false;
3155 if (FormatTok->is(tok::colon)) {
3156 auto *Colon = FormatTok;
3159 if (FormatTok->is(tok::identifier)) {
3160 HasCtorInitializer =
true;
3161 Colon->setFinalizedType(TT_CtorInitializerColon);
3166 while (FormatTok->is(tok::comma))
3169 while (FormatTok->is(tok::identifier)) {
3171 if (FormatTok->is(tok::l_paren)) {
3173 }
else if (FormatTok->is(tok::l_brace)) {
3180 while (FormatTok->is(tok::comma))
3185 if (Style.isJava() && FormatTok->is(tok::l_paren))
3188 keepAncestorBraces();
3190 if (FormatTok->is(tok::l_brace)) {
3191 if (HasCtorInitializer)
3192 FormatTok->setFinalizedType(TT_FunctionLBrace);
3193 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3195 if (Style.BraceWrapping.BeforeCatch)
3198 NeedsUnwrappedLine =
true;
3199 }
else if (FormatTok->isNot(tok::kw_catch)) {
3205 parseStructuralElement();
3208 for (
bool SeenCatch =
false;;) {
3209 if (FormatTok->is(tok::at))
3211 if (FormatTok->isNoneOf(tok::kw_catch, Keywords.kw___except,
3212 tok::kw___finally, tok::objc_catch,
3213 tok::objc_finally) &&
3214 !((Style.isJava() || Style.isJavaScript()) &&
3215 FormatTok->is(Keywords.kw_finally))) {
3218 if (FormatTok->is(tok::kw_catch))
3221 while (FormatTok->isNot(tok::l_brace)) {
3222 if (FormatTok->is(tok::l_paren)) {
3226 if (FormatTok->isOneOf(tok::semi, tok::r_brace) ||
eof()) {
3227 if (Style.RemoveBracesLLVM)
3228 NestedTooDeep.pop_back();
3234 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3237 NeedsUnwrappedLine =
false;
3238 Line->MustBeDeclaration =
false;
3239 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3241 if (Style.BraceWrapping.BeforeCatch)
3244 NeedsUnwrappedLine =
true;
3247 if (Style.RemoveBracesLLVM)
3248 NestedTooDeep.pop_back();
3250 if (NeedsUnwrappedLine)
3254void UnwrappedLineParser::parseNamespaceOrExportBlock(
unsigned AddLevels) {
3255 bool ManageWhitesmithsBraces =
3260 if (ManageWhitesmithsBraces)
3265 parseBlock(
true, AddLevels,
true,
3266 true,
nullptr, ManageWhitesmithsBraces);
3268 addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep);
3270 if (ManageWhitesmithsBraces)
3274void UnwrappedLineParser::parseNamespace() {
3275 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
3276 "'namespace' expected");
3280 if (InitialToken.is(TT_NamespaceMacro)) {
3283 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
3284 tok::l_square, tok::period, tok::l_paren) ||
3285 (Style.isCSharp() && FormatTok->is(tok::kw_union))) {
3286 if (FormatTok->is(tok::l_square))
3288 else if (FormatTok->is(tok::l_paren))
3294 if (FormatTok->is(tok::l_brace)) {
3295 FormatTok->setFinalizedType(TT_NamespaceLBrace);
3298 Tokens->peekNextToken()->is(tok::r_brace))) {
3302 unsigned AddLevels =
3305 DeclarationScopeStack.size() > 1)
3308 parseNamespaceOrExportBlock(AddLevels);
3313void UnwrappedLineParser::parseCppExportBlock() {
3314 if (FormatTok->is(tok::l_brace)) {
3315 FormatTok->setFinalizedType(TT_ExportLBrace);
3316 if (Style.BraceWrapping.AfterExportBlock)
3319 parseNamespaceOrExportBlock(Style.IndentExportBlock ? 1 : 0);
3322void UnwrappedLineParser::parseNew() {
3323 assert(FormatTok->is(tok::kw_new) &&
"'new' expected");
3326 if (Style.isCSharp()) {
3329 if (FormatTok->is(tok::l_paren))
3333 if (FormatTok->is(tok::l_brace))
3336 if (FormatTok->isOneOf(tok::semi, tok::comma))
3343 if (!Style.isJava())
3349 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
3353 if (FormatTok->is(tok::l_paren)) {
3357 if (FormatTok->is(tok::l_brace))
3365void UnwrappedLineParser::parseLoopBody(
bool KeepBraces,
bool WrapRightBrace) {
3366 keepAncestorBraces();
3368 if (isBlockBegin(*FormatTok)) {
3369 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3371 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3372 parseBlock(
false, 1u,
3374 setPreviousRBraceType(TT_ControlStatementRBrace);
3376 assert(!NestedTooDeep.empty());
3377 if (!NestedTooDeep.back())
3383 parseUnbracedBody();
3387 NestedTooDeep.pop_back();
3390void UnwrappedLineParser::parseForOrWhileLoop(
bool HasParens) {
3391 assert((FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) ||
3392 (Style.isVerilog() &&
3393 FormatTok->isOneOf(Keywords.kw_always, Keywords.kw_always_comb,
3394 Keywords.kw_always_ff, Keywords.kw_always_latch,
3395 Keywords.kw_final, Keywords.kw_initial,
3396 Keywords.kw_foreach, Keywords.kw_forever,
3397 Keywords.kw_repeat))) &&
3398 "'for', 'while' or foreach macro expected");
3399 const bool KeepBraces = !Style.RemoveBracesLLVM ||
3400 FormatTok->isNoneOf(tok::kw_for, tok::kw_while);
3404 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
3406 if (IsCpp && FormatTok->is(tok::kw_co_await))
3408 if (HasParens && FormatTok->is(tok::l_paren)) {
3412 if (Style.isVerilog())
3413 FormatTok->setFinalizedType(TT_ConditionLParen);
3417 if (Style.isVerilog()) {
3419 parseVerilogSensitivityList();
3420 }
else if (Style.AllowShortLoopsOnASingleLine && FormatTok->is(tok::semi) &&
3421 Tokens->getPreviousToken()->is(tok::r_paren)) {
3428 parseLoopBody(KeepBraces,
true);
3431void UnwrappedLineParser::parseDoWhile() {
3432 assert(FormatTok->is(tok::kw_do) &&
"'do' expected");
3435 parseLoopBody(
true, Style.BraceWrapping.BeforeWhile);
3438 if (FormatTok->isNot(tok::kw_while)) {
3443 FormatTok->setFinalizedType(TT_DoWhile);
3451 parseStructuralElement();
3454void UnwrappedLineParser::parseLabel(
bool IsGotoLabel) {
3457 const auto IndentGotoLabel = Style.IndentGotoLabels;
3458 const auto OldLineLevel =
Line->Level;
3465 if (OldLineLevel > 1 || (!
Line->InPPDirective && OldLineLevel > 0))
3469 if (!IsGotoLabel && !Style.IndentCaseBlocks &&
3470 CommentsBeforeNextToken.empty() && FormatTok->is(tok::l_brace)) {
3471 CompoundStatementIndenter Indenter(
this,
Level,
3472 Style.BraceWrapping.AfterCaseLabel,
3473 Style.BraceWrapping.IndentBraces);
3475 if (FormatTok->is(tok::kw_break)) {
3476 if (Style.BraceWrapping.AfterControlStatement ==
3479 if (!Style.IndentCaseBlocks &&
3484 parseStructuralElement();
3488 if (FormatTok->is(tok::semi))
3493 Level = OldLineLevel;
3495 if (FormatTok->isNot(tok::l_brace)) {
3496 parseStructuralElement();
3501void UnwrappedLineParser::parseCaseLabel() {
3502 assert(FormatTok->is(tok::kw_case) &&
"'case' expected");
3503 auto *Case = FormatTok;
3508 if (FormatTok->is(tok::colon)) {
3509 FormatTok->setFinalizedType(TT_CaseLabelColon);
3512 if (Style.isJava() && FormatTok->is(tok::arrow)) {
3513 FormatTok->setFinalizedType(TT_CaseLabelArrow);
3514 Case->setFinalizedType(TT_SwitchExpressionLabel);
3521void UnwrappedLineParser::parseSwitch(
bool IsExpr) {
3522 assert(FormatTok->is(tok::kw_switch) &&
"'switch' expected");
3524 if (FormatTok->is(tok::l_paren))
3527 keepAncestorBraces();
3529 if (FormatTok->is(tok::l_brace)) {
3530 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3531 FormatTok->setFinalizedType(IsExpr ? TT_SwitchExpressionLBrace
3532 : TT_ControlStatementLBrace);
3537 setPreviousRBraceType(TT_ControlStatementRBrace);
3543 parseStructuralElement();
3547 if (Style.RemoveBracesLLVM)
3548 NestedTooDeep.pop_back();
3551void UnwrappedLineParser::parseAccessSpecifier() {
3554 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
3557 if (FormatTok->is(tok::colon))
3565bool UnwrappedLineParser::parseRequires(
bool SeenEqual) {
3566 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3570 switch (Tokens->peekNextToken(
true)->Tok.getKind()) {
3573 parseRequiresExpression();
3580 parseRequiresClause();
3591 auto *PreviousNonComment = FormatTok->getPreviousNonComment();
3593 if (!PreviousNonComment ||
3594 PreviousNonComment->is(TT_RequiresExpressionLBrace)) {
3597 parseRequiresClause();
3601 switch (PreviousNonComment->Tok.getKind()) {
3604 case tok::kw_noexcept:
3609 parseRequiresClause();
3618 auto PrevPrev = PreviousNonComment->getPreviousNonComment();
3619 if ((PrevPrev && PrevPrev->is(tok::kw_const)) || !SeenEqual) {
3620 parseRequiresClause();
3626 if (PreviousNonComment->isTypeOrIdentifier(LangOpts)) {
3628 parseRequiresClause();
3632 parseRequiresExpression();
3642 unsigned StoredPosition = Tokens->getPosition();
3645 auto PeekNext = [&Lookahead, &NextToken,
this] {
3647 NextToken = Tokens->getNextToken();
3650 bool FoundType =
false;
3651 bool LastWasColonColon =
false;
3654 for (; Lookahead < 50; PeekNext()) {
3655 switch (NextToken->Tok.getKind()) {
3656 case tok::kw_volatile:
3659 if (OpenAngles == 0) {
3660 FormatTok = Tokens->setPosition(StoredPosition);
3661 parseRequiresExpression();
3669 case tok::coloncolon:
3670 LastWasColonColon =
true;
3672 case tok::kw_decltype:
3673 case tok::identifier:
3674 if (FoundType && !LastWasColonColon && OpenAngles == 0) {
3675 FormatTok = Tokens->setPosition(StoredPosition);
3676 parseRequiresExpression();
3680 LastWasColonColon =
false;
3689 if (NextToken->isTypeName(LangOpts)) {
3690 FormatTok = Tokens->setPosition(StoredPosition);
3691 parseRequiresExpression();
3698 FormatTok = Tokens->setPosition(StoredPosition);
3699 parseRequiresClause();
3708void UnwrappedLineParser::parseRequiresClause() {
3709 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3714 bool InRequiresExpression =
3715 !FormatTok->Previous ||
3716 FormatTok->Previous->is(TT_RequiresExpressionLBrace);
3718 FormatTok->setFinalizedType(InRequiresExpression
3719 ? TT_RequiresClauseInARequiresExpression
3720 : TT_RequiresClause);
3725 parseConstraintExpression();
3727 if (!InRequiresExpression && FormatTok->Previous)
3728 FormatTok->Previous->ClosesRequiresClause =
true;
3736void UnwrappedLineParser::parseRequiresExpression() {
3737 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3739 FormatTok->setFinalizedType(TT_RequiresExpression);
3742 if (FormatTok->is(tok::l_paren)) {
3743 FormatTok->setFinalizedType(TT_RequiresExpressionLParen);
3747 if (FormatTok->is(tok::l_brace)) {
3748 FormatTok->setFinalizedType(TT_RequiresExpressionLBrace);
3757void UnwrappedLineParser::parseConstraintExpression() {
3764 bool LambdaNextTimeAllowed =
true;
3774 bool TopLevelParensAllowed =
true;
3777 bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed,
false);
3779 switch (FormatTok->Tok.getKind()) {
3780 case tok::kw_requires:
3781 parseRequiresExpression();
3785 if (!TopLevelParensAllowed)
3787 parseParens(TT_BinaryOperator);
3788 TopLevelParensAllowed =
false;
3792 if (!LambdaThisTimeAllowed || !tryToParseLambda())
3799 case tok::kw_struct:
3809 FormatTok->setFinalizedType(TT_BinaryOperator);
3811 LambdaNextTimeAllowed =
true;
3812 TopLevelParensAllowed =
true;
3817 LambdaNextTimeAllowed = LambdaThisTimeAllowed;
3821 case tok::kw_sizeof:
3823 case tok::greaterequal:
3824 case tok::greatergreater:
3826 case tok::lessequal:
3828 case tok::equalequal:
3830 case tok::exclaimequal:
3835 LambdaNextTimeAllowed =
true;
3836 TopLevelParensAllowed =
true;
3841 case tok::numeric_constant:
3842 case tok::coloncolon:
3845 TopLevelParensAllowed =
false;
3850 case tok::kw_static_cast:
3851 case tok::kw_const_cast:
3852 case tok::kw_reinterpret_cast:
3853 case tok::kw_dynamic_cast:
3855 if (FormatTok->isNot(tok::less))
3859 parseBracedList(
true);
3863 if (!FormatTok->Tok.getIdentifierInfo()) {
3873 assert(FormatTok->Previous);
3874 switch (FormatTok->Previous->Tok.getKind()) {
3875 case tok::coloncolon:
3879 case tok::kw_requires:
3881 case tok::kw_template:
3889 if (FormatTok->is(tok::less)) {
3891 parseBracedList(
true);
3893 TopLevelParensAllowed =
false;
3899bool UnwrappedLineParser::parseEnum() {
3903 if (FormatTok->is(tok::kw_enum))
3909 if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question))
3918 if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
3920 while (FormatTok->is(tok::l_square))
3921 if (!handleCppAttributes())
3925 while (FormatTok->Tok.getIdentifierInfo() ||
3926 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
3927 tok::greater, tok::comma, tok::question,
3929 if (FormatTok->is(tok::colon))
3930 FormatTok->setFinalizedType(TT_EnumUnderlyingTypeColon);
3931 if (Style.isVerilog()) {
3932 FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
3935 while (FormatTok->is(tok::l_square))
3941 if (FormatTok->is(tok::l_paren))
3943 if (FormatTok->is(tok::identifier)) {
3947 if (IsCpp && FormatTok->is(tok::identifier))
3953 if (FormatTok->isNot(tok::l_brace))
3955 FormatTok->setFinalizedType(TT_EnumLBrace);
3956 FormatTok->setBlockKind(BK_Block);
3958 if (Style.isJava()) {
3960 parseJavaEnumBody();
3968 const bool ManageWhitesmithsBraces =
3971 if (!Style.AllowShortEnumsOnASingleLine &&
3973 Tokens->peekNextToken()->is(tok::r_brace))) {
3978 if (ManageWhitesmithsBraces)
3983 if (!Style.AllowShortEnumsOnASingleLine) {
3985 if (!ManageWhitesmithsBraces)
3988 const auto OpeningLineIndex = CurrentLines->empty()
3989 ? UnwrappedLine::kInvalidIndex
3990 : CurrentLines->size() - 1;
3991 bool HasError = !parseBracedList(
false,
true);
3992 if (!Style.AllowShortEnumsOnASingleLine && !ManageWhitesmithsBraces)
3995 if (FormatTok->is(tok::semi))
3999 setPreviousRBraceType(TT_EnumRBrace);
4000 if (ManageWhitesmithsBraces)
4001 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
4009bool UnwrappedLineParser::parseStructLike() {
4014 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp()) {
4015 if (FormatTok->is(tok::semi))
4026class ScopedTokenPosition {
4027 unsigned StoredPosition;
4028 FormatTokenSource *Tokens;
4031 ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) {
4032 assert(Tokens &&
"Tokens expected to not be null");
4033 StoredPosition = Tokens->getPosition();
4036 ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); }
4042bool UnwrappedLineParser::tryToParseSimpleAttribute() {
4043 ScopedTokenPosition AutoPosition(Tokens);
4051 if (
Tok->
is(tok::r_square))
4053 Tok = Tokens->getNextToken();
4055 if (
Tok->
is(tok::eof))
4057 Tok = Tokens->getNextToken();
4060 Tok = Tokens->getNextToken();
4061 if (
Tok->
is(tok::semi))
4066void UnwrappedLineParser::parseJavaEnumBody() {
4067 assert(FormatTok->is(tok::l_brace));
4073 unsigned StoredPosition = Tokens->getPosition();
4074 bool IsSimple =
true;
4077 if (
Tok->
is(tok::r_brace))
4085 Tok = Tokens->getNextToken();
4087 FormatTok = Tokens->setPosition(StoredPosition);
4104 if (FormatTok->is(tok::l_brace)) {
4106 parseBlock(
true, 1u,
4108 }
else if (FormatTok->is(tok::l_paren)) {
4110 }
else if (FormatTok->is(tok::comma)) {
4113 }
else if (FormatTok->is(tok::semi)) {
4117 }
else if (FormatTok->is(tok::r_brace)) {
4126 parseLevel(OpeningBrace);
4132void UnwrappedLineParser::parseRecord(
bool ParseAsExpr,
bool IsJavaRecord) {
4133 assert(!IsJavaRecord || FormatTok->is(Keywords.kw_record));
4138 IsJavaRecord && FormatTok->is(tok::identifier) ? FormatTok :
nullptr;
4139 bool IsDerived =
false;
4141 return Tok->
is(tok::identifier) &&
Tok->TokenText !=
Tok->TokenText.upper();
4145 bool JSPastExtendsOrImplements =
false;
4149 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
4150 tok::kw_alignas, tok::l_square) ||
4151 FormatTok->isAttribute() ||
4152 ((Style.isJava() || Style.isJavaScript()) &&
4153 FormatTok->isOneOf(tok::period, tok::comma))) {
4154 if (Style.isJavaScript() &&
4155 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
4156 JSPastExtendsOrImplements =
true;
4161 if (FormatTok->is(tok::l_brace)) {
4162 tryToParseBracedList();
4166 if (FormatTok->is(tok::l_square) && handleCppAttributes())
4170 switch (FormatTok->Tok.getKind()) {
4173 if (IsJavaRecord || !IsNonMacroIdentifier(
Previous) ||
4175 Previous->Previous == &InitialToken) {
4179 case tok::coloncolon:
4183 if (JSPastExtendsOrImplements || ClassName ||
4194 auto IsListInitialization = [&] {
4195 if (!ClassName || IsDerived || JSPastExtendsOrImplements)
4197 assert(FormatTok->is(tok::l_brace));
4198 const auto *Prev = FormatTok->getPreviousNonComment();
4200 return Prev != ClassName && Prev->is(tok::identifier) &&
4201 Prev->isNot(Keywords.kw_final) && tryToParseBracedList();
4204 if (FormatTok->isOneOf(tok::colon, tok::less)) {
4205 int AngleNestingLevel = 0;
4207 if (FormatTok->is(tok::less))
4208 ++AngleNestingLevel;
4209 else if (FormatTok->is(tok::greater))
4210 --AngleNestingLevel;
4212 if (AngleNestingLevel == 0) {
4213 if (FormatTok->is(tok::colon)) {
4215 }
else if (!IsDerived && FormatTok->is(tok::identifier) &&
4216 FormatTok->Previous->is(tok::coloncolon)) {
4217 ClassName = FormatTok;
4218 }
else if (FormatTok->is(tok::l_paren) &&
4219 IsNonMacroIdentifier(FormatTok->Previous)) {
4223 if (FormatTok->is(tok::l_brace)) {
4224 if (AngleNestingLevel == 0 && IsListInitialization())
4226 calculateBraceTypes(
true);
4227 if (!tryToParseBracedList())
4230 if (FormatTok->is(tok::l_square)) {
4233 !
Previous->isTypeOrIdentifier(LangOpts))) {
4236 if (!tryToParseLambda())
4243 if (FormatTok->is(tok::semi))
4245 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
4248 parseCSharpGenericTypeConstraint();
4255 auto GetBraceTypes =
4256 [](
const FormatToken &RecordTok) -> std::pair<TokenType, TokenType> {
4257 switch (RecordTok.Tok.getKind()) {
4259 return {TT_ClassLBrace, TT_ClassRBrace};
4260 case tok::kw_struct:
4261 return {TT_StructLBrace, TT_StructRBrace};
4263 return {TT_UnionLBrace, TT_UnionRBrace};
4266 return {TT_RecordLBrace, TT_RecordRBrace};
4269 if (FormatTok->is(tok::l_brace)) {
4270 if (IsListInitialization())
4273 ClassName->setFinalizedType(TT_ClassHeadName);
4274 auto [OpenBraceType, ClosingBraceType] = GetBraceTypes(InitialToken);
4275 FormatTok->setFinalizedType(OpenBraceType);
4280 Tokens->peekNextToken()->is(tok::r_brace),
4285 unsigned AddLevels = Style.IndentAccessModifiers ? 2u : 1u;
4286 parseBlock(
true, AddLevels,
false);
4288 setPreviousRBraceType(ClosingBraceType);
4295void UnwrappedLineParser::parseObjCMethod() {
4296 assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) &&
4297 "'(' or identifier expected.");
4299 if (FormatTok->is(tok::semi)) {
4303 }
else if (FormatTok->is(tok::l_brace)) {
4304 if (Style.BraceWrapping.AfterFunction)
4315void UnwrappedLineParser::parseObjCProtocolList() {
4316 assert(FormatTok->is(tok::less) &&
"'<' expected.");
4320 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4322 }
while (!
eof() && FormatTok->isNot(tok::greater));
4326void UnwrappedLineParser::parseObjCUntilAtEnd() {
4328 if (FormatTok->is(tok::objc_end)) {
4333 if (FormatTok->is(tok::l_brace)) {
4337 }
else if (FormatTok->is(tok::r_brace)) {
4341 }
else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
4343 if (FormatTok->isOneOf(tok::l_paren, tok::identifier))
4346 parseStructuralElement();
4351void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
4352 assert(FormatTok->isOneOf(tok::objc_interface, tok::objc_implementation));
4358 if (FormatTok->is(tok::less))
4359 parseObjCLightweightGenerics();
4360 if (FormatTok->is(tok::colon)) {
4364 if (FormatTok->is(tok::less))
4365 parseObjCLightweightGenerics();
4366 }
else if (FormatTok->is(tok::l_paren)) {
4371 if (FormatTok->is(tok::less))
4372 parseObjCProtocolList();
4374 if (FormatTok->is(tok::l_brace)) {
4375 if (Style.BraceWrapping.AfterObjCDeclaration)
4384 parseObjCUntilAtEnd();
4387void UnwrappedLineParser::parseObjCLightweightGenerics() {
4388 assert(FormatTok->is(tok::less));
4396 unsigned NumOpenAngles = 1;
4400 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4402 if (FormatTok->is(tok::less)) {
4404 }
else if (FormatTok->is(tok::greater)) {
4405 assert(NumOpenAngles > 0 &&
"'>' makes NumOpenAngles negative");
4408 }
while (!
eof() && NumOpenAngles != 0);
4414bool UnwrappedLineParser::parseObjCProtocol() {
4415 assert(FormatTok->is(tok::objc_protocol));
4418 if (FormatTok->is(tok::l_paren)) {
4430 if (FormatTok->is(tok::less))
4431 parseObjCProtocolList();
4434 if (FormatTok->is(tok::semi)) {
4441 parseObjCUntilAtEnd();
4445void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
4446 bool IsImport = FormatTok->is(Keywords.kw_import);
4447 assert(IsImport || FormatTok->is(tok::kw_export));
4451 if (FormatTok->is(tok::kw_default))
4457 if (FormatTok->is(Keywords.kw_async))
4459 if (FormatTok->is(Keywords.kw_function)) {
4468 if (!IsImport && FormatTok->isNoneOf(tok::l_brace, tok::star) &&
4469 !FormatTok->isStringLiteral() &&
4470 !(FormatTok->is(Keywords.kw_type) &&
4471 Tokens->peekNextToken()->isOneOf(tok::l_brace, tok::star))) {
4476 if (FormatTok->is(tok::semi))
4478 if (
Line->Tokens.empty()) {
4483 if (FormatTok->is(tok::l_brace)) {
4484 FormatTok->setBlockKind(BK_Block);
4493void UnwrappedLineParser::parseStatementMacro() {
4495 if (FormatTok->is(tok::l_paren))
4497 if (FormatTok->is(tok::semi))
4502void UnwrappedLineParser::parseVerilogHierarchyIdentifier() {
4505 if (FormatTok->isOneOf(tok::star, tok::period, tok::periodstar,
4506 tok::coloncolon, tok::hash) ||
4507 Keywords.isVerilogIdentifier(*FormatTok)) {
4509 }
else if (FormatTok->is(tok::l_square)) {
4517void UnwrappedLineParser::parseVerilogSensitivityList() {
4518 if (FormatTok->isNot(tok::at))
4522 if (FormatTok->is(tok::at))
4524 switch (FormatTok->Tok.getKind()) {
4532 parseVerilogHierarchyIdentifier();
4537unsigned UnwrappedLineParser::parseVerilogHierarchyHeader() {
4538 unsigned AddLevels = 0;
4540 if (FormatTok->is(Keywords.kw_clocking)) {
4542 if (Keywords.isVerilogIdentifier(*FormatTok))
4544 parseVerilogSensitivityList();
4545 if (FormatTok->is(tok::semi))
4547 }
else if (FormatTok->isOneOf(tok::kw_case, Keywords.kw_casex,
4548 Keywords.kw_casez, Keywords.kw_randcase,
4549 Keywords.kw_randsequence)) {
4550 if (Style.IndentCaseLabels)
4553 if (FormatTok->is(tok::l_paren)) {
4554 FormatTok->setFinalizedType(TT_ConditionLParen);
4557 if (FormatTok->isOneOf(Keywords.kw_inside, Keywords.kw_matches))
4566 if (FormatTok->is(tok::l_square)) {
4567 auto Prev = FormatTok->getPreviousNonComment();
4568 if (Prev && Keywords.isVerilogIdentifier(*Prev))
4569 Prev->setFinalizedType(TT_VerilogDimensionedTypeName);
4571 }
else if (Keywords.isVerilogIdentifier(*FormatTok) ||
4572 FormatTok->isOneOf(tok::hash, tok::hashhash, tok::coloncolon,
4573 Keywords.kw_automatic, tok::kw_static)) {
4580 auto NewLine = [
this]() {
4582 Line->IsContinuation =
true;
4586 while (FormatTok->is(Keywords.kw_import)) {
4589 parseVerilogHierarchyIdentifier();
4590 if (FormatTok->is(tok::semi))
4595 if (FormatTok->is(Keywords.kw_verilogHash)) {
4598 if (FormatTok->is(tok::l_paren)) {
4599 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4603 if (FormatTok->is(tok::l_paren)) {
4605 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4610 if (FormatTok->is(Keywords.kw_extends)) {
4613 parseVerilogHierarchyIdentifier();
4614 if (FormatTok->is(tok::l_paren))
4617 if (FormatTok->is(Keywords.kw_implements)) {
4621 parseVerilogHierarchyIdentifier();
4622 }
while (FormatTok->is(tok::comma));
4626 if (FormatTok->is(tok::at)) {
4628 parseVerilogSensitivityList();
4631 if (FormatTok->is(tok::semi))
4639void UnwrappedLineParser::parseVerilogTable() {
4640 assert(FormatTok->is(Keywords.kw_table));
4644 auto InitialLevel =
Line->Level++;
4645 while (!
eof() && !Keywords.isVerilogEnd(*FormatTok)) {
4648 if (
Tok->
is(tok::semi))
4650 else if (
Tok->
isOneOf(tok::star, tok::colon, tok::question, tok::minus))
4651 Tok->setFinalizedType(TT_VerilogTableItem);
4653 Line->Level = InitialLevel;
4658void UnwrappedLineParser::parseVerilogCaseLabel() {
4664 auto OrigLevel =
Line->Level;
4665 auto FirstLine = CurrentLines->size();
4666 if (
Line->Level == 0 || (
Line->InPPDirective &&
Line->Level <= 1))
4668 else if (!Style.IndentCaseBlocks && Keywords.isVerilogBegin(*FormatTok))
4670 parseStructuralElement();
4673 if (CurrentLines->size() > FirstLine)
4674 (*CurrentLines)[FirstLine].Level = OrigLevel;
4675 Line->Level = OrigLevel;
4678void UnwrappedLineParser::parseVerilogExtern() {
4680 FormatTok->isOneOf(tok::kw_extern, tok::kw_export, Keywords.kw_import));
4683 if (FormatTok->is(tok::string_literal))
4685 skipVerilogQualifiers();
4686 if (Keywords.isVerilogIdentifier(*FormatTok))
4688 if (FormatTok->is(tok::equal))
4690 if (Keywords.isVerilogHierarchy(*FormatTok))
4691 parseVerilogHierarchyHeader();
4694void UnwrappedLineParser::skipVerilogQualifiers() {
4695 while (FormatTok->isOneOf(tok::kw_protected, tok::kw_virtual, tok::kw_static,
4696 Keywords.kw_rand, Keywords.kw_context,
4697 Keywords.kw_pure, Keywords.kw_randc,
4698 Keywords.kw_local)) {
4703bool UnwrappedLineParser::containsExpansion(
const UnwrappedLine &
Line)
const {
4704 for (
const auto &N :
Line.Tokens) {
4705 if (N.Tok->MacroCtx)
4707 for (
const UnwrappedLine &Child : N.Children)
4708 if (containsExpansion(Child))
4714void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) {
4715 if (
Line->Tokens.empty())
4718 if (!parsingPPDirective()) {
4719 llvm::dbgs() <<
"Adding unwrapped line:\n";
4720 printDebugInfo(*
Line);
4728 bool ClosesWhitesmithsBlock =
4729 Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex &&
4735 if (!parsingPPDirective() && !InExpansion && containsExpansion(*
Line)) {
4737 Reconstruct.emplace(
Line->Level, Unexpanded);
4738 Reconstruct->addLine(*
Line);
4743 CurrentExpandedLines.push_back(std::move(*
Line));
4745 if (Reconstruct->finished()) {
4746 UnwrappedLine Reconstructed = std::move(*Reconstruct).takeResult();
4747 assert(!Reconstructed.Tokens.empty() &&
4748 "Reconstructed must at least contain the macro identifier.");
4749 assert(!parsingPPDirective());
4751 llvm::dbgs() <<
"Adding unexpanded line:\n";
4752 printDebugInfo(Reconstructed);
4754 ExpandedLines[Reconstructed.Tokens.begin()->Tok] = CurrentExpandedLines;
4755 Lines.push_back(std::move(Reconstructed));
4756 CurrentExpandedLines.clear();
4757 Reconstruct.reset();
4762 assert(!Reconstruct || (CurrentLines != &Lines) || !PPStack.empty());
4763 CurrentLines->push_back(std::move(*
Line));
4765 Line->Tokens.clear();
4766 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
4767 Line->FirstStartColumn = 0;
4768 Line->IsContinuation =
false;
4769 Line->SeenDecltypeAuto =
false;
4770 Line->IsModuleOrImportDecl =
false;
4772 if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove)
4774 if (!parsingPPDirective() && !PreprocessorDirectives.empty()) {
4775 CurrentLines->append(
4776 std::make_move_iterator(PreprocessorDirectives.begin()),
4777 std::make_move_iterator(PreprocessorDirectives.end()));
4778 PreprocessorDirectives.clear();
4781 FormatTok->Previous =
nullptr;
4784bool UnwrappedLineParser::eof()
const {
return FormatTok->is(tok::eof); }
4786bool UnwrappedLineParser::isOnNewLine(
const FormatToken &FormatTok) {
4787 return (
Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
4788 FormatTok.NewlinesBefore > 0;
4796 const llvm::Regex &CommentPragmasRegex) {
4800 StringRef IndentContent = FormatTok.
TokenText;
4801 if (FormatTok.
TokenText.starts_with(
"//") ||
4802 FormatTok.
TokenText.starts_with(
"/*")) {
4803 IndentContent = FormatTok.
TokenText.substr(2);
4805 if (CommentPragmasRegex.match(IndentContent))
4880 if (PreviousToken && PreviousToken->
is(tok::l_brace) &&
4882 MinColumnToken = PreviousToken;
4885 PreviousToken = Node.
Tok;
4889 MinColumnToken = Node.
Tok;
4891 if (PreviousToken && PreviousToken->
is(tok::l_brace))
4892 MinColumnToken = PreviousToken;
4898void UnwrappedLineParser::flushComments(
bool NewlineBeforeNext) {
4899 bool JustComments =
Line->Tokens.empty();
4909 Tok->ContinuesLineCommentSection =
4910 continuesLineCommentSection(*
Tok, *
Line, Style, CommentPragmasRegex);
4911 if (isOnNewLine(*
Tok) && JustComments && !
Tok->ContinuesLineCommentSection)
4915 if (NewlineBeforeNext && JustComments)
4917 CommentsBeforeNextToken.clear();
4920void UnwrappedLineParser::nextToken(
int LevelDifference) {
4923 flushComments(isOnNewLine(*FormatTok));
4924 pushToken(FormatTok);
4926 if (!Style.isJavaScript())
4927 readToken(LevelDifference);
4929 readTokenWithJavaScriptASI();
4931 if (Style.isVerilog()) {
4938 if (Keywords.isVerilogEnd(*FormatTok))
4939 FormatTok->Tok.setKind(tok::r_brace);
4943void UnwrappedLineParser::distributeComments(
4963 if (Comments.empty())
4965 bool ShouldPushCommentsInCurrentLine =
true;
4966 bool HasTrailAlignedWithNextToken =
false;
4967 unsigned StartOfTrailAlignedWithNextToken = 0;
4970 for (
unsigned i = Comments.size() - 1; i > 0; --i) {
4972 HasTrailAlignedWithNextToken =
true;
4973 StartOfTrailAlignedWithNextToken = i;
4977 for (
unsigned i = 0, e = Comments.size(); i < e; ++i) {
4979 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
4980 FormatTok->ContinuesLineCommentSection =
false;
4983 *FormatTok, *
Line, Style, CommentPragmasRegex);
4985 if (!FormatTok->ContinuesLineCommentSection &&
4986 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
4987 ShouldPushCommentsInCurrentLine =
false;
4989 if (ShouldPushCommentsInCurrentLine)
4990 pushToken(FormatTok);
4992 CommentsBeforeNextToken.push_back(FormatTok);
4996void UnwrappedLineParser::readToken(
int LevelDifference) {
4998 bool PreviousWasComment =
false;
4999 bool FirstNonCommentOnLine =
false;
5001 FormatTok = Tokens->getNextToken();
5003 while (FormatTok->isOneOf(TT_ConflictStart, TT_ConflictEnd,
5004 TT_ConflictAlternative)) {
5005 if (FormatTok->is(TT_ConflictStart))
5006 conditionalCompilationStart(
false);
5007 else if (FormatTok->is(TT_ConflictAlternative))
5008 conditionalCompilationAlternative();
5009 else if (FormatTok->is(TT_ConflictEnd))
5010 conditionalCompilationEnd();
5011 FormatTok = Tokens->getNextToken();
5012 FormatTok->MustBreakBefore =
true;
5013 FormatTok->MustBreakBeforeFinalized =
true;
5016 auto IsFirstNonCommentOnLine = [](
bool FirstNonCommentOnLine,
5018 bool PreviousWasComment) {
5020 return Tok.HasUnescapedNewline ||
Tok.IsFirst;
5025 if (PreviousWasComment)
5026 return FirstNonCommentOnLine || IsFirstOnLine(
Tok);
5027 return IsFirstOnLine(
Tok);
5030 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
5031 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
5032 PreviousWasComment = FormatTok->is(tok::comment);
5034 while (!
Line->InPPDirective && FormatTok->is(tok::hash) &&
5035 FirstNonCommentOnLine) {
5038 const auto *
Next = Tokens->peekNextToken();
5039 if ((Style.isVerilog() && !Keywords.isVerilogPPDirective(*
Next)) ||
5040 (Style.isTableGen() &&
5041 Next->isNoneOf(tok::kw_else, tok::pp_define, tok::pp_ifdef,
5042 tok::pp_ifndef, tok::pp_endif))) {
5045 distributeComments(Comments, FormatTok);
5049 bool SwitchToPreprocessorLines = !
Line->Tokens.empty();
5050 ScopedLineState BlockState(*
this, SwitchToPreprocessorLines);
5051 assert((LevelDifference >= 0 ||
5052 static_cast<unsigned>(-LevelDifference) <=
Line->Level) &&
5053 "LevelDifference makes Line->Level negative");
5054 Line->Level += LevelDifference;
5059 PPBranchLevel > 0) {
5060 Line->Level += PPBranchLevel;
5062 assert(
Line->Level >=
Line->UnbracedBodyLevel);
5063 Line->Level -=
Line->UnbracedBodyLevel;
5064 flushComments(isOnNewLine(*FormatTok));
5065 const bool IsEndIf = Tokens->peekNextToken()->is(tok::pp_endif);
5067 PreviousWasComment = FormatTok->is(tok::comment);
5068 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
5069 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
5072 if (IsEndIf && IncludeGuard == IG_Defined && PPBranchLevel == -1 &&
5073 getIncludeGuardState(Style.IndentPPDirectives) == IG_Inited &&
5075 (PreviousWasComment &&
5076 Tokens->peekNextToken(
true)->is(tok::eof)))) {
5077 IncludeGuard = IG_Found;
5081 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
5082 !
Line->InPPDirective) {
5086 if (FormatTok->is(tok::identifier) &&
5087 Macros.defined(FormatTok->TokenText) &&
5089 !
Line->InPPDirective) {
5091 unsigned Position = Tokens->getPosition();
5095 auto PreCall = std::move(
Line);
5096 Line.reset(
new UnwrappedLine);
5097 bool OldInExpansion = InExpansion;
5100 auto Args = parseMacroCall();
5101 InExpansion = OldInExpansion;
5102 assert(
Line->Tokens.front().Tok == ID);
5104 auto UnexpandedLine = std::move(
Line);
5106 Line = std::move(PreCall);
5109 llvm::dbgs() <<
"Macro call: " <<
ID->TokenText <<
"(";
5111 llvm::dbgs() <<
"(";
5112 for (
const auto &Arg : Args.value())
5113 for (
const auto &
T : Arg)
5114 llvm::dbgs() <<
T->TokenText <<
" ";
5115 llvm::dbgs() <<
")";
5117 llvm::dbgs() <<
"\n";
5119 if (
Macros.objectLike(
ID->TokenText) && Args &&
5120 !
Macros.hasArity(
ID->TokenText, Args->size())) {
5126 LLVM_DEBUG(llvm::dbgs()
5127 <<
"Macro \"" <<
ID->TokenText
5128 <<
"\" not overloaded for arity " << Args->size()
5129 <<
"or not function-like, using object-like overload.");
5131 UnexpandedLine->Tokens.resize(1);
5132 Tokens->setPosition(Position);
5134 assert(!Args &&
Macros.objectLike(
ID->TokenText));
5136 if ((!Args &&
Macros.objectLike(
ID->TokenText)) ||
5137 (Args &&
Macros.hasArity(
ID->TokenText, Args->size()))) {
5140 Unexpanded[
ID] = std::move(UnexpandedLine);
5142 Macros.expand(ID, std::move(Args));
5143 if (!Expansion.empty())
5144 FormatTok = Tokens->insertTokens(Expansion);
5147 llvm::dbgs() <<
"Expanded: ";
5148 for (
const auto &
T : Expansion)
5149 llvm::dbgs() <<
T->TokenText <<
" ";
5150 llvm::dbgs() <<
"\n";
5154 llvm::dbgs() <<
"Did not expand macro \"" <<
ID->TokenText
5155 <<
"\", because it was used ";
5157 llvm::dbgs() <<
"with " << Args->size();
5159 llvm::dbgs() <<
"without";
5160 llvm::dbgs() <<
" arguments, which doesn't match any definition.\n";
5162 Tokens->setPosition(Position);
5167 if (FormatTok->isNot(tok::comment)) {
5168 distributeComments(Comments, FormatTok);
5173 Comments.push_back(FormatTok);
5176 distributeComments(Comments,
nullptr);
5181template <
typename Iterator>
5182void pushTokens(Iterator Begin, Iterator End,
5184 for (
auto I = Begin; I != End; ++I) {
5185 Into.push_back(I->Tok);
5186 for (
const auto &Child : I->Children)
5187 pushTokens(Child.Tokens.begin(), Child.Tokens.end(), Into);
5192std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>
5193UnwrappedLineParser::parseMacroCall() {
5194 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>> Args;
5195 assert(
Line->Tokens.empty());
5197 if (FormatTok->isNot(tok::l_paren))
5199 unsigned Position = Tokens->getPosition();
5203 auto ArgStart = std::prev(
Line->Tokens.end());
5207 switch (FormatTok->Tok.getKind()) {
5212 case tok::r_paren: {
5218 Args->push_back({});
5219 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5228 Args->push_back({});
5229 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5231 ArgStart = std::prev(
Line->Tokens.end());
5239 Line->Tokens.resize(1);
5240 Tokens->setPosition(Position);
5246 Line->Tokens.push_back(UnwrappedLineNode(
Tok));
5247 if (AtEndOfPPLine) {
5248 auto &
Tok = *
Line->Tokens.back().Tok;
5249 Tok.MustBreakBefore =
true;
5250 Tok.MustBreakBeforeFinalized =
true;
5251 Tok.FirstAfterPPLine =
true;
5252 AtEndOfPPLine =
false;
This file contains the main building blocks of macro support in clang-format.
static bool HasAttribute(const QualType &T)
This file implements a token annotator, i.e.
Defines the clang::TokenKind enum and support functions.
This file contains the declaration of the UnwrappedLineParser, which turns a stream of tokens into Un...
Implements an efficient mapping from strings to IdentifierInfo nodes.
Parser - This implements a parser for the C family of languages.
This class handles loading and caching of source files into memory.
Token - This structure provides full information about a lexed token.
IdentifierInfo * getIdentifierInfo() const
bool isLiteral() const
Return true if this is a "literal", like a numeric constant, string, etc.
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
tok::TokenKind getKind() const
bool isOneOf(Ts... Ks) const
bool isNot(tok::TokenKind K) const
@ Macros
Canonicalize -D and -U options.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
bool isLiteral(TokenKind K)
Return true if this is a "literal" kind, like a numeric constant, string, etc.
Top level wrappers for InstallAPI frontend operations.
bool isLineComment(const FormatToken &FormatTok)
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Default
Set to the current date and time.
const FunctionProtoType * T
@ Type
The name was classified as a type.
bool continuesLineComment(const FormatToken &FormatTok, const FormatToken *Previous, const FormatToken *MinColumnToken)
@ Parens
New-expression has a C++98 paren-delimited initializer.
Encapsulates keywords that are context sensitive or for languages not properly supported by Clang's l...
IdentifierInfo * kw_instanceof
IdentifierInfo * kw_implements
IdentifierInfo * kw_override
IdentifierInfo * kw_await
IdentifierInfo * kw_extends
IdentifierInfo * kw_async
IdentifierInfo * kw_abstract
IdentifierInfo * kw_interface
IdentifierInfo * kw_function
IdentifierInfo * kw_yield
IdentifierInfo * kw_where
IdentifierInfo * kw_throws
IdentifierInfo * kw_import
IdentifierInfo * kw_finally
Represents a complete lambda introducer.