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;
134 const FormatStyle &Style,
unsigned &LineLevel)
136 Style.BraceWrapping.AfterControlStatement ==
137 FormatStyle::BWACS_Always,
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();
440 if (Style.Language == FormatStyle::LK_Proto || Style.isVerilog() ||
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;
542 if (Style.Language == FormatStyle::LK_Proto) {
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 =
768 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
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 =
969 Style.AllowShortRecordOnASingleLine < FormatStyle::SRS_Empty ||
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())
1193 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
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() {
1235 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
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));
1357 if (Style.Language == FormatStyle::LK_C ||
1358 Style.Standard < FormatStyle::LS_Cpp20) {
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");
1380 if (Style.Language == FormatStyle::LK_C ||
1381 Style.Standard < FormatStyle::LS_Cpp20) {
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()) {
1512 if (FormatTok->is(tok::l_brace)) {
1513 FormatTok->setFinalizedType(TT_InlineASMBrace);
1515 while (FormatTok && !
eof()) {
1516 if (FormatTok->is(tok::r_brace)) {
1517 FormatTok->setFinalizedType(TT_InlineASMBrace);
1522 FormatTok->Finalized =
true;
1527 case tok::kw_namespace:
1531 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1542 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1546 parseForOrWhileLoop();
1549 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1557 case tok::kw_switch:
1558 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1564 case tok::kw_default: {
1566 if (Style.isVerilog())
1568 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1574 if (FormatTok->is(tok::colon)) {
1575 FormatTok->setFinalizedType(TT_CaseLabelColon);
1579 if (FormatTok->is(tok::arrow)) {
1580 FormatTok->setFinalizedType(TT_CaseLabelArrow);
1581 Default->setFinalizedType(TT_SwitchExpressionLabel);
1590 if (Style.Language == FormatStyle::LK_Proto) {
1594 if (Style.isVerilog()) {
1599 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1608 if (FormatTok->is(tok::kw_case))
1613 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1619 case tok::kw_extern:
1620 if (Style.isVerilog()) {
1623 parseVerilogExtern();
1627 if (FormatTok->is(tok::string_literal)) {
1629 if (FormatTok->is(tok::l_brace)) {
1630 if (Style.BraceWrapping.AfterExternBlock)
1634 unsigned AddLevels =
1635 (Style.IndentExternBlock == FormatStyle::IEBS_Indent) ||
1636 (Style.BraceWrapping.AfterExternBlock &&
1637 Style.IndentExternBlock ==
1638 FormatStyle::IEBS_AfterExternBlock)
1641 parseBlock(
true, AddLevels);
1647 case tok::kw_export:
1650 if (FormatTok->is(tok::kw_namespace)) {
1654 if (FormatTok->is(tok::l_brace)) {
1655 parseCppExportBlock();
1658 if (FormatTok->is(Keywords.kw_module) && parseModuleDecl())
1660 if (FormatTok->is(Keywords.kw_import) && parseImportDecl())
1664 if (Style.isJavaScript()) {
1665 parseJavaScriptEs6ImportExport();
1668 if (Style.isVerilog()) {
1669 parseVerilogExtern();
1673 case tok::kw_inline:
1675 if (FormatTok->is(tok::kw_namespace)) {
1680 case tok::identifier:
1681 if (FormatTok->is(TT_ForEachMacro)) {
1682 parseForOrWhileLoop();
1685 if (FormatTok->is(TT_MacroBlockBegin)) {
1686 parseBlock(
false, 1u,
1690 if (FormatTok->is(Keywords.kw_import)) {
1691 if (IsCpp && parseImportDecl())
1693 if (Style.isJavaScript()) {
1694 parseJavaScriptEs6ImportExport();
1697 if (Style.Language == FormatStyle::LK_Proto) {
1699 if (FormatTok->is(tok::kw_public))
1701 if (FormatTok->isNot(tok::string_literal))
1704 if (FormatTok->is(tok::semi))
1709 if (Style.isVerilog()) {
1710 parseVerilogExtern();
1715 if (FormatTok->is(Keywords.kw_module) && parseModuleDecl())
1717 if (FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
1718 Keywords.kw_slots, Keywords.kw_qslots)) {
1720 if (FormatTok->is(tok::colon)) {
1726 if (FormatTok->is(TT_StatementMacro)) {
1727 parseStatementMacro();
1730 if (FormatTok->is(TT_NamespaceMacro)) {
1739 if (!Style.isJavaScript() && !Style.isVerilog() && !Style.isTableGen() &&
1740 Tokens->peekNextToken()->is(tok::colon) && !
Line->MustBeDeclaration) {
1742 if (!
Line->InMacroBody || CurrentLines->size() > 1)
1743 Line->Tokens.begin()->Tok->MustBreakBefore =
true;
1744 FormatTok->setFinalizedType(TT_GotoLabelColon);
1745 parseLabel(Style.IndentGotoLabels);
1750 if (Style.isJava() && FormatTok->is(Keywords.kw_record)) {
1751 parseRecord(
false,
true);
1761 bool SeenEqual =
false;
1762 for (
const bool InRequiresExpression =
1763 OpeningBrace && OpeningBrace->isOneOf(TT_RequiresExpressionLBrace,
1764 TT_CompoundRequirementLBrace);
1767 switch (FormatTok->Tok.getKind()) {
1770 if (FormatTok->is(tok::l_brace)) {
1775 if (Style.isJava() && FormatTok->is(Keywords.kw_interface)) {
1779 switch (
bool IsAutoRelease =
false; FormatTok->Tok.getObjCKeywordID()) {
1780 case tok::objc_public:
1781 case tok::objc_protected:
1782 case tok::objc_package:
1783 case tok::objc_private:
1784 return parseAccessSpecifier();
1785 case tok::objc_interface:
1786 case tok::objc_implementation:
1787 return parseObjCInterfaceOrImplementation();
1788 case tok::objc_protocol:
1789 if (parseObjCProtocol())
1794 case tok::objc_optional:
1795 case tok::objc_required:
1799 case tok::objc_autoreleasepool:
1800 IsAutoRelease =
true;
1802 case tok::objc_synchronized:
1804 if (!IsAutoRelease && FormatTok->is(tok::l_paren)) {
1808 if (FormatTok->is(tok::l_brace)) {
1809 if (Style.BraceWrapping.AfterControlStatement ==
1810 FormatStyle::BWACS_Always) {
1826 case tok::kw_requires: {
1828 bool ParsedClause = parseRequires(SeenEqual);
1849 if (!IsCpp && !Style.isVerilog()) {
1854 case tok::kw_typedef:
1856 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1857 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS,
1858 Keywords.kw_CF_CLOSED_ENUM,
1859 Keywords.kw_NS_CLOSED_ENUM)) {
1864 if (Style.isVerilog()) {
1869 if (Style.isTableGen()) {
1876 case tok::kw_struct:
1878 if (parseStructLike())
1881 case tok::kw_decltype:
1883 if (FormatTok->is(tok::l_paren)) {
1885 if (FormatTok->Previous &&
1886 FormatTok->Previous->endsSequence(tok::r_paren, tok::kw_auto,
1888 Line->SeenDecltypeAuto =
true;
1895 if (Style.isJava() && FormatTok && FormatTok->is(tok::kw_class))
1897 if (Style.isJavaScript() && FormatTok &&
1898 FormatTok->Tok.getIdentifierInfo()) {
1911 case tok::string_literal:
1912 if (Style.isVerilog() && FormatTok->is(TT_VerilogProtected)) {
1913 FormatTok->Finalized =
true;
1920 case tok::l_paren: {
1927 Tokens->peekNextToken(
true),
1934 case tok::kw_operator:
1936 if (FormatTok->isBinaryOperator())
1940 const auto *Prev = FormatTok->getPreviousNonComment();
1942 if (Prev && Prev->is(tok::identifier))
1945 if (FormatTok->Tok.isAnyIdentifier() || FormatTok->isTypeName(LangOpts)) {
1948 while (FormatTok->is(tok::star))
1952 if (FormatTok->is(tok::l_paren))
1955 if (FormatTok->is(tok::l_brace))
1960 if (InRequiresExpression)
1961 FormatTok->setFinalizedType(TT_BracedListLBrace);
1962 if (!tryToParsePropertyAccessor() && !tryToParseBracedList()) {
1963 IsDecltypeAutoFunction =
Line->SeenDecltypeAuto;
1968 if (Style.isJava() &&
1969 Line->Tokens.front().Tok->is(Keywords.kw_synchronized)) {
1972 if (Style.BraceWrapping.AfterControlStatement ==
1973 FormatStyle::BWACS_Always) {
1976 }
else if (Style.BraceWrapping.AfterFunction) {
1980 FormatTok->setFinalizedType(TT_FunctionLBrace);
1982 IsDecltypeAutoFunction =
false;
1990 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1996 if (Style.BraceWrapping.AfterFunction)
2000 case tok::identifier: {
2001 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where) &&
2002 Line->MustBeDeclaration) {
2004 parseCSharpGenericTypeConstraint();
2007 if (FormatTok->is(TT_MacroBlockEnd)) {
2016 size_t TokenCount =
Line->Tokens.size();
2017 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_function) &&
2020 Line->Tokens.front().Tok->isNot(Keywords.kw_async)))) {
2021 tryToParseJSFunction();
2024 if ((Style.isJavaScript() || Style.isJava()) &&
2025 FormatTok->is(Keywords.kw_interface)) {
2026 if (Style.isJavaScript()) {
2031 unsigned StoredPosition = Tokens->getPosition();
2033 FormatTok = Tokens->setPosition(StoredPosition);
2044 if (Style.isVerilog()) {
2045 if (FormatTok->is(Keywords.kw_table)) {
2046 parseVerilogTable();
2049 if (Keywords.isVerilogBegin(*FormatTok) ||
2050 Keywords.isVerilogHierarchy(*FormatTok)) {
2057 if (!IsCpp && FormatTok->is(Keywords.kw_interface)) {
2058 if (parseStructLike())
2063 if (IsCpp && FormatTok->is(TT_StatementMacro)) {
2064 parseStatementMacro();
2069 StringRef
Text = FormatTok->TokenText;
2076 if (Style.isJavaScript())
2079 auto OneTokenSoFar = [&]() {
2080 auto I =
Line->Tokens.begin(), E =
Line->Tokens.end();
2081 while (I != E && I->Tok->is(tok::comment))
2083 if (Style.isVerilog())
2084 while (I != E && I->Tok->is(tok::hash))
2086 return I != E && (++I == E);
2088 if (OneTokenSoFar()) {
2091 bool FunctionLike = FormatTok->is(tok::l_paren);
2095 bool FollowedByNewline =
2096 CommentsBeforeNextToken.empty()
2097 ? FormatTok->NewlinesBefore > 0
2098 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
2100 if (FollowedByNewline &&
2101 (
Text.size() >= 5 ||
2102 (FunctionLike && FormatTok->isNot(tok::l_paren))) &&
2104 if (PreviousToken->isNot(TT_UntouchableMacroFunc))
2105 PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro);
2113 if ((Style.isJavaScript() || Style.isCSharp()) &&
2114 FormatTok->is(TT_FatArrow)) {
2115 tryToParseChildBlock();
2121 if (FormatTok->is(tok::l_brace)) {
2125 if (!Style.isJavaScript())
2126 FormatTok->setBlockKind(BK_BracedInit);
2129 if (Style.isTableGen() &&
2130 Line->Tokens.begin()->Tok->is(Keywords.kw_defset)) {
2131 FormatTok->setFinalizedType(TT_FunctionLBrace);
2132 parseBlock(
false, 1u,
2139 }
else if (Style.Language == FormatStyle::LK_Proto &&
2140 FormatTok->is(tok::less)) {
2142 parseBracedList(
true);
2149 if (Style.isCSharp() &&
2150 (Tokens->peekNextToken()->isAccessSpecifierKeyword() ||
2157 case tok::kw_switch:
2165 if (Style.Language == FormatStyle::LK_Proto) {
2170 if (Style.isVerilog()) {
2175 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
2182 case tok::kw_default:
2184 if (Style.isVerilog()) {
2185 if (FormatTok->is(tok::colon)) {
2189 if (FormatTok->is(Keywords.kw_clocking)) {
2195 parseVerilogCaseLabel();
2201 if (Style.isVerilog()) {
2202 parseVerilogCaseLabel();
2208 if (FormatTok->is(tok::l_brace))
2209 FormatTok->Previous->setFinalizedType(TT_TemplateCloser);
2218bool UnwrappedLineParser::tryToParsePropertyAccessor() {
2219 assert(FormatTok->is(tok::l_brace));
2220 if (!Style.isCSharp())
2223 if (!FormatTok->Previous || FormatTok->Previous->isNot(tok::identifier))
2231 unsigned int StoredPosition = Tokens->getPosition();
2237 bool HasSpecialAccessor =
false;
2238 bool IsTrivialPropertyAccessor =
true;
2241 if (
const bool IsAccessorKeyword =
2242 Tok->
isOneOf(Keywords.kw_get, Keywords.kw_init, Keywords.kw_set);
2243 IsAccessorKeyword ||
Tok->isAccessSpecifierKeyword() ||
2244 Tok->
isOneOf(tok::l_square, tok::semi, Keywords.kw_internal)) {
2245 if (IsAccessorKeyword)
2246 HasSpecialAccessor =
true;
2247 else if (
Tok->
is(tok::l_square))
2249 Tok = Tokens->getNextToken();
2253 IsTrivialPropertyAccessor =
false;
2258 Tokens->setPosition(StoredPosition);
2264 Tokens->setPosition(StoredPosition);
2265 if (!IsTrivialPropertyAccessor && Style.BraceWrapping.AfterFunction)
2269 switch (FormatTok->Tok.getKind()) {
2272 if (FormatTok->is(tok::equal)) {
2273 while (!
eof() && FormatTok->isNot(tok::semi))
2286 if (FormatTok->is(TT_FatArrow)) {
2290 }
while (!
eof() && FormatTok->isNot(tok::semi));
2299 if (FormatTok->isOneOf(Keywords.kw_get, Keywords.kw_init,
2301 !IsTrivialPropertyAccessor) {
2313bool UnwrappedLineParser::tryToParseLambda() {
2314 assert(FormatTok->is(tok::l_square));
2320 if (!tryToParseLambdaIntroducer())
2324 bool InTemplateParameterList =
false;
2326 while (FormatTok->isNot(tok::l_brace)) {
2327 if (FormatTok->isTypeName(LangOpts) || FormatTok->isAttribute()) {
2331 switch (FormatTok->Tok.getKind()) {
2335 parseParens(TT_PointerOrReference);
2341 assert(FormatTok->Previous);
2342 if (FormatTok->Previous->is(tok::r_square))
2343 InTemplateParameterList =
true;
2348 case tok::kw_struct:
2350 case tok::kw_template:
2351 case tok::kw_typename:
2355 case tok::kw_constexpr:
2356 case tok::kw_consteval:
2359 case tok::identifier:
2360 case tok::numeric_constant:
2361 case tok::coloncolon:
2362 case tok::kw_mutable:
2363 case tok::kw_noexcept:
2364 case tok::kw_static:
2389 case tok::equalequal:
2390 case tok::exclaimequal:
2391 case tok::greaterequal:
2392 case tok::lessequal:
2398 if (Arrow || InTemplateParameterList) {
2407 case tok::kw_requires:
2408 parseRequiresClause();
2411 if (!InTemplateParameterList)
2420 FormatTok->setFinalizedType(TT_LambdaLBrace);
2421 LSquare.setFinalizedType(TT_LambdaLSquare);
2424 Arrow->setFinalizedType(TT_LambdaArrow);
2426 NestedLambdas.push_back(
Line->SeenDecltypeAuto);
2428 assert(!NestedLambdas.empty());
2429 NestedLambdas.pop_back();
2434bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
2439 const auto *PrevPrev =
Previous->getPreviousNonComment();
2440 if (
Previous->is(tok::star) && PrevPrev && PrevPrev->isTypeName(LangOpts))
2448 if (!PrevPrev || PrevPrev->isNoneOf(tok::greater, tok::r_paren))
2452 Previous->isNoneOf(tok::kw_return, tok::kw_co_await, tok::kw_co_yield,
2453 tok::kw_co_return)) {
2457 if (LeftSquare->isCppStructuredBinding(IsCpp))
2459 if (FormatTok->is(tok::l_square) ||
tok::isLiteral(FormatTok->Tok.getKind()))
2461 if (FormatTok->is(tok::r_square)) {
2463 if (
Next->is(tok::greater))
2470void UnwrappedLineParser::tryToParseJSFunction() {
2471 assert(FormatTok->is(Keywords.kw_function));
2472 if (FormatTok->is(Keywords.kw_async))
2478 if (FormatTok->is(tok::star)) {
2479 FormatTok->setFinalizedType(TT_OverloadedOperator);
2484 if (FormatTok->is(tok::identifier))
2487 if (FormatTok->isNot(tok::l_paren))
2493 if (FormatTok->is(tok::colon)) {
2499 if (FormatTok->is(tok::l_brace))
2500 tryToParseBracedList();
2502 while (FormatTok->isNoneOf(tok::l_brace, tok::semi) && !
eof())
2506 if (FormatTok->is(tok::semi))
2512bool UnwrappedLineParser::tryToParseBracedList() {
2513 if (FormatTok->is(BK_Unknown))
2514 calculateBraceTypes();
2515 assert(FormatTok->isNot(BK_Unknown));
2516 if (FormatTok->is(BK_Block))
2523bool UnwrappedLineParser::tryToParseChildBlock() {
2524 assert(Style.isJavaScript() || Style.isCSharp());
2525 assert(FormatTok->is(TT_FatArrow));
2530 if (FormatTok->isNot(tok::l_brace))
2536bool UnwrappedLineParser::parseBracedList(
bool IsAngleBracket,
bool IsEnum) {
2537 assert(!IsAngleBracket || !IsEnum);
2538 bool HasError =
false;
2543 if (Style.isCSharp() && FormatTok->is(TT_FatArrow) &&
2544 tryToParseChildBlock()) {
2547 if (Style.isJavaScript()) {
2548 if (FormatTok->is(Keywords.kw_function)) {
2549 tryToParseJSFunction();
2552 if (FormatTok->is(tok::l_brace)) {
2554 if (tryToParseBracedList())
2559 if (FormatTok->is(IsAngleBracket ? tok::greater : tok::r_brace)) {
2561 FormatTok->setBlockKind(BK_Block);
2562 if (!Style.AllowShortEnumsOnASingleLine)
2568 switch (FormatTok->Tok.getKind()) {
2570 if (Style.isCSharp())
2579 if (Style.isJavaScript()) {
2580 if (FormatTok->is(tok::l_brace))
2588 FormatTok->setBlockKind(BK_BracedInit);
2589 if (!IsAngleBracket) {
2590 auto *Prev = FormatTok->Previous;
2591 if (Prev && Prev->is(tok::greater))
2592 Prev->setFinalizedType(TT_TemplateCloser);
2600 parseBracedList(
true);
2607 if (Style.isJavaScript()) {
2618 if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
2621 case tok::kw_requires:
2622 parseRequiresExpression();
2638bool UnwrappedLineParser::parseParens(TokenType StarAndAmpTokenType,
2640 assert(FormatTok->is(tok::l_paren) &&
"'(' expected.");
2641 auto *LParen = FormatTok;
2642 auto *Prev = FormatTok->Previous;
2643 bool SeenComma =
false;
2644 bool SeenEqual =
false;
2645 bool MightBeFoldExpr =
false;
2647 const bool MightBeStmtExpr = FormatTok->is(tok::l_brace);
2648 if (!InMacroCall && Prev && Prev->is(TT_FunctionLikeMacro))
2651 switch (FormatTok->Tok.getKind()) {
2653 if (parseParens(StarAndAmpTokenType, InMacroCall))
2655 if (Style.isJava() && FormatTok->is(tok::l_brace))
2658 case tok::r_paren: {
2659 auto *RParen = FormatTok;
2662 auto OptionalParens = [&] {
2663 if (Style.RemoveParentheses == FormatStyle::RPS_Leave ||
2664 MightBeStmtExpr || MightBeFoldExpr || SeenComma || InMacroCall ||
2665 Line->InMacroBody || RParen->getPreviousNonComment() == LParen) {
2668 const bool DoubleParens =
2669 Prev->is(tok::l_paren) && FormatTok->is(tok::r_paren);
2671 const auto *PrevPrev = Prev->getPreviousNonComment();
2672 const bool Excluded =
2674 (PrevPrev->isOneOf(tok::kw___attribute, tok::kw_decltype) ||
2676 (PrevPrev->isOneOf(tok::kw_if, tok::kw_while) ||
2677 PrevPrev->endsSequence(tok::kw_constexpr, tok::kw_if))));
2681 const bool CommaSeparated =
2682 Prev->isOneOf(tok::l_paren, tok::comma) &&
2683 FormatTok->isOneOf(tok::comma, tok::r_paren);
2684 if (CommaSeparated &&
2686 !Prev->endsSequence(tok::comma, tok::ellipsis) &&
2688 !(FormatTok->is(tok::comma) &&
2689 Tokens->peekNextToken()->is(tok::ellipsis))) {
2692 const bool ReturnParens =
2693 Style.RemoveParentheses == FormatStyle::RPS_ReturnStatement &&
2694 ((NestedLambdas.empty() && !IsDecltypeAutoFunction) ||
2695 (!NestedLambdas.empty() && !NestedLambdas.back())) &&
2696 Prev->isOneOf(tok::kw_return, tok::kw_co_return) &&
2697 FormatTok->is(tok::semi);
2703 if (OptionalParens()) {
2704 LParen->Optional =
true;
2705 RParen->Optional =
true;
2706 }
else if (Prev->is(TT_TypenameMacro)) {
2707 LParen->setFinalizedType(TT_TypeDeclarationParen);
2708 RParen->setFinalizedType(TT_TypeDeclarationParen);
2709 }
else if (Prev->is(tok::greater) && RParen->Previous == LParen) {
2710 Prev->setFinalizedType(TT_TemplateCloser);
2711 }
else if (FormatTok->is(tok::l_brace) && Prev->is(tok::amp) &&
2713 FormatTok->setBlockKind(BK_BracedInit);
2725 if (!tryToParseBracedList())
2730 if (FormatTok->is(tok::l_brace)) {
2740 MightBeFoldExpr =
true;
2745 if (Style.isCSharp() && FormatTok->is(TT_FatArrow))
2746 tryToParseChildBlock();
2751 if (Style.isJavaScript())
2756 case tok::identifier:
2757 if (Style.isJavaScript() && (FormatTok->is(Keywords.kw_function)))
2758 tryToParseJSFunction();
2762 case tok::kw_switch:
2768 case tok::kw_requires:
2769 parseRequiresExpression();
2774 if (StarAndAmpTokenType != TT_Unknown)
2775 FormatTok->setFinalizedType(StarAndAmpTokenType);
2787 assert(FormatTok->is(tok::l_square) &&
"'[' expected.");
2788 if (tryToParseLambda())
2792 switch (FormatTok->Tok.getKind()) {
2805 case tok::l_brace: {
2806 if (!tryToParseBracedList())
2813 if (FormatTok->is(tok::l_brace)) {
2825void UnwrappedLineParser::keepAncestorBraces() {
2826 if (!Style.RemoveBracesLLVM)
2829 const int MaxNestingLevels = 2;
2830 const int Size = NestedTooDeep.size();
2831 if (Size >= MaxNestingLevels)
2832 NestedTooDeep[
Size - MaxNestingLevels] =
true;
2833 NestedTooDeep.push_back(
false);
2837 for (
const auto &
Token : llvm::reverse(
Line.Tokens))
2844void UnwrappedLineParser::parseUnbracedBody(
bool CheckEOF) {
2847 if (Style.InsertBraces && !
Line->InPPDirective && !
Line->Tokens.empty() &&
2848 PreprocessorDirectives.empty() && FormatTok->isNot(tok::semi)) {
2849 Tok = Style.BraceWrapping.AfterControlStatement == FormatStyle::BWACS_Never
2850 ? getLastNonComment(*
Line)
2853 if (
Tok->BraceCount < 0) {
2854 assert(
Tok->BraceCount == -1);
2857 Tok->BraceCount = -1;
2863 ++
Line->UnbracedBodyLevel;
2864 parseStructuralElement();
2865 --
Line->UnbracedBodyLevel;
2868 assert(!
Line->InPPDirective);
2870 for (
const auto &L : llvm::reverse(*CurrentLines)) {
2872 Tok = L.Tokens.back().Tok;
2880 if (CheckEOF &&
eof())
2890 assert(LeftBrace->
is(tok::l_brace));
2898 assert(RightBrace->
is(tok::r_brace));
2906void UnwrappedLineParser::handleAttributes() {
2908 if (FormatTok->isAttribute())
2910 else if (FormatTok->is(tok::l_square))
2911 handleCppAttributes();
2914bool UnwrappedLineParser::handleCppAttributes() {
2916 assert(FormatTok->is(tok::l_square));
2917 if (!tryToParseSimpleAttribute())
2924bool UnwrappedLineParser::isBlockBegin(
const FormatToken &
Tok)
const {
2927 return Style.isVerilog() ? Keywords.isVerilogBegin(
Tok)
2928 :
Tok.
is(tok::l_brace);
2931FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
2933 bool IsVerilogAssert) {
2934 assert((FormatTok->is(tok::kw_if) ||
2935 (Style.isVerilog() &&
2936 FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
2937 Keywords.kw_assume, Keywords.kw_cover))) &&
2941 if (IsVerilogAssert) {
2943 if (FormatTok->is(Keywords.kw_verilogHash)) {
2945 if (FormatTok->is(tok::numeric_constant))
2947 }
else if (FormatTok->isOneOf(Keywords.kw_final, Keywords.kw_property,
2948 Keywords.kw_sequence)) {
2954 if (Style.isTableGen()) {
2955 while (!
eof() && FormatTok->isNot(Keywords.kw_then)) {
2962 if (FormatTok->is(tok::exclaim))
2965 bool KeepIfBraces =
true;
2966 if (FormatTok->is(tok::kw_consteval)) {
2969 KeepIfBraces = !Style.RemoveBracesLLVM || KeepBraces;
2970 if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
2972 if (FormatTok->is(tok::l_paren)) {
2973 FormatTok->setFinalizedType(TT_ConditionLParen);
2979 if (IsVerilogAssert && FormatTok->is(tok::semi)) {
2985 bool NeedsUnwrappedLine =
false;
2986 keepAncestorBraces();
2989 IfStmtKind IfBlockKind = IfStmtKind::NotIf;
2991 if (isBlockBegin(*FormatTok)) {
2992 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
2993 IfLeftBrace = FormatTok;
2994 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
2995 parseBlock(
false, 1u,
2996 true, KeepIfBraces, &IfBlockKind);
2997 setPreviousRBraceType(TT_ControlStatementRBrace);
2998 if (Style.BraceWrapping.BeforeElse)
3001 NeedsUnwrappedLine =
true;
3002 }
else if (IsVerilogAssert && FormatTok->is(tok::kw_else)) {
3005 parseUnbracedBody();
3008 if (Style.RemoveBracesLLVM) {
3009 assert(!NestedTooDeep.empty());
3010 KeepIfBraces = KeepIfBraces ||
3011 (IfLeftBrace && !IfLeftBrace->MatchingParen) ||
3012 NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly ||
3013 IfBlockKind == IfStmtKind::IfElseIf;
3016 bool KeepElseBraces = KeepIfBraces;
3018 IfStmtKind
Kind = IfStmtKind::IfOnly;
3020 if (FormatTok->is(tok::kw_else)) {
3021 if (Style.RemoveBracesLLVM) {
3022 NestedTooDeep.back() =
false;
3023 Kind = IfStmtKind::IfElse;
3027 if (isBlockBegin(*FormatTok)) {
3028 const bool FollowedByIf = Tokens->peekNextToken()->is(tok::kw_if);
3029 FormatTok->setFinalizedType(TT_ElseLBrace);
3030 ElseLeftBrace = FormatTok;
3031 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3032 IfStmtKind ElseBlockKind = IfStmtKind::NotIf;
3034 parseBlock(
false, 1u,
3035 true, KeepElseBraces, &ElseBlockKind);
3036 setPreviousRBraceType(TT_ElseRBrace);
3037 if (FormatTok->is(tok::kw_else)) {
3038 KeepElseBraces = KeepElseBraces ||
3039 ElseBlockKind == IfStmtKind::IfOnly ||
3040 ElseBlockKind == IfStmtKind::IfElseIf;
3041 }
else if (FollowedByIf && IfLBrace && !IfLBrace->Optional) {
3042 KeepElseBraces =
true;
3043 assert(ElseLeftBrace->MatchingParen);
3047 }
else if (!IsVerilogAssert && FormatTok->is(tok::kw_if)) {
3050 const bool IsPrecededByComment =
Previous->is(tok::comment);
3051 if (IsPrecededByComment) {
3055 bool TooDeep =
true;
3056 if (Style.RemoveBracesLLVM) {
3057 Kind = IfStmtKind::IfElseIf;
3058 TooDeep = NestedTooDeep.pop_back_val();
3060 ElseLeftBrace = parseIfThenElse(
nullptr, KeepIfBraces);
3061 if (Style.RemoveBracesLLVM)
3062 NestedTooDeep.push_back(TooDeep);
3063 if (IsPrecededByComment)
3066 parseUnbracedBody(
true);
3069 KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse;
3070 if (NeedsUnwrappedLine)
3074 if (!Style.RemoveBracesLLVM)
3077 assert(!NestedTooDeep.empty());
3078 KeepElseBraces = KeepElseBraces ||
3079 (ElseLeftBrace && !ElseLeftBrace->MatchingParen) ||
3080 NestedTooDeep.back();
3082 NestedTooDeep.pop_back();
3084 if (!KeepIfBraces && !KeepElseBraces) {
3087 }
else if (IfLeftBrace) {
3088 FormatToken *IfRightBrace = IfLeftBrace->MatchingParen;
3090 assert(IfRightBrace->MatchingParen == IfLeftBrace);
3091 assert(!IfLeftBrace->Optional);
3092 assert(!IfRightBrace->Optional);
3093 IfLeftBrace->MatchingParen =
nullptr;
3094 IfRightBrace->MatchingParen =
nullptr;
3104void UnwrappedLineParser::parseTryCatch() {
3105 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) &&
"'try' expected");
3107 bool NeedsUnwrappedLine =
false;
3108 bool HasCtorInitializer =
false;
3109 if (FormatTok->is(tok::colon)) {
3110 auto *Colon = FormatTok;
3113 if (FormatTok->is(tok::identifier)) {
3114 HasCtorInitializer =
true;
3115 Colon->setFinalizedType(TT_CtorInitializerColon);
3120 while (FormatTok->is(tok::comma))
3123 while (FormatTok->is(tok::identifier)) {
3125 if (FormatTok->is(tok::l_paren)) {
3127 }
else if (FormatTok->is(tok::l_brace)) {
3134 while (FormatTok->is(tok::comma))
3139 if (Style.isJava() && FormatTok->is(tok::l_paren))
3142 keepAncestorBraces();
3144 if (FormatTok->is(tok::l_brace)) {
3145 if (HasCtorInitializer)
3146 FormatTok->setFinalizedType(TT_FunctionLBrace);
3147 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3149 if (Style.BraceWrapping.BeforeCatch)
3152 NeedsUnwrappedLine =
true;
3153 }
else if (FormatTok->isNot(tok::kw_catch)) {
3159 parseStructuralElement();
3162 for (
bool SeenCatch =
false;;) {
3163 if (FormatTok->is(tok::at))
3165 if (FormatTok->isNoneOf(tok::kw_catch, Keywords.kw___except,
3166 tok::kw___finally, tok::objc_catch,
3167 tok::objc_finally) &&
3168 !((Style.isJava() || Style.isJavaScript()) &&
3169 FormatTok->is(Keywords.kw_finally))) {
3172 if (FormatTok->is(tok::kw_catch))
3175 while (FormatTok->isNot(tok::l_brace)) {
3176 if (FormatTok->is(tok::l_paren)) {
3180 if (FormatTok->isOneOf(tok::semi, tok::r_brace) ||
eof()) {
3181 if (Style.RemoveBracesLLVM)
3182 NestedTooDeep.pop_back();
3188 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3191 NeedsUnwrappedLine =
false;
3192 Line->MustBeDeclaration =
false;
3193 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3195 if (Style.BraceWrapping.BeforeCatch)
3198 NeedsUnwrappedLine =
true;
3201 if (Style.RemoveBracesLLVM)
3202 NestedTooDeep.pop_back();
3204 if (NeedsUnwrappedLine)
3208void UnwrappedLineParser::parseNamespaceOrExportBlock(
unsigned AddLevels) {
3209 bool ManageWhitesmithsBraces =
3210 AddLevels == 0u && Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
3214 if (ManageWhitesmithsBraces)
3219 parseBlock(
true, AddLevels,
true,
3220 true,
nullptr, ManageWhitesmithsBraces);
3222 addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep);
3224 if (ManageWhitesmithsBraces)
3228void UnwrappedLineParser::parseNamespace() {
3229 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
3230 "'namespace' expected");
3234 if (InitialToken.is(TT_NamespaceMacro)) {
3237 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
3238 tok::l_square, tok::period, tok::l_paren) ||
3239 (Style.isCSharp() && FormatTok->is(tok::kw_union))) {
3240 if (FormatTok->is(tok::l_square))
3242 else if (FormatTok->is(tok::l_paren))
3248 if (FormatTok->is(tok::l_brace)) {
3249 FormatTok->setFinalizedType(TT_NamespaceLBrace);
3252 Tokens->peekNextToken()->is(tok::r_brace))) {
3256 unsigned AddLevels =
3257 Style.NamespaceIndentation == FormatStyle::NI_All ||
3258 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
3259 DeclarationScopeStack.size() > 1)
3262 parseNamespaceOrExportBlock(AddLevels);
3267void UnwrappedLineParser::parseCppExportBlock() {
3268 parseNamespaceOrExportBlock(Style.IndentExportBlock ? 1 : 0);
3271void UnwrappedLineParser::parseNew() {
3272 assert(FormatTok->is(tok::kw_new) &&
"'new' expected");
3275 if (Style.isCSharp()) {
3278 if (FormatTok->is(tok::l_paren))
3282 if (FormatTok->is(tok::l_brace))
3285 if (FormatTok->isOneOf(tok::semi, tok::comma))
3292 if (!Style.isJava())
3298 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
3302 if (FormatTok->is(tok::l_paren)) {
3306 if (FormatTok->is(tok::l_brace))
3314void UnwrappedLineParser::parseLoopBody(
bool KeepBraces,
bool WrapRightBrace) {
3315 keepAncestorBraces();
3317 if (isBlockBegin(*FormatTok)) {
3318 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3320 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3321 parseBlock(
false, 1u,
3323 setPreviousRBraceType(TT_ControlStatementRBrace);
3325 assert(!NestedTooDeep.empty());
3326 if (!NestedTooDeep.back())
3332 parseUnbracedBody();
3336 NestedTooDeep.pop_back();
3339void UnwrappedLineParser::parseForOrWhileLoop(
bool HasParens) {
3340 assert((FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) ||
3341 (Style.isVerilog() &&
3342 FormatTok->isOneOf(Keywords.kw_always, Keywords.kw_always_comb,
3343 Keywords.kw_always_ff, Keywords.kw_always_latch,
3344 Keywords.kw_final, Keywords.kw_initial,
3345 Keywords.kw_foreach, Keywords.kw_forever,
3346 Keywords.kw_repeat))) &&
3347 "'for', 'while' or foreach macro expected");
3348 const bool KeepBraces = !Style.RemoveBracesLLVM ||
3349 FormatTok->isNoneOf(tok::kw_for, tok::kw_while);
3353 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
3355 if (IsCpp && FormatTok->is(tok::kw_co_await))
3357 if (HasParens && FormatTok->is(tok::l_paren)) {
3361 if (Style.isVerilog())
3362 FormatTok->setFinalizedType(TT_ConditionLParen);
3366 if (Style.isVerilog()) {
3368 parseVerilogSensitivityList();
3369 }
else if (Style.AllowShortLoopsOnASingleLine && FormatTok->is(tok::semi) &&
3370 Tokens->getPreviousToken()->is(tok::r_paren)) {
3377 parseLoopBody(KeepBraces,
true);
3380void UnwrappedLineParser::parseDoWhile() {
3381 assert(FormatTok->is(tok::kw_do) &&
"'do' expected");
3384 parseLoopBody(
true, Style.BraceWrapping.BeforeWhile);
3387 if (FormatTok->isNot(tok::kw_while)) {
3392 FormatTok->setFinalizedType(TT_DoWhile);
3396 if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)
3400 parseStructuralElement();
3403void UnwrappedLineParser::parseLabel(
3404 FormatStyle::IndentGotoLabelStyle IndentGotoLabels) {
3405 const bool IsGotoLabel = FormatTok->is(TT_GotoLabelColon);
3407 unsigned OldLineLevel =
Line->Level;
3409 switch (IndentGotoLabels) {
3410 case FormatStyle::IGLS_NoIndent:
3413 case FormatStyle::IGLS_OuterIndent:
3414 if (
Line->Level > 1 || (!
Line->InPPDirective &&
Line->Level > 0))
3417 case FormatStyle::IGLS_HalfIndent:
3418 case FormatStyle::IGLS_InnerIndent:
3422 if (!IsGotoLabel && !Style.IndentCaseBlocks &&
3423 CommentsBeforeNextToken.empty() && FormatTok->is(tok::l_brace)) {
3424 CompoundStatementIndenter Indenter(
this,
Line->Level,
3425 Style.BraceWrapping.AfterCaseLabel,
3426 Style.BraceWrapping.IndentBraces);
3428 if (FormatTok->is(tok::kw_break)) {
3429 if (Style.BraceWrapping.AfterControlStatement ==
3430 FormatStyle::BWACS_Always) {
3432 if (!Style.IndentCaseBlocks &&
3433 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) {
3437 parseStructuralElement();
3441 if (FormatTok->is(tok::semi))
3445 Line->Level = OldLineLevel;
3446 if (FormatTok->isNot(tok::l_brace)) {
3447 parseStructuralElement();
3452void UnwrappedLineParser::parseCaseLabel() {
3453 assert(FormatTok->is(tok::kw_case) &&
"'case' expected");
3454 auto *Case = FormatTok;
3459 if (FormatTok->is(tok::colon)) {
3460 FormatTok->setFinalizedType(TT_CaseLabelColon);
3463 if (Style.isJava() && FormatTok->is(tok::arrow)) {
3464 FormatTok->setFinalizedType(TT_CaseLabelArrow);
3465 Case->setFinalizedType(TT_SwitchExpressionLabel);
3472void UnwrappedLineParser::parseSwitch(
bool IsExpr) {
3473 assert(FormatTok->is(tok::kw_switch) &&
"'switch' expected");
3475 if (FormatTok->is(tok::l_paren))
3478 keepAncestorBraces();
3480 if (FormatTok->is(tok::l_brace)) {
3481 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3482 FormatTok->setFinalizedType(IsExpr ? TT_SwitchExpressionLBrace
3483 : TT_ControlStatementLBrace);
3488 setPreviousRBraceType(TT_ControlStatementRBrace);
3494 parseStructuralElement();
3498 if (Style.RemoveBracesLLVM)
3499 NestedTooDeep.pop_back();
3502void UnwrappedLineParser::parseAccessSpecifier() {
3505 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
3508 if (FormatTok->is(tok::colon))
3516bool UnwrappedLineParser::parseRequires(
bool SeenEqual) {
3517 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3521 switch (Tokens->peekNextToken(
true)->Tok.getKind()) {
3524 parseRequiresExpression();
3531 parseRequiresClause();
3542 auto *PreviousNonComment = FormatTok->getPreviousNonComment();
3544 if (!PreviousNonComment ||
3545 PreviousNonComment->is(TT_RequiresExpressionLBrace)) {
3548 parseRequiresClause();
3552 switch (PreviousNonComment->Tok.getKind()) {
3555 case tok::kw_noexcept:
3560 parseRequiresClause();
3569 auto PrevPrev = PreviousNonComment->getPreviousNonComment();
3570 if ((PrevPrev && PrevPrev->is(tok::kw_const)) || !SeenEqual) {
3571 parseRequiresClause();
3577 if (PreviousNonComment->isTypeOrIdentifier(LangOpts)) {
3579 parseRequiresClause();
3583 parseRequiresExpression();
3593 unsigned StoredPosition = Tokens->getPosition();
3596 auto PeekNext = [&Lookahead, &NextToken,
this] {
3598 NextToken = Tokens->getNextToken();
3601 bool FoundType =
false;
3602 bool LastWasColonColon =
false;
3605 for (; Lookahead < 50; PeekNext()) {
3606 switch (NextToken->Tok.getKind()) {
3607 case tok::kw_volatile:
3610 if (OpenAngles == 0) {
3611 FormatTok = Tokens->setPosition(StoredPosition);
3612 parseRequiresExpression();
3620 case tok::coloncolon:
3621 LastWasColonColon =
true;
3623 case tok::kw_decltype:
3624 case tok::identifier:
3625 if (FoundType && !LastWasColonColon && OpenAngles == 0) {
3626 FormatTok = Tokens->setPosition(StoredPosition);
3627 parseRequiresExpression();
3631 LastWasColonColon =
false;
3640 if (NextToken->isTypeName(LangOpts)) {
3641 FormatTok = Tokens->setPosition(StoredPosition);
3642 parseRequiresExpression();
3649 FormatTok = Tokens->setPosition(StoredPosition);
3650 parseRequiresClause();
3659void UnwrappedLineParser::parseRequiresClause() {
3660 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3665 bool InRequiresExpression =
3666 !FormatTok->Previous ||
3667 FormatTok->Previous->is(TT_RequiresExpressionLBrace);
3669 FormatTok->setFinalizedType(InRequiresExpression
3670 ? TT_RequiresClauseInARequiresExpression
3671 : TT_RequiresClause);
3676 parseConstraintExpression();
3678 if (!InRequiresExpression && FormatTok->Previous)
3679 FormatTok->Previous->ClosesRequiresClause =
true;
3687void UnwrappedLineParser::parseRequiresExpression() {
3688 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3690 FormatTok->setFinalizedType(TT_RequiresExpression);
3693 if (FormatTok->is(tok::l_paren)) {
3694 FormatTok->setFinalizedType(TT_RequiresExpressionLParen);
3698 if (FormatTok->is(tok::l_brace)) {
3699 FormatTok->setFinalizedType(TT_RequiresExpressionLBrace);
3708void UnwrappedLineParser::parseConstraintExpression() {
3715 bool LambdaNextTimeAllowed =
true;
3725 bool TopLevelParensAllowed =
true;
3728 bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed,
false);
3730 switch (FormatTok->Tok.getKind()) {
3731 case tok::kw_requires:
3732 parseRequiresExpression();
3736 if (!TopLevelParensAllowed)
3738 parseParens(TT_BinaryOperator);
3739 TopLevelParensAllowed =
false;
3743 if (!LambdaThisTimeAllowed || !tryToParseLambda())
3750 case tok::kw_struct:
3760 FormatTok->setFinalizedType(TT_BinaryOperator);
3762 LambdaNextTimeAllowed =
true;
3763 TopLevelParensAllowed =
true;
3768 LambdaNextTimeAllowed = LambdaThisTimeAllowed;
3772 case tok::kw_sizeof:
3774 case tok::greaterequal:
3775 case tok::greatergreater:
3777 case tok::lessequal:
3779 case tok::equalequal:
3781 case tok::exclaimequal:
3786 LambdaNextTimeAllowed =
true;
3787 TopLevelParensAllowed =
true;
3792 case tok::numeric_constant:
3793 case tok::coloncolon:
3796 TopLevelParensAllowed =
false;
3801 case tok::kw_static_cast:
3802 case tok::kw_const_cast:
3803 case tok::kw_reinterpret_cast:
3804 case tok::kw_dynamic_cast:
3806 if (FormatTok->isNot(tok::less))
3810 parseBracedList(
true);
3814 if (!FormatTok->Tok.getIdentifierInfo()) {
3824 assert(FormatTok->Previous);
3825 switch (FormatTok->Previous->Tok.getKind()) {
3826 case tok::coloncolon:
3830 case tok::kw_requires:
3839 if (FormatTok->is(tok::less)) {
3841 parseBracedList(
true);
3843 TopLevelParensAllowed =
false;
3849bool UnwrappedLineParser::parseEnum() {
3853 if (FormatTok->is(tok::kw_enum))
3859 if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question))
3863 if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal))
3868 if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
3870 while (FormatTok->is(tok::l_square))
3871 if (!handleCppAttributes())
3875 while (FormatTok->Tok.getIdentifierInfo() ||
3876 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
3877 tok::greater, tok::comma, tok::question,
3879 if (FormatTok->is(tok::colon))
3880 FormatTok->setFinalizedType(TT_EnumUnderlyingTypeColon);
3881 if (Style.isVerilog()) {
3882 FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
3885 while (FormatTok->is(tok::l_square))
3891 if (FormatTok->is(tok::l_paren))
3893 if (FormatTok->is(tok::identifier)) {
3897 if (IsCpp && FormatTok->is(tok::identifier))
3903 if (FormatTok->isNot(tok::l_brace))
3905 FormatTok->setFinalizedType(TT_EnumLBrace);
3906 FormatTok->setBlockKind(BK_Block);
3908 if (Style.isJava()) {
3910 parseJavaEnumBody();
3913 if (Style.Language == FormatStyle::LK_Proto) {
3918 const bool ManageWhitesmithsBraces =
3919 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
3921 if (!Style.AllowShortEnumsOnASingleLine &&
3923 Tokens->peekNextToken()->is(tok::r_brace))) {
3928 if (ManageWhitesmithsBraces)
3933 if (!Style.AllowShortEnumsOnASingleLine) {
3935 if (!ManageWhitesmithsBraces)
3938 const auto OpeningLineIndex = CurrentLines->empty()
3939 ? UnwrappedLine::kInvalidIndex
3940 : CurrentLines->size() - 1;
3941 bool HasError = !parseBracedList(
false,
true);
3942 if (!Style.AllowShortEnumsOnASingleLine && !ManageWhitesmithsBraces)
3945 if (FormatTok->is(tok::semi))
3949 setPreviousRBraceType(TT_EnumRBrace);
3950 if (ManageWhitesmithsBraces)
3951 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
3959bool UnwrappedLineParser::parseStructLike() {
3964 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp()) {
3965 if (FormatTok->is(tok::semi))
3976class ScopedTokenPosition {
3977 unsigned StoredPosition;
3978 FormatTokenSource *Tokens;
3981 ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) {
3982 assert(Tokens &&
"Tokens expected to not be null");
3983 StoredPosition = Tokens->getPosition();
3986 ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); }
3992bool UnwrappedLineParser::tryToParseSimpleAttribute() {
3993 ScopedTokenPosition AutoPosition(Tokens);
4001 if (
Tok->
is(tok::r_square))
4003 Tok = Tokens->getNextToken();
4005 if (
Tok->
is(tok::eof))
4007 Tok = Tokens->getNextToken();
4010 Tok = Tokens->getNextToken();
4011 if (
Tok->
is(tok::semi))
4016void UnwrappedLineParser::parseJavaEnumBody() {
4017 assert(FormatTok->is(tok::l_brace));
4023 unsigned StoredPosition = Tokens->getPosition();
4024 bool IsSimple =
true;
4027 if (
Tok->
is(tok::r_brace))
4035 Tok = Tokens->getNextToken();
4037 FormatTok = Tokens->setPosition(StoredPosition);
4054 if (FormatTok->is(tok::l_brace)) {
4056 parseBlock(
true, 1u,
4058 }
else if (FormatTok->is(tok::l_paren)) {
4060 }
else if (FormatTok->is(tok::comma)) {
4063 }
else if (FormatTok->is(tok::semi)) {
4067 }
else if (FormatTok->is(tok::r_brace)) {
4076 parseLevel(OpeningBrace);
4082void UnwrappedLineParser::parseRecord(
bool ParseAsExpr,
bool IsJavaRecord) {
4083 assert(!IsJavaRecord || FormatTok->is(Keywords.kw_record));
4088 IsJavaRecord && FormatTok->is(tok::identifier) ? FormatTok :
nullptr;
4089 bool IsDerived =
false;
4091 return Tok->
is(tok::identifier) &&
Tok->TokenText !=
Tok->TokenText.upper();
4095 bool JSPastExtendsOrImplements =
false;
4099 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
4100 tok::kw_alignas, tok::l_square) ||
4101 FormatTok->isAttribute() ||
4102 ((Style.isJava() || Style.isJavaScript()) &&
4103 FormatTok->isOneOf(tok::period, tok::comma))) {
4104 if (Style.isJavaScript() &&
4105 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
4106 JSPastExtendsOrImplements =
true;
4111 if (FormatTok->is(tok::l_brace)) {
4112 tryToParseBracedList();
4116 if (FormatTok->is(tok::l_square) && handleCppAttributes())
4120 switch (FormatTok->Tok.getKind()) {
4123 if (IsJavaRecord || !IsNonMacroIdentifier(
Previous) ||
4125 Previous->Previous == &InitialToken) {
4129 case tok::coloncolon:
4133 if (JSPastExtendsOrImplements || ClassName ||
4144 auto IsListInitialization = [&] {
4145 if (!ClassName || IsDerived || JSPastExtendsOrImplements)
4147 assert(FormatTok->is(tok::l_brace));
4148 const auto *Prev = FormatTok->getPreviousNonComment();
4150 return Prev != ClassName && Prev->is(tok::identifier) &&
4151 Prev->isNot(Keywords.kw_final) && tryToParseBracedList();
4154 if (FormatTok->isOneOf(tok::colon, tok::less)) {
4155 int AngleNestingLevel = 0;
4157 if (FormatTok->is(tok::less))
4158 ++AngleNestingLevel;
4159 else if (FormatTok->is(tok::greater))
4160 --AngleNestingLevel;
4162 if (AngleNestingLevel == 0) {
4163 if (FormatTok->is(tok::colon)) {
4165 }
else if (!IsDerived && FormatTok->is(tok::identifier) &&
4166 FormatTok->Previous->is(tok::coloncolon)) {
4167 ClassName = FormatTok;
4168 }
else if (FormatTok->is(tok::l_paren) &&
4169 IsNonMacroIdentifier(FormatTok->Previous)) {
4173 if (FormatTok->is(tok::l_brace)) {
4174 if (AngleNestingLevel == 0 && IsListInitialization())
4176 calculateBraceTypes(
true);
4177 if (!tryToParseBracedList())
4180 if (FormatTok->is(tok::l_square)) {
4183 !
Previous->isTypeOrIdentifier(LangOpts))) {
4186 if (!tryToParseLambda())
4193 if (FormatTok->is(tok::semi))
4195 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
4198 parseCSharpGenericTypeConstraint();
4205 auto GetBraceTypes =
4206 [](
const FormatToken &RecordTok) -> std::pair<TokenType, TokenType> {
4207 switch (RecordTok.Tok.getKind()) {
4209 return {TT_ClassLBrace, TT_ClassRBrace};
4210 case tok::kw_struct:
4211 return {TT_StructLBrace, TT_StructRBrace};
4213 return {TT_UnionLBrace, TT_UnionRBrace};
4216 return {TT_RecordLBrace, TT_RecordRBrace};
4219 if (FormatTok->is(tok::l_brace)) {
4220 if (IsListInitialization())
4223 ClassName->setFinalizedType(TT_ClassHeadName);
4224 auto [OpenBraceType, ClosingBraceType] = GetBraceTypes(InitialToken);
4225 FormatTok->setFinalizedType(OpenBraceType);
4230 Tokens->peekNextToken()->is(tok::r_brace),
4235 unsigned AddLevels = Style.IndentAccessModifiers ? 2u : 1u;
4236 parseBlock(
true, AddLevels,
false);
4238 setPreviousRBraceType(ClosingBraceType);
4245void UnwrappedLineParser::parseObjCMethod() {
4246 assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) &&
4247 "'(' or identifier expected.");
4249 if (FormatTok->is(tok::semi)) {
4253 }
else if (FormatTok->is(tok::l_brace)) {
4254 if (Style.BraceWrapping.AfterFunction)
4265void UnwrappedLineParser::parseObjCProtocolList() {
4266 assert(FormatTok->is(tok::less) &&
"'<' expected.");
4270 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4272 }
while (!
eof() && FormatTok->isNot(tok::greater));
4276void UnwrappedLineParser::parseObjCUntilAtEnd() {
4278 if (FormatTok->is(tok::objc_end)) {
4283 if (FormatTok->is(tok::l_brace)) {
4287 }
else if (FormatTok->is(tok::r_brace)) {
4291 }
else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
4293 if (FormatTok->isOneOf(tok::l_paren, tok::identifier))
4296 parseStructuralElement();
4301void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
4302 assert(FormatTok->isOneOf(tok::objc_interface, tok::objc_implementation));
4308 if (FormatTok->is(tok::less))
4309 parseObjCLightweightGenerics();
4310 if (FormatTok->is(tok::colon)) {
4314 if (FormatTok->is(tok::less))
4315 parseObjCLightweightGenerics();
4316 }
else if (FormatTok->is(tok::l_paren)) {
4321 if (FormatTok->is(tok::less))
4322 parseObjCProtocolList();
4324 if (FormatTok->is(tok::l_brace)) {
4325 if (Style.BraceWrapping.AfterObjCDeclaration)
4334 parseObjCUntilAtEnd();
4337void UnwrappedLineParser::parseObjCLightweightGenerics() {
4338 assert(FormatTok->is(tok::less));
4346 unsigned NumOpenAngles = 1;
4350 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4352 if (FormatTok->is(tok::less)) {
4354 }
else if (FormatTok->is(tok::greater)) {
4355 assert(NumOpenAngles > 0 &&
"'>' makes NumOpenAngles negative");
4358 }
while (!
eof() && NumOpenAngles != 0);
4364bool UnwrappedLineParser::parseObjCProtocol() {
4365 assert(FormatTok->is(tok::objc_protocol));
4368 if (FormatTok->is(tok::l_paren)) {
4380 if (FormatTok->is(tok::less))
4381 parseObjCProtocolList();
4384 if (FormatTok->is(tok::semi)) {
4391 parseObjCUntilAtEnd();
4395void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
4396 bool IsImport = FormatTok->is(Keywords.kw_import);
4397 assert(IsImport || FormatTok->is(tok::kw_export));
4401 if (FormatTok->is(tok::kw_default))
4407 if (FormatTok->is(Keywords.kw_async))
4409 if (FormatTok->is(Keywords.kw_function)) {
4418 if (!IsImport && FormatTok->isNoneOf(tok::l_brace, tok::star) &&
4419 !FormatTok->isStringLiteral() &&
4420 !(FormatTok->is(Keywords.kw_type) &&
4421 Tokens->peekNextToken()->isOneOf(tok::l_brace, tok::star))) {
4426 if (FormatTok->is(tok::semi))
4428 if (
Line->Tokens.empty()) {
4433 if (FormatTok->is(tok::l_brace)) {
4434 FormatTok->setBlockKind(BK_Block);
4443void UnwrappedLineParser::parseStatementMacro() {
4445 if (FormatTok->is(tok::l_paren))
4447 if (FormatTok->is(tok::semi))
4452void UnwrappedLineParser::parseVerilogHierarchyIdentifier() {
4455 if (FormatTok->isOneOf(tok::star, tok::period, tok::periodstar,
4456 tok::coloncolon, tok::hash) ||
4457 Keywords.isVerilogIdentifier(*FormatTok)) {
4459 }
else if (FormatTok->is(tok::l_square)) {
4467void UnwrappedLineParser::parseVerilogSensitivityList() {
4468 if (FormatTok->isNot(tok::at))
4472 if (FormatTok->is(tok::at))
4474 switch (FormatTok->Tok.getKind()) {
4482 parseVerilogHierarchyIdentifier();
4487unsigned UnwrappedLineParser::parseVerilogHierarchyHeader() {
4488 unsigned AddLevels = 0;
4490 if (FormatTok->is(Keywords.kw_clocking)) {
4492 if (Keywords.isVerilogIdentifier(*FormatTok))
4494 parseVerilogSensitivityList();
4495 if (FormatTok->is(tok::semi))
4497 }
else if (FormatTok->isOneOf(tok::kw_case, Keywords.kw_casex,
4498 Keywords.kw_casez, Keywords.kw_randcase,
4499 Keywords.kw_randsequence)) {
4500 if (Style.IndentCaseLabels)
4503 if (FormatTok->is(tok::l_paren)) {
4504 FormatTok->setFinalizedType(TT_ConditionLParen);
4507 if (FormatTok->isOneOf(Keywords.kw_inside, Keywords.kw_matches))
4516 if (FormatTok->is(tok::l_square)) {
4517 auto Prev = FormatTok->getPreviousNonComment();
4518 if (Prev && Keywords.isVerilogIdentifier(*Prev))
4519 Prev->setFinalizedType(TT_VerilogDimensionedTypeName);
4521 }
else if (Keywords.isVerilogIdentifier(*FormatTok) ||
4522 FormatTok->isOneOf(tok::hash, tok::hashhash, tok::coloncolon,
4523 Keywords.kw_automatic, tok::kw_static)) {
4530 auto NewLine = [
this]() {
4532 Line->IsContinuation =
true;
4536 while (FormatTok->is(Keywords.kw_import)) {
4539 parseVerilogHierarchyIdentifier();
4540 if (FormatTok->is(tok::semi))
4545 if (FormatTok->is(Keywords.kw_verilogHash)) {
4548 if (FormatTok->is(tok::l_paren)) {
4549 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4553 if (FormatTok->is(tok::l_paren)) {
4555 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4560 if (FormatTok->is(Keywords.kw_extends)) {
4563 parseVerilogHierarchyIdentifier();
4564 if (FormatTok->is(tok::l_paren))
4567 if (FormatTok->is(Keywords.kw_implements)) {
4571 parseVerilogHierarchyIdentifier();
4572 }
while (FormatTok->is(tok::comma));
4576 if (FormatTok->is(tok::at)) {
4578 parseVerilogSensitivityList();
4581 if (FormatTok->is(tok::semi))
4589void UnwrappedLineParser::parseVerilogTable() {
4590 assert(FormatTok->is(Keywords.kw_table));
4594 auto InitialLevel =
Line->Level++;
4595 while (!
eof() && !Keywords.isVerilogEnd(*FormatTok)) {
4598 if (
Tok->
is(tok::semi))
4600 else if (
Tok->
isOneOf(tok::star, tok::colon, tok::question, tok::minus))
4601 Tok->setFinalizedType(TT_VerilogTableItem);
4603 Line->Level = InitialLevel;
4608void UnwrappedLineParser::parseVerilogCaseLabel() {
4614 auto OrigLevel =
Line->Level;
4615 auto FirstLine = CurrentLines->size();
4616 if (
Line->Level == 0 || (
Line->InPPDirective &&
Line->Level <= 1))
4618 else if (!Style.IndentCaseBlocks && Keywords.isVerilogBegin(*FormatTok))
4620 parseStructuralElement();
4623 if (CurrentLines->size() > FirstLine)
4624 (*CurrentLines)[FirstLine].Level = OrigLevel;
4625 Line->Level = OrigLevel;
4628void UnwrappedLineParser::parseVerilogExtern() {
4630 FormatTok->isOneOf(tok::kw_extern, tok::kw_export, Keywords.kw_import));
4633 if (FormatTok->is(tok::string_literal))
4635 skipVerilogQualifiers();
4636 if (Keywords.isVerilogIdentifier(*FormatTok))
4638 if (FormatTok->is(tok::equal))
4640 if (Keywords.isVerilogHierarchy(*FormatTok))
4641 parseVerilogHierarchyHeader();
4644void UnwrappedLineParser::skipVerilogQualifiers() {
4645 while (FormatTok->isOneOf(tok::kw_protected, tok::kw_virtual, tok::kw_static,
4646 Keywords.kw_rand, Keywords.kw_context,
4647 Keywords.kw_pure, Keywords.kw_randc,
4648 Keywords.kw_local)) {
4653bool UnwrappedLineParser::containsExpansion(
const UnwrappedLine &
Line)
const {
4654 for (
const auto &N :
Line.Tokens) {
4655 if (N.Tok->MacroCtx)
4657 for (
const UnwrappedLine &Child : N.Children)
4658 if (containsExpansion(Child))
4664void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) {
4665 if (
Line->Tokens.empty())
4668 if (!parsingPPDirective()) {
4669 llvm::dbgs() <<
"Adding unwrapped line:\n";
4670 printDebugInfo(*
Line);
4678 bool ClosesWhitesmithsBlock =
4679 Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex &&
4680 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
4685 if (!parsingPPDirective() && !InExpansion && containsExpansion(*
Line)) {
4687 Reconstruct.emplace(
Line->Level, Unexpanded);
4688 Reconstruct->addLine(*
Line);
4693 CurrentExpandedLines.push_back(std::move(*
Line));
4695 if (Reconstruct->finished()) {
4696 UnwrappedLine Reconstructed = std::move(*Reconstruct).takeResult();
4697 assert(!Reconstructed.Tokens.empty() &&
4698 "Reconstructed must at least contain the macro identifier.");
4699 assert(!parsingPPDirective());
4701 llvm::dbgs() <<
"Adding unexpanded line:\n";
4702 printDebugInfo(Reconstructed);
4704 ExpandedLines[Reconstructed.Tokens.begin()->Tok] = CurrentExpandedLines;
4705 Lines.push_back(std::move(Reconstructed));
4706 CurrentExpandedLines.clear();
4707 Reconstruct.reset();
4712 assert(!Reconstruct || (CurrentLines != &Lines) || !PPStack.empty());
4713 CurrentLines->push_back(std::move(*
Line));
4715 Line->Tokens.clear();
4716 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
4717 Line->FirstStartColumn = 0;
4718 Line->IsContinuation =
false;
4719 Line->SeenDecltypeAuto =
false;
4720 Line->IsModuleOrImportDecl =
false;
4722 if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove)
4724 if (!parsingPPDirective() && !PreprocessorDirectives.empty()) {
4725 CurrentLines->append(
4726 std::make_move_iterator(PreprocessorDirectives.begin()),
4727 std::make_move_iterator(PreprocessorDirectives.end()));
4728 PreprocessorDirectives.clear();
4731 FormatTok->Previous =
nullptr;
4734bool UnwrappedLineParser::eof()
const {
return FormatTok->is(tok::eof); }
4736bool UnwrappedLineParser::isOnNewLine(
const FormatToken &FormatTok) {
4737 return (
Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
4738 FormatTok.NewlinesBefore > 0;
4746 const llvm::Regex &CommentPragmasRegex) {
4747 if (
Line.Tokens.empty() || Style.ReflowComments != FormatStyle::RCS_Always)
4750 StringRef IndentContent = FormatTok.
TokenText;
4751 if (FormatTok.
TokenText.starts_with(
"//") ||
4752 FormatTok.
TokenText.starts_with(
"/*")) {
4753 IndentContent = FormatTok.
TokenText.substr(2);
4755 if (CommentPragmasRegex.match(IndentContent))
4830 if (PreviousToken && PreviousToken->
is(tok::l_brace) &&
4832 MinColumnToken = PreviousToken;
4835 PreviousToken = Node.
Tok;
4839 MinColumnToken = Node.
Tok;
4841 if (PreviousToken && PreviousToken->
is(tok::l_brace))
4842 MinColumnToken = PreviousToken;
4848void UnwrappedLineParser::flushComments(
bool NewlineBeforeNext) {
4849 bool JustComments =
Line->Tokens.empty();
4859 Tok->ContinuesLineCommentSection =
4860 continuesLineCommentSection(*
Tok, *
Line, Style, CommentPragmasRegex);
4861 if (isOnNewLine(*
Tok) && JustComments && !
Tok->ContinuesLineCommentSection)
4865 if (NewlineBeforeNext && JustComments)
4867 CommentsBeforeNextToken.clear();
4870void UnwrappedLineParser::nextToken(
int LevelDifference) {
4873 flushComments(isOnNewLine(*FormatTok));
4874 pushToken(FormatTok);
4876 if (!Style.isJavaScript())
4877 readToken(LevelDifference);
4879 readTokenWithJavaScriptASI();
4881 if (Style.isVerilog()) {
4888 if (Keywords.isVerilogEnd(*FormatTok))
4889 FormatTok->Tok.setKind(tok::r_brace);
4893void UnwrappedLineParser::distributeComments(
4913 if (Comments.empty())
4915 bool ShouldPushCommentsInCurrentLine =
true;
4916 bool HasTrailAlignedWithNextToken =
false;
4917 unsigned StartOfTrailAlignedWithNextToken = 0;
4920 for (
unsigned i = Comments.size() - 1; i > 0; --i) {
4922 HasTrailAlignedWithNextToken =
true;
4923 StartOfTrailAlignedWithNextToken = i;
4927 for (
unsigned i = 0, e = Comments.size(); i < e; ++i) {
4929 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
4930 FormatTok->ContinuesLineCommentSection =
false;
4933 *FormatTok, *
Line, Style, CommentPragmasRegex);
4935 if (!FormatTok->ContinuesLineCommentSection &&
4936 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
4937 ShouldPushCommentsInCurrentLine =
false;
4939 if (ShouldPushCommentsInCurrentLine)
4940 pushToken(FormatTok);
4942 CommentsBeforeNextToken.push_back(FormatTok);
4946void UnwrappedLineParser::readToken(
int LevelDifference) {
4948 bool PreviousWasComment =
false;
4949 bool FirstNonCommentOnLine =
false;
4951 FormatTok = Tokens->getNextToken();
4953 while (FormatTok->isOneOf(TT_ConflictStart, TT_ConflictEnd,
4954 TT_ConflictAlternative)) {
4955 if (FormatTok->is(TT_ConflictStart))
4956 conditionalCompilationStart(
false);
4957 else if (FormatTok->is(TT_ConflictAlternative))
4958 conditionalCompilationAlternative();
4959 else if (FormatTok->is(TT_ConflictEnd))
4960 conditionalCompilationEnd();
4961 FormatTok = Tokens->getNextToken();
4962 FormatTok->MustBreakBefore =
true;
4963 FormatTok->MustBreakBeforeFinalized =
true;
4966 auto IsFirstNonCommentOnLine = [](
bool FirstNonCommentOnLine,
4968 bool PreviousWasComment) {
4970 return Tok.HasUnescapedNewline ||
Tok.IsFirst;
4975 if (PreviousWasComment)
4976 return FirstNonCommentOnLine || IsFirstOnLine(
Tok);
4977 return IsFirstOnLine(
Tok);
4980 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
4981 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
4982 PreviousWasComment = FormatTok->is(tok::comment);
4984 while (!
Line->InPPDirective && FormatTok->is(tok::hash) &&
4985 FirstNonCommentOnLine) {
4988 const auto *
Next = Tokens->peekNextToken();
4989 if ((Style.isVerilog() && !Keywords.isVerilogPPDirective(*
Next)) ||
4990 (Style.isTableGen() &&
4991 Next->isNoneOf(tok::kw_else, tok::pp_define, tok::pp_ifdef,
4992 tok::pp_ifndef, tok::pp_endif))) {
4995 distributeComments(Comments, FormatTok);
4999 bool SwitchToPreprocessorLines = !
Line->Tokens.empty();
5000 ScopedLineState BlockState(*
this, SwitchToPreprocessorLines);
5001 assert((LevelDifference >= 0 ||
5002 static_cast<unsigned>(-LevelDifference) <=
Line->Level) &&
5003 "LevelDifference makes Line->Level negative");
5004 Line->Level += LevelDifference;
5008 if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash &&
5009 PPBranchLevel > 0) {
5010 Line->Level += PPBranchLevel;
5012 assert(
Line->Level >=
Line->UnbracedBodyLevel);
5013 Line->Level -=
Line->UnbracedBodyLevel;
5014 flushComments(isOnNewLine(*FormatTok));
5015 const bool IsEndIf = Tokens->peekNextToken()->is(tok::pp_endif);
5017 PreviousWasComment = FormatTok->is(tok::comment);
5018 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
5019 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
5022 if (IsEndIf && IncludeGuard == IG_Defined && PPBranchLevel == -1 &&
5023 getIncludeGuardState(Style.IndentPPDirectives) == IG_Inited &&
5025 (PreviousWasComment &&
5026 Tokens->peekNextToken(
true)->is(tok::eof)))) {
5027 IncludeGuard = IG_Found;
5031 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
5032 !
Line->InPPDirective) {
5036 if (FormatTok->is(tok::identifier) &&
5037 Macros.defined(FormatTok->TokenText) &&
5039 !
Line->InPPDirective) {
5041 unsigned Position = Tokens->getPosition();
5045 auto PreCall = std::move(
Line);
5046 Line.reset(
new UnwrappedLine);
5047 bool OldInExpansion = InExpansion;
5050 auto Args = parseMacroCall();
5051 InExpansion = OldInExpansion;
5052 assert(
Line->Tokens.front().Tok == ID);
5054 auto UnexpandedLine = std::move(
Line);
5056 Line = std::move(PreCall);
5059 llvm::dbgs() <<
"Macro call: " <<
ID->TokenText <<
"(";
5061 llvm::dbgs() <<
"(";
5062 for (
const auto &Arg : Args.value())
5063 for (
const auto &T : Arg)
5064 llvm::dbgs() << T->TokenText <<
" ";
5065 llvm::dbgs() <<
")";
5067 llvm::dbgs() <<
"\n";
5069 if (
Macros.objectLike(
ID->TokenText) && Args &&
5070 !
Macros.hasArity(
ID->TokenText, Args->size())) {
5076 LLVM_DEBUG(llvm::dbgs()
5077 <<
"Macro \"" <<
ID->TokenText
5078 <<
"\" not overloaded for arity " << Args->size()
5079 <<
"or not function-like, using object-like overload.");
5081 UnexpandedLine->Tokens.resize(1);
5082 Tokens->setPosition(Position);
5084 assert(!Args &&
Macros.objectLike(
ID->TokenText));
5086 if ((!Args &&
Macros.objectLike(
ID->TokenText)) ||
5087 (Args &&
Macros.hasArity(
ID->TokenText, Args->size()))) {
5090 Unexpanded[
ID] = std::move(UnexpandedLine);
5092 Macros.expand(ID, std::move(Args));
5093 if (!Expansion.empty())
5094 FormatTok = Tokens->insertTokens(Expansion);
5097 llvm::dbgs() <<
"Expanded: ";
5098 for (
const auto &T : Expansion)
5099 llvm::dbgs() << T->TokenText <<
" ";
5100 llvm::dbgs() <<
"\n";
5104 llvm::dbgs() <<
"Did not expand macro \"" <<
ID->TokenText
5105 <<
"\", because it was used ";
5107 llvm::dbgs() <<
"with " << Args->size();
5109 llvm::dbgs() <<
"without";
5110 llvm::dbgs() <<
" arguments, which doesn't match any definition.\n";
5112 Tokens->setPosition(Position);
5117 if (FormatTok->isNot(tok::comment)) {
5118 distributeComments(Comments, FormatTok);
5123 Comments.push_back(FormatTok);
5126 distributeComments(Comments,
nullptr);
5131template <
typename Iterator>
5132void pushTokens(Iterator Begin, Iterator End,
5134 for (
auto I = Begin; I != End; ++I) {
5135 Into.push_back(I->Tok);
5136 for (
const auto &Child : I->Children)
5137 pushTokens(Child.Tokens.begin(), Child.Tokens.end(), Into);
5142std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>
5143UnwrappedLineParser::parseMacroCall() {
5144 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>> Args;
5145 assert(
Line->Tokens.empty());
5147 if (FormatTok->isNot(tok::l_paren))
5149 unsigned Position = Tokens->getPosition();
5153 auto ArgStart = std::prev(
Line->Tokens.end());
5157 switch (FormatTok->Tok.getKind()) {
5162 case tok::r_paren: {
5168 Args->push_back({});
5169 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5178 Args->push_back({});
5179 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5181 ArgStart = std::prev(
Line->Tokens.end());
5189 Line->Tokens.resize(1);
5190 Tokens->setPosition(Position);
5196 Line->Tokens.push_back(UnwrappedLineNode(
Tok));
5197 if (AtEndOfPPLine) {
5198 auto &
Tok = *
Line->Tokens.back().Tok;
5199 Tok.MustBreakBefore =
true;
5200 Tok.MustBreakBeforeFinalized =
true;
5201 Tok.FirstAfterPPLine =
true;
5202 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
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.
The JSON file list parser is used to communicate input to InstallAPI.
bool isLineComment(const FormatToken &FormatTok)
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
std::vector< std::string > Macros
A list of macros of the form <definition>=<expansion> .
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Default
Set to the current date and time.
@ 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.