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 if (FormatTok->is(tok::less)) {
1981 parseBracedList(
true);
1984 while (FormatTok->is(tok::star))
1988 if (FormatTok->is(tok::l_paren))
1991 if (FormatTok->is(tok::l_brace))
1996 if (InRequiresExpression)
1997 FormatTok->setFinalizedType(TT_BracedListLBrace);
1998 if (!tryToParsePropertyAccessor() && !tryToParseBracedList()) {
1999 IsDecltypeAutoFunction =
Line->SeenDecltypeAuto;
2004 if (Style.isJava() &&
2005 Line->Tokens.front().Tok->is(Keywords.kw_synchronized)) {
2008 if (Style.BraceWrapping.AfterControlStatement ==
2012 }
else if (Style.BraceWrapping.AfterFunction) {
2016 FormatTok->setFinalizedType(TT_FunctionLBrace);
2018 IsDecltypeAutoFunction =
false;
2026 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
2032 if (Style.BraceWrapping.AfterFunction)
2036 case tok::identifier: {
2037 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where) &&
2038 Line->MustBeDeclaration) {
2040 parseCSharpGenericTypeConstraint();
2043 if (FormatTok->is(TT_MacroBlockEnd)) {
2052 size_t TokenCount =
Line->Tokens.size();
2053 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_function) &&
2056 Line->Tokens.front().Tok->isNot(Keywords.kw_async)))) {
2057 tryToParseJSFunction();
2060 if ((Style.isJavaScript() || Style.isJava()) &&
2061 FormatTok->is(Keywords.kw_interface)) {
2062 if (Style.isJavaScript()) {
2067 unsigned StoredPosition = Tokens->getPosition();
2069 FormatTok = Tokens->setPosition(StoredPosition);
2080 if (Style.isVerilog()) {
2081 if (FormatTok->is(Keywords.kw_table)) {
2082 parseVerilogTable();
2085 if (Keywords.isVerilogBegin(*FormatTok) ||
2086 Keywords.isVerilogHierarchy(*FormatTok)) {
2093 if (!IsCpp && FormatTok->is(Keywords.kw_interface)) {
2094 if (parseStructLike())
2099 if (IsCpp && FormatTok->is(TT_StatementMacro)) {
2100 parseStatementMacro();
2105 StringRef
Text = FormatTok->TokenText;
2112 if (Style.isJavaScript())
2115 auto OneTokenSoFar = [&]() {
2116 auto I =
Line->Tokens.begin(), E =
Line->Tokens.end();
2117 while (I != E && I->Tok->is(tok::comment))
2119 if (Style.isVerilog())
2120 while (I != E && I->Tok->is(tok::hash))
2122 return I != E && (++I == E);
2124 if (OneTokenSoFar()) {
2127 bool FunctionLike = FormatTok->is(tok::l_paren);
2131 bool FollowedByNewline =
2132 CommentsBeforeNextToken.empty()
2133 ? FormatTok->NewlinesBefore > 0
2134 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
2136 if (FollowedByNewline &&
2137 (
Text.size() >= 5 ||
2138 (FunctionLike && FormatTok->isNot(tok::l_paren))) &&
2140 if (PreviousToken->isNot(TT_UntouchableMacroFunc))
2141 PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro);
2149 if ((Style.isJavaScript() || Style.isCSharp()) &&
2150 FormatTok->is(TT_FatArrow)) {
2151 tryToParseChildBlock();
2157 if (FormatTok->is(tok::l_brace)) {
2161 if (!Style.isJavaScript())
2162 FormatTok->setBlockKind(BK_BracedInit);
2165 if (Style.isTableGen() &&
2166 Line->Tokens.begin()->Tok->is(Keywords.kw_defset)) {
2167 FormatTok->setFinalizedType(TT_FunctionLBrace);
2168 parseBlock(
false, 1u,
2176 FormatTok->is(tok::less)) {
2178 parseBracedList(
true);
2185 if (Style.isCSharp() &&
2186 (Tokens->peekNextToken()->isAccessSpecifierKeyword() ||
2193 case tok::kw_switch:
2206 if (Style.isVerilog()) {
2211 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
2218 case tok::kw_default:
2220 if (Style.isVerilog()) {
2221 if (FormatTok->is(tok::colon)) {
2225 if (FormatTok->is(Keywords.kw_clocking)) {
2231 parseVerilogCaseLabel();
2237 if (Style.isVerilog()) {
2238 parseVerilogCaseLabel();
2244 if (FormatTok->is(tok::l_brace))
2245 FormatTok->Previous->setFinalizedType(TT_TemplateCloser);
2254bool UnwrappedLineParser::tryToParsePropertyAccessor() {
2255 assert(FormatTok->is(tok::l_brace));
2256 if (!Style.isCSharp())
2259 if (!FormatTok->Previous || FormatTok->Previous->isNot(tok::identifier))
2267 unsigned int StoredPosition = Tokens->getPosition();
2273 bool HasSpecialAccessor =
false;
2274 bool IsTrivialPropertyAccessor =
true;
2277 if (
const bool IsAccessorKeyword =
2278 Tok->
isOneOf(Keywords.kw_get, Keywords.kw_init, Keywords.kw_set);
2279 IsAccessorKeyword ||
Tok->isAccessSpecifierKeyword() ||
2280 Tok->
isOneOf(tok::l_square, tok::semi, Keywords.kw_internal)) {
2281 if (IsAccessorKeyword)
2282 HasSpecialAccessor =
true;
2283 else if (
Tok->
is(tok::l_square))
2285 Tok = Tokens->getNextToken();
2289 IsTrivialPropertyAccessor =
false;
2294 Tokens->setPosition(StoredPosition);
2300 Tokens->setPosition(StoredPosition);
2301 if (!IsTrivialPropertyAccessor && Style.BraceWrapping.AfterFunction)
2305 switch (FormatTok->Tok.getKind()) {
2308 if (FormatTok->is(tok::equal)) {
2309 while (!
eof() && FormatTok->isNot(tok::semi))
2322 if (FormatTok->is(TT_FatArrow)) {
2326 }
while (!
eof() && FormatTok->isNot(tok::semi));
2335 if (FormatTok->isOneOf(Keywords.kw_get, Keywords.kw_init,
2337 !IsTrivialPropertyAccessor) {
2349bool UnwrappedLineParser::tryToParseLambda() {
2350 assert(FormatTok->is(tok::l_square));
2356 if (!tryToParseLambdaIntroducer())
2360 bool InTemplateParameterList =
false;
2362 while (FormatTok->isNot(tok::l_brace)) {
2363 if (FormatTok->isTypeName(LangOpts) || FormatTok->isAttribute()) {
2367 switch (FormatTok->Tok.getKind()) {
2371 parseParens(TT_PointerOrReference);
2377 assert(FormatTok->Previous);
2378 if (FormatTok->Previous->is(tok::r_square))
2379 InTemplateParameterList =
true;
2384 case tok::kw_struct:
2386 case tok::kw_template:
2387 case tok::kw_typename:
2391 case tok::kw_constexpr:
2392 case tok::kw_consteval:
2395 case tok::identifier:
2396 case tok::numeric_constant:
2397 case tok::coloncolon:
2398 case tok::kw_mutable:
2399 case tok::kw_noexcept:
2400 case tok::kw_static:
2425 case tok::equalequal:
2426 case tok::exclaimequal:
2427 case tok::greaterequal:
2428 case tok::lessequal:
2434 if (Arrow || InTemplateParameterList) {
2443 case tok::kw_requires:
2444 parseRequiresClause();
2447 if (!InTemplateParameterList)
2456 FormatTok->setFinalizedType(TT_LambdaLBrace);
2457 LSquare.setFinalizedType(TT_LambdaLSquare);
2460 Arrow->setFinalizedType(TT_LambdaArrow);
2462 NestedLambdas.push_back(
Line->SeenDecltypeAuto);
2464 assert(!NestedLambdas.empty());
2465 NestedLambdas.pop_back();
2470bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
2475 const auto *PrevPrev =
Previous->getPreviousNonComment();
2476 if (
Previous->is(tok::star) && PrevPrev && PrevPrev->isTypeName(LangOpts))
2484 if (!PrevPrev || PrevPrev->isNoneOf(tok::greater, tok::r_paren))
2488 Previous->isNoneOf(tok::kw_return, tok::kw_co_await, tok::kw_co_yield,
2489 tok::kw_co_return)) {
2493 if (LeftSquare->isCppStructuredBinding(IsCpp))
2495 if (FormatTok->is(tok::l_square) ||
tok::isLiteral(FormatTok->Tok.getKind()))
2497 if (FormatTok->is(tok::r_square)) {
2499 if (
Next->is(tok::greater))
2506void UnwrappedLineParser::tryToParseJSFunction() {
2507 assert(FormatTok->is(Keywords.kw_function));
2508 if (FormatTok->is(Keywords.kw_async))
2514 if (FormatTok->is(tok::star)) {
2515 FormatTok->setFinalizedType(TT_OverloadedOperator);
2520 if (FormatTok->is(tok::identifier))
2523 if (FormatTok->isNot(tok::l_paren))
2529 if (FormatTok->is(tok::colon)) {
2535 if (FormatTok->is(tok::l_brace))
2536 tryToParseBracedList();
2538 while (FormatTok->isNoneOf(tok::l_brace, tok::semi) && !
eof())
2542 if (FormatTok->is(tok::semi))
2548bool UnwrappedLineParser::tryToParseBracedList() {
2549 if (FormatTok->is(BK_Unknown))
2550 calculateBraceTypes();
2551 assert(FormatTok->isNot(BK_Unknown));
2552 if (FormatTok->is(BK_Block))
2559bool UnwrappedLineParser::tryToParseChildBlock() {
2560 assert(Style.isJavaScript() || Style.isCSharp());
2561 assert(FormatTok->is(TT_FatArrow));
2566 if (FormatTok->isNot(tok::l_brace))
2572bool UnwrappedLineParser::parseBracedList(
bool IsAngleBracket,
bool IsEnum) {
2573 assert(!IsAngleBracket || !IsEnum);
2574 bool HasError =
false;
2579 if (Style.isCSharp() && FormatTok->is(TT_FatArrow) &&
2580 tryToParseChildBlock()) {
2583 if (Style.isJavaScript()) {
2584 if (FormatTok->is(Keywords.kw_function)) {
2585 tryToParseJSFunction();
2588 if (FormatTok->is(tok::l_brace)) {
2590 if (tryToParseBracedList())
2595 if (FormatTok->is(IsAngleBracket ? tok::greater : tok::r_brace)) {
2597 FormatTok->setBlockKind(BK_Block);
2598 if (!Style.AllowShortEnumsOnASingleLine)
2604 switch (FormatTok->Tok.getKind()) {
2606 if (Style.isCSharp())
2615 if (Style.isJavaScript()) {
2616 if (FormatTok->is(tok::l_brace))
2624 FormatTok->setBlockKind(BK_BracedInit);
2625 if (!IsAngleBracket) {
2626 auto *Prev = FormatTok->Previous;
2627 if (Prev && Prev->is(tok::greater))
2628 Prev->setFinalizedType(TT_TemplateCloser);
2636 parseBracedList(
true);
2643 if (Style.isJavaScript()) {
2654 if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
2657 case tok::kw_requires:
2658 parseRequiresExpression();
2675bool UnwrappedLineParser::parseParens(TokenType StarAndAmpTokenType,
2677 assert(FormatTok->is(tok::l_paren) &&
"'(' expected.");
2678 auto *LParen = FormatTok;
2679 auto *Prev = FormatTok->Previous;
2680 bool SeenComma =
false;
2681 bool SeenEqual =
false;
2682 bool MightBeFoldExpr =
false;
2683 unsigned ExcessLess = 0;
2685 const bool MightBeStmtExpr = FormatTok->is(tok::l_brace);
2686 if (!InMacroCall && Prev && Prev->is(TT_FunctionLikeMacro))
2689 switch (FormatTok->Tok.getKind()) {
2691 if (parseParens(ExcessLess == 0 ? StarAndAmpTokenType : TT_Unknown,
2695 if (Style.isJava() && FormatTok->is(tok::l_brace))
2698 case tok::r_paren: {
2699 auto *RParen = FormatTok;
2702 auto OptionalParens = [&] {
2704 MightBeStmtExpr || MightBeFoldExpr || SeenComma || InMacroCall ||
2705 Line->InMacroBody || RParen->getPreviousNonComment() == LParen) {
2708 const bool DoubleParens =
2709 Prev->is(tok::l_paren) && FormatTok->is(tok::r_paren);
2711 const auto *PrevPrev = Prev->getPreviousNonComment();
2712 const bool Excluded =
2714 (PrevPrev->isOneOf(tok::kw___attribute, tok::kw_decltype) ||
2716 (PrevPrev->isOneOf(tok::kw_if, tok::kw_while) ||
2717 PrevPrev->endsSequence(tok::kw_constexpr, tok::kw_if))));
2721 const bool CommaSeparated =
2722 Prev->isOneOf(tok::l_paren, tok::comma) &&
2723 FormatTok->isOneOf(tok::comma, tok::r_paren);
2724 if (CommaSeparated &&
2726 !Prev->endsSequence(tok::comma, tok::ellipsis) &&
2728 !(FormatTok->is(tok::comma) &&
2729 Tokens->peekNextToken()->is(tok::ellipsis))) {
2732 const bool ReturnParens =
2734 ((NestedLambdas.empty() && !IsDecltypeAutoFunction) ||
2735 (!NestedLambdas.empty() && !NestedLambdas.back())) &&
2736 Prev->isOneOf(tok::kw_return, tok::kw_co_return) &&
2737 FormatTok->is(tok::semi);
2743 if (OptionalParens()) {
2744 LParen->Optional =
true;
2745 RParen->Optional =
true;
2746 }
else if (Prev->is(TT_TypenameMacro)) {
2747 LParen->setFinalizedType(TT_TypeDeclarationParen);
2748 RParen->setFinalizedType(TT_TypeDeclarationParen);
2749 }
else if (Prev->is(tok::greater) && RParen->Previous == LParen) {
2750 Prev->setFinalizedType(TT_TemplateCloser);
2751 }
else if (FormatTok->is(tok::l_brace) && Prev->is(tok::amp) &&
2753 FormatTok->setBlockKind(BK_BracedInit);
2765 if (!tryToParseBracedList())
2770 if (FormatTok->is(tok::l_brace)) {
2780 MightBeFoldExpr =
true;
2785 if (Style.isCSharp() && FormatTok->is(TT_FatArrow))
2786 tryToParseChildBlock();
2791 if (Style.isJavaScript())
2796 case tok::identifier:
2797 if (Style.isJavaScript() && (FormatTok->is(Keywords.kw_function)))
2798 tryToParseJSFunction();
2802 case tok::kw_switch:
2808 case tok::kw_requires:
2809 parseRequiresExpression();
2825 if (StarAndAmpTokenType != TT_Unknown && ExcessLess == 0)
2826 FormatTok->setFinalizedType(StarAndAmpTokenType);
2838 assert(FormatTok->is(tok::l_square) &&
"'[' expected.");
2839 if (tryToParseLambda())
2843 switch (FormatTok->Tok.getKind()) {
2856 case tok::l_brace: {
2857 if (!tryToParseBracedList())
2864 if (FormatTok->is(tok::l_brace)) {
2876void UnwrappedLineParser::keepAncestorBraces() {
2877 if (!Style.RemoveBracesLLVM)
2880 const int MaxNestingLevels = 2;
2881 const int Size = NestedTooDeep.size();
2882 if (Size >= MaxNestingLevels)
2883 NestedTooDeep[
Size - MaxNestingLevels] =
true;
2884 NestedTooDeep.push_back(
false);
2888 for (
const auto &
Token : llvm::reverse(
Line.Tokens))
2895void UnwrappedLineParser::parseUnbracedBody(
bool CheckEOF) {
2898 if (Style.InsertBraces && !
Line->InPPDirective && !
Line->Tokens.empty() &&
2899 PreprocessorDirectives.empty() && FormatTok->isNot(tok::semi)) {
2901 ? getLastNonComment(*
Line)
2904 if (
Tok->BraceCount < 0) {
2905 assert(
Tok->BraceCount == -1);
2908 Tok->BraceCount = -1;
2914 ++
Line->UnbracedBodyLevel;
2915 parseStructuralElement();
2916 --
Line->UnbracedBodyLevel;
2919 assert(!
Line->InPPDirective);
2921 for (
const auto &L : llvm::reverse(*CurrentLines)) {
2923 Tok = L.Tokens.back().Tok;
2931 if (CheckEOF &&
eof())
2941 assert(LeftBrace->
is(tok::l_brace));
2949 assert(RightBrace->
is(tok::r_brace));
2957void UnwrappedLineParser::handleAttributes() {
2959 if (FormatTok->isAttribute())
2961 else if (FormatTok->is(tok::l_square))
2962 handleCppAttributes();
2965bool UnwrappedLineParser::handleCppAttributes() {
2967 assert(FormatTok->is(tok::l_square));
2968 if (!tryToParseSimpleAttribute())
2975bool UnwrappedLineParser::isBlockBegin(
const FormatToken &
Tok)
const {
2978 return Style.isVerilog() ? Keywords.isVerilogBegin(
Tok)
2979 :
Tok.
is(tok::l_brace);
2982FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
2984 bool IsVerilogAssert) {
2985 assert((FormatTok->is(tok::kw_if) ||
2986 (Style.isVerilog() &&
2987 FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
2988 Keywords.kw_assume, Keywords.kw_cover))) &&
2992 if (IsVerilogAssert) {
2994 if (FormatTok->is(Keywords.kw_verilogHash)) {
2996 if (FormatTok->is(tok::numeric_constant))
2998 }
else if (FormatTok->isOneOf(Keywords.kw_final, Keywords.kw_property,
2999 Keywords.kw_sequence)) {
3005 if (Style.isTableGen()) {
3006 while (!
eof() && FormatTok->isNot(Keywords.kw_then)) {
3013 if (FormatTok->is(tok::exclaim))
3016 bool KeepIfBraces =
true;
3017 if (FormatTok->is(tok::kw_consteval)) {
3020 KeepIfBraces = !Style.RemoveBracesLLVM || KeepBraces;
3021 if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
3023 if (FormatTok->is(tok::l_paren)) {
3024 FormatTok->setFinalizedType(TT_ConditionLParen);
3030 if (IsVerilogAssert && FormatTok->is(tok::semi)) {
3036 bool NeedsUnwrappedLine =
false;
3037 keepAncestorBraces();
3040 IfStmtKind IfBlockKind = IfStmtKind::NotIf;
3042 if (isBlockBegin(*FormatTok)) {
3043 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3044 IfLeftBrace = FormatTok;
3045 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3046 parseBlock(
false, 1u,
3047 true, KeepIfBraces, &IfBlockKind);
3048 setPreviousRBraceType(TT_ControlStatementRBrace);
3049 if (Style.BraceWrapping.BeforeElse)
3052 NeedsUnwrappedLine =
true;
3053 }
else if (IsVerilogAssert && FormatTok->is(tok::kw_else)) {
3056 parseUnbracedBody();
3059 if (Style.RemoveBracesLLVM) {
3060 assert(!NestedTooDeep.empty());
3061 KeepIfBraces = KeepIfBraces ||
3062 (IfLeftBrace && !IfLeftBrace->MatchingParen) ||
3063 NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly ||
3064 IfBlockKind == IfStmtKind::IfElseIf;
3067 bool KeepElseBraces = KeepIfBraces;
3069 IfStmtKind
Kind = IfStmtKind::IfOnly;
3071 if (FormatTok->is(tok::kw_else)) {
3072 if (Style.RemoveBracesLLVM) {
3073 NestedTooDeep.back() =
false;
3074 Kind = IfStmtKind::IfElse;
3078 if (isBlockBegin(*FormatTok)) {
3079 const bool FollowedByIf = Tokens->peekNextToken()->is(tok::kw_if);
3080 FormatTok->setFinalizedType(TT_ElseLBrace);
3081 ElseLeftBrace = FormatTok;
3082 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3083 IfStmtKind ElseBlockKind = IfStmtKind::NotIf;
3085 parseBlock(
false, 1u,
3086 true, KeepElseBraces, &ElseBlockKind);
3087 setPreviousRBraceType(TT_ElseRBrace);
3088 if (FormatTok->is(tok::kw_else)) {
3089 KeepElseBraces = KeepElseBraces ||
3090 ElseBlockKind == IfStmtKind::IfOnly ||
3091 ElseBlockKind == IfStmtKind::IfElseIf;
3092 }
else if (FollowedByIf && IfLBrace && !IfLBrace->Optional) {
3093 KeepElseBraces =
true;
3094 assert(ElseLeftBrace->MatchingParen);
3098 }
else if (!IsVerilogAssert && FormatTok->is(tok::kw_if)) {
3101 const bool IsPrecededByComment =
Previous->is(tok::comment);
3102 if (IsPrecededByComment) {
3106 bool TooDeep =
true;
3107 if (Style.RemoveBracesLLVM) {
3108 Kind = IfStmtKind::IfElseIf;
3109 TooDeep = NestedTooDeep.pop_back_val();
3111 ElseLeftBrace = parseIfThenElse(
nullptr, KeepIfBraces);
3112 if (Style.RemoveBracesLLVM)
3113 NestedTooDeep.push_back(TooDeep);
3114 if (IsPrecededByComment)
3117 parseUnbracedBody(
true);
3120 KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse;
3121 if (NeedsUnwrappedLine)
3125 if (!Style.RemoveBracesLLVM)
3128 assert(!NestedTooDeep.empty());
3129 KeepElseBraces = KeepElseBraces ||
3130 (ElseLeftBrace && !ElseLeftBrace->MatchingParen) ||
3131 NestedTooDeep.back();
3133 NestedTooDeep.pop_back();
3135 if (!KeepIfBraces && !KeepElseBraces) {
3138 }
else if (IfLeftBrace) {
3139 FormatToken *IfRightBrace = IfLeftBrace->MatchingParen;
3141 assert(IfRightBrace->MatchingParen == IfLeftBrace);
3142 assert(!IfLeftBrace->Optional);
3143 assert(!IfRightBrace->Optional);
3144 IfLeftBrace->MatchingParen =
nullptr;
3145 IfRightBrace->MatchingParen =
nullptr;
3155void UnwrappedLineParser::parseTryCatch() {
3156 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) &&
"'try' expected");
3158 bool NeedsUnwrappedLine =
false;
3159 bool HasCtorInitializer =
false;
3160 if (FormatTok->is(tok::colon)) {
3161 auto *Colon = FormatTok;
3164 if (FormatTok->is(tok::identifier)) {
3165 HasCtorInitializer =
true;
3166 Colon->setFinalizedType(TT_CtorInitializerColon);
3171 while (FormatTok->is(tok::comma))
3174 while (FormatTok->is(tok::identifier)) {
3176 if (FormatTok->is(tok::l_paren)) {
3178 }
else if (FormatTok->is(tok::l_brace)) {
3185 while (FormatTok->is(tok::comma))
3190 if (Style.isJava() && FormatTok->is(tok::l_paren))
3193 keepAncestorBraces();
3195 if (FormatTok->is(tok::l_brace)) {
3196 if (HasCtorInitializer)
3197 FormatTok->setFinalizedType(TT_FunctionLBrace);
3198 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3200 if (Style.BraceWrapping.BeforeCatch)
3203 NeedsUnwrappedLine =
true;
3204 }
else if (FormatTok->isNot(tok::kw_catch)) {
3210 parseStructuralElement();
3213 for (
bool SeenCatch =
false;;) {
3214 if (FormatTok->is(tok::at))
3216 if (FormatTok->isNoneOf(tok::kw_catch, Keywords.kw___except,
3217 tok::kw___finally, tok::objc_catch,
3218 tok::objc_finally) &&
3219 !((Style.isJava() || Style.isJavaScript()) &&
3220 FormatTok->is(Keywords.kw_finally))) {
3223 if (FormatTok->is(tok::kw_catch))
3226 while (FormatTok->isNot(tok::l_brace)) {
3227 if (FormatTok->is(tok::l_paren)) {
3231 if (FormatTok->isOneOf(tok::semi, tok::r_brace) ||
eof()) {
3232 if (Style.RemoveBracesLLVM)
3233 NestedTooDeep.pop_back();
3239 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3242 NeedsUnwrappedLine =
false;
3243 Line->MustBeDeclaration =
false;
3244 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3246 if (Style.BraceWrapping.BeforeCatch)
3249 NeedsUnwrappedLine =
true;
3252 if (Style.RemoveBracesLLVM)
3253 NestedTooDeep.pop_back();
3255 if (NeedsUnwrappedLine)
3259void UnwrappedLineParser::parseNamespaceOrExportBlock(
unsigned AddLevels) {
3260 bool ManageWhitesmithsBraces =
3265 if (ManageWhitesmithsBraces)
3270 parseBlock(
true, AddLevels,
true,
3271 true,
nullptr, ManageWhitesmithsBraces);
3273 addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep);
3275 if (ManageWhitesmithsBraces)
3279void UnwrappedLineParser::parseNamespace() {
3280 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
3281 "'namespace' expected");
3285 if (InitialToken.is(TT_NamespaceMacro)) {
3288 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
3289 tok::l_square, tok::period, tok::l_paren) ||
3290 (Style.isCSharp() && FormatTok->is(tok::kw_union))) {
3291 if (FormatTok->is(tok::l_square))
3293 else if (FormatTok->is(tok::l_paren))
3299 if (FormatTok->is(tok::l_brace)) {
3300 FormatTok->setFinalizedType(TT_NamespaceLBrace);
3303 Tokens->peekNextToken()->is(tok::r_brace))) {
3307 unsigned AddLevels =
3310 DeclarationScopeStack.size() > 1)
3313 parseNamespaceOrExportBlock(AddLevels);
3318void UnwrappedLineParser::parseCppExportBlock() {
3319 if (FormatTok->is(tok::l_brace)) {
3320 FormatTok->setFinalizedType(TT_ExportLBrace);
3321 if (Style.BraceWrapping.AfterExportBlock)
3324 parseNamespaceOrExportBlock(Style.IndentExportBlock ? 1 : 0);
3327void UnwrappedLineParser::parseNew() {
3328 assert(FormatTok->is(tok::kw_new) &&
"'new' expected");
3331 if (Style.isCSharp()) {
3334 if (FormatTok->is(tok::l_paren))
3338 if (FormatTok->is(tok::l_brace))
3341 if (FormatTok->isOneOf(tok::semi, tok::comma))
3348 if (!Style.isJava())
3354 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
3358 if (FormatTok->is(tok::l_paren)) {
3362 if (FormatTok->is(tok::l_brace))
3370void UnwrappedLineParser::parseLoopBody(
bool KeepBraces,
bool WrapRightBrace) {
3371 keepAncestorBraces();
3373 if (isBlockBegin(*FormatTok)) {
3374 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3376 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3377 parseBlock(
false, 1u,
3379 setPreviousRBraceType(TT_ControlStatementRBrace);
3381 assert(!NestedTooDeep.empty());
3382 if (!NestedTooDeep.back())
3388 parseUnbracedBody();
3392 NestedTooDeep.pop_back();
3395void UnwrappedLineParser::parseForOrWhileLoop(
bool HasParens) {
3396 assert((FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) ||
3397 (Style.isVerilog() &&
3398 FormatTok->isOneOf(Keywords.kw_always, Keywords.kw_always_comb,
3399 Keywords.kw_always_ff, Keywords.kw_always_latch,
3400 Keywords.kw_final, Keywords.kw_initial,
3401 Keywords.kw_foreach, Keywords.kw_forever,
3402 Keywords.kw_repeat))) &&
3403 "'for', 'while' or foreach macro expected");
3404 const bool KeepBraces = !Style.RemoveBracesLLVM ||
3405 FormatTok->isNoneOf(tok::kw_for, tok::kw_while);
3409 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
3411 if (IsCpp && FormatTok->is(tok::kw_co_await))
3413 if (HasParens && FormatTok->is(tok::l_paren)) {
3417 if (Style.isVerilog())
3418 FormatTok->setFinalizedType(TT_ConditionLParen);
3422 if (Style.isVerilog()) {
3424 parseVerilogSensitivityList();
3425 }
else if (Style.AllowShortLoopsOnASingleLine && FormatTok->is(tok::semi) &&
3426 Tokens->getPreviousToken()->is(tok::r_paren)) {
3433 parseLoopBody(KeepBraces,
true);
3436void UnwrappedLineParser::parseDoWhile() {
3437 assert(FormatTok->is(tok::kw_do) &&
"'do' expected");
3440 parseLoopBody(
true, Style.BraceWrapping.BeforeWhile);
3443 if (FormatTok->isNot(tok::kw_while)) {
3448 FormatTok->setFinalizedType(TT_DoWhile);
3456 parseStructuralElement();
3459void UnwrappedLineParser::parseLabel(
bool IsGotoLabel) {
3462 const auto IndentGotoLabel = Style.IndentGotoLabels;
3463 const auto OldLineLevel =
Line->Level;
3470 if (OldLineLevel > 1 || (!
Line->InPPDirective && OldLineLevel > 0))
3474 if (!IsGotoLabel && !Style.IndentCaseBlocks &&
3475 CommentsBeforeNextToken.empty() && FormatTok->is(tok::l_brace)) {
3476 CompoundStatementIndenter Indenter(
this,
Level,
3477 Style.BraceWrapping.AfterCaseLabel,
3478 Style.BraceWrapping.IndentBraces);
3480 if (FormatTok->is(tok::kw_break)) {
3481 if (Style.BraceWrapping.AfterControlStatement ==
3484 if (!Style.IndentCaseBlocks &&
3489 parseStructuralElement();
3493 if (FormatTok->is(tok::semi))
3498 Level = OldLineLevel;
3500 if (FormatTok->isNot(tok::l_brace)) {
3501 parseStructuralElement();
3506void UnwrappedLineParser::parseCaseLabel() {
3507 assert(FormatTok->is(tok::kw_case) &&
"'case' expected");
3508 auto *Case = FormatTok;
3513 if (FormatTok->is(tok::colon)) {
3514 FormatTok->setFinalizedType(TT_CaseLabelColon);
3517 if (Style.isJava() && FormatTok->is(tok::arrow)) {
3518 FormatTok->setFinalizedType(TT_CaseLabelArrow);
3519 Case->setFinalizedType(TT_SwitchExpressionLabel);
3526void UnwrappedLineParser::parseSwitch(
bool IsExpr) {
3527 assert(FormatTok->is(tok::kw_switch) &&
"'switch' expected");
3529 if (FormatTok->is(tok::l_paren))
3532 keepAncestorBraces();
3534 if (FormatTok->is(tok::l_brace)) {
3535 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3536 FormatTok->setFinalizedType(IsExpr ? TT_SwitchExpressionLBrace
3537 : TT_ControlStatementLBrace);
3542 setPreviousRBraceType(TT_ControlStatementRBrace);
3548 parseStructuralElement();
3552 if (Style.RemoveBracesLLVM)
3553 NestedTooDeep.pop_back();
3556void UnwrappedLineParser::parseAccessSpecifier() {
3559 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
3562 if (FormatTok->is(tok::colon))
3570bool UnwrappedLineParser::parseRequires(
bool SeenEqual) {
3571 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3575 switch (Tokens->peekNextToken(
true)->Tok.getKind()) {
3578 parseRequiresExpression();
3585 parseRequiresClause();
3596 auto *PreviousNonComment = FormatTok->getPreviousNonComment();
3598 if (!PreviousNonComment ||
3599 PreviousNonComment->is(TT_RequiresExpressionLBrace)) {
3602 parseRequiresClause();
3606 switch (PreviousNonComment->Tok.getKind()) {
3609 case tok::kw_noexcept:
3614 parseRequiresClause();
3623 auto PrevPrev = PreviousNonComment->getPreviousNonComment();
3624 if ((PrevPrev && PrevPrev->is(tok::kw_const)) || !SeenEqual) {
3625 parseRequiresClause();
3631 if (PreviousNonComment->isTypeOrIdentifier(LangOpts)) {
3633 parseRequiresClause();
3637 parseRequiresExpression();
3647 unsigned StoredPosition = Tokens->getPosition();
3650 auto PeekNext = [&Lookahead, &NextToken,
this] {
3652 NextToken = Tokens->getNextToken();
3655 bool FoundType =
false;
3656 bool LastWasColonColon =
false;
3659 for (; Lookahead < 50; PeekNext()) {
3660 switch (NextToken->Tok.getKind()) {
3661 case tok::kw_volatile:
3664 if (OpenAngles == 0) {
3665 FormatTok = Tokens->setPosition(StoredPosition);
3666 parseRequiresExpression();
3674 case tok::coloncolon:
3675 LastWasColonColon =
true;
3677 case tok::kw_decltype:
3678 case tok::identifier:
3679 if (FoundType && !LastWasColonColon && OpenAngles == 0) {
3680 FormatTok = Tokens->setPosition(StoredPosition);
3681 parseRequiresExpression();
3685 LastWasColonColon =
false;
3694 if (NextToken->isTypeName(LangOpts)) {
3695 FormatTok = Tokens->setPosition(StoredPosition);
3696 parseRequiresExpression();
3703 FormatTok = Tokens->setPosition(StoredPosition);
3704 parseRequiresClause();
3713void UnwrappedLineParser::parseRequiresClause() {
3714 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3719 bool InRequiresExpression =
3720 !FormatTok->Previous ||
3721 FormatTok->Previous->is(TT_RequiresExpressionLBrace);
3723 FormatTok->setFinalizedType(InRequiresExpression
3724 ? TT_RequiresClauseInARequiresExpression
3725 : TT_RequiresClause);
3730 parseConstraintExpression();
3732 if (!InRequiresExpression && FormatTok->Previous)
3733 FormatTok->Previous->ClosesRequiresClause =
true;
3741void UnwrappedLineParser::parseRequiresExpression() {
3742 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3744 FormatTok->setFinalizedType(TT_RequiresExpression);
3747 if (FormatTok->is(tok::l_paren)) {
3748 FormatTok->setFinalizedType(TT_RequiresExpressionLParen);
3752 if (FormatTok->is(tok::l_brace)) {
3753 FormatTok->setFinalizedType(TT_RequiresExpressionLBrace);
3762void UnwrappedLineParser::parseConstraintExpression() {
3769 bool LambdaNextTimeAllowed =
true;
3779 bool TopLevelParensAllowed =
true;
3782 bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed,
false);
3784 switch (FormatTok->Tok.getKind()) {
3785 case tok::kw_requires:
3786 parseRequiresExpression();
3790 if (!TopLevelParensAllowed)
3792 parseParens(TT_BinaryOperator);
3793 TopLevelParensAllowed =
false;
3797 if (!LambdaThisTimeAllowed || !tryToParseLambda())
3804 case tok::kw_struct:
3814 FormatTok->setFinalizedType(TT_BinaryOperator);
3816 LambdaNextTimeAllowed =
true;
3817 TopLevelParensAllowed =
true;
3822 LambdaNextTimeAllowed = LambdaThisTimeAllowed;
3826 case tok::kw_sizeof:
3828 case tok::greaterequal:
3829 case tok::greatergreater:
3831 case tok::lessequal:
3833 case tok::equalequal:
3835 case tok::exclaimequal:
3840 LambdaNextTimeAllowed =
true;
3841 TopLevelParensAllowed =
true;
3846 case tok::numeric_constant:
3847 case tok::coloncolon:
3850 TopLevelParensAllowed =
false;
3855 case tok::kw_static_cast:
3856 case tok::kw_const_cast:
3857 case tok::kw_reinterpret_cast:
3858 case tok::kw_dynamic_cast:
3860 if (FormatTok->isNot(tok::less))
3864 parseBracedList(
true);
3868 if (!FormatTok->Tok.getIdentifierInfo()) {
3878 assert(FormatTok->Previous);
3879 switch (FormatTok->Previous->Tok.getKind()) {
3880 case tok::coloncolon:
3884 case tok::kw_requires:
3886 case tok::kw_template:
3894 if (FormatTok->is(tok::less)) {
3896 parseBracedList(
true);
3898 TopLevelParensAllowed =
false;
3904bool UnwrappedLineParser::parseEnum() {
3908 if (FormatTok->is(tok::kw_enum))
3914 if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question))
3923 if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
3925 while (FormatTok->is(tok::l_square))
3926 if (!handleCppAttributes())
3930 while (FormatTok->Tok.getIdentifierInfo() ||
3931 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
3932 tok::greater, tok::comma, tok::question,
3934 if (FormatTok->is(tok::colon))
3935 FormatTok->setFinalizedType(TT_EnumUnderlyingTypeColon);
3936 if (Style.isVerilog()) {
3937 FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
3940 while (FormatTok->is(tok::l_square))
3946 if (FormatTok->is(tok::l_paren))
3948 if (FormatTok->is(tok::identifier)) {
3952 if (IsCpp && FormatTok->is(tok::identifier))
3958 if (FormatTok->isNot(tok::l_brace))
3960 FormatTok->setFinalizedType(TT_EnumLBrace);
3961 FormatTok->setBlockKind(BK_Block);
3963 if (Style.isJava()) {
3965 parseJavaEnumBody();
3973 const bool ManageWhitesmithsBraces =
3976 if (!Style.AllowShortEnumsOnASingleLine &&
3978 Tokens->peekNextToken()->is(tok::r_brace))) {
3983 if (ManageWhitesmithsBraces)
3988 if (!Style.AllowShortEnumsOnASingleLine) {
3990 if (!ManageWhitesmithsBraces)
3993 const auto OpeningLineIndex = CurrentLines->empty()
3994 ? UnwrappedLine::kInvalidIndex
3995 : CurrentLines->size() - 1;
3996 bool HasError = !parseBracedList(
false,
true);
3997 if (!Style.AllowShortEnumsOnASingleLine && !ManageWhitesmithsBraces)
4000 if (FormatTok->is(tok::semi))
4004 setPreviousRBraceType(TT_EnumRBrace);
4005 if (ManageWhitesmithsBraces)
4006 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
4014bool UnwrappedLineParser::parseStructLike() {
4019 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp()) {
4020 if (FormatTok->is(tok::semi))
4031class ScopedTokenPosition {
4032 unsigned StoredPosition;
4033 FormatTokenSource *Tokens;
4036 ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) {
4037 assert(Tokens &&
"Tokens expected to not be null");
4038 StoredPosition = Tokens->getPosition();
4041 ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); }
4047bool UnwrappedLineParser::tryToParseSimpleAttribute() {
4048 ScopedTokenPosition AutoPosition(Tokens);
4056 if (
Tok->
is(tok::r_square))
4058 Tok = Tokens->getNextToken();
4060 if (
Tok->
is(tok::eof))
4062 Tok = Tokens->getNextToken();
4065 Tok = Tokens->getNextToken();
4066 if (
Tok->
is(tok::semi))
4071void UnwrappedLineParser::parseJavaEnumBody() {
4072 assert(FormatTok->is(tok::l_brace));
4078 unsigned StoredPosition = Tokens->getPosition();
4079 bool IsSimple =
true;
4082 if (
Tok->
is(tok::r_brace))
4090 Tok = Tokens->getNextToken();
4092 FormatTok = Tokens->setPosition(StoredPosition);
4109 if (FormatTok->is(tok::l_brace)) {
4111 parseBlock(
true, 1u,
4113 }
else if (FormatTok->is(tok::l_paren)) {
4115 }
else if (FormatTok->is(tok::comma)) {
4118 }
else if (FormatTok->is(tok::semi)) {
4122 }
else if (FormatTok->is(tok::r_brace)) {
4131 parseLevel(OpeningBrace);
4137void UnwrappedLineParser::parseRecord(
bool ParseAsExpr,
bool IsJavaRecord) {
4138 assert(!IsJavaRecord || FormatTok->is(Keywords.kw_record));
4143 IsJavaRecord && FormatTok->is(tok::identifier) ? FormatTok :
nullptr;
4144 bool IsDerived =
false;
4146 return Tok->
is(tok::identifier) &&
Tok->TokenText !=
Tok->TokenText.upper();
4150 bool JSPastExtendsOrImplements =
false;
4154 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
4155 tok::kw_alignas, tok::l_square) ||
4156 FormatTok->isAttribute() ||
4157 ((Style.isJava() || Style.isJavaScript()) &&
4158 FormatTok->isOneOf(tok::period, tok::comma))) {
4159 if (Style.isJavaScript() &&
4160 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
4161 JSPastExtendsOrImplements =
true;
4166 if (FormatTok->is(tok::l_brace)) {
4167 tryToParseBracedList();
4171 if (FormatTok->is(tok::l_square) && handleCppAttributes())
4175 switch (FormatTok->Tok.getKind()) {
4178 if (IsJavaRecord || !IsNonMacroIdentifier(
Previous) ||
4180 Previous->Previous == &InitialToken) {
4184 case tok::coloncolon:
4188 if (JSPastExtendsOrImplements || ClassName ||
4199 auto IsListInitialization = [&] {
4200 if (!ClassName || IsDerived || JSPastExtendsOrImplements)
4202 assert(FormatTok->is(tok::l_brace));
4203 const auto *Prev = FormatTok->getPreviousNonComment();
4205 return Prev != ClassName && Prev->is(tok::identifier) &&
4206 Prev->isNot(Keywords.kw_final) && tryToParseBracedList();
4209 if (FormatTok->isOneOf(tok::colon, tok::less)) {
4210 int AngleNestingLevel = 0;
4212 if (FormatTok->is(tok::less))
4213 ++AngleNestingLevel;
4214 else if (FormatTok->is(tok::greater))
4215 --AngleNestingLevel;
4217 if (AngleNestingLevel == 0) {
4218 if (FormatTok->is(tok::colon)) {
4220 }
else if (!IsDerived && FormatTok->is(tok::identifier) &&
4221 FormatTok->Previous->is(tok::coloncolon)) {
4222 ClassName = FormatTok;
4223 }
else if (FormatTok->is(tok::l_paren) &&
4224 IsNonMacroIdentifier(FormatTok->Previous)) {
4228 if (FormatTok->is(tok::l_brace)) {
4229 if (AngleNestingLevel == 0 && IsListInitialization())
4231 calculateBraceTypes(
true);
4232 if (!tryToParseBracedList())
4235 if (FormatTok->is(tok::l_square)) {
4238 !
Previous->isTypeOrIdentifier(LangOpts))) {
4241 if (!tryToParseLambda())
4248 if (FormatTok->is(tok::semi))
4250 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
4253 parseCSharpGenericTypeConstraint();
4260 auto GetBraceTypes =
4261 [](
const FormatToken &RecordTok) -> std::pair<TokenType, TokenType> {
4262 switch (RecordTok.Tok.getKind()) {
4264 return {TT_ClassLBrace, TT_ClassRBrace};
4265 case tok::kw_struct:
4266 return {TT_StructLBrace, TT_StructRBrace};
4268 return {TT_UnionLBrace, TT_UnionRBrace};
4271 return {TT_RecordLBrace, TT_RecordRBrace};
4274 if (FormatTok->is(tok::l_brace)) {
4275 if (IsListInitialization())
4278 ClassName->setFinalizedType(TT_ClassHeadName);
4279 auto [OpenBraceType, ClosingBraceType] = GetBraceTypes(InitialToken);
4280 FormatTok->setFinalizedType(OpenBraceType);
4285 Tokens->peekNextToken()->is(tok::r_brace),
4290 unsigned AddLevels = Style.IndentAccessModifiers ? 2u : 1u;
4291 parseBlock(
true, AddLevels,
false);
4293 setPreviousRBraceType(ClosingBraceType);
4300void UnwrappedLineParser::parseObjCMethod() {
4301 assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) &&
4302 "'(' or identifier expected.");
4304 if (FormatTok->is(tok::semi)) {
4308 }
else if (FormatTok->is(tok::l_brace)) {
4309 if (Style.BraceWrapping.AfterFunction)
4320void UnwrappedLineParser::parseObjCProtocolList() {
4321 assert(FormatTok->is(tok::less) &&
"'<' expected.");
4325 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4327 }
while (!
eof() && FormatTok->isNot(tok::greater));
4331void UnwrappedLineParser::parseObjCUntilAtEnd() {
4333 if (FormatTok->is(tok::objc_end)) {
4338 if (FormatTok->is(tok::l_brace)) {
4342 }
else if (FormatTok->is(tok::r_brace)) {
4346 }
else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
4348 if (FormatTok->isOneOf(tok::l_paren, tok::identifier))
4351 parseStructuralElement();
4356void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
4357 assert(FormatTok->isOneOf(tok::objc_interface, tok::objc_implementation));
4363 if (FormatTok->is(tok::less))
4364 parseObjCLightweightGenerics();
4365 if (FormatTok->is(tok::colon)) {
4369 if (FormatTok->is(tok::less))
4370 parseObjCLightweightGenerics();
4371 }
else if (FormatTok->is(tok::l_paren)) {
4376 if (FormatTok->is(tok::less))
4377 parseObjCProtocolList();
4379 if (FormatTok->is(tok::l_brace)) {
4380 if (Style.BraceWrapping.AfterObjCDeclaration)
4389 parseObjCUntilAtEnd();
4392void UnwrappedLineParser::parseObjCLightweightGenerics() {
4393 assert(FormatTok->is(tok::less));
4401 unsigned NumOpenAngles = 1;
4405 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4407 if (FormatTok->is(tok::less)) {
4409 }
else if (FormatTok->is(tok::greater)) {
4410 assert(NumOpenAngles > 0 &&
"'>' makes NumOpenAngles negative");
4413 }
while (!
eof() && NumOpenAngles != 0);
4419bool UnwrappedLineParser::parseObjCProtocol() {
4420 assert(FormatTok->is(tok::objc_protocol));
4423 if (FormatTok->is(tok::l_paren)) {
4435 if (FormatTok->is(tok::less))
4436 parseObjCProtocolList();
4439 if (FormatTok->is(tok::semi)) {
4446 parseObjCUntilAtEnd();
4450void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
4451 bool IsImport = FormatTok->is(Keywords.kw_import);
4452 assert(IsImport || FormatTok->is(tok::kw_export));
4456 if (FormatTok->is(tok::kw_default))
4462 if (FormatTok->is(Keywords.kw_async))
4464 if (FormatTok->is(Keywords.kw_function)) {
4473 if (!IsImport && FormatTok->isNoneOf(tok::l_brace, tok::star) &&
4474 !FormatTok->isStringLiteral() &&
4475 !(FormatTok->is(Keywords.kw_type) &&
4476 Tokens->peekNextToken()->isOneOf(tok::l_brace, tok::star))) {
4481 if (FormatTok->is(tok::semi))
4483 if (
Line->Tokens.empty()) {
4488 if (FormatTok->is(tok::l_brace)) {
4489 FormatTok->setBlockKind(BK_Block);
4498void UnwrappedLineParser::parseStatementMacro() {
4500 if (FormatTok->is(tok::l_paren))
4502 if (FormatTok->is(tok::semi))
4507void UnwrappedLineParser::parseVerilogHierarchyIdentifier() {
4510 if (FormatTok->isOneOf(tok::star, tok::period, tok::periodstar,
4511 tok::coloncolon, tok::hash) ||
4512 Keywords.isVerilogIdentifier(*FormatTok)) {
4514 }
else if (FormatTok->is(tok::l_square)) {
4522void UnwrappedLineParser::parseVerilogSensitivityList() {
4523 if (FormatTok->isNot(tok::at))
4527 if (FormatTok->is(tok::at))
4529 switch (FormatTok->Tok.getKind()) {
4537 parseVerilogHierarchyIdentifier();
4542unsigned UnwrappedLineParser::parseVerilogHierarchyHeader() {
4543 unsigned AddLevels = 0;
4545 if (FormatTok->is(Keywords.kw_clocking)) {
4547 if (Keywords.isVerilogIdentifier(*FormatTok))
4549 parseVerilogSensitivityList();
4550 if (FormatTok->is(tok::semi))
4552 }
else if (FormatTok->isOneOf(tok::kw_case, Keywords.kw_casex,
4553 Keywords.kw_casez, Keywords.kw_randcase,
4554 Keywords.kw_randsequence)) {
4555 if (Style.IndentCaseLabels)
4558 if (FormatTok->is(tok::l_paren)) {
4559 FormatTok->setFinalizedType(TT_ConditionLParen);
4562 if (FormatTok->isOneOf(Keywords.kw_inside, Keywords.kw_matches))
4571 if (FormatTok->is(tok::l_square)) {
4572 auto Prev = FormatTok->getPreviousNonComment();
4573 if (Prev && Keywords.isVerilogIdentifier(*Prev))
4574 Prev->setFinalizedType(TT_VerilogDimensionedTypeName);
4576 }
else if (Keywords.isVerilogIdentifier(*FormatTok) ||
4577 FormatTok->isOneOf(tok::hash, tok::hashhash, tok::coloncolon,
4578 Keywords.kw_automatic, tok::kw_static)) {
4585 auto NewLine = [
this]() {
4587 Line->IsContinuation =
true;
4591 while (FormatTok->is(Keywords.kw_import)) {
4594 parseVerilogHierarchyIdentifier();
4595 if (FormatTok->is(tok::semi))
4600 if (FormatTok->is(Keywords.kw_verilogHash)) {
4603 if (FormatTok->is(tok::l_paren)) {
4604 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4608 if (FormatTok->is(tok::l_paren)) {
4610 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4615 if (FormatTok->is(Keywords.kw_extends)) {
4618 parseVerilogHierarchyIdentifier();
4619 if (FormatTok->is(tok::l_paren))
4622 if (FormatTok->is(Keywords.kw_implements)) {
4626 parseVerilogHierarchyIdentifier();
4627 }
while (FormatTok->is(tok::comma));
4631 if (FormatTok->is(tok::at)) {
4633 parseVerilogSensitivityList();
4636 if (FormatTok->is(tok::semi))
4644void UnwrappedLineParser::parseVerilogTable() {
4645 assert(FormatTok->is(Keywords.kw_table));
4649 auto InitialLevel =
Line->Level++;
4650 while (!
eof() && !Keywords.isVerilogEnd(*FormatTok)) {
4653 if (
Tok->
is(tok::semi))
4655 else if (
Tok->
isOneOf(tok::star, tok::colon, tok::question, tok::minus))
4656 Tok->setFinalizedType(TT_VerilogTableItem);
4658 Line->Level = InitialLevel;
4663void UnwrappedLineParser::parseVerilogCaseLabel() {
4669 auto OrigLevel =
Line->Level;
4670 auto FirstLine = CurrentLines->size();
4671 if (
Line->Level == 0 || (
Line->InPPDirective &&
Line->Level <= 1))
4673 else if (!Style.IndentCaseBlocks && Keywords.isVerilogBegin(*FormatTok))
4675 parseStructuralElement();
4678 if (CurrentLines->size() > FirstLine)
4679 (*CurrentLines)[FirstLine].Level = OrigLevel;
4680 Line->Level = OrigLevel;
4683void UnwrappedLineParser::parseVerilogExtern() {
4685 FormatTok->isOneOf(tok::kw_extern, tok::kw_export, Keywords.kw_import));
4688 if (FormatTok->is(tok::string_literal))
4690 skipVerilogQualifiers();
4691 if (Keywords.isVerilogIdentifier(*FormatTok))
4693 if (FormatTok->is(tok::equal))
4695 if (Keywords.isVerilogHierarchy(*FormatTok))
4696 parseVerilogHierarchyHeader();
4699void UnwrappedLineParser::skipVerilogQualifiers() {
4700 while (FormatTok->isOneOf(tok::kw_protected, tok::kw_virtual, tok::kw_static,
4701 Keywords.kw_rand, Keywords.kw_context,
4702 Keywords.kw_pure, Keywords.kw_randc,
4703 Keywords.kw_local)) {
4708bool UnwrappedLineParser::containsExpansion(
const UnwrappedLine &
Line)
const {
4709 for (
const auto &N :
Line.Tokens) {
4710 if (N.Tok->MacroCtx)
4712 for (
const UnwrappedLine &Child : N.Children)
4713 if (containsExpansion(Child))
4719void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) {
4720 if (
Line->Tokens.empty())
4723 if (!parsingPPDirective()) {
4724 llvm::dbgs() <<
"Adding unwrapped line:\n";
4725 printDebugInfo(*
Line);
4733 bool ClosesWhitesmithsBlock =
4734 Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex &&
4740 if (!parsingPPDirective() && !InExpansion && containsExpansion(*
Line)) {
4742 Reconstruct.emplace(
Line->Level, Unexpanded);
4743 Reconstruct->addLine(*
Line);
4748 CurrentExpandedLines.push_back(std::move(*
Line));
4750 if (Reconstruct->finished()) {
4751 UnwrappedLine Reconstructed = std::move(*Reconstruct).takeResult();
4752 assert(!Reconstructed.Tokens.empty() &&
4753 "Reconstructed must at least contain the macro identifier.");
4754 assert(!parsingPPDirective());
4756 llvm::dbgs() <<
"Adding unexpanded line:\n";
4757 printDebugInfo(Reconstructed);
4759 ExpandedLines[Reconstructed.Tokens.begin()->Tok] = CurrentExpandedLines;
4760 Lines.push_back(std::move(Reconstructed));
4761 CurrentExpandedLines.clear();
4762 Reconstruct.reset();
4767 assert(!Reconstruct || (CurrentLines != &Lines) || !PPStack.empty());
4768 CurrentLines->push_back(std::move(*
Line));
4770 Line->Tokens.clear();
4771 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
4772 Line->FirstStartColumn = 0;
4773 Line->IsContinuation =
false;
4774 Line->SeenDecltypeAuto =
false;
4775 Line->IsModuleOrImportDecl =
false;
4777 if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove)
4779 if (!parsingPPDirective() && !PreprocessorDirectives.empty()) {
4780 CurrentLines->append(
4781 std::make_move_iterator(PreprocessorDirectives.begin()),
4782 std::make_move_iterator(PreprocessorDirectives.end()));
4783 PreprocessorDirectives.clear();
4786 FormatTok->Previous =
nullptr;
4789bool UnwrappedLineParser::eof()
const {
return FormatTok->is(tok::eof); }
4791bool UnwrappedLineParser::isOnNewLine(
const FormatToken &FormatTok) {
4792 return (
Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
4793 FormatTok.NewlinesBefore > 0;
4801 const llvm::Regex &CommentPragmasRegex) {
4805 StringRef IndentContent = FormatTok.
TokenText;
4806 if (FormatTok.
TokenText.starts_with(
"//") ||
4807 FormatTok.
TokenText.starts_with(
"/*")) {
4808 IndentContent = FormatTok.
TokenText.substr(2);
4810 if (CommentPragmasRegex.match(IndentContent))
4885 if (PreviousToken && PreviousToken->
is(tok::l_brace) &&
4887 MinColumnToken = PreviousToken;
4890 PreviousToken = Node.
Tok;
4894 MinColumnToken = Node.
Tok;
4896 if (PreviousToken && PreviousToken->
is(tok::l_brace))
4897 MinColumnToken = PreviousToken;
4903void UnwrappedLineParser::flushComments(
bool NewlineBeforeNext) {
4904 bool JustComments =
Line->Tokens.empty();
4914 Tok->ContinuesLineCommentSection =
4915 continuesLineCommentSection(*
Tok, *
Line, Style, CommentPragmasRegex);
4916 if (isOnNewLine(*
Tok) && JustComments && !
Tok->ContinuesLineCommentSection)
4920 if (NewlineBeforeNext && JustComments)
4922 CommentsBeforeNextToken.clear();
4925void UnwrappedLineParser::nextToken(
int LevelDifference) {
4928 flushComments(isOnNewLine(*FormatTok));
4929 pushToken(FormatTok);
4931 if (!Style.isJavaScript())
4932 readToken(LevelDifference);
4934 readTokenWithJavaScriptASI();
4936 if (Style.isVerilog()) {
4943 if (Keywords.isVerilogEnd(*FormatTok))
4944 FormatTok->Tok.setKind(tok::r_brace);
4948void UnwrappedLineParser::distributeComments(
4968 if (Comments.empty())
4970 bool ShouldPushCommentsInCurrentLine =
true;
4971 bool HasTrailAlignedWithNextToken =
false;
4972 unsigned StartOfTrailAlignedWithNextToken = 0;
4975 for (
unsigned i = Comments.size() - 1; i > 0; --i) {
4977 HasTrailAlignedWithNextToken =
true;
4978 StartOfTrailAlignedWithNextToken = i;
4982 for (
unsigned i = 0, e = Comments.size(); i < e; ++i) {
4984 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
4985 FormatTok->ContinuesLineCommentSection =
false;
4988 *FormatTok, *
Line, Style, CommentPragmasRegex);
4990 if (!FormatTok->ContinuesLineCommentSection &&
4991 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
4992 ShouldPushCommentsInCurrentLine =
false;
4994 if (ShouldPushCommentsInCurrentLine)
4995 pushToken(FormatTok);
4997 CommentsBeforeNextToken.push_back(FormatTok);
5001void UnwrappedLineParser::readToken(
int LevelDifference) {
5003 bool PreviousWasComment =
false;
5004 bool FirstNonCommentOnLine =
false;
5006 FormatTok = Tokens->getNextToken();
5008 while (FormatTok->isOneOf(TT_ConflictStart, TT_ConflictEnd,
5009 TT_ConflictAlternative)) {
5010 if (FormatTok->is(TT_ConflictStart))
5011 conditionalCompilationStart(
false);
5012 else if (FormatTok->is(TT_ConflictAlternative))
5013 conditionalCompilationAlternative();
5014 else if (FormatTok->is(TT_ConflictEnd))
5015 conditionalCompilationEnd();
5016 FormatTok = Tokens->getNextToken();
5017 FormatTok->MustBreakBefore =
true;
5018 FormatTok->MustBreakBeforeFinalized =
true;
5021 auto IsFirstNonCommentOnLine = [](
bool FirstNonCommentOnLine,
5023 bool PreviousWasComment) {
5025 return Tok.HasUnescapedNewline ||
Tok.IsFirst;
5030 if (PreviousWasComment)
5031 return FirstNonCommentOnLine || IsFirstOnLine(
Tok);
5032 return IsFirstOnLine(
Tok);
5035 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
5036 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
5037 PreviousWasComment = FormatTok->is(tok::comment);
5039 while (!
Line->InPPDirective && FormatTok->is(tok::hash) &&
5040 FirstNonCommentOnLine) {
5043 const auto *
Next = Tokens->peekNextToken();
5044 if ((Style.isVerilog() && !Keywords.isVerilogPPDirective(*
Next)) ||
5045 (Style.isTableGen() &&
5046 Next->isNoneOf(tok::kw_else, tok::pp_define, tok::pp_ifdef,
5047 tok::pp_ifndef, tok::pp_endif))) {
5050 distributeComments(Comments, FormatTok);
5054 bool SwitchToPreprocessorLines = !
Line->Tokens.empty();
5055 ScopedLineState BlockState(*
this, SwitchToPreprocessorLines);
5056 assert((LevelDifference >= 0 ||
5057 static_cast<unsigned>(-LevelDifference) <=
Line->Level) &&
5058 "LevelDifference makes Line->Level negative");
5059 Line->Level += LevelDifference;
5064 PPBranchLevel > 0) {
5065 Line->Level += PPBranchLevel;
5067 assert(
Line->Level >=
Line->UnbracedBodyLevel);
5068 Line->Level -=
Line->UnbracedBodyLevel;
5069 flushComments(isOnNewLine(*FormatTok));
5070 const bool IsEndIf = Tokens->peekNextToken()->is(tok::pp_endif);
5072 PreviousWasComment = FormatTok->is(tok::comment);
5073 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
5074 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
5077 if (IsEndIf && IncludeGuard == IG_Defined && PPBranchLevel == -1 &&
5078 getIncludeGuardState(Style.IndentPPDirectives) == IG_Inited &&
5080 (PreviousWasComment &&
5081 Tokens->peekNextToken(
true)->is(tok::eof)))) {
5082 IncludeGuard = IG_Found;
5086 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
5087 !
Line->InPPDirective) {
5091 if (FormatTok->is(tok::identifier) &&
5092 Macros.defined(FormatTok->TokenText) &&
5094 !
Line->InPPDirective) {
5096 unsigned Position = Tokens->getPosition();
5100 auto PreCall = std::move(
Line);
5101 Line.reset(
new UnwrappedLine);
5102 bool OldInExpansion = InExpansion;
5105 auto Args = parseMacroCall();
5106 InExpansion = OldInExpansion;
5107 assert(
Line->Tokens.front().Tok == ID);
5109 auto UnexpandedLine = std::move(
Line);
5111 Line = std::move(PreCall);
5114 llvm::dbgs() <<
"Macro call: " <<
ID->TokenText <<
"(";
5116 llvm::dbgs() <<
"(";
5117 for (
const auto &Arg : Args.value())
5118 for (
const auto &
T : Arg)
5119 llvm::dbgs() <<
T->TokenText <<
" ";
5120 llvm::dbgs() <<
")";
5122 llvm::dbgs() <<
"\n";
5124 if (
Macros.objectLike(
ID->TokenText) && Args &&
5125 !
Macros.hasArity(
ID->TokenText, Args->size())) {
5131 LLVM_DEBUG(llvm::dbgs()
5132 <<
"Macro \"" <<
ID->TokenText
5133 <<
"\" not overloaded for arity " << Args->size()
5134 <<
"or not function-like, using object-like overload.");
5136 UnexpandedLine->Tokens.resize(1);
5137 Tokens->setPosition(Position);
5139 FormatTok = Tokens->getNextToken();
5140 assert(!Args &&
Macros.objectLike(
ID->TokenText));
5142 if ((!Args &&
Macros.objectLike(
ID->TokenText)) ||
5143 (Args &&
Macros.hasArity(
ID->TokenText, Args->size()))) {
5146 Unexpanded[
ID] = std::move(UnexpandedLine);
5148 Macros.expand(ID, std::move(Args));
5149 if (!Expansion.empty())
5150 FormatTok = Tokens->insertTokens(Expansion);
5153 llvm::dbgs() <<
"Expanded: ";
5154 for (
const auto &
T : Expansion)
5155 llvm::dbgs() <<
T->TokenText <<
" ";
5156 llvm::dbgs() <<
"\n";
5160 llvm::dbgs() <<
"Did not expand macro \"" <<
ID->TokenText
5161 <<
"\", because it was used ";
5163 llvm::dbgs() <<
"with " << Args->size();
5165 llvm::dbgs() <<
"without";
5166 llvm::dbgs() <<
" arguments, which doesn't match any definition.\n";
5168 Tokens->setPosition(Position);
5173 if (FormatTok->isNot(tok::comment)) {
5174 distributeComments(Comments, FormatTok);
5179 Comments.push_back(FormatTok);
5182 distributeComments(Comments,
nullptr);
5187template <
typename Iterator>
5188void pushTokens(Iterator Begin, Iterator End,
5190 for (
auto I = Begin; I != End; ++I) {
5191 Into.push_back(I->Tok);
5192 for (
const auto &Child : I->Children)
5193 pushTokens(Child.Tokens.begin(), Child.Tokens.end(), Into);
5198std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>
5199UnwrappedLineParser::parseMacroCall() {
5200 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>> Args;
5201 assert(
Line->Tokens.empty());
5203 if (FormatTok->isNot(tok::l_paren))
5205 unsigned Position = Tokens->getPosition();
5209 auto ArgStart = std::prev(
Line->Tokens.end());
5213 switch (FormatTok->Tok.getKind()) {
5218 case tok::r_paren: {
5224 Args->push_back({});
5225 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5234 Args->push_back({});
5235 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5237 ArgStart = std::prev(
Line->Tokens.end());
5245 Line->Tokens.resize(1);
5246 Tokens->setPosition(Position);
5252 Line->Tokens.push_back(UnwrappedLineNode(
Tok));
5253 if (AtEndOfPPLine) {
5254 auto &
Tok = *
Line->Tokens.back().Tok;
5255 Tok.MustBreakBefore =
true;
5256 Tok.MustBreakBeforeFinalized =
true;
5257 Tok.FirstAfterPPLine =
true;
5258 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.