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 auto 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 parseNamespaceOrExportBlock(Style.IndentExportBlock ? 1 : 0);
3317void UnwrappedLineParser::parseNew() {
3318 assert(FormatTok->is(tok::kw_new) &&
"'new' expected");
3321 if (Style.isCSharp()) {
3324 if (FormatTok->is(tok::l_paren))
3328 if (FormatTok->is(tok::l_brace))
3331 if (FormatTok->isOneOf(tok::semi, tok::comma))
3338 if (!Style.isJava())
3344 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
3348 if (FormatTok->is(tok::l_paren)) {
3352 if (FormatTok->is(tok::l_brace))
3360void UnwrappedLineParser::parseLoopBody(
bool KeepBraces,
bool WrapRightBrace) {
3361 keepAncestorBraces();
3363 if (isBlockBegin(*FormatTok)) {
3364 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3366 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3367 parseBlock(
false, 1u,
3369 setPreviousRBraceType(TT_ControlStatementRBrace);
3371 assert(!NestedTooDeep.empty());
3372 if (!NestedTooDeep.back())
3378 parseUnbracedBody();
3382 NestedTooDeep.pop_back();
3385void UnwrappedLineParser::parseForOrWhileLoop(
bool HasParens) {
3386 assert((FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) ||
3387 (Style.isVerilog() &&
3388 FormatTok->isOneOf(Keywords.kw_always, Keywords.kw_always_comb,
3389 Keywords.kw_always_ff, Keywords.kw_always_latch,
3390 Keywords.kw_final, Keywords.kw_initial,
3391 Keywords.kw_foreach, Keywords.kw_forever,
3392 Keywords.kw_repeat))) &&
3393 "'for', 'while' or foreach macro expected");
3394 const bool KeepBraces = !Style.RemoveBracesLLVM ||
3395 FormatTok->isNoneOf(tok::kw_for, tok::kw_while);
3399 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
3401 if (IsCpp && FormatTok->is(tok::kw_co_await))
3403 if (HasParens && FormatTok->is(tok::l_paren)) {
3407 if (Style.isVerilog())
3408 FormatTok->setFinalizedType(TT_ConditionLParen);
3412 if (Style.isVerilog()) {
3414 parseVerilogSensitivityList();
3415 }
else if (Style.AllowShortLoopsOnASingleLine && FormatTok->is(tok::semi) &&
3416 Tokens->getPreviousToken()->is(tok::r_paren)) {
3423 parseLoopBody(KeepBraces,
true);
3426void UnwrappedLineParser::parseDoWhile() {
3427 assert(FormatTok->is(tok::kw_do) &&
"'do' expected");
3430 parseLoopBody(
true, Style.BraceWrapping.BeforeWhile);
3433 if (FormatTok->isNot(tok::kw_while)) {
3438 FormatTok->setFinalizedType(TT_DoWhile);
3446 parseStructuralElement();
3449void UnwrappedLineParser::parseLabel(
bool IsGotoLabel) {
3452 const auto IndentGotoLabel = Style.IndentGotoLabels;
3453 const auto OldLineLevel =
Line->Level;
3460 if (OldLineLevel > 1 || (!
Line->InPPDirective && OldLineLevel > 0))
3464 if (!IsGotoLabel && !Style.IndentCaseBlocks &&
3465 CommentsBeforeNextToken.empty() && FormatTok->is(tok::l_brace)) {
3466 CompoundStatementIndenter Indenter(
this,
Level,
3467 Style.BraceWrapping.AfterCaseLabel,
3468 Style.BraceWrapping.IndentBraces);
3470 if (FormatTok->is(tok::kw_break)) {
3471 if (Style.BraceWrapping.AfterControlStatement ==
3474 if (!Style.IndentCaseBlocks &&
3479 parseStructuralElement();
3483 if (FormatTok->is(tok::semi))
3488 Level = OldLineLevel;
3490 if (FormatTok->isNot(tok::l_brace)) {
3491 parseStructuralElement();
3496void UnwrappedLineParser::parseCaseLabel() {
3497 assert(FormatTok->is(tok::kw_case) &&
"'case' expected");
3498 auto *Case = FormatTok;
3503 if (FormatTok->is(tok::colon)) {
3504 FormatTok->setFinalizedType(TT_CaseLabelColon);
3507 if (Style.isJava() && FormatTok->is(tok::arrow)) {
3508 FormatTok->setFinalizedType(TT_CaseLabelArrow);
3509 Case->setFinalizedType(TT_SwitchExpressionLabel);
3516void UnwrappedLineParser::parseSwitch(
bool IsExpr) {
3517 assert(FormatTok->is(tok::kw_switch) &&
"'switch' expected");
3519 if (FormatTok->is(tok::l_paren))
3522 keepAncestorBraces();
3524 if (FormatTok->is(tok::l_brace)) {
3525 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3526 FormatTok->setFinalizedType(IsExpr ? TT_SwitchExpressionLBrace
3527 : TT_ControlStatementLBrace);
3532 setPreviousRBraceType(TT_ControlStatementRBrace);
3538 parseStructuralElement();
3542 if (Style.RemoveBracesLLVM)
3543 NestedTooDeep.pop_back();
3546void UnwrappedLineParser::parseAccessSpecifier() {
3549 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
3552 if (FormatTok->is(tok::colon))
3560bool UnwrappedLineParser::parseRequires(
bool SeenEqual) {
3561 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3565 switch (Tokens->peekNextToken(
true)->Tok.getKind()) {
3568 parseRequiresExpression();
3575 parseRequiresClause();
3586 auto *PreviousNonComment = FormatTok->getPreviousNonComment();
3588 if (!PreviousNonComment ||
3589 PreviousNonComment->is(TT_RequiresExpressionLBrace)) {
3592 parseRequiresClause();
3596 switch (PreviousNonComment->Tok.getKind()) {
3599 case tok::kw_noexcept:
3604 parseRequiresClause();
3613 auto PrevPrev = PreviousNonComment->getPreviousNonComment();
3614 if ((PrevPrev && PrevPrev->is(tok::kw_const)) || !SeenEqual) {
3615 parseRequiresClause();
3621 if (PreviousNonComment->isTypeOrIdentifier(LangOpts)) {
3623 parseRequiresClause();
3627 parseRequiresExpression();
3637 unsigned StoredPosition = Tokens->getPosition();
3640 auto PeekNext = [&Lookahead, &NextToken,
this] {
3642 NextToken = Tokens->getNextToken();
3645 bool FoundType =
false;
3646 bool LastWasColonColon =
false;
3649 for (; Lookahead < 50; PeekNext()) {
3650 switch (NextToken->Tok.getKind()) {
3651 case tok::kw_volatile:
3654 if (OpenAngles == 0) {
3655 FormatTok = Tokens->setPosition(StoredPosition);
3656 parseRequiresExpression();
3664 case tok::coloncolon:
3665 LastWasColonColon =
true;
3667 case tok::kw_decltype:
3668 case tok::identifier:
3669 if (FoundType && !LastWasColonColon && OpenAngles == 0) {
3670 FormatTok = Tokens->setPosition(StoredPosition);
3671 parseRequiresExpression();
3675 LastWasColonColon =
false;
3684 if (NextToken->isTypeName(LangOpts)) {
3685 FormatTok = Tokens->setPosition(StoredPosition);
3686 parseRequiresExpression();
3693 FormatTok = Tokens->setPosition(StoredPosition);
3694 parseRequiresClause();
3703void UnwrappedLineParser::parseRequiresClause() {
3704 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3709 bool InRequiresExpression =
3710 !FormatTok->Previous ||
3711 FormatTok->Previous->is(TT_RequiresExpressionLBrace);
3713 FormatTok->setFinalizedType(InRequiresExpression
3714 ? TT_RequiresClauseInARequiresExpression
3715 : TT_RequiresClause);
3720 parseConstraintExpression();
3722 if (!InRequiresExpression && FormatTok->Previous)
3723 FormatTok->Previous->ClosesRequiresClause =
true;
3731void UnwrappedLineParser::parseRequiresExpression() {
3732 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3734 FormatTok->setFinalizedType(TT_RequiresExpression);
3737 if (FormatTok->is(tok::l_paren)) {
3738 FormatTok->setFinalizedType(TT_RequiresExpressionLParen);
3742 if (FormatTok->is(tok::l_brace)) {
3743 FormatTok->setFinalizedType(TT_RequiresExpressionLBrace);
3752void UnwrappedLineParser::parseConstraintExpression() {
3759 bool LambdaNextTimeAllowed =
true;
3769 bool TopLevelParensAllowed =
true;
3772 bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed,
false);
3774 switch (FormatTok->Tok.getKind()) {
3775 case tok::kw_requires:
3776 parseRequiresExpression();
3780 if (!TopLevelParensAllowed)
3782 parseParens(TT_BinaryOperator);
3783 TopLevelParensAllowed =
false;
3787 if (!LambdaThisTimeAllowed || !tryToParseLambda())
3794 case tok::kw_struct:
3804 FormatTok->setFinalizedType(TT_BinaryOperator);
3806 LambdaNextTimeAllowed =
true;
3807 TopLevelParensAllowed =
true;
3812 LambdaNextTimeAllowed = LambdaThisTimeAllowed;
3816 case tok::kw_sizeof:
3818 case tok::greaterequal:
3819 case tok::greatergreater:
3821 case tok::lessequal:
3823 case tok::equalequal:
3825 case tok::exclaimequal:
3830 LambdaNextTimeAllowed =
true;
3831 TopLevelParensAllowed =
true;
3836 case tok::numeric_constant:
3837 case tok::coloncolon:
3840 TopLevelParensAllowed =
false;
3845 case tok::kw_static_cast:
3846 case tok::kw_const_cast:
3847 case tok::kw_reinterpret_cast:
3848 case tok::kw_dynamic_cast:
3850 if (FormatTok->isNot(tok::less))
3854 parseBracedList(
true);
3858 if (!FormatTok->Tok.getIdentifierInfo()) {
3868 assert(FormatTok->Previous);
3869 switch (FormatTok->Previous->Tok.getKind()) {
3870 case tok::coloncolon:
3874 case tok::kw_requires:
3876 case tok::kw_template:
3884 if (FormatTok->is(tok::less)) {
3886 parseBracedList(
true);
3888 TopLevelParensAllowed =
false;
3894bool UnwrappedLineParser::parseEnum() {
3898 if (FormatTok->is(tok::kw_enum))
3904 if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question))
3913 if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
3915 while (FormatTok->is(tok::l_square))
3916 if (!handleCppAttributes())
3920 while (FormatTok->Tok.getIdentifierInfo() ||
3921 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
3922 tok::greater, tok::comma, tok::question,
3924 if (FormatTok->is(tok::colon))
3925 FormatTok->setFinalizedType(TT_EnumUnderlyingTypeColon);
3926 if (Style.isVerilog()) {
3927 FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
3930 while (FormatTok->is(tok::l_square))
3936 if (FormatTok->is(tok::l_paren))
3938 if (FormatTok->is(tok::identifier)) {
3942 if (IsCpp && FormatTok->is(tok::identifier))
3948 if (FormatTok->isNot(tok::l_brace))
3950 FormatTok->setFinalizedType(TT_EnumLBrace);
3951 FormatTok->setBlockKind(BK_Block);
3953 if (Style.isJava()) {
3955 parseJavaEnumBody();
3963 const bool ManageWhitesmithsBraces =
3966 if (!Style.AllowShortEnumsOnASingleLine &&
3968 Tokens->peekNextToken()->is(tok::r_brace))) {
3973 if (ManageWhitesmithsBraces)
3978 if (!Style.AllowShortEnumsOnASingleLine) {
3980 if (!ManageWhitesmithsBraces)
3983 const auto OpeningLineIndex = CurrentLines->empty()
3984 ? UnwrappedLine::kInvalidIndex
3985 : CurrentLines->size() - 1;
3986 bool HasError = !parseBracedList(
false,
true);
3987 if (!Style.AllowShortEnumsOnASingleLine && !ManageWhitesmithsBraces)
3990 if (FormatTok->is(tok::semi))
3994 setPreviousRBraceType(TT_EnumRBrace);
3995 if (ManageWhitesmithsBraces)
3996 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
4004bool UnwrappedLineParser::parseStructLike() {
4009 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp()) {
4010 if (FormatTok->is(tok::semi))
4021class ScopedTokenPosition {
4022 unsigned StoredPosition;
4023 FormatTokenSource *Tokens;
4026 ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) {
4027 assert(Tokens &&
"Tokens expected to not be null");
4028 StoredPosition = Tokens->getPosition();
4031 ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); }
4037bool UnwrappedLineParser::tryToParseSimpleAttribute() {
4038 ScopedTokenPosition AutoPosition(Tokens);
4046 if (
Tok->
is(tok::r_square))
4048 Tok = Tokens->getNextToken();
4050 if (
Tok->
is(tok::eof))
4052 Tok = Tokens->getNextToken();
4055 Tok = Tokens->getNextToken();
4056 if (
Tok->
is(tok::semi))
4061void UnwrappedLineParser::parseJavaEnumBody() {
4062 assert(FormatTok->is(tok::l_brace));
4068 unsigned StoredPosition = Tokens->getPosition();
4069 bool IsSimple =
true;
4072 if (
Tok->
is(tok::r_brace))
4080 Tok = Tokens->getNextToken();
4082 FormatTok = Tokens->setPosition(StoredPosition);
4099 if (FormatTok->is(tok::l_brace)) {
4101 parseBlock(
true, 1u,
4103 }
else if (FormatTok->is(tok::l_paren)) {
4105 }
else if (FormatTok->is(tok::comma)) {
4108 }
else if (FormatTok->is(tok::semi)) {
4112 }
else if (FormatTok->is(tok::r_brace)) {
4121 parseLevel(OpeningBrace);
4127void UnwrappedLineParser::parseRecord(
bool ParseAsExpr,
bool IsJavaRecord) {
4128 assert(!IsJavaRecord || FormatTok->is(Keywords.kw_record));
4133 IsJavaRecord && FormatTok->is(tok::identifier) ? FormatTok :
nullptr;
4134 bool IsDerived =
false;
4136 return Tok->
is(tok::identifier) &&
Tok->TokenText !=
Tok->TokenText.upper();
4140 bool JSPastExtendsOrImplements =
false;
4144 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
4145 tok::kw_alignas, tok::l_square) ||
4146 FormatTok->isAttribute() ||
4147 ((Style.isJava() || Style.isJavaScript()) &&
4148 FormatTok->isOneOf(tok::period, tok::comma))) {
4149 if (Style.isJavaScript() &&
4150 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
4151 JSPastExtendsOrImplements =
true;
4156 if (FormatTok->is(tok::l_brace)) {
4157 tryToParseBracedList();
4161 if (FormatTok->is(tok::l_square) && handleCppAttributes())
4165 switch (FormatTok->Tok.getKind()) {
4168 if (IsJavaRecord || !IsNonMacroIdentifier(
Previous) ||
4170 Previous->Previous == &InitialToken) {
4174 case tok::coloncolon:
4178 if (JSPastExtendsOrImplements || ClassName ||
4189 auto IsListInitialization = [&] {
4190 if (!ClassName || IsDerived || JSPastExtendsOrImplements)
4192 assert(FormatTok->is(tok::l_brace));
4193 const auto *Prev = FormatTok->getPreviousNonComment();
4195 return Prev != ClassName && Prev->is(tok::identifier) &&
4196 Prev->isNot(Keywords.kw_final) && tryToParseBracedList();
4199 if (FormatTok->isOneOf(tok::colon, tok::less)) {
4200 int AngleNestingLevel = 0;
4202 if (FormatTok->is(tok::less))
4203 ++AngleNestingLevel;
4204 else if (FormatTok->is(tok::greater))
4205 --AngleNestingLevel;
4207 if (AngleNestingLevel == 0) {
4208 if (FormatTok->is(tok::colon)) {
4210 }
else if (!IsDerived && FormatTok->is(tok::identifier) &&
4211 FormatTok->Previous->is(tok::coloncolon)) {
4212 ClassName = FormatTok;
4213 }
else if (FormatTok->is(tok::l_paren) &&
4214 IsNonMacroIdentifier(FormatTok->Previous)) {
4218 if (FormatTok->is(tok::l_brace)) {
4219 if (AngleNestingLevel == 0 && IsListInitialization())
4221 calculateBraceTypes(
true);
4222 if (!tryToParseBracedList())
4225 if (FormatTok->is(tok::l_square)) {
4228 !
Previous->isTypeOrIdentifier(LangOpts))) {
4231 if (!tryToParseLambda())
4238 if (FormatTok->is(tok::semi))
4240 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
4243 parseCSharpGenericTypeConstraint();
4250 auto GetBraceTypes =
4251 [](
const FormatToken &RecordTok) -> std::pair<TokenType, TokenType> {
4252 switch (RecordTok.Tok.getKind()) {
4254 return {TT_ClassLBrace, TT_ClassRBrace};
4255 case tok::kw_struct:
4256 return {TT_StructLBrace, TT_StructRBrace};
4258 return {TT_UnionLBrace, TT_UnionRBrace};
4261 return {TT_RecordLBrace, TT_RecordRBrace};
4264 if (FormatTok->is(tok::l_brace)) {
4265 if (IsListInitialization())
4268 ClassName->setFinalizedType(TT_ClassHeadName);
4269 auto [OpenBraceType, ClosingBraceType] = GetBraceTypes(InitialToken);
4270 FormatTok->setFinalizedType(OpenBraceType);
4275 Tokens->peekNextToken()->is(tok::r_brace),
4280 unsigned AddLevels = Style.IndentAccessModifiers ? 2u : 1u;
4281 parseBlock(
true, AddLevels,
false);
4283 setPreviousRBraceType(ClosingBraceType);
4290void UnwrappedLineParser::parseObjCMethod() {
4291 assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) &&
4292 "'(' or identifier expected.");
4294 if (FormatTok->is(tok::semi)) {
4298 }
else if (FormatTok->is(tok::l_brace)) {
4299 if (Style.BraceWrapping.AfterFunction)
4310void UnwrappedLineParser::parseObjCProtocolList() {
4311 assert(FormatTok->is(tok::less) &&
"'<' expected.");
4315 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4317 }
while (!
eof() && FormatTok->isNot(tok::greater));
4321void UnwrappedLineParser::parseObjCUntilAtEnd() {
4323 if (FormatTok->is(tok::objc_end)) {
4328 if (FormatTok->is(tok::l_brace)) {
4332 }
else if (FormatTok->is(tok::r_brace)) {
4336 }
else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
4338 if (FormatTok->isOneOf(tok::l_paren, tok::identifier))
4341 parseStructuralElement();
4346void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
4347 assert(FormatTok->isOneOf(tok::objc_interface, tok::objc_implementation));
4353 if (FormatTok->is(tok::less))
4354 parseObjCLightweightGenerics();
4355 if (FormatTok->is(tok::colon)) {
4359 if (FormatTok->is(tok::less))
4360 parseObjCLightweightGenerics();
4361 }
else if (FormatTok->is(tok::l_paren)) {
4366 if (FormatTok->is(tok::less))
4367 parseObjCProtocolList();
4369 if (FormatTok->is(tok::l_brace)) {
4370 if (Style.BraceWrapping.AfterObjCDeclaration)
4379 parseObjCUntilAtEnd();
4382void UnwrappedLineParser::parseObjCLightweightGenerics() {
4383 assert(FormatTok->is(tok::less));
4391 unsigned NumOpenAngles = 1;
4395 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4397 if (FormatTok->is(tok::less)) {
4399 }
else if (FormatTok->is(tok::greater)) {
4400 assert(NumOpenAngles > 0 &&
"'>' makes NumOpenAngles negative");
4403 }
while (!
eof() && NumOpenAngles != 0);
4409bool UnwrappedLineParser::parseObjCProtocol() {
4410 assert(FormatTok->is(tok::objc_protocol));
4413 if (FormatTok->is(tok::l_paren)) {
4425 if (FormatTok->is(tok::less))
4426 parseObjCProtocolList();
4429 if (FormatTok->is(tok::semi)) {
4436 parseObjCUntilAtEnd();
4440void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
4441 bool IsImport = FormatTok->is(Keywords.kw_import);
4442 assert(IsImport || FormatTok->is(tok::kw_export));
4446 if (FormatTok->is(tok::kw_default))
4452 if (FormatTok->is(Keywords.kw_async))
4454 if (FormatTok->is(Keywords.kw_function)) {
4463 if (!IsImport && FormatTok->isNoneOf(tok::l_brace, tok::star) &&
4464 !FormatTok->isStringLiteral() &&
4465 !(FormatTok->is(Keywords.kw_type) &&
4466 Tokens->peekNextToken()->isOneOf(tok::l_brace, tok::star))) {
4471 if (FormatTok->is(tok::semi))
4473 if (
Line->Tokens.empty()) {
4478 if (FormatTok->is(tok::l_brace)) {
4479 FormatTok->setBlockKind(BK_Block);
4488void UnwrappedLineParser::parseStatementMacro() {
4490 if (FormatTok->is(tok::l_paren))
4492 if (FormatTok->is(tok::semi))
4497void UnwrappedLineParser::parseVerilogHierarchyIdentifier() {
4500 if (FormatTok->isOneOf(tok::star, tok::period, tok::periodstar,
4501 tok::coloncolon, tok::hash) ||
4502 Keywords.isVerilogIdentifier(*FormatTok)) {
4504 }
else if (FormatTok->is(tok::l_square)) {
4512void UnwrappedLineParser::parseVerilogSensitivityList() {
4513 if (FormatTok->isNot(tok::at))
4517 if (FormatTok->is(tok::at))
4519 switch (FormatTok->Tok.getKind()) {
4527 parseVerilogHierarchyIdentifier();
4532unsigned UnwrappedLineParser::parseVerilogHierarchyHeader() {
4533 unsigned AddLevels = 0;
4535 if (FormatTok->is(Keywords.kw_clocking)) {
4537 if (Keywords.isVerilogIdentifier(*FormatTok))
4539 parseVerilogSensitivityList();
4540 if (FormatTok->is(tok::semi))
4542 }
else if (FormatTok->isOneOf(tok::kw_case, Keywords.kw_casex,
4543 Keywords.kw_casez, Keywords.kw_randcase,
4544 Keywords.kw_randsequence)) {
4545 if (Style.IndentCaseLabels)
4548 if (FormatTok->is(tok::l_paren)) {
4549 FormatTok->setFinalizedType(TT_ConditionLParen);
4552 if (FormatTok->isOneOf(Keywords.kw_inside, Keywords.kw_matches))
4561 if (FormatTok->is(tok::l_square)) {
4562 auto Prev = FormatTok->getPreviousNonComment();
4563 if (Prev && Keywords.isVerilogIdentifier(*Prev))
4564 Prev->setFinalizedType(TT_VerilogDimensionedTypeName);
4566 }
else if (Keywords.isVerilogIdentifier(*FormatTok) ||
4567 FormatTok->isOneOf(tok::hash, tok::hashhash, tok::coloncolon,
4568 Keywords.kw_automatic, tok::kw_static)) {
4575 auto NewLine = [
this]() {
4577 Line->IsContinuation =
true;
4581 while (FormatTok->is(Keywords.kw_import)) {
4584 parseVerilogHierarchyIdentifier();
4585 if (FormatTok->is(tok::semi))
4590 if (FormatTok->is(Keywords.kw_verilogHash)) {
4593 if (FormatTok->is(tok::l_paren)) {
4594 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4598 if (FormatTok->is(tok::l_paren)) {
4600 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4605 if (FormatTok->is(Keywords.kw_extends)) {
4608 parseVerilogHierarchyIdentifier();
4609 if (FormatTok->is(tok::l_paren))
4612 if (FormatTok->is(Keywords.kw_implements)) {
4616 parseVerilogHierarchyIdentifier();
4617 }
while (FormatTok->is(tok::comma));
4621 if (FormatTok->is(tok::at)) {
4623 parseVerilogSensitivityList();
4626 if (FormatTok->is(tok::semi))
4634void UnwrappedLineParser::parseVerilogTable() {
4635 assert(FormatTok->is(Keywords.kw_table));
4639 auto InitialLevel =
Line->Level++;
4640 while (!
eof() && !Keywords.isVerilogEnd(*FormatTok)) {
4643 if (
Tok->
is(tok::semi))
4645 else if (
Tok->
isOneOf(tok::star, tok::colon, tok::question, tok::minus))
4646 Tok->setFinalizedType(TT_VerilogTableItem);
4648 Line->Level = InitialLevel;
4653void UnwrappedLineParser::parseVerilogCaseLabel() {
4659 auto OrigLevel =
Line->Level;
4660 auto FirstLine = CurrentLines->size();
4661 if (
Line->Level == 0 || (
Line->InPPDirective &&
Line->Level <= 1))
4663 else if (!Style.IndentCaseBlocks && Keywords.isVerilogBegin(*FormatTok))
4665 parseStructuralElement();
4668 if (CurrentLines->size() > FirstLine)
4669 (*CurrentLines)[FirstLine].Level = OrigLevel;
4670 Line->Level = OrigLevel;
4673void UnwrappedLineParser::parseVerilogExtern() {
4675 FormatTok->isOneOf(tok::kw_extern, tok::kw_export, Keywords.kw_import));
4678 if (FormatTok->is(tok::string_literal))
4680 skipVerilogQualifiers();
4681 if (Keywords.isVerilogIdentifier(*FormatTok))
4683 if (FormatTok->is(tok::equal))
4685 if (Keywords.isVerilogHierarchy(*FormatTok))
4686 parseVerilogHierarchyHeader();
4689void UnwrappedLineParser::skipVerilogQualifiers() {
4690 while (FormatTok->isOneOf(tok::kw_protected, tok::kw_virtual, tok::kw_static,
4691 Keywords.kw_rand, Keywords.kw_context,
4692 Keywords.kw_pure, Keywords.kw_randc,
4693 Keywords.kw_local)) {
4698bool UnwrappedLineParser::containsExpansion(
const UnwrappedLine &
Line)
const {
4699 for (
const auto &N :
Line.Tokens) {
4700 if (N.Tok->MacroCtx)
4702 for (
const UnwrappedLine &Child : N.Children)
4703 if (containsExpansion(Child))
4709void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) {
4710 if (
Line->Tokens.empty())
4713 if (!parsingPPDirective()) {
4714 llvm::dbgs() <<
"Adding unwrapped line:\n";
4715 printDebugInfo(*
Line);
4723 bool ClosesWhitesmithsBlock =
4724 Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex &&
4730 if (!parsingPPDirective() && !InExpansion && containsExpansion(*
Line)) {
4732 Reconstruct.emplace(
Line->Level, Unexpanded);
4733 Reconstruct->addLine(*
Line);
4738 CurrentExpandedLines.push_back(std::move(*
Line));
4740 if (Reconstruct->finished()) {
4741 UnwrappedLine Reconstructed = std::move(*Reconstruct).takeResult();
4742 assert(!Reconstructed.Tokens.empty() &&
4743 "Reconstructed must at least contain the macro identifier.");
4744 assert(!parsingPPDirective());
4746 llvm::dbgs() <<
"Adding unexpanded line:\n";
4747 printDebugInfo(Reconstructed);
4749 ExpandedLines[Reconstructed.Tokens.begin()->Tok] = CurrentExpandedLines;
4750 Lines.push_back(std::move(Reconstructed));
4751 CurrentExpandedLines.clear();
4752 Reconstruct.reset();
4757 assert(!Reconstruct || (CurrentLines != &Lines) || !PPStack.empty());
4758 CurrentLines->push_back(std::move(*
Line));
4760 Line->Tokens.clear();
4761 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
4762 Line->FirstStartColumn = 0;
4763 Line->IsContinuation =
false;
4764 Line->SeenDecltypeAuto =
false;
4765 Line->IsModuleOrImportDecl =
false;
4767 if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove)
4769 if (!parsingPPDirective() && !PreprocessorDirectives.empty()) {
4770 CurrentLines->append(
4771 std::make_move_iterator(PreprocessorDirectives.begin()),
4772 std::make_move_iterator(PreprocessorDirectives.end()));
4773 PreprocessorDirectives.clear();
4776 FormatTok->Previous =
nullptr;
4779bool UnwrappedLineParser::eof()
const {
return FormatTok->is(tok::eof); }
4781bool UnwrappedLineParser::isOnNewLine(
const FormatToken &FormatTok) {
4782 return (
Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
4783 FormatTok.NewlinesBefore > 0;
4791 const llvm::Regex &CommentPragmasRegex) {
4795 StringRef IndentContent = FormatTok.
TokenText;
4796 if (FormatTok.
TokenText.starts_with(
"//") ||
4797 FormatTok.
TokenText.starts_with(
"/*")) {
4798 IndentContent = FormatTok.
TokenText.substr(2);
4800 if (CommentPragmasRegex.match(IndentContent))
4875 if (PreviousToken && PreviousToken->
is(tok::l_brace) &&
4877 MinColumnToken = PreviousToken;
4880 PreviousToken = Node.
Tok;
4884 MinColumnToken = Node.
Tok;
4886 if (PreviousToken && PreviousToken->
is(tok::l_brace))
4887 MinColumnToken = PreviousToken;
4893void UnwrappedLineParser::flushComments(
bool NewlineBeforeNext) {
4894 bool JustComments =
Line->Tokens.empty();
4904 Tok->ContinuesLineCommentSection =
4905 continuesLineCommentSection(*
Tok, *
Line, Style, CommentPragmasRegex);
4906 if (isOnNewLine(*
Tok) && JustComments && !
Tok->ContinuesLineCommentSection)
4910 if (NewlineBeforeNext && JustComments)
4912 CommentsBeforeNextToken.clear();
4915void UnwrappedLineParser::nextToken(
int LevelDifference) {
4918 flushComments(isOnNewLine(*FormatTok));
4919 pushToken(FormatTok);
4921 if (!Style.isJavaScript())
4922 readToken(LevelDifference);
4924 readTokenWithJavaScriptASI();
4926 if (Style.isVerilog()) {
4933 if (Keywords.isVerilogEnd(*FormatTok))
4934 FormatTok->Tok.setKind(tok::r_brace);
4938void UnwrappedLineParser::distributeComments(
4958 if (Comments.empty())
4960 bool ShouldPushCommentsInCurrentLine =
true;
4961 bool HasTrailAlignedWithNextToken =
false;
4962 unsigned StartOfTrailAlignedWithNextToken = 0;
4965 for (
unsigned i = Comments.size() - 1; i > 0; --i) {
4967 HasTrailAlignedWithNextToken =
true;
4968 StartOfTrailAlignedWithNextToken = i;
4972 for (
unsigned i = 0, e = Comments.size(); i < e; ++i) {
4974 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
4975 FormatTok->ContinuesLineCommentSection =
false;
4978 *FormatTok, *
Line, Style, CommentPragmasRegex);
4980 if (!FormatTok->ContinuesLineCommentSection &&
4981 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
4982 ShouldPushCommentsInCurrentLine =
false;
4984 if (ShouldPushCommentsInCurrentLine)
4985 pushToken(FormatTok);
4987 CommentsBeforeNextToken.push_back(FormatTok);
4991void UnwrappedLineParser::readToken(
int LevelDifference) {
4993 bool PreviousWasComment =
false;
4994 bool FirstNonCommentOnLine =
false;
4996 FormatTok = Tokens->getNextToken();
4998 while (FormatTok->isOneOf(TT_ConflictStart, TT_ConflictEnd,
4999 TT_ConflictAlternative)) {
5000 if (FormatTok->is(TT_ConflictStart))
5001 conditionalCompilationStart(
false);
5002 else if (FormatTok->is(TT_ConflictAlternative))
5003 conditionalCompilationAlternative();
5004 else if (FormatTok->is(TT_ConflictEnd))
5005 conditionalCompilationEnd();
5006 FormatTok = Tokens->getNextToken();
5007 FormatTok->MustBreakBefore =
true;
5008 FormatTok->MustBreakBeforeFinalized =
true;
5011 auto IsFirstNonCommentOnLine = [](
bool FirstNonCommentOnLine,
5013 bool PreviousWasComment) {
5015 return Tok.HasUnescapedNewline ||
Tok.IsFirst;
5020 if (PreviousWasComment)
5021 return FirstNonCommentOnLine || IsFirstOnLine(
Tok);
5022 return IsFirstOnLine(
Tok);
5025 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
5026 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
5027 PreviousWasComment = FormatTok->is(tok::comment);
5029 while (!
Line->InPPDirective && FormatTok->is(tok::hash) &&
5030 FirstNonCommentOnLine) {
5033 const auto *
Next = Tokens->peekNextToken();
5034 if ((Style.isVerilog() && !Keywords.isVerilogPPDirective(*
Next)) ||
5035 (Style.isTableGen() &&
5036 Next->isNoneOf(tok::kw_else, tok::pp_define, tok::pp_ifdef,
5037 tok::pp_ifndef, tok::pp_endif))) {
5040 distributeComments(Comments, FormatTok);
5044 bool SwitchToPreprocessorLines = !
Line->Tokens.empty();
5045 ScopedLineState BlockState(*
this, SwitchToPreprocessorLines);
5046 assert((LevelDifference >= 0 ||
5047 static_cast<unsigned>(-LevelDifference) <=
Line->Level) &&
5048 "LevelDifference makes Line->Level negative");
5049 Line->Level += LevelDifference;
5054 PPBranchLevel > 0) {
5055 Line->Level += PPBranchLevel;
5057 assert(
Line->Level >=
Line->UnbracedBodyLevel);
5058 Line->Level -=
Line->UnbracedBodyLevel;
5059 flushComments(isOnNewLine(*FormatTok));
5060 const bool IsEndIf = Tokens->peekNextToken()->is(tok::pp_endif);
5062 PreviousWasComment = FormatTok->is(tok::comment);
5063 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
5064 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
5067 if (IsEndIf && IncludeGuard == IG_Defined && PPBranchLevel == -1 &&
5068 getIncludeGuardState(Style.IndentPPDirectives) == IG_Inited &&
5070 (PreviousWasComment &&
5071 Tokens->peekNextToken(
true)->is(tok::eof)))) {
5072 IncludeGuard = IG_Found;
5076 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
5077 !
Line->InPPDirective) {
5081 if (FormatTok->is(tok::identifier) &&
5082 Macros.defined(FormatTok->TokenText) &&
5084 !
Line->InPPDirective) {
5086 unsigned Position = Tokens->getPosition();
5090 auto PreCall = std::move(
Line);
5091 Line.reset(
new UnwrappedLine);
5092 bool OldInExpansion = InExpansion;
5095 auto Args = parseMacroCall();
5096 InExpansion = OldInExpansion;
5097 assert(
Line->Tokens.front().Tok == ID);
5099 auto UnexpandedLine = std::move(
Line);
5101 Line = std::move(PreCall);
5104 llvm::dbgs() <<
"Macro call: " <<
ID->TokenText <<
"(";
5106 llvm::dbgs() <<
"(";
5107 for (
const auto &Arg : Args.value())
5108 for (
const auto &
T : Arg)
5109 llvm::dbgs() <<
T->TokenText <<
" ";
5110 llvm::dbgs() <<
")";
5112 llvm::dbgs() <<
"\n";
5114 if (
Macros.objectLike(
ID->TokenText) && Args &&
5115 !
Macros.hasArity(
ID->TokenText, Args->size())) {
5121 LLVM_DEBUG(llvm::dbgs()
5122 <<
"Macro \"" <<
ID->TokenText
5123 <<
"\" not overloaded for arity " << Args->size()
5124 <<
"or not function-like, using object-like overload.");
5126 UnexpandedLine->Tokens.resize(1);
5127 Tokens->setPosition(Position);
5129 assert(!Args &&
Macros.objectLike(
ID->TokenText));
5131 if ((!Args &&
Macros.objectLike(
ID->TokenText)) ||
5132 (Args &&
Macros.hasArity(
ID->TokenText, Args->size()))) {
5135 Unexpanded[
ID] = std::move(UnexpandedLine);
5137 Macros.expand(ID, std::move(Args));
5138 if (!Expansion.empty())
5139 FormatTok = Tokens->insertTokens(Expansion);
5142 llvm::dbgs() <<
"Expanded: ";
5143 for (
const auto &
T : Expansion)
5144 llvm::dbgs() <<
T->TokenText <<
" ";
5145 llvm::dbgs() <<
"\n";
5149 llvm::dbgs() <<
"Did not expand macro \"" <<
ID->TokenText
5150 <<
"\", because it was used ";
5152 llvm::dbgs() <<
"with " << Args->size();
5154 llvm::dbgs() <<
"without";
5155 llvm::dbgs() <<
" arguments, which doesn't match any definition.\n";
5157 Tokens->setPosition(Position);
5162 if (FormatTok->isNot(tok::comment)) {
5163 distributeComments(Comments, FormatTok);
5168 Comments.push_back(FormatTok);
5171 distributeComments(Comments,
nullptr);
5176template <
typename Iterator>
5177void pushTokens(Iterator Begin, Iterator End,
5179 for (
auto I = Begin; I != End; ++I) {
5180 Into.push_back(I->Tok);
5181 for (
const auto &Child : I->Children)
5182 pushTokens(Child.Tokens.begin(), Child.Tokens.end(), Into);
5187std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>
5188UnwrappedLineParser::parseMacroCall() {
5189 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>> Args;
5190 assert(
Line->Tokens.empty());
5192 if (FormatTok->isNot(tok::l_paren))
5194 unsigned Position = Tokens->getPosition();
5198 auto ArgStart = std::prev(
Line->Tokens.end());
5202 switch (FormatTok->Tok.getKind()) {
5207 case tok::r_paren: {
5213 Args->push_back({});
5214 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5223 Args->push_back({});
5224 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5226 ArgStart = std::prev(
Line->Tokens.end());
5234 Line->Tokens.resize(1);
5235 Tokens->setPosition(Position);
5241 Line->Tokens.push_back(UnwrappedLineNode(
Tok));
5242 if (AtEndOfPPLine) {
5243 auto &
Tok = *
Line->Tokens.back().Tok;
5244 Tok.MustBreakBefore =
true;
5245 Tok.MustBreakBeforeFinalized =
true;
5246 Tok.FirstAfterPPLine =
true;
5247 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.