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()) {
1454 if (Keywords.isVerilogStructuredProcedure(*FormatTok)) {
1455 parseForOrWhileLoop(
false);
1458 if (FormatTok->isOneOf(Keywords.kw_foreach, Keywords.kw_repeat)) {
1459 parseForOrWhileLoop();
1462 if (FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
1463 Keywords.kw_assume, Keywords.kw_cover)) {
1464 parseIfThenElse(IfKind,
false,
true);
1470 if (FormatTok->isOneOf(Keywords.kw_priority, Keywords.kw_unique,
1471 Keywords.kw_unique0)) {
1473 }
else if (FormatTok->is(tok::l_paren) &&
1474 Tokens->peekNextToken()->is(tok::star)) {
1483 if (FormatTok->isAccessSpecifierKeyword()) {
1484 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp())
1487 parseAccessSpecifier();
1490 switch (FormatTok->Tok.getKind()) {
1493 if (FormatTok->is(tok::l_brace)) {
1494 FormatTok->setFinalizedType(TT_InlineASMBrace);
1496 while (FormatTok && !
eof()) {
1497 if (FormatTok->is(tok::r_brace)) {
1498 FormatTok->setFinalizedType(TT_InlineASMBrace);
1503 FormatTok->Finalized =
true;
1508 case tok::kw_namespace:
1512 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1523 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1527 parseForOrWhileLoop();
1530 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1538 case tok::kw_switch:
1539 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1545 case tok::kw_default: {
1547 if (Style.isVerilog())
1549 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1555 if (FormatTok->is(tok::colon)) {
1556 FormatTok->setFinalizedType(TT_CaseLabelColon);
1560 if (FormatTok->is(tok::arrow)) {
1561 FormatTok->setFinalizedType(TT_CaseLabelArrow);
1562 Default->setFinalizedType(TT_SwitchExpressionLabel);
1571 if (Style.Language == FormatStyle::LK_Proto) {
1575 if (Style.isVerilog()) {
1580 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1589 if (FormatTok->is(tok::kw_case))
1594 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1600 case tok::kw_extern:
1601 if (Style.isVerilog()) {
1604 parseVerilogExtern();
1608 if (FormatTok->is(tok::string_literal)) {
1610 if (FormatTok->is(tok::l_brace)) {
1611 if (Style.BraceWrapping.AfterExternBlock)
1615 unsigned AddLevels =
1616 (Style.IndentExternBlock == FormatStyle::IEBS_Indent) ||
1617 (Style.BraceWrapping.AfterExternBlock &&
1618 Style.IndentExternBlock ==
1619 FormatStyle::IEBS_AfterExternBlock)
1622 parseBlock(
true, AddLevels);
1628 case tok::kw_export:
1629 if (Style.isJavaScript()) {
1630 parseJavaScriptEs6ImportExport();
1633 if (Style.isVerilog()) {
1634 parseVerilogExtern();
1639 if (FormatTok->is(tok::kw_namespace)) {
1643 if (FormatTok->is(tok::l_brace)) {
1644 parseCppExportBlock();
1647 if (FormatTok->is(Keywords.kw_import) && parseModuleImport())
1651 case tok::kw_inline:
1653 if (FormatTok->is(tok::kw_namespace)) {
1658 case tok::identifier:
1659 if (FormatTok->is(TT_ForEachMacro)) {
1660 parseForOrWhileLoop();
1663 if (FormatTok->is(TT_MacroBlockBegin)) {
1664 parseBlock(
false, 1u,
1668 if (FormatTok->is(Keywords.kw_import)) {
1669 if (Style.isJavaScript()) {
1670 parseJavaScriptEs6ImportExport();
1673 if (Style.Language == FormatStyle::LK_Proto) {
1675 if (FormatTok->is(tok::kw_public))
1677 if (FormatTok->isNot(tok::string_literal))
1680 if (FormatTok->is(tok::semi))
1685 if (Style.isVerilog()) {
1686 parseVerilogExtern();
1689 if (IsCpp && parseModuleImport())
1692 if (IsCpp && FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
1693 Keywords.kw_slots, Keywords.kw_qslots)) {
1695 if (FormatTok->is(tok::colon)) {
1701 if (IsCpp && FormatTok->is(TT_StatementMacro)) {
1702 parseStatementMacro();
1705 if (IsCpp && FormatTok->is(TT_NamespaceMacro)) {
1713 if (!Style.isJavaScript() && !Style.isVerilog() && !Style.isTableGen() &&
1714 Tokens->peekNextToken()->is(tok::colon) && !
Line->MustBeDeclaration) {
1716 if (!
Line->InMacroBody || CurrentLines->size() > 1)
1717 Line->Tokens.begin()->Tok->MustBreakBefore =
true;
1718 FormatTok->setFinalizedType(TT_GotoLabelColon);
1719 parseLabel(Style.IndentGotoLabels);
1724 if (Style.isJava() && FormatTok->is(Keywords.kw_record)) {
1725 parseRecord(
false,
true);
1735 bool SeenEqual =
false;
1736 for (
const bool InRequiresExpression =
1737 OpeningBrace && OpeningBrace->isOneOf(TT_RequiresExpressionLBrace,
1738 TT_CompoundRequirementLBrace);
1741 switch (FormatTok->Tok.getKind()) {
1744 if (FormatTok->is(tok::l_brace)) {
1749 if (Style.isJava() && FormatTok->is(Keywords.kw_interface)) {
1753 switch (
bool IsAutoRelease =
false; FormatTok->Tok.getObjCKeywordID()) {
1754 case tok::objc_public:
1755 case tok::objc_protected:
1756 case tok::objc_package:
1757 case tok::objc_private:
1758 return parseAccessSpecifier();
1759 case tok::objc_interface:
1760 case tok::objc_implementation:
1761 return parseObjCInterfaceOrImplementation();
1762 case tok::objc_protocol:
1763 if (parseObjCProtocol())
1768 case tok::objc_optional:
1769 case tok::objc_required:
1773 case tok::objc_autoreleasepool:
1774 IsAutoRelease =
true;
1776 case tok::objc_synchronized:
1778 if (!IsAutoRelease && FormatTok->is(tok::l_paren)) {
1782 if (FormatTok->is(tok::l_brace)) {
1783 if (Style.BraceWrapping.AfterControlStatement ==
1784 FormatStyle::BWACS_Always) {
1800 case tok::kw_requires: {
1802 bool ParsedClause = parseRequires(SeenEqual);
1823 if (!IsCpp && !Style.isVerilog()) {
1828 case tok::kw_typedef:
1830 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1831 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS,
1832 Keywords.kw_CF_CLOSED_ENUM,
1833 Keywords.kw_NS_CLOSED_ENUM)) {
1838 if (Style.isVerilog()) {
1843 if (Style.isTableGen()) {
1850 case tok::kw_struct:
1852 if (parseStructLike())
1855 case tok::kw_decltype:
1857 if (FormatTok->is(tok::l_paren)) {
1859 if (FormatTok->Previous &&
1860 FormatTok->Previous->endsSequence(tok::r_paren, tok::kw_auto,
1862 Line->SeenDecltypeAuto =
true;
1869 if (Style.isJava() && FormatTok && FormatTok->is(tok::kw_class))
1871 if (Style.isJavaScript() && FormatTok &&
1872 FormatTok->Tok.getIdentifierInfo()) {
1885 case tok::string_literal:
1886 if (Style.isVerilog() && FormatTok->is(TT_VerilogProtected)) {
1887 FormatTok->Finalized =
true;
1894 case tok::l_paren: {
1901 Tokens->peekNextToken(
true),
1908 case tok::kw_operator:
1910 if (FormatTok->isBinaryOperator())
1914 const auto *Prev = FormatTok->getPreviousNonComment();
1916 if (Prev && Prev->is(tok::identifier))
1919 if (FormatTok->Tok.isAnyIdentifier() || FormatTok->isTypeName(LangOpts)) {
1922 while (FormatTok->is(tok::star))
1926 if (FormatTok->is(tok::l_paren))
1929 if (FormatTok->is(tok::l_brace))
1934 if (InRequiresExpression)
1935 FormatTok->setFinalizedType(TT_BracedListLBrace);
1936 if (!tryToParsePropertyAccessor() && !tryToParseBracedList()) {
1937 IsDecltypeAutoFunction =
Line->SeenDecltypeAuto;
1942 if (Style.isJava() &&
1943 Line->Tokens.front().Tok->is(Keywords.kw_synchronized)) {
1946 if (Style.BraceWrapping.AfterControlStatement ==
1947 FormatStyle::BWACS_Always) {
1950 }
else if (Style.BraceWrapping.AfterFunction) {
1954 FormatTok->setFinalizedType(TT_FunctionLBrace);
1956 IsDecltypeAutoFunction =
false;
1964 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1970 if (Style.BraceWrapping.AfterFunction)
1974 case tok::identifier: {
1975 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where) &&
1976 Line->MustBeDeclaration) {
1978 parseCSharpGenericTypeConstraint();
1981 if (FormatTok->is(TT_MacroBlockEnd)) {
1990 size_t TokenCount =
Line->Tokens.size();
1991 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_function) &&
1994 Line->Tokens.front().Tok->isNot(Keywords.kw_async)))) {
1995 tryToParseJSFunction();
1998 if ((Style.isJavaScript() || Style.isJava()) &&
1999 FormatTok->is(Keywords.kw_interface)) {
2000 if (Style.isJavaScript()) {
2005 unsigned StoredPosition = Tokens->getPosition();
2007 FormatTok = Tokens->setPosition(StoredPosition);
2018 if (Style.isVerilog()) {
2019 if (FormatTok->is(Keywords.kw_table)) {
2020 parseVerilogTable();
2023 if (Keywords.isVerilogBegin(*FormatTok) ||
2024 Keywords.isVerilogHierarchy(*FormatTok)) {
2031 if (!IsCpp && FormatTok->is(Keywords.kw_interface)) {
2032 if (parseStructLike())
2037 if (IsCpp && FormatTok->is(TT_StatementMacro)) {
2038 parseStatementMacro();
2043 StringRef
Text = FormatTok->TokenText;
2050 if (Style.isJavaScript())
2053 auto OneTokenSoFar = [&]() {
2054 auto I =
Line->Tokens.begin(), E =
Line->Tokens.end();
2055 while (I != E && I->Tok->is(tok::comment))
2057 if (Style.isVerilog())
2058 while (I != E && I->Tok->is(tok::hash))
2060 return I != E && (++I == E);
2062 if (OneTokenSoFar()) {
2065 bool FunctionLike = FormatTok->is(tok::l_paren);
2069 bool FollowedByNewline =
2070 CommentsBeforeNextToken.empty()
2071 ? FormatTok->NewlinesBefore > 0
2072 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
2074 if (FollowedByNewline &&
2075 (
Text.size() >= 5 ||
2076 (FunctionLike && FormatTok->isNot(tok::l_paren))) &&
2078 if (PreviousToken->isNot(TT_UntouchableMacroFunc))
2079 PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro);
2087 if ((Style.isJavaScript() || Style.isCSharp()) &&
2088 FormatTok->is(TT_FatArrow)) {
2089 tryToParseChildBlock();
2095 if (FormatTok->is(tok::l_brace)) {
2099 if (!Style.isJavaScript())
2100 FormatTok->setBlockKind(BK_BracedInit);
2103 if (Style.isTableGen() &&
2104 Line->Tokens.begin()->Tok->is(Keywords.kw_defset)) {
2105 FormatTok->setFinalizedType(TT_FunctionLBrace);
2106 parseBlock(
false, 1u,
2113 }
else if (Style.Language == FormatStyle::LK_Proto &&
2114 FormatTok->is(tok::less)) {
2116 parseBracedList(
true);
2123 if (Style.isCSharp() &&
2124 (Tokens->peekNextToken()->isAccessSpecifierKeyword() ||
2131 case tok::kw_switch:
2139 if (Style.Language == FormatStyle::LK_Proto) {
2144 if (Style.isVerilog()) {
2149 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
2156 case tok::kw_default:
2158 if (Style.isVerilog()) {
2159 if (FormatTok->is(tok::colon)) {
2163 if (FormatTok->is(Keywords.kw_clocking)) {
2169 parseVerilogCaseLabel();
2175 if (Style.isVerilog()) {
2176 parseVerilogCaseLabel();
2182 if (FormatTok->is(tok::l_brace))
2183 FormatTok->Previous->setFinalizedType(TT_TemplateCloser);
2192bool UnwrappedLineParser::tryToParsePropertyAccessor() {
2193 assert(FormatTok->is(tok::l_brace));
2194 if (!Style.isCSharp())
2197 if (!FormatTok->Previous || FormatTok->Previous->isNot(tok::identifier))
2205 unsigned int StoredPosition = Tokens->getPosition();
2211 bool HasSpecialAccessor =
false;
2212 bool IsTrivialPropertyAccessor =
true;
2215 if (
const bool IsAccessorKeyword =
2216 Tok->
isOneOf(Keywords.kw_get, Keywords.kw_init, Keywords.kw_set);
2217 IsAccessorKeyword ||
Tok->isAccessSpecifierKeyword() ||
2218 Tok->
isOneOf(tok::l_square, tok::semi, Keywords.kw_internal)) {
2219 if (IsAccessorKeyword)
2220 HasSpecialAccessor =
true;
2221 else if (
Tok->
is(tok::l_square))
2223 Tok = Tokens->getNextToken();
2227 IsTrivialPropertyAccessor =
false;
2232 Tokens->setPosition(StoredPosition);
2238 Tokens->setPosition(StoredPosition);
2239 if (!IsTrivialPropertyAccessor && Style.BraceWrapping.AfterFunction)
2243 switch (FormatTok->Tok.getKind()) {
2246 if (FormatTok->is(tok::equal)) {
2247 while (!
eof() && FormatTok->isNot(tok::semi))
2260 if (FormatTok->is(TT_FatArrow)) {
2264 }
while (!
eof() && FormatTok->isNot(tok::semi));
2273 if (FormatTok->isOneOf(Keywords.kw_get, Keywords.kw_init,
2275 !IsTrivialPropertyAccessor) {
2287bool UnwrappedLineParser::tryToParseLambda() {
2288 assert(FormatTok->is(tok::l_square));
2294 if (!tryToParseLambdaIntroducer())
2298 bool InTemplateParameterList =
false;
2300 while (FormatTok->isNot(tok::l_brace)) {
2301 if (FormatTok->isTypeName(LangOpts) || FormatTok->isAttribute()) {
2305 switch (FormatTok->Tok.getKind()) {
2309 parseParens(TT_PointerOrReference);
2315 assert(FormatTok->Previous);
2316 if (FormatTok->Previous->is(tok::r_square))
2317 InTemplateParameterList =
true;
2322 case tok::kw_struct:
2324 case tok::kw_template:
2325 case tok::kw_typename:
2329 case tok::kw_constexpr:
2330 case tok::kw_consteval:
2333 case tok::identifier:
2334 case tok::numeric_constant:
2335 case tok::coloncolon:
2336 case tok::kw_mutable:
2337 case tok::kw_noexcept:
2338 case tok::kw_static:
2363 case tok::equalequal:
2364 case tok::exclaimequal:
2365 case tok::greaterequal:
2366 case tok::lessequal:
2372 if (Arrow || InTemplateParameterList) {
2381 case tok::kw_requires:
2382 parseRequiresClause();
2385 if (!InTemplateParameterList)
2394 FormatTok->setFinalizedType(TT_LambdaLBrace);
2395 LSquare.setFinalizedType(TT_LambdaLSquare);
2398 Arrow->setFinalizedType(TT_LambdaArrow);
2400 NestedLambdas.push_back(
Line->SeenDecltypeAuto);
2402 assert(!NestedLambdas.empty());
2403 NestedLambdas.pop_back();
2408bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
2413 const auto *PrevPrev =
Previous->getPreviousNonComment();
2414 if (
Previous->is(tok::star) && PrevPrev && PrevPrev->isTypeName(LangOpts))
2422 if (!PrevPrev || PrevPrev->isNoneOf(tok::greater, tok::r_paren))
2426 Previous->isNoneOf(tok::kw_return, tok::kw_co_await, tok::kw_co_yield,
2427 tok::kw_co_return)) {
2431 if (LeftSquare->isCppStructuredBinding(IsCpp))
2433 if (FormatTok->is(tok::l_square) ||
tok::isLiteral(FormatTok->Tok.getKind()))
2435 if (FormatTok->is(tok::r_square)) {
2437 if (
Next->is(tok::greater))
2444void UnwrappedLineParser::tryToParseJSFunction() {
2445 assert(FormatTok->is(Keywords.kw_function));
2446 if (FormatTok->is(Keywords.kw_async))
2452 if (FormatTok->is(tok::star)) {
2453 FormatTok->setFinalizedType(TT_OverloadedOperator);
2458 if (FormatTok->is(tok::identifier))
2461 if (FormatTok->isNot(tok::l_paren))
2467 if (FormatTok->is(tok::colon)) {
2473 if (FormatTok->is(tok::l_brace))
2474 tryToParseBracedList();
2476 while (FormatTok->isNoneOf(tok::l_brace, tok::semi) && !
eof())
2480 if (FormatTok->is(tok::semi))
2486bool UnwrappedLineParser::tryToParseBracedList() {
2487 if (FormatTok->is(BK_Unknown))
2488 calculateBraceTypes();
2489 assert(FormatTok->isNot(BK_Unknown));
2490 if (FormatTok->is(BK_Block))
2497bool UnwrappedLineParser::tryToParseChildBlock() {
2498 assert(Style.isJavaScript() || Style.isCSharp());
2499 assert(FormatTok->is(TT_FatArrow));
2504 if (FormatTok->isNot(tok::l_brace))
2510bool UnwrappedLineParser::parseBracedList(
bool IsAngleBracket,
bool IsEnum) {
2511 assert(!IsAngleBracket || !IsEnum);
2512 bool HasError =
false;
2517 if (Style.isCSharp() && FormatTok->is(TT_FatArrow) &&
2518 tryToParseChildBlock()) {
2521 if (Style.isJavaScript()) {
2522 if (FormatTok->is(Keywords.kw_function)) {
2523 tryToParseJSFunction();
2526 if (FormatTok->is(tok::l_brace)) {
2528 if (tryToParseBracedList())
2533 if (FormatTok->is(IsAngleBracket ? tok::greater : tok::r_brace)) {
2535 FormatTok->setBlockKind(BK_Block);
2536 if (!Style.AllowShortEnumsOnASingleLine)
2542 switch (FormatTok->Tok.getKind()) {
2544 if (Style.isCSharp())
2553 if (Style.isJavaScript()) {
2554 if (FormatTok->is(tok::l_brace))
2562 FormatTok->setBlockKind(BK_BracedInit);
2563 if (!IsAngleBracket) {
2564 auto *Prev = FormatTok->Previous;
2565 if (Prev && Prev->is(tok::greater))
2566 Prev->setFinalizedType(TT_TemplateCloser);
2574 parseBracedList(
true);
2581 if (Style.isJavaScript()) {
2592 if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
2595 case tok::kw_requires:
2596 parseRequiresExpression();
2612bool UnwrappedLineParser::parseParens(TokenType StarAndAmpTokenType,
2614 assert(FormatTok->is(tok::l_paren) &&
"'(' expected.");
2615 auto *LParen = FormatTok;
2616 auto *Prev = FormatTok->Previous;
2617 bool SeenComma =
false;
2618 bool SeenEqual =
false;
2619 bool MightBeFoldExpr =
false;
2621 const bool MightBeStmtExpr = FormatTok->is(tok::l_brace);
2622 if (!InMacroCall && Prev && Prev->is(TT_FunctionLikeMacro))
2625 switch (FormatTok->Tok.getKind()) {
2627 if (parseParens(StarAndAmpTokenType, InMacroCall))
2629 if (Style.isJava() && FormatTok->is(tok::l_brace))
2632 case tok::r_paren: {
2633 auto *RParen = FormatTok;
2636 auto OptionalParens = [&] {
2637 if (Style.RemoveParentheses == FormatStyle::RPS_Leave ||
2638 MightBeStmtExpr || MightBeFoldExpr || SeenComma || InMacroCall ||
2639 Line->InMacroBody || RParen->getPreviousNonComment() == LParen) {
2642 const bool DoubleParens =
2643 Prev->is(tok::l_paren) && FormatTok->is(tok::r_paren);
2645 const auto *PrevPrev = Prev->getPreviousNonComment();
2646 const bool Excluded =
2648 (PrevPrev->isOneOf(tok::kw___attribute, tok::kw_decltype) ||
2650 (PrevPrev->isOneOf(tok::kw_if, tok::kw_while) ||
2651 PrevPrev->endsSequence(tok::kw_constexpr, tok::kw_if))));
2655 const bool CommaSeparated =
2656 Prev->isOneOf(tok::l_paren, tok::comma) &&
2657 FormatTok->isOneOf(tok::comma, tok::r_paren);
2658 if (CommaSeparated &&
2660 !Prev->endsSequence(tok::comma, tok::ellipsis) &&
2662 !(FormatTok->is(tok::comma) &&
2663 Tokens->peekNextToken()->is(tok::ellipsis))) {
2666 const bool ReturnParens =
2667 Style.RemoveParentheses == FormatStyle::RPS_ReturnStatement &&
2668 ((NestedLambdas.empty() && !IsDecltypeAutoFunction) ||
2669 (!NestedLambdas.empty() && !NestedLambdas.back())) &&
2670 Prev->isOneOf(tok::kw_return, tok::kw_co_return) &&
2671 FormatTok->is(tok::semi);
2677 if (OptionalParens()) {
2678 LParen->Optional =
true;
2679 RParen->Optional =
true;
2680 }
else if (Prev->is(TT_TypenameMacro)) {
2681 LParen->setFinalizedType(TT_TypeDeclarationParen);
2682 RParen->setFinalizedType(TT_TypeDeclarationParen);
2683 }
else if (Prev->is(tok::greater) && RParen->Previous == LParen) {
2684 Prev->setFinalizedType(TT_TemplateCloser);
2685 }
else if (FormatTok->is(tok::l_brace) && Prev->is(tok::amp) &&
2687 FormatTok->setBlockKind(BK_BracedInit);
2699 if (!tryToParseBracedList())
2704 if (FormatTok->is(tok::l_brace)) {
2714 MightBeFoldExpr =
true;
2719 if (Style.isCSharp() && FormatTok->is(TT_FatArrow))
2720 tryToParseChildBlock();
2725 if (Style.isJavaScript())
2730 case tok::identifier:
2731 if (Style.isJavaScript() && (FormatTok->is(Keywords.kw_function)))
2732 tryToParseJSFunction();
2736 case tok::kw_switch:
2742 case tok::kw_requires:
2743 parseRequiresExpression();
2748 if (StarAndAmpTokenType != TT_Unknown)
2749 FormatTok->setFinalizedType(StarAndAmpTokenType);
2761 assert(FormatTok->is(tok::l_square) &&
"'[' expected.");
2762 if (tryToParseLambda())
2766 switch (FormatTok->Tok.getKind()) {
2779 case tok::l_brace: {
2780 if (!tryToParseBracedList())
2787 if (FormatTok->is(tok::l_brace)) {
2799void UnwrappedLineParser::keepAncestorBraces() {
2800 if (!Style.RemoveBracesLLVM)
2803 const int MaxNestingLevels = 2;
2804 const int Size = NestedTooDeep.size();
2805 if (Size >= MaxNestingLevels)
2806 NestedTooDeep[
Size - MaxNestingLevels] =
true;
2807 NestedTooDeep.push_back(
false);
2811 for (
const auto &
Token : llvm::reverse(
Line.Tokens))
2818void UnwrappedLineParser::parseUnbracedBody(
bool CheckEOF) {
2821 if (Style.InsertBraces && !
Line->InPPDirective && !
Line->Tokens.empty() &&
2822 PreprocessorDirectives.empty() && FormatTok->isNot(tok::semi)) {
2823 Tok = Style.BraceWrapping.AfterControlStatement == FormatStyle::BWACS_Never
2824 ? getLastNonComment(*
Line)
2827 if (
Tok->BraceCount < 0) {
2828 assert(
Tok->BraceCount == -1);
2831 Tok->BraceCount = -1;
2837 ++
Line->UnbracedBodyLevel;
2838 parseStructuralElement();
2839 --
Line->UnbracedBodyLevel;
2842 assert(!
Line->InPPDirective);
2844 for (
const auto &L : llvm::reverse(*CurrentLines)) {
2846 Tok = L.Tokens.back().Tok;
2854 if (CheckEOF &&
eof())
2864 assert(LeftBrace->
is(tok::l_brace));
2872 assert(RightBrace->
is(tok::r_brace));
2880void UnwrappedLineParser::handleAttributes() {
2882 if (FormatTok->isAttribute())
2884 else if (FormatTok->is(tok::l_square))
2885 handleCppAttributes();
2888bool UnwrappedLineParser::handleCppAttributes() {
2890 assert(FormatTok->is(tok::l_square));
2891 if (!tryToParseSimpleAttribute())
2898bool UnwrappedLineParser::isBlockBegin(
const FormatToken &
Tok)
const {
2901 return Style.isVerilog() ? Keywords.isVerilogBegin(
Tok)
2902 :
Tok.
is(tok::l_brace);
2905FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
2907 bool IsVerilogAssert) {
2908 assert((FormatTok->is(tok::kw_if) ||
2909 (Style.isVerilog() &&
2910 FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
2911 Keywords.kw_assume, Keywords.kw_cover))) &&
2915 if (IsVerilogAssert) {
2917 if (FormatTok->is(Keywords.kw_verilogHash)) {
2919 if (FormatTok->is(tok::numeric_constant))
2921 }
else if (FormatTok->isOneOf(Keywords.kw_final, Keywords.kw_property,
2922 Keywords.kw_sequence)) {
2928 if (Style.isTableGen()) {
2929 while (!
eof() && FormatTok->isNot(Keywords.kw_then)) {
2936 if (FormatTok->is(tok::exclaim))
2939 bool KeepIfBraces =
true;
2940 if (FormatTok->is(tok::kw_consteval)) {
2943 KeepIfBraces = !Style.RemoveBracesLLVM || KeepBraces;
2944 if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
2946 if (FormatTok->is(tok::l_paren)) {
2947 FormatTok->setFinalizedType(TT_ConditionLParen);
2953 if (IsVerilogAssert && FormatTok->is(tok::semi)) {
2959 bool NeedsUnwrappedLine =
false;
2960 keepAncestorBraces();
2963 IfStmtKind IfBlockKind = IfStmtKind::NotIf;
2965 if (isBlockBegin(*FormatTok)) {
2966 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
2967 IfLeftBrace = FormatTok;
2968 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
2969 parseBlock(
false, 1u,
2970 true, KeepIfBraces, &IfBlockKind);
2971 setPreviousRBraceType(TT_ControlStatementRBrace);
2972 if (Style.BraceWrapping.BeforeElse)
2975 NeedsUnwrappedLine =
true;
2976 }
else if (IsVerilogAssert && FormatTok->is(tok::kw_else)) {
2979 parseUnbracedBody();
2982 if (Style.RemoveBracesLLVM) {
2983 assert(!NestedTooDeep.empty());
2984 KeepIfBraces = KeepIfBraces ||
2985 (IfLeftBrace && !IfLeftBrace->MatchingParen) ||
2986 NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly ||
2987 IfBlockKind == IfStmtKind::IfElseIf;
2990 bool KeepElseBraces = KeepIfBraces;
2992 IfStmtKind
Kind = IfStmtKind::IfOnly;
2994 if (FormatTok->is(tok::kw_else)) {
2995 if (Style.RemoveBracesLLVM) {
2996 NestedTooDeep.back() =
false;
2997 Kind = IfStmtKind::IfElse;
3001 if (isBlockBegin(*FormatTok)) {
3002 const bool FollowedByIf = Tokens->peekNextToken()->is(tok::kw_if);
3003 FormatTok->setFinalizedType(TT_ElseLBrace);
3004 ElseLeftBrace = FormatTok;
3005 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3006 IfStmtKind ElseBlockKind = IfStmtKind::NotIf;
3008 parseBlock(
false, 1u,
3009 true, KeepElseBraces, &ElseBlockKind);
3010 setPreviousRBraceType(TT_ElseRBrace);
3011 if (FormatTok->is(tok::kw_else)) {
3012 KeepElseBraces = KeepElseBraces ||
3013 ElseBlockKind == IfStmtKind::IfOnly ||
3014 ElseBlockKind == IfStmtKind::IfElseIf;
3015 }
else if (FollowedByIf && IfLBrace && !IfLBrace->Optional) {
3016 KeepElseBraces =
true;
3017 assert(ElseLeftBrace->MatchingParen);
3021 }
else if (!IsVerilogAssert && FormatTok->is(tok::kw_if)) {
3024 const bool IsPrecededByComment =
Previous->is(tok::comment);
3025 if (IsPrecededByComment) {
3029 bool TooDeep =
true;
3030 if (Style.RemoveBracesLLVM) {
3031 Kind = IfStmtKind::IfElseIf;
3032 TooDeep = NestedTooDeep.pop_back_val();
3034 ElseLeftBrace = parseIfThenElse(
nullptr, KeepIfBraces);
3035 if (Style.RemoveBracesLLVM)
3036 NestedTooDeep.push_back(TooDeep);
3037 if (IsPrecededByComment)
3040 parseUnbracedBody(
true);
3043 KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse;
3044 if (NeedsUnwrappedLine)
3048 if (!Style.RemoveBracesLLVM)
3051 assert(!NestedTooDeep.empty());
3052 KeepElseBraces = KeepElseBraces ||
3053 (ElseLeftBrace && !ElseLeftBrace->MatchingParen) ||
3054 NestedTooDeep.back();
3056 NestedTooDeep.pop_back();
3058 if (!KeepIfBraces && !KeepElseBraces) {
3061 }
else if (IfLeftBrace) {
3062 FormatToken *IfRightBrace = IfLeftBrace->MatchingParen;
3064 assert(IfRightBrace->MatchingParen == IfLeftBrace);
3065 assert(!IfLeftBrace->Optional);
3066 assert(!IfRightBrace->Optional);
3067 IfLeftBrace->MatchingParen =
nullptr;
3068 IfRightBrace->MatchingParen =
nullptr;
3078void UnwrappedLineParser::parseTryCatch() {
3079 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) &&
"'try' expected");
3081 bool NeedsUnwrappedLine =
false;
3082 bool HasCtorInitializer =
false;
3083 if (FormatTok->is(tok::colon)) {
3084 auto *Colon = FormatTok;
3087 if (FormatTok->is(tok::identifier)) {
3088 HasCtorInitializer =
true;
3089 Colon->setFinalizedType(TT_CtorInitializerColon);
3094 while (FormatTok->is(tok::comma))
3097 while (FormatTok->is(tok::identifier)) {
3099 if (FormatTok->is(tok::l_paren)) {
3101 }
else if (FormatTok->is(tok::l_brace)) {
3108 while (FormatTok->is(tok::comma))
3113 if (Style.isJava() && FormatTok->is(tok::l_paren))
3116 keepAncestorBraces();
3118 if (FormatTok->is(tok::l_brace)) {
3119 if (HasCtorInitializer)
3120 FormatTok->setFinalizedType(TT_FunctionLBrace);
3121 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3123 if (Style.BraceWrapping.BeforeCatch)
3126 NeedsUnwrappedLine =
true;
3127 }
else if (FormatTok->isNot(tok::kw_catch)) {
3133 parseStructuralElement();
3136 for (
bool SeenCatch =
false;;) {
3137 if (FormatTok->is(tok::at))
3139 if (FormatTok->isNoneOf(tok::kw_catch, Keywords.kw___except,
3140 tok::kw___finally, tok::objc_catch,
3141 tok::objc_finally) &&
3142 !((Style.isJava() || Style.isJavaScript()) &&
3143 FormatTok->is(Keywords.kw_finally))) {
3146 if (FormatTok->is(tok::kw_catch))
3149 while (FormatTok->isNot(tok::l_brace)) {
3150 if (FormatTok->is(tok::l_paren)) {
3154 if (FormatTok->isOneOf(tok::semi, tok::r_brace) ||
eof()) {
3155 if (Style.RemoveBracesLLVM)
3156 NestedTooDeep.pop_back();
3162 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3165 NeedsUnwrappedLine =
false;
3166 Line->MustBeDeclaration =
false;
3167 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3169 if (Style.BraceWrapping.BeforeCatch)
3172 NeedsUnwrappedLine =
true;
3175 if (Style.RemoveBracesLLVM)
3176 NestedTooDeep.pop_back();
3178 if (NeedsUnwrappedLine)
3182void UnwrappedLineParser::parseNamespaceOrExportBlock(
unsigned AddLevels) {
3183 bool ManageWhitesmithsBraces =
3184 AddLevels == 0u && Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
3188 if (ManageWhitesmithsBraces)
3193 parseBlock(
true, AddLevels,
true,
3194 true,
nullptr, ManageWhitesmithsBraces);
3196 addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep);
3198 if (ManageWhitesmithsBraces)
3202void UnwrappedLineParser::parseNamespace() {
3203 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
3204 "'namespace' expected");
3208 if (InitialToken.is(TT_NamespaceMacro)) {
3211 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
3212 tok::l_square, tok::period, tok::l_paren) ||
3213 (Style.isCSharp() && FormatTok->is(tok::kw_union))) {
3214 if (FormatTok->is(tok::l_square))
3216 else if (FormatTok->is(tok::l_paren))
3222 if (FormatTok->is(tok::l_brace)) {
3223 FormatTok->setFinalizedType(TT_NamespaceLBrace);
3226 Tokens->peekNextToken()->is(tok::r_brace))) {
3230 unsigned AddLevels =
3231 Style.NamespaceIndentation == FormatStyle::NI_All ||
3232 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
3233 DeclarationScopeStack.size() > 1)
3236 parseNamespaceOrExportBlock(AddLevels);
3241void UnwrappedLineParser::parseCppExportBlock() {
3242 parseNamespaceOrExportBlock(Style.IndentExportBlock ? 1 : 0);
3245void UnwrappedLineParser::parseNew() {
3246 assert(FormatTok->is(tok::kw_new) &&
"'new' expected");
3249 if (Style.isCSharp()) {
3252 if (FormatTok->is(tok::l_paren))
3256 if (FormatTok->is(tok::l_brace))
3259 if (FormatTok->isOneOf(tok::semi, tok::comma))
3266 if (!Style.isJava())
3272 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
3276 if (FormatTok->is(tok::l_paren)) {
3280 if (FormatTok->is(tok::l_brace))
3288void UnwrappedLineParser::parseLoopBody(
bool KeepBraces,
bool WrapRightBrace) {
3289 keepAncestorBraces();
3291 if (isBlockBegin(*FormatTok)) {
3292 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3294 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3295 parseBlock(
false, 1u,
3297 setPreviousRBraceType(TT_ControlStatementRBrace);
3299 assert(!NestedTooDeep.empty());
3300 if (!NestedTooDeep.back())
3306 parseUnbracedBody();
3310 NestedTooDeep.pop_back();
3313void UnwrappedLineParser::parseForOrWhileLoop(
bool HasParens) {
3314 assert((FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) ||
3315 (Style.isVerilog() &&
3316 FormatTok->isOneOf(Keywords.kw_always, Keywords.kw_always_comb,
3317 Keywords.kw_always_ff, Keywords.kw_always_latch,
3318 Keywords.kw_final, Keywords.kw_initial,
3319 Keywords.kw_foreach, Keywords.kw_forever,
3320 Keywords.kw_repeat))) &&
3321 "'for', 'while' or foreach macro expected");
3322 const bool KeepBraces = !Style.RemoveBracesLLVM ||
3323 FormatTok->isNoneOf(tok::kw_for, tok::kw_while);
3327 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
3329 if (IsCpp && FormatTok->is(tok::kw_co_await))
3331 if (HasParens && FormatTok->is(tok::l_paren)) {
3335 if (Style.isVerilog())
3336 FormatTok->setFinalizedType(TT_ConditionLParen);
3340 if (Style.isVerilog()) {
3342 parseVerilogSensitivityList();
3343 }
else if (Style.AllowShortLoopsOnASingleLine && FormatTok->is(tok::semi) &&
3344 Tokens->getPreviousToken()->is(tok::r_paren)) {
3351 parseLoopBody(KeepBraces,
true);
3354void UnwrappedLineParser::parseDoWhile() {
3355 assert(FormatTok->is(tok::kw_do) &&
"'do' expected");
3358 parseLoopBody(
true, Style.BraceWrapping.BeforeWhile);
3361 if (FormatTok->isNot(tok::kw_while)) {
3366 FormatTok->setFinalizedType(TT_DoWhile);
3370 if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)
3374 parseStructuralElement();
3377void UnwrappedLineParser::parseLabel(
3378 FormatStyle::IndentGotoLabelStyle IndentGotoLabels) {
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 (!Style.IndentCaseBlocks && CommentsBeforeNextToken.empty() &&
3396 FormatTok->is(tok::l_brace)) {
3398 CompoundStatementIndenter Indenter(
this,
Line->Level,
3399 Style.BraceWrapping.AfterCaseLabel,
3400 Style.BraceWrapping.IndentBraces);
3402 if (FormatTok->is(tok::kw_break)) {
3403 if (Style.BraceWrapping.AfterControlStatement ==
3404 FormatStyle::BWACS_Always) {
3406 if (!Style.IndentCaseBlocks &&
3407 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) {
3411 parseStructuralElement();
3415 if (FormatTok->is(tok::semi))
3419 Line->Level = OldLineLevel;
3420 if (FormatTok->isNot(tok::l_brace)) {
3421 parseStructuralElement();
3426void UnwrappedLineParser::parseCaseLabel() {
3427 assert(FormatTok->is(tok::kw_case) &&
"'case' expected");
3428 auto *Case = FormatTok;
3433 if (FormatTok->is(tok::colon)) {
3434 FormatTok->setFinalizedType(TT_CaseLabelColon);
3437 if (Style.isJava() && FormatTok->is(tok::arrow)) {
3438 FormatTok->setFinalizedType(TT_CaseLabelArrow);
3439 Case->setFinalizedType(TT_SwitchExpressionLabel);
3446void UnwrappedLineParser::parseSwitch(
bool IsExpr) {
3447 assert(FormatTok->is(tok::kw_switch) &&
"'switch' expected");
3449 if (FormatTok->is(tok::l_paren))
3452 keepAncestorBraces();
3454 if (FormatTok->is(tok::l_brace)) {
3455 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3456 FormatTok->setFinalizedType(IsExpr ? TT_SwitchExpressionLBrace
3457 : TT_ControlStatementLBrace);
3462 setPreviousRBraceType(TT_ControlStatementRBrace);
3468 parseStructuralElement();
3472 if (Style.RemoveBracesLLVM)
3473 NestedTooDeep.pop_back();
3476void UnwrappedLineParser::parseAccessSpecifier() {
3479 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
3482 if (FormatTok->is(tok::colon))
3490bool UnwrappedLineParser::parseRequires(
bool SeenEqual) {
3491 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3495 switch (Tokens->peekNextToken(
true)->Tok.getKind()) {
3498 parseRequiresExpression();
3505 parseRequiresClause();
3516 auto *PreviousNonComment = FormatTok->getPreviousNonComment();
3518 if (!PreviousNonComment ||
3519 PreviousNonComment->is(TT_RequiresExpressionLBrace)) {
3522 parseRequiresClause();
3526 switch (PreviousNonComment->Tok.getKind()) {
3529 case tok::kw_noexcept:
3534 parseRequiresClause();
3543 auto PrevPrev = PreviousNonComment->getPreviousNonComment();
3544 if ((PrevPrev && PrevPrev->is(tok::kw_const)) || !SeenEqual) {
3545 parseRequiresClause();
3551 if (PreviousNonComment->isTypeOrIdentifier(LangOpts)) {
3553 parseRequiresClause();
3557 parseRequiresExpression();
3567 unsigned StoredPosition = Tokens->getPosition();
3570 auto PeekNext = [&Lookahead, &NextToken,
this] {
3572 NextToken = Tokens->getNextToken();
3575 bool FoundType =
false;
3576 bool LastWasColonColon =
false;
3579 for (; Lookahead < 50; PeekNext()) {
3580 switch (NextToken->Tok.getKind()) {
3581 case tok::kw_volatile:
3584 if (OpenAngles == 0) {
3585 FormatTok = Tokens->setPosition(StoredPosition);
3586 parseRequiresExpression();
3594 case tok::coloncolon:
3595 LastWasColonColon =
true;
3597 case tok::kw_decltype:
3598 case tok::identifier:
3599 if (FoundType && !LastWasColonColon && OpenAngles == 0) {
3600 FormatTok = Tokens->setPosition(StoredPosition);
3601 parseRequiresExpression();
3605 LastWasColonColon =
false;
3614 if (NextToken->isTypeName(LangOpts)) {
3615 FormatTok = Tokens->setPosition(StoredPosition);
3616 parseRequiresExpression();
3623 FormatTok = Tokens->setPosition(StoredPosition);
3624 parseRequiresClause();
3633void UnwrappedLineParser::parseRequiresClause() {
3634 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3639 bool InRequiresExpression =
3640 !FormatTok->Previous ||
3641 FormatTok->Previous->is(TT_RequiresExpressionLBrace);
3643 FormatTok->setFinalizedType(InRequiresExpression
3644 ? TT_RequiresClauseInARequiresExpression
3645 : TT_RequiresClause);
3650 parseConstraintExpression();
3652 if (!InRequiresExpression && FormatTok->Previous)
3653 FormatTok->Previous->ClosesRequiresClause =
true;
3661void UnwrappedLineParser::parseRequiresExpression() {
3662 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3664 FormatTok->setFinalizedType(TT_RequiresExpression);
3667 if (FormatTok->is(tok::l_paren)) {
3668 FormatTok->setFinalizedType(TT_RequiresExpressionLParen);
3672 if (FormatTok->is(tok::l_brace)) {
3673 FormatTok->setFinalizedType(TT_RequiresExpressionLBrace);
3682void UnwrappedLineParser::parseConstraintExpression() {
3689 bool LambdaNextTimeAllowed =
true;
3699 bool TopLevelParensAllowed =
true;
3702 bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed,
false);
3704 switch (FormatTok->Tok.getKind()) {
3705 case tok::kw_requires:
3706 parseRequiresExpression();
3710 if (!TopLevelParensAllowed)
3712 parseParens(TT_BinaryOperator);
3713 TopLevelParensAllowed =
false;
3717 if (!LambdaThisTimeAllowed || !tryToParseLambda())
3724 case tok::kw_struct:
3734 FormatTok->setFinalizedType(TT_BinaryOperator);
3736 LambdaNextTimeAllowed =
true;
3737 TopLevelParensAllowed =
true;
3742 LambdaNextTimeAllowed = LambdaThisTimeAllowed;
3746 case tok::kw_sizeof:
3748 case tok::greaterequal:
3749 case tok::greatergreater:
3751 case tok::lessequal:
3753 case tok::equalequal:
3755 case tok::exclaimequal:
3760 LambdaNextTimeAllowed =
true;
3761 TopLevelParensAllowed =
true;
3766 case tok::numeric_constant:
3767 case tok::coloncolon:
3770 TopLevelParensAllowed =
false;
3775 case tok::kw_static_cast:
3776 case tok::kw_const_cast:
3777 case tok::kw_reinterpret_cast:
3778 case tok::kw_dynamic_cast:
3780 if (FormatTok->isNot(tok::less))
3784 parseBracedList(
true);
3788 if (!FormatTok->Tok.getIdentifierInfo()) {
3798 assert(FormatTok->Previous);
3799 switch (FormatTok->Previous->Tok.getKind()) {
3800 case tok::coloncolon:
3804 case tok::kw_requires:
3813 if (FormatTok->is(tok::less)) {
3815 parseBracedList(
true);
3817 TopLevelParensAllowed =
false;
3823bool UnwrappedLineParser::parseEnum() {
3827 if (FormatTok->is(tok::kw_enum))
3833 if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question))
3837 if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal))
3842 if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
3844 while (FormatTok->is(tok::l_square))
3845 if (!handleCppAttributes())
3849 while (FormatTok->Tok.getIdentifierInfo() ||
3850 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
3851 tok::greater, tok::comma, tok::question,
3853 if (FormatTok->is(tok::colon))
3854 FormatTok->setFinalizedType(TT_EnumUnderlyingTypeColon);
3855 if (Style.isVerilog()) {
3856 FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
3859 while (FormatTok->is(tok::l_square))
3865 if (FormatTok->is(tok::l_paren))
3867 if (FormatTok->is(tok::identifier)) {
3871 if (IsCpp && FormatTok->is(tok::identifier))
3877 if (FormatTok->isNot(tok::l_brace))
3879 FormatTok->setFinalizedType(TT_EnumLBrace);
3880 FormatTok->setBlockKind(BK_Block);
3882 if (Style.isJava()) {
3884 parseJavaEnumBody();
3887 if (Style.Language == FormatStyle::LK_Proto) {
3892 const bool ManageWhitesmithsBraces =
3893 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
3895 if (!Style.AllowShortEnumsOnASingleLine &&
3897 Tokens->peekNextToken()->is(tok::r_brace))) {
3902 if (ManageWhitesmithsBraces)
3907 if (!Style.AllowShortEnumsOnASingleLine) {
3909 if (!ManageWhitesmithsBraces)
3912 const auto OpeningLineIndex = CurrentLines->empty()
3913 ? UnwrappedLine::kInvalidIndex
3914 : CurrentLines->size() - 1;
3915 bool HasError = !parseBracedList(
false,
true);
3916 if (!Style.AllowShortEnumsOnASingleLine && !ManageWhitesmithsBraces)
3919 if (FormatTok->is(tok::semi))
3923 setPreviousRBraceType(TT_EnumRBrace);
3924 if (ManageWhitesmithsBraces)
3925 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
3933bool UnwrappedLineParser::parseStructLike() {
3938 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp()) {
3939 if (FormatTok->is(tok::semi))
3950class ScopedTokenPosition {
3951 unsigned StoredPosition;
3952 FormatTokenSource *Tokens;
3955 ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) {
3956 assert(Tokens &&
"Tokens expected to not be null");
3957 StoredPosition = Tokens->getPosition();
3960 ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); }
3966bool UnwrappedLineParser::tryToParseSimpleAttribute() {
3967 ScopedTokenPosition AutoPosition(Tokens);
3975 if (
Tok->
is(tok::r_square))
3977 Tok = Tokens->getNextToken();
3979 if (
Tok->
is(tok::eof))
3981 Tok = Tokens->getNextToken();
3984 Tok = Tokens->getNextToken();
3985 if (
Tok->
is(tok::semi))
3990void UnwrappedLineParser::parseJavaEnumBody() {
3991 assert(FormatTok->is(tok::l_brace));
3997 unsigned StoredPosition = Tokens->getPosition();
3998 bool IsSimple =
true;
4001 if (
Tok->
is(tok::r_brace))
4009 Tok = Tokens->getNextToken();
4011 FormatTok = Tokens->setPosition(StoredPosition);
4028 if (FormatTok->is(tok::l_brace)) {
4030 parseBlock(
true, 1u,
4032 }
else if (FormatTok->is(tok::l_paren)) {
4034 }
else if (FormatTok->is(tok::comma)) {
4037 }
else if (FormatTok->is(tok::semi)) {
4041 }
else if (FormatTok->is(tok::r_brace)) {
4050 parseLevel(OpeningBrace);
4056void UnwrappedLineParser::parseRecord(
bool ParseAsExpr,
bool IsJavaRecord) {
4057 assert(!IsJavaRecord || FormatTok->is(Keywords.kw_record));
4062 IsJavaRecord && FormatTok->is(tok::identifier) ? FormatTok :
nullptr;
4063 bool IsDerived =
false;
4065 return Tok->
is(tok::identifier) &&
Tok->TokenText !=
Tok->TokenText.upper();
4069 bool JSPastExtendsOrImplements =
false;
4073 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
4074 tok::kw_alignas, tok::l_square) ||
4075 FormatTok->isAttribute() ||
4076 ((Style.isJava() || Style.isJavaScript()) &&
4077 FormatTok->isOneOf(tok::period, tok::comma))) {
4078 if (Style.isJavaScript() &&
4079 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
4080 JSPastExtendsOrImplements =
true;
4085 if (FormatTok->is(tok::l_brace)) {
4086 tryToParseBracedList();
4090 if (FormatTok->is(tok::l_square) && handleCppAttributes())
4094 switch (FormatTok->Tok.getKind()) {
4097 if (IsJavaRecord || !IsNonMacroIdentifier(
Previous) ||
4099 Previous->Previous == &InitialToken) {
4103 case tok::coloncolon:
4107 if (JSPastExtendsOrImplements || ClassName ||
4118 auto IsListInitialization = [&] {
4119 if (!ClassName || IsDerived || JSPastExtendsOrImplements)
4121 assert(FormatTok->is(tok::l_brace));
4122 const auto *Prev = FormatTok->getPreviousNonComment();
4124 return Prev != ClassName && Prev->is(tok::identifier) &&
4125 Prev->isNot(Keywords.kw_final) && tryToParseBracedList();
4128 if (FormatTok->isOneOf(tok::colon, tok::less)) {
4129 int AngleNestingLevel = 0;
4131 if (FormatTok->is(tok::less))
4132 ++AngleNestingLevel;
4133 else if (FormatTok->is(tok::greater))
4134 --AngleNestingLevel;
4136 if (AngleNestingLevel == 0) {
4137 if (FormatTok->is(tok::colon)) {
4139 }
else if (!IsDerived && FormatTok->is(tok::identifier) &&
4140 FormatTok->Previous->is(tok::coloncolon)) {
4141 ClassName = FormatTok;
4142 }
else if (FormatTok->is(tok::l_paren) &&
4143 IsNonMacroIdentifier(FormatTok->Previous)) {
4147 if (FormatTok->is(tok::l_brace)) {
4148 if (AngleNestingLevel == 0 && IsListInitialization())
4150 calculateBraceTypes(
true);
4151 if (!tryToParseBracedList())
4154 if (FormatTok->is(tok::l_square)) {
4157 !
Previous->isTypeOrIdentifier(LangOpts))) {
4160 if (!tryToParseLambda())
4167 if (FormatTok->is(tok::semi))
4169 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
4172 parseCSharpGenericTypeConstraint();
4179 auto GetBraceTypes =
4180 [](
const FormatToken &RecordTok) -> std::pair<TokenType, TokenType> {
4181 switch (RecordTok.Tok.getKind()) {
4183 return {TT_ClassLBrace, TT_ClassRBrace};
4184 case tok::kw_struct:
4185 return {TT_StructLBrace, TT_StructRBrace};
4187 return {TT_UnionLBrace, TT_UnionRBrace};
4190 return {TT_RecordLBrace, TT_RecordRBrace};
4193 if (FormatTok->is(tok::l_brace)) {
4194 if (IsListInitialization())
4197 ClassName->setFinalizedType(TT_ClassHeadName);
4198 auto [OpenBraceType, ClosingBraceType] = GetBraceTypes(InitialToken);
4199 FormatTok->setFinalizedType(OpenBraceType);
4204 Tokens->peekNextToken()->is(tok::r_brace),
4209 unsigned AddLevels = Style.IndentAccessModifiers ? 2u : 1u;
4210 parseBlock(
true, AddLevels,
false);
4212 setPreviousRBraceType(ClosingBraceType);
4219void UnwrappedLineParser::parseObjCMethod() {
4220 assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) &&
4221 "'(' or identifier expected.");
4223 if (FormatTok->is(tok::semi)) {
4227 }
else if (FormatTok->is(tok::l_brace)) {
4228 if (Style.BraceWrapping.AfterFunction)
4239void UnwrappedLineParser::parseObjCProtocolList() {
4240 assert(FormatTok->is(tok::less) &&
"'<' expected.");
4244 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4246 }
while (!
eof() && FormatTok->isNot(tok::greater));
4250void UnwrappedLineParser::parseObjCUntilAtEnd() {
4252 if (FormatTok->is(tok::objc_end)) {
4257 if (FormatTok->is(tok::l_brace)) {
4261 }
else if (FormatTok->is(tok::r_brace)) {
4265 }
else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
4269 parseStructuralElement();
4274void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
4275 assert(FormatTok->isOneOf(tok::objc_interface, tok::objc_implementation));
4281 if (FormatTok->is(tok::less))
4282 parseObjCLightweightGenerics();
4283 if (FormatTok->is(tok::colon)) {
4287 if (FormatTok->is(tok::less))
4288 parseObjCLightweightGenerics();
4289 }
else if (FormatTok->is(tok::l_paren)) {
4294 if (FormatTok->is(tok::less))
4295 parseObjCProtocolList();
4297 if (FormatTok->is(tok::l_brace)) {
4298 if (Style.BraceWrapping.AfterObjCDeclaration)
4307 parseObjCUntilAtEnd();
4310void UnwrappedLineParser::parseObjCLightweightGenerics() {
4311 assert(FormatTok->is(tok::less));
4319 unsigned NumOpenAngles = 1;
4323 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4325 if (FormatTok->is(tok::less)) {
4327 }
else if (FormatTok->is(tok::greater)) {
4328 assert(NumOpenAngles > 0 &&
"'>' makes NumOpenAngles negative");
4331 }
while (!
eof() && NumOpenAngles != 0);
4337bool UnwrappedLineParser::parseObjCProtocol() {
4338 assert(FormatTok->is(tok::objc_protocol));
4341 if (FormatTok->is(tok::l_paren)) {
4353 if (FormatTok->is(tok::less))
4354 parseObjCProtocolList();
4357 if (FormatTok->is(tok::semi)) {
4364 parseObjCUntilAtEnd();
4368void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
4369 bool IsImport = FormatTok->is(Keywords.kw_import);
4370 assert(IsImport || FormatTok->is(tok::kw_export));
4374 if (FormatTok->is(tok::kw_default))
4380 if (FormatTok->is(Keywords.kw_async))
4382 if (FormatTok->is(Keywords.kw_function)) {
4391 if (!IsImport && FormatTok->isNoneOf(tok::l_brace, tok::star) &&
4392 !FormatTok->isStringLiteral() &&
4393 !(FormatTok->is(Keywords.kw_type) &&
4394 Tokens->peekNextToken()->isOneOf(tok::l_brace, tok::star))) {
4399 if (FormatTok->is(tok::semi))
4401 if (
Line->Tokens.empty()) {
4406 if (FormatTok->is(tok::l_brace)) {
4407 FormatTok->setBlockKind(BK_Block);
4416void UnwrappedLineParser::parseStatementMacro() {
4418 if (FormatTok->is(tok::l_paren))
4420 if (FormatTok->is(tok::semi))
4425void UnwrappedLineParser::parseVerilogHierarchyIdentifier() {
4428 if (FormatTok->isOneOf(tok::star, tok::period, tok::periodstar,
4429 tok::coloncolon, tok::hash) ||
4430 Keywords.isVerilogIdentifier(*FormatTok)) {
4432 }
else if (FormatTok->is(tok::l_square)) {
4440void UnwrappedLineParser::parseVerilogSensitivityList() {
4441 if (FormatTok->isNot(tok::at))
4445 if (FormatTok->is(tok::at))
4447 switch (FormatTok->Tok.getKind()) {
4455 parseVerilogHierarchyIdentifier();
4460unsigned UnwrappedLineParser::parseVerilogHierarchyHeader() {
4461 unsigned AddLevels = 0;
4463 if (FormatTok->is(Keywords.kw_clocking)) {
4465 if (Keywords.isVerilogIdentifier(*FormatTok))
4467 parseVerilogSensitivityList();
4468 if (FormatTok->is(tok::semi))
4470 }
else if (FormatTok->isOneOf(tok::kw_case, Keywords.kw_casex,
4471 Keywords.kw_casez, Keywords.kw_randcase,
4472 Keywords.kw_randsequence)) {
4473 if (Style.IndentCaseLabels)
4476 if (FormatTok->is(tok::l_paren)) {
4477 FormatTok->setFinalizedType(TT_ConditionLParen);
4480 if (FormatTok->isOneOf(Keywords.kw_inside, Keywords.kw_matches))
4489 if (FormatTok->is(tok::l_square)) {
4490 auto Prev = FormatTok->getPreviousNonComment();
4491 if (Prev && Keywords.isVerilogIdentifier(*Prev))
4492 Prev->setFinalizedType(TT_VerilogDimensionedTypeName);
4494 }
else if (Keywords.isVerilogIdentifier(*FormatTok) ||
4495 FormatTok->isOneOf(tok::hash, tok::hashhash, tok::coloncolon,
4496 Keywords.kw_automatic, tok::kw_static)) {
4503 auto NewLine = [
this]() {
4505 Line->IsContinuation =
true;
4509 while (FormatTok->is(Keywords.kw_import)) {
4512 parseVerilogHierarchyIdentifier();
4513 if (FormatTok->is(tok::semi))
4518 if (FormatTok->is(Keywords.kw_verilogHash)) {
4521 if (FormatTok->is(tok::l_paren)) {
4522 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4526 if (FormatTok->is(tok::l_paren)) {
4528 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4533 if (FormatTok->is(Keywords.kw_extends)) {
4536 parseVerilogHierarchyIdentifier();
4537 if (FormatTok->is(tok::l_paren))
4540 if (FormatTok->is(Keywords.kw_implements)) {
4544 parseVerilogHierarchyIdentifier();
4545 }
while (FormatTok->is(tok::comma));
4549 if (FormatTok->is(tok::at)) {
4551 parseVerilogSensitivityList();
4554 if (FormatTok->is(tok::semi))
4562void UnwrappedLineParser::parseVerilogTable() {
4563 assert(FormatTok->is(Keywords.kw_table));
4567 auto InitialLevel =
Line->Level++;
4568 while (!
eof() && !Keywords.isVerilogEnd(*FormatTok)) {
4571 if (
Tok->
is(tok::semi))
4573 else if (
Tok->
isOneOf(tok::star, tok::colon, tok::question, tok::minus))
4574 Tok->setFinalizedType(TT_VerilogTableItem);
4576 Line->Level = InitialLevel;
4581void UnwrappedLineParser::parseVerilogCaseLabel() {
4587 auto OrigLevel =
Line->Level;
4588 auto FirstLine = CurrentLines->size();
4589 if (
Line->Level == 0 || (
Line->InPPDirective &&
Line->Level <= 1))
4591 else if (!Style.IndentCaseBlocks && Keywords.isVerilogBegin(*FormatTok))
4593 parseStructuralElement();
4596 if (CurrentLines->size() > FirstLine)
4597 (*CurrentLines)[FirstLine].Level = OrigLevel;
4598 Line->Level = OrigLevel;
4601void UnwrappedLineParser::parseVerilogExtern() {
4603 FormatTok->isOneOf(tok::kw_extern, tok::kw_export, Keywords.kw_import));
4606 if (FormatTok->is(tok::string_literal))
4608 if (FormatTok->isOneOf(Keywords.kw_context, Keywords.kw_pure))
4610 if (Keywords.isVerilogIdentifier(*FormatTok))
4612 if (FormatTok->is(tok::equal))
4614 if (Keywords.isVerilogHierarchy(*FormatTok))
4615 parseVerilogHierarchyHeader();
4618bool UnwrappedLineParser::containsExpansion(
const UnwrappedLine &
Line)
const {
4619 for (
const auto &N :
Line.Tokens) {
4620 if (N.Tok->MacroCtx)
4622 for (
const UnwrappedLine &Child : N.Children)
4623 if (containsExpansion(Child))
4629void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) {
4630 if (
Line->Tokens.empty())
4633 if (!parsingPPDirective()) {
4634 llvm::dbgs() <<
"Adding unwrapped line:\n";
4635 printDebugInfo(*
Line);
4643 bool ClosesWhitesmithsBlock =
4644 Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex &&
4645 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
4650 if (!parsingPPDirective() && !InExpansion && containsExpansion(*
Line)) {
4652 Reconstruct.emplace(
Line->Level, Unexpanded);
4653 Reconstruct->addLine(*
Line);
4658 CurrentExpandedLines.push_back(std::move(*
Line));
4660 if (Reconstruct->finished()) {
4661 UnwrappedLine Reconstructed = std::move(*Reconstruct).takeResult();
4662 assert(!Reconstructed.Tokens.empty() &&
4663 "Reconstructed must at least contain the macro identifier.");
4664 assert(!parsingPPDirective());
4666 llvm::dbgs() <<
"Adding unexpanded line:\n";
4667 printDebugInfo(Reconstructed);
4669 ExpandedLines[Reconstructed.Tokens.begin()->Tok] = CurrentExpandedLines;
4670 Lines.push_back(std::move(Reconstructed));
4671 CurrentExpandedLines.clear();
4672 Reconstruct.reset();
4677 assert(!Reconstruct || (CurrentLines != &Lines) || !PPStack.empty());
4678 CurrentLines->push_back(std::move(*
Line));
4680 Line->Tokens.clear();
4681 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
4682 Line->FirstStartColumn = 0;
4683 Line->IsContinuation =
false;
4684 Line->SeenDecltypeAuto =
false;
4686 if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove)
4688 if (!parsingPPDirective() && !PreprocessorDirectives.empty()) {
4689 CurrentLines->append(
4690 std::make_move_iterator(PreprocessorDirectives.begin()),
4691 std::make_move_iterator(PreprocessorDirectives.end()));
4692 PreprocessorDirectives.clear();
4695 FormatTok->Previous =
nullptr;
4698bool UnwrappedLineParser::eof()
const {
return FormatTok->is(tok::eof); }
4700bool UnwrappedLineParser::isOnNewLine(
const FormatToken &FormatTok) {
4701 return (
Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
4702 FormatTok.NewlinesBefore > 0;
4710 const llvm::Regex &CommentPragmasRegex) {
4711 if (
Line.Tokens.empty() || Style.ReflowComments != FormatStyle::RCS_Always)
4714 StringRef IndentContent = FormatTok.
TokenText;
4715 if (FormatTok.
TokenText.starts_with(
"//") ||
4716 FormatTok.
TokenText.starts_with(
"/*")) {
4717 IndentContent = FormatTok.
TokenText.substr(2);
4719 if (CommentPragmasRegex.match(IndentContent))
4794 if (PreviousToken && PreviousToken->
is(tok::l_brace) &&
4796 MinColumnToken = PreviousToken;
4799 PreviousToken = Node.
Tok;
4803 MinColumnToken = Node.
Tok;
4805 if (PreviousToken && PreviousToken->
is(tok::l_brace))
4806 MinColumnToken = PreviousToken;
4812void UnwrappedLineParser::flushComments(
bool NewlineBeforeNext) {
4813 bool JustComments =
Line->Tokens.empty();
4823 Tok->ContinuesLineCommentSection =
4824 continuesLineCommentSection(*
Tok, *
Line, Style, CommentPragmasRegex);
4825 if (isOnNewLine(*
Tok) && JustComments && !
Tok->ContinuesLineCommentSection)
4829 if (NewlineBeforeNext && JustComments)
4831 CommentsBeforeNextToken.clear();
4834void UnwrappedLineParser::nextToken(
int LevelDifference) {
4837 flushComments(isOnNewLine(*FormatTok));
4838 pushToken(FormatTok);
4840 if (!Style.isJavaScript())
4841 readToken(LevelDifference);
4843 readTokenWithJavaScriptASI();
4845 if (Style.isVerilog()) {
4852 if (Keywords.isVerilogEnd(*FormatTok))
4853 FormatTok->Tok.setKind(tok::r_brace);
4857void UnwrappedLineParser::distributeComments(
4877 if (Comments.empty())
4879 bool ShouldPushCommentsInCurrentLine =
true;
4880 bool HasTrailAlignedWithNextToken =
false;
4881 unsigned StartOfTrailAlignedWithNextToken = 0;
4884 for (
unsigned i = Comments.size() - 1; i > 0; --i) {
4886 HasTrailAlignedWithNextToken =
true;
4887 StartOfTrailAlignedWithNextToken = i;
4891 for (
unsigned i = 0, e = Comments.size(); i < e; ++i) {
4893 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
4894 FormatTok->ContinuesLineCommentSection =
false;
4897 *FormatTok, *
Line, Style, CommentPragmasRegex);
4899 if (!FormatTok->ContinuesLineCommentSection &&
4900 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
4901 ShouldPushCommentsInCurrentLine =
false;
4903 if (ShouldPushCommentsInCurrentLine)
4904 pushToken(FormatTok);
4906 CommentsBeforeNextToken.push_back(FormatTok);
4910void UnwrappedLineParser::readToken(
int LevelDifference) {
4912 bool PreviousWasComment =
false;
4913 bool FirstNonCommentOnLine =
false;
4915 FormatTok = Tokens->getNextToken();
4917 while (FormatTok->isOneOf(TT_ConflictStart, TT_ConflictEnd,
4918 TT_ConflictAlternative)) {
4919 if (FormatTok->is(TT_ConflictStart))
4920 conditionalCompilationStart(
false);
4921 else if (FormatTok->is(TT_ConflictAlternative))
4922 conditionalCompilationAlternative();
4923 else if (FormatTok->is(TT_ConflictEnd))
4924 conditionalCompilationEnd();
4925 FormatTok = Tokens->getNextToken();
4926 FormatTok->MustBreakBefore =
true;
4927 FormatTok->MustBreakBeforeFinalized =
true;
4930 auto IsFirstNonCommentOnLine = [](
bool FirstNonCommentOnLine,
4932 bool PreviousWasComment) {
4934 return Tok.HasUnescapedNewline ||
Tok.IsFirst;
4939 if (PreviousWasComment)
4940 return FirstNonCommentOnLine || IsFirstOnLine(
Tok);
4941 return IsFirstOnLine(
Tok);
4944 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
4945 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
4946 PreviousWasComment = FormatTok->is(tok::comment);
4948 while (!
Line->InPPDirective && FormatTok->is(tok::hash) &&
4949 FirstNonCommentOnLine) {
4952 const auto *
Next = Tokens->peekNextToken();
4953 if ((Style.isVerilog() && !Keywords.isVerilogPPDirective(*
Next)) ||
4954 (Style.isTableGen() &&
4955 Next->isNoneOf(tok::kw_else, tok::pp_define, tok::pp_ifdef,
4956 tok::pp_ifndef, tok::pp_endif))) {
4959 distributeComments(Comments, FormatTok);
4963 bool SwitchToPreprocessorLines = !
Line->Tokens.empty();
4964 ScopedLineState BlockState(*
this, SwitchToPreprocessorLines);
4965 assert((LevelDifference >= 0 ||
4966 static_cast<unsigned>(-LevelDifference) <=
Line->Level) &&
4967 "LevelDifference makes Line->Level negative");
4968 Line->Level += LevelDifference;
4972 if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash &&
4973 PPBranchLevel > 0) {
4974 Line->Level += PPBranchLevel;
4976 assert(
Line->Level >=
Line->UnbracedBodyLevel);
4977 Line->Level -=
Line->UnbracedBodyLevel;
4978 flushComments(isOnNewLine(*FormatTok));
4979 const bool IsEndIf = Tokens->peekNextToken()->is(tok::pp_endif);
4981 PreviousWasComment = FormatTok->is(tok::comment);
4982 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
4983 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
4986 if (IsEndIf && IncludeGuard == IG_Defined && PPBranchLevel == -1 &&
4987 getIncludeGuardState(Style.IndentPPDirectives) == IG_Inited &&
4989 (PreviousWasComment &&
4990 Tokens->peekNextToken(
true)->is(tok::eof)))) {
4991 IncludeGuard = IG_Found;
4995 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
4996 !
Line->InPPDirective) {
5000 if (FormatTok->is(tok::identifier) &&
5001 Macros.defined(FormatTok->TokenText) &&
5003 !
Line->InPPDirective) {
5005 unsigned Position = Tokens->getPosition();
5009 auto PreCall = std::move(
Line);
5010 Line.reset(
new UnwrappedLine);
5011 bool OldInExpansion = InExpansion;
5014 auto Args = parseMacroCall();
5015 InExpansion = OldInExpansion;
5016 assert(
Line->Tokens.front().Tok == ID);
5018 auto UnexpandedLine = std::move(
Line);
5020 Line = std::move(PreCall);
5023 llvm::dbgs() <<
"Macro call: " <<
ID->TokenText <<
"(";
5025 llvm::dbgs() <<
"(";
5026 for (
const auto &Arg : Args.value())
5027 for (
const auto &T : Arg)
5028 llvm::dbgs() << T->TokenText <<
" ";
5029 llvm::dbgs() <<
")";
5031 llvm::dbgs() <<
"\n";
5033 if (
Macros.objectLike(
ID->TokenText) && Args &&
5034 !
Macros.hasArity(
ID->TokenText, Args->size())) {
5040 LLVM_DEBUG(llvm::dbgs()
5041 <<
"Macro \"" <<
ID->TokenText
5042 <<
"\" not overloaded for arity " << Args->size()
5043 <<
"or not function-like, using object-like overload.");
5045 UnexpandedLine->Tokens.resize(1);
5046 Tokens->setPosition(Position);
5048 assert(!Args &&
Macros.objectLike(
ID->TokenText));
5050 if ((!Args &&
Macros.objectLike(
ID->TokenText)) ||
5051 (Args &&
Macros.hasArity(
ID->TokenText, Args->size()))) {
5054 Unexpanded[
ID] = std::move(UnexpandedLine);
5056 Macros.expand(ID, std::move(Args));
5057 if (!Expansion.empty())
5058 FormatTok = Tokens->insertTokens(Expansion);
5061 llvm::dbgs() <<
"Expanded: ";
5062 for (
const auto &T : Expansion)
5063 llvm::dbgs() << T->TokenText <<
" ";
5064 llvm::dbgs() <<
"\n";
5068 llvm::dbgs() <<
"Did not expand macro \"" <<
ID->TokenText
5069 <<
"\", because it was used ";
5071 llvm::dbgs() <<
"with " << Args->size();
5073 llvm::dbgs() <<
"without";
5074 llvm::dbgs() <<
" arguments, which doesn't match any definition.\n";
5076 Tokens->setPosition(Position);
5081 if (FormatTok->isNot(tok::comment)) {
5082 distributeComments(Comments, FormatTok);
5087 Comments.push_back(FormatTok);
5090 distributeComments(Comments,
nullptr);
5095template <
typename Iterator>
5096void pushTokens(Iterator Begin, Iterator End,
5098 for (
auto I = Begin; I != End; ++I) {
5099 Into.push_back(I->Tok);
5100 for (
const auto &Child : I->Children)
5101 pushTokens(Child.Tokens.begin(), Child.Tokens.end(), Into);
5106std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>
5107UnwrappedLineParser::parseMacroCall() {
5108 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>> Args;
5109 assert(
Line->Tokens.empty());
5111 if (FormatTok->isNot(tok::l_paren))
5113 unsigned Position = Tokens->getPosition();
5117 auto ArgStart = std::prev(
Line->Tokens.end());
5121 switch (FormatTok->Tok.getKind()) {
5126 case tok::r_paren: {
5132 Args->push_back({});
5133 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5142 Args->push_back({});
5143 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5145 ArgStart = std::prev(
Line->Tokens.end());
5153 Line->Tokens.resize(1);
5154 Tokens->setPosition(Position);
5160 Line->Tokens.push_back(UnwrappedLineNode(
Tok));
5161 if (AtEndOfPPLine) {
5162 auto &
Tok = *
Line->Tokens.back().Tok;
5163 Tok.MustBreakBefore =
true;
5164 Tok.MustBreakBeforeFinalized =
true;
5165 Tok.FirstAfterPPLine =
true;
5166 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.