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);
100 bool SwitchToPreprocessorLines =
false,
101 bool DiscardLines =
false)
102 : Parser(Parser), OriginalLines(Parser.CurrentLines),
103 DiscardLines(DiscardLines) {
104 if (SwitchToPreprocessorLines)
105 Parser.CurrentLines = &Parser.PreprocessorDirectives;
106 else if (!Parser.Line->Tokens.empty())
107 Parser.CurrentLines = &Parser.Line->Tokens.back().Children;
108 OriginalNumLines = Parser.CurrentLines->size();
109 PreBlockLine = std::move(Parser.Line);
110 Parser.Line = std::make_unique<UnwrappedLine>();
111 Parser.Line->Level = PreBlockLine->Level;
112 Parser.Line->PPLevel = PreBlockLine->PPLevel;
113 Parser.Line->InPPDirective = PreBlockLine->InPPDirective;
114 Parser.Line->InMacroBody = PreBlockLine->InMacroBody;
115 Parser.Line->UnbracedBodyLevel = PreBlockLine->UnbracedBodyLevel;
119 if (!Parser.Line->Tokens.empty())
120 Parser.addUnwrappedLine();
121 assert(Parser.Line->Tokens.empty());
123 Parser.CurrentLines->truncate(OriginalNumLines);
124 Parser.Line = std::move(PreBlockLine);
125 if (Parser.CurrentLines == &Parser.PreprocessorDirectives)
126 Parser.PP.AtEndOfPPLine =
true;
127 Parser.CurrentLines = OriginalLines;
133 std::unique_ptr<UnwrappedLine> PreBlockLine;
135 size_t OriginalNumLines;
144 Style.BraceWrapping.AfterControlStatement ==
146 Style.BraceWrapping.IndentBraces) {}
148 bool WrapBrace,
bool IndentBrace)
149 : LineLevel(LineLevel), OldLineLevel(LineLevel) {
151 Parser->addUnwrappedLine();
159 unsigned OldLineLevel;
166 llvm::SpecificBumpPtrAllocator<FormatToken> &Allocator,
168 : Line(new
UnwrappedLine), CurrentLines(&Lines), Style(Style),
170 Keywords(Keywords), CommentPragmasRegex(Style.CommentPragmas),
171 Tokens(
nullptr), Callback(Callback), AllTokens(Tokens),
172 PP(getIncludeGuardState(Style.IndentPPDirectives)),
173 FirstStartColumn(FirstStartColumn),
174 Macros(Style.Macros, SourceMgr, Style, Allocator, IdentTable) {}
176void UnwrappedLineParser::reset() {
178 PP.IncludeGuard = getIncludeGuardState(Style.IndentPPDirectives);
179 PP.IncludeGuardToken =
nullptr;
180 ParsedPPDirectives.clear();
182 CommentsBeforeNextToken.clear();
184 PP.AtEndOfPPLine =
false;
185 IsDecltypeAutoFunction =
false;
186 PreprocessorDirectives.clear();
187 CurrentLines = &Lines;
188 DeclarationScopeStack.clear();
189 NestedTooDeep.clear();
190 NestedLambdas.clear();
192 Line->FirstStartColumn = FirstStartColumn;
194 if (!Unexpanded.empty())
196 Token->MacroCtx.reset();
197 CurrentExpandedLines.clear();
198 ExpandedLines.clear();
206 Line->FirstStartColumn = FirstStartColumn;
208 LLVM_DEBUG(llvm::dbgs() <<
"----\n");
210 Tokens = &TokenSource;
218 if (PP.IncludeGuard == IG_Found) {
219 for (
auto &Line : Lines)
220 if (Line.InPPDirective && Line.Level > 0)
226 pushToken(FormatTok);
231 if (!ExpandedLines.empty()) {
232 LLVM_DEBUG(llvm::dbgs() <<
"Expanded lines:\n");
233 for (
const auto &Line : Lines) {
234 if (!Line.Tokens.empty()) {
235 auto it = ExpandedLines.find(Line.Tokens.begin()->Tok);
236 if (it != ExpandedLines.end()) {
237 for (
const auto &Expanded : it->second) {
238 LLVM_DEBUG(printDebugInfo(Expanded));
239 Callback.consumeUnwrappedLine(Expanded);
244 LLVM_DEBUG(printDebugInfo(Line));
245 Callback.consumeUnwrappedLine(Line);
247 Callback.finishRun();
250 LLVM_DEBUG(llvm::dbgs() <<
"Unwrapped lines:\n");
252 LLVM_DEBUG(printDebugInfo(Line));
253 Callback.consumeUnwrappedLine(Line);
255 Callback.finishRun();
257 while (!PP.LevelBranchIndex.empty() &&
258 PP.LevelBranchIndex.back() + 1 >= PP.LevelBranchCount.back()) {
259 PP.LevelBranchIndex.resize(PP.LevelBranchIndex.size() - 1);
260 PP.LevelBranchCount.resize(PP.LevelBranchCount.size() - 1);
262 if (!PP.LevelBranchIndex.empty()) {
263 ++PP.LevelBranchIndex.back();
264 assert(PP.LevelBranchIndex.size() == PP.LevelBranchCount.size());
265 assert(PP.LevelBranchIndex.back() <= PP.LevelBranchCount.back());
267 }
while (!PP.LevelBranchIndex.empty());
270void UnwrappedLineParser::parseFile() {
273 bool MustBeDeclaration = !
Line->InPPDirective && !Style.isJavaScript();
274 ScopedDeclarationState DeclarationState(*
Line, DeclarationScopeStack,
276 if (Style.isTextProto() || (Style.isJson() && FormatTok->
IsFirst))
290 if (Style.isTextProto() && !CommentsBeforeNextToken.empty())
296void UnwrappedLineParser::parseCSharpGenericTypeConstraint() {
306 parseCSharpGenericTypeConstraint();
315void UnwrappedLineParser::parseCSharpAttribute() {
316 int UnpairedSquareBrackets = 1;
318 switch (FormatTok->Tok.getKind()) {
321 --UnpairedSquareBrackets;
322 if (UnpairedSquareBrackets == 0) {
328 ++UnpairedSquareBrackets;
338bool UnwrappedLineParser::precededByCommentOrPPDirective()
const {
339 if (!Lines.empty() && Lines.back().InPPDirective)
353bool UnwrappedLineParser::parseLevel(
const FormatToken *OpeningBrace,
356 bool *SeenExplicitAccessModifier) {
357 const bool InRequiresExpression =
358 OpeningBrace && OpeningBrace->is(TT_RequiresExpressionLBrace);
359 const bool IsPrecededByCommentOrPPDirective =
360 !Style.RemoveBracesLLVM || precededByCommentOrPPDirective();
362 bool HasDoWhile =
false;
363 bool HasLabel =
false;
364 unsigned StatementCount = 0;
365 bool SwitchLabelEncountered =
false;
368 if (FormatTok->isAttribute()) {
370 if (FormatTok->is(tok::l_paren))
375 if (FormatTok->is(TT_MacroBlockBegin))
377 else if (FormatTok->is(TT_MacroBlockEnd))
380 auto ParseDefault = [
this, OpeningBrace, IfKind, &IfLBrace, &HasDoWhile,
381 &HasLabel, &StatementCount,
382 SeenExplicitAccessModifier] {
383 if (SeenExplicitAccessModifier && !*SeenExplicitAccessModifier) {
384 const bool IsQtAccessLabel =
385 FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
386 Keywords.kw_slots, Keywords.kw_qslots) &&
387 Tokens->peekNextToken(
true)->is(tok::colon);
388 if (FormatTok->isAccessSpecifierKeyword() || IsQtAccessLabel) {
390 *SeenExplicitAccessModifier =
true;
393 parseStructuralElement(OpeningBrace, IfKind, &IfLBrace,
394 HasDoWhile ?
nullptr : &HasDoWhile,
395 HasLabel ?
nullptr : &HasLabel);
397 assert(StatementCount > 0 &&
"StatementCount overflow!");
406 if (InRequiresExpression) {
407 FormatTok->setFinalizedType(TT_CompoundRequirementLBrace);
408 }
else if (FormatTok->Previous &&
409 FormatTok->Previous->ClosesRequiresClause) {
415 if (!InRequiresExpression && FormatTok->isNot(TT_MacroBlockBegin)) {
416 if (tryToParseBracedList())
418 FormatTok->setFinalizedType(TT_BlockLBrace);
422 assert(StatementCount > 0 &&
"StatementCount overflow!");
427 if (!Style.RemoveBracesLLVM || Line->InPPDirective ||
428 OpeningBrace->isNoneOf(TT_ControlStatementLBrace, TT_ElseLBrace)) {
431 if (FormatTok->isNot(tok::r_brace) || StatementCount != 1 || HasLabel ||
432 HasDoWhile || IsPrecededByCommentOrPPDirective ||
433 precededByCommentOrPPDirective()) {
437 if (
Next->is(tok::comment) &&
Next->NewlinesBefore == 0)
440 *IfLeftBrace = IfLBrace;
446 case tok::kw_default: {
447 unsigned StoredPosition = Tokens->getPosition();
448 auto *
Next = Tokens->getNextNonComment();
449 FormatTok = Tokens->setPosition(StoredPosition);
450 if (
Next->isNoneOf(tok::colon, tok::arrow)) {
453 parseStructuralElement();
461 (Style.isJavaScript() && Line->MustBeDeclaration)) {
469 if (!SwitchLabelEncountered &&
470 (Style.IndentCaseLabels ||
471 (OpeningBrace && OpeningBrace->is(TT_SwitchExpressionLBrace)) ||
472 (Line->InPPDirective && Line->Level == 1))) {
475 SwitchLabelEncountered =
true;
476 parseStructuralElement();
479 if (Style.isCSharp()) {
481 parseCSharpAttribute();
484 if (handleCppAttributes())
496void UnwrappedLineParser::calculateBraceTypes(
bool ExpectClassBody) {
501 unsigned StoredPosition = Tokens->getPosition();
511 SmallVector<StackEntry, 8> LBraceStack;
512 assert(
Tok->is(tok::l_brace));
515 auto *NextTok = Tokens->getNextNonComment();
517 if (!Line->InMacroBody && !Style.isTableGen()) {
519 while (NextTok->is(tok::hash)) {
520 NextTok = Tokens->getNextToken();
521 if (NextTok->isOneOf(tok::pp_not_keyword, tok::pp_define))
524 NextTok = Tokens->getNextToken();
525 }
while (!NextTok->HasUnescapedNewline && NextTok->isNot(tok::eof));
527 while (NextTok->is(tok::comment))
528 NextTok = Tokens->getNextToken();
532 switch (
Tok->Tok.getKind()) {
534 if (Style.isJavaScript() && PrevTok) {
535 if (PrevTok->isOneOf(tok::colon, tok::less)) {
546 }
else if (PrevTok->is(tok::r_paren)) {
550 }
else if (Style.isJava() && PrevTok && PrevTok->is(tok::arrow)) {
555 LBraceStack.push_back({
Tok, PrevTok});
558 if (LBraceStack.empty())
560 if (
auto *LBrace = LBraceStack.back().Tok; LBrace->is(
BK_Unknown)) {
561 bool ProbablyBracedList =
false;
563 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
564 }
else if (LBrace->isNot(TT_EnumLBrace)) {
567 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
568 NextTok->OriginalColumn == 0;
578 ProbablyBracedList = LBrace->is(TT_BracedListLBrace);
580 ProbablyBracedList = ProbablyBracedList ||
581 (Style.isJavaScript() &&
582 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
585 ProbablyBracedList ||
586 (IsCpp && (PrevTok->Tok.isLiteral() ||
587 NextTok->isOneOf(tok::l_paren, tok::arrow)));
594 ProbablyBracedList ||
595 NextTok->isOneOf(tok::comma, tok::period, tok::colon,
596 tok::r_paren, tok::r_square, tok::ellipsis);
601 ProbablyBracedList ||
602 (NextTok->is(tok::l_brace) && LBraceStack.back().PrevTok &&
603 LBraceStack.back().PrevTok->isOneOf(tok::identifier,
607 ProbablyBracedList ||
608 (NextTok->is(tok::identifier) &&
609 PrevTok->isNoneOf(tok::semi, tok::r_brace, tok::l_brace));
611 ProbablyBracedList = ProbablyBracedList ||
612 (NextTok->is(tok::semi) &&
613 (!ExpectClassBody || LBraceStack.size() != 1));
616 ProbablyBracedList ||
617 (NextTok->isBinaryOperator() && !NextIsObjCMethod);
619 if (!Style.isCSharp() && NextTok->is(tok::l_square)) {
622 NextTok = Tokens->getNextToken();
623 ProbablyBracedList = NextTok->isNot(tok::l_square);
627 if (IsCpp && Line->InMacroBody && PrevTok != FormatTok &&
628 !FormatTok->Previous && NextTok->is(tok::eof) &&
632 PrevTok->isNoneOf(tok::semi,
BK_Block, tok::colon)) {
633 ProbablyBracedList =
true;
637 Tok->setBlockKind(BlockKind);
638 LBrace->setBlockKind(BlockKind);
640 LBraceStack.pop_back();
642 case tok::identifier:
643 if (
Tok->isNot(TT_StatementMacro))
654 if (!LBraceStack.empty() && LBraceStack.back().Tok->is(
BK_Unknown))
655 LBraceStack.back().Tok->setBlockKind(
BK_Block);
663 }
while (
Tok->isNot(tok::eof) && !LBraceStack.empty());
666 for (
const auto &Entry : LBraceStack)
670 FormatTok = Tokens->setPosition(StoredPosition);
674void UnwrappedLineParser::setPreviousRBraceType(
TokenType Type) {
675 if (
auto Prev = FormatTok->getPreviousNonComment();
676 Prev && Prev->is(tok::r_brace)) {
677 Prev->setFinalizedType(
Type);
684 seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
687size_t UnwrappedLineParser::computePPHash()
const {
689 for (
const auto &i : PP.Stack) {
700bool UnwrappedLineParser::mightFitOnOneLine(
702 const auto ColumnLimit = Style.ColumnLimit;
703 if (ColumnLimit == 0)
706 auto &Tokens = ParsedLine.Tokens;
707 assert(!Tokens.empty());
709 const auto *LastToken = Tokens.back().Tok;
712 SmallVector<UnwrappedLineNode> SavedTokens(Tokens.size());
715 for (
const auto &Token : Tokens) {
717 auto &SavedToken = SavedTokens[Index++];
719 SavedToken.Tok->copyFrom(*Token.Tok);
720 SavedToken.Children = std::move(Token.Children);
723 AnnotatedLine
Line(ParsedLine);
724 assert(Line.Last == LastToken);
726 TokenAnnotator Annotator(Style, Keywords);
727 Annotator.annotate(Line);
728 Annotator.calculateFormattingInformation(Line);
730 auto Length = LastToken->TotalLength;
732 assert(OpeningBrace != Tokens.front().Tok);
733 if (
auto Prev = OpeningBrace->Previous;
734 Prev && Prev->TotalLength + ColumnLimit == OpeningBrace->TotalLength) {
735 Length -= ColumnLimit;
737 Length -= OpeningBrace->TokenText.size() + 1;
740 if (
const auto *FirstToken = Line.First; FirstToken->is(tok::r_brace)) {
741 assert(!OpeningBrace || OpeningBrace->is(TT_ControlStatementLBrace));
742 Length -= FirstToken->TokenText.size() + 1;
746 for (
auto &Token : Tokens) {
747 const auto &SavedToken = SavedTokens[Index++];
748 Token.Tok->copyFrom(*SavedToken.Tok);
749 Token.Children = std::move(SavedToken.Children);
750 delete SavedToken.Tok;
754 assert(!Line.InMacroBody);
755 assert(!Line.InPPDirective);
756 return Line.Level * Style.IndentWidth + Length <= ColumnLimit;
760 bool MustBeDeclaration,
unsigned AddLevels,
bool MunchSemi,
bool KeepBraces,
761 IfStmtKind *IfKind,
bool UnindentWhitesmithsBraces,
762 bool IndentAfterExplicitAccessModifier) {
763 auto HandleVerilogBlockLabel = [
this]() {
765 if (Style.isVerilog() && FormatTok->is(tok::colon)) {
767 if (Keywords.isVerilogIdentifier(*FormatTok))
774 const bool VerilogHierarchy =
775 Style.isVerilog() && Keywords.isVerilogHierarchy(*FormatTok);
776 assert((FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) ||
777 (Style.isVerilog() &&
778 (Keywords.isVerilogBegin(*FormatTok) || VerilogHierarchy))) &&
779 "'{' or macro block token expected");
781 const bool FollowedByComment = Tokens->peekNextToken()->is(tok::comment);
782 auto Index = CurrentLines->size();
783 const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
786 const bool IsWhitesmiths =
791 if (!VerilogHierarchy && AddLevels > 0 && IsWhitesmiths)
794 size_t PPStartHash = computePPHash();
796 const unsigned InitialLevel = Line->Level;
797 if (VerilogHierarchy) {
798 AddLevels += parseVerilogHierarchyHeader();
800 nextToken(AddLevels);
801 HandleVerilogBlockLabel();
805 if (Line->Level > 300)
808 if (MacroBlock && FormatTok->is(tok::l_paren))
811 size_t NbPreprocessorDirectives =
812 !parsingPPDirective() ? PreprocessorDirectives.size() : 0;
814 size_t OpeningLineIndex =
815 CurrentLines->empty()
817 : (CurrentLines->size() - 1 - NbPreprocessorDirectives);
822 if (UnindentWhitesmithsBraces)
825 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
831 Line->Level += AddLevels - (IsWhitesmiths ? 1 : 0);
834 bool SeenExplicitAccessModifier =
false;
835 const bool SimpleBlock =
836 parseLevel(
Tok, IfKind, &IfLBrace,
837 IndentAfterExplicitAccessModifier ? &SeenExplicitAccessModifier
843 if (MacroBlock ? FormatTok->isNot(TT_MacroBlockEnd)
844 : FormatTok->isNot(tok::r_brace)) {
845 Line->Level = InitialLevel;
846 FormatTok->setBlockKind(BK_Block);
850 if (FormatTok->is(tok::r_brace)) {
851 FormatTok->setBlockKind(BK_Block);
852 if (Tok->is(TT_NamespaceLBrace))
853 FormatTok->setFinalizedType(TT_NamespaceRBrace);
856 const bool IsFunctionRBrace =
857 FormatTok->is(tok::r_brace) &&
Tok->is(TT_FunctionLBrace);
859 auto RemoveBraces = [=]()
mutable {
862 assert(Tok->isOneOf(TT_ControlStatementLBrace, TT_ElseLBrace));
863 assert(FormatTok->is(tok::r_brace));
864 const bool WrappedOpeningBrace = !Tok->Previous;
865 if (WrappedOpeningBrace && FollowedByComment)
867 const bool HasRequiredIfBraces = IfLBrace && !IfLBrace->Optional;
868 if (KeepBraces && !HasRequiredIfBraces)
870 if (Tok->isNot(TT_ElseLBrace) || !HasRequiredIfBraces) {
871 const FormatToken *Previous = Tokens->getPreviousToken();
873 if (Previous->is(tok::r_brace) && !Previous->Optional)
876 assert(!CurrentLines->empty());
877 auto &LastLine = CurrentLines->back();
878 if (LastLine.Level == InitialLevel + 1 && !mightFitOnOneLine(LastLine))
880 if (
Tok->is(TT_ElseLBrace))
882 if (WrappedOpeningBrace) {
887 return mightFitOnOneLine((*CurrentLines)[Index],
Tok);
889 if (RemoveBraces()) {
890 Tok->MatchingParen = FormatTok;
891 FormatTok->MatchingParen =
Tok;
894 size_t PPEndHash = computePPHash();
896 if (SeenExplicitAccessModifier)
899 nextToken(-AddLevels);
904 if (Style.RemoveSemicolon && IsFunctionRBrace) {
905 while (FormatTok->is(tok::semi)) {
906 FormatTok->Optional =
true;
911 HandleVerilogBlockLabel();
913 if (MacroBlock && FormatTok->is(tok::l_paren))
916 Line->Level = InitialLevel;
918 if (FormatTok->is(tok::kw_noexcept)) {
923 if (FormatTok->is(tok::arrow)) {
927 parseStructuralElement();
930 if (MunchSemi && FormatTok->is(tok::semi))
933 if (PPStartHash == PPEndHash) {
934 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
937 (*CurrentLines)[OpeningLineIndex].MatchingClosingBlockLineIndex =
938 CurrentLines->size() - 1;
948 if (
Line.Tokens.size() < 4)
950 auto I =
Line.Tokens.begin();
951 if (I->Tok->TokenText !=
"goog")
954 if (I->Tok->isNot(tok::period))
957 if (I->Tok->TokenText !=
"scope")
960 return I->Tok->is(tok::l_paren);
969 if (
Line.Tokens.size() < 3)
971 auto I =
Line.Tokens.begin();
972 if (I->Tok->isNot(tok::l_paren))
978 return I->Tok->is(tok::l_paren);
984 bool IsJavaRecord =
false) {
986 return Style.BraceWrapping.AfterClass;
989 if (InitialToken.
is(TT_NamespaceMacro))
990 Kind = tok::kw_namespace;
992 const bool WrapRecordAllowed =
995 Style.BraceWrapping.SplitEmptyRecord;
998 case tok::kw_namespace:
999 return Style.BraceWrapping.AfterNamespace;
1001 return Style.BraceWrapping.AfterClass && WrapRecordAllowed;
1003 return Style.BraceWrapping.AfterUnion && WrapRecordAllowed;
1004 case tok::kw_struct:
1005 return Style.BraceWrapping.AfterStruct && WrapRecordAllowed;
1007 return Style.BraceWrapping.AfterEnum;
1013void UnwrappedLineParser::parseChildBlock() {
1014 assert(FormatTok->is(tok::l_brace));
1015 FormatTok->setBlockKind(BK_Block);
1019 bool SkipIndent = (Style.isJavaScript() &&
1020 (isGoogScope(*
Line) || isIIFE(*
Line, Keywords)));
1021 ScopedLineState LineState(*
this);
1022 ScopedDeclarationState DeclarationState(*
Line, DeclarationScopeStack,
1024 Line->Level += SkipIndent ? 0 : 1;
1025 parseLevel(OpeningBrace);
1026 flushComments(isOnNewLine(*FormatTok));
1027 Line->Level -= SkipIndent ? 0 : 1;
1032void UnwrappedLineParser::parsePPDirective() {
1033 assert(FormatTok->is(tok::hash) &&
"'#' expected");
1034 ScopedMacroState MacroState(*
Line, Tokens, FormatTok);
1038 if (!FormatTok->Tok.getIdentifierInfo()) {
1043 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
1044 case tok::pp_define:
1051 case tok::pp_ifndef:
1055 case tok::pp_elifdef:
1056 case tok::pp_elifndef:
1063 case tok::pp_pragma:
1067 case tok::pp_warning:
1069 if (!
eof() && Style.isCpp())
1070 FormatTok->setFinalizedType(TT_AfterPPDirective);
1078void UnwrappedLineParser::conditionalCompilationCondition(
bool Unreachable) {
1079 size_t Line = CurrentLines->size();
1080 if (CurrentLines == &PreprocessorDirectives)
1081 Line += Lines.size();
1084 (!PP.Stack.empty() && PP.Stack.back().Kind == PP_Unreachable)) {
1085 PP.Stack.push_back({PP_Unreachable,
Line});
1087 PP.Stack.push_back({PP_Conditional,
Line});
1091void UnwrappedLineParser::conditionalCompilationStart(
bool Unreachable) {
1093 assert(PP.BranchLevel >= 0 &&
1094 PP.BranchLevel <= (
int)PP.LevelBranchIndex.size());
1095 if (PP.BranchLevel == (
int)PP.LevelBranchIndex.size()) {
1096 PP.LevelBranchIndex.push_back(0);
1097 PP.LevelBranchCount.push_back(0);
1099 PP.ChainBranchIndex.push(Unreachable ? -1 : 0);
1100 bool Skip = PP.LevelBranchIndex[PP.BranchLevel] > 0;
1101 conditionalCompilationCondition(Unreachable ||
Skip);
1104void UnwrappedLineParser::conditionalCompilationAlternative() {
1105 if (!PP.Stack.empty())
1106 PP.Stack.pop_back();
1107 assert(PP.BranchLevel < (
int)PP.LevelBranchIndex.size());
1108 if (!PP.ChainBranchIndex.empty())
1109 ++PP.ChainBranchIndex.top();
1110 conditionalCompilationCondition(
1111 PP.BranchLevel >= 0 && !PP.ChainBranchIndex.empty() &&
1112 PP.LevelBranchIndex[PP.BranchLevel] != PP.ChainBranchIndex.top());
1115void UnwrappedLineParser::conditionalCompilationEnd() {
1116 assert(PP.BranchLevel < (
int)PP.LevelBranchIndex.size());
1117 if (PP.BranchLevel >= 0 && !PP.ChainBranchIndex.empty()) {
1118 if (PP.ChainBranchIndex.top() + 1 > PP.LevelBranchCount[PP.BranchLevel])
1119 PP.LevelBranchCount[PP.BranchLevel] = PP.ChainBranchIndex.top() + 1;
1122 if (PP.BranchLevel > -1)
1124 if (!PP.ChainBranchIndex.empty())
1125 PP.ChainBranchIndex.pop();
1126 if (!PP.Stack.empty())
1127 PP.Stack.pop_back();
1130void UnwrappedLineParser::parsePPIf(
bool IfDef) {
1131 bool IfNDef = FormatTok->is(tok::pp_ifndef);
1133 bool Unreachable =
false;
1134 if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText ==
"0"))
1136 if (IfDef && !IfNDef && FormatTok->TokenText ==
"SWIG")
1138 conditionalCompilationStart(Unreachable);
1142 bool MaybeIncludeGuard = IfNDef;
1143 if (PP.IncludeGuard == IG_Inited && MaybeIncludeGuard) {
1144 for (
auto &
Line : Lines) {
1145 if (
Line.Tokens.front().Tok->isNot(tok::comment)) {
1146 MaybeIncludeGuard =
false;
1147 PP.IncludeGuard = IG_Rejected;
1155 if (PP.IncludeGuard == IG_Inited && MaybeIncludeGuard) {
1156 PP.IncludeGuard = IG_IfNdefed;
1157 PP.IncludeGuardToken = IfCondition;
1161void UnwrappedLineParser::parsePPElse() {
1163 if (PP.IncludeGuard == IG_Defined && PP.BranchLevel == 0)
1164 PP.IncludeGuard = IG_Rejected;
1166 assert(PP.BranchLevel >= -1);
1167 if (PP.BranchLevel == -1)
1168 conditionalCompilationStart(
true);
1169 conditionalCompilationAlternative();
1175void UnwrappedLineParser::parsePPEndIf() {
1176 conditionalCompilationEnd();
1180void UnwrappedLineParser::parsePPDefine() {
1183 if (!FormatTok->Tok.getIdentifierInfo()) {
1184 PP.IncludeGuard = IG_Rejected;
1185 PP.IncludeGuardToken =
nullptr;
1190 bool MaybeIncludeGuard =
false;
1191 if (PP.IncludeGuard == IG_IfNdefed &&
1192 PP.IncludeGuardToken->TokenText == FormatTok->TokenText) {
1193 PP.IncludeGuard = IG_Defined;
1194 PP.IncludeGuardToken =
nullptr;
1195 for (
auto &
Line : Lines) {
1196 if (
Line.Tokens.front().Tok->isNoneOf(tok::comment, tok::hash)) {
1197 PP.IncludeGuard = IG_Rejected;
1201 MaybeIncludeGuard = PP.IncludeGuard == IG_Defined;
1209 FormatTok->Tok.setKind(tok::identifier);
1210 FormatTok->Tok.setIdentifierInfo(Keywords.kw_internal_ident_after_define);
1214 if (MaybeIncludeGuard && !
eof())
1215 PP.IncludeGuard = IG_Rejected;
1217 if (FormatTok->is(tok::l_paren) && !FormatTok->hasWhitespaceBefore())
1220 Line->Level += PP.BranchLevel + 1;
1224 Line->PPLevel = PP.BranchLevel + (PP.IncludeGuard == IG_Defined ? 0 : 1);
1225 assert((
int)
Line->PPLevel >= 0);
1230 Line->InMacroBody =
true;
1232 if (!Style.SkipMacroDefinitionBody) {
1242 for (
auto *Comment : CommentsBeforeNextToken)
1243 Comment->Finalized =
true;
1246 FormatTok->Finalized =
true;
1247 FormatTok = Tokens->getNextToken();
1253void UnwrappedLineParser::parsePPPragma() {
1254 Line->InPragmaDirective =
true;
1258void UnwrappedLineParser::parsePPUnknown() {
1262 Line->Level += PP.BranchLevel + 1;
1272 return Tok.isNoneOf(tok::semi, tok::l_brace,
1275 tok::period, tok::periodstar, tok::arrow, tok::arrowstar,
1276 tok::less, tok::greater, tok::slash, tok::percent,
1277 tok::lessless, tok::greatergreater, tok::equal,
1278 tok::plusequal, tok::minusequal, tok::starequal,
1279 tok::slashequal, tok::percentequal, tok::ampequal,
1280 tok::pipeequal, tok::caretequal, tok::greatergreaterequal,
1293 return FormatTok->
is(tok::identifier) &&
1308 FormatTok->
isOneOf(tok::kw_true, tok::kw_false) ||
1319 tok::kw_if, tok::kw_else,
1321 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
1323 tok::kw_switch, tok::kw_case,
1325 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.
kw_finally,
1327 tok::kw_const, tok::kw_class, Keywords.
kw_var, Keywords.
kw_let,
1335 return Tok.isOneOf(tok::kw_char, tok::kw_short, tok::kw_int, tok::kw_long,
1336 tok::kw_unsigned, tok::kw_float, tok::kw_double,
1353 if (FuncName->
isNot(tok::identifier))
1361 Tok->isNoneOf(tok::kw_register, tok::kw_struct, tok::kw_union)) {
1365 if (
Next->isNot(tok::star) && !
Next->Tok.getIdentifierInfo())
1369 if (!
Tok ||
Tok->isNot(tok::r_paren))
1373 if (!
Tok ||
Tok->isNot(tok::identifier))
1376 return Tok->Previous &&
Tok->Previous->isOneOf(tok::l_paren, tok::comma);
1379bool UnwrappedLineParser::parseModuleDecl() {
1381 assert(FormatTok->is(Keywords.kw_module));
1389 if (FormatTok->isNot(tok::identifier))
1392 for (nextToken(); FormatTok->isNoneOf(tok::semi, tok::eof); nextToken())
1393 if (FormatTok->is(tok::colon))
1394 FormatTok->setFinalizedType(TT_ModulePartitionColon);
1397 Line->IsModuleOrImportDecl =
true;
1402bool UnwrappedLineParser::parseImportDecl() {
1404 assert(FormatTok->is(Keywords.kw_import) &&
"'import' expected");
1412 if (FormatTok->is(tok::colon)) {
1413 FormatTok->setFinalizedType(TT_ModulePartitionColon);
1416 if (FormatTok->isNoneOf(tok::identifier, tok::less, tok::string_literal))
1419 for (; FormatTok->isNoneOf(tok::semi, tok::eof); nextToken()) {
1421 if (FormatTok->is(tok::less)) {
1422 for (nextToken(); FormatTok->isNoneOf(tok::greater, tok::semi, tok::eof);
1426 FormatTok->setFinalizedType(TT_ImplicitStringLiteral);
1432 Line->IsModuleOrImportDecl =
true;
1444void UnwrappedLineParser::readTokenWithJavaScriptASI() {
1450 CommentsBeforeNextToken.empty()
1451 ?
Next->NewlinesBefore == 0
1452 : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
1457 bool PreviousStartsTemplateExpr =
1459 if (PreviousMustBeValue ||
Previous->is(tok::r_paren)) {
1462 bool HasAt = llvm::any_of(
Line->Tokens, [](UnwrappedLineNode &LineNode) {
1463 return LineNode.Tok->is(tok::at);
1468 if (
Next->is(tok::exclaim) && PreviousMustBeValue)
1469 return addUnwrappedLine();
1471 bool NextEndsTemplateExpr =
1472 Next->is(TT_TemplateString) &&
Next->TokenText.starts_with(
"}");
1473 if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
1474 (PreviousMustBeValue ||
1475 Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
1476 tok::minusminus))) {
1477 return addUnwrappedLine();
1479 if ((PreviousMustBeValue ||
Previous->is(tok::r_paren)) &&
1481 return addUnwrappedLine();
1485void UnwrappedLineParser::parseStructuralElement(
1486 const FormatToken *OpeningBrace, IfStmtKind *IfKind,
1487 FormatToken **IfLeftBrace,
bool *HasDoWhile,
bool *HasLabel) {
1488 if (Style.isTableGen() && FormatTok->is(tok::pp_include)) {
1490 if (FormatTok->is(tok::string_literal))
1497 while (FormatTok->is(tok::l_square) && handleCppAttributes()) {
1499 }
else if (Style.isVerilog()) {
1501 while (FormatTok->is(tok::l_paren) &&
1502 Tokens->peekNextToken()->is(tok::star)) {
1505 skipVerilogQualifiers();
1507 if (FormatTok->isOneOf(Keywords.kw_priority, Keywords.kw_unique,
1508 Keywords.kw_unique0)) {
1512 if (Keywords.isVerilogStructuredProcedure(*FormatTok)) {
1513 parseForOrWhileLoop(
false);
1516 if (FormatTok->isOneOf(Keywords.kw_foreach, Keywords.kw_repeat)) {
1517 parseForOrWhileLoop();
1520 if (FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
1521 Keywords.kw_assume, Keywords.kw_cover)) {
1522 parseIfThenElse(IfKind,
false,
true);
1528 if (FormatTok->isAccessSpecifierKeyword()) {
1529 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp())
1532 parseAccessSpecifier();
1535 switch (FormatTok->Tok.getKind()) {
1540 bool DoNotFormat =
false;
1545 FormatTok->isOneOf(tok::kw_volatile, tok::kw_inline, tok::kw_goto)) {
1550 if (FormatTok->is(tok::l_brace)) {
1551 FormatTok->setFinalizedType(TT_InlineASMBrace);
1552 OpenType = tok::l_brace;
1553 CloseType = tok::r_brace;
1555 }
else if (FormatTok->is(tok::l_paren)) {
1556 OpenType = tok::l_paren;
1557 CloseType = tok::r_paren;
1558 FormatTok->setFinalizedType(TT_InlineASMParen);
1566 while (FormatTok && !
eof()) {
1567 if (FormatTok->is(OpenType)) {
1569 }
else if (FormatTok->is(CloseType)) {
1571 if (NestLevel < 1) {
1572 FormatTok->setFinalizedType(OpenTok->getType());
1578 FormatTok->Finalized =
true;
1584 case tok::kw_namespace:
1588 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1599 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1603 parseForOrWhileLoop();
1606 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1614 case tok::kw_switch:
1615 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1621 case tok::kw_default: {
1623 if (Style.isVerilog())
1625 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1631 if (FormatTok->is(tok::colon)) {
1632 FormatTok->setFinalizedType(TT_CaseLabelColon);
1636 if (FormatTok->is(tok::arrow)) {
1637 FormatTok->setFinalizedType(TT_CaseLabelArrow);
1638 Default->setFinalizedType(TT_SwitchExpressionLabel);
1651 if (Style.isVerilog()) {
1656 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1665 if (FormatTok->is(tok::kw_case))
1670 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1676 case tok::kw_extern:
1677 if (Style.isVerilog()) {
1680 parseVerilogExtern();
1684 if (FormatTok->is(tok::string_literal)) {
1686 if (FormatTok->is(tok::l_brace)) {
1687 if (Style.BraceWrapping.AfterExternBlock)
1691 unsigned AddLevels =
1693 (Style.BraceWrapping.AfterExternBlock &&
1694 Style.IndentExternBlock ==
1698 parseBlock(
true, AddLevels);
1704 case tok::kw_export:
1707 if (FormatTok->is(tok::kw_namespace)) {
1711 if (FormatTok->is(tok::l_brace)) {
1712 parseCppExportBlock();
1715 if (FormatTok->is(Keywords.kw_module) && parseModuleDecl())
1717 if (FormatTok->is(Keywords.kw_import) && parseImportDecl())
1721 if (Style.isJavaScript()) {
1722 parseJavaScriptEs6ImportExport();
1725 if (Style.isVerilog()) {
1726 parseVerilogExtern();
1730 case tok::kw_inline:
1732 if (FormatTok->is(tok::kw_namespace)) {
1737 case tok::identifier:
1738 if (FormatTok->is(TT_ForEachMacro)) {
1739 parseForOrWhileLoop();
1742 if (FormatTok->is(TT_MacroBlockBegin)) {
1743 parseBlock(
false, 1u,
1747 if (FormatTok->is(Keywords.kw_import)) {
1748 if (IsCpp && parseImportDecl())
1750 if (Style.isJavaScript()) {
1751 parseJavaScriptEs6ImportExport();
1756 if (FormatTok->is(tok::kw_public))
1758 if (FormatTok->isNot(tok::string_literal))
1761 if (FormatTok->is(tok::semi))
1766 if (Style.isVerilog()) {
1767 parseVerilogExtern();
1772 if (FormatTok->is(Keywords.kw_module) && parseModuleDecl())
1774 if (FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
1775 Keywords.kw_slots, Keywords.kw_qslots)) {
1777 if (FormatTok->is(tok::colon)) {
1783 if (FormatTok->is(TT_StatementMacro)) {
1784 parseStatementMacro();
1787 if (FormatTok->is(TT_NamespaceMacro)) {
1796 if (!Style.isJavaScript() && !Style.isVerilog() && !Style.isTableGen() &&
1797 Tokens->peekNextToken()->is(tok::colon) && !
Line->MustBeDeclaration) {
1799 if (!
Line->InMacroBody || CurrentLines->size() > 1)
1800 Line->Tokens.begin()->Tok->MustBreakBefore =
true;
1801 FormatTok->setFinalizedType(TT_GotoLabelColon);
1807 if (Style.isJava() && FormatTok->is(Keywords.kw_record)) {
1808 parseRecord(
false,
true);
1818 bool SeenEqual =
false;
1819 for (
const bool InRequiresExpression =
1820 OpeningBrace && OpeningBrace->isOneOf(TT_RequiresExpressionLBrace,
1821 TT_CompoundRequirementLBrace);
1824 switch (FormatTok->Tok.getKind()) {
1827 if (FormatTok->is(tok::l_brace)) {
1832 if (Style.isJava() && FormatTok->is(Keywords.kw_interface)) {
1836 switch (
bool IsAutoRelease =
false; FormatTok->Tok.getObjCKeywordID()) {
1837 case tok::objc_public:
1838 case tok::objc_protected:
1839 case tok::objc_package:
1840 case tok::objc_private:
1841 return parseAccessSpecifier();
1842 case tok::objc_interface:
1843 case tok::objc_implementation:
1844 return parseObjCInterfaceOrImplementation();
1845 case tok::objc_protocol:
1846 if (parseObjCProtocol())
1851 case tok::objc_optional:
1852 case tok::objc_required:
1856 case tok::objc_autoreleasepool:
1857 IsAutoRelease =
true;
1859 case tok::objc_synchronized:
1861 if (!IsAutoRelease && FormatTok->is(tok::l_paren)) {
1865 if (FormatTok->is(tok::l_brace)) {
1866 if (Style.BraceWrapping.AfterControlStatement ==
1883 case tok::kw_requires: {
1885 bool ParsedClause = parseRequires(SeenEqual);
1906 if (!IsCpp && !Style.isVerilog()) {
1911 case tok::kw_typedef:
1913 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1914 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS,
1915 Keywords.kw_CF_CLOSED_ENUM,
1916 Keywords.kw_NS_CLOSED_ENUM)) {
1921 if (Style.isVerilog()) {
1926 if (Style.isTableGen()) {
1933 case tok::kw_struct:
1935 if (parseStructLike())
1938 case tok::kw_decltype:
1940 if (FormatTok->is(tok::l_paren)) {
1942 if (FormatTok->Previous &&
1943 FormatTok->Previous->endsSequence(tok::r_paren, tok::kw_auto,
1945 Line->SeenDecltypeAuto =
true;
1952 if (Style.isJava() && FormatTok && FormatTok->is(tok::kw_class))
1954 if (Style.isJavaScript() && FormatTok &&
1955 FormatTok->Tok.getIdentifierInfo()) {
1968 case tok::string_literal:
1969 if (Style.isVerilog() && FormatTok->is(TT_VerilogProtected)) {
1970 FormatTok->Finalized =
true;
1977 case tok::l_paren: {
1984 Tokens->peekNextToken(
true),
1991 case tok::kw_operator:
1993 if (FormatTok->isBinaryOperator())
1997 const auto *Prev = FormatTok->getPreviousNonComment();
1999 if (Prev && Prev->is(tok::identifier))
2002 if (FormatTok->Tok.isAnyIdentifier() || FormatTok->isTypeName(LangOpts)) {
2005 if (FormatTok->is(tok::less)) {
2007 parseBracedList(
true);
2010 while (FormatTok->is(tok::star))
2014 if (FormatTok->is(tok::l_paren))
2017 if (FormatTok->is(tok::l_brace))
2022 if (InRequiresExpression)
2023 FormatTok->setFinalizedType(TT_BracedListLBrace);
2024 if (!tryToParsePropertyAccessor() && !tryToParseBracedList()) {
2025 IsDecltypeAutoFunction =
Line->SeenDecltypeAuto;
2030 if (Style.isJava() &&
2031 Line->Tokens.front().Tok->is(Keywords.kw_synchronized)) {
2034 if (Style.BraceWrapping.AfterControlStatement ==
2038 }
else if (Style.BraceWrapping.AfterFunction) {
2042 FormatTok->setFinalizedType(TT_FunctionLBrace);
2044 IsDecltypeAutoFunction =
false;
2052 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
2058 if (Style.BraceWrapping.AfterFunction)
2062 case tok::identifier: {
2063 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where) &&
2064 Line->MustBeDeclaration) {
2066 parseCSharpGenericTypeConstraint();
2069 if (FormatTok->is(TT_MacroBlockEnd)) {
2078 size_t TokenCount =
Line->Tokens.size();
2079 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_function) &&
2082 Line->Tokens.front().Tok->isNot(Keywords.kw_async)))) {
2083 tryToParseJSFunction();
2086 if ((Style.isJavaScript() || Style.isJava()) &&
2087 FormatTok->is(Keywords.kw_interface)) {
2088 if (Style.isJavaScript()) {
2093 unsigned StoredPosition = Tokens->getPosition();
2095 FormatTok = Tokens->setPosition(StoredPosition);
2106 if (Style.isVerilog()) {
2107 if (FormatTok->is(Keywords.kw_table)) {
2108 parseVerilogTable();
2111 if (Keywords.isVerilogBegin(*FormatTok) ||
2112 Keywords.isVerilogHierarchy(*FormatTok)) {
2119 if (!IsCpp && FormatTok->is(Keywords.kw_interface)) {
2120 if (parseStructLike())
2125 if (IsCpp && FormatTok->is(TT_StatementMacro)) {
2126 parseStatementMacro();
2131 StringRef
Text = FormatTok->TokenText;
2138 if (Style.isJavaScript())
2141 auto OneTokenSoFar = [&]() {
2142 auto I =
Line->Tokens.begin(), E =
Line->Tokens.end();
2143 while (I != E && I->Tok->is(tok::comment))
2145 if (Style.isVerilog())
2146 while (I != E && I->Tok->is(tok::hash))
2148 return I != E && (++I == E);
2150 if (OneTokenSoFar()) {
2153 bool FunctionLike = FormatTok->is(tok::l_paren);
2157 bool FollowedByNewline =
2158 CommentsBeforeNextToken.empty()
2159 ? FormatTok->NewlinesBefore > 0
2160 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
2162 if (FollowedByNewline &&
2163 (
Text.size() >= 5 ||
2164 (FunctionLike && FormatTok->isNot(tok::l_paren))) &&
2166 if (PreviousToken->isNot(TT_UntouchableMacroFunc))
2167 PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro);
2175 if ((Style.isJavaScript() || Style.isCSharp()) &&
2176 FormatTok->is(TT_FatArrow)) {
2177 tryToParseChildBlock();
2183 if (FormatTok->is(tok::l_brace)) {
2187 if (!Style.isJavaScript())
2188 FormatTok->setBlockKind(BK_BracedInit);
2191 if (Style.isTableGen() &&
2192 Line->Tokens.begin()->Tok->is(Keywords.kw_defset)) {
2193 FormatTok->setFinalizedType(TT_FunctionLBrace);
2194 parseBlock(
false, 1u,
2202 FormatTok->is(tok::less)) {
2204 parseBracedList(
true);
2211 if (Style.isCSharp() &&
2212 (Tokens->peekNextToken()->isAccessSpecifierKeyword() ||
2219 case tok::kw_switch:
2232 if (Style.isVerilog()) {
2237 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
2244 case tok::kw_default:
2246 if (Style.isVerilog()) {
2247 if (FormatTok->is(tok::colon)) {
2251 if (FormatTok->is(Keywords.kw_clocking)) {
2257 parseVerilogCaseLabel();
2263 if (Style.isVerilog()) {
2264 parseVerilogCaseLabel();
2270 if (FormatTok->is(tok::l_brace))
2271 FormatTok->Previous->setFinalizedType(TT_TemplateCloser);
2280bool UnwrappedLineParser::tryToParsePropertyAccessor() {
2281 assert(FormatTok->is(tok::l_brace));
2282 if (!Style.isCSharp())
2285 if (!FormatTok->Previous || FormatTok->Previous->isNot(tok::identifier))
2293 unsigned int StoredPosition = Tokens->getPosition();
2299 bool HasSpecialAccessor =
false;
2300 bool IsTrivialPropertyAccessor =
true;
2303 if (
const bool IsAccessorKeyword =
2304 Tok->
isOneOf(Keywords.kw_get, Keywords.kw_init, Keywords.kw_set);
2305 IsAccessorKeyword ||
Tok->isAccessSpecifierKeyword() ||
2306 Tok->
isOneOf(tok::l_square, tok::semi, Keywords.kw_internal)) {
2307 if (IsAccessorKeyword)
2308 HasSpecialAccessor =
true;
2309 else if (
Tok->
is(tok::l_square))
2311 Tok = Tokens->getNextToken();
2315 IsTrivialPropertyAccessor =
false;
2320 Tokens->setPosition(StoredPosition);
2326 Tokens->setPosition(StoredPosition);
2327 if (!IsTrivialPropertyAccessor && Style.BraceWrapping.AfterFunction)
2331 switch (FormatTok->Tok.getKind()) {
2334 if (FormatTok->is(tok::equal)) {
2335 while (!
eof() && FormatTok->isNot(tok::semi))
2348 if (FormatTok->is(TT_FatArrow)) {
2352 }
while (!
eof() && FormatTok->isNot(tok::semi));
2361 if (FormatTok->isOneOf(Keywords.kw_get, Keywords.kw_init,
2363 !IsTrivialPropertyAccessor) {
2375bool UnwrappedLineParser::tryToParseLambda() {
2376 assert(FormatTok->is(tok::l_square));
2382 if (!tryToParseLambdaIntroducer())
2386 bool InTemplateParameterList =
false;
2388 while (FormatTok->isNot(tok::l_brace)) {
2389 if (FormatTok->isTypeName(LangOpts) || FormatTok->isAttribute()) {
2393 switch (FormatTok->Tok.getKind()) {
2397 parseParens(TT_PointerOrReference);
2403 assert(FormatTok->Previous);
2404 if (FormatTok->Previous->is(tok::r_square))
2405 InTemplateParameterList =
true;
2410 case tok::kw_struct:
2412 case tok::kw_template:
2413 case tok::kw_typename:
2417 case tok::kw_constexpr:
2418 case tok::kw_consteval:
2421 case tok::identifier:
2422 case tok::numeric_constant:
2423 case tok::coloncolon:
2424 case tok::kw_mutable:
2425 case tok::kw_noexcept:
2426 case tok::kw_static:
2451 case tok::equalequal:
2452 case tok::exclaimequal:
2453 case tok::greaterequal:
2454 case tok::lessequal:
2460 if (Arrow || InTemplateParameterList) {
2469 case tok::kw_requires:
2470 parseRequiresClause();
2473 if (!InTemplateParameterList)
2482 FormatTok->setFinalizedType(TT_LambdaLBrace);
2483 LSquare.setFinalizedType(TT_LambdaLSquare);
2486 Arrow->setFinalizedType(TT_LambdaArrow);
2488 NestedLambdas.push_back(
Line->SeenDecltypeAuto);
2490 assert(!NestedLambdas.empty());
2491 NestedLambdas.pop_back();
2496bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
2501 const auto *PrevPrev =
Previous->getPreviousNonComment();
2502 if (
Previous->is(tok::star) && PrevPrev && PrevPrev->isTypeName(LangOpts))
2510 if (!PrevPrev || PrevPrev->isNoneOf(tok::greater, tok::r_paren))
2514 Previous->isNoneOf(tok::kw_return, tok::kw_co_await, tok::kw_co_yield,
2515 tok::kw_co_return)) {
2519 if (LeftSquare->isCppStructuredBinding(IsCpp))
2521 if (FormatTok->is(tok::l_square) ||
tok::isLiteral(FormatTok->Tok.getKind()))
2523 if (FormatTok->is(tok::r_square)) {
2525 if (
Next->is(tok::greater))
2532void UnwrappedLineParser::tryToParseJSFunction() {
2533 assert(FormatTok->is(Keywords.kw_function));
2534 if (FormatTok->is(Keywords.kw_async))
2540 if (FormatTok->is(tok::star)) {
2541 FormatTok->setFinalizedType(TT_OverloadedOperator);
2546 if (FormatTok->is(tok::identifier))
2549 if (FormatTok->isNot(tok::l_paren))
2555 if (FormatTok->is(tok::colon)) {
2561 if (FormatTok->is(tok::l_brace))
2562 tryToParseBracedList();
2564 while (FormatTok->isNoneOf(tok::l_brace, tok::semi) && !
eof())
2568 if (FormatTok->is(tok::semi))
2574bool UnwrappedLineParser::tryToParseBracedList() {
2575 if (FormatTok->is(BK_Unknown))
2576 calculateBraceTypes();
2577 assert(FormatTok->isNot(BK_Unknown));
2578 if (FormatTok->is(BK_Block))
2585bool UnwrappedLineParser::tryToParseChildBlock() {
2586 assert(Style.isJavaScript() || Style.isCSharp());
2587 assert(FormatTok->is(TT_FatArrow));
2592 if (FormatTok->isNot(tok::l_brace))
2598bool UnwrappedLineParser::parseBracedList(
bool IsAngleBracket,
bool IsEnum) {
2599 assert(!IsAngleBracket || !IsEnum);
2600 bool HasError =
false;
2605 if (Style.isCSharp() && FormatTok->is(TT_FatArrow) &&
2606 tryToParseChildBlock()) {
2609 if (Style.isJavaScript()) {
2610 if (FormatTok->is(Keywords.kw_function)) {
2611 tryToParseJSFunction();
2614 if (FormatTok->is(tok::l_brace)) {
2616 if (tryToParseBracedList())
2621 if (FormatTok->is(IsAngleBracket ? tok::greater : tok::r_brace)) {
2623 FormatTok->setBlockKind(BK_Block);
2624 if (!Style.AllowShortEnumsOnASingleLine)
2630 switch (FormatTok->Tok.getKind()) {
2632 if (Style.isCSharp())
2641 if (Style.isJavaScript()) {
2642 if (FormatTok->is(tok::l_brace))
2650 FormatTok->setBlockKind(BK_BracedInit);
2651 if (!IsAngleBracket) {
2652 auto *Prev = FormatTok->Previous;
2653 if (Prev && Prev->is(tok::greater))
2654 Prev->setFinalizedType(TT_TemplateCloser);
2662 parseBracedList(
true);
2669 if (Style.isJavaScript()) {
2680 if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
2683 case tok::kw_requires:
2684 parseRequiresExpression();
2701bool UnwrappedLineParser::parseParens(TokenType StarAndAmpTokenType,
2703 assert(FormatTok->is(tok::l_paren) &&
"'(' expected.");
2704 auto *LParen = FormatTok;
2705 auto *Prev = FormatTok->Previous;
2706 bool SeenComma =
false;
2707 bool SeenEqual =
false;
2708 bool MightBeFoldExpr =
false;
2709 unsigned ExcessLess = 0;
2711 const bool MightBeStmtExpr = FormatTok->is(tok::l_brace);
2712 if (!InMacroCall && Prev && Prev->is(TT_FunctionLikeMacro))
2715 switch (FormatTok->Tok.getKind()) {
2717 if (parseParens(ExcessLess == 0 ? StarAndAmpTokenType : TT_Unknown,
2721 if (Style.isJava() && FormatTok->is(tok::l_brace))
2724 case tok::r_paren: {
2725 auto *RParen = FormatTok;
2728 auto OptionalParens = [&] {
2730 MightBeStmtExpr || MightBeFoldExpr || SeenComma || InMacroCall ||
2731 Line->InMacroBody || RParen->getPreviousNonComment() == LParen) {
2734 const bool DoubleParens =
2735 Prev->is(tok::l_paren) && FormatTok->is(tok::r_paren);
2737 const auto *PrevPrev = Prev->getPreviousNonComment();
2738 const bool Excluded =
2740 (PrevPrev->isOneOf(tok::kw___attribute, tok::kw_decltype) ||
2742 (PrevPrev->isOneOf(tok::kw_if, tok::kw_while) ||
2743 PrevPrev->endsSequence(tok::kw_constexpr, tok::kw_if))));
2747 const bool CommaSeparated =
2748 Prev->isOneOf(tok::l_paren, tok::comma) &&
2749 FormatTok->isOneOf(tok::comma, tok::r_paren);
2750 if (CommaSeparated &&
2752 !Prev->endsSequence(tok::comma, tok::ellipsis) &&
2754 !(FormatTok->is(tok::comma) &&
2755 Tokens->peekNextToken()->is(tok::ellipsis))) {
2758 const bool ReturnParens =
2760 ((NestedLambdas.empty() && !IsDecltypeAutoFunction) ||
2761 (!NestedLambdas.empty() && !NestedLambdas.back())) &&
2762 Prev->isOneOf(tok::kw_return, tok::kw_co_return) &&
2763 FormatTok->is(tok::semi);
2769 if (OptionalParens()) {
2770 LParen->Optional =
true;
2771 RParen->Optional =
true;
2772 }
else if (Prev->is(TT_TypenameMacro)) {
2773 LParen->setFinalizedType(TT_TypeDeclarationParen);
2774 RParen->setFinalizedType(TT_TypeDeclarationParen);
2775 }
else if (Prev->is(tok::greater) && RParen->Previous == LParen) {
2776 Prev->setFinalizedType(TT_TemplateCloser);
2777 }
else if (FormatTok->is(tok::l_brace) && Prev->is(tok::amp) &&
2779 FormatTok->setBlockKind(BK_BracedInit);
2791 if (!tryToParseBracedList())
2796 if (FormatTok->is(tok::l_brace)) {
2806 MightBeFoldExpr =
true;
2811 if (Style.isCSharp() && FormatTok->is(TT_FatArrow))
2812 tryToParseChildBlock();
2817 if (Style.isJavaScript())
2822 case tok::identifier:
2823 if (Style.isJavaScript() && (FormatTok->is(Keywords.kw_function)))
2824 tryToParseJSFunction();
2828 case tok::kw_switch:
2834 case tok::kw_requires:
2835 parseRequiresExpression();
2851 if (StarAndAmpTokenType != TT_Unknown && ExcessLess == 0)
2852 FormatTok->setFinalizedType(StarAndAmpTokenType);
2864 assert(FormatTok->is(tok::l_square) &&
"'[' expected.");
2865 if (tryToParseLambda())
2869 switch (FormatTok->Tok.getKind()) {
2882 case tok::l_brace: {
2883 if (!tryToParseBracedList())
2890 if (FormatTok->is(tok::l_brace)) {
2902void UnwrappedLineParser::keepAncestorBraces() {
2903 if (!Style.RemoveBracesLLVM)
2906 const int MaxNestingLevels = 2;
2907 const int Size = NestedTooDeep.size();
2908 if (Size >= MaxNestingLevels)
2909 NestedTooDeep[
Size - MaxNestingLevels] =
true;
2910 NestedTooDeep.push_back(
false);
2914 for (
const auto &
Token : llvm::reverse(
Line.Tokens))
2921void UnwrappedLineParser::parseUnbracedBody(
bool CheckEOF) {
2924 if (Style.InsertBraces && !
Line->InPPDirective && !
Line->Tokens.empty() &&
2925 PreprocessorDirectives.empty() && FormatTok->isNot(tok::semi)) {
2927 ? getLastNonComment(*
Line)
2930 if (
Tok->BraceCount < 0) {
2931 assert(
Tok->BraceCount == -1);
2934 Tok->BraceCount = -1;
2939 const auto BodyStart = CurrentLines->size();
2941 ++
Line->UnbracedBodyLevel;
2942 parseStructuralElement();
2943 --
Line->UnbracedBodyLevel;
2946 assert(!
Line->InPPDirective);
2949 auto BodyEnd = CurrentLines->size();
2950 while (BodyEnd > 0) {
2951 const auto &L = (*CurrentLines)[--BodyEnd];
2953 Tok = L.Tokens.back().Tok;
2959 bool EnclosesPPDirective =
false;
2960 for (
size_t I = BodyStart; I <= BodyEnd && !EnclosesPPDirective; ++I) {
2961 const auto &BodyLine = (*CurrentLines)[I];
2962 EnclosesPPDirective =
2963 BodyLine.InPPDirective ||
2964 llvm::any_of(BodyLine.Tokens, [](
const UnwrappedLineNode &Node) {
2965 return Node.Tok->FirstAfterPPLine;
2968 if (EnclosesPPDirective)
2969 LBraceTok->BraceCount = 0;
2974 if (CheckEOF &&
eof())
2984 assert(LeftBrace->
is(tok::l_brace));
2992 assert(RightBrace->
is(tok::r_brace));
3000void UnwrappedLineParser::handleAttributes() {
3002 if (FormatTok->isAttribute())
3004 else if (FormatTok->is(tok::l_square))
3005 handleCppAttributes();
3008bool UnwrappedLineParser::handleCppAttributes() {
3010 assert(FormatTok->is(tok::l_square));
3011 if (!tryToParseSimpleAttribute())
3018bool UnwrappedLineParser::isBlockBegin(
const FormatToken &
Tok)
const {
3021 return Style.isVerilog() ? Keywords.isVerilogBegin(
Tok)
3022 :
Tok.
is(tok::l_brace);
3025FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
3027 bool IsVerilogAssert) {
3028 assert((FormatTok->is(tok::kw_if) ||
3029 (Style.isVerilog() &&
3030 FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
3031 Keywords.kw_assume, Keywords.kw_cover))) &&
3035 if (IsVerilogAssert) {
3037 if (FormatTok->is(Keywords.kw_verilogHash)) {
3039 if (FormatTok->is(tok::numeric_constant))
3041 }
else if (FormatTok->isOneOf(Keywords.kw_final, Keywords.kw_property,
3042 Keywords.kw_sequence)) {
3048 if (Style.isTableGen()) {
3049 while (!
eof() && FormatTok->isNot(Keywords.kw_then)) {
3056 if (FormatTok->is(tok::exclaim))
3059 bool KeepIfBraces =
true;
3060 if (FormatTok->is(tok::kw_consteval)) {
3063 KeepIfBraces = !Style.RemoveBracesLLVM || KeepBraces;
3064 if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
3066 if (FormatTok->is(tok::l_paren)) {
3067 FormatTok->setFinalizedType(TT_ConditionLParen);
3073 if (IsVerilogAssert && FormatTok->is(tok::semi)) {
3079 bool NeedsUnwrappedLine =
false;
3080 keepAncestorBraces();
3083 IfStmtKind IfBlockKind = IfStmtKind::NotIf;
3085 if (isBlockBegin(*FormatTok)) {
3086 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3087 IfLeftBrace = FormatTok;
3088 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3089 parseBlock(
false, 1u,
3090 true, KeepIfBraces, &IfBlockKind);
3091 setPreviousRBraceType(TT_ControlStatementRBrace);
3092 if (Style.BraceWrapping.BeforeElse)
3095 NeedsUnwrappedLine =
true;
3096 }
else if (IsVerilogAssert && FormatTok->is(tok::kw_else)) {
3099 parseUnbracedBody();
3102 if (Style.RemoveBracesLLVM) {
3103 assert(!NestedTooDeep.empty());
3104 KeepIfBraces = KeepIfBraces ||
3105 (IfLeftBrace && !IfLeftBrace->MatchingParen) ||
3106 NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly ||
3107 IfBlockKind == IfStmtKind::IfElseIf;
3110 bool KeepElseBraces = KeepIfBraces;
3112 IfStmtKind
Kind = IfStmtKind::IfOnly;
3114 if (FormatTok->is(tok::kw_else)) {
3115 if (Style.RemoveBracesLLVM) {
3116 NestedTooDeep.back() =
false;
3117 Kind = IfStmtKind::IfElse;
3121 if (isBlockBegin(*FormatTok)) {
3122 const bool FollowedByIf = Tokens->peekNextToken()->is(tok::kw_if);
3123 FormatTok->setFinalizedType(TT_ElseLBrace);
3124 ElseLeftBrace = FormatTok;
3125 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3126 IfStmtKind ElseBlockKind = IfStmtKind::NotIf;
3128 parseBlock(
false, 1u,
3129 true, KeepElseBraces, &ElseBlockKind);
3130 setPreviousRBraceType(TT_ElseRBrace);
3131 if (FormatTok->is(tok::kw_else)) {
3132 KeepElseBraces = KeepElseBraces ||
3133 ElseBlockKind == IfStmtKind::IfOnly ||
3134 ElseBlockKind == IfStmtKind::IfElseIf;
3135 }
else if (FollowedByIf && IfLBrace && !IfLBrace->Optional) {
3136 KeepElseBraces =
true;
3137 assert(ElseLeftBrace->MatchingParen);
3141 }
else if (!IsVerilogAssert && FormatTok->is(tok::kw_if)) {
3144 const bool IsPrecededByComment =
Previous->is(tok::comment);
3145 if (IsPrecededByComment) {
3149 bool TooDeep =
true;
3150 if (Style.RemoveBracesLLVM) {
3151 Kind = IfStmtKind::IfElseIf;
3152 TooDeep = NestedTooDeep.pop_back_val();
3154 ElseLeftBrace = parseIfThenElse(
nullptr, KeepIfBraces);
3155 if (Style.RemoveBracesLLVM)
3156 NestedTooDeep.push_back(TooDeep);
3157 if (IsPrecededByComment)
3160 parseUnbracedBody(
true);
3163 KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse;
3164 if (NeedsUnwrappedLine)
3168 if (!Style.RemoveBracesLLVM)
3171 assert(!NestedTooDeep.empty());
3172 KeepElseBraces = KeepElseBraces ||
3173 (ElseLeftBrace && !ElseLeftBrace->MatchingParen) ||
3174 NestedTooDeep.back();
3176 NestedTooDeep.pop_back();
3178 if (!KeepIfBraces && !KeepElseBraces) {
3181 }
else if (IfLeftBrace) {
3182 FormatToken *IfRightBrace = IfLeftBrace->MatchingParen;
3184 assert(IfRightBrace->MatchingParen == IfLeftBrace);
3185 assert(!IfLeftBrace->Optional);
3186 assert(!IfRightBrace->Optional);
3187 IfLeftBrace->MatchingParen =
nullptr;
3188 IfRightBrace->MatchingParen =
nullptr;
3198void UnwrappedLineParser::parseTryCatch() {
3199 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) &&
"'try' expected");
3201 bool NeedsUnwrappedLine =
false;
3202 bool HasCtorInitializer =
false;
3203 if (FormatTok->is(tok::colon)) {
3204 auto *Colon = FormatTok;
3207 if (FormatTok->is(tok::identifier)) {
3208 HasCtorInitializer =
true;
3209 Colon->setFinalizedType(TT_CtorInitializerColon);
3214 while (FormatTok->is(tok::comma))
3217 while (FormatTok->is(tok::identifier)) {
3219 if (FormatTok->is(tok::l_paren)) {
3221 }
else if (FormatTok->is(tok::l_brace)) {
3228 while (FormatTok->is(tok::comma))
3233 if (Style.isJava() && FormatTok->is(tok::l_paren))
3236 keepAncestorBraces();
3238 if (FormatTok->is(tok::l_brace)) {
3239 if (HasCtorInitializer)
3240 FormatTok->setFinalizedType(TT_FunctionLBrace);
3241 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3243 if (Style.BraceWrapping.BeforeCatch)
3246 NeedsUnwrappedLine =
true;
3247 }
else if (FormatTok->isNot(tok::kw_catch)) {
3253 parseStructuralElement();
3256 for (
bool SeenCatch =
false;;) {
3257 if (FormatTok->is(tok::at))
3259 if (FormatTok->isNoneOf(tok::kw_catch, Keywords.kw___except,
3260 tok::kw___finally, tok::objc_catch,
3261 tok::objc_finally) &&
3262 !((Style.isJava() || Style.isJavaScript()) &&
3263 FormatTok->is(Keywords.kw_finally))) {
3266 if (FormatTok->is(tok::kw_catch))
3269 while (FormatTok->isNot(tok::l_brace)) {
3270 if (FormatTok->is(tok::l_paren)) {
3274 if (FormatTok->isOneOf(tok::semi, tok::r_brace) ||
eof()) {
3275 if (Style.RemoveBracesLLVM)
3276 NestedTooDeep.pop_back();
3282 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3285 NeedsUnwrappedLine =
false;
3286 Line->MustBeDeclaration =
false;
3287 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3289 if (Style.BraceWrapping.BeforeCatch)
3292 NeedsUnwrappedLine =
true;
3295 if (Style.RemoveBracesLLVM)
3296 NestedTooDeep.pop_back();
3298 if (NeedsUnwrappedLine)
3302void UnwrappedLineParser::parseNamespaceOrExportBlock(
unsigned AddLevels) {
3303 bool ManageWhitesmithsBraces =
3308 if (ManageWhitesmithsBraces)
3313 parseBlock(
true, AddLevels,
true,
3314 true,
nullptr, ManageWhitesmithsBraces);
3316 addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep);
3318 if (ManageWhitesmithsBraces)
3322void UnwrappedLineParser::parseNamespace() {
3323 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
3324 "'namespace' expected");
3328 if (InitialToken.is(TT_NamespaceMacro)) {
3331 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
3332 tok::l_square, tok::period, tok::l_paren) ||
3333 (Style.isCSharp() && FormatTok->is(tok::kw_union))) {
3334 if (FormatTok->is(tok::l_square))
3336 else if (FormatTok->is(tok::l_paren))
3342 if (FormatTok->is(tok::l_brace)) {
3343 FormatTok->setFinalizedType(TT_NamespaceLBrace);
3346 Tokens->peekNextToken()->is(tok::r_brace))) {
3350 unsigned AddLevels =
3353 DeclarationScopeStack.size() > 1)
3356 parseNamespaceOrExportBlock(AddLevels);
3361void UnwrappedLineParser::parseCppExportBlock() {
3362 if (FormatTok->is(tok::l_brace)) {
3363 FormatTok->setFinalizedType(TT_ExportLBrace);
3364 if (Style.BraceWrapping.AfterExportBlock)
3367 parseNamespaceOrExportBlock(Style.IndentExportBlock ? 1 : 0);
3370void UnwrappedLineParser::parseNew() {
3371 assert(FormatTok->is(tok::kw_new) &&
"'new' expected");
3374 if (Style.isCSharp()) {
3377 if (FormatTok->is(tok::l_paren))
3381 if (FormatTok->is(tok::l_brace))
3384 if (FormatTok->isOneOf(tok::semi, tok::comma))
3391 if (!Style.isJava())
3397 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
3401 if (FormatTok->is(tok::l_paren)) {
3405 if (FormatTok->is(tok::l_brace))
3413void UnwrappedLineParser::parseLoopBody(
bool KeepBraces,
bool WrapRightBrace) {
3414 keepAncestorBraces();
3416 if (isBlockBegin(*FormatTok)) {
3417 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3419 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3420 parseBlock(
false, 1u,
3422 setPreviousRBraceType(TT_ControlStatementRBrace);
3424 assert(!NestedTooDeep.empty());
3425 if (!NestedTooDeep.back())
3431 parseUnbracedBody();
3435 NestedTooDeep.pop_back();
3438void UnwrappedLineParser::parseForOrWhileLoop(
bool HasParens) {
3439 assert((FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) ||
3440 (Style.isVerilog() &&
3441 FormatTok->isOneOf(Keywords.kw_always, Keywords.kw_always_comb,
3442 Keywords.kw_always_ff, Keywords.kw_always_latch,
3443 Keywords.kw_final, Keywords.kw_initial,
3444 Keywords.kw_foreach, Keywords.kw_forever,
3445 Keywords.kw_repeat))) &&
3446 "'for', 'while' or foreach macro expected");
3447 const bool KeepBraces = !Style.RemoveBracesLLVM ||
3448 FormatTok->isNoneOf(tok::kw_for, tok::kw_while);
3452 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
3454 if (IsCpp && FormatTok->is(tok::kw_co_await))
3456 if (HasParens && FormatTok->is(tok::l_paren)) {
3460 if (Style.isVerilog())
3461 FormatTok->setFinalizedType(TT_ConditionLParen);
3465 if (Style.isVerilog()) {
3467 parseVerilogSensitivityList();
3468 }
else if (Style.AllowShortLoopsOnASingleLine && FormatTok->is(tok::semi) &&
3469 Tokens->getPreviousToken()->is(tok::r_paren)) {
3476 parseLoopBody(KeepBraces,
true);
3479void UnwrappedLineParser::parseDoWhile() {
3480 assert(FormatTok->is(tok::kw_do) &&
"'do' expected");
3483 parseLoopBody(
true, Style.BraceWrapping.BeforeWhile);
3486 if (FormatTok->isNot(tok::kw_while)) {
3491 FormatTok->setFinalizedType(TT_DoWhile);
3499 parseStructuralElement();
3502void UnwrappedLineParser::parseLabel(
bool IsGotoLabel) {
3505 const auto IndentGotoLabel = Style.IndentGotoLabels;
3506 const auto OldLineLevel =
Line->Level;
3513 if (OldLineLevel > 1 || (!
Line->InPPDirective && OldLineLevel > 0))
3517 if (!IsGotoLabel && !Style.IndentCaseBlocks &&
3518 CommentsBeforeNextToken.empty() && FormatTok->is(tok::l_brace)) {
3519 CompoundStatementIndenter Indenter(
this,
Level,
3520 Style.BraceWrapping.AfterCaseLabel,
3521 Style.BraceWrapping.IndentBraces);
3523 if (FormatTok->is(tok::kw_break)) {
3524 if (Style.BraceWrapping.AfterControlStatement ==
3527 if (!Style.IndentCaseBlocks &&
3532 parseStructuralElement();
3536 if (FormatTok->is(tok::semi))
3541 Level = OldLineLevel;
3543 if (FormatTok->isNot(tok::l_brace)) {
3544 parseStructuralElement();
3549void UnwrappedLineParser::parseCaseLabel() {
3550 assert(FormatTok->is(tok::kw_case) &&
"'case' expected");
3551 auto *Case = FormatTok;
3556 if (FormatTok->is(tok::colon)) {
3557 FormatTok->setFinalizedType(TT_CaseLabelColon);
3560 if (Style.isJava() && FormatTok->is(tok::arrow)) {
3561 FormatTok->setFinalizedType(TT_CaseLabelArrow);
3562 Case->setFinalizedType(TT_SwitchExpressionLabel);
3569void UnwrappedLineParser::parseSwitch(
bool IsExpr) {
3570 assert(FormatTok->is(tok::kw_switch) &&
"'switch' expected");
3572 if (FormatTok->is(tok::l_paren))
3575 keepAncestorBraces();
3577 if (FormatTok->is(tok::l_brace)) {
3578 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3579 FormatTok->setFinalizedType(IsExpr ? TT_SwitchExpressionLBrace
3580 : TT_ControlStatementLBrace);
3585 setPreviousRBraceType(TT_ControlStatementRBrace);
3591 parseStructuralElement();
3595 if (Style.RemoveBracesLLVM)
3596 NestedTooDeep.pop_back();
3599void UnwrappedLineParser::parseAccessSpecifier() {
3602 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
3605 if (FormatTok->is(tok::colon))
3613bool UnwrappedLineParser::parseRequires(
bool SeenEqual) {
3614 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3618 switch (Tokens->peekNextToken(
true)->Tok.getKind()) {
3621 parseRequiresExpression();
3628 parseRequiresClause();
3639 auto *PreviousNonComment = FormatTok->getPreviousNonComment();
3641 if (!PreviousNonComment ||
3642 PreviousNonComment->is(TT_RequiresExpressionLBrace)) {
3645 parseRequiresClause();
3649 switch (PreviousNonComment->Tok.getKind()) {
3652 case tok::kw_noexcept:
3657 parseRequiresClause();
3666 auto PrevPrev = PreviousNonComment->getPreviousNonComment();
3667 if ((PrevPrev && PrevPrev->is(tok::kw_const)) || !SeenEqual) {
3668 parseRequiresClause();
3674 if (PreviousNonComment->isTypeOrIdentifier(LangOpts)) {
3676 parseRequiresClause();
3680 parseRequiresExpression();
3690 unsigned StoredPosition = Tokens->getPosition();
3693 auto PeekNext = [&Lookahead, &NextToken,
this] {
3695 NextToken = Tokens->getNextToken();
3698 bool FoundType =
false;
3699 bool LastWasColonColon =
false;
3702 for (; Lookahead < 50; PeekNext()) {
3703 switch (NextToken->Tok.getKind()) {
3704 case tok::kw_volatile:
3707 if (OpenAngles == 0) {
3708 FormatTok = Tokens->setPosition(StoredPosition);
3709 parseRequiresExpression();
3717 case tok::coloncolon:
3718 LastWasColonColon =
true;
3720 case tok::kw_decltype:
3721 case tok::identifier:
3722 if (FoundType && !LastWasColonColon && OpenAngles == 0) {
3723 FormatTok = Tokens->setPosition(StoredPosition);
3724 parseRequiresExpression();
3728 LastWasColonColon =
false;
3737 if (NextToken->isTypeName(LangOpts)) {
3738 FormatTok = Tokens->setPosition(StoredPosition);
3739 parseRequiresExpression();
3746 FormatTok = Tokens->setPosition(StoredPosition);
3747 parseRequiresClause();
3756void UnwrappedLineParser::parseRequiresClause() {
3757 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3762 bool InRequiresExpression =
3763 !FormatTok->Previous ||
3764 FormatTok->Previous->is(TT_RequiresExpressionLBrace);
3766 FormatTok->setFinalizedType(InRequiresExpression
3767 ? TT_RequiresClauseInARequiresExpression
3768 : TT_RequiresClause);
3773 parseConstraintExpression();
3775 if (!InRequiresExpression && FormatTok->Previous)
3776 FormatTok->Previous->ClosesRequiresClause =
true;
3784void UnwrappedLineParser::parseRequiresExpression() {
3785 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3787 FormatTok->setFinalizedType(TT_RequiresExpression);
3790 if (FormatTok->is(tok::l_paren)) {
3791 FormatTok->setFinalizedType(TT_RequiresExpressionLParen);
3795 if (FormatTok->is(tok::l_brace)) {
3796 FormatTok->setFinalizedType(TT_RequiresExpressionLBrace);
3805void UnwrappedLineParser::parseConstraintExpression() {
3812 bool LambdaNextTimeAllowed =
true;
3822 bool TopLevelParensAllowed =
true;
3825 bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed,
false);
3827 switch (FormatTok->Tok.getKind()) {
3828 case tok::kw_requires:
3829 parseRequiresExpression();
3833 if (!TopLevelParensAllowed)
3835 parseParens(TT_BinaryOperator);
3836 TopLevelParensAllowed =
false;
3840 if (!LambdaThisTimeAllowed || !tryToParseLambda())
3847 case tok::kw_struct:
3857 FormatTok->setFinalizedType(TT_BinaryOperator);
3859 LambdaNextTimeAllowed =
true;
3860 TopLevelParensAllowed =
true;
3865 LambdaNextTimeAllowed = LambdaThisTimeAllowed;
3869 case tok::kw_sizeof:
3871 case tok::greaterequal:
3872 case tok::greatergreater:
3874 case tok::lessequal:
3876 case tok::equalequal:
3878 case tok::exclaimequal:
3883 LambdaNextTimeAllowed =
true;
3884 TopLevelParensAllowed =
true;
3889 case tok::numeric_constant:
3890 case tok::coloncolon:
3893 TopLevelParensAllowed =
false;
3898 case tok::kw_static_cast:
3899 case tok::kw_const_cast:
3900 case tok::kw_reinterpret_cast:
3901 case tok::kw_dynamic_cast:
3903 if (FormatTok->isNot(tok::less))
3907 parseBracedList(
true);
3911 if (!FormatTok->Tok.getIdentifierInfo()) {
3921 assert(FormatTok->Previous);
3922 switch (FormatTok->Previous->Tok.getKind()) {
3923 case tok::coloncolon:
3927 case tok::kw_requires:
3929 case tok::kw_template:
3937 if (FormatTok->is(tok::less)) {
3939 parseBracedList(
true);
3941 TopLevelParensAllowed =
false;
3947bool UnwrappedLineParser::parseEnum() {
3951 if (FormatTok->is(tok::kw_enum))
3957 if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question))
3966 if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
3968 while (FormatTok->is(tok::l_square))
3969 if (!handleCppAttributes())
3973 while (FormatTok->Tok.getIdentifierInfo() ||
3974 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
3975 tok::greater, tok::comma, tok::question,
3977 if (FormatTok->is(tok::colon))
3978 FormatTok->setFinalizedType(TT_EnumUnderlyingTypeColon);
3979 if (Style.isVerilog()) {
3980 FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
3983 while (FormatTok->is(tok::l_square))
3989 if (FormatTok->is(tok::l_paren))
3991 if (FormatTok->is(tok::identifier)) {
3995 if (IsCpp && FormatTok->is(tok::identifier))
4001 if (FormatTok->isNot(tok::l_brace))
4003 FormatTok->setFinalizedType(TT_EnumLBrace);
4004 FormatTok->setBlockKind(BK_Block);
4006 if (Style.isJava()) {
4008 parseJavaEnumBody();
4016 const bool ManageWhitesmithsBraces =
4019 if (!Style.AllowShortEnumsOnASingleLine &&
4021 Tokens->peekNextToken()->is(tok::r_brace))) {
4026 if (ManageWhitesmithsBraces)
4031 if (!Style.AllowShortEnumsOnASingleLine) {
4033 if (!ManageWhitesmithsBraces)
4036 const auto OpeningLineIndex = CurrentLines->empty()
4037 ? UnwrappedLine::kInvalidIndex
4038 : CurrentLines->size() - 1;
4039 bool HasError = !parseBracedList(
false,
true);
4040 if (!Style.AllowShortEnumsOnASingleLine && !ManageWhitesmithsBraces)
4043 if (FormatTok->is(tok::semi))
4047 setPreviousRBraceType(TT_EnumRBrace);
4048 if (ManageWhitesmithsBraces)
4049 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
4057bool UnwrappedLineParser::parseStructLike() {
4062 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp()) {
4063 if (FormatTok->is(tok::semi))
4074class ScopedTokenPosition {
4075 unsigned StoredPosition;
4076 FormatTokenSource *Tokens;
4079 ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) {
4080 assert(Tokens &&
"Tokens expected to not be null");
4081 StoredPosition = Tokens->getPosition();
4084 ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); }
4090bool UnwrappedLineParser::tryToParseSimpleAttribute() {
4091 ScopedTokenPosition AutoPosition(Tokens);
4099 if (
Tok->
is(tok::r_square))
4101 Tok = Tokens->getNextToken();
4103 if (
Tok->
is(tok::eof))
4105 Tok = Tokens->getNextToken();
4108 Tok = Tokens->getNextToken();
4109 if (
Tok->
is(tok::semi))
4114void UnwrappedLineParser::parseJavaEnumBody() {
4115 assert(FormatTok->is(tok::l_brace));
4121 unsigned StoredPosition = Tokens->getPosition();
4122 bool IsSimple =
true;
4125 if (
Tok->
is(tok::r_brace))
4133 Tok = Tokens->getNextToken();
4135 FormatTok = Tokens->setPosition(StoredPosition);
4152 if (FormatTok->is(tok::l_brace)) {
4154 parseBlock(
true, 1u,
4156 }
else if (FormatTok->is(tok::l_paren)) {
4158 }
else if (FormatTok->is(tok::comma)) {
4161 }
else if (FormatTok->is(tok::semi)) {
4165 }
else if (FormatTok->is(tok::r_brace)) {
4174 parseLevel(OpeningBrace);
4180void UnwrappedLineParser::parseRecord(
bool ParseAsExpr,
bool IsJavaRecord) {
4181 assert(!IsJavaRecord || FormatTok->is(Keywords.kw_record));
4186 IsJavaRecord && FormatTok->is(tok::identifier) ? FormatTok :
nullptr;
4187 bool IsDerived =
false;
4189 return Tok->
is(tok::identifier) &&
Tok->TokenText !=
Tok->TokenText.upper();
4193 bool JSPastExtendsOrImplements =
false;
4197 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
4198 tok::kw_alignas, tok::l_square) ||
4199 FormatTok->isAttribute() ||
4200 ((Style.isJava() || Style.isJavaScript()) &&
4201 FormatTok->isOneOf(tok::period, tok::comma)) ||
4202 (Style.isVerilog() &&
4203 FormatTok->isOneOf(tok::kw_signed, tok::kw_unsigned))) {
4204 if (Style.isJavaScript() &&
4205 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
4206 JSPastExtendsOrImplements =
true;
4211 if (FormatTok->is(tok::l_brace)) {
4212 tryToParseBracedList();
4216 if (FormatTok->is(tok::l_square) && handleCppAttributes())
4220 switch (FormatTok->Tok.getKind()) {
4223 if (IsJavaRecord || !IsNonMacroIdentifier(
Previous) ||
4225 Previous->Previous == &InitialToken) {
4229 case tok::coloncolon:
4233 if (JSPastExtendsOrImplements || ClassName ||
4244 auto IsListInitialization = [&] {
4245 if (!ClassName || IsDerived || JSPastExtendsOrImplements)
4247 assert(FormatTok->is(tok::l_brace));
4248 const auto *Prev = FormatTok->getPreviousNonComment();
4250 return Prev != ClassName && Prev->is(tok::identifier) &&
4251 Prev->isNot(Keywords.kw_final) && tryToParseBracedList();
4254 if (FormatTok->isOneOf(tok::colon, tok::less)) {
4255 int AngleNestingLevel = 0;
4257 if (FormatTok->is(tok::less))
4258 ++AngleNestingLevel;
4259 else if (FormatTok->is(tok::greater))
4260 --AngleNestingLevel;
4262 if (AngleNestingLevel == 0) {
4263 if (FormatTok->is(tok::colon)) {
4265 }
else if (!IsDerived && FormatTok->is(tok::identifier) &&
4266 FormatTok->Previous->is(tok::coloncolon)) {
4267 ClassName = FormatTok;
4268 }
else if (FormatTok->is(tok::l_paren) &&
4269 IsNonMacroIdentifier(FormatTok->Previous)) {
4273 if (FormatTok->is(tok::l_brace)) {
4274 if (AngleNestingLevel == 0 && IsListInitialization())
4276 calculateBraceTypes(
true);
4277 if (!tryToParseBracedList())
4280 if (FormatTok->is(tok::l_square)) {
4283 !
Previous->isTypeOrIdentifier(LangOpts))) {
4286 if (!tryToParseLambda())
4293 if (FormatTok->is(tok::semi))
4295 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
4298 parseCSharpGenericTypeConstraint();
4305 auto GetBraceTypes =
4306 [](
const FormatToken &RecordTok) -> std::pair<TokenType, TokenType> {
4307 switch (RecordTok.Tok.getKind()) {
4309 return {TT_ClassLBrace, TT_ClassRBrace};
4310 case tok::kw_struct:
4311 return {TT_StructLBrace, TT_StructRBrace};
4313 return {TT_UnionLBrace, TT_UnionRBrace};
4316 return {TT_RecordLBrace, TT_RecordRBrace};
4319 if (FormatTok->is(tok::l_brace)) {
4320 if (IsListInitialization())
4323 ClassName->setFinalizedType(TT_ClassHeadName);
4324 auto [OpenBraceType, ClosingBraceType] = GetBraceTypes(InitialToken);
4325 FormatTok->setFinalizedType(OpenBraceType);
4330 Tokens->peekNextToken()->is(tok::r_brace),
4335 bool IndentAfterExplicitAccessModifier =
false;
4336 unsigned AddLevels = 1u;
4337 switch (Style.IndentAccessModifiers) {
4341 if (Style.isCpp()) {
4342 IndentAfterExplicitAccessModifier =
true;
4351 parseBlock(
true, AddLevels,
false,
4354 IndentAfterExplicitAccessModifier);
4356 setPreviousRBraceType(ClosingBraceType);
4363void UnwrappedLineParser::parseObjCMethod() {
4364 assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) &&
4365 "'(' or identifier expected.");
4367 if (FormatTok->is(tok::semi)) {
4371 }
else if (FormatTok->is(tok::l_brace)) {
4372 if (Style.BraceWrapping.AfterFunction)
4383void UnwrappedLineParser::parseObjCProtocolList() {
4384 assert(FormatTok->is(tok::less) &&
"'<' expected.");
4388 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4390 }
while (!
eof() && FormatTok->isNot(tok::greater));
4394void UnwrappedLineParser::parseObjCUntilAtEnd() {
4396 if (FormatTok->is(tok::objc_end)) {
4401 if (FormatTok->is(tok::l_brace)) {
4405 }
else if (FormatTok->is(tok::r_brace)) {
4409 }
else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
4411 if (FormatTok->isOneOf(tok::l_paren, tok::identifier))
4414 parseStructuralElement();
4419void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
4420 assert(FormatTok->isOneOf(tok::objc_interface, tok::objc_implementation));
4426 if (FormatTok->is(tok::less))
4427 parseObjCLightweightGenerics();
4428 if (FormatTok->is(tok::colon)) {
4432 if (FormatTok->is(tok::less))
4433 parseObjCLightweightGenerics();
4434 }
else if (FormatTok->is(tok::l_paren)) {
4439 if (FormatTok->is(tok::less))
4440 parseObjCProtocolList();
4442 if (FormatTok->is(tok::l_brace)) {
4443 if (Style.BraceWrapping.AfterObjCDeclaration)
4452 parseObjCUntilAtEnd();
4455void UnwrappedLineParser::parseObjCLightweightGenerics() {
4456 assert(FormatTok->is(tok::less));
4464 unsigned NumOpenAngles = 1;
4468 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4470 if (FormatTok->is(tok::less)) {
4472 }
else if (FormatTok->is(tok::greater)) {
4473 assert(NumOpenAngles > 0 &&
"'>' makes NumOpenAngles negative");
4476 }
while (!
eof() && NumOpenAngles != 0);
4482bool UnwrappedLineParser::parseObjCProtocol() {
4483 assert(FormatTok->is(tok::objc_protocol));
4486 if (FormatTok->is(tok::l_paren)) {
4498 if (FormatTok->is(tok::less))
4499 parseObjCProtocolList();
4502 if (FormatTok->is(tok::semi)) {
4509 parseObjCUntilAtEnd();
4513void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
4514 bool IsImport = FormatTok->is(Keywords.kw_import);
4515 assert(IsImport || FormatTok->is(tok::kw_export));
4519 if (FormatTok->is(tok::kw_default))
4525 if (FormatTok->is(Keywords.kw_async))
4527 if (FormatTok->is(Keywords.kw_function)) {
4536 if (!IsImport && FormatTok->isNoneOf(tok::l_brace, tok::star) &&
4537 !FormatTok->isStringLiteral() &&
4538 !(FormatTok->is(Keywords.kw_type) &&
4539 Tokens->peekNextToken()->isOneOf(tok::l_brace, tok::star))) {
4544 if (FormatTok->is(tok::semi))
4546 if (
Line->Tokens.empty()) {
4551 if (FormatTok->is(tok::l_brace)) {
4552 FormatTok->setBlockKind(BK_Block);
4561void UnwrappedLineParser::parseStatementMacro() {
4563 if (FormatTok->is(tok::l_paren))
4565 if (FormatTok->is(tok::semi))
4570void UnwrappedLineParser::parseVerilogHierarchyIdentifier() {
4573 if (FormatTok->isOneOf(tok::star, tok::period, tok::periodstar,
4574 tok::coloncolon, tok::hash) ||
4575 Keywords.isVerilogIdentifier(*FormatTok)) {
4577 }
else if (FormatTok->is(tok::l_square)) {
4585void UnwrappedLineParser::parseVerilogSensitivityList() {
4586 if (FormatTok->isNot(tok::at))
4590 if (FormatTok->is(tok::at))
4592 switch (FormatTok->Tok.getKind()) {
4600 parseVerilogHierarchyIdentifier();
4605unsigned UnwrappedLineParser::parseVerilogHierarchyHeader() {
4606 unsigned AddLevels = 0;
4608 if (FormatTok->is(Keywords.kw_clocking)) {
4610 if (Keywords.isVerilogIdentifier(*FormatTok))
4612 parseVerilogSensitivityList();
4613 if (FormatTok->is(tok::semi))
4615 }
else if (FormatTok->isOneOf(tok::kw_case, Keywords.kw_casex,
4616 Keywords.kw_casez, Keywords.kw_randcase,
4617 Keywords.kw_randsequence)) {
4618 if (Style.IndentCaseLabels)
4621 if (FormatTok->is(tok::l_paren)) {
4622 FormatTok->setFinalizedType(TT_ConditionLParen);
4625 if (FormatTok->isOneOf(Keywords.kw_inside, Keywords.kw_matches))
4634 if (FormatTok->is(tok::l_square)) {
4635 auto Prev = FormatTok->getPreviousNonComment();
4636 if (Prev && Keywords.isVerilogIdentifier(*Prev))
4637 Prev->setFinalizedType(TT_VerilogDimensionedTypeName);
4639 }
else if (Keywords.isVerilogIdentifier(*FormatTok) ||
4640 FormatTok->isOneOf(tok::hash, tok::hashhash, tok::coloncolon,
4641 Keywords.kw_automatic, tok::kw_static)) {
4648 auto NewLine = [
this]() {
4650 Line->IsContinuation =
true;
4654 while (FormatTok->is(Keywords.kw_import)) {
4657 parseVerilogHierarchyIdentifier();
4658 if (FormatTok->is(tok::semi))
4663 if (FormatTok->is(Keywords.kw_verilogHash)) {
4666 if (FormatTok->is(tok::l_paren)) {
4667 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4671 if (FormatTok->is(tok::l_paren)) {
4673 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4678 if (FormatTok->is(Keywords.kw_extends)) {
4681 parseVerilogHierarchyIdentifier();
4682 if (FormatTok->is(tok::l_paren))
4685 if (FormatTok->is(Keywords.kw_implements)) {
4689 parseVerilogHierarchyIdentifier();
4690 }
while (FormatTok->is(tok::comma));
4694 if (FormatTok->is(tok::at)) {
4696 parseVerilogSensitivityList();
4699 if (FormatTok->is(tok::semi))
4707void UnwrappedLineParser::parseVerilogTable() {
4708 assert(FormatTok->is(Keywords.kw_table));
4712 auto InitialLevel =
Line->Level++;
4713 while (!
eof() && !Keywords.isVerilogEnd(*FormatTok)) {
4716 if (
Tok->
is(tok::semi))
4718 else if (
Tok->
isOneOf(tok::star, tok::colon, tok::question, tok::minus))
4719 Tok->setFinalizedType(TT_VerilogTableItem);
4721 Line->Level = InitialLevel;
4726void UnwrappedLineParser::parseVerilogCaseLabel() {
4732 auto OrigLevel =
Line->Level;
4733 auto FirstLine = CurrentLines->size();
4734 if (
Line->Level == 0 || (
Line->InPPDirective &&
Line->Level <= 1))
4736 else if (!Style.IndentCaseBlocks && Keywords.isVerilogBegin(*FormatTok))
4738 parseStructuralElement();
4741 if (CurrentLines->size() > FirstLine)
4742 (*CurrentLines)[FirstLine].Level = OrigLevel;
4743 Line->Level = OrigLevel;
4746void UnwrappedLineParser::parseVerilogExtern() {
4748 FormatTok->isOneOf(tok::kw_extern, tok::kw_export, Keywords.kw_import));
4751 if (FormatTok->is(tok::string_literal))
4753 skipVerilogQualifiers();
4754 if (Keywords.isVerilogIdentifier(*FormatTok))
4756 if (FormatTok->is(tok::equal))
4758 if (Keywords.isVerilogHierarchy(*FormatTok))
4759 parseVerilogHierarchyHeader();
4762void UnwrappedLineParser::skipVerilogQualifiers() {
4763 while (FormatTok->isOneOf(tok::kw_protected, tok::kw_virtual, tok::kw_static,
4764 Keywords.kw_rand, Keywords.kw_context,
4765 Keywords.kw_pure, Keywords.kw_randc,
4766 Keywords.kw_local)) {
4771bool UnwrappedLineParser::containsExpansion(
const UnwrappedLine &
Line)
const {
4772 for (
const auto &N :
Line.Tokens) {
4773 if (N.Tok->MacroCtx)
4775 for (
const UnwrappedLine &Child : N.Children)
4776 if (containsExpansion(Child))
4782void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) {
4783 if (
Line->Tokens.empty())
4786 if (!parsingPPDirective()) {
4787 llvm::dbgs() <<
"Adding unwrapped line:\n";
4788 printDebugInfo(*
Line);
4796 bool ClosesWhitesmithsBlock =
4797 Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex &&
4803 if (!parsingPPDirective() && !InExpansion && containsExpansion(*
Line)) {
4805 Reconstruct.emplace(
Line->Level, Unexpanded);
4806 Reconstruct->addLine(*
Line);
4811 CurrentExpandedLines.push_back(std::move(*
Line));
4813 if (Reconstruct->finished()) {
4814 UnwrappedLine Reconstructed = std::move(*Reconstruct).takeResult();
4815 assert(!Reconstructed.Tokens.empty() &&
4816 "Reconstructed must at least contain the macro identifier.");
4817 assert(!parsingPPDirective());
4819 llvm::dbgs() <<
"Adding unexpanded line:\n";
4820 printDebugInfo(Reconstructed);
4822 ExpandedLines[Reconstructed.Tokens.begin()->Tok] = CurrentExpandedLines;
4823 Lines.push_back(std::move(Reconstructed));
4824 CurrentExpandedLines.clear();
4825 Reconstruct.reset();
4830 assert(!Reconstruct || (CurrentLines != &Lines) || !PP.Stack.empty());
4831 CurrentLines->push_back(std::move(*
Line));
4833 Line->Tokens.clear();
4834 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
4835 Line->FirstStartColumn = 0;
4836 Line->IsContinuation =
false;
4837 Line->SeenDecltypeAuto =
false;
4838 Line->IsModuleOrImportDecl =
false;
4840 if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove)
4842 if (!parsingPPDirective() && !PreprocessorDirectives.empty()) {
4843 CurrentLines->append(
4844 std::make_move_iterator(PreprocessorDirectives.begin()),
4845 std::make_move_iterator(PreprocessorDirectives.end()));
4846 PreprocessorDirectives.clear();
4849 FormatTok->Previous =
nullptr;
4852bool UnwrappedLineParser::eof()
const {
return FormatTok->is(tok::eof); }
4854bool UnwrappedLineParser::isOnNewLine(
const FormatToken &FormatTok) {
4855 return (
Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
4856 FormatTok.NewlinesBefore > 0;
4864 const llvm::Regex &CommentPragmasRegex) {
4868 StringRef IndentContent = FormatTok.
TokenText;
4869 if (FormatTok.
TokenText.starts_with(
"//") ||
4870 FormatTok.
TokenText.starts_with(
"/*")) {
4871 IndentContent = FormatTok.
TokenText.substr(2);
4873 if (CommentPragmasRegex.match(IndentContent))
4948 if (PreviousToken && PreviousToken->
is(tok::l_brace) &&
4950 MinColumnToken = PreviousToken;
4953 PreviousToken = Node.
Tok;
4957 MinColumnToken = Node.
Tok;
4959 if (PreviousToken && PreviousToken->
is(tok::l_brace))
4960 MinColumnToken = PreviousToken;
4966void UnwrappedLineParser::flushComments(
bool NewlineBeforeNext) {
4967 bool JustComments =
Line->Tokens.empty();
4977 Tok->ContinuesLineCommentSection =
4978 continuesLineCommentSection(*
Tok, *
Line, Style, CommentPragmasRegex);
4979 if (isOnNewLine(*
Tok) && JustComments && !
Tok->ContinuesLineCommentSection)
4983 if (NewlineBeforeNext && JustComments)
4985 CommentsBeforeNextToken.clear();
4988void UnwrappedLineParser::nextToken(
int LevelDifference) {
4991 flushComments(isOnNewLine(*FormatTok));
4992 pushToken(FormatTok);
4994 if (!Style.isJavaScript())
4995 readToken(LevelDifference);
4997 readTokenWithJavaScriptASI();
4999 if (Style.isVerilog()) {
5006 if (Keywords.isVerilogEnd(*FormatTok))
5007 FormatTok->Tok.setKind(tok::r_brace);
5011void UnwrappedLineParser::distributeComments(
5031 if (Comments.empty())
5033 bool ShouldPushCommentsInCurrentLine =
true;
5034 bool HasTrailAlignedWithNextToken =
false;
5035 unsigned StartOfTrailAlignedWithNextToken = 0;
5038 for (
unsigned i = Comments.size() - 1; i > 0; --i) {
5040 HasTrailAlignedWithNextToken =
true;
5041 StartOfTrailAlignedWithNextToken = i;
5045 for (
unsigned i = 0, e = Comments.size(); i < e; ++i) {
5047 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
5048 FormatTok->ContinuesLineCommentSection =
false;
5051 *FormatTok, *
Line, Style, CommentPragmasRegex);
5053 if (!FormatTok->ContinuesLineCommentSection &&
5054 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
5055 ShouldPushCommentsInCurrentLine =
false;
5057 if (ShouldPushCommentsInCurrentLine)
5058 pushToken(FormatTok);
5060 CommentsBeforeNextToken.push_back(FormatTok);
5064void UnwrappedLineParser::readToken(
int LevelDifference) {
5066 bool PreviousWasComment =
false;
5067 bool FirstNonCommentOnLine =
false;
5069 FormatTok = Tokens->getNextToken();
5071 while (FormatTok->isOneOf(TT_ConflictStart, TT_ConflictEnd,
5072 TT_ConflictAlternative)) {
5073 if (FormatTok->is(TT_ConflictStart))
5074 conditionalCompilationStart(
false);
5075 else if (FormatTok->is(TT_ConflictAlternative))
5076 conditionalCompilationAlternative();
5077 else if (FormatTok->is(TT_ConflictEnd))
5078 conditionalCompilationEnd();
5079 FormatTok = Tokens->getNextToken();
5080 FormatTok->MustBreakBefore =
true;
5081 FormatTok->MustBreakBeforeFinalized =
true;
5084 auto IsFirstNonCommentOnLine = [](
bool FirstNonCommentOnLine,
5086 bool PreviousWasComment) {
5088 return Tok.HasUnescapedNewline ||
Tok.IsFirst;
5093 if (PreviousWasComment)
5094 return FirstNonCommentOnLine || IsFirstOnLine(
Tok);
5095 return IsFirstOnLine(
Tok);
5098 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
5099 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
5100 PreviousWasComment = FormatTok->is(tok::comment);
5102 while (!
Line->InPPDirective && FormatTok->is(tok::hash) &&
5103 FirstNonCommentOnLine) {
5106 const auto *
Next = Tokens->peekNextToken();
5107 if ((Style.isVerilog() && !Keywords.isVerilogPPDirective(*
Next)) ||
5108 (Style.isTableGen() &&
5109 Next->isNoneOf(tok::kw_else, tok::pp_define, tok::pp_ifdef,
5110 tok::pp_ifndef, tok::pp_endif))) {
5113 distributeComments(Comments, FormatTok);
5118 const bool ParsedBefore = !ParsedPPDirectives.insert(FormatTok).second;
5121 bool SwitchToPreprocessorLines = !
Line->Tokens.empty();
5122 ScopedLineState BlockState(*
this, SwitchToPreprocessorLines,
5124 assert((LevelDifference >= 0 ||
5125 static_cast<unsigned>(-LevelDifference) <=
Line->Level) &&
5126 "LevelDifference makes Line->Level negative");
5127 Line->Level += LevelDifference;
5132 PP.BranchLevel > 0) {
5133 Line->Level += PP.BranchLevel;
5135 assert(
Line->Level >=
Line->UnbracedBodyLevel);
5136 Line->Level -=
Line->UnbracedBodyLevel;
5137 flushComments(isOnNewLine(*FormatTok));
5138 const bool IsEndIf = Tokens->peekNextToken()->is(tok::pp_endif);
5140 PreviousWasComment = FormatTok->is(tok::comment);
5141 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
5142 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
5145 if (IsEndIf && PP.IncludeGuard == IG_Defined && PP.BranchLevel == -1 &&
5146 getIncludeGuardState(Style.IndentPPDirectives) == IG_Inited &&
5148 (PreviousWasComment &&
5149 Tokens->peekNextToken(
true)->is(tok::eof)))) {
5150 PP.IncludeGuard = IG_Found;
5154 if (!PP.Stack.empty() && (PP.Stack.back().Kind == PP_Unreachable) &&
5155 !
Line->InPPDirective) {
5159 if (FormatTok->is(tok::identifier) &&
5160 Macros.defined(FormatTok->TokenText) &&
5162 !
Line->InPPDirective) {
5164 unsigned Position = Tokens->getPosition();
5169 const auto SavedPPState = PP;
5173 auto PreCall = std::move(
Line);
5174 Line.reset(
new UnwrappedLine);
5175 bool OldInExpansion = InExpansion;
5178 auto Args = parseMacroCall(SavedPPState);
5179 InExpansion = OldInExpansion;
5180 assert(
Line->Tokens.front().Tok == ID);
5182 auto UnexpandedLine = std::move(
Line);
5184 Line = std::move(PreCall);
5187 llvm::dbgs() <<
"Macro call: " <<
ID->TokenText <<
"(";
5189 llvm::dbgs() <<
"(";
5190 for (
const auto &Arg : Args.value())
5191 for (
const auto &
T : Arg)
5192 llvm::dbgs() <<
T->TokenText <<
" ";
5193 llvm::dbgs() <<
")";
5195 llvm::dbgs() <<
"\n";
5197 if (
Macros.objectLike(
ID->TokenText) && Args &&
5198 !
Macros.hasArity(
ID->TokenText, Args->size())) {
5204 LLVM_DEBUG(llvm::dbgs()
5205 <<
"Macro \"" <<
ID->TokenText
5206 <<
"\" not overloaded for arity " << Args->size()
5207 <<
"or not function-like, using object-like overload.");
5209 UnexpandedLine->Tokens.resize(1);
5210 Tokens->setPosition(Position);
5212 FormatTok = Tokens->getNextToken();
5214 assert(!Args &&
Macros.objectLike(
ID->TokenText));
5216 if ((!Args &&
Macros.objectLike(
ID->TokenText)) ||
5217 (Args &&
Macros.hasArity(
ID->TokenText, Args->size()))) {
5220 Unexpanded[
ID] = std::move(UnexpandedLine);
5222 Macros.expand(ID, std::move(Args));
5223 if (!Expansion.empty())
5224 FormatTok = Tokens->insertTokens(Expansion);
5227 llvm::dbgs() <<
"Expanded: ";
5228 for (
const auto &
T : Expansion)
5229 llvm::dbgs() <<
T->TokenText <<
" ";
5230 llvm::dbgs() <<
"\n";
5234 llvm::dbgs() <<
"Did not expand macro \"" <<
ID->TokenText
5235 <<
"\", because it was used ";
5237 llvm::dbgs() <<
"with " << Args->size();
5239 llvm::dbgs() <<
"without";
5240 llvm::dbgs() <<
" arguments, which doesn't match any definition.\n";
5242 Tokens->setPosition(Position);
5248 if (FormatTok->isNot(tok::comment)) {
5249 distributeComments(Comments, FormatTok);
5254 Comments.push_back(FormatTok);
5257 distributeComments(Comments,
nullptr);
5262template <
typename Iterator>
5263void pushTokens(Iterator Begin, Iterator End,
5265 for (
auto I = Begin; I != End; ++I) {
5266 Into.push_back(I->Tok);
5267 for (
const auto &Child : I->Children)
5268 pushTokens(Child.Tokens.begin(), Child.Tokens.end(), Into);
5273std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>
5274UnwrappedLineParser::parseMacroCall(
const PPState &SavedPPState) {
5275 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>> Args;
5276 assert(
Line->Tokens.empty());
5279 auto ConsumeLastTokenOfCall = [
this] {
5280 flushComments(isOnNewLine(*FormatTok));
5281 pushToken(FormatTok);
5282 FormatTok = Tokens->getNextToken();
5284 if (Tokens->peekNextToken(
true)->isNot(tok::l_paren)) {
5285 ConsumeLastTokenOfCall();
5289 assert(FormatTok->is(tok::l_paren));
5290 unsigned Position = Tokens->getPosition();
5294 auto ArgStart = std::prev(
Line->Tokens.end());
5298 switch (FormatTok->Tok.getKind()) {
5303 case tok::r_paren: {
5309 Args->push_back({});
5310 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5311 ConsumeLastTokenOfCall();
5319 Args->push_back({});
5320 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5322 ArgStart = std::prev(
Line->Tokens.end());
5330 Line->Tokens.resize(1);
5331 Tokens->setPosition(Position);
5338 Line->Tokens.push_back(UnwrappedLineNode(
Tok));
5339 if (PP.AtEndOfPPLine) {
5340 auto &
Tok = *
Line->Tokens.back().Tok;
5341 Tok.MustBreakBefore =
true;
5342 Tok.MustBreakBeforeFinalized =
true;
5343 Tok.FirstAfterPPLine =
true;
5344 PP.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
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.