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;
2940 ++
Line->UnbracedBodyLevel;
2941 parseStructuralElement();
2942 --
Line->UnbracedBodyLevel;
2945 assert(!
Line->InPPDirective);
2947 for (
const auto &L : llvm::reverse(*CurrentLines)) {
2949 Tok = L.Tokens.back().Tok;
2957 if (CheckEOF &&
eof())
2967 assert(LeftBrace->
is(tok::l_brace));
2975 assert(RightBrace->
is(tok::r_brace));
2983void UnwrappedLineParser::handleAttributes() {
2985 if (FormatTok->isAttribute())
2987 else if (FormatTok->is(tok::l_square))
2988 handleCppAttributes();
2991bool UnwrappedLineParser::handleCppAttributes() {
2993 assert(FormatTok->is(tok::l_square));
2994 if (!tryToParseSimpleAttribute())
3001bool UnwrappedLineParser::isBlockBegin(
const FormatToken &
Tok)
const {
3004 return Style.isVerilog() ? Keywords.isVerilogBegin(
Tok)
3005 :
Tok.
is(tok::l_brace);
3008FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
3010 bool IsVerilogAssert) {
3011 assert((FormatTok->is(tok::kw_if) ||
3012 (Style.isVerilog() &&
3013 FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
3014 Keywords.kw_assume, Keywords.kw_cover))) &&
3018 if (IsVerilogAssert) {
3020 if (FormatTok->is(Keywords.kw_verilogHash)) {
3022 if (FormatTok->is(tok::numeric_constant))
3024 }
else if (FormatTok->isOneOf(Keywords.kw_final, Keywords.kw_property,
3025 Keywords.kw_sequence)) {
3031 if (Style.isTableGen()) {
3032 while (!
eof() && FormatTok->isNot(Keywords.kw_then)) {
3039 if (FormatTok->is(tok::exclaim))
3042 bool KeepIfBraces =
true;
3043 if (FormatTok->is(tok::kw_consteval)) {
3046 KeepIfBraces = !Style.RemoveBracesLLVM || KeepBraces;
3047 if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
3049 if (FormatTok->is(tok::l_paren)) {
3050 FormatTok->setFinalizedType(TT_ConditionLParen);
3056 if (IsVerilogAssert && FormatTok->is(tok::semi)) {
3062 bool NeedsUnwrappedLine =
false;
3063 keepAncestorBraces();
3066 IfStmtKind IfBlockKind = IfStmtKind::NotIf;
3068 if (isBlockBegin(*FormatTok)) {
3069 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3070 IfLeftBrace = FormatTok;
3071 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3072 parseBlock(
false, 1u,
3073 true, KeepIfBraces, &IfBlockKind);
3074 setPreviousRBraceType(TT_ControlStatementRBrace);
3075 if (Style.BraceWrapping.BeforeElse)
3078 NeedsUnwrappedLine =
true;
3079 }
else if (IsVerilogAssert && FormatTok->is(tok::kw_else)) {
3082 parseUnbracedBody();
3085 if (Style.RemoveBracesLLVM) {
3086 assert(!NestedTooDeep.empty());
3087 KeepIfBraces = KeepIfBraces ||
3088 (IfLeftBrace && !IfLeftBrace->MatchingParen) ||
3089 NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly ||
3090 IfBlockKind == IfStmtKind::IfElseIf;
3093 bool KeepElseBraces = KeepIfBraces;
3095 IfStmtKind
Kind = IfStmtKind::IfOnly;
3097 if (FormatTok->is(tok::kw_else)) {
3098 if (Style.RemoveBracesLLVM) {
3099 NestedTooDeep.back() =
false;
3100 Kind = IfStmtKind::IfElse;
3104 if (isBlockBegin(*FormatTok)) {
3105 const bool FollowedByIf = Tokens->peekNextToken()->is(tok::kw_if);
3106 FormatTok->setFinalizedType(TT_ElseLBrace);
3107 ElseLeftBrace = FormatTok;
3108 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3109 IfStmtKind ElseBlockKind = IfStmtKind::NotIf;
3111 parseBlock(
false, 1u,
3112 true, KeepElseBraces, &ElseBlockKind);
3113 setPreviousRBraceType(TT_ElseRBrace);
3114 if (FormatTok->is(tok::kw_else)) {
3115 KeepElseBraces = KeepElseBraces ||
3116 ElseBlockKind == IfStmtKind::IfOnly ||
3117 ElseBlockKind == IfStmtKind::IfElseIf;
3118 }
else if (FollowedByIf && IfLBrace && !IfLBrace->Optional) {
3119 KeepElseBraces =
true;
3120 assert(ElseLeftBrace->MatchingParen);
3124 }
else if (!IsVerilogAssert && FormatTok->is(tok::kw_if)) {
3127 const bool IsPrecededByComment =
Previous->is(tok::comment);
3128 if (IsPrecededByComment) {
3132 bool TooDeep =
true;
3133 if (Style.RemoveBracesLLVM) {
3134 Kind = IfStmtKind::IfElseIf;
3135 TooDeep = NestedTooDeep.pop_back_val();
3137 ElseLeftBrace = parseIfThenElse(
nullptr, KeepIfBraces);
3138 if (Style.RemoveBracesLLVM)
3139 NestedTooDeep.push_back(TooDeep);
3140 if (IsPrecededByComment)
3143 parseUnbracedBody(
true);
3146 KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse;
3147 if (NeedsUnwrappedLine)
3151 if (!Style.RemoveBracesLLVM)
3154 assert(!NestedTooDeep.empty());
3155 KeepElseBraces = KeepElseBraces ||
3156 (ElseLeftBrace && !ElseLeftBrace->MatchingParen) ||
3157 NestedTooDeep.back();
3159 NestedTooDeep.pop_back();
3161 if (!KeepIfBraces && !KeepElseBraces) {
3164 }
else if (IfLeftBrace) {
3165 FormatToken *IfRightBrace = IfLeftBrace->MatchingParen;
3167 assert(IfRightBrace->MatchingParen == IfLeftBrace);
3168 assert(!IfLeftBrace->Optional);
3169 assert(!IfRightBrace->Optional);
3170 IfLeftBrace->MatchingParen =
nullptr;
3171 IfRightBrace->MatchingParen =
nullptr;
3181void UnwrappedLineParser::parseTryCatch() {
3182 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) &&
"'try' expected");
3184 bool NeedsUnwrappedLine =
false;
3185 bool HasCtorInitializer =
false;
3186 if (FormatTok->is(tok::colon)) {
3187 auto *Colon = FormatTok;
3190 if (FormatTok->is(tok::identifier)) {
3191 HasCtorInitializer =
true;
3192 Colon->setFinalizedType(TT_CtorInitializerColon);
3197 while (FormatTok->is(tok::comma))
3200 while (FormatTok->is(tok::identifier)) {
3202 if (FormatTok->is(tok::l_paren)) {
3204 }
else if (FormatTok->is(tok::l_brace)) {
3211 while (FormatTok->is(tok::comma))
3216 if (Style.isJava() && FormatTok->is(tok::l_paren))
3219 keepAncestorBraces();
3221 if (FormatTok->is(tok::l_brace)) {
3222 if (HasCtorInitializer)
3223 FormatTok->setFinalizedType(TT_FunctionLBrace);
3224 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3226 if (Style.BraceWrapping.BeforeCatch)
3229 NeedsUnwrappedLine =
true;
3230 }
else if (FormatTok->isNot(tok::kw_catch)) {
3236 parseStructuralElement();
3239 for (
bool SeenCatch =
false;;) {
3240 if (FormatTok->is(tok::at))
3242 if (FormatTok->isNoneOf(tok::kw_catch, Keywords.kw___except,
3243 tok::kw___finally, tok::objc_catch,
3244 tok::objc_finally) &&
3245 !((Style.isJava() || Style.isJavaScript()) &&
3246 FormatTok->is(Keywords.kw_finally))) {
3249 if (FormatTok->is(tok::kw_catch))
3252 while (FormatTok->isNot(tok::l_brace)) {
3253 if (FormatTok->is(tok::l_paren)) {
3257 if (FormatTok->isOneOf(tok::semi, tok::r_brace) ||
eof()) {
3258 if (Style.RemoveBracesLLVM)
3259 NestedTooDeep.pop_back();
3265 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3268 NeedsUnwrappedLine =
false;
3269 Line->MustBeDeclaration =
false;
3270 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3272 if (Style.BraceWrapping.BeforeCatch)
3275 NeedsUnwrappedLine =
true;
3278 if (Style.RemoveBracesLLVM)
3279 NestedTooDeep.pop_back();
3281 if (NeedsUnwrappedLine)
3285void UnwrappedLineParser::parseNamespaceOrExportBlock(
unsigned AddLevels) {
3286 bool ManageWhitesmithsBraces =
3291 if (ManageWhitesmithsBraces)
3296 parseBlock(
true, AddLevels,
true,
3297 true,
nullptr, ManageWhitesmithsBraces);
3299 addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep);
3301 if (ManageWhitesmithsBraces)
3305void UnwrappedLineParser::parseNamespace() {
3306 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
3307 "'namespace' expected");
3311 if (InitialToken.is(TT_NamespaceMacro)) {
3314 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
3315 tok::l_square, tok::period, tok::l_paren) ||
3316 (Style.isCSharp() && FormatTok->is(tok::kw_union))) {
3317 if (FormatTok->is(tok::l_square))
3319 else if (FormatTok->is(tok::l_paren))
3325 if (FormatTok->is(tok::l_brace)) {
3326 FormatTok->setFinalizedType(TT_NamespaceLBrace);
3329 Tokens->peekNextToken()->is(tok::r_brace))) {
3333 unsigned AddLevels =
3336 DeclarationScopeStack.size() > 1)
3339 parseNamespaceOrExportBlock(AddLevels);
3344void UnwrappedLineParser::parseCppExportBlock() {
3345 if (FormatTok->is(tok::l_brace)) {
3346 FormatTok->setFinalizedType(TT_ExportLBrace);
3347 if (Style.BraceWrapping.AfterExportBlock)
3350 parseNamespaceOrExportBlock(Style.IndentExportBlock ? 1 : 0);
3353void UnwrappedLineParser::parseNew() {
3354 assert(FormatTok->is(tok::kw_new) &&
"'new' expected");
3357 if (Style.isCSharp()) {
3360 if (FormatTok->is(tok::l_paren))
3364 if (FormatTok->is(tok::l_brace))
3367 if (FormatTok->isOneOf(tok::semi, tok::comma))
3374 if (!Style.isJava())
3380 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
3384 if (FormatTok->is(tok::l_paren)) {
3388 if (FormatTok->is(tok::l_brace))
3396void UnwrappedLineParser::parseLoopBody(
bool KeepBraces,
bool WrapRightBrace) {
3397 keepAncestorBraces();
3399 if (isBlockBegin(*FormatTok)) {
3400 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3402 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3403 parseBlock(
false, 1u,
3405 setPreviousRBraceType(TT_ControlStatementRBrace);
3407 assert(!NestedTooDeep.empty());
3408 if (!NestedTooDeep.back())
3414 parseUnbracedBody();
3418 NestedTooDeep.pop_back();
3421void UnwrappedLineParser::parseForOrWhileLoop(
bool HasParens) {
3422 assert((FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) ||
3423 (Style.isVerilog() &&
3424 FormatTok->isOneOf(Keywords.kw_always, Keywords.kw_always_comb,
3425 Keywords.kw_always_ff, Keywords.kw_always_latch,
3426 Keywords.kw_final, Keywords.kw_initial,
3427 Keywords.kw_foreach, Keywords.kw_forever,
3428 Keywords.kw_repeat))) &&
3429 "'for', 'while' or foreach macro expected");
3430 const bool KeepBraces = !Style.RemoveBracesLLVM ||
3431 FormatTok->isNoneOf(tok::kw_for, tok::kw_while);
3435 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
3437 if (IsCpp && FormatTok->is(tok::kw_co_await))
3439 if (HasParens && FormatTok->is(tok::l_paren)) {
3443 if (Style.isVerilog())
3444 FormatTok->setFinalizedType(TT_ConditionLParen);
3448 if (Style.isVerilog()) {
3450 parseVerilogSensitivityList();
3451 }
else if (Style.AllowShortLoopsOnASingleLine && FormatTok->is(tok::semi) &&
3452 Tokens->getPreviousToken()->is(tok::r_paren)) {
3459 parseLoopBody(KeepBraces,
true);
3462void UnwrappedLineParser::parseDoWhile() {
3463 assert(FormatTok->is(tok::kw_do) &&
"'do' expected");
3466 parseLoopBody(
true, Style.BraceWrapping.BeforeWhile);
3469 if (FormatTok->isNot(tok::kw_while)) {
3474 FormatTok->setFinalizedType(TT_DoWhile);
3482 parseStructuralElement();
3485void UnwrappedLineParser::parseLabel(
bool IsGotoLabel) {
3488 const auto IndentGotoLabel = Style.IndentGotoLabels;
3489 const auto OldLineLevel =
Line->Level;
3496 if (OldLineLevel > 1 || (!
Line->InPPDirective && OldLineLevel > 0))
3500 if (!IsGotoLabel && !Style.IndentCaseBlocks &&
3501 CommentsBeforeNextToken.empty() && FormatTok->is(tok::l_brace)) {
3502 CompoundStatementIndenter Indenter(
this,
Level,
3503 Style.BraceWrapping.AfterCaseLabel,
3504 Style.BraceWrapping.IndentBraces);
3506 if (FormatTok->is(tok::kw_break)) {
3507 if (Style.BraceWrapping.AfterControlStatement ==
3510 if (!Style.IndentCaseBlocks &&
3515 parseStructuralElement();
3519 if (FormatTok->is(tok::semi))
3524 Level = OldLineLevel;
3526 if (FormatTok->isNot(tok::l_brace)) {
3527 parseStructuralElement();
3532void UnwrappedLineParser::parseCaseLabel() {
3533 assert(FormatTok->is(tok::kw_case) &&
"'case' expected");
3534 auto *Case = FormatTok;
3539 if (FormatTok->is(tok::colon)) {
3540 FormatTok->setFinalizedType(TT_CaseLabelColon);
3543 if (Style.isJava() && FormatTok->is(tok::arrow)) {
3544 FormatTok->setFinalizedType(TT_CaseLabelArrow);
3545 Case->setFinalizedType(TT_SwitchExpressionLabel);
3552void UnwrappedLineParser::parseSwitch(
bool IsExpr) {
3553 assert(FormatTok->is(tok::kw_switch) &&
"'switch' expected");
3555 if (FormatTok->is(tok::l_paren))
3558 keepAncestorBraces();
3560 if (FormatTok->is(tok::l_brace)) {
3561 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3562 FormatTok->setFinalizedType(IsExpr ? TT_SwitchExpressionLBrace
3563 : TT_ControlStatementLBrace);
3568 setPreviousRBraceType(TT_ControlStatementRBrace);
3574 parseStructuralElement();
3578 if (Style.RemoveBracesLLVM)
3579 NestedTooDeep.pop_back();
3582void UnwrappedLineParser::parseAccessSpecifier() {
3585 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
3588 if (FormatTok->is(tok::colon))
3596bool UnwrappedLineParser::parseRequires(
bool SeenEqual) {
3597 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3601 switch (Tokens->peekNextToken(
true)->Tok.getKind()) {
3604 parseRequiresExpression();
3611 parseRequiresClause();
3622 auto *PreviousNonComment = FormatTok->getPreviousNonComment();
3624 if (!PreviousNonComment ||
3625 PreviousNonComment->is(TT_RequiresExpressionLBrace)) {
3628 parseRequiresClause();
3632 switch (PreviousNonComment->Tok.getKind()) {
3635 case tok::kw_noexcept:
3640 parseRequiresClause();
3649 auto PrevPrev = PreviousNonComment->getPreviousNonComment();
3650 if ((PrevPrev && PrevPrev->is(tok::kw_const)) || !SeenEqual) {
3651 parseRequiresClause();
3657 if (PreviousNonComment->isTypeOrIdentifier(LangOpts)) {
3659 parseRequiresClause();
3663 parseRequiresExpression();
3673 unsigned StoredPosition = Tokens->getPosition();
3676 auto PeekNext = [&Lookahead, &NextToken,
this] {
3678 NextToken = Tokens->getNextToken();
3681 bool FoundType =
false;
3682 bool LastWasColonColon =
false;
3685 for (; Lookahead < 50; PeekNext()) {
3686 switch (NextToken->Tok.getKind()) {
3687 case tok::kw_volatile:
3690 if (OpenAngles == 0) {
3691 FormatTok = Tokens->setPosition(StoredPosition);
3692 parseRequiresExpression();
3700 case tok::coloncolon:
3701 LastWasColonColon =
true;
3703 case tok::kw_decltype:
3704 case tok::identifier:
3705 if (FoundType && !LastWasColonColon && OpenAngles == 0) {
3706 FormatTok = Tokens->setPosition(StoredPosition);
3707 parseRequiresExpression();
3711 LastWasColonColon =
false;
3720 if (NextToken->isTypeName(LangOpts)) {
3721 FormatTok = Tokens->setPosition(StoredPosition);
3722 parseRequiresExpression();
3729 FormatTok = Tokens->setPosition(StoredPosition);
3730 parseRequiresClause();
3739void UnwrappedLineParser::parseRequiresClause() {
3740 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3745 bool InRequiresExpression =
3746 !FormatTok->Previous ||
3747 FormatTok->Previous->is(TT_RequiresExpressionLBrace);
3749 FormatTok->setFinalizedType(InRequiresExpression
3750 ? TT_RequiresClauseInARequiresExpression
3751 : TT_RequiresClause);
3756 parseConstraintExpression();
3758 if (!InRequiresExpression && FormatTok->Previous)
3759 FormatTok->Previous->ClosesRequiresClause =
true;
3767void UnwrappedLineParser::parseRequiresExpression() {
3768 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3770 FormatTok->setFinalizedType(TT_RequiresExpression);
3773 if (FormatTok->is(tok::l_paren)) {
3774 FormatTok->setFinalizedType(TT_RequiresExpressionLParen);
3778 if (FormatTok->is(tok::l_brace)) {
3779 FormatTok->setFinalizedType(TT_RequiresExpressionLBrace);
3788void UnwrappedLineParser::parseConstraintExpression() {
3795 bool LambdaNextTimeAllowed =
true;
3805 bool TopLevelParensAllowed =
true;
3808 bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed,
false);
3810 switch (FormatTok->Tok.getKind()) {
3811 case tok::kw_requires:
3812 parseRequiresExpression();
3816 if (!TopLevelParensAllowed)
3818 parseParens(TT_BinaryOperator);
3819 TopLevelParensAllowed =
false;
3823 if (!LambdaThisTimeAllowed || !tryToParseLambda())
3830 case tok::kw_struct:
3840 FormatTok->setFinalizedType(TT_BinaryOperator);
3842 LambdaNextTimeAllowed =
true;
3843 TopLevelParensAllowed =
true;
3848 LambdaNextTimeAllowed = LambdaThisTimeAllowed;
3852 case tok::kw_sizeof:
3854 case tok::greaterequal:
3855 case tok::greatergreater:
3857 case tok::lessequal:
3859 case tok::equalequal:
3861 case tok::exclaimequal:
3866 LambdaNextTimeAllowed =
true;
3867 TopLevelParensAllowed =
true;
3872 case tok::numeric_constant:
3873 case tok::coloncolon:
3876 TopLevelParensAllowed =
false;
3881 case tok::kw_static_cast:
3882 case tok::kw_const_cast:
3883 case tok::kw_reinterpret_cast:
3884 case tok::kw_dynamic_cast:
3886 if (FormatTok->isNot(tok::less))
3890 parseBracedList(
true);
3894 if (!FormatTok->Tok.getIdentifierInfo()) {
3904 assert(FormatTok->Previous);
3905 switch (FormatTok->Previous->Tok.getKind()) {
3906 case tok::coloncolon:
3910 case tok::kw_requires:
3912 case tok::kw_template:
3920 if (FormatTok->is(tok::less)) {
3922 parseBracedList(
true);
3924 TopLevelParensAllowed =
false;
3930bool UnwrappedLineParser::parseEnum() {
3934 if (FormatTok->is(tok::kw_enum))
3940 if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question))
3949 if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
3951 while (FormatTok->is(tok::l_square))
3952 if (!handleCppAttributes())
3956 while (FormatTok->Tok.getIdentifierInfo() ||
3957 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
3958 tok::greater, tok::comma, tok::question,
3960 if (FormatTok->is(tok::colon))
3961 FormatTok->setFinalizedType(TT_EnumUnderlyingTypeColon);
3962 if (Style.isVerilog()) {
3963 FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
3966 while (FormatTok->is(tok::l_square))
3972 if (FormatTok->is(tok::l_paren))
3974 if (FormatTok->is(tok::identifier)) {
3978 if (IsCpp && FormatTok->is(tok::identifier))
3984 if (FormatTok->isNot(tok::l_brace))
3986 FormatTok->setFinalizedType(TT_EnumLBrace);
3987 FormatTok->setBlockKind(BK_Block);
3989 if (Style.isJava()) {
3991 parseJavaEnumBody();
3999 const bool ManageWhitesmithsBraces =
4002 if (!Style.AllowShortEnumsOnASingleLine &&
4004 Tokens->peekNextToken()->is(tok::r_brace))) {
4009 if (ManageWhitesmithsBraces)
4014 if (!Style.AllowShortEnumsOnASingleLine) {
4016 if (!ManageWhitesmithsBraces)
4019 const auto OpeningLineIndex = CurrentLines->empty()
4020 ? UnwrappedLine::kInvalidIndex
4021 : CurrentLines->size() - 1;
4022 bool HasError = !parseBracedList(
false,
true);
4023 if (!Style.AllowShortEnumsOnASingleLine && !ManageWhitesmithsBraces)
4026 if (FormatTok->is(tok::semi))
4030 setPreviousRBraceType(TT_EnumRBrace);
4031 if (ManageWhitesmithsBraces)
4032 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
4040bool UnwrappedLineParser::parseStructLike() {
4045 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp()) {
4046 if (FormatTok->is(tok::semi))
4057class ScopedTokenPosition {
4058 unsigned StoredPosition;
4059 FormatTokenSource *Tokens;
4062 ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) {
4063 assert(Tokens &&
"Tokens expected to not be null");
4064 StoredPosition = Tokens->getPosition();
4067 ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); }
4073bool UnwrappedLineParser::tryToParseSimpleAttribute() {
4074 ScopedTokenPosition AutoPosition(Tokens);
4082 if (
Tok->
is(tok::r_square))
4084 Tok = Tokens->getNextToken();
4086 if (
Tok->
is(tok::eof))
4088 Tok = Tokens->getNextToken();
4091 Tok = Tokens->getNextToken();
4092 if (
Tok->
is(tok::semi))
4097void UnwrappedLineParser::parseJavaEnumBody() {
4098 assert(FormatTok->is(tok::l_brace));
4104 unsigned StoredPosition = Tokens->getPosition();
4105 bool IsSimple =
true;
4108 if (
Tok->
is(tok::r_brace))
4116 Tok = Tokens->getNextToken();
4118 FormatTok = Tokens->setPosition(StoredPosition);
4135 if (FormatTok->is(tok::l_brace)) {
4137 parseBlock(
true, 1u,
4139 }
else if (FormatTok->is(tok::l_paren)) {
4141 }
else if (FormatTok->is(tok::comma)) {
4144 }
else if (FormatTok->is(tok::semi)) {
4148 }
else if (FormatTok->is(tok::r_brace)) {
4157 parseLevel(OpeningBrace);
4163void UnwrappedLineParser::parseRecord(
bool ParseAsExpr,
bool IsJavaRecord) {
4164 assert(!IsJavaRecord || FormatTok->is(Keywords.kw_record));
4169 IsJavaRecord && FormatTok->is(tok::identifier) ? FormatTok :
nullptr;
4170 bool IsDerived =
false;
4172 return Tok->
is(tok::identifier) &&
Tok->TokenText !=
Tok->TokenText.upper();
4176 bool JSPastExtendsOrImplements =
false;
4180 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
4181 tok::kw_alignas, tok::l_square) ||
4182 FormatTok->isAttribute() ||
4183 ((Style.isJava() || Style.isJavaScript()) &&
4184 FormatTok->isOneOf(tok::period, tok::comma)) ||
4185 (Style.isVerilog() &&
4186 FormatTok->isOneOf(tok::kw_signed, tok::kw_unsigned))) {
4187 if (Style.isJavaScript() &&
4188 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
4189 JSPastExtendsOrImplements =
true;
4194 if (FormatTok->is(tok::l_brace)) {
4195 tryToParseBracedList();
4199 if (FormatTok->is(tok::l_square) && handleCppAttributes())
4203 switch (FormatTok->Tok.getKind()) {
4206 if (IsJavaRecord || !IsNonMacroIdentifier(
Previous) ||
4208 Previous->Previous == &InitialToken) {
4212 case tok::coloncolon:
4216 if (JSPastExtendsOrImplements || ClassName ||
4227 auto IsListInitialization = [&] {
4228 if (!ClassName || IsDerived || JSPastExtendsOrImplements)
4230 assert(FormatTok->is(tok::l_brace));
4231 const auto *Prev = FormatTok->getPreviousNonComment();
4233 return Prev != ClassName && Prev->is(tok::identifier) &&
4234 Prev->isNot(Keywords.kw_final) && tryToParseBracedList();
4237 if (FormatTok->isOneOf(tok::colon, tok::less)) {
4238 int AngleNestingLevel = 0;
4240 if (FormatTok->is(tok::less))
4241 ++AngleNestingLevel;
4242 else if (FormatTok->is(tok::greater))
4243 --AngleNestingLevel;
4245 if (AngleNestingLevel == 0) {
4246 if (FormatTok->is(tok::colon)) {
4248 }
else if (!IsDerived && FormatTok->is(tok::identifier) &&
4249 FormatTok->Previous->is(tok::coloncolon)) {
4250 ClassName = FormatTok;
4251 }
else if (FormatTok->is(tok::l_paren) &&
4252 IsNonMacroIdentifier(FormatTok->Previous)) {
4256 if (FormatTok->is(tok::l_brace)) {
4257 if (AngleNestingLevel == 0 && IsListInitialization())
4259 calculateBraceTypes(
true);
4260 if (!tryToParseBracedList())
4263 if (FormatTok->is(tok::l_square)) {
4266 !
Previous->isTypeOrIdentifier(LangOpts))) {
4269 if (!tryToParseLambda())
4276 if (FormatTok->is(tok::semi))
4278 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
4281 parseCSharpGenericTypeConstraint();
4288 auto GetBraceTypes =
4289 [](
const FormatToken &RecordTok) -> std::pair<TokenType, TokenType> {
4290 switch (RecordTok.Tok.getKind()) {
4292 return {TT_ClassLBrace, TT_ClassRBrace};
4293 case tok::kw_struct:
4294 return {TT_StructLBrace, TT_StructRBrace};
4296 return {TT_UnionLBrace, TT_UnionRBrace};
4299 return {TT_RecordLBrace, TT_RecordRBrace};
4302 if (FormatTok->is(tok::l_brace)) {
4303 if (IsListInitialization())
4306 ClassName->setFinalizedType(TT_ClassHeadName);
4307 auto [OpenBraceType, ClosingBraceType] = GetBraceTypes(InitialToken);
4308 FormatTok->setFinalizedType(OpenBraceType);
4313 Tokens->peekNextToken()->is(tok::r_brace),
4318 bool IndentAfterExplicitAccessModifier =
false;
4319 unsigned AddLevels = 1u;
4320 switch (Style.IndentAccessModifiers) {
4324 if (Style.isCpp()) {
4325 IndentAfterExplicitAccessModifier =
true;
4334 parseBlock(
true, AddLevels,
false,
4337 IndentAfterExplicitAccessModifier);
4339 setPreviousRBraceType(ClosingBraceType);
4346void UnwrappedLineParser::parseObjCMethod() {
4347 assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) &&
4348 "'(' or identifier expected.");
4350 if (FormatTok->is(tok::semi)) {
4354 }
else if (FormatTok->is(tok::l_brace)) {
4355 if (Style.BraceWrapping.AfterFunction)
4366void UnwrappedLineParser::parseObjCProtocolList() {
4367 assert(FormatTok->is(tok::less) &&
"'<' expected.");
4371 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4373 }
while (!
eof() && FormatTok->isNot(tok::greater));
4377void UnwrappedLineParser::parseObjCUntilAtEnd() {
4379 if (FormatTok->is(tok::objc_end)) {
4384 if (FormatTok->is(tok::l_brace)) {
4388 }
else if (FormatTok->is(tok::r_brace)) {
4392 }
else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
4394 if (FormatTok->isOneOf(tok::l_paren, tok::identifier))
4397 parseStructuralElement();
4402void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
4403 assert(FormatTok->isOneOf(tok::objc_interface, tok::objc_implementation));
4409 if (FormatTok->is(tok::less))
4410 parseObjCLightweightGenerics();
4411 if (FormatTok->is(tok::colon)) {
4415 if (FormatTok->is(tok::less))
4416 parseObjCLightweightGenerics();
4417 }
else if (FormatTok->is(tok::l_paren)) {
4422 if (FormatTok->is(tok::less))
4423 parseObjCProtocolList();
4425 if (FormatTok->is(tok::l_brace)) {
4426 if (Style.BraceWrapping.AfterObjCDeclaration)
4435 parseObjCUntilAtEnd();
4438void UnwrappedLineParser::parseObjCLightweightGenerics() {
4439 assert(FormatTok->is(tok::less));
4447 unsigned NumOpenAngles = 1;
4451 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4453 if (FormatTok->is(tok::less)) {
4455 }
else if (FormatTok->is(tok::greater)) {
4456 assert(NumOpenAngles > 0 &&
"'>' makes NumOpenAngles negative");
4459 }
while (!
eof() && NumOpenAngles != 0);
4465bool UnwrappedLineParser::parseObjCProtocol() {
4466 assert(FormatTok->is(tok::objc_protocol));
4469 if (FormatTok->is(tok::l_paren)) {
4481 if (FormatTok->is(tok::less))
4482 parseObjCProtocolList();
4485 if (FormatTok->is(tok::semi)) {
4492 parseObjCUntilAtEnd();
4496void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
4497 bool IsImport = FormatTok->is(Keywords.kw_import);
4498 assert(IsImport || FormatTok->is(tok::kw_export));
4502 if (FormatTok->is(tok::kw_default))
4508 if (FormatTok->is(Keywords.kw_async))
4510 if (FormatTok->is(Keywords.kw_function)) {
4519 if (!IsImport && FormatTok->isNoneOf(tok::l_brace, tok::star) &&
4520 !FormatTok->isStringLiteral() &&
4521 !(FormatTok->is(Keywords.kw_type) &&
4522 Tokens->peekNextToken()->isOneOf(tok::l_brace, tok::star))) {
4527 if (FormatTok->is(tok::semi))
4529 if (
Line->Tokens.empty()) {
4534 if (FormatTok->is(tok::l_brace)) {
4535 FormatTok->setBlockKind(BK_Block);
4544void UnwrappedLineParser::parseStatementMacro() {
4546 if (FormatTok->is(tok::l_paren))
4548 if (FormatTok->is(tok::semi))
4553void UnwrappedLineParser::parseVerilogHierarchyIdentifier() {
4556 if (FormatTok->isOneOf(tok::star, tok::period, tok::periodstar,
4557 tok::coloncolon, tok::hash) ||
4558 Keywords.isVerilogIdentifier(*FormatTok)) {
4560 }
else if (FormatTok->is(tok::l_square)) {
4568void UnwrappedLineParser::parseVerilogSensitivityList() {
4569 if (FormatTok->isNot(tok::at))
4573 if (FormatTok->is(tok::at))
4575 switch (FormatTok->Tok.getKind()) {
4583 parseVerilogHierarchyIdentifier();
4588unsigned UnwrappedLineParser::parseVerilogHierarchyHeader() {
4589 unsigned AddLevels = 0;
4591 if (FormatTok->is(Keywords.kw_clocking)) {
4593 if (Keywords.isVerilogIdentifier(*FormatTok))
4595 parseVerilogSensitivityList();
4596 if (FormatTok->is(tok::semi))
4598 }
else if (FormatTok->isOneOf(tok::kw_case, Keywords.kw_casex,
4599 Keywords.kw_casez, Keywords.kw_randcase,
4600 Keywords.kw_randsequence)) {
4601 if (Style.IndentCaseLabels)
4604 if (FormatTok->is(tok::l_paren)) {
4605 FormatTok->setFinalizedType(TT_ConditionLParen);
4608 if (FormatTok->isOneOf(Keywords.kw_inside, Keywords.kw_matches))
4617 if (FormatTok->is(tok::l_square)) {
4618 auto Prev = FormatTok->getPreviousNonComment();
4619 if (Prev && Keywords.isVerilogIdentifier(*Prev))
4620 Prev->setFinalizedType(TT_VerilogDimensionedTypeName);
4622 }
else if (Keywords.isVerilogIdentifier(*FormatTok) ||
4623 FormatTok->isOneOf(tok::hash, tok::hashhash, tok::coloncolon,
4624 Keywords.kw_automatic, tok::kw_static)) {
4631 auto NewLine = [
this]() {
4633 Line->IsContinuation =
true;
4637 while (FormatTok->is(Keywords.kw_import)) {
4640 parseVerilogHierarchyIdentifier();
4641 if (FormatTok->is(tok::semi))
4646 if (FormatTok->is(Keywords.kw_verilogHash)) {
4649 if (FormatTok->is(tok::l_paren)) {
4650 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4654 if (FormatTok->is(tok::l_paren)) {
4656 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4661 if (FormatTok->is(Keywords.kw_extends)) {
4664 parseVerilogHierarchyIdentifier();
4665 if (FormatTok->is(tok::l_paren))
4668 if (FormatTok->is(Keywords.kw_implements)) {
4672 parseVerilogHierarchyIdentifier();
4673 }
while (FormatTok->is(tok::comma));
4677 if (FormatTok->is(tok::at)) {
4679 parseVerilogSensitivityList();
4682 if (FormatTok->is(tok::semi))
4690void UnwrappedLineParser::parseVerilogTable() {
4691 assert(FormatTok->is(Keywords.kw_table));
4695 auto InitialLevel =
Line->Level++;
4696 while (!
eof() && !Keywords.isVerilogEnd(*FormatTok)) {
4699 if (
Tok->
is(tok::semi))
4701 else if (
Tok->
isOneOf(tok::star, tok::colon, tok::question, tok::minus))
4702 Tok->setFinalizedType(TT_VerilogTableItem);
4704 Line->Level = InitialLevel;
4709void UnwrappedLineParser::parseVerilogCaseLabel() {
4715 auto OrigLevel =
Line->Level;
4716 auto FirstLine = CurrentLines->size();
4717 if (
Line->Level == 0 || (
Line->InPPDirective &&
Line->Level <= 1))
4719 else if (!Style.IndentCaseBlocks && Keywords.isVerilogBegin(*FormatTok))
4721 parseStructuralElement();
4724 if (CurrentLines->size() > FirstLine)
4725 (*CurrentLines)[FirstLine].Level = OrigLevel;
4726 Line->Level = OrigLevel;
4729void UnwrappedLineParser::parseVerilogExtern() {
4731 FormatTok->isOneOf(tok::kw_extern, tok::kw_export, Keywords.kw_import));
4734 if (FormatTok->is(tok::string_literal))
4736 skipVerilogQualifiers();
4737 if (Keywords.isVerilogIdentifier(*FormatTok))
4739 if (FormatTok->is(tok::equal))
4741 if (Keywords.isVerilogHierarchy(*FormatTok))
4742 parseVerilogHierarchyHeader();
4745void UnwrappedLineParser::skipVerilogQualifiers() {
4746 while (FormatTok->isOneOf(tok::kw_protected, tok::kw_virtual, tok::kw_static,
4747 Keywords.kw_rand, Keywords.kw_context,
4748 Keywords.kw_pure, Keywords.kw_randc,
4749 Keywords.kw_local)) {
4754bool UnwrappedLineParser::containsExpansion(
const UnwrappedLine &
Line)
const {
4755 for (
const auto &N :
Line.Tokens) {
4756 if (N.Tok->MacroCtx)
4758 for (
const UnwrappedLine &Child : N.Children)
4759 if (containsExpansion(Child))
4765void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) {
4766 if (
Line->Tokens.empty())
4769 if (!parsingPPDirective()) {
4770 llvm::dbgs() <<
"Adding unwrapped line:\n";
4771 printDebugInfo(*
Line);
4779 bool ClosesWhitesmithsBlock =
4780 Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex &&
4786 if (!parsingPPDirective() && !InExpansion && containsExpansion(*
Line)) {
4788 Reconstruct.emplace(
Line->Level, Unexpanded);
4789 Reconstruct->addLine(*
Line);
4794 CurrentExpandedLines.push_back(std::move(*
Line));
4796 if (Reconstruct->finished()) {
4797 UnwrappedLine Reconstructed = std::move(*Reconstruct).takeResult();
4798 assert(!Reconstructed.Tokens.empty() &&
4799 "Reconstructed must at least contain the macro identifier.");
4800 assert(!parsingPPDirective());
4802 llvm::dbgs() <<
"Adding unexpanded line:\n";
4803 printDebugInfo(Reconstructed);
4805 ExpandedLines[Reconstructed.Tokens.begin()->Tok] = CurrentExpandedLines;
4806 Lines.push_back(std::move(Reconstructed));
4807 CurrentExpandedLines.clear();
4808 Reconstruct.reset();
4813 assert(!Reconstruct || (CurrentLines != &Lines) || !PP.Stack.empty());
4814 CurrentLines->push_back(std::move(*
Line));
4816 Line->Tokens.clear();
4817 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
4818 Line->FirstStartColumn = 0;
4819 Line->IsContinuation =
false;
4820 Line->SeenDecltypeAuto =
false;
4821 Line->IsModuleOrImportDecl =
false;
4823 if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove)
4825 if (!parsingPPDirective() && !PreprocessorDirectives.empty()) {
4826 CurrentLines->append(
4827 std::make_move_iterator(PreprocessorDirectives.begin()),
4828 std::make_move_iterator(PreprocessorDirectives.end()));
4829 PreprocessorDirectives.clear();
4832 FormatTok->Previous =
nullptr;
4835bool UnwrappedLineParser::eof()
const {
return FormatTok->is(tok::eof); }
4837bool UnwrappedLineParser::isOnNewLine(
const FormatToken &FormatTok) {
4838 return (
Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
4839 FormatTok.NewlinesBefore > 0;
4847 const llvm::Regex &CommentPragmasRegex) {
4851 StringRef IndentContent = FormatTok.
TokenText;
4852 if (FormatTok.
TokenText.starts_with(
"//") ||
4853 FormatTok.
TokenText.starts_with(
"/*")) {
4854 IndentContent = FormatTok.
TokenText.substr(2);
4856 if (CommentPragmasRegex.match(IndentContent))
4931 if (PreviousToken && PreviousToken->
is(tok::l_brace) &&
4933 MinColumnToken = PreviousToken;
4936 PreviousToken = Node.
Tok;
4940 MinColumnToken = Node.
Tok;
4942 if (PreviousToken && PreviousToken->
is(tok::l_brace))
4943 MinColumnToken = PreviousToken;
4949void UnwrappedLineParser::flushComments(
bool NewlineBeforeNext) {
4950 bool JustComments =
Line->Tokens.empty();
4960 Tok->ContinuesLineCommentSection =
4961 continuesLineCommentSection(*
Tok, *
Line, Style, CommentPragmasRegex);
4962 if (isOnNewLine(*
Tok) && JustComments && !
Tok->ContinuesLineCommentSection)
4966 if (NewlineBeforeNext && JustComments)
4968 CommentsBeforeNextToken.clear();
4971void UnwrappedLineParser::nextToken(
int LevelDifference) {
4974 flushComments(isOnNewLine(*FormatTok));
4975 pushToken(FormatTok);
4977 if (!Style.isJavaScript())
4978 readToken(LevelDifference);
4980 readTokenWithJavaScriptASI();
4982 if (Style.isVerilog()) {
4989 if (Keywords.isVerilogEnd(*FormatTok))
4990 FormatTok->Tok.setKind(tok::r_brace);
4994void UnwrappedLineParser::distributeComments(
5014 if (Comments.empty())
5016 bool ShouldPushCommentsInCurrentLine =
true;
5017 bool HasTrailAlignedWithNextToken =
false;
5018 unsigned StartOfTrailAlignedWithNextToken = 0;
5021 for (
unsigned i = Comments.size() - 1; i > 0; --i) {
5023 HasTrailAlignedWithNextToken =
true;
5024 StartOfTrailAlignedWithNextToken = i;
5028 for (
unsigned i = 0, e = Comments.size(); i < e; ++i) {
5030 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
5031 FormatTok->ContinuesLineCommentSection =
false;
5034 *FormatTok, *
Line, Style, CommentPragmasRegex);
5036 if (!FormatTok->ContinuesLineCommentSection &&
5037 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
5038 ShouldPushCommentsInCurrentLine =
false;
5040 if (ShouldPushCommentsInCurrentLine)
5041 pushToken(FormatTok);
5043 CommentsBeforeNextToken.push_back(FormatTok);
5047void UnwrappedLineParser::readToken(
int LevelDifference) {
5049 bool PreviousWasComment =
false;
5050 bool FirstNonCommentOnLine =
false;
5052 FormatTok = Tokens->getNextToken();
5054 while (FormatTok->isOneOf(TT_ConflictStart, TT_ConflictEnd,
5055 TT_ConflictAlternative)) {
5056 if (FormatTok->is(TT_ConflictStart))
5057 conditionalCompilationStart(
false);
5058 else if (FormatTok->is(TT_ConflictAlternative))
5059 conditionalCompilationAlternative();
5060 else if (FormatTok->is(TT_ConflictEnd))
5061 conditionalCompilationEnd();
5062 FormatTok = Tokens->getNextToken();
5063 FormatTok->MustBreakBefore =
true;
5064 FormatTok->MustBreakBeforeFinalized =
true;
5067 auto IsFirstNonCommentOnLine = [](
bool FirstNonCommentOnLine,
5069 bool PreviousWasComment) {
5071 return Tok.HasUnescapedNewline ||
Tok.IsFirst;
5076 if (PreviousWasComment)
5077 return FirstNonCommentOnLine || IsFirstOnLine(
Tok);
5078 return IsFirstOnLine(
Tok);
5081 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
5082 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
5083 PreviousWasComment = FormatTok->is(tok::comment);
5085 while (!
Line->InPPDirective && FormatTok->is(tok::hash) &&
5086 FirstNonCommentOnLine) {
5089 const auto *
Next = Tokens->peekNextToken();
5090 if ((Style.isVerilog() && !Keywords.isVerilogPPDirective(*
Next)) ||
5091 (Style.isTableGen() &&
5092 Next->isNoneOf(tok::kw_else, tok::pp_define, tok::pp_ifdef,
5093 tok::pp_ifndef, tok::pp_endif))) {
5096 distributeComments(Comments, FormatTok);
5101 const bool ParsedBefore = !ParsedPPDirectives.insert(FormatTok).second;
5104 bool SwitchToPreprocessorLines = !
Line->Tokens.empty();
5105 ScopedLineState BlockState(*
this, SwitchToPreprocessorLines,
5107 assert((LevelDifference >= 0 ||
5108 static_cast<unsigned>(-LevelDifference) <=
Line->Level) &&
5109 "LevelDifference makes Line->Level negative");
5110 Line->Level += LevelDifference;
5115 PP.BranchLevel > 0) {
5116 Line->Level += PP.BranchLevel;
5118 assert(
Line->Level >=
Line->UnbracedBodyLevel);
5119 Line->Level -=
Line->UnbracedBodyLevel;
5120 flushComments(isOnNewLine(*FormatTok));
5121 const bool IsEndIf = Tokens->peekNextToken()->is(tok::pp_endif);
5123 PreviousWasComment = FormatTok->is(tok::comment);
5124 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
5125 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
5128 if (IsEndIf && PP.IncludeGuard == IG_Defined && PP.BranchLevel == -1 &&
5129 getIncludeGuardState(Style.IndentPPDirectives) == IG_Inited &&
5131 (PreviousWasComment &&
5132 Tokens->peekNextToken(
true)->is(tok::eof)))) {
5133 PP.IncludeGuard = IG_Found;
5137 if (!PP.Stack.empty() && (PP.Stack.back().Kind == PP_Unreachable) &&
5138 !
Line->InPPDirective) {
5142 if (FormatTok->is(tok::identifier) &&
5143 Macros.defined(FormatTok->TokenText) &&
5145 !
Line->InPPDirective) {
5147 unsigned Position = Tokens->getPosition();
5152 const auto SavedPPState = PP;
5156 auto PreCall = std::move(
Line);
5157 Line.reset(
new UnwrappedLine);
5158 bool OldInExpansion = InExpansion;
5161 auto Args = parseMacroCall(SavedPPState);
5162 InExpansion = OldInExpansion;
5163 assert(
Line->Tokens.front().Tok == ID);
5165 auto UnexpandedLine = std::move(
Line);
5167 Line = std::move(PreCall);
5170 llvm::dbgs() <<
"Macro call: " <<
ID->TokenText <<
"(";
5172 llvm::dbgs() <<
"(";
5173 for (
const auto &Arg : Args.value())
5174 for (
const auto &
T : Arg)
5175 llvm::dbgs() <<
T->TokenText <<
" ";
5176 llvm::dbgs() <<
")";
5178 llvm::dbgs() <<
"\n";
5180 if (
Macros.objectLike(
ID->TokenText) && Args &&
5181 !
Macros.hasArity(
ID->TokenText, Args->size())) {
5187 LLVM_DEBUG(llvm::dbgs()
5188 <<
"Macro \"" <<
ID->TokenText
5189 <<
"\" not overloaded for arity " << Args->size()
5190 <<
"or not function-like, using object-like overload.");
5192 UnexpandedLine->Tokens.resize(1);
5193 Tokens->setPosition(Position);
5195 FormatTok = Tokens->getNextToken();
5197 assert(!Args &&
Macros.objectLike(
ID->TokenText));
5199 if ((!Args &&
Macros.objectLike(
ID->TokenText)) ||
5200 (Args &&
Macros.hasArity(
ID->TokenText, Args->size()))) {
5203 Unexpanded[
ID] = std::move(UnexpandedLine);
5205 Macros.expand(ID, std::move(Args));
5206 if (!Expansion.empty())
5207 FormatTok = Tokens->insertTokens(Expansion);
5210 llvm::dbgs() <<
"Expanded: ";
5211 for (
const auto &
T : Expansion)
5212 llvm::dbgs() <<
T->TokenText <<
" ";
5213 llvm::dbgs() <<
"\n";
5217 llvm::dbgs() <<
"Did not expand macro \"" <<
ID->TokenText
5218 <<
"\", because it was used ";
5220 llvm::dbgs() <<
"with " << Args->size();
5222 llvm::dbgs() <<
"without";
5223 llvm::dbgs() <<
" arguments, which doesn't match any definition.\n";
5225 Tokens->setPosition(Position);
5231 if (FormatTok->isNot(tok::comment)) {
5232 distributeComments(Comments, FormatTok);
5237 Comments.push_back(FormatTok);
5240 distributeComments(Comments,
nullptr);
5245template <
typename Iterator>
5246void pushTokens(Iterator Begin, Iterator End,
5248 for (
auto I = Begin; I != End; ++I) {
5249 Into.push_back(I->Tok);
5250 for (
const auto &Child : I->Children)
5251 pushTokens(Child.Tokens.begin(), Child.Tokens.end(), Into);
5256std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>
5257UnwrappedLineParser::parseMacroCall(
const PPState &SavedPPState) {
5258 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>> Args;
5259 assert(
Line->Tokens.empty());
5262 auto ConsumeLastTokenOfCall = [
this] {
5263 flushComments(isOnNewLine(*FormatTok));
5264 pushToken(FormatTok);
5265 FormatTok = Tokens->getNextToken();
5267 if (Tokens->peekNextToken(
true)->isNot(tok::l_paren)) {
5268 ConsumeLastTokenOfCall();
5272 assert(FormatTok->is(tok::l_paren));
5273 unsigned Position = Tokens->getPosition();
5277 auto ArgStart = std::prev(
Line->Tokens.end());
5281 switch (FormatTok->Tok.getKind()) {
5286 case tok::r_paren: {
5292 Args->push_back({});
5293 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5294 ConsumeLastTokenOfCall();
5302 Args->push_back({});
5303 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5305 ArgStart = std::prev(
Line->Tokens.end());
5313 Line->Tokens.resize(1);
5314 Tokens->setPosition(Position);
5321 Line->Tokens.push_back(UnwrappedLineNode(
Tok));
5322 if (PP.AtEndOfPPLine) {
5323 auto &
Tok = *
Line->Tokens.back().Tok;
5324 Tok.MustBreakBefore =
true;
5325 Tok.MustBreakBeforeFinalized =
true;
5326 Tok.FirstAfterPPLine =
true;
5327 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.