21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/Support/raw_os_ostream.h"
25#include "llvm/Support/raw_ostream.h"
29#define DEBUG_TYPE "format-parser"
36void printLine(llvm::raw_ostream &OS,
const UnwrappedLine &
Line,
37 StringRef Prefix =
"",
bool PrintText =
false) {
38 OS << Prefix <<
"Line(" <<
Line.Level <<
", FSC=" <<
Line.FirstStartColumn
39 <<
")" << (
Line.InPPDirective ?
" MACRO" :
"") <<
": ";
41 for (std::list<UnwrappedLineNode>::const_iterator I =
Line.Tokens.begin(),
42 E =
Line.Tokens.end();
48 OS << I->Tok->Tok.getName() <<
"["
49 <<
"T=" << (
unsigned)I->Tok->getType()
50 <<
", OC=" << I->Tok->OriginalColumn <<
", \"" << I->Tok->TokenText
52 for (
const auto *CI = I->Children.begin(), *CE = I->Children.end();
55 printLine(OS, *CI, (Prefix +
" ").str());
63[[maybe_unused]]
static void printDebugInfo(
const UnwrappedLine &
Line) {
64 printLine(llvm::dbgs(),
Line);
67class ScopedDeclarationState {
69 ScopedDeclarationState(UnwrappedLine &
Line, llvm::BitVector &Stack,
70 bool MustBeDeclaration)
72 Line.MustBeDeclaration = MustBeDeclaration;
73 Stack.push_back(MustBeDeclaration);
75 ~ScopedDeclarationState() {
78 Line.MustBeDeclaration = Stack.back();
80 Line.MustBeDeclaration =
true;
85 llvm::BitVector &Stack;
91 llvm::raw_os_ostream OS(Stream);
99 bool SwitchToPreprocessorLines =
false)
100 : Parser(Parser), OriginalLines(Parser.CurrentLines) {
101 if (SwitchToPreprocessorLines)
102 Parser.CurrentLines = &Parser.PreprocessorDirectives;
103 else if (!Parser.Line->Tokens.empty())
104 Parser.CurrentLines = &Parser.Line->Tokens.back().Children;
105 PreBlockLine = std::move(Parser.Line);
106 Parser.Line = std::make_unique<UnwrappedLine>();
107 Parser.Line->Level = PreBlockLine->Level;
108 Parser.Line->PPLevel = PreBlockLine->PPLevel;
109 Parser.Line->InPPDirective = PreBlockLine->InPPDirective;
110 Parser.Line->InMacroBody = PreBlockLine->InMacroBody;
111 Parser.Line->UnbracedBodyLevel = PreBlockLine->UnbracedBodyLevel;
115 if (!Parser.Line->Tokens.empty())
116 Parser.addUnwrappedLine();
117 assert(Parser.Line->Tokens.empty());
118 Parser.Line = std::move(PreBlockLine);
119 if (Parser.CurrentLines == &Parser.PreprocessorDirectives)
120 Parser.AtEndOfPPLine =
true;
121 Parser.CurrentLines = OriginalLines;
127 std::unique_ptr<UnwrappedLine> PreBlockLine;
134 const FormatStyle &Style,
unsigned &LineLevel)
136 Style.BraceWrapping.AfterControlStatement ==
137 FormatStyle::BWACS_Always,
138 Style.BraceWrapping.IndentBraces) {}
140 bool WrapBrace,
bool IndentBrace)
141 : LineLevel(LineLevel), OldLineLevel(LineLevel) {
143 Parser->addUnwrappedLine();
151 unsigned OldLineLevel;
158 llvm::SpecificBumpPtrAllocator<FormatToken> &Allocator,
161 Style(Style), IsCpp(Style.
isCpp()),
163 CommentPragmasRegex(Style.CommentPragmas), Tokens(
nullptr),
164 Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1),
165 IncludeGuard(getIncludeGuardState(Style.IndentPPDirectives)),
166 IncludeGuardToken(
nullptr), FirstStartColumn(FirstStartColumn),
167 Macros(Style.Macros, SourceMgr, Style, Allocator, IdentTable) {}
169void UnwrappedLineParser::reset() {
171 IncludeGuard = getIncludeGuardState(Style.IndentPPDirectives);
172 IncludeGuardToken =
nullptr;
174 CommentsBeforeNextToken.clear();
176 AtEndOfPPLine =
false;
177 IsDecltypeAutoFunction =
false;
178 PreprocessorDirectives.clear();
179 CurrentLines = &Lines;
180 DeclarationScopeStack.clear();
181 NestedTooDeep.clear();
182 NestedLambdas.clear();
184 Line->FirstStartColumn = FirstStartColumn;
186 if (!Unexpanded.empty())
188 Token->MacroCtx.reset();
189 CurrentExpandedLines.clear();
190 ExpandedLines.clear();
198 Line->FirstStartColumn = FirstStartColumn;
200 LLVM_DEBUG(llvm::dbgs() <<
"----\n");
202 Tokens = &TokenSource;
210 if (IncludeGuard == IG_Found) {
211 for (
auto &Line : Lines)
212 if (Line.InPPDirective && Line.Level > 0)
218 pushToken(FormatTok);
223 if (!ExpandedLines.empty()) {
224 LLVM_DEBUG(llvm::dbgs() <<
"Expanded lines:\n");
225 for (
const auto &Line : Lines) {
226 if (!Line.Tokens.empty()) {
227 auto it = ExpandedLines.find(Line.Tokens.begin()->Tok);
228 if (it != ExpandedLines.end()) {
229 for (
const auto &Expanded : it->second) {
230 LLVM_DEBUG(printDebugInfo(Expanded));
231 Callback.consumeUnwrappedLine(Expanded);
236 LLVM_DEBUG(printDebugInfo(Line));
237 Callback.consumeUnwrappedLine(Line);
239 Callback.finishRun();
242 LLVM_DEBUG(llvm::dbgs() <<
"Unwrapped lines:\n");
244 LLVM_DEBUG(printDebugInfo(Line));
245 Callback.consumeUnwrappedLine(Line);
247 Callback.finishRun();
249 while (!PPLevelBranchIndex.empty() &&
250 PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) {
251 PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1);
252 PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1);
254 if (!PPLevelBranchIndex.empty()) {
255 ++PPLevelBranchIndex.back();
256 assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size());
257 assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back());
259 }
while (!PPLevelBranchIndex.empty());
262void UnwrappedLineParser::parseFile() {
265 bool MustBeDeclaration = !
Line->InPPDirective && !Style.isJavaScript();
266 ScopedDeclarationState DeclarationState(*
Line, DeclarationScopeStack,
268 if (Style.isTextProto() || (Style.isJson() && FormatTok->
IsFirst))
282 if (Style.isTextProto() && !CommentsBeforeNextToken.empty())
288void UnwrappedLineParser::parseCSharpGenericTypeConstraint() {
298 parseCSharpGenericTypeConstraint();
307void UnwrappedLineParser::parseCSharpAttribute() {
308 int UnpairedSquareBrackets = 1;
310 switch (FormatTok->Tok.getKind()) {
313 --UnpairedSquareBrackets;
314 if (UnpairedSquareBrackets == 0) {
320 ++UnpairedSquareBrackets;
330bool UnwrappedLineParser::precededByCommentOrPPDirective()
const {
331 if (!Lines.empty() && Lines.back().InPPDirective)
345bool UnwrappedLineParser::parseLevel(
const FormatToken *OpeningBrace,
348 const bool InRequiresExpression =
349 OpeningBrace && OpeningBrace->is(TT_RequiresExpressionLBrace);
350 const bool IsPrecededByCommentOrPPDirective =
351 !Style.RemoveBracesLLVM || precededByCommentOrPPDirective();
353 bool HasDoWhile =
false;
354 bool HasLabel =
false;
355 unsigned StatementCount = 0;
356 bool SwitchLabelEncountered =
false;
359 if (FormatTok->isAttribute()) {
361 if (FormatTok->is(tok::l_paren))
366 if (FormatTok->is(TT_MacroBlockBegin))
368 else if (FormatTok->is(TT_MacroBlockEnd))
371 auto ParseDefault = [
this, OpeningBrace, IfKind, &IfLBrace, &HasDoWhile,
372 &HasLabel, &StatementCount] {
373 parseStructuralElement(OpeningBrace, IfKind, &IfLBrace,
374 HasDoWhile ?
nullptr : &HasDoWhile,
375 HasLabel ?
nullptr : &HasLabel);
377 assert(StatementCount > 0 &&
"StatementCount overflow!");
386 if (InRequiresExpression) {
387 FormatTok->setFinalizedType(TT_CompoundRequirementLBrace);
388 }
else if (FormatTok->Previous &&
389 FormatTok->Previous->ClosesRequiresClause) {
395 if (!InRequiresExpression && FormatTok->isNot(TT_MacroBlockBegin)) {
396 if (tryToParseBracedList())
398 FormatTok->setFinalizedType(TT_BlockLBrace);
402 assert(StatementCount > 0 &&
"StatementCount overflow!");
407 if (!Style.RemoveBracesLLVM || Line->InPPDirective ||
408 OpeningBrace->isNoneOf(TT_ControlStatementLBrace, TT_ElseLBrace)) {
411 if (FormatTok->isNot(tok::r_brace) || StatementCount != 1 || HasLabel ||
412 HasDoWhile || IsPrecededByCommentOrPPDirective ||
413 precededByCommentOrPPDirective()) {
417 if (
Next->is(tok::comment) &&
Next->NewlinesBefore == 0)
420 *IfLeftBrace = IfLBrace;
426 case tok::kw_default: {
427 unsigned StoredPosition = Tokens->getPosition();
428 auto *
Next = Tokens->getNextNonComment();
429 FormatTok = Tokens->setPosition(StoredPosition);
430 if (
Next->isNoneOf(tok::colon, tok::arrow)) {
433 parseStructuralElement();
440 if (Style.Language == FormatStyle::LK_Proto || Style.isVerilog() ||
441 (Style.isJavaScript() && Line->MustBeDeclaration)) {
449 if (!SwitchLabelEncountered &&
450 (Style.IndentCaseLabels ||
451 (OpeningBrace && OpeningBrace->is(TT_SwitchExpressionLBrace)) ||
452 (Line->InPPDirective && Line->Level == 1))) {
455 SwitchLabelEncountered =
true;
456 parseStructuralElement();
459 if (Style.isCSharp()) {
461 parseCSharpAttribute();
464 if (handleCppAttributes())
476void UnwrappedLineParser::calculateBraceTypes(
bool ExpectClassBody) {
481 unsigned StoredPosition = Tokens->getPosition();
491 SmallVector<StackEntry, 8> LBraceStack;
492 assert(
Tok->is(tok::l_brace));
495 auto *NextTok = Tokens->getNextNonComment();
497 if (!Line->InMacroBody && !Style.isTableGen()) {
499 while (NextTok->is(tok::hash)) {
500 NextTok = Tokens->getNextToken();
501 if (NextTok->isOneOf(tok::pp_not_keyword, tok::pp_define))
504 NextTok = Tokens->getNextToken();
505 }
while (!NextTok->HasUnescapedNewline && NextTok->isNot(tok::eof));
507 while (NextTok->is(tok::comment))
508 NextTok = Tokens->getNextToken();
512 switch (
Tok->Tok.getKind()) {
514 if (Style.isJavaScript() && PrevTok) {
515 if (PrevTok->isOneOf(tok::colon, tok::less)) {
526 }
else if (PrevTok->is(tok::r_paren)) {
530 }
else if (Style.isJava() && PrevTok && PrevTok->is(tok::arrow)) {
535 LBraceStack.push_back({
Tok, PrevTok});
538 if (LBraceStack.empty())
540 if (
auto *LBrace = LBraceStack.back().Tok; LBrace->is(
BK_Unknown)) {
541 bool ProbablyBracedList =
false;
542 if (Style.Language == FormatStyle::LK_Proto) {
543 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
544 }
else if (LBrace->isNot(TT_EnumLBrace)) {
547 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
548 NextTok->OriginalColumn == 0;
558 ProbablyBracedList = LBrace->is(TT_BracedListLBrace);
560 ProbablyBracedList = ProbablyBracedList ||
561 (Style.isJavaScript() &&
562 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
565 ProbablyBracedList ||
566 (IsCpp && (PrevTok->Tok.isLiteral() ||
567 NextTok->isOneOf(tok::l_paren, tok::arrow)));
574 ProbablyBracedList ||
575 NextTok->isOneOf(tok::comma, tok::period, tok::colon,
576 tok::r_paren, tok::r_square, tok::ellipsis);
581 ProbablyBracedList ||
582 (NextTok->is(tok::l_brace) && LBraceStack.back().PrevTok &&
583 LBraceStack.back().PrevTok->isOneOf(tok::identifier,
587 ProbablyBracedList ||
588 (NextTok->is(tok::identifier) &&
589 PrevTok->isNoneOf(tok::semi, tok::r_brace, tok::l_brace));
591 ProbablyBracedList = ProbablyBracedList ||
592 (NextTok->is(tok::semi) &&
593 (!ExpectClassBody || LBraceStack.size() != 1));
596 ProbablyBracedList ||
597 (NextTok->isBinaryOperator() && !NextIsObjCMethod);
599 if (!Style.isCSharp() && NextTok->is(tok::l_square)) {
602 NextTok = Tokens->getNextToken();
603 ProbablyBracedList = NextTok->isNot(tok::l_square);
607 if (IsCpp && Line->InMacroBody && PrevTok != FormatTok &&
608 !FormatTok->Previous && NextTok->is(tok::eof) &&
612 PrevTok->isNoneOf(tok::semi,
BK_Block, tok::colon)) {
613 ProbablyBracedList =
true;
617 Tok->setBlockKind(BlockKind);
618 LBrace->setBlockKind(BlockKind);
620 LBraceStack.pop_back();
622 case tok::identifier:
623 if (
Tok->isNot(TT_StatementMacro))
634 if (!LBraceStack.empty() && LBraceStack.back().Tok->is(
BK_Unknown))
635 LBraceStack.back().Tok->setBlockKind(
BK_Block);
643 }
while (
Tok->isNot(tok::eof) && !LBraceStack.empty());
646 for (
const auto &Entry : LBraceStack)
650 FormatTok = Tokens->setPosition(StoredPosition);
654void UnwrappedLineParser::setPreviousRBraceType(
TokenType Type) {
655 if (
auto Prev = FormatTok->getPreviousNonComment();
656 Prev && Prev->is(tok::r_brace)) {
657 Prev->setFinalizedType(
Type);
664 seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
667size_t UnwrappedLineParser::computePPHash()
const {
669 for (
const auto &i : PPStack) {
680bool UnwrappedLineParser::mightFitOnOneLine(
682 const auto ColumnLimit = Style.ColumnLimit;
683 if (ColumnLimit == 0)
686 auto &Tokens = ParsedLine.Tokens;
687 assert(!Tokens.empty());
689 const auto *LastToken = Tokens.back().Tok;
692 SmallVector<UnwrappedLineNode> SavedTokens(Tokens.size());
695 for (
const auto &Token : Tokens) {
697 auto &SavedToken = SavedTokens[Index++];
699 SavedToken.Tok->copyFrom(*Token.Tok);
700 SavedToken.Children = std::move(Token.Children);
703 AnnotatedLine
Line(ParsedLine);
704 assert(Line.Last == LastToken);
706 TokenAnnotator Annotator(Style, Keywords);
707 Annotator.annotate(Line);
708 Annotator.calculateFormattingInformation(Line);
710 auto Length = LastToken->TotalLength;
712 assert(OpeningBrace != Tokens.front().Tok);
713 if (
auto Prev = OpeningBrace->Previous;
714 Prev && Prev->TotalLength + ColumnLimit == OpeningBrace->TotalLength) {
715 Length -= ColumnLimit;
717 Length -= OpeningBrace->TokenText.size() + 1;
720 if (
const auto *FirstToken = Line.First; FirstToken->is(tok::r_brace)) {
721 assert(!OpeningBrace || OpeningBrace->is(TT_ControlStatementLBrace));
722 Length -= FirstToken->TokenText.size() + 1;
726 for (
auto &Token : Tokens) {
727 const auto &SavedToken = SavedTokens[Index++];
728 Token.Tok->copyFrom(*SavedToken.Tok);
729 Token.Children = std::move(SavedToken.Children);
730 delete SavedToken.Tok;
734 assert(!Line.InMacroBody);
735 assert(!Line.InPPDirective);
736 return Line.Level * Style.IndentWidth + Length <= ColumnLimit;
739FormatToken *UnwrappedLineParser::parseBlock(
bool MustBeDeclaration,
740 unsigned AddLevels,
bool MunchSemi,
743 bool UnindentWhitesmithsBraces) {
744 auto HandleVerilogBlockLabel = [
this]() {
746 if (Style.isVerilog() && FormatTok->is(tok::colon)) {
748 if (Keywords.isVerilogIdentifier(*FormatTok))
755 const bool VerilogHierarchy =
756 Style.isVerilog() && Keywords.isVerilogHierarchy(*FormatTok);
757 assert((FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) ||
758 (Style.isVerilog() &&
759 (Keywords.isVerilogBegin(*FormatTok) || VerilogHierarchy))) &&
760 "'{' or macro block token expected");
762 const bool FollowedByComment = Tokens->peekNextToken()->is(tok::comment);
763 auto Index = CurrentLines->size();
764 const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
767 const bool IsWhitesmiths =
768 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
772 if (!VerilogHierarchy && AddLevels > 0 && IsWhitesmiths)
775 size_t PPStartHash = computePPHash();
777 const unsigned InitialLevel = Line->Level;
778 if (VerilogHierarchy) {
779 AddLevels += parseVerilogHierarchyHeader();
781 nextToken(AddLevels);
782 HandleVerilogBlockLabel();
786 if (Line->Level > 300)
789 if (MacroBlock && FormatTok->is(tok::l_paren))
792 size_t NbPreprocessorDirectives =
793 !parsingPPDirective() ? PreprocessorDirectives.size() : 0;
795 size_t OpeningLineIndex =
796 CurrentLines->empty()
798 : (CurrentLines->size() - 1 - NbPreprocessorDirectives);
803 if (UnindentWhitesmithsBraces)
806 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
812 Line->Level += AddLevels - (IsWhitesmiths ? 1 : 0);
815 const bool SimpleBlock = parseLevel(
Tok, IfKind, &IfLBrace);
820 if (MacroBlock ? FormatTok->isNot(TT_MacroBlockEnd)
821 : FormatTok->isNot(tok::r_brace)) {
822 Line->Level = InitialLevel;
823 FormatTok->setBlockKind(BK_Block);
827 if (FormatTok->is(tok::r_brace)) {
828 FormatTok->setBlockKind(BK_Block);
829 if (Tok->is(TT_NamespaceLBrace))
830 FormatTok->setFinalizedType(TT_NamespaceRBrace);
833 const bool IsFunctionRBrace =
834 FormatTok->is(tok::r_brace) &&
Tok->is(TT_FunctionLBrace);
836 auto RemoveBraces = [=]()
mutable {
839 assert(Tok->isOneOf(TT_ControlStatementLBrace, TT_ElseLBrace));
840 assert(FormatTok->is(tok::r_brace));
841 const bool WrappedOpeningBrace = !Tok->Previous;
842 if (WrappedOpeningBrace && FollowedByComment)
844 const bool HasRequiredIfBraces = IfLBrace && !IfLBrace->Optional;
845 if (KeepBraces && !HasRequiredIfBraces)
847 if (Tok->isNot(TT_ElseLBrace) || !HasRequiredIfBraces) {
848 const FormatToken *Previous = Tokens->getPreviousToken();
850 if (Previous->is(tok::r_brace) && !Previous->Optional)
853 assert(!CurrentLines->empty());
854 auto &LastLine = CurrentLines->back();
855 if (LastLine.Level == InitialLevel + 1 && !mightFitOnOneLine(LastLine))
857 if (
Tok->is(TT_ElseLBrace))
859 if (WrappedOpeningBrace) {
864 return mightFitOnOneLine((*CurrentLines)[Index],
Tok);
866 if (RemoveBraces()) {
867 Tok->MatchingParen = FormatTok;
868 FormatTok->MatchingParen =
Tok;
871 size_t PPEndHash = computePPHash();
874 nextToken(-AddLevels);
879 if (Style.RemoveSemicolon && IsFunctionRBrace) {
880 while (FormatTok->is(tok::semi)) {
881 FormatTok->Optional =
true;
886 HandleVerilogBlockLabel();
888 if (MacroBlock && FormatTok->is(tok::l_paren))
891 Line->Level = InitialLevel;
893 if (FormatTok->is(tok::kw_noexcept)) {
898 if (FormatTok->is(tok::arrow)) {
902 parseStructuralElement();
905 if (MunchSemi && FormatTok->is(tok::semi))
908 if (PPStartHash == PPEndHash) {
909 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
912 (*CurrentLines)[OpeningLineIndex].MatchingClosingBlockLineIndex =
913 CurrentLines->size() - 1;
923 if (
Line.Tokens.size() < 4)
925 auto I =
Line.Tokens.begin();
926 if (I->Tok->TokenText !=
"goog")
929 if (I->Tok->isNot(tok::period))
932 if (I->Tok->TokenText !=
"scope")
935 return I->Tok->is(tok::l_paren);
944 if (
Line.Tokens.size() < 3)
946 auto I =
Line.Tokens.begin();
947 if (I->Tok->isNot(tok::l_paren))
953 return I->Tok->is(tok::l_paren);
959 bool IsJavaRecord =
false) {
961 return Style.BraceWrapping.AfterClass;
964 if (InitialToken.
is(TT_NamespaceMacro))
965 Kind = tok::kw_namespace;
967 const bool WrapRecordAllowed =
969 Style.AllowShortRecordOnASingleLine < FormatStyle::SRS_Empty ||
970 Style.BraceWrapping.SplitEmptyRecord;
973 case tok::kw_namespace:
974 return Style.BraceWrapping.AfterNamespace;
976 return Style.BraceWrapping.AfterClass && WrapRecordAllowed;
978 return Style.BraceWrapping.AfterUnion && WrapRecordAllowed;
980 return Style.BraceWrapping.AfterStruct && WrapRecordAllowed;
982 return Style.BraceWrapping.AfterEnum;
988void UnwrappedLineParser::parseChildBlock() {
989 assert(FormatTok->is(tok::l_brace));
990 FormatTok->setBlockKind(BK_Block);
994 bool SkipIndent = (Style.isJavaScript() &&
995 (isGoogScope(*
Line) || isIIFE(*
Line, Keywords)));
996 ScopedLineState LineState(*
this);
997 ScopedDeclarationState DeclarationState(*
Line, DeclarationScopeStack,
999 Line->Level += SkipIndent ? 0 : 1;
1000 parseLevel(OpeningBrace);
1001 flushComments(isOnNewLine(*FormatTok));
1002 Line->Level -= SkipIndent ? 0 : 1;
1007void UnwrappedLineParser::parsePPDirective() {
1008 assert(FormatTok->is(tok::hash) &&
"'#' expected");
1009 ScopedMacroState MacroState(*
Line, Tokens, FormatTok);
1013 if (!FormatTok->Tok.getIdentifierInfo()) {
1018 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
1019 case tok::pp_define:
1026 case tok::pp_ifndef:
1030 case tok::pp_elifdef:
1031 case tok::pp_elifndef:
1038 case tok::pp_pragma:
1042 case tok::pp_warning:
1044 if (!
eof() && Style.isCpp())
1045 FormatTok->setFinalizedType(TT_AfterPPDirective);
1053void UnwrappedLineParser::conditionalCompilationCondition(
bool Unreachable) {
1054 size_t Line = CurrentLines->size();
1055 if (CurrentLines == &PreprocessorDirectives)
1056 Line += Lines.size();
1059 (!PPStack.empty() && PPStack.back().Kind == PP_Unreachable)) {
1060 PPStack.push_back({PP_Unreachable,
Line});
1062 PPStack.push_back({PP_Conditional,
Line});
1066void UnwrappedLineParser::conditionalCompilationStart(
bool Unreachable) {
1068 assert(PPBranchLevel >= 0 && PPBranchLevel <= (
int)PPLevelBranchIndex.size());
1069 if (PPBranchLevel == (
int)PPLevelBranchIndex.size()) {
1070 PPLevelBranchIndex.push_back(0);
1071 PPLevelBranchCount.push_back(0);
1073 PPChainBranchIndex.push(Unreachable ? -1 : 0);
1074 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
1075 conditionalCompilationCondition(Unreachable ||
Skip);
1078void UnwrappedLineParser::conditionalCompilationAlternative() {
1079 if (!PPStack.empty())
1081 assert(PPBranchLevel < (
int)PPLevelBranchIndex.size());
1082 if (!PPChainBranchIndex.empty())
1083 ++PPChainBranchIndex.top();
1084 conditionalCompilationCondition(
1085 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
1086 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
1089void UnwrappedLineParser::conditionalCompilationEnd() {
1090 assert(PPBranchLevel < (
int)PPLevelBranchIndex.size());
1091 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
1092 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel])
1093 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
1096 if (PPBranchLevel > -1)
1098 if (!PPChainBranchIndex.empty())
1099 PPChainBranchIndex.pop();
1100 if (!PPStack.empty())
1104void UnwrappedLineParser::parsePPIf(
bool IfDef) {
1105 bool IfNDef = FormatTok->is(tok::pp_ifndef);
1107 bool Unreachable =
false;
1108 if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText ==
"0"))
1110 if (IfDef && !IfNDef && FormatTok->TokenText ==
"SWIG")
1112 conditionalCompilationStart(Unreachable);
1116 bool MaybeIncludeGuard = IfNDef;
1117 if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
1118 for (
auto &
Line : Lines) {
1119 if (
Line.Tokens.front().Tok->isNot(tok::comment)) {
1120 MaybeIncludeGuard =
false;
1121 IncludeGuard = IG_Rejected;
1129 if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
1130 IncludeGuard = IG_IfNdefed;
1131 IncludeGuardToken = IfCondition;
1135void UnwrappedLineParser::parsePPElse() {
1137 if (IncludeGuard == IG_Defined && PPBranchLevel == 0)
1138 IncludeGuard = IG_Rejected;
1140 assert(PPBranchLevel >= -1);
1141 if (PPBranchLevel == -1)
1142 conditionalCompilationStart(
true);
1143 conditionalCompilationAlternative();
1149void UnwrappedLineParser::parsePPEndIf() {
1150 conditionalCompilationEnd();
1154void UnwrappedLineParser::parsePPDefine() {
1157 if (!FormatTok->Tok.getIdentifierInfo()) {
1158 IncludeGuard = IG_Rejected;
1159 IncludeGuardToken =
nullptr;
1164 bool MaybeIncludeGuard =
false;
1165 if (IncludeGuard == IG_IfNdefed &&
1166 IncludeGuardToken->TokenText == FormatTok->TokenText) {
1167 IncludeGuard = IG_Defined;
1168 IncludeGuardToken =
nullptr;
1169 for (
auto &
Line : Lines) {
1170 if (
Line.Tokens.front().Tok->isNoneOf(tok::comment, tok::hash)) {
1171 IncludeGuard = IG_Rejected;
1175 MaybeIncludeGuard = IncludeGuard == IG_Defined;
1183 FormatTok->Tok.setKind(tok::identifier);
1184 FormatTok->Tok.setIdentifierInfo(Keywords.kw_internal_ident_after_define);
1188 if (MaybeIncludeGuard && !
eof())
1189 IncludeGuard = IG_Rejected;
1191 if (FormatTok->is(tok::l_paren) && !FormatTok->hasWhitespaceBefore())
1193 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
1194 Line->Level += PPBranchLevel + 1;
1198 Line->PPLevel = PPBranchLevel + (IncludeGuard == IG_Defined ? 0 : 1);
1199 assert((
int)
Line->PPLevel >= 0);
1204 Line->InMacroBody =
true;
1206 if (!Style.SkipMacroDefinitionBody) {
1216 for (
auto *Comment : CommentsBeforeNextToken)
1217 Comment->Finalized =
true;
1220 FormatTok->Finalized =
true;
1221 FormatTok = Tokens->getNextToken();
1227void UnwrappedLineParser::parsePPPragma() {
1228 Line->InPragmaDirective =
true;
1232void UnwrappedLineParser::parsePPUnknown() {
1235 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
1236 Line->Level += PPBranchLevel + 1;
1246 return Tok.isNoneOf(tok::semi, tok::l_brace,
1249 tok::period, tok::periodstar, tok::arrow, tok::arrowstar,
1250 tok::less, tok::greater, tok::slash, tok::percent,
1251 tok::lessless, tok::greatergreater, tok::equal,
1252 tok::plusequal, tok::minusequal, tok::starequal,
1253 tok::slashequal, tok::percentequal, tok::ampequal,
1254 tok::pipeequal, tok::caretequal, tok::greatergreaterequal,
1267 return FormatTok->
is(tok::identifier) &&
1282 FormatTok->
isOneOf(tok::kw_true, tok::kw_false) ||
1293 tok::kw_if, tok::kw_else,
1295 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
1297 tok::kw_switch, tok::kw_case,
1299 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.
kw_finally,
1301 tok::kw_const, tok::kw_class, Keywords.
kw_var, Keywords.
kw_let,
1309 return Tok.isOneOf(tok::kw_char, tok::kw_short, tok::kw_int, tok::kw_long,
1310 tok::kw_unsigned, tok::kw_float, tok::kw_double,
1327 if (FuncName->
isNot(tok::identifier))
1335 Tok->isNoneOf(tok::kw_register, tok::kw_struct, tok::kw_union)) {
1339 if (
Next->isNot(tok::star) && !
Next->Tok.getIdentifierInfo())
1343 if (!
Tok ||
Tok->isNot(tok::r_paren))
1347 if (!
Tok ||
Tok->isNot(tok::identifier))
1350 return Tok->Previous &&
Tok->Previous->isOneOf(tok::l_paren, tok::comma);
1353bool UnwrappedLineParser::parseModuleImport() {
1354 assert(FormatTok->is(Keywords.kw_import) &&
"'import' expected");
1356 if (
auto Token = Tokens->peekNextToken(
true);
1358 Token->
isNoneOf(tok::colon, tok::less, tok::string_literal)) {
1364 if (FormatTok->is(tok::colon)) {
1365 FormatTok->setFinalizedType(TT_ModulePartitionColon);
1368 else if (FormatTok->is(tok::less)) {
1370 while (FormatTok->isNoneOf(tok::semi, tok::greater) && !
eof()) {
1373 if (FormatTok->isNot(tok::comment) &&
1374 !FormatTok->TokenText.starts_with(
"//")) {
1375 FormatTok->setFinalizedType(TT_ImplicitStringLiteral);
1380 if (FormatTok->is(tok::semi)) {
1398void UnwrappedLineParser::readTokenWithJavaScriptASI() {
1404 CommentsBeforeNextToken.empty()
1405 ?
Next->NewlinesBefore == 0
1406 : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
1411 bool PreviousStartsTemplateExpr =
1413 if (PreviousMustBeValue ||
Previous->is(tok::r_paren)) {
1416 bool HasAt = llvm::any_of(
Line->Tokens, [](UnwrappedLineNode &LineNode) {
1417 return LineNode.Tok->is(tok::at);
1422 if (
Next->is(tok::exclaim) && PreviousMustBeValue)
1423 return addUnwrappedLine();
1425 bool NextEndsTemplateExpr =
1426 Next->is(TT_TemplateString) &&
Next->TokenText.starts_with(
"}");
1427 if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
1428 (PreviousMustBeValue ||
1429 Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
1430 tok::minusminus))) {
1431 return addUnwrappedLine();
1433 if ((PreviousMustBeValue ||
Previous->is(tok::r_paren)) &&
1435 return addUnwrappedLine();
1439void UnwrappedLineParser::parseStructuralElement(
1440 const FormatToken *OpeningBrace, IfStmtKind *IfKind,
1441 FormatToken **IfLeftBrace,
bool *HasDoWhile,
bool *HasLabel) {
1442 if (Style.isTableGen() && FormatTok->is(tok::pp_include)) {
1444 if (FormatTok->is(tok::string_literal))
1451 while (FormatTok->is(tok::l_square) && handleCppAttributes()) {
1453 }
else if (Style.isVerilog()) {
1455 while (FormatTok->is(tok::l_paren) &&
1456 Tokens->peekNextToken()->is(tok::star)) {
1460 if (FormatTok->isOneOf(Keywords.kw_priority, Keywords.kw_unique,
1461 Keywords.kw_unique0)) {
1465 if (Keywords.isVerilogStructuredProcedure(*FormatTok)) {
1466 parseForOrWhileLoop(
false);
1469 if (FormatTok->isOneOf(Keywords.kw_foreach, Keywords.kw_repeat)) {
1470 parseForOrWhileLoop();
1473 if (FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
1474 Keywords.kw_assume, Keywords.kw_cover)) {
1475 parseIfThenElse(IfKind,
false,
true);
1481 if (FormatTok->isAccessSpecifierKeyword()) {
1482 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp())
1485 parseAccessSpecifier();
1488 switch (FormatTok->Tok.getKind()) {
1491 if (FormatTok->is(tok::l_brace)) {
1492 FormatTok->setFinalizedType(TT_InlineASMBrace);
1494 while (FormatTok && !
eof()) {
1495 if (FormatTok->is(tok::r_brace)) {
1496 FormatTok->setFinalizedType(TT_InlineASMBrace);
1501 FormatTok->Finalized =
true;
1506 case tok::kw_namespace:
1510 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1521 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1525 parseForOrWhileLoop();
1528 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1536 case tok::kw_switch:
1537 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1543 case tok::kw_default: {
1545 if (Style.isVerilog())
1547 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1553 if (FormatTok->is(tok::colon)) {
1554 FormatTok->setFinalizedType(TT_CaseLabelColon);
1558 if (FormatTok->is(tok::arrow)) {
1559 FormatTok->setFinalizedType(TT_CaseLabelArrow);
1560 Default->setFinalizedType(TT_SwitchExpressionLabel);
1569 if (Style.Language == FormatStyle::LK_Proto) {
1573 if (Style.isVerilog()) {
1578 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1587 if (FormatTok->is(tok::kw_case))
1592 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1598 case tok::kw_extern:
1599 if (Style.isVerilog()) {
1602 parseVerilogExtern();
1606 if (FormatTok->is(tok::string_literal)) {
1608 if (FormatTok->is(tok::l_brace)) {
1609 if (Style.BraceWrapping.AfterExternBlock)
1613 unsigned AddLevels =
1614 (Style.IndentExternBlock == FormatStyle::IEBS_Indent) ||
1615 (Style.BraceWrapping.AfterExternBlock &&
1616 Style.IndentExternBlock ==
1617 FormatStyle::IEBS_AfterExternBlock)
1620 parseBlock(
true, AddLevels);
1626 case tok::kw_export:
1627 if (Style.isJavaScript()) {
1628 parseJavaScriptEs6ImportExport();
1631 if (Style.isVerilog()) {
1632 parseVerilogExtern();
1637 if (FormatTok->is(tok::kw_namespace)) {
1641 if (FormatTok->is(tok::l_brace)) {
1642 parseCppExportBlock();
1645 if (FormatTok->is(Keywords.kw_import) && parseModuleImport())
1649 case tok::kw_inline:
1651 if (FormatTok->is(tok::kw_namespace)) {
1656 case tok::identifier:
1657 if (FormatTok->is(TT_ForEachMacro)) {
1658 parseForOrWhileLoop();
1661 if (FormatTok->is(TT_MacroBlockBegin)) {
1662 parseBlock(
false, 1u,
1666 if (FormatTok->is(Keywords.kw_import)) {
1667 if (Style.isJavaScript()) {
1668 parseJavaScriptEs6ImportExport();
1671 if (Style.Language == FormatStyle::LK_Proto) {
1673 if (FormatTok->is(tok::kw_public))
1675 if (FormatTok->isNot(tok::string_literal))
1678 if (FormatTok->is(tok::semi))
1683 if (Style.isVerilog()) {
1684 parseVerilogExtern();
1687 if (IsCpp && parseModuleImport())
1690 if (IsCpp && FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
1691 Keywords.kw_slots, Keywords.kw_qslots)) {
1693 if (FormatTok->is(tok::colon)) {
1699 if (IsCpp && FormatTok->is(TT_StatementMacro)) {
1700 parseStatementMacro();
1703 if (IsCpp && FormatTok->is(TT_NamespaceMacro)) {
1711 if (!Style.isJavaScript() && !Style.isVerilog() && !Style.isTableGen() &&
1712 Tokens->peekNextToken()->is(tok::colon) && !
Line->MustBeDeclaration) {
1714 if (!
Line->InMacroBody || CurrentLines->size() > 1)
1715 Line->Tokens.begin()->Tok->MustBreakBefore =
true;
1716 FormatTok->setFinalizedType(TT_GotoLabelColon);
1717 parseLabel(Style.IndentGotoLabels);
1722 if (Style.isJava() && FormatTok->is(Keywords.kw_record)) {
1723 parseRecord(
false,
true);
1733 bool SeenEqual =
false;
1734 for (
const bool InRequiresExpression =
1735 OpeningBrace && OpeningBrace->isOneOf(TT_RequiresExpressionLBrace,
1736 TT_CompoundRequirementLBrace);
1739 switch (FormatTok->Tok.getKind()) {
1742 if (FormatTok->is(tok::l_brace)) {
1747 if (Style.isJava() && FormatTok->is(Keywords.kw_interface)) {
1751 switch (
bool IsAutoRelease =
false; FormatTok->Tok.getObjCKeywordID()) {
1752 case tok::objc_public:
1753 case tok::objc_protected:
1754 case tok::objc_package:
1755 case tok::objc_private:
1756 return parseAccessSpecifier();
1757 case tok::objc_interface:
1758 case tok::objc_implementation:
1759 return parseObjCInterfaceOrImplementation();
1760 case tok::objc_protocol:
1761 if (parseObjCProtocol())
1766 case tok::objc_optional:
1767 case tok::objc_required:
1771 case tok::objc_autoreleasepool:
1772 IsAutoRelease =
true;
1774 case tok::objc_synchronized:
1776 if (!IsAutoRelease && FormatTok->is(tok::l_paren)) {
1780 if (FormatTok->is(tok::l_brace)) {
1781 if (Style.BraceWrapping.AfterControlStatement ==
1782 FormatStyle::BWACS_Always) {
1798 case tok::kw_requires: {
1800 bool ParsedClause = parseRequires(SeenEqual);
1821 if (!IsCpp && !Style.isVerilog()) {
1826 case tok::kw_typedef:
1828 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1829 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS,
1830 Keywords.kw_CF_CLOSED_ENUM,
1831 Keywords.kw_NS_CLOSED_ENUM)) {
1836 if (Style.isVerilog()) {
1841 if (Style.isTableGen()) {
1848 case tok::kw_struct:
1850 if (parseStructLike())
1853 case tok::kw_decltype:
1855 if (FormatTok->is(tok::l_paren)) {
1857 if (FormatTok->Previous &&
1858 FormatTok->Previous->endsSequence(tok::r_paren, tok::kw_auto,
1860 Line->SeenDecltypeAuto =
true;
1867 if (Style.isJava() && FormatTok && FormatTok->is(tok::kw_class))
1869 if (Style.isJavaScript() && FormatTok &&
1870 FormatTok->Tok.getIdentifierInfo()) {
1883 case tok::string_literal:
1884 if (Style.isVerilog() && FormatTok->is(TT_VerilogProtected)) {
1885 FormatTok->Finalized =
true;
1892 case tok::l_paren: {
1899 Tokens->peekNextToken(
true),
1906 case tok::kw_operator:
1908 if (FormatTok->isBinaryOperator())
1912 const auto *Prev = FormatTok->getPreviousNonComment();
1914 if (Prev && Prev->is(tok::identifier))
1917 if (FormatTok->Tok.isAnyIdentifier() || FormatTok->isTypeName(LangOpts)) {
1920 while (FormatTok->is(tok::star))
1924 if (FormatTok->is(tok::l_paren))
1927 if (FormatTok->is(tok::l_brace))
1932 if (InRequiresExpression)
1933 FormatTok->setFinalizedType(TT_BracedListLBrace);
1934 if (!tryToParsePropertyAccessor() && !tryToParseBracedList()) {
1935 IsDecltypeAutoFunction =
Line->SeenDecltypeAuto;
1940 if (Style.isJava() &&
1941 Line->Tokens.front().Tok->is(Keywords.kw_synchronized)) {
1944 if (Style.BraceWrapping.AfterControlStatement ==
1945 FormatStyle::BWACS_Always) {
1948 }
else if (Style.BraceWrapping.AfterFunction) {
1952 FormatTok->setFinalizedType(TT_FunctionLBrace);
1954 IsDecltypeAutoFunction =
false;
1962 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1968 if (Style.BraceWrapping.AfterFunction)
1972 case tok::identifier: {
1973 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where) &&
1974 Line->MustBeDeclaration) {
1976 parseCSharpGenericTypeConstraint();
1979 if (FormatTok->is(TT_MacroBlockEnd)) {
1988 size_t TokenCount =
Line->Tokens.size();
1989 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_function) &&
1992 Line->Tokens.front().Tok->isNot(Keywords.kw_async)))) {
1993 tryToParseJSFunction();
1996 if ((Style.isJavaScript() || Style.isJava()) &&
1997 FormatTok->is(Keywords.kw_interface)) {
1998 if (Style.isJavaScript()) {
2003 unsigned StoredPosition = Tokens->getPosition();
2005 FormatTok = Tokens->setPosition(StoredPosition);
2016 if (Style.isVerilog()) {
2017 if (FormatTok->is(Keywords.kw_table)) {
2018 parseVerilogTable();
2021 if (Keywords.isVerilogBegin(*FormatTok) ||
2022 Keywords.isVerilogHierarchy(*FormatTok)) {
2029 if (!IsCpp && FormatTok->is(Keywords.kw_interface)) {
2030 if (parseStructLike())
2035 if (IsCpp && FormatTok->is(TT_StatementMacro)) {
2036 parseStatementMacro();
2041 StringRef
Text = FormatTok->TokenText;
2048 if (Style.isJavaScript())
2051 auto OneTokenSoFar = [&]() {
2052 auto I =
Line->Tokens.begin(), E =
Line->Tokens.end();
2053 while (I != E && I->Tok->is(tok::comment))
2055 if (Style.isVerilog())
2056 while (I != E && I->Tok->is(tok::hash))
2058 return I != E && (++I == E);
2060 if (OneTokenSoFar()) {
2063 bool FunctionLike = FormatTok->is(tok::l_paren);
2067 bool FollowedByNewline =
2068 CommentsBeforeNextToken.empty()
2069 ? FormatTok->NewlinesBefore > 0
2070 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
2072 if (FollowedByNewline &&
2073 (
Text.size() >= 5 ||
2074 (FunctionLike && FormatTok->isNot(tok::l_paren))) &&
2076 if (PreviousToken->isNot(TT_UntouchableMacroFunc))
2077 PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro);
2085 if ((Style.isJavaScript() || Style.isCSharp()) &&
2086 FormatTok->is(TT_FatArrow)) {
2087 tryToParseChildBlock();
2093 if (FormatTok->is(tok::l_brace)) {
2097 if (!Style.isJavaScript())
2098 FormatTok->setBlockKind(BK_BracedInit);
2101 if (Style.isTableGen() &&
2102 Line->Tokens.begin()->Tok->is(Keywords.kw_defset)) {
2103 FormatTok->setFinalizedType(TT_FunctionLBrace);
2104 parseBlock(
false, 1u,
2111 }
else if (Style.Language == FormatStyle::LK_Proto &&
2112 FormatTok->is(tok::less)) {
2114 parseBracedList(
true);
2121 if (Style.isCSharp() &&
2122 (Tokens->peekNextToken()->isAccessSpecifierKeyword() ||
2129 case tok::kw_switch:
2137 if (Style.Language == FormatStyle::LK_Proto) {
2142 if (Style.isVerilog()) {
2147 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
2154 case tok::kw_default:
2156 if (Style.isVerilog()) {
2157 if (FormatTok->is(tok::colon)) {
2161 if (FormatTok->is(Keywords.kw_clocking)) {
2167 parseVerilogCaseLabel();
2173 if (Style.isVerilog()) {
2174 parseVerilogCaseLabel();
2180 if (FormatTok->is(tok::l_brace))
2181 FormatTok->Previous->setFinalizedType(TT_TemplateCloser);
2190bool UnwrappedLineParser::tryToParsePropertyAccessor() {
2191 assert(FormatTok->is(tok::l_brace));
2192 if (!Style.isCSharp())
2195 if (!FormatTok->Previous || FormatTok->Previous->isNot(tok::identifier))
2203 unsigned int StoredPosition = Tokens->getPosition();
2209 bool HasSpecialAccessor =
false;
2210 bool IsTrivialPropertyAccessor =
true;
2213 if (
const bool IsAccessorKeyword =
2214 Tok->
isOneOf(Keywords.kw_get, Keywords.kw_init, Keywords.kw_set);
2215 IsAccessorKeyword ||
Tok->isAccessSpecifierKeyword() ||
2216 Tok->
isOneOf(tok::l_square, tok::semi, Keywords.kw_internal)) {
2217 if (IsAccessorKeyword)
2218 HasSpecialAccessor =
true;
2219 else if (
Tok->
is(tok::l_square))
2221 Tok = Tokens->getNextToken();
2225 IsTrivialPropertyAccessor =
false;
2230 Tokens->setPosition(StoredPosition);
2236 Tokens->setPosition(StoredPosition);
2237 if (!IsTrivialPropertyAccessor && Style.BraceWrapping.AfterFunction)
2241 switch (FormatTok->Tok.getKind()) {
2244 if (FormatTok->is(tok::equal)) {
2245 while (!
eof() && FormatTok->isNot(tok::semi))
2258 if (FormatTok->is(TT_FatArrow)) {
2262 }
while (!
eof() && FormatTok->isNot(tok::semi));
2271 if (FormatTok->isOneOf(Keywords.kw_get, Keywords.kw_init,
2273 !IsTrivialPropertyAccessor) {
2285bool UnwrappedLineParser::tryToParseLambda() {
2286 assert(FormatTok->is(tok::l_square));
2292 if (!tryToParseLambdaIntroducer())
2296 bool InTemplateParameterList =
false;
2298 while (FormatTok->isNot(tok::l_brace)) {
2299 if (FormatTok->isTypeName(LangOpts) || FormatTok->isAttribute()) {
2303 switch (FormatTok->Tok.getKind()) {
2307 parseParens(TT_PointerOrReference);
2313 assert(FormatTok->Previous);
2314 if (FormatTok->Previous->is(tok::r_square))
2315 InTemplateParameterList =
true;
2320 case tok::kw_struct:
2322 case tok::kw_template:
2323 case tok::kw_typename:
2327 case tok::kw_constexpr:
2328 case tok::kw_consteval:
2331 case tok::identifier:
2332 case tok::numeric_constant:
2333 case tok::coloncolon:
2334 case tok::kw_mutable:
2335 case tok::kw_noexcept:
2336 case tok::kw_static:
2361 case tok::equalequal:
2362 case tok::exclaimequal:
2363 case tok::greaterequal:
2364 case tok::lessequal:
2370 if (Arrow || InTemplateParameterList) {
2379 case tok::kw_requires:
2380 parseRequiresClause();
2383 if (!InTemplateParameterList)
2392 FormatTok->setFinalizedType(TT_LambdaLBrace);
2393 LSquare.setFinalizedType(TT_LambdaLSquare);
2396 Arrow->setFinalizedType(TT_LambdaArrow);
2398 NestedLambdas.push_back(
Line->SeenDecltypeAuto);
2400 assert(!NestedLambdas.empty());
2401 NestedLambdas.pop_back();
2406bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
2411 const auto *PrevPrev =
Previous->getPreviousNonComment();
2412 if (
Previous->is(tok::star) && PrevPrev && PrevPrev->isTypeName(LangOpts))
2420 if (!PrevPrev || PrevPrev->isNoneOf(tok::greater, tok::r_paren))
2424 Previous->isNoneOf(tok::kw_return, tok::kw_co_await, tok::kw_co_yield,
2425 tok::kw_co_return)) {
2429 if (LeftSquare->isCppStructuredBinding(IsCpp))
2431 if (FormatTok->is(tok::l_square) ||
tok::isLiteral(FormatTok->Tok.getKind()))
2433 if (FormatTok->is(tok::r_square)) {
2435 if (
Next->is(tok::greater))
2442void UnwrappedLineParser::tryToParseJSFunction() {
2443 assert(FormatTok->is(Keywords.kw_function));
2444 if (FormatTok->is(Keywords.kw_async))
2450 if (FormatTok->is(tok::star)) {
2451 FormatTok->setFinalizedType(TT_OverloadedOperator);
2456 if (FormatTok->is(tok::identifier))
2459 if (FormatTok->isNot(tok::l_paren))
2465 if (FormatTok->is(tok::colon)) {
2471 if (FormatTok->is(tok::l_brace))
2472 tryToParseBracedList();
2474 while (FormatTok->isNoneOf(tok::l_brace, tok::semi) && !
eof())
2478 if (FormatTok->is(tok::semi))
2484bool UnwrappedLineParser::tryToParseBracedList() {
2485 if (FormatTok->is(BK_Unknown))
2486 calculateBraceTypes();
2487 assert(FormatTok->isNot(BK_Unknown));
2488 if (FormatTok->is(BK_Block))
2495bool UnwrappedLineParser::tryToParseChildBlock() {
2496 assert(Style.isJavaScript() || Style.isCSharp());
2497 assert(FormatTok->is(TT_FatArrow));
2502 if (FormatTok->isNot(tok::l_brace))
2508bool UnwrappedLineParser::parseBracedList(
bool IsAngleBracket,
bool IsEnum) {
2509 assert(!IsAngleBracket || !IsEnum);
2510 bool HasError =
false;
2515 if (Style.isCSharp() && FormatTok->is(TT_FatArrow) &&
2516 tryToParseChildBlock()) {
2519 if (Style.isJavaScript()) {
2520 if (FormatTok->is(Keywords.kw_function)) {
2521 tryToParseJSFunction();
2524 if (FormatTok->is(tok::l_brace)) {
2526 if (tryToParseBracedList())
2531 if (FormatTok->is(IsAngleBracket ? tok::greater : tok::r_brace)) {
2533 FormatTok->setBlockKind(BK_Block);
2534 if (!Style.AllowShortEnumsOnASingleLine)
2540 switch (FormatTok->Tok.getKind()) {
2542 if (Style.isCSharp())
2551 if (Style.isJavaScript()) {
2552 if (FormatTok->is(tok::l_brace))
2560 FormatTok->setBlockKind(BK_BracedInit);
2561 if (!IsAngleBracket) {
2562 auto *Prev = FormatTok->Previous;
2563 if (Prev && Prev->is(tok::greater))
2564 Prev->setFinalizedType(TT_TemplateCloser);
2572 parseBracedList(
true);
2579 if (Style.isJavaScript()) {
2590 if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
2593 case tok::kw_requires:
2594 parseRequiresExpression();
2610bool UnwrappedLineParser::parseParens(TokenType StarAndAmpTokenType,
2612 assert(FormatTok->is(tok::l_paren) &&
"'(' expected.");
2613 auto *LParen = FormatTok;
2614 auto *Prev = FormatTok->Previous;
2615 bool SeenComma =
false;
2616 bool SeenEqual =
false;
2617 bool MightBeFoldExpr =
false;
2619 const bool MightBeStmtExpr = FormatTok->is(tok::l_brace);
2620 if (!InMacroCall && Prev && Prev->is(TT_FunctionLikeMacro))
2623 switch (FormatTok->Tok.getKind()) {
2625 if (parseParens(StarAndAmpTokenType, InMacroCall))
2627 if (Style.isJava() && FormatTok->is(tok::l_brace))
2630 case tok::r_paren: {
2631 auto *RParen = FormatTok;
2634 auto OptionalParens = [&] {
2635 if (Style.RemoveParentheses == FormatStyle::RPS_Leave ||
2636 MightBeStmtExpr || MightBeFoldExpr || SeenComma || InMacroCall ||
2637 Line->InMacroBody || RParen->getPreviousNonComment() == LParen) {
2640 const bool DoubleParens =
2641 Prev->is(tok::l_paren) && FormatTok->is(tok::r_paren);
2643 const auto *PrevPrev = Prev->getPreviousNonComment();
2644 const bool Excluded =
2646 (PrevPrev->isOneOf(tok::kw___attribute, tok::kw_decltype) ||
2648 (PrevPrev->isOneOf(tok::kw_if, tok::kw_while) ||
2649 PrevPrev->endsSequence(tok::kw_constexpr, tok::kw_if))));
2653 const bool CommaSeparated =
2654 Prev->isOneOf(tok::l_paren, tok::comma) &&
2655 FormatTok->isOneOf(tok::comma, tok::r_paren);
2656 if (CommaSeparated &&
2658 !Prev->endsSequence(tok::comma, tok::ellipsis) &&
2660 !(FormatTok->is(tok::comma) &&
2661 Tokens->peekNextToken()->is(tok::ellipsis))) {
2664 const bool ReturnParens =
2665 Style.RemoveParentheses == FormatStyle::RPS_ReturnStatement &&
2666 ((NestedLambdas.empty() && !IsDecltypeAutoFunction) ||
2667 (!NestedLambdas.empty() && !NestedLambdas.back())) &&
2668 Prev->isOneOf(tok::kw_return, tok::kw_co_return) &&
2669 FormatTok->is(tok::semi);
2675 if (OptionalParens()) {
2676 LParen->Optional =
true;
2677 RParen->Optional =
true;
2678 }
else if (Prev->is(TT_TypenameMacro)) {
2679 LParen->setFinalizedType(TT_TypeDeclarationParen);
2680 RParen->setFinalizedType(TT_TypeDeclarationParen);
2681 }
else if (Prev->is(tok::greater) && RParen->Previous == LParen) {
2682 Prev->setFinalizedType(TT_TemplateCloser);
2683 }
else if (FormatTok->is(tok::l_brace) && Prev->is(tok::amp) &&
2685 FormatTok->setBlockKind(BK_BracedInit);
2697 if (!tryToParseBracedList())
2702 if (FormatTok->is(tok::l_brace)) {
2712 MightBeFoldExpr =
true;
2717 if (Style.isCSharp() && FormatTok->is(TT_FatArrow))
2718 tryToParseChildBlock();
2723 if (Style.isJavaScript())
2728 case tok::identifier:
2729 if (Style.isJavaScript() && (FormatTok->is(Keywords.kw_function)))
2730 tryToParseJSFunction();
2734 case tok::kw_switch:
2740 case tok::kw_requires:
2741 parseRequiresExpression();
2746 if (StarAndAmpTokenType != TT_Unknown)
2747 FormatTok->setFinalizedType(StarAndAmpTokenType);
2759 assert(FormatTok->is(tok::l_square) &&
"'[' expected.");
2760 if (tryToParseLambda())
2764 switch (FormatTok->Tok.getKind()) {
2777 case tok::l_brace: {
2778 if (!tryToParseBracedList())
2785 if (FormatTok->is(tok::l_brace)) {
2797void UnwrappedLineParser::keepAncestorBraces() {
2798 if (!Style.RemoveBracesLLVM)
2801 const int MaxNestingLevels = 2;
2802 const int Size = NestedTooDeep.size();
2803 if (Size >= MaxNestingLevels)
2804 NestedTooDeep[
Size - MaxNestingLevels] =
true;
2805 NestedTooDeep.push_back(
false);
2809 for (
const auto &
Token : llvm::reverse(
Line.Tokens))
2816void UnwrappedLineParser::parseUnbracedBody(
bool CheckEOF) {
2819 if (Style.InsertBraces && !
Line->InPPDirective && !
Line->Tokens.empty() &&
2820 PreprocessorDirectives.empty() && FormatTok->isNot(tok::semi)) {
2821 Tok = Style.BraceWrapping.AfterControlStatement == FormatStyle::BWACS_Never
2822 ? getLastNonComment(*
Line)
2825 if (
Tok->BraceCount < 0) {
2826 assert(
Tok->BraceCount == -1);
2829 Tok->BraceCount = -1;
2835 ++
Line->UnbracedBodyLevel;
2836 parseStructuralElement();
2837 --
Line->UnbracedBodyLevel;
2840 assert(!
Line->InPPDirective);
2842 for (
const auto &L : llvm::reverse(*CurrentLines)) {
2844 Tok = L.Tokens.back().Tok;
2852 if (CheckEOF &&
eof())
2862 assert(LeftBrace->
is(tok::l_brace));
2870 assert(RightBrace->
is(tok::r_brace));
2878void UnwrappedLineParser::handleAttributes() {
2880 if (FormatTok->isAttribute())
2882 else if (FormatTok->is(tok::l_square))
2883 handleCppAttributes();
2886bool UnwrappedLineParser::handleCppAttributes() {
2888 assert(FormatTok->is(tok::l_square));
2889 if (!tryToParseSimpleAttribute())
2896bool UnwrappedLineParser::isBlockBegin(
const FormatToken &
Tok)
const {
2899 return Style.isVerilog() ? Keywords.isVerilogBegin(
Tok)
2900 :
Tok.
is(tok::l_brace);
2903FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
2905 bool IsVerilogAssert) {
2906 assert((FormatTok->is(tok::kw_if) ||
2907 (Style.isVerilog() &&
2908 FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
2909 Keywords.kw_assume, Keywords.kw_cover))) &&
2913 if (IsVerilogAssert) {
2915 if (FormatTok->is(Keywords.kw_verilogHash)) {
2917 if (FormatTok->is(tok::numeric_constant))
2919 }
else if (FormatTok->isOneOf(Keywords.kw_final, Keywords.kw_property,
2920 Keywords.kw_sequence)) {
2926 if (Style.isTableGen()) {
2927 while (!
eof() && FormatTok->isNot(Keywords.kw_then)) {
2934 if (FormatTok->is(tok::exclaim))
2937 bool KeepIfBraces =
true;
2938 if (FormatTok->is(tok::kw_consteval)) {
2941 KeepIfBraces = !Style.RemoveBracesLLVM || KeepBraces;
2942 if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
2944 if (FormatTok->is(tok::l_paren)) {
2945 FormatTok->setFinalizedType(TT_ConditionLParen);
2951 if (IsVerilogAssert && FormatTok->is(tok::semi)) {
2957 bool NeedsUnwrappedLine =
false;
2958 keepAncestorBraces();
2961 IfStmtKind IfBlockKind = IfStmtKind::NotIf;
2963 if (isBlockBegin(*FormatTok)) {
2964 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
2965 IfLeftBrace = FormatTok;
2966 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
2967 parseBlock(
false, 1u,
2968 true, KeepIfBraces, &IfBlockKind);
2969 setPreviousRBraceType(TT_ControlStatementRBrace);
2970 if (Style.BraceWrapping.BeforeElse)
2973 NeedsUnwrappedLine =
true;
2974 }
else if (IsVerilogAssert && FormatTok->is(tok::kw_else)) {
2977 parseUnbracedBody();
2980 if (Style.RemoveBracesLLVM) {
2981 assert(!NestedTooDeep.empty());
2982 KeepIfBraces = KeepIfBraces ||
2983 (IfLeftBrace && !IfLeftBrace->MatchingParen) ||
2984 NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly ||
2985 IfBlockKind == IfStmtKind::IfElseIf;
2988 bool KeepElseBraces = KeepIfBraces;
2990 IfStmtKind
Kind = IfStmtKind::IfOnly;
2992 if (FormatTok->is(tok::kw_else)) {
2993 if (Style.RemoveBracesLLVM) {
2994 NestedTooDeep.back() =
false;
2995 Kind = IfStmtKind::IfElse;
2999 if (isBlockBegin(*FormatTok)) {
3000 const bool FollowedByIf = Tokens->peekNextToken()->is(tok::kw_if);
3001 FormatTok->setFinalizedType(TT_ElseLBrace);
3002 ElseLeftBrace = FormatTok;
3003 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3004 IfStmtKind ElseBlockKind = IfStmtKind::NotIf;
3006 parseBlock(
false, 1u,
3007 true, KeepElseBraces, &ElseBlockKind);
3008 setPreviousRBraceType(TT_ElseRBrace);
3009 if (FormatTok->is(tok::kw_else)) {
3010 KeepElseBraces = KeepElseBraces ||
3011 ElseBlockKind == IfStmtKind::IfOnly ||
3012 ElseBlockKind == IfStmtKind::IfElseIf;
3013 }
else if (FollowedByIf && IfLBrace && !IfLBrace->Optional) {
3014 KeepElseBraces =
true;
3015 assert(ElseLeftBrace->MatchingParen);
3019 }
else if (!IsVerilogAssert && FormatTok->is(tok::kw_if)) {
3022 const bool IsPrecededByComment =
Previous->is(tok::comment);
3023 if (IsPrecededByComment) {
3027 bool TooDeep =
true;
3028 if (Style.RemoveBracesLLVM) {
3029 Kind = IfStmtKind::IfElseIf;
3030 TooDeep = NestedTooDeep.pop_back_val();
3032 ElseLeftBrace = parseIfThenElse(
nullptr, KeepIfBraces);
3033 if (Style.RemoveBracesLLVM)
3034 NestedTooDeep.push_back(TooDeep);
3035 if (IsPrecededByComment)
3038 parseUnbracedBody(
true);
3041 KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse;
3042 if (NeedsUnwrappedLine)
3046 if (!Style.RemoveBracesLLVM)
3049 assert(!NestedTooDeep.empty());
3050 KeepElseBraces = KeepElseBraces ||
3051 (ElseLeftBrace && !ElseLeftBrace->MatchingParen) ||
3052 NestedTooDeep.back();
3054 NestedTooDeep.pop_back();
3056 if (!KeepIfBraces && !KeepElseBraces) {
3059 }
else if (IfLeftBrace) {
3060 FormatToken *IfRightBrace = IfLeftBrace->MatchingParen;
3062 assert(IfRightBrace->MatchingParen == IfLeftBrace);
3063 assert(!IfLeftBrace->Optional);
3064 assert(!IfRightBrace->Optional);
3065 IfLeftBrace->MatchingParen =
nullptr;
3066 IfRightBrace->MatchingParen =
nullptr;
3076void UnwrappedLineParser::parseTryCatch() {
3077 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) &&
"'try' expected");
3079 bool NeedsUnwrappedLine =
false;
3080 bool HasCtorInitializer =
false;
3081 if (FormatTok->is(tok::colon)) {
3082 auto *Colon = FormatTok;
3085 if (FormatTok->is(tok::identifier)) {
3086 HasCtorInitializer =
true;
3087 Colon->setFinalizedType(TT_CtorInitializerColon);
3092 while (FormatTok->is(tok::comma))
3095 while (FormatTok->is(tok::identifier)) {
3097 if (FormatTok->is(tok::l_paren)) {
3099 }
else if (FormatTok->is(tok::l_brace)) {
3106 while (FormatTok->is(tok::comma))
3111 if (Style.isJava() && FormatTok->is(tok::l_paren))
3114 keepAncestorBraces();
3116 if (FormatTok->is(tok::l_brace)) {
3117 if (HasCtorInitializer)
3118 FormatTok->setFinalizedType(TT_FunctionLBrace);
3119 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3121 if (Style.BraceWrapping.BeforeCatch)
3124 NeedsUnwrappedLine =
true;
3125 }
else if (FormatTok->isNot(tok::kw_catch)) {
3131 parseStructuralElement();
3134 for (
bool SeenCatch =
false;;) {
3135 if (FormatTok->is(tok::at))
3137 if (FormatTok->isNoneOf(tok::kw_catch, Keywords.kw___except,
3138 tok::kw___finally, tok::objc_catch,
3139 tok::objc_finally) &&
3140 !((Style.isJava() || Style.isJavaScript()) &&
3141 FormatTok->is(Keywords.kw_finally))) {
3144 if (FormatTok->is(tok::kw_catch))
3147 while (FormatTok->isNot(tok::l_brace)) {
3148 if (FormatTok->is(tok::l_paren)) {
3152 if (FormatTok->isOneOf(tok::semi, tok::r_brace) ||
eof()) {
3153 if (Style.RemoveBracesLLVM)
3154 NestedTooDeep.pop_back();
3160 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3163 NeedsUnwrappedLine =
false;
3164 Line->MustBeDeclaration =
false;
3165 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3167 if (Style.BraceWrapping.BeforeCatch)
3170 NeedsUnwrappedLine =
true;
3173 if (Style.RemoveBracesLLVM)
3174 NestedTooDeep.pop_back();
3176 if (NeedsUnwrappedLine)
3180void UnwrappedLineParser::parseNamespaceOrExportBlock(
unsigned AddLevels) {
3181 bool ManageWhitesmithsBraces =
3182 AddLevels == 0u && Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
3186 if (ManageWhitesmithsBraces)
3191 parseBlock(
true, AddLevels,
true,
3192 true,
nullptr, ManageWhitesmithsBraces);
3194 addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep);
3196 if (ManageWhitesmithsBraces)
3200void UnwrappedLineParser::parseNamespace() {
3201 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
3202 "'namespace' expected");
3206 if (InitialToken.is(TT_NamespaceMacro)) {
3209 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
3210 tok::l_square, tok::period, tok::l_paren) ||
3211 (Style.isCSharp() && FormatTok->is(tok::kw_union))) {
3212 if (FormatTok->is(tok::l_square))
3214 else if (FormatTok->is(tok::l_paren))
3220 if (FormatTok->is(tok::l_brace)) {
3221 FormatTok->setFinalizedType(TT_NamespaceLBrace);
3224 Tokens->peekNextToken()->is(tok::r_brace))) {
3228 unsigned AddLevels =
3229 Style.NamespaceIndentation == FormatStyle::NI_All ||
3230 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
3231 DeclarationScopeStack.size() > 1)
3234 parseNamespaceOrExportBlock(AddLevels);
3239void UnwrappedLineParser::parseCppExportBlock() {
3240 parseNamespaceOrExportBlock(Style.IndentExportBlock ? 1 : 0);
3243void UnwrappedLineParser::parseNew() {
3244 assert(FormatTok->is(tok::kw_new) &&
"'new' expected");
3247 if (Style.isCSharp()) {
3250 if (FormatTok->is(tok::l_paren))
3254 if (FormatTok->is(tok::l_brace))
3257 if (FormatTok->isOneOf(tok::semi, tok::comma))
3264 if (!Style.isJava())
3270 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
3274 if (FormatTok->is(tok::l_paren)) {
3278 if (FormatTok->is(tok::l_brace))
3286void UnwrappedLineParser::parseLoopBody(
bool KeepBraces,
bool WrapRightBrace) {
3287 keepAncestorBraces();
3289 if (isBlockBegin(*FormatTok)) {
3290 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3292 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3293 parseBlock(
false, 1u,
3295 setPreviousRBraceType(TT_ControlStatementRBrace);
3297 assert(!NestedTooDeep.empty());
3298 if (!NestedTooDeep.back())
3304 parseUnbracedBody();
3308 NestedTooDeep.pop_back();
3311void UnwrappedLineParser::parseForOrWhileLoop(
bool HasParens) {
3312 assert((FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) ||
3313 (Style.isVerilog() &&
3314 FormatTok->isOneOf(Keywords.kw_always, Keywords.kw_always_comb,
3315 Keywords.kw_always_ff, Keywords.kw_always_latch,
3316 Keywords.kw_final, Keywords.kw_initial,
3317 Keywords.kw_foreach, Keywords.kw_forever,
3318 Keywords.kw_repeat))) &&
3319 "'for', 'while' or foreach macro expected");
3320 const bool KeepBraces = !Style.RemoveBracesLLVM ||
3321 FormatTok->isNoneOf(tok::kw_for, tok::kw_while);
3325 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
3327 if (IsCpp && FormatTok->is(tok::kw_co_await))
3329 if (HasParens && FormatTok->is(tok::l_paren)) {
3333 if (Style.isVerilog())
3334 FormatTok->setFinalizedType(TT_ConditionLParen);
3338 if (Style.isVerilog()) {
3340 parseVerilogSensitivityList();
3341 }
else if (Style.AllowShortLoopsOnASingleLine && FormatTok->is(tok::semi) &&
3342 Tokens->getPreviousToken()->is(tok::r_paren)) {
3349 parseLoopBody(KeepBraces,
true);
3352void UnwrappedLineParser::parseDoWhile() {
3353 assert(FormatTok->is(tok::kw_do) &&
"'do' expected");
3356 parseLoopBody(
true, Style.BraceWrapping.BeforeWhile);
3359 if (FormatTok->isNot(tok::kw_while)) {
3364 FormatTok->setFinalizedType(TT_DoWhile);
3368 if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)
3372 parseStructuralElement();
3375void UnwrappedLineParser::parseLabel(
3376 FormatStyle::IndentGotoLabelStyle IndentGotoLabels) {
3377 const bool IsGotoLabel = FormatTok->is(TT_GotoLabelColon);
3379 unsigned OldLineLevel =
Line->Level;
3381 switch (IndentGotoLabels) {
3382 case FormatStyle::IGLS_NoIndent:
3385 case FormatStyle::IGLS_OuterIndent:
3386 if (
Line->Level > 1 || (!
Line->InPPDirective &&
Line->Level > 0))
3389 case FormatStyle::IGLS_HalfIndent:
3390 case FormatStyle::IGLS_InnerIndent:
3394 if (!IsGotoLabel && !Style.IndentCaseBlocks &&
3395 CommentsBeforeNextToken.empty() && FormatTok->is(tok::l_brace)) {
3396 CompoundStatementIndenter Indenter(
this,
Line->Level,
3397 Style.BraceWrapping.AfterCaseLabel,
3398 Style.BraceWrapping.IndentBraces);
3400 if (FormatTok->is(tok::kw_break)) {
3401 if (Style.BraceWrapping.AfterControlStatement ==
3402 FormatStyle::BWACS_Always) {
3404 if (!Style.IndentCaseBlocks &&
3405 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) {
3409 parseStructuralElement();
3413 if (FormatTok->is(tok::semi))
3417 Line->Level = OldLineLevel;
3418 if (FormatTok->isNot(tok::l_brace)) {
3419 parseStructuralElement();
3424void UnwrappedLineParser::parseCaseLabel() {
3425 assert(FormatTok->is(tok::kw_case) &&
"'case' expected");
3426 auto *Case = FormatTok;
3431 if (FormatTok->is(tok::colon)) {
3432 FormatTok->setFinalizedType(TT_CaseLabelColon);
3435 if (Style.isJava() && FormatTok->is(tok::arrow)) {
3436 FormatTok->setFinalizedType(TT_CaseLabelArrow);
3437 Case->setFinalizedType(TT_SwitchExpressionLabel);
3444void UnwrappedLineParser::parseSwitch(
bool IsExpr) {
3445 assert(FormatTok->is(tok::kw_switch) &&
"'switch' expected");
3447 if (FormatTok->is(tok::l_paren))
3450 keepAncestorBraces();
3452 if (FormatTok->is(tok::l_brace)) {
3453 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3454 FormatTok->setFinalizedType(IsExpr ? TT_SwitchExpressionLBrace
3455 : TT_ControlStatementLBrace);
3460 setPreviousRBraceType(TT_ControlStatementRBrace);
3466 parseStructuralElement();
3470 if (Style.RemoveBracesLLVM)
3471 NestedTooDeep.pop_back();
3474void UnwrappedLineParser::parseAccessSpecifier() {
3477 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
3480 if (FormatTok->is(tok::colon))
3488bool UnwrappedLineParser::parseRequires(
bool SeenEqual) {
3489 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3493 switch (Tokens->peekNextToken(
true)->Tok.getKind()) {
3496 parseRequiresExpression();
3503 parseRequiresClause();
3514 auto *PreviousNonComment = FormatTok->getPreviousNonComment();
3516 if (!PreviousNonComment ||
3517 PreviousNonComment->is(TT_RequiresExpressionLBrace)) {
3520 parseRequiresClause();
3524 switch (PreviousNonComment->Tok.getKind()) {
3527 case tok::kw_noexcept:
3532 parseRequiresClause();
3541 auto PrevPrev = PreviousNonComment->getPreviousNonComment();
3542 if ((PrevPrev && PrevPrev->is(tok::kw_const)) || !SeenEqual) {
3543 parseRequiresClause();
3549 if (PreviousNonComment->isTypeOrIdentifier(LangOpts)) {
3551 parseRequiresClause();
3555 parseRequiresExpression();
3565 unsigned StoredPosition = Tokens->getPosition();
3568 auto PeekNext = [&Lookahead, &NextToken,
this] {
3570 NextToken = Tokens->getNextToken();
3573 bool FoundType =
false;
3574 bool LastWasColonColon =
false;
3577 for (; Lookahead < 50; PeekNext()) {
3578 switch (NextToken->Tok.getKind()) {
3579 case tok::kw_volatile:
3582 if (OpenAngles == 0) {
3583 FormatTok = Tokens->setPosition(StoredPosition);
3584 parseRequiresExpression();
3592 case tok::coloncolon:
3593 LastWasColonColon =
true;
3595 case tok::kw_decltype:
3596 case tok::identifier:
3597 if (FoundType && !LastWasColonColon && OpenAngles == 0) {
3598 FormatTok = Tokens->setPosition(StoredPosition);
3599 parseRequiresExpression();
3603 LastWasColonColon =
false;
3612 if (NextToken->isTypeName(LangOpts)) {
3613 FormatTok = Tokens->setPosition(StoredPosition);
3614 parseRequiresExpression();
3621 FormatTok = Tokens->setPosition(StoredPosition);
3622 parseRequiresClause();
3631void UnwrappedLineParser::parseRequiresClause() {
3632 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3637 bool InRequiresExpression =
3638 !FormatTok->Previous ||
3639 FormatTok->Previous->is(TT_RequiresExpressionLBrace);
3641 FormatTok->setFinalizedType(InRequiresExpression
3642 ? TT_RequiresClauseInARequiresExpression
3643 : TT_RequiresClause);
3648 parseConstraintExpression();
3650 if (!InRequiresExpression && FormatTok->Previous)
3651 FormatTok->Previous->ClosesRequiresClause =
true;
3659void UnwrappedLineParser::parseRequiresExpression() {
3660 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3662 FormatTok->setFinalizedType(TT_RequiresExpression);
3665 if (FormatTok->is(tok::l_paren)) {
3666 FormatTok->setFinalizedType(TT_RequiresExpressionLParen);
3670 if (FormatTok->is(tok::l_brace)) {
3671 FormatTok->setFinalizedType(TT_RequiresExpressionLBrace);
3680void UnwrappedLineParser::parseConstraintExpression() {
3687 bool LambdaNextTimeAllowed =
true;
3697 bool TopLevelParensAllowed =
true;
3700 bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed,
false);
3702 switch (FormatTok->Tok.getKind()) {
3703 case tok::kw_requires:
3704 parseRequiresExpression();
3708 if (!TopLevelParensAllowed)
3710 parseParens(TT_BinaryOperator);
3711 TopLevelParensAllowed =
false;
3715 if (!LambdaThisTimeAllowed || !tryToParseLambda())
3722 case tok::kw_struct:
3732 FormatTok->setFinalizedType(TT_BinaryOperator);
3734 LambdaNextTimeAllowed =
true;
3735 TopLevelParensAllowed =
true;
3740 LambdaNextTimeAllowed = LambdaThisTimeAllowed;
3744 case tok::kw_sizeof:
3746 case tok::greaterequal:
3747 case tok::greatergreater:
3749 case tok::lessequal:
3751 case tok::equalequal:
3753 case tok::exclaimequal:
3758 LambdaNextTimeAllowed =
true;
3759 TopLevelParensAllowed =
true;
3764 case tok::numeric_constant:
3765 case tok::coloncolon:
3768 TopLevelParensAllowed =
false;
3773 case tok::kw_static_cast:
3774 case tok::kw_const_cast:
3775 case tok::kw_reinterpret_cast:
3776 case tok::kw_dynamic_cast:
3778 if (FormatTok->isNot(tok::less))
3782 parseBracedList(
true);
3786 if (!FormatTok->Tok.getIdentifierInfo()) {
3796 assert(FormatTok->Previous);
3797 switch (FormatTok->Previous->Tok.getKind()) {
3798 case tok::coloncolon:
3802 case tok::kw_requires:
3811 if (FormatTok->is(tok::less)) {
3813 parseBracedList(
true);
3815 TopLevelParensAllowed =
false;
3821bool UnwrappedLineParser::parseEnum() {
3825 if (FormatTok->is(tok::kw_enum))
3831 if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question))
3835 if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal))
3840 if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
3842 while (FormatTok->is(tok::l_square))
3843 if (!handleCppAttributes())
3847 while (FormatTok->Tok.getIdentifierInfo() ||
3848 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
3849 tok::greater, tok::comma, tok::question,
3851 if (FormatTok->is(tok::colon))
3852 FormatTok->setFinalizedType(TT_EnumUnderlyingTypeColon);
3853 if (Style.isVerilog()) {
3854 FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
3857 while (FormatTok->is(tok::l_square))
3863 if (FormatTok->is(tok::l_paren))
3865 if (FormatTok->is(tok::identifier)) {
3869 if (IsCpp && FormatTok->is(tok::identifier))
3875 if (FormatTok->isNot(tok::l_brace))
3877 FormatTok->setFinalizedType(TT_EnumLBrace);
3878 FormatTok->setBlockKind(BK_Block);
3880 if (Style.isJava()) {
3882 parseJavaEnumBody();
3885 if (Style.Language == FormatStyle::LK_Proto) {
3890 const bool ManageWhitesmithsBraces =
3891 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
3893 if (!Style.AllowShortEnumsOnASingleLine &&
3895 Tokens->peekNextToken()->is(tok::r_brace))) {
3900 if (ManageWhitesmithsBraces)
3905 if (!Style.AllowShortEnumsOnASingleLine) {
3907 if (!ManageWhitesmithsBraces)
3910 const auto OpeningLineIndex = CurrentLines->empty()
3911 ? UnwrappedLine::kInvalidIndex
3912 : CurrentLines->size() - 1;
3913 bool HasError = !parseBracedList(
false,
true);
3914 if (!Style.AllowShortEnumsOnASingleLine && !ManageWhitesmithsBraces)
3917 if (FormatTok->is(tok::semi))
3921 setPreviousRBraceType(TT_EnumRBrace);
3922 if (ManageWhitesmithsBraces)
3923 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
3931bool UnwrappedLineParser::parseStructLike() {
3936 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp()) {
3937 if (FormatTok->is(tok::semi))
3948class ScopedTokenPosition {
3949 unsigned StoredPosition;
3950 FormatTokenSource *Tokens;
3953 ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) {
3954 assert(Tokens &&
"Tokens expected to not be null");
3955 StoredPosition = Tokens->getPosition();
3958 ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); }
3964bool UnwrappedLineParser::tryToParseSimpleAttribute() {
3965 ScopedTokenPosition AutoPosition(Tokens);
3973 if (
Tok->
is(tok::r_square))
3975 Tok = Tokens->getNextToken();
3977 if (
Tok->
is(tok::eof))
3979 Tok = Tokens->getNextToken();
3982 Tok = Tokens->getNextToken();
3983 if (
Tok->
is(tok::semi))
3988void UnwrappedLineParser::parseJavaEnumBody() {
3989 assert(FormatTok->is(tok::l_brace));
3995 unsigned StoredPosition = Tokens->getPosition();
3996 bool IsSimple =
true;
3999 if (
Tok->
is(tok::r_brace))
4007 Tok = Tokens->getNextToken();
4009 FormatTok = Tokens->setPosition(StoredPosition);
4026 if (FormatTok->is(tok::l_brace)) {
4028 parseBlock(
true, 1u,
4030 }
else if (FormatTok->is(tok::l_paren)) {
4032 }
else if (FormatTok->is(tok::comma)) {
4035 }
else if (FormatTok->is(tok::semi)) {
4039 }
else if (FormatTok->is(tok::r_brace)) {
4048 parseLevel(OpeningBrace);
4054void UnwrappedLineParser::parseRecord(
bool ParseAsExpr,
bool IsJavaRecord) {
4055 assert(!IsJavaRecord || FormatTok->is(Keywords.kw_record));
4060 IsJavaRecord && FormatTok->is(tok::identifier) ? FormatTok :
nullptr;
4061 bool IsDerived =
false;
4063 return Tok->
is(tok::identifier) &&
Tok->TokenText !=
Tok->TokenText.upper();
4067 bool JSPastExtendsOrImplements =
false;
4071 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
4072 tok::kw_alignas, tok::l_square) ||
4073 FormatTok->isAttribute() ||
4074 ((Style.isJava() || Style.isJavaScript()) &&
4075 FormatTok->isOneOf(tok::period, tok::comma))) {
4076 if (Style.isJavaScript() &&
4077 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
4078 JSPastExtendsOrImplements =
true;
4083 if (FormatTok->is(tok::l_brace)) {
4084 tryToParseBracedList();
4088 if (FormatTok->is(tok::l_square) && handleCppAttributes())
4092 switch (FormatTok->Tok.getKind()) {
4095 if (IsJavaRecord || !IsNonMacroIdentifier(
Previous) ||
4097 Previous->Previous == &InitialToken) {
4101 case tok::coloncolon:
4105 if (JSPastExtendsOrImplements || ClassName ||
4116 auto IsListInitialization = [&] {
4117 if (!ClassName || IsDerived || JSPastExtendsOrImplements)
4119 assert(FormatTok->is(tok::l_brace));
4120 const auto *Prev = FormatTok->getPreviousNonComment();
4122 return Prev != ClassName && Prev->is(tok::identifier) &&
4123 Prev->isNot(Keywords.kw_final) && tryToParseBracedList();
4126 if (FormatTok->isOneOf(tok::colon, tok::less)) {
4127 int AngleNestingLevel = 0;
4129 if (FormatTok->is(tok::less))
4130 ++AngleNestingLevel;
4131 else if (FormatTok->is(tok::greater))
4132 --AngleNestingLevel;
4134 if (AngleNestingLevel == 0) {
4135 if (FormatTok->is(tok::colon)) {
4137 }
else if (!IsDerived && FormatTok->is(tok::identifier) &&
4138 FormatTok->Previous->is(tok::coloncolon)) {
4139 ClassName = FormatTok;
4140 }
else if (FormatTok->is(tok::l_paren) &&
4141 IsNonMacroIdentifier(FormatTok->Previous)) {
4145 if (FormatTok->is(tok::l_brace)) {
4146 if (AngleNestingLevel == 0 && IsListInitialization())
4148 calculateBraceTypes(
true);
4149 if (!tryToParseBracedList())
4152 if (FormatTok->is(tok::l_square)) {
4155 !
Previous->isTypeOrIdentifier(LangOpts))) {
4158 if (!tryToParseLambda())
4165 if (FormatTok->is(tok::semi))
4167 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
4170 parseCSharpGenericTypeConstraint();
4177 auto GetBraceTypes =
4178 [](
const FormatToken &RecordTok) -> std::pair<TokenType, TokenType> {
4179 switch (RecordTok.Tok.getKind()) {
4181 return {TT_ClassLBrace, TT_ClassRBrace};
4182 case tok::kw_struct:
4183 return {TT_StructLBrace, TT_StructRBrace};
4185 return {TT_UnionLBrace, TT_UnionRBrace};
4188 return {TT_RecordLBrace, TT_RecordRBrace};
4191 if (FormatTok->is(tok::l_brace)) {
4192 if (IsListInitialization())
4195 ClassName->setFinalizedType(TT_ClassHeadName);
4196 auto [OpenBraceType, ClosingBraceType] = GetBraceTypes(InitialToken);
4197 FormatTok->setFinalizedType(OpenBraceType);
4202 Tokens->peekNextToken()->is(tok::r_brace),
4207 unsigned AddLevels = Style.IndentAccessModifiers ? 2u : 1u;
4208 parseBlock(
true, AddLevels,
false);
4210 setPreviousRBraceType(ClosingBraceType);
4217void UnwrappedLineParser::parseObjCMethod() {
4218 assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) &&
4219 "'(' or identifier expected.");
4221 if (FormatTok->is(tok::semi)) {
4225 }
else if (FormatTok->is(tok::l_brace)) {
4226 if (Style.BraceWrapping.AfterFunction)
4237void UnwrappedLineParser::parseObjCProtocolList() {
4238 assert(FormatTok->is(tok::less) &&
"'<' expected.");
4242 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4244 }
while (!
eof() && FormatTok->isNot(tok::greater));
4248void UnwrappedLineParser::parseObjCUntilAtEnd() {
4250 if (FormatTok->is(tok::objc_end)) {
4255 if (FormatTok->is(tok::l_brace)) {
4259 }
else if (FormatTok->is(tok::r_brace)) {
4263 }
else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
4267 parseStructuralElement();
4272void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
4273 assert(FormatTok->isOneOf(tok::objc_interface, tok::objc_implementation));
4279 if (FormatTok->is(tok::less))
4280 parseObjCLightweightGenerics();
4281 if (FormatTok->is(tok::colon)) {
4285 if (FormatTok->is(tok::less))
4286 parseObjCLightweightGenerics();
4287 }
else if (FormatTok->is(tok::l_paren)) {
4292 if (FormatTok->is(tok::less))
4293 parseObjCProtocolList();
4295 if (FormatTok->is(tok::l_brace)) {
4296 if (Style.BraceWrapping.AfterObjCDeclaration)
4305 parseObjCUntilAtEnd();
4308void UnwrappedLineParser::parseObjCLightweightGenerics() {
4309 assert(FormatTok->is(tok::less));
4317 unsigned NumOpenAngles = 1;
4321 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4323 if (FormatTok->is(tok::less)) {
4325 }
else if (FormatTok->is(tok::greater)) {
4326 assert(NumOpenAngles > 0 &&
"'>' makes NumOpenAngles negative");
4329 }
while (!
eof() && NumOpenAngles != 0);
4335bool UnwrappedLineParser::parseObjCProtocol() {
4336 assert(FormatTok->is(tok::objc_protocol));
4339 if (FormatTok->is(tok::l_paren)) {
4351 if (FormatTok->is(tok::less))
4352 parseObjCProtocolList();
4355 if (FormatTok->is(tok::semi)) {
4362 parseObjCUntilAtEnd();
4366void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
4367 bool IsImport = FormatTok->is(Keywords.kw_import);
4368 assert(IsImport || FormatTok->is(tok::kw_export));
4372 if (FormatTok->is(tok::kw_default))
4378 if (FormatTok->is(Keywords.kw_async))
4380 if (FormatTok->is(Keywords.kw_function)) {
4389 if (!IsImport && FormatTok->isNoneOf(tok::l_brace, tok::star) &&
4390 !FormatTok->isStringLiteral() &&
4391 !(FormatTok->is(Keywords.kw_type) &&
4392 Tokens->peekNextToken()->isOneOf(tok::l_brace, tok::star))) {
4397 if (FormatTok->is(tok::semi))
4399 if (
Line->Tokens.empty()) {
4404 if (FormatTok->is(tok::l_brace)) {
4405 FormatTok->setBlockKind(BK_Block);
4414void UnwrappedLineParser::parseStatementMacro() {
4416 if (FormatTok->is(tok::l_paren))
4418 if (FormatTok->is(tok::semi))
4423void UnwrappedLineParser::parseVerilogHierarchyIdentifier() {
4426 if (FormatTok->isOneOf(tok::star, tok::period, tok::periodstar,
4427 tok::coloncolon, tok::hash) ||
4428 Keywords.isVerilogIdentifier(*FormatTok)) {
4430 }
else if (FormatTok->is(tok::l_square)) {
4438void UnwrappedLineParser::parseVerilogSensitivityList() {
4439 if (FormatTok->isNot(tok::at))
4443 if (FormatTok->is(tok::at))
4445 switch (FormatTok->Tok.getKind()) {
4453 parseVerilogHierarchyIdentifier();
4458unsigned UnwrappedLineParser::parseVerilogHierarchyHeader() {
4459 unsigned AddLevels = 0;
4461 if (FormatTok->is(Keywords.kw_clocking)) {
4463 if (Keywords.isVerilogIdentifier(*FormatTok))
4465 parseVerilogSensitivityList();
4466 if (FormatTok->is(tok::semi))
4468 }
else if (FormatTok->isOneOf(tok::kw_case, Keywords.kw_casex,
4469 Keywords.kw_casez, Keywords.kw_randcase,
4470 Keywords.kw_randsequence)) {
4471 if (Style.IndentCaseLabels)
4474 if (FormatTok->is(tok::l_paren)) {
4475 FormatTok->setFinalizedType(TT_ConditionLParen);
4478 if (FormatTok->isOneOf(Keywords.kw_inside, Keywords.kw_matches))
4487 if (FormatTok->is(tok::l_square)) {
4488 auto Prev = FormatTok->getPreviousNonComment();
4489 if (Prev && Keywords.isVerilogIdentifier(*Prev))
4490 Prev->setFinalizedType(TT_VerilogDimensionedTypeName);
4492 }
else if (Keywords.isVerilogIdentifier(*FormatTok) ||
4493 FormatTok->isOneOf(tok::hash, tok::hashhash, tok::coloncolon,
4494 Keywords.kw_automatic, tok::kw_static)) {
4501 auto NewLine = [
this]() {
4503 Line->IsContinuation =
true;
4507 while (FormatTok->is(Keywords.kw_import)) {
4510 parseVerilogHierarchyIdentifier();
4511 if (FormatTok->is(tok::semi))
4516 if (FormatTok->is(Keywords.kw_verilogHash)) {
4519 if (FormatTok->is(tok::l_paren)) {
4520 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4524 if (FormatTok->is(tok::l_paren)) {
4526 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4531 if (FormatTok->is(Keywords.kw_extends)) {
4534 parseVerilogHierarchyIdentifier();
4535 if (FormatTok->is(tok::l_paren))
4538 if (FormatTok->is(Keywords.kw_implements)) {
4542 parseVerilogHierarchyIdentifier();
4543 }
while (FormatTok->is(tok::comma));
4547 if (FormatTok->is(tok::at)) {
4549 parseVerilogSensitivityList();
4552 if (FormatTok->is(tok::semi))
4560void UnwrappedLineParser::parseVerilogTable() {
4561 assert(FormatTok->is(Keywords.kw_table));
4565 auto InitialLevel =
Line->Level++;
4566 while (!
eof() && !Keywords.isVerilogEnd(*FormatTok)) {
4569 if (
Tok->
is(tok::semi))
4571 else if (
Tok->
isOneOf(tok::star, tok::colon, tok::question, tok::minus))
4572 Tok->setFinalizedType(TT_VerilogTableItem);
4574 Line->Level = InitialLevel;
4579void UnwrappedLineParser::parseVerilogCaseLabel() {
4585 auto OrigLevel =
Line->Level;
4586 auto FirstLine = CurrentLines->size();
4587 if (
Line->Level == 0 || (
Line->InPPDirective &&
Line->Level <= 1))
4589 else if (!Style.IndentCaseBlocks && Keywords.isVerilogBegin(*FormatTok))
4591 parseStructuralElement();
4594 if (CurrentLines->size() > FirstLine)
4595 (*CurrentLines)[FirstLine].Level = OrigLevel;
4596 Line->Level = OrigLevel;
4599void UnwrappedLineParser::parseVerilogExtern() {
4601 FormatTok->isOneOf(tok::kw_extern, tok::kw_export, Keywords.kw_import));
4604 if (FormatTok->is(tok::string_literal))
4606 if (FormatTok->isOneOf(Keywords.kw_context, Keywords.kw_pure))
4608 if (Keywords.isVerilogIdentifier(*FormatTok))
4610 if (FormatTok->is(tok::equal))
4612 if (Keywords.isVerilogHierarchy(*FormatTok))
4613 parseVerilogHierarchyHeader();
4616bool UnwrappedLineParser::containsExpansion(
const UnwrappedLine &
Line)
const {
4617 for (
const auto &N :
Line.Tokens) {
4618 if (N.Tok->MacroCtx)
4620 for (
const UnwrappedLine &Child : N.Children)
4621 if (containsExpansion(Child))
4627void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) {
4628 if (
Line->Tokens.empty())
4631 if (!parsingPPDirective()) {
4632 llvm::dbgs() <<
"Adding unwrapped line:\n";
4633 printDebugInfo(*
Line);
4641 bool ClosesWhitesmithsBlock =
4642 Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex &&
4643 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
4648 if (!parsingPPDirective() && !InExpansion && containsExpansion(*
Line)) {
4650 Reconstruct.emplace(
Line->Level, Unexpanded);
4651 Reconstruct->addLine(*
Line);
4656 CurrentExpandedLines.push_back(std::move(*
Line));
4658 if (Reconstruct->finished()) {
4659 UnwrappedLine Reconstructed = std::move(*Reconstruct).takeResult();
4660 assert(!Reconstructed.Tokens.empty() &&
4661 "Reconstructed must at least contain the macro identifier.");
4662 assert(!parsingPPDirective());
4664 llvm::dbgs() <<
"Adding unexpanded line:\n";
4665 printDebugInfo(Reconstructed);
4667 ExpandedLines[Reconstructed.Tokens.begin()->Tok] = CurrentExpandedLines;
4668 Lines.push_back(std::move(Reconstructed));
4669 CurrentExpandedLines.clear();
4670 Reconstruct.reset();
4675 assert(!Reconstruct || (CurrentLines != &Lines) || !PPStack.empty());
4676 CurrentLines->push_back(std::move(*
Line));
4678 Line->Tokens.clear();
4679 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
4680 Line->FirstStartColumn = 0;
4681 Line->IsContinuation =
false;
4682 Line->SeenDecltypeAuto =
false;
4684 if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove)
4686 if (!parsingPPDirective() && !PreprocessorDirectives.empty()) {
4687 CurrentLines->append(
4688 std::make_move_iterator(PreprocessorDirectives.begin()),
4689 std::make_move_iterator(PreprocessorDirectives.end()));
4690 PreprocessorDirectives.clear();
4693 FormatTok->Previous =
nullptr;
4696bool UnwrappedLineParser::eof()
const {
return FormatTok->is(tok::eof); }
4698bool UnwrappedLineParser::isOnNewLine(
const FormatToken &FormatTok) {
4699 return (
Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
4700 FormatTok.NewlinesBefore > 0;
4708 const llvm::Regex &CommentPragmasRegex) {
4709 if (
Line.Tokens.empty() || Style.ReflowComments != FormatStyle::RCS_Always)
4712 StringRef IndentContent = FormatTok.
TokenText;
4713 if (FormatTok.
TokenText.starts_with(
"//") ||
4714 FormatTok.
TokenText.starts_with(
"/*")) {
4715 IndentContent = FormatTok.
TokenText.substr(2);
4717 if (CommentPragmasRegex.match(IndentContent))
4792 if (PreviousToken && PreviousToken->
is(tok::l_brace) &&
4794 MinColumnToken = PreviousToken;
4797 PreviousToken = Node.
Tok;
4801 MinColumnToken = Node.
Tok;
4803 if (PreviousToken && PreviousToken->
is(tok::l_brace))
4804 MinColumnToken = PreviousToken;
4810void UnwrappedLineParser::flushComments(
bool NewlineBeforeNext) {
4811 bool JustComments =
Line->Tokens.empty();
4821 Tok->ContinuesLineCommentSection =
4822 continuesLineCommentSection(*
Tok, *
Line, Style, CommentPragmasRegex);
4823 if (isOnNewLine(*
Tok) && JustComments && !
Tok->ContinuesLineCommentSection)
4827 if (NewlineBeforeNext && JustComments)
4829 CommentsBeforeNextToken.clear();
4832void UnwrappedLineParser::nextToken(
int LevelDifference) {
4835 flushComments(isOnNewLine(*FormatTok));
4836 pushToken(FormatTok);
4838 if (!Style.isJavaScript())
4839 readToken(LevelDifference);
4841 readTokenWithJavaScriptASI();
4843 if (Style.isVerilog()) {
4850 if (Keywords.isVerilogEnd(*FormatTok))
4851 FormatTok->Tok.setKind(tok::r_brace);
4855void UnwrappedLineParser::distributeComments(
4875 if (Comments.empty())
4877 bool ShouldPushCommentsInCurrentLine =
true;
4878 bool HasTrailAlignedWithNextToken =
false;
4879 unsigned StartOfTrailAlignedWithNextToken = 0;
4882 for (
unsigned i = Comments.size() - 1; i > 0; --i) {
4884 HasTrailAlignedWithNextToken =
true;
4885 StartOfTrailAlignedWithNextToken = i;
4889 for (
unsigned i = 0, e = Comments.size(); i < e; ++i) {
4891 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
4892 FormatTok->ContinuesLineCommentSection =
false;
4895 *FormatTok, *
Line, Style, CommentPragmasRegex);
4897 if (!FormatTok->ContinuesLineCommentSection &&
4898 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
4899 ShouldPushCommentsInCurrentLine =
false;
4901 if (ShouldPushCommentsInCurrentLine)
4902 pushToken(FormatTok);
4904 CommentsBeforeNextToken.push_back(FormatTok);
4908void UnwrappedLineParser::readToken(
int LevelDifference) {
4910 bool PreviousWasComment =
false;
4911 bool FirstNonCommentOnLine =
false;
4913 FormatTok = Tokens->getNextToken();
4915 while (FormatTok->isOneOf(TT_ConflictStart, TT_ConflictEnd,
4916 TT_ConflictAlternative)) {
4917 if (FormatTok->is(TT_ConflictStart))
4918 conditionalCompilationStart(
false);
4919 else if (FormatTok->is(TT_ConflictAlternative))
4920 conditionalCompilationAlternative();
4921 else if (FormatTok->is(TT_ConflictEnd))
4922 conditionalCompilationEnd();
4923 FormatTok = Tokens->getNextToken();
4924 FormatTok->MustBreakBefore =
true;
4925 FormatTok->MustBreakBeforeFinalized =
true;
4928 auto IsFirstNonCommentOnLine = [](
bool FirstNonCommentOnLine,
4930 bool PreviousWasComment) {
4932 return Tok.HasUnescapedNewline ||
Tok.IsFirst;
4937 if (PreviousWasComment)
4938 return FirstNonCommentOnLine || IsFirstOnLine(
Tok);
4939 return IsFirstOnLine(
Tok);
4942 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
4943 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
4944 PreviousWasComment = FormatTok->is(tok::comment);
4946 while (!
Line->InPPDirective && FormatTok->is(tok::hash) &&
4947 FirstNonCommentOnLine) {
4950 const auto *
Next = Tokens->peekNextToken();
4951 if ((Style.isVerilog() && !Keywords.isVerilogPPDirective(*
Next)) ||
4952 (Style.isTableGen() &&
4953 Next->isNoneOf(tok::kw_else, tok::pp_define, tok::pp_ifdef,
4954 tok::pp_ifndef, tok::pp_endif))) {
4957 distributeComments(Comments, FormatTok);
4961 bool SwitchToPreprocessorLines = !
Line->Tokens.empty();
4962 ScopedLineState BlockState(*
this, SwitchToPreprocessorLines);
4963 assert((LevelDifference >= 0 ||
4964 static_cast<unsigned>(-LevelDifference) <=
Line->Level) &&
4965 "LevelDifference makes Line->Level negative");
4966 Line->Level += LevelDifference;
4970 if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash &&
4971 PPBranchLevel > 0) {
4972 Line->Level += PPBranchLevel;
4974 assert(
Line->Level >=
Line->UnbracedBodyLevel);
4975 Line->Level -=
Line->UnbracedBodyLevel;
4976 flushComments(isOnNewLine(*FormatTok));
4977 const bool IsEndIf = Tokens->peekNextToken()->is(tok::pp_endif);
4979 PreviousWasComment = FormatTok->is(tok::comment);
4980 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
4981 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
4984 if (IsEndIf && IncludeGuard == IG_Defined && PPBranchLevel == -1 &&
4985 getIncludeGuardState(Style.IndentPPDirectives) == IG_Inited &&
4987 (PreviousWasComment &&
4988 Tokens->peekNextToken(
true)->is(tok::eof)))) {
4989 IncludeGuard = IG_Found;
4993 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
4994 !
Line->InPPDirective) {
4998 if (FormatTok->is(tok::identifier) &&
4999 Macros.defined(FormatTok->TokenText) &&
5001 !
Line->InPPDirective) {
5003 unsigned Position = Tokens->getPosition();
5007 auto PreCall = std::move(
Line);
5008 Line.reset(
new UnwrappedLine);
5009 bool OldInExpansion = InExpansion;
5012 auto Args = parseMacroCall();
5013 InExpansion = OldInExpansion;
5014 assert(
Line->Tokens.front().Tok == ID);
5016 auto UnexpandedLine = std::move(
Line);
5018 Line = std::move(PreCall);
5021 llvm::dbgs() <<
"Macro call: " <<
ID->TokenText <<
"(";
5023 llvm::dbgs() <<
"(";
5024 for (
const auto &Arg : Args.value())
5025 for (
const auto &T : Arg)
5026 llvm::dbgs() << T->TokenText <<
" ";
5027 llvm::dbgs() <<
")";
5029 llvm::dbgs() <<
"\n";
5031 if (
Macros.objectLike(
ID->TokenText) && Args &&
5032 !
Macros.hasArity(
ID->TokenText, Args->size())) {
5038 LLVM_DEBUG(llvm::dbgs()
5039 <<
"Macro \"" <<
ID->TokenText
5040 <<
"\" not overloaded for arity " << Args->size()
5041 <<
"or not function-like, using object-like overload.");
5043 UnexpandedLine->Tokens.resize(1);
5044 Tokens->setPosition(Position);
5046 assert(!Args &&
Macros.objectLike(
ID->TokenText));
5048 if ((!Args &&
Macros.objectLike(
ID->TokenText)) ||
5049 (Args &&
Macros.hasArity(
ID->TokenText, Args->size()))) {
5052 Unexpanded[
ID] = std::move(UnexpandedLine);
5054 Macros.expand(ID, std::move(Args));
5055 if (!Expansion.empty())
5056 FormatTok = Tokens->insertTokens(Expansion);
5059 llvm::dbgs() <<
"Expanded: ";
5060 for (
const auto &T : Expansion)
5061 llvm::dbgs() << T->TokenText <<
" ";
5062 llvm::dbgs() <<
"\n";
5066 llvm::dbgs() <<
"Did not expand macro \"" <<
ID->TokenText
5067 <<
"\", because it was used ";
5069 llvm::dbgs() <<
"with " << Args->size();
5071 llvm::dbgs() <<
"without";
5072 llvm::dbgs() <<
" arguments, which doesn't match any definition.\n";
5074 Tokens->setPosition(Position);
5079 if (FormatTok->isNot(tok::comment)) {
5080 distributeComments(Comments, FormatTok);
5085 Comments.push_back(FormatTok);
5088 distributeComments(Comments,
nullptr);
5093template <
typename Iterator>
5094void pushTokens(Iterator Begin, Iterator End,
5096 for (
auto I = Begin; I != End; ++I) {
5097 Into.push_back(I->Tok);
5098 for (
const auto &Child : I->Children)
5099 pushTokens(Child.Tokens.begin(), Child.Tokens.end(), Into);
5104std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>
5105UnwrappedLineParser::parseMacroCall() {
5106 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>> Args;
5107 assert(
Line->Tokens.empty());
5109 if (FormatTok->isNot(tok::l_paren))
5111 unsigned Position = Tokens->getPosition();
5115 auto ArgStart = std::prev(
Line->Tokens.end());
5119 switch (FormatTok->Tok.getKind()) {
5124 case tok::r_paren: {
5130 Args->push_back({});
5131 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5140 Args->push_back({});
5141 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5143 ArgStart = std::prev(
Line->Tokens.end());
5151 Line->Tokens.resize(1);
5152 Tokens->setPosition(Position);
5158 Line->Tokens.push_back(UnwrappedLineNode(
Tok));
5159 if (AtEndOfPPLine) {
5160 auto &
Tok = *
Line->Tokens.back().Tok;
5161 Tok.MustBreakBefore =
true;
5162 Tok.MustBreakBeforeFinalized =
true;
5163 Tok.FirstAfterPPLine =
true;
5164 AtEndOfPPLine =
false;
This file contains the main building blocks of macro support in clang-format.
static bool HasAttribute(const QualType &T)
This file implements a token annotator, i.e.
Defines the clang::TokenKind enum and support functions.
This file contains the declaration of the UnwrappedLineParser, which turns a stream of tokens into Un...
Implements an efficient mapping from strings to IdentifierInfo nodes.
Parser - This implements a parser for the C family of languages.
This class handles loading and caching of source files into memory.
Token - This structure provides full information about a lexed token.
IdentifierInfo * getIdentifierInfo() const
bool isLiteral() const
Return true if this is a "literal", like a numeric constant, string, etc.
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
tok::TokenKind getKind() const
bool isOneOf(Ts... Ks) const
bool isNot(tok::TokenKind K) const
bool isNoneOf(Ts... Ks) const
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
bool isLiteral(TokenKind K)
Return true if this is a "literal" kind, like a numeric constant, string, etc.
The JSON file list parser is used to communicate input to InstallAPI.
bool isLineComment(const FormatToken &FormatTok)
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
std::vector< std::string > Macros
A list of macros of the form <definition>=<expansion> .
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Type
The name was classified as a type.
bool continuesLineComment(const FormatToken &FormatTok, const FormatToken *Previous, const FormatToken *MinColumnToken)
@ Parens
New-expression has a C++98 paren-delimited initializer.
Encapsulates keywords that are context sensitive or for languages not properly supported by Clang's l...
IdentifierInfo * kw_instanceof
IdentifierInfo * kw_implements
IdentifierInfo * kw_override
IdentifierInfo * kw_await
IdentifierInfo * kw_extends
IdentifierInfo * kw_async
IdentifierInfo * kw_abstract
IdentifierInfo * kw_interface
IdentifierInfo * kw_function
IdentifierInfo * kw_yield
IdentifierInfo * kw_where
IdentifierInfo * kw_throws
IdentifierInfo * kw_import
IdentifierInfo * kw_finally
Represents a complete lambda introducer.