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)) {
1459 skipVerilogQualifiers();
1461 if (FormatTok->isOneOf(Keywords.kw_priority, Keywords.kw_unique,
1462 Keywords.kw_unique0)) {
1466 if (Keywords.isVerilogStructuredProcedure(*FormatTok)) {
1467 parseForOrWhileLoop(
false);
1470 if (FormatTok->isOneOf(Keywords.kw_foreach, Keywords.kw_repeat)) {
1471 parseForOrWhileLoop();
1474 if (FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
1475 Keywords.kw_assume, Keywords.kw_cover)) {
1476 parseIfThenElse(IfKind,
false,
true);
1482 if (FormatTok->isAccessSpecifierKeyword()) {
1483 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp())
1486 parseAccessSpecifier();
1489 switch (FormatTok->Tok.getKind()) {
1492 if (FormatTok->is(tok::l_brace)) {
1493 FormatTok->setFinalizedType(TT_InlineASMBrace);
1495 while (FormatTok && !
eof()) {
1496 if (FormatTok->is(tok::r_brace)) {
1497 FormatTok->setFinalizedType(TT_InlineASMBrace);
1502 FormatTok->Finalized =
true;
1507 case tok::kw_namespace:
1511 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1522 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1526 parseForOrWhileLoop();
1529 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1537 case tok::kw_switch:
1538 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1544 case tok::kw_default: {
1546 if (Style.isVerilog())
1548 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1554 if (FormatTok->is(tok::colon)) {
1555 FormatTok->setFinalizedType(TT_CaseLabelColon);
1559 if (FormatTok->is(tok::arrow)) {
1560 FormatTok->setFinalizedType(TT_CaseLabelArrow);
1561 Default->setFinalizedType(TT_SwitchExpressionLabel);
1570 if (Style.Language == FormatStyle::LK_Proto) {
1574 if (Style.isVerilog()) {
1579 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1588 if (FormatTok->is(tok::kw_case))
1593 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1599 case tok::kw_extern:
1600 if (Style.isVerilog()) {
1603 parseVerilogExtern();
1607 if (FormatTok->is(tok::string_literal)) {
1609 if (FormatTok->is(tok::l_brace)) {
1610 if (Style.BraceWrapping.AfterExternBlock)
1614 unsigned AddLevels =
1615 (Style.IndentExternBlock == FormatStyle::IEBS_Indent) ||
1616 (Style.BraceWrapping.AfterExternBlock &&
1617 Style.IndentExternBlock ==
1618 FormatStyle::IEBS_AfterExternBlock)
1621 parseBlock(
true, AddLevels);
1627 case tok::kw_export:
1628 if (Style.isJavaScript()) {
1629 parseJavaScriptEs6ImportExport();
1632 if (Style.isVerilog()) {
1633 parseVerilogExtern();
1638 if (FormatTok->is(tok::kw_namespace)) {
1642 if (FormatTok->is(tok::l_brace)) {
1643 parseCppExportBlock();
1646 if (FormatTok->is(Keywords.kw_import) && parseModuleImport())
1650 case tok::kw_inline:
1652 if (FormatTok->is(tok::kw_namespace)) {
1657 case tok::identifier:
1658 if (FormatTok->is(TT_ForEachMacro)) {
1659 parseForOrWhileLoop();
1662 if (FormatTok->is(TT_MacroBlockBegin)) {
1663 parseBlock(
false, 1u,
1667 if (FormatTok->is(Keywords.kw_import)) {
1668 if (Style.isJavaScript()) {
1669 parseJavaScriptEs6ImportExport();
1672 if (Style.Language == FormatStyle::LK_Proto) {
1674 if (FormatTok->is(tok::kw_public))
1676 if (FormatTok->isNot(tok::string_literal))
1679 if (FormatTok->is(tok::semi))
1684 if (Style.isVerilog()) {
1685 parseVerilogExtern();
1688 if (IsCpp && parseModuleImport())
1691 if (IsCpp && FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
1692 Keywords.kw_slots, Keywords.kw_qslots)) {
1694 if (FormatTok->is(tok::colon)) {
1700 if (IsCpp && FormatTok->is(TT_StatementMacro)) {
1701 parseStatementMacro();
1704 if (IsCpp && FormatTok->is(TT_NamespaceMacro)) {
1712 if (!Style.isJavaScript() && !Style.isVerilog() && !Style.isTableGen() &&
1713 Tokens->peekNextToken()->is(tok::colon) && !
Line->MustBeDeclaration) {
1715 if (!
Line->InMacroBody || CurrentLines->size() > 1)
1716 Line->Tokens.begin()->Tok->MustBreakBefore =
true;
1717 FormatTok->setFinalizedType(TT_GotoLabelColon);
1718 parseLabel(Style.IndentGotoLabels);
1723 if (Style.isJava() && FormatTok->is(Keywords.kw_record)) {
1724 parseRecord(
false,
true);
1734 bool SeenEqual =
false;
1735 for (
const bool InRequiresExpression =
1736 OpeningBrace && OpeningBrace->isOneOf(TT_RequiresExpressionLBrace,
1737 TT_CompoundRequirementLBrace);
1740 switch (FormatTok->Tok.getKind()) {
1743 if (FormatTok->is(tok::l_brace)) {
1748 if (Style.isJava() && FormatTok->is(Keywords.kw_interface)) {
1752 switch (
bool IsAutoRelease =
false; FormatTok->Tok.getObjCKeywordID()) {
1753 case tok::objc_public:
1754 case tok::objc_protected:
1755 case tok::objc_package:
1756 case tok::objc_private:
1757 return parseAccessSpecifier();
1758 case tok::objc_interface:
1759 case tok::objc_implementation:
1760 return parseObjCInterfaceOrImplementation();
1761 case tok::objc_protocol:
1762 if (parseObjCProtocol())
1767 case tok::objc_optional:
1768 case tok::objc_required:
1772 case tok::objc_autoreleasepool:
1773 IsAutoRelease =
true;
1775 case tok::objc_synchronized:
1777 if (!IsAutoRelease && FormatTok->is(tok::l_paren)) {
1781 if (FormatTok->is(tok::l_brace)) {
1782 if (Style.BraceWrapping.AfterControlStatement ==
1783 FormatStyle::BWACS_Always) {
1799 case tok::kw_requires: {
1801 bool ParsedClause = parseRequires(SeenEqual);
1822 if (!IsCpp && !Style.isVerilog()) {
1827 case tok::kw_typedef:
1829 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1830 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS,
1831 Keywords.kw_CF_CLOSED_ENUM,
1832 Keywords.kw_NS_CLOSED_ENUM)) {
1837 if (Style.isVerilog()) {
1842 if (Style.isTableGen()) {
1849 case tok::kw_struct:
1851 if (parseStructLike())
1854 case tok::kw_decltype:
1856 if (FormatTok->is(tok::l_paren)) {
1858 if (FormatTok->Previous &&
1859 FormatTok->Previous->endsSequence(tok::r_paren, tok::kw_auto,
1861 Line->SeenDecltypeAuto =
true;
1868 if (Style.isJava() && FormatTok && FormatTok->is(tok::kw_class))
1870 if (Style.isJavaScript() && FormatTok &&
1871 FormatTok->Tok.getIdentifierInfo()) {
1884 case tok::string_literal:
1885 if (Style.isVerilog() && FormatTok->is(TT_VerilogProtected)) {
1886 FormatTok->Finalized =
true;
1893 case tok::l_paren: {
1900 Tokens->peekNextToken(
true),
1907 case tok::kw_operator:
1909 if (FormatTok->isBinaryOperator())
1913 const auto *Prev = FormatTok->getPreviousNonComment();
1915 if (Prev && Prev->is(tok::identifier))
1918 if (FormatTok->Tok.isAnyIdentifier() || FormatTok->isTypeName(LangOpts)) {
1921 while (FormatTok->is(tok::star))
1925 if (FormatTok->is(tok::l_paren))
1928 if (FormatTok->is(tok::l_brace))
1933 if (InRequiresExpression)
1934 FormatTok->setFinalizedType(TT_BracedListLBrace);
1935 if (!tryToParsePropertyAccessor() && !tryToParseBracedList()) {
1936 IsDecltypeAutoFunction =
Line->SeenDecltypeAuto;
1941 if (Style.isJava() &&
1942 Line->Tokens.front().Tok->is(Keywords.kw_synchronized)) {
1945 if (Style.BraceWrapping.AfterControlStatement ==
1946 FormatStyle::BWACS_Always) {
1949 }
else if (Style.BraceWrapping.AfterFunction) {
1953 FormatTok->setFinalizedType(TT_FunctionLBrace);
1955 IsDecltypeAutoFunction =
false;
1963 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1969 if (Style.BraceWrapping.AfterFunction)
1973 case tok::identifier: {
1974 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where) &&
1975 Line->MustBeDeclaration) {
1977 parseCSharpGenericTypeConstraint();
1980 if (FormatTok->is(TT_MacroBlockEnd)) {
1989 size_t TokenCount =
Line->Tokens.size();
1990 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_function) &&
1993 Line->Tokens.front().Tok->isNot(Keywords.kw_async)))) {
1994 tryToParseJSFunction();
1997 if ((Style.isJavaScript() || Style.isJava()) &&
1998 FormatTok->is(Keywords.kw_interface)) {
1999 if (Style.isJavaScript()) {
2004 unsigned StoredPosition = Tokens->getPosition();
2006 FormatTok = Tokens->setPosition(StoredPosition);
2017 if (Style.isVerilog()) {
2018 if (FormatTok->is(Keywords.kw_table)) {
2019 parseVerilogTable();
2022 if (Keywords.isVerilogBegin(*FormatTok) ||
2023 Keywords.isVerilogHierarchy(*FormatTok)) {
2030 if (!IsCpp && FormatTok->is(Keywords.kw_interface)) {
2031 if (parseStructLike())
2036 if (IsCpp && FormatTok->is(TT_StatementMacro)) {
2037 parseStatementMacro();
2042 StringRef
Text = FormatTok->TokenText;
2049 if (Style.isJavaScript())
2052 auto OneTokenSoFar = [&]() {
2053 auto I =
Line->Tokens.begin(), E =
Line->Tokens.end();
2054 while (I != E && I->Tok->is(tok::comment))
2056 if (Style.isVerilog())
2057 while (I != E && I->Tok->is(tok::hash))
2059 return I != E && (++I == E);
2061 if (OneTokenSoFar()) {
2064 bool FunctionLike = FormatTok->is(tok::l_paren);
2068 bool FollowedByNewline =
2069 CommentsBeforeNextToken.empty()
2070 ? FormatTok->NewlinesBefore > 0
2071 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
2073 if (FollowedByNewline &&
2074 (
Text.size() >= 5 ||
2075 (FunctionLike && FormatTok->isNot(tok::l_paren))) &&
2077 if (PreviousToken->isNot(TT_UntouchableMacroFunc))
2078 PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro);
2086 if ((Style.isJavaScript() || Style.isCSharp()) &&
2087 FormatTok->is(TT_FatArrow)) {
2088 tryToParseChildBlock();
2094 if (FormatTok->is(tok::l_brace)) {
2098 if (!Style.isJavaScript())
2099 FormatTok->setBlockKind(BK_BracedInit);
2102 if (Style.isTableGen() &&
2103 Line->Tokens.begin()->Tok->is(Keywords.kw_defset)) {
2104 FormatTok->setFinalizedType(TT_FunctionLBrace);
2105 parseBlock(
false, 1u,
2112 }
else if (Style.Language == FormatStyle::LK_Proto &&
2113 FormatTok->is(tok::less)) {
2115 parseBracedList(
true);
2122 if (Style.isCSharp() &&
2123 (Tokens->peekNextToken()->isAccessSpecifierKeyword() ||
2130 case tok::kw_switch:
2138 if (Style.Language == FormatStyle::LK_Proto) {
2143 if (Style.isVerilog()) {
2148 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
2155 case tok::kw_default:
2157 if (Style.isVerilog()) {
2158 if (FormatTok->is(tok::colon)) {
2162 if (FormatTok->is(Keywords.kw_clocking)) {
2168 parseVerilogCaseLabel();
2174 if (Style.isVerilog()) {
2175 parseVerilogCaseLabel();
2181 if (FormatTok->is(tok::l_brace))
2182 FormatTok->Previous->setFinalizedType(TT_TemplateCloser);
2191bool UnwrappedLineParser::tryToParsePropertyAccessor() {
2192 assert(FormatTok->is(tok::l_brace));
2193 if (!Style.isCSharp())
2196 if (!FormatTok->Previous || FormatTok->Previous->isNot(tok::identifier))
2204 unsigned int StoredPosition = Tokens->getPosition();
2210 bool HasSpecialAccessor =
false;
2211 bool IsTrivialPropertyAccessor =
true;
2214 if (
const bool IsAccessorKeyword =
2215 Tok->
isOneOf(Keywords.kw_get, Keywords.kw_init, Keywords.kw_set);
2216 IsAccessorKeyword ||
Tok->isAccessSpecifierKeyword() ||
2217 Tok->
isOneOf(tok::l_square, tok::semi, Keywords.kw_internal)) {
2218 if (IsAccessorKeyword)
2219 HasSpecialAccessor =
true;
2220 else if (
Tok->
is(tok::l_square))
2222 Tok = Tokens->getNextToken();
2226 IsTrivialPropertyAccessor =
false;
2231 Tokens->setPosition(StoredPosition);
2237 Tokens->setPosition(StoredPosition);
2238 if (!IsTrivialPropertyAccessor && Style.BraceWrapping.AfterFunction)
2242 switch (FormatTok->Tok.getKind()) {
2245 if (FormatTok->is(tok::equal)) {
2246 while (!
eof() && FormatTok->isNot(tok::semi))
2259 if (FormatTok->is(TT_FatArrow)) {
2263 }
while (!
eof() && FormatTok->isNot(tok::semi));
2272 if (FormatTok->isOneOf(Keywords.kw_get, Keywords.kw_init,
2274 !IsTrivialPropertyAccessor) {
2286bool UnwrappedLineParser::tryToParseLambda() {
2287 assert(FormatTok->is(tok::l_square));
2293 if (!tryToParseLambdaIntroducer())
2297 bool InTemplateParameterList =
false;
2299 while (FormatTok->isNot(tok::l_brace)) {
2300 if (FormatTok->isTypeName(LangOpts) || FormatTok->isAttribute()) {
2304 switch (FormatTok->Tok.getKind()) {
2308 parseParens(TT_PointerOrReference);
2314 assert(FormatTok->Previous);
2315 if (FormatTok->Previous->is(tok::r_square))
2316 InTemplateParameterList =
true;
2321 case tok::kw_struct:
2323 case tok::kw_template:
2324 case tok::kw_typename:
2328 case tok::kw_constexpr:
2329 case tok::kw_consteval:
2332 case tok::identifier:
2333 case tok::numeric_constant:
2334 case tok::coloncolon:
2335 case tok::kw_mutable:
2336 case tok::kw_noexcept:
2337 case tok::kw_static:
2362 case tok::equalequal:
2363 case tok::exclaimequal:
2364 case tok::greaterequal:
2365 case tok::lessequal:
2371 if (Arrow || InTemplateParameterList) {
2380 case tok::kw_requires:
2381 parseRequiresClause();
2384 if (!InTemplateParameterList)
2393 FormatTok->setFinalizedType(TT_LambdaLBrace);
2394 LSquare.setFinalizedType(TT_LambdaLSquare);
2397 Arrow->setFinalizedType(TT_LambdaArrow);
2399 NestedLambdas.push_back(
Line->SeenDecltypeAuto);
2401 assert(!NestedLambdas.empty());
2402 NestedLambdas.pop_back();
2407bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
2412 const auto *PrevPrev =
Previous->getPreviousNonComment();
2413 if (
Previous->is(tok::star) && PrevPrev && PrevPrev->isTypeName(LangOpts))
2421 if (!PrevPrev || PrevPrev->isNoneOf(tok::greater, tok::r_paren))
2425 Previous->isNoneOf(tok::kw_return, tok::kw_co_await, tok::kw_co_yield,
2426 tok::kw_co_return)) {
2430 if (LeftSquare->isCppStructuredBinding(IsCpp))
2432 if (FormatTok->is(tok::l_square) ||
tok::isLiteral(FormatTok->Tok.getKind()))
2434 if (FormatTok->is(tok::r_square)) {
2436 if (
Next->is(tok::greater))
2443void UnwrappedLineParser::tryToParseJSFunction() {
2444 assert(FormatTok->is(Keywords.kw_function));
2445 if (FormatTok->is(Keywords.kw_async))
2451 if (FormatTok->is(tok::star)) {
2452 FormatTok->setFinalizedType(TT_OverloadedOperator);
2457 if (FormatTok->is(tok::identifier))
2460 if (FormatTok->isNot(tok::l_paren))
2466 if (FormatTok->is(tok::colon)) {
2472 if (FormatTok->is(tok::l_brace))
2473 tryToParseBracedList();
2475 while (FormatTok->isNoneOf(tok::l_brace, tok::semi) && !
eof())
2479 if (FormatTok->is(tok::semi))
2485bool UnwrappedLineParser::tryToParseBracedList() {
2486 if (FormatTok->is(BK_Unknown))
2487 calculateBraceTypes();
2488 assert(FormatTok->isNot(BK_Unknown));
2489 if (FormatTok->is(BK_Block))
2496bool UnwrappedLineParser::tryToParseChildBlock() {
2497 assert(Style.isJavaScript() || Style.isCSharp());
2498 assert(FormatTok->is(TT_FatArrow));
2503 if (FormatTok->isNot(tok::l_brace))
2509bool UnwrappedLineParser::parseBracedList(
bool IsAngleBracket,
bool IsEnum) {
2510 assert(!IsAngleBracket || !IsEnum);
2511 bool HasError =
false;
2516 if (Style.isCSharp() && FormatTok->is(TT_FatArrow) &&
2517 tryToParseChildBlock()) {
2520 if (Style.isJavaScript()) {
2521 if (FormatTok->is(Keywords.kw_function)) {
2522 tryToParseJSFunction();
2525 if (FormatTok->is(tok::l_brace)) {
2527 if (tryToParseBracedList())
2532 if (FormatTok->is(IsAngleBracket ? tok::greater : tok::r_brace)) {
2534 FormatTok->setBlockKind(BK_Block);
2535 if (!Style.AllowShortEnumsOnASingleLine)
2541 switch (FormatTok->Tok.getKind()) {
2543 if (Style.isCSharp())
2552 if (Style.isJavaScript()) {
2553 if (FormatTok->is(tok::l_brace))
2561 FormatTok->setBlockKind(BK_BracedInit);
2562 if (!IsAngleBracket) {
2563 auto *Prev = FormatTok->Previous;
2564 if (Prev && Prev->is(tok::greater))
2565 Prev->setFinalizedType(TT_TemplateCloser);
2573 parseBracedList(
true);
2580 if (Style.isJavaScript()) {
2591 if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
2594 case tok::kw_requires:
2595 parseRequiresExpression();
2611bool UnwrappedLineParser::parseParens(TokenType StarAndAmpTokenType,
2613 assert(FormatTok->is(tok::l_paren) &&
"'(' expected.");
2614 auto *LParen = FormatTok;
2615 auto *Prev = FormatTok->Previous;
2616 bool SeenComma =
false;
2617 bool SeenEqual =
false;
2618 bool MightBeFoldExpr =
false;
2620 const bool MightBeStmtExpr = FormatTok->is(tok::l_brace);
2621 if (!InMacroCall && Prev && Prev->is(TT_FunctionLikeMacro))
2624 switch (FormatTok->Tok.getKind()) {
2626 if (parseParens(StarAndAmpTokenType, InMacroCall))
2628 if (Style.isJava() && FormatTok->is(tok::l_brace))
2631 case tok::r_paren: {
2632 auto *RParen = FormatTok;
2635 auto OptionalParens = [&] {
2636 if (Style.RemoveParentheses == FormatStyle::RPS_Leave ||
2637 MightBeStmtExpr || MightBeFoldExpr || SeenComma || InMacroCall ||
2638 Line->InMacroBody || RParen->getPreviousNonComment() == LParen) {
2641 const bool DoubleParens =
2642 Prev->is(tok::l_paren) && FormatTok->is(tok::r_paren);
2644 const auto *PrevPrev = Prev->getPreviousNonComment();
2645 const bool Excluded =
2647 (PrevPrev->isOneOf(tok::kw___attribute, tok::kw_decltype) ||
2649 (PrevPrev->isOneOf(tok::kw_if, tok::kw_while) ||
2650 PrevPrev->endsSequence(tok::kw_constexpr, tok::kw_if))));
2654 const bool CommaSeparated =
2655 Prev->isOneOf(tok::l_paren, tok::comma) &&
2656 FormatTok->isOneOf(tok::comma, tok::r_paren);
2657 if (CommaSeparated &&
2659 !Prev->endsSequence(tok::comma, tok::ellipsis) &&
2661 !(FormatTok->is(tok::comma) &&
2662 Tokens->peekNextToken()->is(tok::ellipsis))) {
2665 const bool ReturnParens =
2666 Style.RemoveParentheses == FormatStyle::RPS_ReturnStatement &&
2667 ((NestedLambdas.empty() && !IsDecltypeAutoFunction) ||
2668 (!NestedLambdas.empty() && !NestedLambdas.back())) &&
2669 Prev->isOneOf(tok::kw_return, tok::kw_co_return) &&
2670 FormatTok->is(tok::semi);
2676 if (OptionalParens()) {
2677 LParen->Optional =
true;
2678 RParen->Optional =
true;
2679 }
else if (Prev->is(TT_TypenameMacro)) {
2680 LParen->setFinalizedType(TT_TypeDeclarationParen);
2681 RParen->setFinalizedType(TT_TypeDeclarationParen);
2682 }
else if (Prev->is(tok::greater) && RParen->Previous == LParen) {
2683 Prev->setFinalizedType(TT_TemplateCloser);
2684 }
else if (FormatTok->is(tok::l_brace) && Prev->is(tok::amp) &&
2686 FormatTok->setBlockKind(BK_BracedInit);
2698 if (!tryToParseBracedList())
2703 if (FormatTok->is(tok::l_brace)) {
2713 MightBeFoldExpr =
true;
2718 if (Style.isCSharp() && FormatTok->is(TT_FatArrow))
2719 tryToParseChildBlock();
2724 if (Style.isJavaScript())
2729 case tok::identifier:
2730 if (Style.isJavaScript() && (FormatTok->is(Keywords.kw_function)))
2731 tryToParseJSFunction();
2735 case tok::kw_switch:
2741 case tok::kw_requires:
2742 parseRequiresExpression();
2747 if (StarAndAmpTokenType != TT_Unknown)
2748 FormatTok->setFinalizedType(StarAndAmpTokenType);
2760 assert(FormatTok->is(tok::l_square) &&
"'[' expected.");
2761 if (tryToParseLambda())
2765 switch (FormatTok->Tok.getKind()) {
2778 case tok::l_brace: {
2779 if (!tryToParseBracedList())
2786 if (FormatTok->is(tok::l_brace)) {
2798void UnwrappedLineParser::keepAncestorBraces() {
2799 if (!Style.RemoveBracesLLVM)
2802 const int MaxNestingLevels = 2;
2803 const int Size = NestedTooDeep.size();
2804 if (Size >= MaxNestingLevels)
2805 NestedTooDeep[
Size - MaxNestingLevels] =
true;
2806 NestedTooDeep.push_back(
false);
2810 for (
const auto &
Token : llvm::reverse(
Line.Tokens))
2817void UnwrappedLineParser::parseUnbracedBody(
bool CheckEOF) {
2820 if (Style.InsertBraces && !
Line->InPPDirective && !
Line->Tokens.empty() &&
2821 PreprocessorDirectives.empty() && FormatTok->isNot(tok::semi)) {
2822 Tok = Style.BraceWrapping.AfterControlStatement == FormatStyle::BWACS_Never
2823 ? getLastNonComment(*
Line)
2826 if (
Tok->BraceCount < 0) {
2827 assert(
Tok->BraceCount == -1);
2830 Tok->BraceCount = -1;
2836 ++
Line->UnbracedBodyLevel;
2837 parseStructuralElement();
2838 --
Line->UnbracedBodyLevel;
2841 assert(!
Line->InPPDirective);
2843 for (
const auto &L : llvm::reverse(*CurrentLines)) {
2845 Tok = L.Tokens.back().Tok;
2853 if (CheckEOF &&
eof())
2863 assert(LeftBrace->
is(tok::l_brace));
2871 assert(RightBrace->
is(tok::r_brace));
2879void UnwrappedLineParser::handleAttributes() {
2881 if (FormatTok->isAttribute())
2883 else if (FormatTok->is(tok::l_square))
2884 handleCppAttributes();
2887bool UnwrappedLineParser::handleCppAttributes() {
2889 assert(FormatTok->is(tok::l_square));
2890 if (!tryToParseSimpleAttribute())
2897bool UnwrappedLineParser::isBlockBegin(
const FormatToken &
Tok)
const {
2900 return Style.isVerilog() ? Keywords.isVerilogBegin(
Tok)
2901 :
Tok.
is(tok::l_brace);
2904FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
2906 bool IsVerilogAssert) {
2907 assert((FormatTok->is(tok::kw_if) ||
2908 (Style.isVerilog() &&
2909 FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
2910 Keywords.kw_assume, Keywords.kw_cover))) &&
2914 if (IsVerilogAssert) {
2916 if (FormatTok->is(Keywords.kw_verilogHash)) {
2918 if (FormatTok->is(tok::numeric_constant))
2920 }
else if (FormatTok->isOneOf(Keywords.kw_final, Keywords.kw_property,
2921 Keywords.kw_sequence)) {
2927 if (Style.isTableGen()) {
2928 while (!
eof() && FormatTok->isNot(Keywords.kw_then)) {
2935 if (FormatTok->is(tok::exclaim))
2938 bool KeepIfBraces =
true;
2939 if (FormatTok->is(tok::kw_consteval)) {
2942 KeepIfBraces = !Style.RemoveBracesLLVM || KeepBraces;
2943 if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
2945 if (FormatTok->is(tok::l_paren)) {
2946 FormatTok->setFinalizedType(TT_ConditionLParen);
2952 if (IsVerilogAssert && FormatTok->is(tok::semi)) {
2958 bool NeedsUnwrappedLine =
false;
2959 keepAncestorBraces();
2962 IfStmtKind IfBlockKind = IfStmtKind::NotIf;
2964 if (isBlockBegin(*FormatTok)) {
2965 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
2966 IfLeftBrace = FormatTok;
2967 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
2968 parseBlock(
false, 1u,
2969 true, KeepIfBraces, &IfBlockKind);
2970 setPreviousRBraceType(TT_ControlStatementRBrace);
2971 if (Style.BraceWrapping.BeforeElse)
2974 NeedsUnwrappedLine =
true;
2975 }
else if (IsVerilogAssert && FormatTok->is(tok::kw_else)) {
2978 parseUnbracedBody();
2981 if (Style.RemoveBracesLLVM) {
2982 assert(!NestedTooDeep.empty());
2983 KeepIfBraces = KeepIfBraces ||
2984 (IfLeftBrace && !IfLeftBrace->MatchingParen) ||
2985 NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly ||
2986 IfBlockKind == IfStmtKind::IfElseIf;
2989 bool KeepElseBraces = KeepIfBraces;
2991 IfStmtKind
Kind = IfStmtKind::IfOnly;
2993 if (FormatTok->is(tok::kw_else)) {
2994 if (Style.RemoveBracesLLVM) {
2995 NestedTooDeep.back() =
false;
2996 Kind = IfStmtKind::IfElse;
3000 if (isBlockBegin(*FormatTok)) {
3001 const bool FollowedByIf = Tokens->peekNextToken()->is(tok::kw_if);
3002 FormatTok->setFinalizedType(TT_ElseLBrace);
3003 ElseLeftBrace = FormatTok;
3004 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3005 IfStmtKind ElseBlockKind = IfStmtKind::NotIf;
3007 parseBlock(
false, 1u,
3008 true, KeepElseBraces, &ElseBlockKind);
3009 setPreviousRBraceType(TT_ElseRBrace);
3010 if (FormatTok->is(tok::kw_else)) {
3011 KeepElseBraces = KeepElseBraces ||
3012 ElseBlockKind == IfStmtKind::IfOnly ||
3013 ElseBlockKind == IfStmtKind::IfElseIf;
3014 }
else if (FollowedByIf && IfLBrace && !IfLBrace->Optional) {
3015 KeepElseBraces =
true;
3016 assert(ElseLeftBrace->MatchingParen);
3020 }
else if (!IsVerilogAssert && FormatTok->is(tok::kw_if)) {
3023 const bool IsPrecededByComment =
Previous->is(tok::comment);
3024 if (IsPrecededByComment) {
3028 bool TooDeep =
true;
3029 if (Style.RemoveBracesLLVM) {
3030 Kind = IfStmtKind::IfElseIf;
3031 TooDeep = NestedTooDeep.pop_back_val();
3033 ElseLeftBrace = parseIfThenElse(
nullptr, KeepIfBraces);
3034 if (Style.RemoveBracesLLVM)
3035 NestedTooDeep.push_back(TooDeep);
3036 if (IsPrecededByComment)
3039 parseUnbracedBody(
true);
3042 KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse;
3043 if (NeedsUnwrappedLine)
3047 if (!Style.RemoveBracesLLVM)
3050 assert(!NestedTooDeep.empty());
3051 KeepElseBraces = KeepElseBraces ||
3052 (ElseLeftBrace && !ElseLeftBrace->MatchingParen) ||
3053 NestedTooDeep.back();
3055 NestedTooDeep.pop_back();
3057 if (!KeepIfBraces && !KeepElseBraces) {
3060 }
else if (IfLeftBrace) {
3061 FormatToken *IfRightBrace = IfLeftBrace->MatchingParen;
3063 assert(IfRightBrace->MatchingParen == IfLeftBrace);
3064 assert(!IfLeftBrace->Optional);
3065 assert(!IfRightBrace->Optional);
3066 IfLeftBrace->MatchingParen =
nullptr;
3067 IfRightBrace->MatchingParen =
nullptr;
3077void UnwrappedLineParser::parseTryCatch() {
3078 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) &&
"'try' expected");
3080 bool NeedsUnwrappedLine =
false;
3081 bool HasCtorInitializer =
false;
3082 if (FormatTok->is(tok::colon)) {
3083 auto *Colon = FormatTok;
3086 if (FormatTok->is(tok::identifier)) {
3087 HasCtorInitializer =
true;
3088 Colon->setFinalizedType(TT_CtorInitializerColon);
3093 while (FormatTok->is(tok::comma))
3096 while (FormatTok->is(tok::identifier)) {
3098 if (FormatTok->is(tok::l_paren)) {
3100 }
else if (FormatTok->is(tok::l_brace)) {
3107 while (FormatTok->is(tok::comma))
3112 if (Style.isJava() && FormatTok->is(tok::l_paren))
3115 keepAncestorBraces();
3117 if (FormatTok->is(tok::l_brace)) {
3118 if (HasCtorInitializer)
3119 FormatTok->setFinalizedType(TT_FunctionLBrace);
3120 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3122 if (Style.BraceWrapping.BeforeCatch)
3125 NeedsUnwrappedLine =
true;
3126 }
else if (FormatTok->isNot(tok::kw_catch)) {
3132 parseStructuralElement();
3135 for (
bool SeenCatch =
false;;) {
3136 if (FormatTok->is(tok::at))
3138 if (FormatTok->isNoneOf(tok::kw_catch, Keywords.kw___except,
3139 tok::kw___finally, tok::objc_catch,
3140 tok::objc_finally) &&
3141 !((Style.isJava() || Style.isJavaScript()) &&
3142 FormatTok->is(Keywords.kw_finally))) {
3145 if (FormatTok->is(tok::kw_catch))
3148 while (FormatTok->isNot(tok::l_brace)) {
3149 if (FormatTok->is(tok::l_paren)) {
3153 if (FormatTok->isOneOf(tok::semi, tok::r_brace) ||
eof()) {
3154 if (Style.RemoveBracesLLVM)
3155 NestedTooDeep.pop_back();
3161 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3164 NeedsUnwrappedLine =
false;
3165 Line->MustBeDeclaration =
false;
3166 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3168 if (Style.BraceWrapping.BeforeCatch)
3171 NeedsUnwrappedLine =
true;
3174 if (Style.RemoveBracesLLVM)
3175 NestedTooDeep.pop_back();
3177 if (NeedsUnwrappedLine)
3181void UnwrappedLineParser::parseNamespaceOrExportBlock(
unsigned AddLevels) {
3182 bool ManageWhitesmithsBraces =
3183 AddLevels == 0u && Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
3187 if (ManageWhitesmithsBraces)
3192 parseBlock(
true, AddLevels,
true,
3193 true,
nullptr, ManageWhitesmithsBraces);
3195 addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep);
3197 if (ManageWhitesmithsBraces)
3201void UnwrappedLineParser::parseNamespace() {
3202 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
3203 "'namespace' expected");
3207 if (InitialToken.is(TT_NamespaceMacro)) {
3210 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
3211 tok::l_square, tok::period, tok::l_paren) ||
3212 (Style.isCSharp() && FormatTok->is(tok::kw_union))) {
3213 if (FormatTok->is(tok::l_square))
3215 else if (FormatTok->is(tok::l_paren))
3221 if (FormatTok->is(tok::l_brace)) {
3222 FormatTok->setFinalizedType(TT_NamespaceLBrace);
3225 Tokens->peekNextToken()->is(tok::r_brace))) {
3229 unsigned AddLevels =
3230 Style.NamespaceIndentation == FormatStyle::NI_All ||
3231 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
3232 DeclarationScopeStack.size() > 1)
3235 parseNamespaceOrExportBlock(AddLevels);
3240void UnwrappedLineParser::parseCppExportBlock() {
3241 parseNamespaceOrExportBlock(Style.IndentExportBlock ? 1 : 0);
3244void UnwrappedLineParser::parseNew() {
3245 assert(FormatTok->is(tok::kw_new) &&
"'new' expected");
3248 if (Style.isCSharp()) {
3251 if (FormatTok->is(tok::l_paren))
3255 if (FormatTok->is(tok::l_brace))
3258 if (FormatTok->isOneOf(tok::semi, tok::comma))
3265 if (!Style.isJava())
3271 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
3275 if (FormatTok->is(tok::l_paren)) {
3279 if (FormatTok->is(tok::l_brace))
3287void UnwrappedLineParser::parseLoopBody(
bool KeepBraces,
bool WrapRightBrace) {
3288 keepAncestorBraces();
3290 if (isBlockBegin(*FormatTok)) {
3291 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3293 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3294 parseBlock(
false, 1u,
3296 setPreviousRBraceType(TT_ControlStatementRBrace);
3298 assert(!NestedTooDeep.empty());
3299 if (!NestedTooDeep.back())
3305 parseUnbracedBody();
3309 NestedTooDeep.pop_back();
3312void UnwrappedLineParser::parseForOrWhileLoop(
bool HasParens) {
3313 assert((FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) ||
3314 (Style.isVerilog() &&
3315 FormatTok->isOneOf(Keywords.kw_always, Keywords.kw_always_comb,
3316 Keywords.kw_always_ff, Keywords.kw_always_latch,
3317 Keywords.kw_final, Keywords.kw_initial,
3318 Keywords.kw_foreach, Keywords.kw_forever,
3319 Keywords.kw_repeat))) &&
3320 "'for', 'while' or foreach macro expected");
3321 const bool KeepBraces = !Style.RemoveBracesLLVM ||
3322 FormatTok->isNoneOf(tok::kw_for, tok::kw_while);
3326 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
3328 if (IsCpp && FormatTok->is(tok::kw_co_await))
3330 if (HasParens && FormatTok->is(tok::l_paren)) {
3334 if (Style.isVerilog())
3335 FormatTok->setFinalizedType(TT_ConditionLParen);
3339 if (Style.isVerilog()) {
3341 parseVerilogSensitivityList();
3342 }
else if (Style.AllowShortLoopsOnASingleLine && FormatTok->is(tok::semi) &&
3343 Tokens->getPreviousToken()->is(tok::r_paren)) {
3350 parseLoopBody(KeepBraces,
true);
3353void UnwrappedLineParser::parseDoWhile() {
3354 assert(FormatTok->is(tok::kw_do) &&
"'do' expected");
3357 parseLoopBody(
true, Style.BraceWrapping.BeforeWhile);
3360 if (FormatTok->isNot(tok::kw_while)) {
3365 FormatTok->setFinalizedType(TT_DoWhile);
3369 if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)
3373 parseStructuralElement();
3376void UnwrappedLineParser::parseLabel(
3377 FormatStyle::IndentGotoLabelStyle IndentGotoLabels) {
3378 const bool IsGotoLabel = FormatTok->is(TT_GotoLabelColon);
3380 unsigned OldLineLevel =
Line->Level;
3382 switch (IndentGotoLabels) {
3383 case FormatStyle::IGLS_NoIndent:
3386 case FormatStyle::IGLS_OuterIndent:
3387 if (
Line->Level > 1 || (!
Line->InPPDirective &&
Line->Level > 0))
3390 case FormatStyle::IGLS_HalfIndent:
3391 case FormatStyle::IGLS_InnerIndent:
3395 if (!IsGotoLabel && !Style.IndentCaseBlocks &&
3396 CommentsBeforeNextToken.empty() && FormatTok->is(tok::l_brace)) {
3397 CompoundStatementIndenter Indenter(
this,
Line->Level,
3398 Style.BraceWrapping.AfterCaseLabel,
3399 Style.BraceWrapping.IndentBraces);
3401 if (FormatTok->is(tok::kw_break)) {
3402 if (Style.BraceWrapping.AfterControlStatement ==
3403 FormatStyle::BWACS_Always) {
3405 if (!Style.IndentCaseBlocks &&
3406 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) {
3410 parseStructuralElement();
3414 if (FormatTok->is(tok::semi))
3418 Line->Level = OldLineLevel;
3419 if (FormatTok->isNot(tok::l_brace)) {
3420 parseStructuralElement();
3425void UnwrappedLineParser::parseCaseLabel() {
3426 assert(FormatTok->is(tok::kw_case) &&
"'case' expected");
3427 auto *Case = FormatTok;
3432 if (FormatTok->is(tok::colon)) {
3433 FormatTok->setFinalizedType(TT_CaseLabelColon);
3436 if (Style.isJava() && FormatTok->is(tok::arrow)) {
3437 FormatTok->setFinalizedType(TT_CaseLabelArrow);
3438 Case->setFinalizedType(TT_SwitchExpressionLabel);
3445void UnwrappedLineParser::parseSwitch(
bool IsExpr) {
3446 assert(FormatTok->is(tok::kw_switch) &&
"'switch' expected");
3448 if (FormatTok->is(tok::l_paren))
3451 keepAncestorBraces();
3453 if (FormatTok->is(tok::l_brace)) {
3454 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3455 FormatTok->setFinalizedType(IsExpr ? TT_SwitchExpressionLBrace
3456 : TT_ControlStatementLBrace);
3461 setPreviousRBraceType(TT_ControlStatementRBrace);
3467 parseStructuralElement();
3471 if (Style.RemoveBracesLLVM)
3472 NestedTooDeep.pop_back();
3475void UnwrappedLineParser::parseAccessSpecifier() {
3478 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
3481 if (FormatTok->is(tok::colon))
3489bool UnwrappedLineParser::parseRequires(
bool SeenEqual) {
3490 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3494 switch (Tokens->peekNextToken(
true)->Tok.getKind()) {
3497 parseRequiresExpression();
3504 parseRequiresClause();
3515 auto *PreviousNonComment = FormatTok->getPreviousNonComment();
3517 if (!PreviousNonComment ||
3518 PreviousNonComment->is(TT_RequiresExpressionLBrace)) {
3521 parseRequiresClause();
3525 switch (PreviousNonComment->Tok.getKind()) {
3528 case tok::kw_noexcept:
3533 parseRequiresClause();
3542 auto PrevPrev = PreviousNonComment->getPreviousNonComment();
3543 if ((PrevPrev && PrevPrev->is(tok::kw_const)) || !SeenEqual) {
3544 parseRequiresClause();
3550 if (PreviousNonComment->isTypeOrIdentifier(LangOpts)) {
3552 parseRequiresClause();
3556 parseRequiresExpression();
3566 unsigned StoredPosition = Tokens->getPosition();
3569 auto PeekNext = [&Lookahead, &NextToken,
this] {
3571 NextToken = Tokens->getNextToken();
3574 bool FoundType =
false;
3575 bool LastWasColonColon =
false;
3578 for (; Lookahead < 50; PeekNext()) {
3579 switch (NextToken->Tok.getKind()) {
3580 case tok::kw_volatile:
3583 if (OpenAngles == 0) {
3584 FormatTok = Tokens->setPosition(StoredPosition);
3585 parseRequiresExpression();
3593 case tok::coloncolon:
3594 LastWasColonColon =
true;
3596 case tok::kw_decltype:
3597 case tok::identifier:
3598 if (FoundType && !LastWasColonColon && OpenAngles == 0) {
3599 FormatTok = Tokens->setPosition(StoredPosition);
3600 parseRequiresExpression();
3604 LastWasColonColon =
false;
3613 if (NextToken->isTypeName(LangOpts)) {
3614 FormatTok = Tokens->setPosition(StoredPosition);
3615 parseRequiresExpression();
3622 FormatTok = Tokens->setPosition(StoredPosition);
3623 parseRequiresClause();
3632void UnwrappedLineParser::parseRequiresClause() {
3633 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3638 bool InRequiresExpression =
3639 !FormatTok->Previous ||
3640 FormatTok->Previous->is(TT_RequiresExpressionLBrace);
3642 FormatTok->setFinalizedType(InRequiresExpression
3643 ? TT_RequiresClauseInARequiresExpression
3644 : TT_RequiresClause);
3649 parseConstraintExpression();
3651 if (!InRequiresExpression && FormatTok->Previous)
3652 FormatTok->Previous->ClosesRequiresClause =
true;
3660void UnwrappedLineParser::parseRequiresExpression() {
3661 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3663 FormatTok->setFinalizedType(TT_RequiresExpression);
3666 if (FormatTok->is(tok::l_paren)) {
3667 FormatTok->setFinalizedType(TT_RequiresExpressionLParen);
3671 if (FormatTok->is(tok::l_brace)) {
3672 FormatTok->setFinalizedType(TT_RequiresExpressionLBrace);
3681void UnwrappedLineParser::parseConstraintExpression() {
3688 bool LambdaNextTimeAllowed =
true;
3698 bool TopLevelParensAllowed =
true;
3701 bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed,
false);
3703 switch (FormatTok->Tok.getKind()) {
3704 case tok::kw_requires:
3705 parseRequiresExpression();
3709 if (!TopLevelParensAllowed)
3711 parseParens(TT_BinaryOperator);
3712 TopLevelParensAllowed =
false;
3716 if (!LambdaThisTimeAllowed || !tryToParseLambda())
3723 case tok::kw_struct:
3733 FormatTok->setFinalizedType(TT_BinaryOperator);
3735 LambdaNextTimeAllowed =
true;
3736 TopLevelParensAllowed =
true;
3741 LambdaNextTimeAllowed = LambdaThisTimeAllowed;
3745 case tok::kw_sizeof:
3747 case tok::greaterequal:
3748 case tok::greatergreater:
3750 case tok::lessequal:
3752 case tok::equalequal:
3754 case tok::exclaimequal:
3759 LambdaNextTimeAllowed =
true;
3760 TopLevelParensAllowed =
true;
3765 case tok::numeric_constant:
3766 case tok::coloncolon:
3769 TopLevelParensAllowed =
false;
3774 case tok::kw_static_cast:
3775 case tok::kw_const_cast:
3776 case tok::kw_reinterpret_cast:
3777 case tok::kw_dynamic_cast:
3779 if (FormatTok->isNot(tok::less))
3783 parseBracedList(
true);
3787 if (!FormatTok->Tok.getIdentifierInfo()) {
3797 assert(FormatTok->Previous);
3798 switch (FormatTok->Previous->Tok.getKind()) {
3799 case tok::coloncolon:
3803 case tok::kw_requires:
3812 if (FormatTok->is(tok::less)) {
3814 parseBracedList(
true);
3816 TopLevelParensAllowed =
false;
3822bool UnwrappedLineParser::parseEnum() {
3826 if (FormatTok->is(tok::kw_enum))
3832 if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question))
3836 if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal))
3841 if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
3843 while (FormatTok->is(tok::l_square))
3844 if (!handleCppAttributes())
3848 while (FormatTok->Tok.getIdentifierInfo() ||
3849 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
3850 tok::greater, tok::comma, tok::question,
3852 if (FormatTok->is(tok::colon))
3853 FormatTok->setFinalizedType(TT_EnumUnderlyingTypeColon);
3854 if (Style.isVerilog()) {
3855 FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
3858 while (FormatTok->is(tok::l_square))
3864 if (FormatTok->is(tok::l_paren))
3866 if (FormatTok->is(tok::identifier)) {
3870 if (IsCpp && FormatTok->is(tok::identifier))
3876 if (FormatTok->isNot(tok::l_brace))
3878 FormatTok->setFinalizedType(TT_EnumLBrace);
3879 FormatTok->setBlockKind(BK_Block);
3881 if (Style.isJava()) {
3883 parseJavaEnumBody();
3886 if (Style.Language == FormatStyle::LK_Proto) {
3891 const bool ManageWhitesmithsBraces =
3892 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
3894 if (!Style.AllowShortEnumsOnASingleLine &&
3896 Tokens->peekNextToken()->is(tok::r_brace))) {
3901 if (ManageWhitesmithsBraces)
3906 if (!Style.AllowShortEnumsOnASingleLine) {
3908 if (!ManageWhitesmithsBraces)
3911 const auto OpeningLineIndex = CurrentLines->empty()
3912 ? UnwrappedLine::kInvalidIndex
3913 : CurrentLines->size() - 1;
3914 bool HasError = !parseBracedList(
false,
true);
3915 if (!Style.AllowShortEnumsOnASingleLine && !ManageWhitesmithsBraces)
3918 if (FormatTok->is(tok::semi))
3922 setPreviousRBraceType(TT_EnumRBrace);
3923 if (ManageWhitesmithsBraces)
3924 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
3932bool UnwrappedLineParser::parseStructLike() {
3937 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp()) {
3938 if (FormatTok->is(tok::semi))
3949class ScopedTokenPosition {
3950 unsigned StoredPosition;
3951 FormatTokenSource *Tokens;
3954 ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) {
3955 assert(Tokens &&
"Tokens expected to not be null");
3956 StoredPosition = Tokens->getPosition();
3959 ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); }
3965bool UnwrappedLineParser::tryToParseSimpleAttribute() {
3966 ScopedTokenPosition AutoPosition(Tokens);
3974 if (
Tok->
is(tok::r_square))
3976 Tok = Tokens->getNextToken();
3978 if (
Tok->
is(tok::eof))
3980 Tok = Tokens->getNextToken();
3983 Tok = Tokens->getNextToken();
3984 if (
Tok->
is(tok::semi))
3989void UnwrappedLineParser::parseJavaEnumBody() {
3990 assert(FormatTok->is(tok::l_brace));
3996 unsigned StoredPosition = Tokens->getPosition();
3997 bool IsSimple =
true;
4000 if (
Tok->
is(tok::r_brace))
4008 Tok = Tokens->getNextToken();
4010 FormatTok = Tokens->setPosition(StoredPosition);
4027 if (FormatTok->is(tok::l_brace)) {
4029 parseBlock(
true, 1u,
4031 }
else if (FormatTok->is(tok::l_paren)) {
4033 }
else if (FormatTok->is(tok::comma)) {
4036 }
else if (FormatTok->is(tok::semi)) {
4040 }
else if (FormatTok->is(tok::r_brace)) {
4049 parseLevel(OpeningBrace);
4055void UnwrappedLineParser::parseRecord(
bool ParseAsExpr,
bool IsJavaRecord) {
4056 assert(!IsJavaRecord || FormatTok->is(Keywords.kw_record));
4061 IsJavaRecord && FormatTok->is(tok::identifier) ? FormatTok :
nullptr;
4062 bool IsDerived =
false;
4064 return Tok->
is(tok::identifier) &&
Tok->TokenText !=
Tok->TokenText.upper();
4068 bool JSPastExtendsOrImplements =
false;
4072 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
4073 tok::kw_alignas, tok::l_square) ||
4074 FormatTok->isAttribute() ||
4075 ((Style.isJava() || Style.isJavaScript()) &&
4076 FormatTok->isOneOf(tok::period, tok::comma))) {
4077 if (Style.isJavaScript() &&
4078 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
4079 JSPastExtendsOrImplements =
true;
4084 if (FormatTok->is(tok::l_brace)) {
4085 tryToParseBracedList();
4089 if (FormatTok->is(tok::l_square) && handleCppAttributes())
4093 switch (FormatTok->Tok.getKind()) {
4096 if (IsJavaRecord || !IsNonMacroIdentifier(
Previous) ||
4098 Previous->Previous == &InitialToken) {
4102 case tok::coloncolon:
4106 if (JSPastExtendsOrImplements || ClassName ||
4117 auto IsListInitialization = [&] {
4118 if (!ClassName || IsDerived || JSPastExtendsOrImplements)
4120 assert(FormatTok->is(tok::l_brace));
4121 const auto *Prev = FormatTok->getPreviousNonComment();
4123 return Prev != ClassName && Prev->is(tok::identifier) &&
4124 Prev->isNot(Keywords.kw_final) && tryToParseBracedList();
4127 if (FormatTok->isOneOf(tok::colon, tok::less)) {
4128 int AngleNestingLevel = 0;
4130 if (FormatTok->is(tok::less))
4131 ++AngleNestingLevel;
4132 else if (FormatTok->is(tok::greater))
4133 --AngleNestingLevel;
4135 if (AngleNestingLevel == 0) {
4136 if (FormatTok->is(tok::colon)) {
4138 }
else if (!IsDerived && FormatTok->is(tok::identifier) &&
4139 FormatTok->Previous->is(tok::coloncolon)) {
4140 ClassName = FormatTok;
4141 }
else if (FormatTok->is(tok::l_paren) &&
4142 IsNonMacroIdentifier(FormatTok->Previous)) {
4146 if (FormatTok->is(tok::l_brace)) {
4147 if (AngleNestingLevel == 0 && IsListInitialization())
4149 calculateBraceTypes(
true);
4150 if (!tryToParseBracedList())
4153 if (FormatTok->is(tok::l_square)) {
4156 !
Previous->isTypeOrIdentifier(LangOpts))) {
4159 if (!tryToParseLambda())
4166 if (FormatTok->is(tok::semi))
4168 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
4171 parseCSharpGenericTypeConstraint();
4178 auto GetBraceTypes =
4179 [](
const FormatToken &RecordTok) -> std::pair<TokenType, TokenType> {
4180 switch (RecordTok.Tok.getKind()) {
4182 return {TT_ClassLBrace, TT_ClassRBrace};
4183 case tok::kw_struct:
4184 return {TT_StructLBrace, TT_StructRBrace};
4186 return {TT_UnionLBrace, TT_UnionRBrace};
4189 return {TT_RecordLBrace, TT_RecordRBrace};
4192 if (FormatTok->is(tok::l_brace)) {
4193 if (IsListInitialization())
4196 ClassName->setFinalizedType(TT_ClassHeadName);
4197 auto [OpenBraceType, ClosingBraceType] = GetBraceTypes(InitialToken);
4198 FormatTok->setFinalizedType(OpenBraceType);
4203 Tokens->peekNextToken()->is(tok::r_brace),
4208 unsigned AddLevels = Style.IndentAccessModifiers ? 2u : 1u;
4209 parseBlock(
true, AddLevels,
false);
4211 setPreviousRBraceType(ClosingBraceType);
4218void UnwrappedLineParser::parseObjCMethod() {
4219 assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) &&
4220 "'(' or identifier expected.");
4222 if (FormatTok->is(tok::semi)) {
4226 }
else if (FormatTok->is(tok::l_brace)) {
4227 if (Style.BraceWrapping.AfterFunction)
4238void UnwrappedLineParser::parseObjCProtocolList() {
4239 assert(FormatTok->is(tok::less) &&
"'<' expected.");
4243 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4245 }
while (!
eof() && FormatTok->isNot(tok::greater));
4249void UnwrappedLineParser::parseObjCUntilAtEnd() {
4251 if (FormatTok->is(tok::objc_end)) {
4256 if (FormatTok->is(tok::l_brace)) {
4260 }
else if (FormatTok->is(tok::r_brace)) {
4264 }
else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
4268 parseStructuralElement();
4273void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
4274 assert(FormatTok->isOneOf(tok::objc_interface, tok::objc_implementation));
4280 if (FormatTok->is(tok::less))
4281 parseObjCLightweightGenerics();
4282 if (FormatTok->is(tok::colon)) {
4286 if (FormatTok->is(tok::less))
4287 parseObjCLightweightGenerics();
4288 }
else if (FormatTok->is(tok::l_paren)) {
4293 if (FormatTok->is(tok::less))
4294 parseObjCProtocolList();
4296 if (FormatTok->is(tok::l_brace)) {
4297 if (Style.BraceWrapping.AfterObjCDeclaration)
4306 parseObjCUntilAtEnd();
4309void UnwrappedLineParser::parseObjCLightweightGenerics() {
4310 assert(FormatTok->is(tok::less));
4318 unsigned NumOpenAngles = 1;
4322 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4324 if (FormatTok->is(tok::less)) {
4326 }
else if (FormatTok->is(tok::greater)) {
4327 assert(NumOpenAngles > 0 &&
"'>' makes NumOpenAngles negative");
4330 }
while (!
eof() && NumOpenAngles != 0);
4336bool UnwrappedLineParser::parseObjCProtocol() {
4337 assert(FormatTok->is(tok::objc_protocol));
4340 if (FormatTok->is(tok::l_paren)) {
4352 if (FormatTok->is(tok::less))
4353 parseObjCProtocolList();
4356 if (FormatTok->is(tok::semi)) {
4363 parseObjCUntilAtEnd();
4367void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
4368 bool IsImport = FormatTok->is(Keywords.kw_import);
4369 assert(IsImport || FormatTok->is(tok::kw_export));
4373 if (FormatTok->is(tok::kw_default))
4379 if (FormatTok->is(Keywords.kw_async))
4381 if (FormatTok->is(Keywords.kw_function)) {
4390 if (!IsImport && FormatTok->isNoneOf(tok::l_brace, tok::star) &&
4391 !FormatTok->isStringLiteral() &&
4392 !(FormatTok->is(Keywords.kw_type) &&
4393 Tokens->peekNextToken()->isOneOf(tok::l_brace, tok::star))) {
4398 if (FormatTok->is(tok::semi))
4400 if (
Line->Tokens.empty()) {
4405 if (FormatTok->is(tok::l_brace)) {
4406 FormatTok->setBlockKind(BK_Block);
4415void UnwrappedLineParser::parseStatementMacro() {
4417 if (FormatTok->is(tok::l_paren))
4419 if (FormatTok->is(tok::semi))
4424void UnwrappedLineParser::parseVerilogHierarchyIdentifier() {
4427 if (FormatTok->isOneOf(tok::star, tok::period, tok::periodstar,
4428 tok::coloncolon, tok::hash) ||
4429 Keywords.isVerilogIdentifier(*FormatTok)) {
4431 }
else if (FormatTok->is(tok::l_square)) {
4439void UnwrappedLineParser::parseVerilogSensitivityList() {
4440 if (FormatTok->isNot(tok::at))
4444 if (FormatTok->is(tok::at))
4446 switch (FormatTok->Tok.getKind()) {
4454 parseVerilogHierarchyIdentifier();
4459unsigned UnwrappedLineParser::parseVerilogHierarchyHeader() {
4460 unsigned AddLevels = 0;
4462 if (FormatTok->is(Keywords.kw_clocking)) {
4464 if (Keywords.isVerilogIdentifier(*FormatTok))
4466 parseVerilogSensitivityList();
4467 if (FormatTok->is(tok::semi))
4469 }
else if (FormatTok->isOneOf(tok::kw_case, Keywords.kw_casex,
4470 Keywords.kw_casez, Keywords.kw_randcase,
4471 Keywords.kw_randsequence)) {
4472 if (Style.IndentCaseLabels)
4475 if (FormatTok->is(tok::l_paren)) {
4476 FormatTok->setFinalizedType(TT_ConditionLParen);
4479 if (FormatTok->isOneOf(Keywords.kw_inside, Keywords.kw_matches))
4488 if (FormatTok->is(tok::l_square)) {
4489 auto Prev = FormatTok->getPreviousNonComment();
4490 if (Prev && Keywords.isVerilogIdentifier(*Prev))
4491 Prev->setFinalizedType(TT_VerilogDimensionedTypeName);
4493 }
else if (Keywords.isVerilogIdentifier(*FormatTok) ||
4494 FormatTok->isOneOf(tok::hash, tok::hashhash, tok::coloncolon,
4495 Keywords.kw_automatic, tok::kw_static)) {
4502 auto NewLine = [
this]() {
4504 Line->IsContinuation =
true;
4508 while (FormatTok->is(Keywords.kw_import)) {
4511 parseVerilogHierarchyIdentifier();
4512 if (FormatTok->is(tok::semi))
4517 if (FormatTok->is(Keywords.kw_verilogHash)) {
4520 if (FormatTok->is(tok::l_paren)) {
4521 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4525 if (FormatTok->is(tok::l_paren)) {
4527 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4532 if (FormatTok->is(Keywords.kw_extends)) {
4535 parseVerilogHierarchyIdentifier();
4536 if (FormatTok->is(tok::l_paren))
4539 if (FormatTok->is(Keywords.kw_implements)) {
4543 parseVerilogHierarchyIdentifier();
4544 }
while (FormatTok->is(tok::comma));
4548 if (FormatTok->is(tok::at)) {
4550 parseVerilogSensitivityList();
4553 if (FormatTok->is(tok::semi))
4561void UnwrappedLineParser::parseVerilogTable() {
4562 assert(FormatTok->is(Keywords.kw_table));
4566 auto InitialLevel =
Line->Level++;
4567 while (!
eof() && !Keywords.isVerilogEnd(*FormatTok)) {
4570 if (
Tok->
is(tok::semi))
4572 else if (
Tok->
isOneOf(tok::star, tok::colon, tok::question, tok::minus))
4573 Tok->setFinalizedType(TT_VerilogTableItem);
4575 Line->Level = InitialLevel;
4580void UnwrappedLineParser::parseVerilogCaseLabel() {
4586 auto OrigLevel =
Line->Level;
4587 auto FirstLine = CurrentLines->size();
4588 if (
Line->Level == 0 || (
Line->InPPDirective &&
Line->Level <= 1))
4590 else if (!Style.IndentCaseBlocks && Keywords.isVerilogBegin(*FormatTok))
4592 parseStructuralElement();
4595 if (CurrentLines->size() > FirstLine)
4596 (*CurrentLines)[FirstLine].Level = OrigLevel;
4597 Line->Level = OrigLevel;
4600void UnwrappedLineParser::parseVerilogExtern() {
4602 FormatTok->isOneOf(tok::kw_extern, tok::kw_export, Keywords.kw_import));
4605 if (FormatTok->is(tok::string_literal))
4607 skipVerilogQualifiers();
4608 if (Keywords.isVerilogIdentifier(*FormatTok))
4610 if (FormatTok->is(tok::equal))
4612 if (Keywords.isVerilogHierarchy(*FormatTok))
4613 parseVerilogHierarchyHeader();
4616void UnwrappedLineParser::skipVerilogQualifiers() {
4617 while (FormatTok->isOneOf(tok::kw_protected, tok::kw_virtual, tok::kw_static,
4618 Keywords.kw_rand, Keywords.kw_context,
4619 Keywords.kw_pure, Keywords.kw_randc,
4620 Keywords.kw_local)) {
4625bool UnwrappedLineParser::containsExpansion(
const UnwrappedLine &
Line)
const {
4626 for (
const auto &N :
Line.Tokens) {
4627 if (N.Tok->MacroCtx)
4629 for (
const UnwrappedLine &Child : N.Children)
4630 if (containsExpansion(Child))
4636void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) {
4637 if (
Line->Tokens.empty())
4640 if (!parsingPPDirective()) {
4641 llvm::dbgs() <<
"Adding unwrapped line:\n";
4642 printDebugInfo(*
Line);
4650 bool ClosesWhitesmithsBlock =
4651 Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex &&
4652 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
4657 if (!parsingPPDirective() && !InExpansion && containsExpansion(*
Line)) {
4659 Reconstruct.emplace(
Line->Level, Unexpanded);
4660 Reconstruct->addLine(*
Line);
4665 CurrentExpandedLines.push_back(std::move(*
Line));
4667 if (Reconstruct->finished()) {
4668 UnwrappedLine Reconstructed = std::move(*Reconstruct).takeResult();
4669 assert(!Reconstructed.Tokens.empty() &&
4670 "Reconstructed must at least contain the macro identifier.");
4671 assert(!parsingPPDirective());
4673 llvm::dbgs() <<
"Adding unexpanded line:\n";
4674 printDebugInfo(Reconstructed);
4676 ExpandedLines[Reconstructed.Tokens.begin()->Tok] = CurrentExpandedLines;
4677 Lines.push_back(std::move(Reconstructed));
4678 CurrentExpandedLines.clear();
4679 Reconstruct.reset();
4684 assert(!Reconstruct || (CurrentLines != &Lines) || !PPStack.empty());
4685 CurrentLines->push_back(std::move(*
Line));
4687 Line->Tokens.clear();
4688 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
4689 Line->FirstStartColumn = 0;
4690 Line->IsContinuation =
false;
4691 Line->SeenDecltypeAuto =
false;
4693 if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove)
4695 if (!parsingPPDirective() && !PreprocessorDirectives.empty()) {
4696 CurrentLines->append(
4697 std::make_move_iterator(PreprocessorDirectives.begin()),
4698 std::make_move_iterator(PreprocessorDirectives.end()));
4699 PreprocessorDirectives.clear();
4702 FormatTok->Previous =
nullptr;
4705bool UnwrappedLineParser::eof()
const {
return FormatTok->is(tok::eof); }
4707bool UnwrappedLineParser::isOnNewLine(
const FormatToken &FormatTok) {
4708 return (
Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
4709 FormatTok.NewlinesBefore > 0;
4717 const llvm::Regex &CommentPragmasRegex) {
4718 if (
Line.Tokens.empty() || Style.ReflowComments != FormatStyle::RCS_Always)
4721 StringRef IndentContent = FormatTok.
TokenText;
4722 if (FormatTok.
TokenText.starts_with(
"//") ||
4723 FormatTok.
TokenText.starts_with(
"/*")) {
4724 IndentContent = FormatTok.
TokenText.substr(2);
4726 if (CommentPragmasRegex.match(IndentContent))
4801 if (PreviousToken && PreviousToken->
is(tok::l_brace) &&
4803 MinColumnToken = PreviousToken;
4806 PreviousToken = Node.
Tok;
4810 MinColumnToken = Node.
Tok;
4812 if (PreviousToken && PreviousToken->
is(tok::l_brace))
4813 MinColumnToken = PreviousToken;
4819void UnwrappedLineParser::flushComments(
bool NewlineBeforeNext) {
4820 bool JustComments =
Line->Tokens.empty();
4830 Tok->ContinuesLineCommentSection =
4831 continuesLineCommentSection(*
Tok, *
Line, Style, CommentPragmasRegex);
4832 if (isOnNewLine(*
Tok) && JustComments && !
Tok->ContinuesLineCommentSection)
4836 if (NewlineBeforeNext && JustComments)
4838 CommentsBeforeNextToken.clear();
4841void UnwrappedLineParser::nextToken(
int LevelDifference) {
4844 flushComments(isOnNewLine(*FormatTok));
4845 pushToken(FormatTok);
4847 if (!Style.isJavaScript())
4848 readToken(LevelDifference);
4850 readTokenWithJavaScriptASI();
4852 if (Style.isVerilog()) {
4859 if (Keywords.isVerilogEnd(*FormatTok))
4860 FormatTok->Tok.setKind(tok::r_brace);
4864void UnwrappedLineParser::distributeComments(
4884 if (Comments.empty())
4886 bool ShouldPushCommentsInCurrentLine =
true;
4887 bool HasTrailAlignedWithNextToken =
false;
4888 unsigned StartOfTrailAlignedWithNextToken = 0;
4891 for (
unsigned i = Comments.size() - 1; i > 0; --i) {
4893 HasTrailAlignedWithNextToken =
true;
4894 StartOfTrailAlignedWithNextToken = i;
4898 for (
unsigned i = 0, e = Comments.size(); i < e; ++i) {
4900 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
4901 FormatTok->ContinuesLineCommentSection =
false;
4904 *FormatTok, *
Line, Style, CommentPragmasRegex);
4906 if (!FormatTok->ContinuesLineCommentSection &&
4907 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
4908 ShouldPushCommentsInCurrentLine =
false;
4910 if (ShouldPushCommentsInCurrentLine)
4911 pushToken(FormatTok);
4913 CommentsBeforeNextToken.push_back(FormatTok);
4917void UnwrappedLineParser::readToken(
int LevelDifference) {
4919 bool PreviousWasComment =
false;
4920 bool FirstNonCommentOnLine =
false;
4922 FormatTok = Tokens->getNextToken();
4924 while (FormatTok->isOneOf(TT_ConflictStart, TT_ConflictEnd,
4925 TT_ConflictAlternative)) {
4926 if (FormatTok->is(TT_ConflictStart))
4927 conditionalCompilationStart(
false);
4928 else if (FormatTok->is(TT_ConflictAlternative))
4929 conditionalCompilationAlternative();
4930 else if (FormatTok->is(TT_ConflictEnd))
4931 conditionalCompilationEnd();
4932 FormatTok = Tokens->getNextToken();
4933 FormatTok->MustBreakBefore =
true;
4934 FormatTok->MustBreakBeforeFinalized =
true;
4937 auto IsFirstNonCommentOnLine = [](
bool FirstNonCommentOnLine,
4939 bool PreviousWasComment) {
4941 return Tok.HasUnescapedNewline ||
Tok.IsFirst;
4946 if (PreviousWasComment)
4947 return FirstNonCommentOnLine || IsFirstOnLine(
Tok);
4948 return IsFirstOnLine(
Tok);
4951 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
4952 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
4953 PreviousWasComment = FormatTok->is(tok::comment);
4955 while (!
Line->InPPDirective && FormatTok->is(tok::hash) &&
4956 FirstNonCommentOnLine) {
4959 const auto *
Next = Tokens->peekNextToken();
4960 if ((Style.isVerilog() && !Keywords.isVerilogPPDirective(*
Next)) ||
4961 (Style.isTableGen() &&
4962 Next->isNoneOf(tok::kw_else, tok::pp_define, tok::pp_ifdef,
4963 tok::pp_ifndef, tok::pp_endif))) {
4966 distributeComments(Comments, FormatTok);
4970 bool SwitchToPreprocessorLines = !
Line->Tokens.empty();
4971 ScopedLineState BlockState(*
this, SwitchToPreprocessorLines);
4972 assert((LevelDifference >= 0 ||
4973 static_cast<unsigned>(-LevelDifference) <=
Line->Level) &&
4974 "LevelDifference makes Line->Level negative");
4975 Line->Level += LevelDifference;
4979 if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash &&
4980 PPBranchLevel > 0) {
4981 Line->Level += PPBranchLevel;
4983 assert(
Line->Level >=
Line->UnbracedBodyLevel);
4984 Line->Level -=
Line->UnbracedBodyLevel;
4985 flushComments(isOnNewLine(*FormatTok));
4986 const bool IsEndIf = Tokens->peekNextToken()->is(tok::pp_endif);
4988 PreviousWasComment = FormatTok->is(tok::comment);
4989 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
4990 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
4993 if (IsEndIf && IncludeGuard == IG_Defined && PPBranchLevel == -1 &&
4994 getIncludeGuardState(Style.IndentPPDirectives) == IG_Inited &&
4996 (PreviousWasComment &&
4997 Tokens->peekNextToken(
true)->is(tok::eof)))) {
4998 IncludeGuard = IG_Found;
5002 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
5003 !
Line->InPPDirective) {
5007 if (FormatTok->is(tok::identifier) &&
5008 Macros.defined(FormatTok->TokenText) &&
5010 !
Line->InPPDirective) {
5012 unsigned Position = Tokens->getPosition();
5016 auto PreCall = std::move(
Line);
5017 Line.reset(
new UnwrappedLine);
5018 bool OldInExpansion = InExpansion;
5021 auto Args = parseMacroCall();
5022 InExpansion = OldInExpansion;
5023 assert(
Line->Tokens.front().Tok == ID);
5025 auto UnexpandedLine = std::move(
Line);
5027 Line = std::move(PreCall);
5030 llvm::dbgs() <<
"Macro call: " <<
ID->TokenText <<
"(";
5032 llvm::dbgs() <<
"(";
5033 for (
const auto &Arg : Args.value())
5034 for (
const auto &T : Arg)
5035 llvm::dbgs() << T->TokenText <<
" ";
5036 llvm::dbgs() <<
")";
5038 llvm::dbgs() <<
"\n";
5040 if (
Macros.objectLike(
ID->TokenText) && Args &&
5041 !
Macros.hasArity(
ID->TokenText, Args->size())) {
5047 LLVM_DEBUG(llvm::dbgs()
5048 <<
"Macro \"" <<
ID->TokenText
5049 <<
"\" not overloaded for arity " << Args->size()
5050 <<
"or not function-like, using object-like overload.");
5052 UnexpandedLine->Tokens.resize(1);
5053 Tokens->setPosition(Position);
5055 assert(!Args &&
Macros.objectLike(
ID->TokenText));
5057 if ((!Args &&
Macros.objectLike(
ID->TokenText)) ||
5058 (Args &&
Macros.hasArity(
ID->TokenText, Args->size()))) {
5061 Unexpanded[
ID] = std::move(UnexpandedLine);
5063 Macros.expand(ID, std::move(Args));
5064 if (!Expansion.empty())
5065 FormatTok = Tokens->insertTokens(Expansion);
5068 llvm::dbgs() <<
"Expanded: ";
5069 for (
const auto &T : Expansion)
5070 llvm::dbgs() << T->TokenText <<
" ";
5071 llvm::dbgs() <<
"\n";
5075 llvm::dbgs() <<
"Did not expand macro \"" <<
ID->TokenText
5076 <<
"\", because it was used ";
5078 llvm::dbgs() <<
"with " << Args->size();
5080 llvm::dbgs() <<
"without";
5081 llvm::dbgs() <<
" arguments, which doesn't match any definition.\n";
5083 Tokens->setPosition(Position);
5088 if (FormatTok->isNot(tok::comment)) {
5089 distributeComments(Comments, FormatTok);
5094 Comments.push_back(FormatTok);
5097 distributeComments(Comments,
nullptr);
5102template <
typename Iterator>
5103void pushTokens(Iterator Begin, Iterator End,
5105 for (
auto I = Begin; I != End; ++I) {
5106 Into.push_back(I->Tok);
5107 for (
const auto &Child : I->Children)
5108 pushTokens(Child.Tokens.begin(), Child.Tokens.end(), Into);
5113std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>
5114UnwrappedLineParser::parseMacroCall() {
5115 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>> Args;
5116 assert(
Line->Tokens.empty());
5118 if (FormatTok->isNot(tok::l_paren))
5120 unsigned Position = Tokens->getPosition();
5124 auto ArgStart = std::prev(
Line->Tokens.end());
5128 switch (FormatTok->Tok.getKind()) {
5133 case tok::r_paren: {
5139 Args->push_back({});
5140 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5149 Args->push_back({});
5150 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5152 ArgStart = std::prev(
Line->Tokens.end());
5160 Line->Tokens.resize(1);
5161 Tokens->setPosition(Position);
5167 Line->Tokens.push_back(UnwrappedLineNode(
Tok));
5168 if (AtEndOfPPLine) {
5169 auto &
Tok = *
Line->Tokens.back().Tok;
5170 Tok.MustBreakBefore =
true;
5171 Tok.MustBreakBeforeFinalized =
true;
5172 Tok.FirstAfterPPLine =
true;
5173 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.