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();
181 TokenAfterIfWithConditionalElse =
nullptr;
183 CommentsBeforeNextToken.clear();
185 PP.AtEndOfPPLine =
false;
186 IsDecltypeAutoFunction =
false;
187 PreprocessorDirectives.clear();
188 CurrentLines = &Lines;
189 DeclarationScopeStack.clear();
190 NestedTooDeep.clear();
191 NestedLambdas.clear();
193 Line->FirstStartColumn = FirstStartColumn;
195 if (!Unexpanded.empty())
197 Token->MacroCtx.reset();
198 CurrentExpandedLines.clear();
199 ExpandedLines.clear();
207 Line->FirstStartColumn = FirstStartColumn;
209 LLVM_DEBUG(llvm::dbgs() <<
"----\n");
211 Tokens = &TokenSource;
219 if (PP.IncludeGuard == IG_Found) {
220 for (
auto &Line : Lines)
221 if (Line.InPPDirective && Line.Level > 0)
227 pushToken(FormatTok);
232 if (!ExpandedLines.empty()) {
233 LLVM_DEBUG(llvm::dbgs() <<
"Expanded lines:\n");
234 for (
auto &Line : Lines) {
235 if (!Line.Tokens.empty()) {
236 auto it = ExpandedLines.find(Line.Tokens.begin()->Tok);
237 if (it != ExpandedLines.end()) {
238 for (
auto &Expanded : it->second) {
239 Expanded.InMacroExpansion =
true;
240 LLVM_DEBUG(printDebugInfo(Expanded));
241 Callback.consumeUnwrappedLine(Expanded);
246 Line.InMacroExpansion =
true;
247 LLVM_DEBUG(printDebugInfo(Line));
248 Callback.consumeUnwrappedLine(Line);
249 Line.InMacroExpansion =
false;
251 Callback.finishRun();
254 LLVM_DEBUG(llvm::dbgs() <<
"Unwrapped lines:\n");
256 LLVM_DEBUG(printDebugInfo(Line));
257 Callback.consumeUnwrappedLine(Line);
259 Callback.finishRun();
261 while (!PP.LevelBranchIndex.empty() &&
262 PP.LevelBranchIndex.back() + 1 >= PP.LevelBranchCount.back()) {
263 PP.LevelBranchIndex.resize(PP.LevelBranchIndex.size() - 1);
264 PP.LevelBranchCount.resize(PP.LevelBranchCount.size() - 1);
266 if (!PP.LevelBranchIndex.empty()) {
267 ++PP.LevelBranchIndex.back();
268 assert(PP.LevelBranchIndex.size() == PP.LevelBranchCount.size());
269 assert(PP.LevelBranchIndex.back() <= PP.LevelBranchCount.back());
271 }
while (!PP.LevelBranchIndex.empty());
274void UnwrappedLineParser::parseFile() {
277 bool MustBeDeclaration = !
Line->InPPDirective && !Style.isJavaScript();
278 ScopedDeclarationState DeclarationState(*
Line, DeclarationScopeStack,
280 if (Style.isTextProto() || (Style.isJson() && FormatTok->
IsFirst))
295 if (Style.isTextProto() && !CommentsBeforeNextToken.empty())
301void UnwrappedLineParser::parseCSharpGenericTypeConstraint() {
311 parseCSharpGenericTypeConstraint();
320void UnwrappedLineParser::parseCSharpAttribute() {
321 int UnpairedSquareBrackets = 1;
323 switch (FormatTok->Tok.getKind()) {
326 --UnpairedSquareBrackets;
327 if (UnpairedSquareBrackets == 0) {
333 ++UnpairedSquareBrackets;
343bool UnwrappedLineParser::precededByCommentOrPPDirective()
const {
344 if (!Lines.empty() && Lines.back().InPPDirective)
358bool UnwrappedLineParser::parseLevel(
const FormatToken *OpeningBrace,
361 bool *SeenExplicitAccessModifier) {
362 const bool InRequiresExpression =
363 OpeningBrace && OpeningBrace->is(TT_RequiresExpressionLBrace);
364 const bool IsPrecededByCommentOrPPDirective =
365 !Style.RemoveBracesLLVM || precededByCommentOrPPDirective();
367 bool HasDoWhile =
false;
368 bool HasLabel =
false;
369 unsigned StatementCount = 0;
370 bool SwitchLabelEncountered =
false;
373 if (FormatTok->isAttribute()) {
375 if (FormatTok->is(tok::l_paren))
380 if (FormatTok->is(TT_MacroBlockBegin))
382 else if (FormatTok->is(TT_MacroBlockEnd))
385 auto ParseDefault = [
this, OpeningBrace, IfKind, &IfLBrace, &HasDoWhile,
386 &HasLabel, &StatementCount,
387 SeenExplicitAccessModifier] {
388 if (SeenExplicitAccessModifier && !*SeenExplicitAccessModifier) {
389 const bool IsQtAccessLabel =
390 FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
391 Keywords.kw_slots, Keywords.kw_qslots) &&
392 Tokens->peekNextToken(
true)->is(tok::colon);
393 if (FormatTok->isAccessSpecifierKeyword() || IsQtAccessLabel) {
395 *SeenExplicitAccessModifier =
true;
398 parseStructuralElement(OpeningBrace, IfKind, &IfLBrace,
399 HasDoWhile ?
nullptr : &HasDoWhile,
400 HasLabel ?
nullptr : &HasLabel);
402 assert(StatementCount > 0 &&
"StatementCount overflow!");
411 if (InRequiresExpression) {
412 FormatTok->setFinalizedType(TT_CompoundRequirementLBrace);
413 }
else if (FormatTok->Previous &&
414 FormatTok->Previous->ClosesRequiresClause) {
420 if (!InRequiresExpression && FormatTok->isNot(TT_MacroBlockBegin)) {
421 if (tryToParseBracedList())
423 FormatTok->setFinalizedType(TT_BlockLBrace);
427 assert(StatementCount > 0 &&
"StatementCount overflow!");
432 if (!Style.RemoveBracesLLVM || Line->InPPDirective ||
433 OpeningBrace->isNoneOf(TT_ControlStatementLBrace, TT_ElseLBrace)) {
436 if (FormatTok->isNot(tok::r_brace) || StatementCount != 1 || HasLabel ||
437 HasDoWhile || IsPrecededByCommentOrPPDirective ||
438 precededByCommentOrPPDirective()) {
442 if (
Next->is(tok::comment) &&
Next->NewlinesBefore == 0)
445 *IfLeftBrace = IfLBrace;
451 case tok::kw_default: {
452 unsigned StoredPosition = Tokens->getPosition();
453 auto *
Next = Tokens->getNextNonComment();
454 FormatTok = Tokens->setPosition(StoredPosition);
455 if (
Next->isNoneOf(tok::colon, tok::arrow)) {
458 parseStructuralElement();
466 (Style.isJavaScript() && Line->MustBeDeclaration)) {
474 if (!SwitchLabelEncountered &&
475 (Style.IndentCaseLabels ||
476 (OpeningBrace && OpeningBrace->is(TT_SwitchExpressionLBrace)) ||
477 (Line->InPPDirective && Line->Level == 1))) {
480 SwitchLabelEncountered =
true;
481 parseStructuralElement();
484 if (Style.isCSharp()) {
486 parseCSharpAttribute();
489 if (handleCppAttributes())
501void UnwrappedLineParser::calculateBraceTypes(
bool ExpectClassBody) {
506 unsigned StoredPosition = Tokens->getPosition();
516 SmallVector<StackEntry, 8> LBraceStack;
517 assert(
Tok->is(tok::l_brace));
520 auto *NextTok = Tokens->getNextNonComment();
522 if (!Line->InMacroBody && !Style.isTableGen()) {
524 while (NextTok->is(tok::hash)) {
525 NextTok = Tokens->getNextToken();
526 if (NextTok->isOneOf(tok::pp_not_keyword, tok::pp_define))
529 NextTok = Tokens->getNextToken();
530 }
while (!NextTok->HasUnescapedNewline && NextTok->isNot(tok::eof));
532 while (NextTok->is(tok::comment))
533 NextTok = Tokens->getNextToken();
537 switch (
Tok->Tok.getKind()) {
539 if (Style.isJavaScript() && PrevTok) {
540 if (PrevTok->isOneOf(tok::colon, tok::less)) {
551 }
else if (PrevTok->is(tok::r_paren)) {
555 }
else if (Style.isJava() && PrevTok && PrevTok->is(tok::arrow)) {
560 LBraceStack.push_back({
Tok, PrevTok});
563 if (LBraceStack.empty())
565 if (
auto *LBrace = LBraceStack.back().Tok; LBrace->is(
BK_Unknown)) {
566 bool ProbablyBracedList =
false;
568 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
569 }
else if (LBrace->isNot(TT_EnumLBrace)) {
572 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
573 NextTok->OriginalColumn == 0;
583 ProbablyBracedList = LBrace->is(TT_BracedListLBrace);
585 ProbablyBracedList = ProbablyBracedList ||
586 (Style.isJavaScript() &&
587 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
590 ProbablyBracedList ||
591 (IsCpp && (PrevTok->Tok.isLiteral() ||
592 NextTok->isOneOf(tok::l_paren, tok::arrow)));
599 ProbablyBracedList ||
600 NextTok->isOneOf(tok::comma, tok::period, tok::colon,
601 tok::r_paren, tok::r_square, tok::ellipsis);
606 ProbablyBracedList ||
607 (NextTok->is(tok::l_brace) && LBraceStack.back().PrevTok &&
608 LBraceStack.back().PrevTok->isOneOf(tok::identifier,
612 ProbablyBracedList ||
613 (NextTok->is(tok::identifier) &&
614 PrevTok->isNoneOf(tok::semi, tok::r_brace, tok::l_brace));
616 ProbablyBracedList = ProbablyBracedList ||
617 (NextTok->is(tok::semi) &&
618 (!ExpectClassBody || LBraceStack.size() != 1));
621 ProbablyBracedList ||
622 (NextTok->isBinaryOperator() && !NextIsObjCMethod);
624 if (!Style.isCSharp() && NextTok->is(tok::l_square)) {
627 NextTok = Tokens->getNextToken();
628 ProbablyBracedList = NextTok->isNot(tok::l_square);
632 if (IsCpp && Line->InMacroBody && PrevTok != FormatTok &&
633 !FormatTok->Previous && NextTok->is(tok::eof) &&
637 PrevTok->isNoneOf(tok::semi,
BK_Block, tok::colon)) {
638 ProbablyBracedList =
true;
642 Tok->setBlockKind(BlockKind);
643 LBrace->setBlockKind(BlockKind);
645 LBraceStack.pop_back();
647 case tok::identifier:
648 if (
Tok->isNot(TT_StatementMacro))
659 if (!LBraceStack.empty() && LBraceStack.back().Tok->is(
BK_Unknown))
660 LBraceStack.back().Tok->setBlockKind(
BK_Block);
668 }
while (
Tok->isNot(tok::eof) && !LBraceStack.empty());
671 for (
const auto &Entry : LBraceStack)
675 FormatTok = Tokens->setPosition(StoredPosition);
679void UnwrappedLineParser::setPreviousRBraceType(
TokenType Type) {
680 if (
auto Prev = FormatTok->getPreviousNonComment();
681 Prev && Prev->is(tok::r_brace)) {
682 Prev->setFinalizedType(
Type);
689 seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
692size_t UnwrappedLineParser::computePPHash()
const {
694 for (
const auto &i : PP.Stack) {
705bool UnwrappedLineParser::mightFitOnOneLine(
707 const auto ColumnLimit = Style.ColumnLimit;
708 if (ColumnLimit == 0)
711 auto &Tokens = ParsedLine.Tokens;
712 assert(!Tokens.empty());
714 const auto *LastToken = Tokens.back().Tok;
717 SmallVector<UnwrappedLineNode> SavedTokens(Tokens.size());
720 for (
const auto &Token : Tokens) {
722 auto &SavedToken = SavedTokens[Index++];
724 SavedToken.Tok->copyFrom(*Token.Tok);
725 SavedToken.Children = std::move(Token.Children);
728 AnnotatedLine
Line(ParsedLine);
729 assert(Line.Last == LastToken);
731 TokenAnnotator Annotator(Style, Keywords);
732 Annotator.annotate(Line);
733 Annotator.calculateFormattingInformation(Line);
735 auto Length = LastToken->TotalLength;
737 assert(OpeningBrace != Tokens.front().Tok);
738 if (
auto Prev = OpeningBrace->Previous;
739 Prev && Prev->TotalLength + ColumnLimit == OpeningBrace->TotalLength) {
740 Length -= ColumnLimit;
742 Length -= OpeningBrace->TokenText.size() + 1;
745 if (
const auto *FirstToken = Line.First; FirstToken->is(tok::r_brace)) {
746 assert(!OpeningBrace || OpeningBrace->is(TT_ControlStatementLBrace));
747 Length -= FirstToken->TokenText.size() + 1;
751 for (
auto &Token : Tokens) {
752 const auto &SavedToken = SavedTokens[Index++];
753 Token.Tok->copyFrom(*SavedToken.Tok);
754 Token.Children = std::move(SavedToken.Children);
755 delete SavedToken.Tok;
759 assert(!Line.InMacroBody);
760 assert(!Line.InPPDirective);
761 return Line.Level * Style.IndentWidth + Length <= ColumnLimit;
765 bool MustBeDeclaration,
unsigned AddLevels,
bool MunchSemi,
bool KeepBraces,
766 IfStmtKind *IfKind,
bool UnindentWhitesmithsBraces,
767 bool IndentAfterExplicitAccessModifier) {
768 auto HandleVerilogBlockLabel = [
this]() {
770 if (Style.isVerilog() && FormatTok->is(tok::colon)) {
772 if (Keywords.isVerilogIdentifier(*FormatTok))
779 const bool VerilogHierarchy =
780 Style.isVerilog() && Keywords.isVerilogHierarchy(*FormatTok);
781 assert((FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) ||
782 (Style.isVerilog() &&
783 (Keywords.isVerilogBegin(*FormatTok) || VerilogHierarchy))) &&
784 "'{' or macro block token expected");
786 const bool FollowedByComment = Tokens->peekNextToken()->is(tok::comment);
787 auto Index = CurrentLines->size();
788 const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
791 const bool IsWhitesmiths =
796 if (!VerilogHierarchy && AddLevels > 0 && IsWhitesmiths)
799 size_t PPStartHash = computePPHash();
801 const unsigned InitialLevel = Line->Level;
802 if (VerilogHierarchy) {
803 AddLevels += parseVerilogHierarchyHeader();
805 nextToken(AddLevels);
806 HandleVerilogBlockLabel();
810 if (Line->Level > 300)
813 if (MacroBlock && FormatTok->is(tok::l_paren))
816 size_t NbPreprocessorDirectives =
817 !parsingPPDirective() ? PreprocessorDirectives.size() : 0;
819 size_t OpeningLineIndex =
820 CurrentLines->empty() || !CurrentExpandedLines.empty()
822 : (CurrentLines->size() - 1 - NbPreprocessorDirectives);
827 if (UnindentWhitesmithsBraces)
830 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
836 Line->Level += AddLevels - (IsWhitesmiths ? 1 : 0);
839 bool SeenExplicitAccessModifier =
false;
840 const bool SimpleBlock =
841 parseLevel(
Tok, IfKind, &IfLBrace,
842 IndentAfterExplicitAccessModifier ? &SeenExplicitAccessModifier
848 if (MacroBlock ? FormatTok->isNot(TT_MacroBlockEnd)
849 : FormatTok->isNot(tok::r_brace)) {
850 Line->Level = InitialLevel;
851 FormatTok->setBlockKind(BK_Block);
855 if (FormatTok->is(tok::r_brace)) {
856 FormatTok->setBlockKind(BK_Block);
857 if (Tok->is(TT_NamespaceLBrace))
858 FormatTok->setFinalizedType(TT_NamespaceRBrace);
861 const bool IsFunctionRBrace =
862 FormatTok->is(tok::r_brace) &&
Tok->is(TT_FunctionLBrace);
864 auto RemoveBraces = [=]()
mutable {
867 assert(Tok->isOneOf(TT_ControlStatementLBrace, TT_ElseLBrace));
868 assert(FormatTok->is(tok::r_brace));
869 const bool WrappedOpeningBrace = !Tok->Previous;
870 if (WrappedOpeningBrace && FollowedByComment)
872 const bool HasRequiredIfBraces = IfLBrace && !IfLBrace->Optional;
873 if (KeepBraces && !HasRequiredIfBraces)
875 if (Tok->isNot(TT_ElseLBrace) || !HasRequiredIfBraces) {
876 const FormatToken *Previous = Tokens->getPreviousToken();
878 if (Previous->is(tok::r_brace) && !Previous->Optional)
883 assert(!CurrentLines->empty());
884 auto &LastLine = CurrentLines->back();
885 if (LastLine.Level == InitialLevel + 1 && !mightFitOnOneLine(LastLine))
887 if (
Tok->is(TT_ElseLBrace))
889 if (WrappedOpeningBrace) {
894 return mightFitOnOneLine((*CurrentLines)[Index],
Tok);
896 if (RemoveBraces()) {
897 Tok->MatchingParen = FormatTok;
898 FormatTok->MatchingParen =
Tok;
901 size_t PPEndHash = computePPHash();
903 if (SeenExplicitAccessModifier)
906 nextToken(-AddLevels);
911 if (Style.RemoveSemicolon && IsFunctionRBrace) {
912 while (FormatTok->is(tok::semi)) {
913 FormatTok->Optional =
true;
918 HandleVerilogBlockLabel();
920 if (MacroBlock && FormatTok->is(tok::l_paren))
923 Line->Level = InitialLevel;
925 if (FormatTok->is(tok::kw_noexcept)) {
930 if (FormatTok->is(tok::arrow)) {
934 parseStructuralElement();
937 if (MunchSemi && FormatTok->is(tok::semi))
940 if (PPStartHash == PPEndHash && CurrentExpandedLines.empty() &&
941 !containsExpansion(*
Line)) {
942 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
945 (*CurrentLines)[OpeningLineIndex].MatchingClosingBlockLineIndex =
946 CurrentLines->size() - 1;
956 if (
Line.Tokens.size() < 4)
958 auto I =
Line.Tokens.begin();
959 if (I->Tok->TokenText !=
"goog")
962 if (I->Tok->isNot(tok::period))
965 if (I->Tok->TokenText !=
"scope")
968 return I->Tok->is(tok::l_paren);
977 if (
Line.Tokens.size() < 3)
979 auto I =
Line.Tokens.begin();
980 if (I->Tok->isNot(tok::l_paren))
986 return I->Tok->is(tok::l_paren);
992 bool IsJavaRecord =
false) {
994 return Style.BraceWrapping.AfterClass;
997 if (InitialToken.
is(TT_NamespaceMacro))
998 Kind = tok::kw_namespace;
1000 const bool WrapRecordAllowed =
1003 Style.BraceWrapping.SplitEmptyRecord;
1006 case tok::kw_namespace:
1007 return Style.BraceWrapping.AfterNamespace;
1009 return Style.BraceWrapping.AfterClass && WrapRecordAllowed;
1011 return Style.BraceWrapping.AfterUnion && WrapRecordAllowed;
1012 case tok::kw_struct:
1013 return Style.BraceWrapping.AfterStruct && WrapRecordAllowed;
1015 return Style.BraceWrapping.AfterEnum;
1021void UnwrappedLineParser::parseChildBlock() {
1022 assert(FormatTok->is(tok::l_brace));
1023 FormatTok->setBlockKind(BK_Block);
1027 bool SkipIndent = (Style.isJavaScript() &&
1028 (isGoogScope(*
Line) || isIIFE(*
Line, Keywords)));
1029 ScopedLineState LineState(*
this);
1030 ScopedDeclarationState DeclarationState(*
Line, DeclarationScopeStack,
1032 Line->Level += SkipIndent ? 0 : 1;
1033 parseLevel(OpeningBrace);
1034 flushComments(isOnNewLine(*FormatTok));
1035 Line->Level -= SkipIndent ? 0 : 1;
1040void UnwrappedLineParser::parsePPDirective() {
1041 assert(FormatTok->is(tok::hash) &&
"'#' expected");
1042 ScopedMacroState MacroState(*
Line, Tokens, FormatTok);
1046 if (!FormatTok->Tok.getIdentifierInfo()) {
1051 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
1052 case tok::pp_define:
1059 case tok::pp_ifndef:
1063 case tok::pp_elifdef:
1064 case tok::pp_elifndef:
1071 case tok::pp_pragma:
1075 case tok::pp_warning:
1077 if (!
eof() && Style.isCpp())
1078 FormatTok->setFinalizedType(TT_AfterPPDirective);
1086void UnwrappedLineParser::conditionalCompilationCondition(
bool Unreachable) {
1087 size_t Line = CurrentLines->size();
1088 if (CurrentLines == &PreprocessorDirectives)
1089 Line += Lines.size();
1092 (!PP.Stack.empty() && PP.Stack.back().Kind == PP_Unreachable)) {
1093 PP.Stack.push_back({PP_Unreachable,
Line});
1095 PP.Stack.push_back({PP_Conditional,
Line});
1099void UnwrappedLineParser::conditionalCompilationStart(
bool Unreachable) {
1101 assert(PP.BranchLevel >= 0 &&
1102 PP.BranchLevel <= (
int)PP.LevelBranchIndex.size());
1103 if (PP.BranchLevel == (
int)PP.LevelBranchIndex.size()) {
1104 PP.LevelBranchIndex.push_back(0);
1105 PP.LevelBranchCount.push_back(0);
1107 PP.ChainBranchIndex.push(Unreachable ? -1 : 0);
1108 bool Skip = PP.LevelBranchIndex[PP.BranchLevel] > 0;
1109 conditionalCompilationCondition(Unreachable ||
Skip);
1112void UnwrappedLineParser::conditionalCompilationAlternative() {
1113 if (!PP.Stack.empty())
1114 PP.Stack.pop_back();
1115 assert(PP.BranchLevel < (
int)PP.LevelBranchIndex.size());
1116 if (!PP.ChainBranchIndex.empty())
1117 ++PP.ChainBranchIndex.top();
1118 conditionalCompilationCondition(
1119 PP.BranchLevel >= 0 && !PP.ChainBranchIndex.empty() &&
1120 PP.LevelBranchIndex[PP.BranchLevel] != PP.ChainBranchIndex.top());
1123void UnwrappedLineParser::conditionalCompilationEnd() {
1124 assert(PP.BranchLevel < (
int)PP.LevelBranchIndex.size());
1125 if (PP.BranchLevel >= 0 && !PP.ChainBranchIndex.empty()) {
1126 if (PP.ChainBranchIndex.top() + 1 > PP.LevelBranchCount[PP.BranchLevel])
1127 PP.LevelBranchCount[PP.BranchLevel] = PP.ChainBranchIndex.top() + 1;
1130 if (PP.BranchLevel > -1)
1132 if (!PP.ChainBranchIndex.empty())
1133 PP.ChainBranchIndex.pop();
1134 if (!PP.Stack.empty())
1135 PP.Stack.pop_back();
1138void UnwrappedLineParser::parsePPIf(
bool IfDef) {
1139 bool IfNDef = FormatTok->is(tok::pp_ifndef);
1141 bool Unreachable =
false;
1142 if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText ==
"0"))
1144 if (IfDef && !IfNDef && FormatTok->TokenText ==
"SWIG")
1146 conditionalCompilationStart(Unreachable);
1150 bool MaybeIncludeGuard = IfNDef;
1151 if (PP.IncludeGuard == IG_Inited && MaybeIncludeGuard) {
1152 for (
auto &
Line : Lines) {
1153 if (
Line.Tokens.front().Tok->isNot(tok::comment)) {
1154 MaybeIncludeGuard =
false;
1155 PP.IncludeGuard = IG_Rejected;
1163 if (PP.IncludeGuard == IG_Inited && MaybeIncludeGuard) {
1164 PP.IncludeGuard = IG_IfNdefed;
1165 PP.IncludeGuardToken = IfCondition;
1169void UnwrappedLineParser::parsePPElse() {
1171 if (PP.IncludeGuard == IG_Defined && PP.BranchLevel == 0)
1172 PP.IncludeGuard = IG_Rejected;
1174 assert(PP.BranchLevel >= -1);
1175 if (PP.BranchLevel == -1)
1176 conditionalCompilationStart(
true);
1177 conditionalCompilationAlternative();
1183void UnwrappedLineParser::parsePPEndIf() {
1184 conditionalCompilationEnd();
1188void UnwrappedLineParser::parsePPDefine() {
1191 if (!FormatTok->Tok.getIdentifierInfo()) {
1192 PP.IncludeGuard = IG_Rejected;
1193 PP.IncludeGuardToken =
nullptr;
1198 bool MaybeIncludeGuard =
false;
1199 if (PP.IncludeGuard == IG_IfNdefed &&
1200 PP.IncludeGuardToken->TokenText == FormatTok->TokenText) {
1201 PP.IncludeGuard = IG_Defined;
1202 PP.IncludeGuardToken =
nullptr;
1203 for (
auto &
Line : Lines) {
1204 if (
Line.Tokens.front().Tok->isNoneOf(tok::comment, tok::hash)) {
1205 PP.IncludeGuard = IG_Rejected;
1209 MaybeIncludeGuard = PP.IncludeGuard == IG_Defined;
1217 FormatTok->Tok.setKind(tok::identifier);
1218 FormatTok->Tok.setIdentifierInfo(Keywords.kw_internal_ident_after_define);
1222 if (MaybeIncludeGuard && !
eof())
1223 PP.IncludeGuard = IG_Rejected;
1225 if (FormatTok->is(tok::l_paren) && !FormatTok->hasWhitespaceBefore())
1228 Line->Level += PP.BranchLevel + 1;
1232 Line->PPLevel = PP.BranchLevel + (PP.IncludeGuard == IG_Defined ? 0 : 1);
1233 assert((
int)
Line->PPLevel >= 0);
1238 Line->InMacroBody =
true;
1240 if (!Style.SkipMacroDefinitionBody) {
1250 for (
auto *Comment : CommentsBeforeNextToken)
1251 Comment->Finalized =
true;
1254 FormatTok->Finalized =
true;
1255 FormatTok = Tokens->getNextToken();
1261void UnwrappedLineParser::parsePPPragma() {
1262 Line->InPragmaDirective =
true;
1266void UnwrappedLineParser::parsePPUnknown() {
1270 Line->Level += PP.BranchLevel + 1;
1280 return Tok.isNoneOf(tok::semi, tok::l_brace,
1283 tok::period, tok::periodstar, tok::arrow, tok::arrowstar,
1284 tok::less, tok::greater, tok::slash, tok::percent,
1285 tok::lessless, tok::greatergreater, tok::equal,
1286 tok::plusequal, tok::minusequal, tok::starequal,
1287 tok::slashequal, tok::percentequal, tok::ampequal,
1288 tok::pipeequal, tok::caretequal, tok::greatergreaterequal,
1301 return FormatTok->
is(tok::identifier) &&
1316 FormatTok->
isOneOf(tok::kw_true, tok::kw_false) ||
1327 tok::kw_if, tok::kw_else,
1329 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
1331 tok::kw_switch, tok::kw_case,
1333 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.
kw_finally,
1335 tok::kw_const, tok::kw_class, Keywords.
kw_var, Keywords.
kw_let,
1343 return Tok.isOneOf(tok::kw_char, tok::kw_short, tok::kw_int, tok::kw_long,
1344 tok::kw_unsigned, tok::kw_float, tok::kw_double,
1361 if (FuncName->
isNot(tok::identifier))
1369 Tok->isNoneOf(tok::kw_register, tok::kw_struct, tok::kw_union)) {
1373 if (
Next->isNot(tok::star) && !
Next->Tok.getIdentifierInfo())
1377 if (!
Tok ||
Tok->isNot(tok::r_paren))
1381 if (!
Tok ||
Tok->isNot(tok::identifier))
1384 return Tok->Previous &&
Tok->Previous->isOneOf(tok::l_paren, tok::comma);
1387bool UnwrappedLineParser::parseModuleDecl() {
1389 assert(FormatTok->is(Keywords.kw_module));
1397 if (FormatTok->isNot(tok::identifier))
1400 for (nextToken(); FormatTok->isNoneOf(tok::semi, tok::eof); nextToken())
1401 if (FormatTok->is(tok::colon))
1402 FormatTok->setFinalizedType(TT_ModulePartitionColon);
1405 Line->IsModuleOrImportDecl =
true;
1410bool UnwrappedLineParser::parseImportDecl() {
1412 assert(FormatTok->is(Keywords.kw_import) &&
"'import' expected");
1420 if (FormatTok->is(tok::colon)) {
1421 FormatTok->setFinalizedType(TT_ModulePartitionColon);
1424 if (FormatTok->isNoneOf(tok::identifier, tok::less, tok::string_literal))
1427 for (; FormatTok->isNoneOf(tok::semi, tok::eof); nextToken()) {
1429 if (FormatTok->is(tok::less)) {
1430 for (nextToken(); FormatTok->isNoneOf(tok::greater, tok::semi, tok::eof);
1434 FormatTok->setFinalizedType(TT_ImplicitStringLiteral);
1440 Line->IsModuleOrImportDecl =
true;
1452void UnwrappedLineParser::readTokenWithJavaScriptASI() {
1458 CommentsBeforeNextToken.empty()
1459 ?
Next->NewlinesBefore == 0
1460 : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
1465 bool PreviousStartsTemplateExpr =
1467 if (PreviousMustBeValue ||
Previous->is(tok::r_paren)) {
1470 bool HasAt = llvm::any_of(
Line->Tokens, [](UnwrappedLineNode &LineNode) {
1471 return LineNode.Tok->is(tok::at);
1476 if (
Next->is(tok::exclaim) && PreviousMustBeValue)
1477 return addUnwrappedLine();
1479 bool NextEndsTemplateExpr =
1480 Next->is(TT_TemplateString) &&
Next->TokenText.starts_with(
"}");
1481 if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
1482 (PreviousMustBeValue ||
1483 Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
1484 tok::minusminus))) {
1485 return addUnwrappedLine();
1487 if ((PreviousMustBeValue ||
Previous->is(tok::r_paren)) &&
1489 return addUnwrappedLine();
1493void UnwrappedLineParser::parseStructuralElement(
1494 const FormatToken *OpeningBrace, IfStmtKind *IfKind,
1495 FormatToken **IfLeftBrace,
bool *HasDoWhile,
bool *HasLabel) {
1496 if (Style.isTableGen() && FormatTok->is(tok::pp_include)) {
1498 if (FormatTok->is(tok::string_literal))
1505 while (FormatTok->is(tok::l_square) && handleCppAttributes()) {
1507 }
else if (Style.isVerilog()) {
1509 while (FormatTok->is(tok::l_paren) &&
1510 Tokens->peekNextToken()->is(tok::star)) {
1513 skipVerilogQualifiers();
1515 if (FormatTok->isOneOf(Keywords.kw_priority, Keywords.kw_unique,
1516 Keywords.kw_unique0)) {
1520 if (Keywords.isVerilogStructuredProcedure(*FormatTok)) {
1521 parseForOrWhileLoop(
false);
1524 if (FormatTok->isOneOf(Keywords.kw_foreach, Keywords.kw_repeat)) {
1525 parseForOrWhileLoop();
1528 if (FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
1529 Keywords.kw_assume, Keywords.kw_cover)) {
1530 parseIfThenElse(IfKind,
false,
true);
1536 if (FormatTok->isAccessSpecifierKeyword()) {
1537 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp())
1540 parseAccessSpecifier();
1543 switch (FormatTok->Tok.getKind()) {
1548 bool DoNotFormat =
false;
1553 FormatTok->isOneOf(tok::kw_volatile, tok::kw_inline, tok::kw_goto)) {
1558 if (FormatTok->is(tok::l_brace)) {
1559 FormatTok->setFinalizedType(TT_InlineASMBrace);
1560 OpenType = tok::l_brace;
1561 CloseType = tok::r_brace;
1563 }
else if (FormatTok->is(tok::l_paren)) {
1564 OpenType = tok::l_paren;
1565 CloseType = tok::r_paren;
1566 FormatTok->setFinalizedType(TT_InlineASMParen);
1574 while (FormatTok && !
eof()) {
1575 if (FormatTok->is(OpenType)) {
1577 }
else if (FormatTok->is(CloseType)) {
1579 if (NestLevel < 1) {
1580 FormatTok->setFinalizedType(OpenTok->getType());
1586 FormatTok->Finalized =
true;
1592 case tok::kw_namespace:
1596 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1607 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1611 parseForOrWhileLoop();
1614 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1622 case tok::kw_switch:
1623 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1629 case tok::kw_default: {
1631 if (Style.isVerilog())
1633 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1639 if (FormatTok->is(tok::colon)) {
1640 FormatTok->setFinalizedType(TT_CaseLabelColon);
1644 if (FormatTok->is(tok::arrow)) {
1645 FormatTok->setFinalizedType(TT_CaseLabelArrow);
1646 Default->setFinalizedType(TT_SwitchExpressionLabel);
1659 if (Style.isVerilog()) {
1664 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1673 if (FormatTok->is(tok::kw_case))
1678 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1684 case tok::kw_extern:
1685 if (Style.isVerilog()) {
1688 parseVerilogExtern();
1692 if (FormatTok->is(tok::string_literal)) {
1694 if (FormatTok->is(tok::l_brace)) {
1695 if (Style.BraceWrapping.AfterExternBlock)
1699 unsigned AddLevels =
1701 (Style.BraceWrapping.AfterExternBlock &&
1702 Style.IndentExternBlock ==
1706 parseBlock(
true, AddLevels);
1712 case tok::kw_export:
1715 if (FormatTok->is(tok::kw_namespace)) {
1719 if (FormatTok->is(tok::l_brace)) {
1720 parseCppExportBlock();
1723 if (FormatTok->is(Keywords.kw_module) && parseModuleDecl())
1725 if (FormatTok->is(Keywords.kw_import) && parseImportDecl())
1729 if (Style.isJavaScript()) {
1730 parseJavaScriptEs6ImportExport();
1733 if (Style.isVerilog()) {
1734 parseVerilogExtern();
1738 case tok::kw_inline:
1740 if (FormatTok->is(tok::kw_namespace)) {
1745 case tok::identifier:
1746 if (FormatTok->is(TT_ForEachMacro)) {
1747 parseForOrWhileLoop();
1750 if (FormatTok->is(TT_MacroBlockBegin)) {
1751 parseBlock(
false, 1u,
1755 if (FormatTok->is(Keywords.kw_import)) {
1756 if (IsCpp && parseImportDecl())
1758 if (Style.isJavaScript()) {
1759 parseJavaScriptEs6ImportExport();
1764 if (FormatTok->is(tok::kw_public))
1766 if (FormatTok->isNot(tok::string_literal))
1769 if (FormatTok->is(tok::semi))
1774 if (Style.isVerilog()) {
1775 parseVerilogExtern();
1780 if (FormatTok->is(Keywords.kw_module) && parseModuleDecl())
1782 if (FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
1783 Keywords.kw_slots, Keywords.kw_qslots)) {
1785 if (FormatTok->is(tok::colon)) {
1791 if (FormatTok->is(TT_StatementMacro)) {
1792 parseStatementMacro();
1795 if (FormatTok->is(TT_NamespaceMacro)) {
1804 if (!Style.isJavaScript() && !Style.isVerilog() && !Style.isTableGen() &&
1805 Tokens->peekNextToken()->is(tok::colon) && !
Line->MustBeDeclaration) {
1807 if (!
Line->InMacroBody || CurrentLines->size() > 1)
1808 Line->Tokens.begin()->Tok->MustBreakBefore =
true;
1809 FormatTok->setFinalizedType(TT_GotoLabelColon);
1815 if (Style.isJava() && FormatTok->is(Keywords.kw_record)) {
1816 parseRecord(
false,
true);
1826 bool SeenEqual =
false;
1827 for (
const bool InRequiresExpression =
1828 OpeningBrace && OpeningBrace->isOneOf(TT_RequiresExpressionLBrace,
1829 TT_CompoundRequirementLBrace);
1832 switch (FormatTok->Tok.getKind()) {
1835 if (FormatTok->is(tok::l_brace)) {
1840 if (Style.isJava() && FormatTok->is(Keywords.kw_interface)) {
1844 switch (
bool IsAutoRelease =
false; FormatTok->Tok.getObjCKeywordID()) {
1845 case tok::objc_public:
1846 case tok::objc_protected:
1847 case tok::objc_package:
1848 case tok::objc_private:
1849 return parseAccessSpecifier();
1850 case tok::objc_interface:
1851 case tok::objc_implementation:
1852 return parseObjCInterfaceOrImplementation();
1853 case tok::objc_protocol:
1854 if (parseObjCProtocol())
1859 case tok::objc_optional:
1860 case tok::objc_required:
1864 case tok::objc_autoreleasepool:
1865 IsAutoRelease =
true;
1867 case tok::objc_synchronized:
1869 if (!IsAutoRelease && FormatTok->is(tok::l_paren)) {
1873 if (FormatTok->is(tok::l_brace)) {
1874 if (Style.BraceWrapping.AfterControlStatement ==
1891 case tok::kw_requires: {
1893 bool ParsedClause = parseRequires(SeenEqual);
1914 if (!IsCpp && !Style.isVerilog()) {
1919 case tok::kw_typedef:
1921 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1922 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS,
1923 Keywords.kw_CF_CLOSED_ENUM,
1924 Keywords.kw_NS_CLOSED_ENUM)) {
1929 if (Style.isVerilog()) {
1934 if (Style.isTableGen()) {
1941 case tok::kw_struct:
1943 if (parseStructLike())
1946 case tok::kw_decltype:
1948 if (FormatTok->is(tok::l_paren)) {
1950 if (FormatTok->Previous &&
1951 FormatTok->Previous->endsSequence(tok::r_paren, tok::kw_auto,
1953 Line->SeenDecltypeAuto =
true;
1960 if (Style.isJava() && FormatTok && FormatTok->is(tok::kw_class))
1962 if (Style.isJavaScript() && FormatTok &&
1963 FormatTok->Tok.getIdentifierInfo()) {
1976 case tok::string_literal:
1977 if (Style.isVerilog() && FormatTok->is(TT_VerilogProtected)) {
1978 FormatTok->Finalized =
true;
1985 case tok::l_paren: {
1992 Tokens->peekNextToken(
true),
1999 case tok::kw_operator:
2001 if (FormatTok->isBinaryOperator())
2005 const auto *Prev = FormatTok->getPreviousNonComment();
2007 if (Prev && Prev->is(tok::identifier))
2010 if (FormatTok->Tok.isAnyIdentifier() || FormatTok->isTypeName(LangOpts)) {
2013 if (FormatTok->is(tok::less)) {
2015 parseBracedList(
true);
2018 while (FormatTok->is(tok::star))
2022 if (FormatTok->is(tok::l_paren))
2025 if (FormatTok->is(tok::l_brace))
2030 if (InRequiresExpression)
2031 FormatTok->setFinalizedType(TT_BracedListLBrace);
2032 if (!tryToParsePropertyAccessor() && !tryToParseBracedList()) {
2033 IsDecltypeAutoFunction =
Line->SeenDecltypeAuto;
2038 if (Style.isJava() &&
2039 Line->Tokens.front().Tok->is(Keywords.kw_synchronized)) {
2042 if (Style.BraceWrapping.AfterControlStatement ==
2046 }
else if (Style.BraceWrapping.AfterFunction) {
2050 FormatTok->setFinalizedType(TT_FunctionLBrace);
2052 IsDecltypeAutoFunction =
false;
2060 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
2066 if (Style.BraceWrapping.AfterFunction)
2070 case tok::identifier: {
2071 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where) &&
2072 Line->MustBeDeclaration) {
2074 parseCSharpGenericTypeConstraint();
2077 if (FormatTok->is(TT_MacroBlockEnd)) {
2086 size_t TokenCount =
Line->Tokens.size();
2087 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_function) &&
2090 Line->Tokens.front().Tok->isNot(Keywords.kw_async)))) {
2091 tryToParseJSFunction();
2094 if ((Style.isJavaScript() || Style.isJava()) &&
2095 FormatTok->is(Keywords.kw_interface)) {
2096 if (Style.isJavaScript()) {
2101 unsigned StoredPosition = Tokens->getPosition();
2103 FormatTok = Tokens->setPosition(StoredPosition);
2114 if (Style.isVerilog()) {
2115 if (FormatTok->is(Keywords.kw_table)) {
2116 parseVerilogTable();
2119 if (Keywords.isVerilogBegin(*FormatTok) ||
2120 Keywords.isVerilogHierarchy(*FormatTok)) {
2127 if (!IsCpp && FormatTok->is(Keywords.kw_interface)) {
2128 if (parseStructLike())
2133 if (IsCpp && FormatTok->is(TT_StatementMacro)) {
2134 parseStatementMacro();
2139 StringRef
Text = FormatTok->TokenText;
2146 if (Style.isJavaScript())
2149 auto OneTokenSoFar = [&]() {
2150 auto I =
Line->Tokens.begin(), E =
Line->Tokens.end();
2151 while (I != E && I->Tok->is(tok::comment))
2153 if (Style.isVerilog())
2154 while (I != E && I->Tok->is(tok::hash))
2156 return I != E && (++I == E);
2158 if (OneTokenSoFar()) {
2161 bool FunctionLike = FormatTok->is(tok::l_paren);
2165 bool FollowedByNewline =
2166 CommentsBeforeNextToken.empty()
2167 ? FormatTok->NewlinesBefore > 0
2168 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
2170 if (FollowedByNewline &&
2171 (
Text.size() >= 5 ||
2172 (FunctionLike && FormatTok->isNot(tok::l_paren))) &&
2174 (!FormatTok->Previous ||
2175 FormatTok->Previous->isNot(TT_TrailingCommaVaOptRParen))) {
2176 if (PreviousToken->isNot(TT_UntouchableMacroFunc))
2177 PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro);
2185 if ((Style.isJavaScript() || Style.isCSharp()) &&
2186 FormatTok->is(TT_FatArrow)) {
2187 tryToParseChildBlock();
2193 if (FormatTok->is(tok::l_brace)) {
2197 if (!Style.isJavaScript())
2198 FormatTok->setBlockKind(BK_BracedInit);
2201 if (Style.isTableGen() &&
2202 Line->Tokens.begin()->Tok->is(Keywords.kw_defset)) {
2203 FormatTok->setFinalizedType(TT_FunctionLBrace);
2204 parseBlock(
false, 1u,
2212 FormatTok->is(tok::less)) {
2214 parseBracedList(
true);
2221 if ((Style.isCSharp() &&
2222 (Tokens->peekNextToken()->isAccessSpecifierKeyword() ||
2224 FormatTok->endsSequence(tok::kw_new, tok::kw_operator)) {
2230 case tok::kw_switch:
2243 if (Style.isVerilog()) {
2248 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
2255 case tok::kw_default:
2257 if (Style.isVerilog()) {
2258 if (FormatTok->is(tok::colon)) {
2262 if (FormatTok->is(Keywords.kw_clocking)) {
2268 parseVerilogCaseLabel();
2274 if (Style.isVerilog()) {
2275 parseVerilogCaseLabel();
2281 if (FormatTok->is(tok::l_brace))
2282 FormatTok->Previous->setFinalizedType(TT_TemplateCloser);
2291bool UnwrappedLineParser::tryToParsePropertyAccessor() {
2292 assert(FormatTok->is(tok::l_brace));
2293 if (!Style.isCSharp())
2296 if (!FormatTok->Previous || FormatTok->Previous->isNot(tok::identifier))
2304 unsigned int StoredPosition = Tokens->getPosition();
2310 bool HasSpecialAccessor =
false;
2311 bool IsTrivialPropertyAccessor =
true;
2314 if (
const bool IsAccessorKeyword =
2315 Tok->
isOneOf(Keywords.kw_get, Keywords.kw_init, Keywords.kw_set);
2316 IsAccessorKeyword ||
Tok->isAccessSpecifierKeyword() ||
2317 Tok->
isOneOf(tok::l_square, tok::semi, Keywords.kw_internal)) {
2318 if (IsAccessorKeyword)
2319 HasSpecialAccessor =
true;
2320 else if (
Tok->
is(tok::l_square))
2322 Tok = Tokens->getNextToken();
2326 IsTrivialPropertyAccessor =
false;
2331 Tokens->setPosition(StoredPosition);
2337 Tokens->setPosition(StoredPosition);
2338 if (!IsTrivialPropertyAccessor && Style.BraceWrapping.AfterFunction)
2342 switch (FormatTok->Tok.getKind()) {
2345 if (FormatTok->is(tok::equal)) {
2346 while (!
eof() && FormatTok->isNot(tok::semi))
2359 if (FormatTok->is(TT_FatArrow)) {
2363 }
while (!
eof() && FormatTok->isNot(tok::semi));
2372 if (FormatTok->isOneOf(Keywords.kw_get, Keywords.kw_init,
2374 !IsTrivialPropertyAccessor) {
2386bool UnwrappedLineParser::tryToParseLambda() {
2387 assert(FormatTok->is(tok::l_square));
2393 if (!tryToParseLambdaIntroducer())
2397 bool InTemplateParameterList =
false;
2399 while (FormatTok->isNot(tok::l_brace)) {
2400 if (FormatTok->isTypeName(LangOpts) || FormatTok->isAttribute()) {
2404 switch (FormatTok->Tok.getKind()) {
2408 parseParens(TT_PointerOrReference);
2414 assert(FormatTok->Previous);
2415 if (FormatTok->Previous->is(tok::r_square))
2416 InTemplateParameterList =
true;
2421 case tok::kw_struct:
2423 case tok::kw_template:
2424 case tok::kw_typename:
2428 case tok::kw_constexpr:
2429 case tok::kw_consteval:
2432 case tok::identifier:
2433 case tok::numeric_constant:
2434 case tok::coloncolon:
2435 case tok::kw_mutable:
2436 case tok::kw_noexcept:
2437 case tok::kw_static:
2462 case tok::equalequal:
2463 case tok::exclaimequal:
2464 case tok::greaterequal:
2465 case tok::lessequal:
2471 if (Arrow || InTemplateParameterList) {
2480 case tok::kw_requires:
2481 parseRequiresClause();
2484 if (!InTemplateParameterList)
2493 FormatTok->setFinalizedType(TT_LambdaLBrace);
2494 LSquare.setFinalizedType(TT_LambdaLSquare);
2497 Arrow->setFinalizedType(TT_LambdaArrow);
2499 NestedLambdas.push_back(
Line->SeenDecltypeAuto);
2501 assert(!NestedLambdas.empty());
2502 NestedLambdas.pop_back();
2507bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
2512 const auto *PrevPrev =
Previous->getPreviousNonComment();
2513 if (
Previous->is(tok::star) && PrevPrev && PrevPrev->isTypeName(LangOpts))
2516 Previous->isNot(TT_TrailingCommaVaOptRParen)) {
2522 if (!PrevPrev || PrevPrev->isNoneOf(tok::greater, tok::r_paren))
2526 Previous->isNoneOf(tok::kw_return, tok::kw_co_await, tok::kw_co_yield,
2527 tok::kw_co_return)) {
2531 if (LeftSquare->isCppStructuredBinding(IsCpp))
2533 if (FormatTok->is(tok::l_square) ||
tok::isLiteral(FormatTok->Tok.getKind()))
2535 if (FormatTok->is(tok::r_square)) {
2537 if (
Next->is(tok::greater))
2544void UnwrappedLineParser::tryToParseJSFunction() {
2545 assert(FormatTok->is(Keywords.kw_function));
2546 if (FormatTok->is(Keywords.kw_async))
2552 if (FormatTok->is(tok::star)) {
2553 FormatTok->setFinalizedType(TT_OverloadedOperator);
2558 if (FormatTok->is(tok::identifier))
2561 if (FormatTok->isNot(tok::l_paren))
2567 if (FormatTok->is(tok::colon)) {
2573 if (FormatTok->is(tok::l_brace))
2574 tryToParseBracedList();
2576 while (FormatTok->isNoneOf(tok::l_brace, tok::semi) && !
eof())
2580 if (FormatTok->is(tok::semi))
2586bool UnwrappedLineParser::tryToParseBracedList() {
2587 if (FormatTok->is(BK_Unknown))
2588 calculateBraceTypes();
2589 assert(FormatTok->isNot(BK_Unknown));
2590 if (FormatTok->is(BK_Block))
2597bool UnwrappedLineParser::tryToParseChildBlock() {
2598 assert(Style.isJavaScript() || Style.isCSharp());
2599 assert(FormatTok->is(TT_FatArrow));
2604 if (FormatTok->isNot(tok::l_brace))
2610bool UnwrappedLineParser::parseBracedList(
bool IsAngleBracket,
bool IsEnum) {
2611 assert(!IsAngleBracket || !IsEnum);
2612 bool HasError =
false;
2617 if (Style.isCSharp() && FormatTok->is(TT_FatArrow) &&
2618 tryToParseChildBlock()) {
2621 if (Style.isJavaScript()) {
2622 if (FormatTok->is(Keywords.kw_function)) {
2623 tryToParseJSFunction();
2626 if (FormatTok->is(tok::l_brace)) {
2628 if (tryToParseBracedList())
2633 if (FormatTok->is(IsAngleBracket ? tok::greater : tok::r_brace)) {
2635 FormatTok->setBlockKind(BK_Block);
2636 if (!Style.AllowShortEnumsOnASingleLine)
2642 switch (FormatTok->Tok.getKind()) {
2644 if (Style.isCSharp())
2653 if (Style.isJavaScript()) {
2654 if (FormatTok->is(tok::l_brace))
2658 if (IsEnum && !Style.AllowShortEnumsOnASingleLine &&
2659 FormatTok->Previous &&
2660 FormatTok->Previous->is(TT_TrailingCommaVaOptRParen)) {
2667 FormatTok->setBlockKind(BK_BracedInit);
2668 if (!IsAngleBracket) {
2669 auto *Prev = FormatTok->Previous;
2670 if (Prev && Prev->is(tok::greater))
2671 Prev->setFinalizedType(TT_TemplateCloser);
2679 parseBracedList(
true);
2687 if (Style.isJavaScript() || Style.isProto() || Style.isJson()) {
2698 if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
2701 case tok::kw_requires:
2702 parseRequiresExpression();
2719bool UnwrappedLineParser::parseParens(TokenType StarAndAmpTokenType,
2721 assert(FormatTok->is(tok::l_paren) &&
"'(' expected.");
2722 auto *LParen = FormatTok;
2723 auto *Prev = FormatTok->Previous;
2724 bool SeenComma =
false;
2725 bool SeenEqual =
false;
2726 bool MightBeFoldExpr =
false;
2727 unsigned ExcessLess = 0;
2729 const bool MightBeStmtExpr = FormatTok->is(tok::l_brace);
2730 if (!InMacroCall && Prev && Prev->is(TT_FunctionLikeMacro))
2733 switch (FormatTok->Tok.getKind()) {
2735 if (parseParens(ExcessLess == 0 ? StarAndAmpTokenType : TT_Unknown,
2739 if (Style.isJava() && FormatTok->is(tok::l_brace))
2742 case tok::r_paren: {
2743 auto *RParen = FormatTok;
2746 auto OptionalParens = [&] {
2748 MightBeStmtExpr || MightBeFoldExpr || SeenComma || InMacroCall ||
2749 Line->InMacroBody || RParen->getPreviousNonComment() == LParen) {
2752 const bool DoubleParens =
2753 Prev->is(tok::l_paren) && FormatTok->is(tok::r_paren);
2755 const auto *PrevPrev = Prev->getPreviousNonComment();
2756 const bool Excluded =
2758 (PrevPrev->isOneOf(tok::kw___attribute, tok::kw_decltype) ||
2760 (PrevPrev->isOneOf(tok::kw_if, tok::kw_while) ||
2761 PrevPrev->endsSequence(tok::kw_constexpr, tok::kw_if))));
2765 const bool CommaSeparated =
2766 Prev->isOneOf(tok::l_paren, tok::comma) &&
2767 FormatTok->isOneOf(tok::comma, tok::r_paren);
2768 if (CommaSeparated &&
2770 !Prev->endsSequence(tok::comma, tok::ellipsis) &&
2772 !(FormatTok->is(tok::comma) &&
2773 Tokens->peekNextToken()->is(tok::ellipsis))) {
2776 const bool ReturnParens =
2778 ((NestedLambdas.empty() && !IsDecltypeAutoFunction) ||
2779 (!NestedLambdas.empty() && !NestedLambdas.back())) &&
2780 Prev->isOneOf(tok::kw_return, tok::kw_co_return) &&
2781 FormatTok->is(tok::semi);
2787 if (OptionalParens()) {
2788 LParen->Optional =
true;
2789 RParen->Optional =
true;
2790 }
else if (Prev->is(TT_TypenameMacro)) {
2791 LParen->setFinalizedType(TT_TypeDeclarationParen);
2792 RParen->setFinalizedType(TT_TypeDeclarationParen);
2793 }
else if (IsCpp && Prev->is(Keywords.kw___VA_OPT__) &&
2794 Prev->is(TT_Unknown) && RParen->Previous->is(tok::comma) &&
2795 RParen->Previous->Previous->isNot(tok::kw_operator)) {
2797 RParen->setFinalizedType(TT_TrailingCommaVaOptRParen);
2798 }
else if (Prev->is(tok::greater) && RParen->Previous == LParen) {
2799 Prev->setFinalizedType(TT_TemplateCloser);
2800 }
else if (FormatTok->is(tok::l_brace) && Prev->is(tok::amp) &&
2802 FormatTok->setBlockKind(BK_BracedInit);
2814 if (!tryToParseBracedList())
2819 if (FormatTok->is(tok::l_brace)) {
2829 MightBeFoldExpr =
true;
2834 if (Style.isCSharp() && FormatTok->is(TT_FatArrow))
2835 tryToParseChildBlock();
2840 if (Style.isJavaScript())
2845 case tok::identifier:
2846 if (Style.isJavaScript() && (FormatTok->is(Keywords.kw_function)))
2847 tryToParseJSFunction();
2851 case tok::kw_switch:
2857 case tok::kw_requires:
2858 parseRequiresExpression();
2874 if (StarAndAmpTokenType != TT_Unknown && ExcessLess == 0)
2875 FormatTok->setFinalizedType(StarAndAmpTokenType);
2885void UnwrappedLineParser::parseSquare(
bool SkipLambda) {
2887 assert(FormatTok->is(tok::l_square) &&
"'[' expected.");
2888 if (tryToParseLambda())
2892 switch (FormatTok->Tok.getKind()) {
2905 case tok::l_brace: {
2906 if (!tryToParseBracedList())
2913 if (FormatTok->is(tok::l_brace)) {
2925void UnwrappedLineParser::keepAncestorBraces() {
2926 if (!Style.RemoveBracesLLVM)
2929 const int MaxNestingLevels = 2;
2930 const int Size = NestedTooDeep.size();
2931 if (Size >= MaxNestingLevels)
2932 NestedTooDeep[
Size - MaxNestingLevels] =
true;
2933 NestedTooDeep.push_back(
false);
2937 for (
const auto &
Token : llvm::reverse(
Line.Tokens))
2945 return llvm::any_of(
2946 llvm::drop_begin(
Line.Tokens),
2952bool UnwrappedLineParser::isFollowedByConditionalElse()
const {
2955 if (!
Line->Tokens.empty()) {
2958 for (
const auto &PreviousLine : llvm::reverse(*CurrentLines)) {
2959 if (!PreviousLine.InPPDirective) {
2960 Last = PreviousLine.Tokens.back().Tok;
2970 llvm::lower_bound(AllTokens,
Last->Tok.getLocation(),
2972 return Tok->Tok.getLocation() < Loc;
2974 if (It == AllTokens.end() || *It !=
Last)
2980 size_t UnreachableDepth = 0;
2981 bool IsFirstOnLine =
false;
2982 bool IsFirstAfterDirective =
false;
2983 for (++It; It != AllTokens.end(); ++It) {
2984 const auto &
Tok = **It;
2985 if (
Tok.HasUnescapedNewline)
2986 IsFirstOnLine =
true;
2987 if (
Tok.
is(tok::comment))
2989 if (
Tok.
is(tok::hash) && IsFirstOnLine) {
2991 for (
const auto *
Next = std::next(It);
2992 Next != AllTokens.end() && !(*Next)->HasUnescapedNewline;
2994 if ((*Next)->isNot(tok::comment))
3001 const auto IsLiteral = [&](
bool Value) {
3002 if (
Keyword.isNoneOf(tok::pp_if, tok::pp_elif) ||
3012 if (
Keyword.isOneOf(tok::pp_if, tok::pp_ifdef, tok::pp_ifndef)) {
3013 Conditionals.push_back(IsLiteral(
true));
3014 if (UnreachableDepth == 0 && IsLiteral(
false))
3015 UnreachableDepth = Conditionals.size();
3016 }
else if (
Keyword.is(tok::pp_endif)) {
3017 if (Conditionals.size() == UnreachableDepth)
3018 UnreachableDepth = 0;
3019 if (!Conditionals.empty())
3020 Conditionals.pop_back();
3021 }
else if (
Keyword.isOneOf(tok::pp_else, tok::pp_elif, tok::pp_elifdef,
3022 tok::pp_elifndef)) {
3023 if (Conditionals.size() == UnreachableDepth)
3024 UnreachableDepth = 0;
3026 if (Conditionals.empty())
3027 Conditionals.push_back(
false);
3028 if (UnreachableDepth == 0 &&
3029 (Conditionals.back() || IsLiteral(
false))) {
3030 UnreachableDepth = Conditionals.size();
3031 }
else if (IsLiteral(
true)) {
3032 Conditionals.back() =
true;
3036 IsFirstAfterDirective =
true;
3039 IsFirstOnLine =
false;
3040 if (UnreachableDepth > 0)
3043 if (IsFirstAfterDirective &&
Tok.
is(tok::kw_else))
3046 if (Conditionals.empty())
3048 IsFirstAfterDirective =
false;
3053void UnwrappedLineParser::parseUnbracedBody(
bool CheckEOF) {
3056 if (Style.InsertBraces && !
Line->InPPDirective && !
Line->Tokens.empty() &&
3062 if (
Tok->BraceCount < 0) {
3063 assert(
Tok->BraceCount == -1);
3066 Tok->BraceCount = -1;
3071 const auto BodyStart = CurrentLines->size();
3073 ++
Line->UnbracedBodyLevel;
3074 parseStructuralElement();
3075 --
Line->UnbracedBodyLevel;
3078 assert(!
Line->InPPDirective);
3081 auto BodyEnd = CurrentLines->size();
3082 while (BodyEnd > 0) {
3083 const auto &L = (*CurrentLines)[--BodyEnd];
3085 Tok = L.Tokens.back().Tok;
3091 bool EnclosesPPDirective =
false;
3092 for (
size_t I = BodyStart; I <= BodyEnd && !EnclosesPPDirective; ++I) {
3093 const auto &BodyLine = (*CurrentLines)[I];
3094 EnclosesPPDirective =
3095 BodyLine.InPPDirective ||
3096 llvm::any_of(BodyLine.Tokens, [](
const UnwrappedLineNode &Node) {
3097 return Node.Tok->FirstAfterPPLine;
3100 if (EnclosesPPDirective || FormatTok == TokenAfterIfWithConditionalElse)
3101 LBraceTok->BraceCount = 0;
3106 if (CheckEOF &&
eof())
3116 assert(LeftBrace->
is(tok::l_brace));
3124 assert(RightBrace->
is(tok::r_brace));
3132void UnwrappedLineParser::handleAttributes() {
3134 if (FormatTok->isAttribute())
3136 else if (FormatTok->is(tok::l_square))
3137 handleCppAttributes();
3140bool UnwrappedLineParser::handleCppAttributes() {
3142 assert(FormatTok->is(tok::l_square));
3143 if (!tryToParseSimpleAttribute())
3150bool UnwrappedLineParser::isBlockBegin(
const FormatToken &
Tok)
const {
3153 return Style.isVerilog() ? Keywords.isVerilogBegin(
Tok)
3154 :
Tok.
is(tok::l_brace);
3157FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
3159 bool IsVerilogAssert) {
3160 assert((FormatTok->is(tok::kw_if) ||
3161 (Style.isVerilog() &&
3162 FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
3163 Keywords.kw_assume, Keywords.kw_cover))) &&
3167 if (IsVerilogAssert) {
3169 if (FormatTok->is(Keywords.kw_verilogHash)) {
3171 if (FormatTok->is(tok::numeric_constant))
3173 }
else if (FormatTok->isOneOf(Keywords.kw_final, Keywords.kw_property,
3174 Keywords.kw_sequence)) {
3180 if (Style.isTableGen()) {
3181 while (!
eof() && FormatTok->isNot(Keywords.kw_then)) {
3188 if (FormatTok->is(tok::exclaim))
3191 bool KeepIfBraces =
true;
3192 if (FormatTok->is(tok::kw_consteval)) {
3195 KeepIfBraces = !Style.RemoveBracesLLVM || KeepBraces;
3196 if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
3198 if (FormatTok->is(tok::l_paren)) {
3199 FormatTok->setFinalizedType(TT_ConditionLParen);
3205 if (IsVerilogAssert && FormatTok->is(tok::semi)) {
3211 bool NeedsUnwrappedLine =
false;
3212 keepAncestorBraces();
3215 IfStmtKind IfBlockKind = IfStmtKind::NotIf;
3217 if (isBlockBegin(*FormatTok)) {
3218 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3219 IfLeftBrace = FormatTok;
3220 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3221 parseBlock(
false, 1u,
3222 true, KeepIfBraces, &IfBlockKind);
3223 setPreviousRBraceType(TT_ControlStatementRBrace);
3224 if (Style.BraceWrapping.BeforeElse)
3227 NeedsUnwrappedLine =
true;
3228 }
else if (IsVerilogAssert && FormatTok->is(tok::kw_else)) {
3231 parseUnbracedBody();
3234 if (Style.RemoveBracesLLVM) {
3235 assert(!NestedTooDeep.empty());
3236 KeepIfBraces = KeepIfBraces ||
3237 (IfLeftBrace && !IfLeftBrace->MatchingParen) ||
3238 NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly ||
3239 IfBlockKind == IfStmtKind::IfElseIf;
3242 bool KeepElseBraces = KeepIfBraces;
3244 IfStmtKind
Kind = IfStmtKind::IfOnly;
3246 if (FormatTok->is(tok::kw_else)) {
3247 if (Style.RemoveBracesLLVM) {
3248 NestedTooDeep.back() =
false;
3249 Kind = IfStmtKind::IfElse;
3253 if (isBlockBegin(*FormatTok)) {
3254 const bool FollowedByIf = Tokens->peekNextToken()->is(tok::kw_if);
3255 FormatTok->setFinalizedType(TT_ElseLBrace);
3256 ElseLeftBrace = FormatTok;
3257 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3258 IfStmtKind ElseBlockKind = IfStmtKind::NotIf;
3260 parseBlock(
false, 1u,
3261 true, KeepElseBraces, &ElseBlockKind);
3262 setPreviousRBraceType(TT_ElseRBrace);
3263 if (FormatTok->is(tok::kw_else)) {
3264 KeepElseBraces = KeepElseBraces ||
3265 ElseBlockKind == IfStmtKind::IfOnly ||
3266 ElseBlockKind == IfStmtKind::IfElseIf;
3267 }
else if (FollowedByIf && IfLBrace && !IfLBrace->Optional) {
3268 KeepElseBraces =
true;
3269 assert(ElseLeftBrace->MatchingParen);
3273 }
else if (!IsVerilogAssert && FormatTok->is(tok::kw_if)) {
3276 const bool IsPrecededByComment =
Previous->is(tok::comment);
3277 if (IsPrecededByComment) {
3281 bool TooDeep =
true;
3282 if (Style.RemoveBracesLLVM) {
3283 Kind = IfStmtKind::IfElseIf;
3284 TooDeep = NestedTooDeep.pop_back_val();
3286 ElseLeftBrace = parseIfThenElse(
nullptr, KeepIfBraces);
3287 if (Style.RemoveBracesLLVM)
3288 NestedTooDeep.push_back(TooDeep);
3289 if (IsPrecededByComment)
3292 parseUnbracedBody(
true);
3295 if (Style.InsertBraces && isFollowedByConditionalElse())
3296 TokenAfterIfWithConditionalElse = FormatTok;
3297 KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse;
3298 if (NeedsUnwrappedLine)
3302 if (!Style.RemoveBracesLLVM)
3305 assert(!NestedTooDeep.empty());
3306 KeepElseBraces = KeepElseBraces ||
3307 (ElseLeftBrace && !ElseLeftBrace->MatchingParen) ||
3308 NestedTooDeep.back();
3310 NestedTooDeep.pop_back();
3312 if (!KeepIfBraces && !KeepElseBraces) {
3315 }
else if (IfLeftBrace) {
3316 FormatToken *IfRightBrace = IfLeftBrace->MatchingParen;
3318 assert(IfRightBrace->MatchingParen == IfLeftBrace);
3319 assert(!IfLeftBrace->Optional);
3320 assert(!IfRightBrace->Optional);
3321 IfLeftBrace->MatchingParen =
nullptr;
3322 IfRightBrace->MatchingParen =
nullptr;
3332void UnwrappedLineParser::parseTryCatch() {
3333 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) &&
"'try' expected");
3335 bool NeedsUnwrappedLine =
false;
3336 bool HasCtorInitializer =
false;
3337 if (FormatTok->is(tok::colon)) {
3338 auto *Colon = FormatTok;
3341 if (FormatTok->is(tok::identifier)) {
3342 HasCtorInitializer =
true;
3343 Colon->setFinalizedType(TT_CtorInitializerColon);
3348 while (FormatTok->is(tok::comma))
3351 while (FormatTok->is(tok::identifier)) {
3353 if (FormatTok->is(tok::l_paren)) {
3355 }
else if (FormatTok->is(tok::l_brace)) {
3362 while (FormatTok->is(tok::comma))
3367 if (Style.isJava() && FormatTok->is(tok::l_paren))
3370 keepAncestorBraces();
3372 if (FormatTok->is(tok::l_brace)) {
3373 if (HasCtorInitializer)
3374 FormatTok->setFinalizedType(TT_FunctionLBrace);
3375 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3377 if (Style.BraceWrapping.BeforeCatch)
3380 NeedsUnwrappedLine =
true;
3381 }
else if (FormatTok->isNot(tok::kw_catch)) {
3387 parseStructuralElement();
3390 for (
bool SeenCatch =
false;;) {
3391 if (FormatTok->is(tok::at))
3393 if (FormatTok->isNoneOf(tok::kw_catch, Keywords.kw___except,
3394 tok::kw___finally, tok::objc_catch,
3395 tok::objc_finally) &&
3396 !((Style.isJava() || Style.isJavaScript()) &&
3397 FormatTok->is(Keywords.kw_finally))) {
3400 if (FormatTok->is(tok::kw_catch))
3403 while (FormatTok->isNot(tok::l_brace)) {
3404 if (FormatTok->is(tok::l_paren)) {
3408 if (FormatTok->isOneOf(tok::semi, tok::r_brace) ||
eof()) {
3409 if (Style.RemoveBracesLLVM)
3410 NestedTooDeep.pop_back();
3416 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3419 NeedsUnwrappedLine =
false;
3420 Line->MustBeDeclaration =
false;
3421 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3423 if (Style.BraceWrapping.BeforeCatch)
3426 NeedsUnwrappedLine =
true;
3429 if (Style.RemoveBracesLLVM)
3430 NestedTooDeep.pop_back();
3432 if (NeedsUnwrappedLine)
3436void UnwrappedLineParser::parseNamespaceOrExportBlock(
unsigned AddLevels) {
3437 bool ManageWhitesmithsBraces =
3442 if (ManageWhitesmithsBraces)
3447 parseBlock(
true, AddLevels,
true,
3448 true,
nullptr, ManageWhitesmithsBraces);
3450 addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep);
3452 if (ManageWhitesmithsBraces)
3456void UnwrappedLineParser::parseNamespace() {
3457 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
3458 "'namespace' expected");
3462 if (InitialToken.is(TT_NamespaceMacro)) {
3465 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
3466 tok::l_square, tok::period, tok::l_paren) ||
3467 (Style.isCSharp() && FormatTok->is(tok::kw_union))) {
3468 if (FormatTok->is(tok::l_square))
3470 else if (FormatTok->is(tok::l_paren))
3476 if (FormatTok->is(tok::l_brace)) {
3477 FormatTok->setFinalizedType(TT_NamespaceLBrace);
3480 Tokens->peekNextToken()->is(tok::r_brace))) {
3484 unsigned AddLevels =
3487 DeclarationScopeStack.size() > 1)
3490 parseNamespaceOrExportBlock(AddLevels);
3495void UnwrappedLineParser::parseCppExportBlock() {
3496 if (FormatTok->is(tok::l_brace)) {
3497 FormatTok->setFinalizedType(TT_ExportLBrace);
3498 if (Style.BraceWrapping.AfterExportBlock)
3501 parseNamespaceOrExportBlock(Style.IndentExportBlock ? 1 : 0);
3504void UnwrappedLineParser::parseNew() {
3505 assert(FormatTok->is(tok::kw_new) &&
"'new' expected");
3508 if (Style.isCSharp()) {
3511 if (FormatTok->is(tok::l_paren))
3515 if (FormatTok->is(tok::l_brace))
3518 if (FormatTok->isOneOf(tok::semi, tok::comma))
3523 }
else if (Style.isJava()) {
3527 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
3531 if (FormatTok->is(tok::l_paren)) {
3536 if (FormatTok->is(tok::l_brace))
3542 }
else if (Style.isCpp()) {
3546 if (FormatTok->is(tok::l_brace))
3548 if (FormatTok->is(tok::l_paren))
3550 if (FormatTok->is(tok::l_paren)) {
3556 if (FormatTok->isOneOf(tok::kw_alignas, tok::kw_decltype)) {
3558 if (FormatTok->is(tok::l_paren))
3560 }
else if (FormatTok->is(tok::l_square)) {
3563 }
else if (FormatTok->is(tok::less)) {
3565 parseBracedList(
true);
3566 }
else if (FormatTok->Tok.getIdentifierInfo() ||
3567 FormatTok->isOneOf(tok::coloncolon, tok::star)) {
3574 if (FormatTok->is(tok::l_brace))
3576 else if (FormatTok->is(tok::l_paren))
3581void UnwrappedLineParser::parseLoopBody(
bool KeepBraces,
bool WrapRightBrace) {
3582 keepAncestorBraces();
3584 if (isBlockBegin(*FormatTok)) {
3585 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3587 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3588 parseBlock(
false, 1u,
3590 setPreviousRBraceType(TT_ControlStatementRBrace);
3592 assert(!NestedTooDeep.empty());
3593 if (!NestedTooDeep.back())
3599 parseUnbracedBody();
3603 NestedTooDeep.pop_back();
3606void UnwrappedLineParser::parseForOrWhileLoop(
bool HasParens) {
3607 assert((FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) ||
3608 (Style.isVerilog() &&
3609 FormatTok->isOneOf(Keywords.kw_always, Keywords.kw_always_comb,
3610 Keywords.kw_always_ff, Keywords.kw_always_latch,
3611 Keywords.kw_final, Keywords.kw_initial,
3612 Keywords.kw_foreach, Keywords.kw_forever,
3613 Keywords.kw_repeat))) &&
3614 "'for', 'while' or foreach macro expected");
3615 const bool KeepBraces = !Style.RemoveBracesLLVM ||
3616 FormatTok->isNoneOf(tok::kw_for, tok::kw_while);
3620 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
3622 if (IsCpp && FormatTok->is(tok::kw_co_await))
3624 if (HasParens && FormatTok->is(tok::l_paren)) {
3628 if (Style.isVerilog())
3629 FormatTok->setFinalizedType(TT_ConditionLParen);
3633 if (Style.isVerilog()) {
3635 parseVerilogSensitivityList();
3636 }
else if (Style.AllowShortLoopsOnASingleLine && FormatTok->is(tok::semi) &&
3637 Tokens->getPreviousToken()->is(tok::r_paren)) {
3644 parseLoopBody(KeepBraces,
true);
3647void UnwrappedLineParser::parseDoWhile() {
3648 assert(FormatTok->is(tok::kw_do) &&
"'do' expected");
3651 parseLoopBody(
true, Style.BraceWrapping.BeforeWhile);
3654 if (FormatTok->isNot(tok::kw_while)) {
3659 FormatTok->setFinalizedType(TT_DoWhile);
3667 parseStructuralElement();
3670void UnwrappedLineParser::parseLabel(
bool IsGotoLabel) {
3673 const auto IndentGotoLabel = Style.IndentGotoLabels;
3674 const auto OldLineLevel =
Line->Level;
3681 if (OldLineLevel > 1 || (!
Line->InPPDirective && OldLineLevel > 0))
3685 if (!IsGotoLabel && !Style.IndentCaseBlocks &&
3686 CommentsBeforeNextToken.empty() && FormatTok->is(tok::l_brace)) {
3687 CompoundStatementIndenter Indenter(
this,
Level,
3688 Style.BraceWrapping.AfterCaseLabel,
3689 Style.BraceWrapping.IndentBraces);
3691 if (FormatTok->is(tok::kw_break)) {
3692 if (Style.BraceWrapping.AfterControlStatement ==
3694 Style.CompactCaseLabels) {
3696 if (!Style.IndentCaseBlocks &&
3701 parseStructuralElement();
3705 if (FormatTok->is(tok::semi))
3710 Level = OldLineLevel;
3712 if (FormatTok->isNot(tok::l_brace)) {
3713 parseStructuralElement();
3718void UnwrappedLineParser::parseCaseLabel() {
3719 assert(FormatTok->is(tok::kw_case) &&
"'case' expected");
3720 auto *Case = FormatTok;
3725 if (FormatTok->is(tok::colon)) {
3726 FormatTok->setFinalizedType(TT_CaseLabelColon);
3729 if (Style.isJava() && FormatTok->is(tok::arrow)) {
3730 FormatTok->setFinalizedType(TT_CaseLabelArrow);
3731 Case->setFinalizedType(TT_SwitchExpressionLabel);
3738void UnwrappedLineParser::parseSwitch(
bool IsExpr) {
3739 assert(FormatTok->is(tok::kw_switch) &&
"'switch' expected");
3741 if (FormatTok->is(tok::l_paren))
3744 keepAncestorBraces();
3746 if (FormatTok->is(tok::l_brace)) {
3747 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3748 FormatTok->setFinalizedType(IsExpr ? TT_SwitchExpressionLBrace
3749 : TT_ControlStatementLBrace);
3754 setPreviousRBraceType(TT_ControlStatementRBrace);
3760 parseStructuralElement();
3764 if (Style.RemoveBracesLLVM)
3765 NestedTooDeep.pop_back();
3768void UnwrappedLineParser::parseAccessSpecifier() {
3771 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
3774 if (FormatTok->is(tok::colon))
3782bool UnwrappedLineParser::parseRequires(
bool SeenEqual) {
3783 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3787 switch (Tokens->peekNextToken(
true)->Tok.getKind()) {
3790 parseRequiresExpression();
3797 parseRequiresClause();
3808 auto *PreviousNonComment = FormatTok->getPreviousNonComment();
3810 if (!PreviousNonComment ||
3811 PreviousNonComment->is(TT_RequiresExpressionLBrace)) {
3814 parseRequiresClause();
3818 switch (PreviousNonComment->Tok.getKind()) {
3821 case tok::kw_noexcept:
3826 parseRequiresClause();
3835 auto PrevPrev = PreviousNonComment->getPreviousNonComment();
3836 if ((PrevPrev && PrevPrev->is(tok::kw_const)) || !SeenEqual) {
3837 parseRequiresClause();
3843 if (PreviousNonComment->isTypeOrIdentifier(LangOpts)) {
3845 parseRequiresClause();
3849 parseRequiresExpression();
3859 unsigned StoredPosition = Tokens->getPosition();
3862 auto PeekNext = [&Lookahead, &NextToken,
this] {
3864 NextToken = Tokens->getNextToken();
3867 bool FoundType =
false;
3868 bool LastWasColonColon =
false;
3871 for (; Lookahead < 50; PeekNext()) {
3872 switch (NextToken->Tok.getKind()) {
3873 case tok::kw_volatile:
3876 if (OpenAngles == 0) {
3877 FormatTok = Tokens->setPosition(StoredPosition);
3878 parseRequiresExpression();
3886 case tok::coloncolon:
3887 LastWasColonColon =
true;
3889 case tok::kw_decltype:
3890 case tok::identifier:
3891 if (FoundType && !LastWasColonColon && OpenAngles == 0) {
3892 FormatTok = Tokens->setPosition(StoredPosition);
3893 parseRequiresExpression();
3897 LastWasColonColon =
false;
3906 if (NextToken->isTypeName(LangOpts)) {
3907 FormatTok = Tokens->setPosition(StoredPosition);
3908 parseRequiresExpression();
3915 FormatTok = Tokens->setPosition(StoredPosition);
3916 parseRequiresClause();
3925void UnwrappedLineParser::parseRequiresClause() {
3926 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3931 bool InRequiresExpression =
3932 !FormatTok->Previous ||
3933 FormatTok->Previous->is(TT_RequiresExpressionLBrace);
3935 FormatTok->setFinalizedType(InRequiresExpression
3936 ? TT_RequiresClauseInARequiresExpression
3937 : TT_RequiresClause);
3942 parseConstraintExpression();
3944 if (!InRequiresExpression && FormatTok->Previous)
3945 FormatTok->Previous->ClosesRequiresClause =
true;
3953void UnwrappedLineParser::parseRequiresExpression() {
3954 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3956 FormatTok->setFinalizedType(TT_RequiresExpression);
3959 if (FormatTok->is(tok::l_paren)) {
3960 FormatTok->setFinalizedType(TT_RequiresExpressionLParen);
3964 if (FormatTok->is(tok::l_brace)) {
3965 FormatTok->setFinalizedType(TT_RequiresExpressionLBrace);
3974void UnwrappedLineParser::parseConstraintExpression() {
3981 bool LambdaNextTimeAllowed =
true;
3991 bool TopLevelParensAllowed =
true;
3994 bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed,
false);
3996 switch (FormatTok->Tok.getKind()) {
3997 case tok::kw_requires:
3998 parseRequiresExpression();
4002 if (!TopLevelParensAllowed)
4004 parseParens(TT_BinaryOperator);
4005 TopLevelParensAllowed =
false;
4009 if (!LambdaThisTimeAllowed || !tryToParseLambda())
4016 case tok::kw_struct:
4026 FormatTok->setFinalizedType(TT_BinaryOperator);
4028 LambdaNextTimeAllowed =
true;
4029 TopLevelParensAllowed =
true;
4034 LambdaNextTimeAllowed = LambdaThisTimeAllowed;
4038 case tok::kw_sizeof:
4040 case tok::greaterequal:
4041 case tok::greatergreater:
4043 case tok::lessequal:
4045 case tok::equalequal:
4047 case tok::exclaimequal:
4052 LambdaNextTimeAllowed =
true;
4053 TopLevelParensAllowed =
true;
4058 case tok::numeric_constant:
4059 case tok::coloncolon:
4062 TopLevelParensAllowed =
false;
4067 case tok::kw_static_cast:
4068 case tok::kw_const_cast:
4069 case tok::kw_reinterpret_cast:
4070 case tok::kw_dynamic_cast:
4072 if (FormatTok->isNot(tok::less))
4076 parseBracedList(
true);
4080 if (!FormatTok->Tok.getIdentifierInfo()) {
4090 assert(FormatTok->Previous);
4091 switch (FormatTok->Previous->Tok.getKind()) {
4092 case tok::coloncolon:
4096 case tok::kw_requires:
4098 case tok::kw_template:
4106 if (FormatTok->is(tok::less)) {
4108 parseBracedList(
true);
4110 TopLevelParensAllowed =
false;
4116bool UnwrappedLineParser::parseEnum() {
4120 if (FormatTok->is(tok::kw_enum))
4126 if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question))
4134 if (IsCpp && FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
4137 while (FormatTok->Tok.getIdentifierInfo() ||
4138 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
4139 tok::greater, tok::comma, tok::question,
4141 if (FormatTok->is(TT_AttributeMacro)) {
4145 if (IsCpp && FormatTok->is(tok::l_square)) {
4146 if (handleCppAttributes())
4150 if (FormatTok->is(tok::colon))
4151 FormatTok->setFinalizedType(TT_EnumUnderlyingTypeColon);
4152 if (Style.isVerilog()) {
4153 FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
4156 while (FormatTok->is(tok::l_square))
4162 if (FormatTok->is(tok::l_paren)) {
4166 if (FormatTok->is(tok::identifier)) {
4170 if (IsCpp && FormatTok->is(tok::identifier))
4176 if (FormatTok->isNot(tok::l_brace))
4178 FormatTok->setFinalizedType(TT_EnumLBrace);
4179 FormatTok->setBlockKind(BK_Block);
4181 if (Style.isJava()) {
4183 parseJavaEnumBody();
4191 const bool ManageWhitesmithsBraces =
4194 if (!Style.AllowShortEnumsOnASingleLine &&
4196 Tokens->peekNextToken()->is(tok::r_brace))) {
4201 if (ManageWhitesmithsBraces)
4206 if (!Style.AllowShortEnumsOnASingleLine) {
4208 if (!ManageWhitesmithsBraces)
4211 const auto OpeningLineIndex =
4212 CurrentLines->empty() || !CurrentExpandedLines.empty()
4213 ? UnwrappedLine::kInvalidIndex
4214 : CurrentLines->size() - 1;
4215 bool HasError = !parseBracedList(
false,
true);
4216 if (!Style.AllowShortEnumsOnASingleLine && !ManageWhitesmithsBraces)
4219 if (FormatTok->is(tok::semi))
4223 setPreviousRBraceType(TT_EnumRBrace);
4224 if (ManageWhitesmithsBraces && CurrentExpandedLines.empty() &&
4225 !containsExpansion(*
Line)) {
4226 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
4235bool UnwrappedLineParser::parseStructLike() {
4240 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp()) {
4241 if (FormatTok->is(tok::semi))
4252class ScopedTokenPosition {
4253 unsigned StoredPosition;
4254 FormatTokenSource *Tokens;
4257 ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) {
4258 assert(Tokens &&
"Tokens expected to not be null");
4259 StoredPosition = Tokens->getPosition();
4262 ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); }
4268bool UnwrappedLineParser::tryToParseSimpleAttribute() {
4269 ScopedTokenPosition AutoPosition(Tokens);
4277 if (
Tok->
is(tok::r_square))
4279 Tok = Tokens->getNextToken();
4281 if (
Tok->
is(tok::eof))
4283 Tok = Tokens->getNextToken();
4286 Tok = Tokens->getNextToken();
4287 if (
Tok->
is(tok::semi))
4292void UnwrappedLineParser::parseJavaEnumBody() {
4293 assert(FormatTok->is(tok::l_brace));
4299 unsigned StoredPosition = Tokens->getPosition();
4300 bool IsSimple =
true;
4303 if (
Tok->
is(tok::r_brace))
4311 Tok = Tokens->getNextToken();
4313 FormatTok = Tokens->setPosition(StoredPosition);
4330 if (FormatTok->is(tok::l_brace)) {
4332 parseBlock(
true, 1u,
4334 }
else if (FormatTok->is(tok::l_paren)) {
4336 }
else if (FormatTok->is(tok::comma)) {
4339 }
else if (FormatTok->is(tok::semi)) {
4343 }
else if (FormatTok->is(tok::r_brace)) {
4352 parseLevel(OpeningBrace);
4358void UnwrappedLineParser::parseRecord(
bool ParseAsExpr,
bool IsJavaRecord) {
4359 assert(!IsJavaRecord || FormatTok->is(Keywords.kw_record));
4364 IsJavaRecord && FormatTok->is(tok::identifier) ? FormatTok :
nullptr;
4365 bool IsDerived =
false;
4367 return Tok->
is(tok::identifier) &&
Tok->TokenText !=
Tok->TokenText.upper();
4371 bool JSPastExtendsOrImplements =
false;
4375 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
4376 tok::kw_alignas, tok::l_square) ||
4377 FormatTok->isAttribute() ||
4378 ((Style.isJava() || Style.isJavaScript()) &&
4379 FormatTok->isOneOf(tok::period, tok::comma)) ||
4380 (Style.isVerilog() &&
4381 FormatTok->isOneOf(tok::kw_signed, tok::kw_unsigned))) {
4382 if (Style.isJavaScript() &&
4383 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
4384 JSPastExtendsOrImplements =
true;
4389 if (FormatTok->is(tok::l_brace)) {
4390 tryToParseBracedList();
4394 if (FormatTok->is(tok::l_square) && handleCppAttributes())
4398 switch (FormatTok->Tok.getKind()) {
4401 if (IsJavaRecord || !IsNonMacroIdentifier(
Previous) ||
4403 Previous->Previous == &InitialToken) {
4407 case tok::coloncolon:
4411 if (JSPastExtendsOrImplements || ClassName ||
4422 auto IsListInitialization = [&] {
4423 if (!ClassName || IsDerived || JSPastExtendsOrImplements)
4425 assert(FormatTok->is(tok::l_brace));
4426 const auto *Prev = FormatTok->getPreviousNonComment();
4428 return Prev != ClassName && Prev->is(tok::identifier) &&
4429 Prev->isNot(Keywords.kw_final) && tryToParseBracedList();
4432 if (FormatTok->isOneOf(tok::colon, tok::less)) {
4433 int AngleNestingLevel = 0;
4435 if (FormatTok->is(tok::less))
4436 ++AngleNestingLevel;
4437 else if (FormatTok->is(tok::greater))
4438 --AngleNestingLevel;
4440 if (AngleNestingLevel == 0) {
4441 if (FormatTok->is(tok::colon)) {
4443 }
else if (!IsDerived && FormatTok->is(tok::identifier) &&
4444 FormatTok->Previous->is(tok::coloncolon)) {
4445 ClassName = FormatTok;
4446 }
else if (FormatTok->is(tok::l_paren) &&
4447 IsNonMacroIdentifier(FormatTok->Previous)) {
4451 if (FormatTok->is(tok::l_brace)) {
4452 if (AngleNestingLevel == 0 && IsListInitialization())
4454 calculateBraceTypes(
true);
4455 if (!tryToParseBracedList())
4458 if (FormatTok->is(tok::l_square)) {
4461 !
Previous->isTypeOrIdentifier(LangOpts))) {
4464 if (!tryToParseLambda())
4471 if (FormatTok->is(tok::semi))
4473 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
4476 parseCSharpGenericTypeConstraint();
4483 auto GetBraceTypes =
4484 [](
const FormatToken &RecordTok) -> std::pair<TokenType, TokenType> {
4485 switch (RecordTok.Tok.getKind()) {
4487 return {TT_ClassLBrace, TT_ClassRBrace};
4488 case tok::kw_struct:
4489 return {TT_StructLBrace, TT_StructRBrace};
4491 return {TT_UnionLBrace, TT_UnionRBrace};
4494 return {TT_RecordLBrace, TT_RecordRBrace};
4497 if (FormatTok->is(tok::l_brace)) {
4498 if (IsListInitialization())
4501 ClassName->setFinalizedType(TT_ClassHeadName);
4502 auto [OpenBraceType, ClosingBraceType] = GetBraceTypes(InitialToken);
4503 FormatTok->setFinalizedType(OpenBraceType);
4508 Tokens->peekNextToken()->is(tok::r_brace),
4513 bool IndentAfterExplicitAccessModifier =
false;
4514 unsigned AddLevels = 1u;
4515 switch (Style.IndentAccessModifiers) {
4519 if (Style.isCpp()) {
4520 IndentAfterExplicitAccessModifier =
true;
4529 parseBlock(
true, AddLevels,
false,
4532 IndentAfterExplicitAccessModifier);
4534 setPreviousRBraceType(ClosingBraceType);
4541void UnwrappedLineParser::parseObjCMethod() {
4542 assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) &&
4543 "'(' or identifier expected.");
4545 if (FormatTok->is(tok::semi)) {
4549 }
else if (FormatTok->is(tok::l_brace)) {
4550 if (Style.BraceWrapping.AfterFunction)
4561void UnwrappedLineParser::parseObjCProtocolList() {
4562 assert(FormatTok->is(tok::less) &&
"'<' expected.");
4566 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4568 }
while (!
eof() && FormatTok->isNot(tok::greater));
4572void UnwrappedLineParser::parseObjCUntilAtEnd() {
4574 if (FormatTok->is(tok::objc_end)) {
4579 if (FormatTok->is(tok::l_brace)) {
4583 }
else if (FormatTok->is(tok::r_brace)) {
4587 }
else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
4589 if (FormatTok->isOneOf(tok::l_paren, tok::identifier))
4592 parseStructuralElement();
4597void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
4598 assert(FormatTok->isOneOf(tok::objc_interface, tok::objc_implementation));
4604 if (FormatTok->is(tok::less))
4605 parseObjCLightweightGenerics();
4606 if (FormatTok->is(tok::colon)) {
4610 if (FormatTok->is(tok::less))
4611 parseObjCLightweightGenerics();
4612 }
else if (FormatTok->is(tok::l_paren)) {
4617 if (FormatTok->is(tok::less))
4618 parseObjCProtocolList();
4620 if (FormatTok->is(tok::l_brace)) {
4621 if (Style.BraceWrapping.AfterObjCDeclaration)
4630 parseObjCUntilAtEnd();
4633void UnwrappedLineParser::parseObjCLightweightGenerics() {
4634 assert(FormatTok->is(tok::less));
4642 unsigned NumOpenAngles = 1;
4646 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4648 if (FormatTok->is(tok::less)) {
4650 }
else if (FormatTok->is(tok::greater)) {
4651 assert(NumOpenAngles > 0 &&
"'>' makes NumOpenAngles negative");
4654 }
while (!
eof() && NumOpenAngles != 0);
4660bool UnwrappedLineParser::parseObjCProtocol() {
4661 assert(FormatTok->is(tok::objc_protocol));
4664 if (FormatTok->is(tok::l_paren)) {
4676 if (FormatTok->is(tok::less))
4677 parseObjCProtocolList();
4680 if (FormatTok->is(tok::semi)) {
4687 parseObjCUntilAtEnd();
4691void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
4692 bool IsImport = FormatTok->is(Keywords.kw_import);
4693 assert(IsImport || FormatTok->is(tok::kw_export));
4697 if (FormatTok->is(tok::kw_default))
4703 if (FormatTok->is(Keywords.kw_async))
4705 if (FormatTok->is(Keywords.kw_function)) {
4714 if (!IsImport && FormatTok->isNoneOf(tok::l_brace, tok::star) &&
4715 !FormatTok->isStringLiteral() &&
4716 !(FormatTok->is(Keywords.kw_type) &&
4717 Tokens->peekNextToken()->isOneOf(tok::l_brace, tok::star))) {
4722 if (FormatTok->is(tok::semi))
4724 if (
Line->Tokens.empty()) {
4729 if (FormatTok->is(tok::l_brace)) {
4730 FormatTok->setBlockKind(BK_Block);
4739void UnwrappedLineParser::parseStatementMacro() {
4741 if (FormatTok->is(tok::l_paren))
4743 if (FormatTok->is(tok::semi))
4748void UnwrappedLineParser::parseVerilogHierarchyIdentifier() {
4751 if (FormatTok->isOneOf(tok::star, tok::period, tok::periodstar,
4752 tok::coloncolon, tok::hash) ||
4753 Keywords.isVerilogIdentifier(*FormatTok)) {
4755 }
else if (FormatTok->is(tok::l_square)) {
4763void UnwrappedLineParser::parseVerilogSensitivityList() {
4764 if (FormatTok->isNot(tok::at))
4768 if (FormatTok->is(tok::at))
4770 switch (FormatTok->Tok.getKind()) {
4778 parseVerilogHierarchyIdentifier();
4783unsigned UnwrappedLineParser::parseVerilogHierarchyHeader() {
4784 unsigned AddLevels = 0;
4786 if (FormatTok->is(Keywords.kw_clocking)) {
4788 if (Keywords.isVerilogIdentifier(*FormatTok))
4790 parseVerilogSensitivityList();
4791 if (FormatTok->is(tok::semi))
4793 }
else if (FormatTok->isOneOf(tok::kw_case, Keywords.kw_casex,
4794 Keywords.kw_casez, Keywords.kw_randcase,
4795 Keywords.kw_randsequence)) {
4796 if (Style.IndentCaseLabels)
4799 if (FormatTok->is(tok::l_paren)) {
4800 FormatTok->setFinalizedType(TT_ConditionLParen);
4803 if (FormatTok->isOneOf(Keywords.kw_inside, Keywords.kw_matches))
4812 if (FormatTok->is(tok::l_square)) {
4813 auto Prev = FormatTok->getPreviousNonComment();
4814 if (Prev && Keywords.isVerilogIdentifier(*Prev))
4815 Prev->setFinalizedType(TT_VerilogDimensionedTypeName);
4817 }
else if (Keywords.isVerilogIdentifier(*FormatTok) ||
4818 FormatTok->isOneOf(tok::hash, tok::hashhash, tok::coloncolon,
4819 Keywords.kw_automatic, tok::kw_static)) {
4826 auto NewLine = [
this]() {
4828 Line->IsContinuation =
true;
4832 while (FormatTok->is(Keywords.kw_import)) {
4835 parseVerilogHierarchyIdentifier();
4836 if (FormatTok->is(tok::semi))
4841 if (FormatTok->is(Keywords.kw_verilogHash)) {
4844 if (FormatTok->is(tok::l_paren)) {
4845 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4849 if (FormatTok->is(tok::l_paren)) {
4851 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4856 if (FormatTok->is(Keywords.kw_extends)) {
4859 parseVerilogHierarchyIdentifier();
4860 if (FormatTok->is(tok::l_paren))
4863 if (FormatTok->is(Keywords.kw_implements)) {
4867 parseVerilogHierarchyIdentifier();
4868 }
while (FormatTok->is(tok::comma));
4872 if (FormatTok->is(tok::at)) {
4874 parseVerilogSensitivityList();
4877 if (FormatTok->is(tok::semi))
4885void UnwrappedLineParser::parseVerilogTable() {
4886 assert(FormatTok->is(Keywords.kw_table));
4890 auto InitialLevel =
Line->Level++;
4891 while (!
eof() && !Keywords.isVerilogEnd(*FormatTok)) {
4894 if (
Tok->
is(tok::semi))
4896 else if (
Tok->
isOneOf(tok::star, tok::colon, tok::question, tok::minus))
4897 Tok->setFinalizedType(TT_VerilogTableItem);
4899 Line->Level = InitialLevel;
4904void UnwrappedLineParser::parseVerilogCaseLabel() {
4910 auto OrigLevel =
Line->Level;
4911 auto FirstLine = CurrentLines->size();
4912 if (
Line->Level == 0 || (
Line->InPPDirective &&
Line->Level <= 1))
4914 else if (!Style.IndentCaseBlocks && Keywords.isVerilogBegin(*FormatTok))
4916 parseStructuralElement();
4919 if (CurrentLines->size() > FirstLine)
4920 (*CurrentLines)[FirstLine].Level = OrigLevel;
4921 Line->Level = OrigLevel;
4924void UnwrappedLineParser::parseVerilogExtern() {
4926 FormatTok->isOneOf(tok::kw_extern, tok::kw_export, Keywords.kw_import));
4929 if (FormatTok->is(tok::string_literal))
4931 skipVerilogQualifiers();
4932 if (Keywords.isVerilogIdentifier(*FormatTok))
4934 if (FormatTok->is(tok::equal))
4936 if (Keywords.isVerilogHierarchy(*FormatTok))
4937 parseVerilogHierarchyHeader();
4940void UnwrappedLineParser::skipVerilogQualifiers() {
4941 while (FormatTok->isOneOf(tok::kw_protected, tok::kw_virtual, tok::kw_static,
4942 Keywords.kw_rand, Keywords.kw_context,
4943 Keywords.kw_pure, Keywords.kw_randc,
4944 Keywords.kw_local)) {
4949bool UnwrappedLineParser::containsExpansion(
const UnwrappedLine &
Line)
const {
4950 for (
const auto &N :
Line.Tokens) {
4951 if (N.Tok->MacroCtx)
4953 for (
const UnwrappedLine &Child : N.Children)
4954 if (containsExpansion(Child))
4960void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) {
4961 if (
Line->Tokens.empty())
4964 if (!parsingPPDirective()) {
4965 llvm::dbgs() <<
"Adding unwrapped line:\n";
4966 printDebugInfo(*
Line);
4974 bool ClosesWhitesmithsBlock =
4975 Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex &&
4981 if (!parsingPPDirective() && !InExpansion && containsExpansion(*
Line)) {
4983 Reconstruct.emplace(
Line->Level, Unexpanded);
4984 Reconstruct->addLine(*
Line);
4989 CurrentExpandedLines.push_back(std::move(*
Line));
4991 if (Reconstruct->finished()) {
4992 UnwrappedLine Reconstructed = std::move(*Reconstruct).takeResult();
4993 assert(!Reconstructed.Tokens.empty() &&
4994 "Reconstructed must at least contain the macro identifier.");
4995 assert(!parsingPPDirective());
4997 llvm::dbgs() <<
"Adding unexpanded line:\n";
4998 printDebugInfo(Reconstructed);
5000 ExpandedLines[Reconstructed.Tokens.begin()->Tok] = CurrentExpandedLines;
5001 Lines.push_back(std::move(Reconstructed));
5002 CurrentExpandedLines.clear();
5003 Reconstruct.reset();
5008 assert(!Reconstruct || (CurrentLines != &Lines) || !PP.Stack.empty());
5009 CurrentLines->push_back(std::move(*
Line));
5011 Line->Tokens.clear();
5012 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
5013 Line->FirstStartColumn = 0;
5014 Line->IsContinuation =
false;
5015 Line->SeenDecltypeAuto =
false;
5016 Line->IsModuleOrImportDecl =
false;
5018 if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove)
5020 if (!parsingPPDirective() && !PreprocessorDirectives.empty()) {
5021 CurrentLines->append(
5022 std::make_move_iterator(PreprocessorDirectives.begin()),
5023 std::make_move_iterator(PreprocessorDirectives.end()));
5024 PreprocessorDirectives.clear();
5027 FormatTok->Previous =
nullptr;
5030bool UnwrappedLineParser::eof()
const {
return FormatTok->is(tok::eof); }
5032bool UnwrappedLineParser::isOnNewLine(
const FormatToken &FormatTok) {
5033 return (
Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
5034 FormatTok.NewlinesBefore > 0;
5042 const llvm::Regex &CommentPragmasRegex) {
5046 StringRef IndentContent = FormatTok.
TokenText;
5047 if (FormatTok.
TokenText.starts_with(
"//") ||
5048 FormatTok.
TokenText.starts_with(
"/*")) {
5049 IndentContent = FormatTok.
TokenText.substr(2);
5051 if (CommentPragmasRegex.match(IndentContent))
5126 if (PreviousToken && PreviousToken->
is(tok::l_brace) &&
5128 MinColumnToken = PreviousToken;
5131 PreviousToken = Node.
Tok;
5135 MinColumnToken = Node.
Tok;
5137 if (PreviousToken && PreviousToken->
is(tok::l_brace))
5138 MinColumnToken = PreviousToken;
5144void UnwrappedLineParser::flushComments(
bool NewlineBeforeNext) {
5145 bool JustComments =
Line->Tokens.empty();
5155 Tok->ContinuesLineCommentSection =
5156 continuesLineCommentSection(*
Tok, *
Line, Style, CommentPragmasRegex);
5157 if (isOnNewLine(*
Tok) && JustComments && !
Tok->ContinuesLineCommentSection)
5161 if (NewlineBeforeNext && JustComments)
5163 CommentsBeforeNextToken.clear();
5166void UnwrappedLineParser::nextToken(
int LevelDifference) {
5169 flushComments(isOnNewLine(*FormatTok));
5170 pushToken(FormatTok);
5172 if (!Style.isJavaScript())
5173 readToken(LevelDifference);
5175 readTokenWithJavaScriptASI();
5177 if (Style.isVerilog()) {
5184 if (Keywords.isVerilogEnd(*FormatTok))
5185 FormatTok->Tok.setKind(tok::r_brace);
5189void UnwrappedLineParser::distributeComments(
5209 if (Comments.empty())
5211 bool ShouldPushCommentsInCurrentLine =
true;
5212 bool HasTrailAlignedWithNextToken =
false;
5213 unsigned StartOfTrailAlignedWithNextToken = 0;
5216 for (
unsigned i = Comments.size() - 1; i > 0; --i) {
5218 HasTrailAlignedWithNextToken =
true;
5219 StartOfTrailAlignedWithNextToken = i;
5223 for (
unsigned i = 0, e = Comments.size(); i < e; ++i) {
5225 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
5226 FormatTok->ContinuesLineCommentSection =
false;
5229 *FormatTok, *
Line, Style, CommentPragmasRegex);
5231 if (!FormatTok->ContinuesLineCommentSection &&
5232 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
5233 ShouldPushCommentsInCurrentLine =
false;
5235 if (ShouldPushCommentsInCurrentLine)
5236 pushToken(FormatTok);
5238 CommentsBeforeNextToken.push_back(FormatTok);
5242void UnwrappedLineParser::readToken(
int LevelDifference) {
5244 bool PreviousWasComment =
false;
5245 bool FirstNonCommentOnLine =
false;
5247 FormatTok = Tokens->getNextToken();
5249 while (FormatTok->isOneOf(TT_ConflictStart, TT_ConflictEnd,
5250 TT_ConflictAlternative)) {
5251 if (FormatTok->is(TT_ConflictStart))
5252 conditionalCompilationStart(
false);
5253 else if (FormatTok->is(TT_ConflictAlternative))
5254 conditionalCompilationAlternative();
5255 else if (FormatTok->is(TT_ConflictEnd))
5256 conditionalCompilationEnd();
5257 FormatTok = Tokens->getNextToken();
5258 FormatTok->MustBreakBefore =
true;
5259 FormatTok->MustBreakBeforeFinalized =
true;
5262 auto IsFirstNonCommentOnLine = [](
bool FirstNonCommentOnLine,
5264 bool PreviousWasComment) {
5266 return Tok.HasUnescapedNewline ||
Tok.IsFirst;
5271 if (PreviousWasComment)
5272 return FirstNonCommentOnLine || IsFirstOnLine(
Tok);
5273 return IsFirstOnLine(
Tok);
5276 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
5277 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
5278 PreviousWasComment = FormatTok->is(tok::comment);
5280 while (!
Line->InPPDirective && FormatTok->is(tok::hash) &&
5281 FirstNonCommentOnLine) {
5284 const auto *
Next = Tokens->peekNextToken();
5285 if ((Style.isVerilog() && !Keywords.isVerilogPPDirective(*
Next)) ||
5286 (Style.isTableGen() &&
5287 Next->isNoneOf(tok::kw_else, tok::pp_define, tok::pp_ifdef,
5288 tok::pp_ifndef, tok::pp_endif))) {
5291 distributeComments(Comments, FormatTok);
5296 const bool ParsedBefore = !ParsedPPDirectives.insert(FormatTok).second;
5299 bool SwitchToPreprocessorLines = !
Line->Tokens.empty();
5300 ScopedLineState BlockState(*
this, SwitchToPreprocessorLines,
5302 assert((LevelDifference >= 0 ||
5303 static_cast<unsigned>(-LevelDifference) <=
Line->Level) &&
5304 "LevelDifference makes Line->Level negative");
5305 Line->Level += LevelDifference;
5310 PP.BranchLevel > 0) {
5311 Line->Level += PP.BranchLevel;
5313 assert(
Line->Level >=
Line->UnbracedBodyLevel);
5314 Line->Level -=
Line->UnbracedBodyLevel;
5315 flushComments(isOnNewLine(*FormatTok));
5316 const bool IsEndIf = Tokens->peekNextToken()->is(tok::pp_endif);
5318 PreviousWasComment = FormatTok->is(tok::comment);
5319 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
5320 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
5323 if (IsEndIf && PP.IncludeGuard == IG_Defined && PP.BranchLevel == -1 &&
5324 getIncludeGuardState(Style.IndentPPDirectives) == IG_Inited &&
5326 (PreviousWasComment &&
5327 Tokens->peekNextToken(
true)->is(tok::eof)))) {
5328 PP.IncludeGuard = IG_Found;
5332 if (!PP.Stack.empty() && (PP.Stack.back().Kind == PP_Unreachable) &&
5333 !
Line->InPPDirective) {
5337 if (FormatTok->is(tok::identifier) &&
5338 Macros.defined(FormatTok->TokenText) &&
5340 !
Line->InPPDirective) {
5342 unsigned Position = Tokens->getPosition();
5347 const auto SavedPPState = PP;
5351 auto PreCall = std::move(
Line);
5352 Line.reset(
new UnwrappedLine);
5353 bool OldInExpansion = InExpansion;
5356 auto Args = parseMacroCall(SavedPPState);
5357 InExpansion = OldInExpansion;
5358 assert(
Line->Tokens.front().Tok == ID);
5360 auto UnexpandedLine = std::move(
Line);
5362 Line = std::move(PreCall);
5365 llvm::dbgs() <<
"Macro call: " <<
ID->TokenText <<
"(";
5367 llvm::dbgs() <<
"(";
5368 for (
const auto &Arg : Args.value())
5369 for (
const auto &
T : Arg)
5370 llvm::dbgs() <<
T->TokenText <<
" ";
5371 llvm::dbgs() <<
")";
5373 llvm::dbgs() <<
"\n";
5375 if (
Macros.objectLike(
ID->TokenText) && Args &&
5376 !
Macros.hasArity(
ID->TokenText, Args->size())) {
5382 LLVM_DEBUG(llvm::dbgs()
5383 <<
"Macro \"" <<
ID->TokenText
5384 <<
"\" not overloaded for arity " << Args->size()
5385 <<
"or not function-like, using object-like overload.");
5387 UnexpandedLine->Tokens.resize(1);
5388 Tokens->setPosition(Position);
5390 FormatTok = Tokens->getNextToken();
5392 assert(!Args &&
Macros.objectLike(
ID->TokenText));
5394 if ((!Args &&
Macros.objectLike(
ID->TokenText)) ||
5395 (Args &&
Macros.hasArity(
ID->TokenText, Args->size()))) {
5398 Unexpanded[
ID] = std::move(UnexpandedLine);
5400 Macros.expand(ID, std::move(Args));
5401 if (!Expansion.empty())
5402 FormatTok = Tokens->insertTokens(Expansion);
5405 llvm::dbgs() <<
"Expanded: ";
5406 for (
const auto &
T : Expansion)
5407 llvm::dbgs() <<
T->TokenText <<
" ";
5408 llvm::dbgs() <<
"\n";
5412 llvm::dbgs() <<
"Did not expand macro \"" <<
ID->TokenText
5413 <<
"\", because it was used ";
5415 llvm::dbgs() <<
"with " << Args->size();
5417 llvm::dbgs() <<
"without";
5418 llvm::dbgs() <<
" arguments, which doesn't match any definition.\n";
5420 Tokens->setPosition(Position);
5426 if (FormatTok->isNot(tok::comment)) {
5427 distributeComments(Comments, FormatTok);
5432 Comments.push_back(FormatTok);
5435 distributeComments(Comments,
nullptr);
5440template <
typename Iterator>
5441void pushTokens(Iterator Begin, Iterator End,
5443 for (
auto I = Begin; I != End; ++I) {
5444 Into.push_back(I->Tok);
5445 for (
const auto &Child : I->Children)
5446 pushTokens(Child.Tokens.begin(), Child.Tokens.end(), Into);
5451std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>
5452UnwrappedLineParser::parseMacroCall(
const PPState &SavedPPState) {
5453 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>> Args;
5454 assert(
Line->Tokens.empty());
5457 auto ConsumeLastTokenOfCall = [
this] {
5458 flushComments(isOnNewLine(*FormatTok));
5459 pushToken(FormatTok);
5460 FormatTok = Tokens->getNextToken();
5462 if (Tokens->peekNextToken(
true)->isNot(tok::l_paren)) {
5463 ConsumeLastTokenOfCall();
5467 assert(FormatTok->is(tok::l_paren));
5468 unsigned Position = Tokens->getPosition();
5472 auto ArgStart = std::prev(
Line->Tokens.end());
5476 switch (FormatTok->Tok.getKind()) {
5481 case tok::r_paren: {
5487 Args->push_back({});
5488 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5489 ConsumeLastTokenOfCall();
5497 Args->push_back({});
5498 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5500 ArgStart = std::prev(
Line->Tokens.end());
5508 Line->Tokens.resize(1);
5509 Tokens->setPosition(Position);
5516 Line->Tokens.push_back(UnwrappedLineNode(
Tok));
5517 if (PP.AtEndOfPPLine) {
5518 auto &
Tok = *
Line->Tokens.back().Tok;
5519 Tok.MustBreakBefore =
true;
5520 Tok.MustBreakBeforeFinalized =
true;
5521 Tok.FirstAfterPPLine =
true;
5522 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...
VerifyDiagnosticConsumer::Directive Directive
Implements an efficient mapping from strings to IdentifierInfo nodes.
Parser - This implements a parser for the C family of languages.
Encodes a location in the source.
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
@ Keyword
The name has been typo-corrected to a keyword.
bool continuesLineComment(const FormatToken &FormatTok, const FormatToken *Previous, const FormatToken *MinColumnToken)
@ Parens
New-expression has a C++98 paren-delimited initializer.
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 unsigned
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