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::l_paren: {
1892 Tokens->peekNextToken(
true),
1899 case tok::kw_operator:
1901 if (FormatTok->isBinaryOperator())
1905 const auto *Prev = FormatTok->getPreviousNonComment();
1907 if (Prev && Prev->is(tok::identifier))
1910 if (FormatTok->Tok.isAnyIdentifier() || FormatTok->isTypeName(LangOpts)) {
1913 while (FormatTok->is(tok::star))
1917 if (FormatTok->is(tok::l_paren))
1920 if (FormatTok->is(tok::l_brace))
1925 if (InRequiresExpression)
1926 FormatTok->setFinalizedType(TT_BracedListLBrace);
1927 if (!tryToParsePropertyAccessor() && !tryToParseBracedList()) {
1928 IsDecltypeAutoFunction =
Line->SeenDecltypeAuto;
1933 if (Style.isJava() &&
1934 Line->Tokens.front().Tok->is(Keywords.kw_synchronized)) {
1937 if (Style.BraceWrapping.AfterControlStatement ==
1938 FormatStyle::BWACS_Always) {
1941 }
else if (Style.BraceWrapping.AfterFunction) {
1945 FormatTok->setFinalizedType(TT_FunctionLBrace);
1947 IsDecltypeAutoFunction =
false;
1955 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1961 if (Style.BraceWrapping.AfterFunction)
1965 case tok::identifier: {
1966 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where) &&
1967 Line->MustBeDeclaration) {
1969 parseCSharpGenericTypeConstraint();
1972 if (FormatTok->is(TT_MacroBlockEnd)) {
1981 size_t TokenCount =
Line->Tokens.size();
1982 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_function) &&
1985 Line->Tokens.front().Tok->isNot(Keywords.kw_async)))) {
1986 tryToParseJSFunction();
1989 if ((Style.isJavaScript() || Style.isJava()) &&
1990 FormatTok->is(Keywords.kw_interface)) {
1991 if (Style.isJavaScript()) {
1996 unsigned StoredPosition = Tokens->getPosition();
1998 FormatTok = Tokens->setPosition(StoredPosition);
2009 if (Style.isVerilog()) {
2010 if (FormatTok->is(Keywords.kw_table)) {
2011 parseVerilogTable();
2014 if (Keywords.isVerilogBegin(*FormatTok) ||
2015 Keywords.isVerilogHierarchy(*FormatTok)) {
2022 if (!IsCpp && FormatTok->is(Keywords.kw_interface)) {
2023 if (parseStructLike())
2028 if (IsCpp && FormatTok->is(TT_StatementMacro)) {
2029 parseStatementMacro();
2034 StringRef
Text = FormatTok->TokenText;
2041 if (Style.isJavaScript())
2044 auto OneTokenSoFar = [&]() {
2045 auto I =
Line->Tokens.begin(), E =
Line->Tokens.end();
2046 while (I != E && I->Tok->is(tok::comment))
2048 if (Style.isVerilog())
2049 while (I != E && I->Tok->is(tok::hash))
2051 return I != E && (++I == E);
2053 if (OneTokenSoFar()) {
2056 bool FunctionLike = FormatTok->is(tok::l_paren);
2060 bool FollowedByNewline =
2061 CommentsBeforeNextToken.empty()
2062 ? FormatTok->NewlinesBefore > 0
2063 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
2065 if (FollowedByNewline &&
2066 (
Text.size() >= 5 ||
2067 (FunctionLike && FormatTok->isNot(tok::l_paren))) &&
2069 if (PreviousToken->isNot(TT_UntouchableMacroFunc))
2070 PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro);
2078 if ((Style.isJavaScript() || Style.isCSharp()) &&
2079 FormatTok->is(TT_FatArrow)) {
2080 tryToParseChildBlock();
2086 if (FormatTok->is(tok::l_brace)) {
2090 if (Style.isCSharp())
2091 FormatTok->setBlockKind(BK_BracedInit);
2094 if (Style.isTableGen() &&
2095 Line->Tokens.begin()->Tok->is(Keywords.kw_defset)) {
2096 FormatTok->setFinalizedType(TT_FunctionLBrace);
2097 parseBlock(
false, 1u,
2104 }
else if (Style.Language == FormatStyle::LK_Proto &&
2105 FormatTok->is(tok::less)) {
2107 parseBracedList(
true);
2114 if (Style.isCSharp() &&
2115 (Tokens->peekNextToken()->isAccessSpecifierKeyword() ||
2122 case tok::kw_switch:
2130 if (Style.Language == FormatStyle::LK_Proto) {
2135 if (Style.isVerilog()) {
2140 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
2147 case tok::kw_default:
2149 if (Style.isVerilog()) {
2150 if (FormatTok->is(tok::colon)) {
2154 if (FormatTok->is(Keywords.kw_clocking)) {
2160 parseVerilogCaseLabel();
2166 if (Style.isVerilog()) {
2167 parseVerilogCaseLabel();
2173 if (FormatTok->is(tok::l_brace))
2174 FormatTok->Previous->setFinalizedType(TT_TemplateCloser);
2183bool UnwrappedLineParser::tryToParsePropertyAccessor() {
2184 assert(FormatTok->is(tok::l_brace));
2185 if (!Style.isCSharp())
2188 if (!FormatTok->Previous || FormatTok->Previous->isNot(tok::identifier))
2196 unsigned int StoredPosition = Tokens->getPosition();
2202 bool HasSpecialAccessor =
false;
2203 bool IsTrivialPropertyAccessor =
true;
2206 if (
const bool IsAccessorKeyword =
2207 Tok->
isOneOf(Keywords.kw_get, Keywords.kw_init, Keywords.kw_set);
2208 IsAccessorKeyword ||
Tok->isAccessSpecifierKeyword() ||
2209 Tok->
isOneOf(tok::l_square, tok::semi, Keywords.kw_internal)) {
2210 if (IsAccessorKeyword)
2211 HasSpecialAccessor =
true;
2212 else if (
Tok->
is(tok::l_square))
2214 Tok = Tokens->getNextToken();
2218 IsTrivialPropertyAccessor =
false;
2223 Tokens->setPosition(StoredPosition);
2229 Tokens->setPosition(StoredPosition);
2230 if (!IsTrivialPropertyAccessor && Style.BraceWrapping.AfterFunction)
2234 switch (FormatTok->Tok.getKind()) {
2237 if (FormatTok->is(tok::equal)) {
2238 while (!
eof() && FormatTok->isNot(tok::semi))
2251 if (FormatTok->is(TT_FatArrow)) {
2255 }
while (!
eof() && FormatTok->isNot(tok::semi));
2264 if (FormatTok->isOneOf(Keywords.kw_get, Keywords.kw_init,
2266 !IsTrivialPropertyAccessor) {
2278bool UnwrappedLineParser::tryToParseLambda() {
2279 assert(FormatTok->is(tok::l_square));
2285 if (!tryToParseLambdaIntroducer())
2289 bool InTemplateParameterList =
false;
2291 while (FormatTok->isNot(tok::l_brace)) {
2292 if (FormatTok->isTypeName(LangOpts) || FormatTok->isAttribute()) {
2296 switch (FormatTok->Tok.getKind()) {
2300 parseParens(TT_PointerOrReference);
2306 assert(FormatTok->Previous);
2307 if (FormatTok->Previous->is(tok::r_square))
2308 InTemplateParameterList =
true;
2313 case tok::kw_struct:
2315 case tok::kw_template:
2316 case tok::kw_typename:
2320 case tok::kw_constexpr:
2321 case tok::kw_consteval:
2324 case tok::identifier:
2325 case tok::numeric_constant:
2326 case tok::coloncolon:
2327 case tok::kw_mutable:
2328 case tok::kw_noexcept:
2329 case tok::kw_static:
2354 case tok::equalequal:
2355 case tok::exclaimequal:
2356 case tok::greaterequal:
2357 case tok::lessequal:
2363 if (Arrow || InTemplateParameterList) {
2372 case tok::kw_requires:
2373 parseRequiresClause();
2376 if (!InTemplateParameterList)
2385 FormatTok->setFinalizedType(TT_LambdaLBrace);
2386 LSquare.setFinalizedType(TT_LambdaLSquare);
2389 Arrow->setFinalizedType(TT_LambdaArrow);
2391 NestedLambdas.push_back(
Line->SeenDecltypeAuto);
2393 assert(!NestedLambdas.empty());
2394 NestedLambdas.pop_back();
2399bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
2404 const auto *PrevPrev =
Previous->getPreviousNonComment();
2405 if (
Previous->is(tok::star) && PrevPrev && PrevPrev->isTypeName(LangOpts))
2413 if (!PrevPrev || PrevPrev->isNoneOf(tok::greater, tok::r_paren))
2417 Previous->isNoneOf(tok::kw_return, tok::kw_co_await, tok::kw_co_yield,
2418 tok::kw_co_return)) {
2422 if (LeftSquare->isCppStructuredBinding(IsCpp))
2424 if (FormatTok->is(tok::l_square) ||
tok::isLiteral(FormatTok->Tok.getKind()))
2426 if (FormatTok->is(tok::r_square)) {
2428 if (
Next->is(tok::greater))
2435void UnwrappedLineParser::tryToParseJSFunction() {
2436 assert(FormatTok->is(Keywords.kw_function));
2437 if (FormatTok->is(Keywords.kw_async))
2443 if (FormatTok->is(tok::star)) {
2444 FormatTok->setFinalizedType(TT_OverloadedOperator);
2449 if (FormatTok->is(tok::identifier))
2452 if (FormatTok->isNot(tok::l_paren))
2458 if (FormatTok->is(tok::colon)) {
2464 if (FormatTok->is(tok::l_brace))
2465 tryToParseBracedList();
2467 while (FormatTok->isNoneOf(tok::l_brace, tok::semi) && !
eof())
2471 if (FormatTok->is(tok::semi))
2477bool UnwrappedLineParser::tryToParseBracedList() {
2478 if (FormatTok->is(BK_Unknown))
2479 calculateBraceTypes();
2480 assert(FormatTok->isNot(BK_Unknown));
2481 if (FormatTok->is(BK_Block))
2488bool UnwrappedLineParser::tryToParseChildBlock() {
2489 assert(Style.isJavaScript() || Style.isCSharp());
2490 assert(FormatTok->is(TT_FatArrow));
2495 if (FormatTok->isNot(tok::l_brace))
2501bool UnwrappedLineParser::parseBracedList(
bool IsAngleBracket,
bool IsEnum) {
2502 assert(!IsAngleBracket || !IsEnum);
2503 bool HasError =
false;
2508 if (Style.isCSharp() && FormatTok->is(TT_FatArrow) &&
2509 tryToParseChildBlock()) {
2512 if (Style.isJavaScript()) {
2513 if (FormatTok->is(Keywords.kw_function)) {
2514 tryToParseJSFunction();
2517 if (FormatTok->is(tok::l_brace)) {
2519 if (tryToParseBracedList())
2524 if (FormatTok->is(IsAngleBracket ? tok::greater : tok::r_brace)) {
2526 FormatTok->setBlockKind(BK_Block);
2527 if (!Style.AllowShortEnumsOnASingleLine)
2533 switch (FormatTok->Tok.getKind()) {
2535 if (Style.isCSharp())
2544 if (Style.isJavaScript()) {
2545 if (FormatTok->is(tok::l_brace))
2553 FormatTok->setBlockKind(BK_BracedInit);
2554 if (!IsAngleBracket) {
2555 auto *Prev = FormatTok->Previous;
2556 if (Prev && Prev->is(tok::greater))
2557 Prev->setFinalizedType(TT_TemplateCloser);
2565 parseBracedList(
true);
2572 if (Style.isJavaScript()) {
2583 if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
2586 case tok::kw_requires:
2587 parseRequiresExpression();
2602bool UnwrappedLineParser::parseParens(TokenType AmpAmpTokenType,
2604 assert(FormatTok->is(tok::l_paren) &&
"'(' expected.");
2605 auto *LParen = FormatTok;
2606 auto *Prev = FormatTok->Previous;
2607 bool SeenComma =
false;
2608 bool SeenEqual =
false;
2609 bool MightBeFoldExpr =
false;
2611 const bool MightBeStmtExpr = FormatTok->is(tok::l_brace);
2612 if (!InMacroCall && Prev && Prev->is(TT_FunctionLikeMacro))
2615 switch (FormatTok->Tok.getKind()) {
2617 if (parseParens(AmpAmpTokenType, InMacroCall))
2619 if (Style.isJava() && FormatTok->is(tok::l_brace))
2622 case tok::r_paren: {
2623 auto *RParen = FormatTok;
2626 auto OptionalParens = [&] {
2627 if (Style.RemoveParentheses == FormatStyle::RPS_Leave ||
2628 MightBeStmtExpr || MightBeFoldExpr || SeenComma || InMacroCall ||
2629 Line->InMacroBody || RParen->getPreviousNonComment() == LParen) {
2632 const bool DoubleParens =
2633 Prev->is(tok::l_paren) && FormatTok->is(tok::r_paren);
2635 const auto *PrevPrev = Prev->getPreviousNonComment();
2636 const bool Excluded =
2638 (PrevPrev->isOneOf(tok::kw___attribute, tok::kw_decltype) ||
2640 (PrevPrev->isOneOf(tok::kw_if, tok::kw_while) ||
2641 PrevPrev->endsSequence(tok::kw_constexpr, tok::kw_if))));
2645 const bool CommaSeparated =
2646 Prev->isOneOf(tok::l_paren, tok::comma) &&
2647 FormatTok->isOneOf(tok::comma, tok::r_paren);
2648 if (CommaSeparated &&
2650 !Prev->endsSequence(tok::comma, tok::ellipsis) &&
2652 !(FormatTok->is(tok::comma) &&
2653 Tokens->peekNextToken()->is(tok::ellipsis))) {
2656 const bool ReturnParens =
2657 Style.RemoveParentheses == FormatStyle::RPS_ReturnStatement &&
2658 ((NestedLambdas.empty() && !IsDecltypeAutoFunction) ||
2659 (!NestedLambdas.empty() && !NestedLambdas.back())) &&
2660 Prev->isOneOf(tok::kw_return, tok::kw_co_return) &&
2661 FormatTok->is(tok::semi);
2667 if (OptionalParens()) {
2668 LParen->Optional =
true;
2669 RParen->Optional =
true;
2670 }
else if (Prev->is(TT_TypenameMacro)) {
2671 LParen->setFinalizedType(TT_TypeDeclarationParen);
2672 RParen->setFinalizedType(TT_TypeDeclarationParen);
2673 }
else if (Prev->is(tok::greater) && RParen->Previous == LParen) {
2674 Prev->setFinalizedType(TT_TemplateCloser);
2675 }
else if (FormatTok->is(tok::l_brace) && Prev->is(tok::amp) &&
2677 FormatTok->setBlockKind(BK_BracedInit);
2689 if (!tryToParseBracedList())
2694 if (FormatTok->is(tok::l_brace)) {
2704 MightBeFoldExpr =
true;
2709 if (Style.isCSharp() && FormatTok->is(TT_FatArrow))
2710 tryToParseChildBlock();
2715 if (Style.isJavaScript())
2720 case tok::identifier:
2721 if (Style.isJavaScript() && (FormatTok->is(Keywords.kw_function)))
2722 tryToParseJSFunction();
2726 case tok::kw_switch:
2732 case tok::kw_requires:
2733 parseRequiresExpression();
2736 if (AmpAmpTokenType != TT_Unknown)
2737 FormatTok->setFinalizedType(AmpAmpTokenType);
2749 assert(FormatTok->is(tok::l_square) &&
"'[' expected.");
2750 if (tryToParseLambda())
2754 switch (FormatTok->Tok.getKind()) {
2767 case tok::l_brace: {
2768 if (!tryToParseBracedList())
2775 if (FormatTok->is(tok::l_brace)) {
2787void UnwrappedLineParser::keepAncestorBraces() {
2788 if (!Style.RemoveBracesLLVM)
2791 const int MaxNestingLevels = 2;
2792 const int Size = NestedTooDeep.size();
2793 if (Size >= MaxNestingLevels)
2794 NestedTooDeep[
Size - MaxNestingLevels] =
true;
2795 NestedTooDeep.push_back(
false);
2799 for (
const auto &
Token : llvm::reverse(
Line.Tokens))
2806void UnwrappedLineParser::parseUnbracedBody(
bool CheckEOF) {
2809 if (Style.InsertBraces && !
Line->InPPDirective && !
Line->Tokens.empty() &&
2810 PreprocessorDirectives.empty() && FormatTok->isNot(tok::semi)) {
2811 Tok = Style.BraceWrapping.AfterControlStatement == FormatStyle::BWACS_Never
2812 ? getLastNonComment(*
Line)
2815 if (
Tok->BraceCount < 0) {
2816 assert(
Tok->BraceCount == -1);
2819 Tok->BraceCount = -1;
2825 ++
Line->UnbracedBodyLevel;
2826 parseStructuralElement();
2827 --
Line->UnbracedBodyLevel;
2830 assert(!
Line->InPPDirective);
2832 for (
const auto &L : llvm::reverse(*CurrentLines)) {
2834 Tok = L.Tokens.back().Tok;
2842 if (CheckEOF &&
eof())
2852 assert(LeftBrace->
is(tok::l_brace));
2860 assert(RightBrace->
is(tok::r_brace));
2868void UnwrappedLineParser::handleAttributes() {
2870 if (FormatTok->isAttribute())
2872 else if (FormatTok->is(tok::l_square))
2873 handleCppAttributes();
2876bool UnwrappedLineParser::handleCppAttributes() {
2878 assert(FormatTok->is(tok::l_square));
2879 if (!tryToParseSimpleAttribute())
2886bool UnwrappedLineParser::isBlockBegin(
const FormatToken &
Tok)
const {
2889 return Style.isVerilog() ? Keywords.isVerilogBegin(
Tok)
2890 :
Tok.
is(tok::l_brace);
2893FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
2895 bool IsVerilogAssert) {
2896 assert((FormatTok->is(tok::kw_if) ||
2897 (Style.isVerilog() &&
2898 FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
2899 Keywords.kw_assume, Keywords.kw_cover))) &&
2903 if (IsVerilogAssert) {
2905 if (FormatTok->is(Keywords.kw_verilogHash)) {
2907 if (FormatTok->is(tok::numeric_constant))
2909 }
else if (FormatTok->isOneOf(Keywords.kw_final, Keywords.kw_property,
2910 Keywords.kw_sequence)) {
2916 if (Style.isTableGen()) {
2917 while (!
eof() && FormatTok->isNot(Keywords.kw_then)) {
2924 if (FormatTok->is(tok::exclaim))
2927 bool KeepIfBraces =
true;
2928 if (FormatTok->is(tok::kw_consteval)) {
2931 KeepIfBraces = !Style.RemoveBracesLLVM || KeepBraces;
2932 if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
2934 if (FormatTok->is(tok::l_paren)) {
2935 FormatTok->setFinalizedType(TT_ConditionLParen);
2941 if (IsVerilogAssert && FormatTok->is(tok::semi)) {
2947 bool NeedsUnwrappedLine =
false;
2948 keepAncestorBraces();
2951 IfStmtKind IfBlockKind = IfStmtKind::NotIf;
2953 if (isBlockBegin(*FormatTok)) {
2954 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
2955 IfLeftBrace = FormatTok;
2956 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
2957 parseBlock(
false, 1u,
2958 true, KeepIfBraces, &IfBlockKind);
2959 setPreviousRBraceType(TT_ControlStatementRBrace);
2960 if (Style.BraceWrapping.BeforeElse)
2963 NeedsUnwrappedLine =
true;
2964 }
else if (IsVerilogAssert && FormatTok->is(tok::kw_else)) {
2967 parseUnbracedBody();
2970 if (Style.RemoveBracesLLVM) {
2971 assert(!NestedTooDeep.empty());
2972 KeepIfBraces = KeepIfBraces ||
2973 (IfLeftBrace && !IfLeftBrace->MatchingParen) ||
2974 NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly ||
2975 IfBlockKind == IfStmtKind::IfElseIf;
2978 bool KeepElseBraces = KeepIfBraces;
2980 IfStmtKind
Kind = IfStmtKind::IfOnly;
2982 if (FormatTok->is(tok::kw_else)) {
2983 if (Style.RemoveBracesLLVM) {
2984 NestedTooDeep.back() =
false;
2985 Kind = IfStmtKind::IfElse;
2989 if (isBlockBegin(*FormatTok)) {
2990 const bool FollowedByIf = Tokens->peekNextToken()->is(tok::kw_if);
2991 FormatTok->setFinalizedType(TT_ElseLBrace);
2992 ElseLeftBrace = FormatTok;
2993 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
2994 IfStmtKind ElseBlockKind = IfStmtKind::NotIf;
2996 parseBlock(
false, 1u,
2997 true, KeepElseBraces, &ElseBlockKind);
2998 setPreviousRBraceType(TT_ElseRBrace);
2999 if (FormatTok->is(tok::kw_else)) {
3000 KeepElseBraces = KeepElseBraces ||
3001 ElseBlockKind == IfStmtKind::IfOnly ||
3002 ElseBlockKind == IfStmtKind::IfElseIf;
3003 }
else if (FollowedByIf && IfLBrace && !IfLBrace->Optional) {
3004 KeepElseBraces =
true;
3005 assert(ElseLeftBrace->MatchingParen);
3009 }
else if (!IsVerilogAssert && FormatTok->is(tok::kw_if)) {
3012 const bool IsPrecededByComment =
Previous->is(tok::comment);
3013 if (IsPrecededByComment) {
3017 bool TooDeep =
true;
3018 if (Style.RemoveBracesLLVM) {
3019 Kind = IfStmtKind::IfElseIf;
3020 TooDeep = NestedTooDeep.pop_back_val();
3022 ElseLeftBrace = parseIfThenElse(
nullptr, KeepIfBraces);
3023 if (Style.RemoveBracesLLVM)
3024 NestedTooDeep.push_back(TooDeep);
3025 if (IsPrecededByComment)
3028 parseUnbracedBody(
true);
3031 KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse;
3032 if (NeedsUnwrappedLine)
3036 if (!Style.RemoveBracesLLVM)
3039 assert(!NestedTooDeep.empty());
3040 KeepElseBraces = KeepElseBraces ||
3041 (ElseLeftBrace && !ElseLeftBrace->MatchingParen) ||
3042 NestedTooDeep.back();
3044 NestedTooDeep.pop_back();
3046 if (!KeepIfBraces && !KeepElseBraces) {
3049 }
else if (IfLeftBrace) {
3050 FormatToken *IfRightBrace = IfLeftBrace->MatchingParen;
3052 assert(IfRightBrace->MatchingParen == IfLeftBrace);
3053 assert(!IfLeftBrace->Optional);
3054 assert(!IfRightBrace->Optional);
3055 IfLeftBrace->MatchingParen =
nullptr;
3056 IfRightBrace->MatchingParen =
nullptr;
3066void UnwrappedLineParser::parseTryCatch() {
3067 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) &&
"'try' expected");
3069 bool NeedsUnwrappedLine =
false;
3070 bool HasCtorInitializer =
false;
3071 if (FormatTok->is(tok::colon)) {
3072 auto *Colon = FormatTok;
3075 if (FormatTok->is(tok::identifier)) {
3076 HasCtorInitializer =
true;
3077 Colon->setFinalizedType(TT_CtorInitializerColon);
3082 while (FormatTok->is(tok::comma))
3085 while (FormatTok->is(tok::identifier)) {
3087 if (FormatTok->is(tok::l_paren)) {
3089 }
else if (FormatTok->is(tok::l_brace)) {
3096 while (FormatTok->is(tok::comma))
3101 if (Style.isJava() && FormatTok->is(tok::l_paren))
3104 keepAncestorBraces();
3106 if (FormatTok->is(tok::l_brace)) {
3107 if (HasCtorInitializer)
3108 FormatTok->setFinalizedType(TT_FunctionLBrace);
3109 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3111 if (Style.BraceWrapping.BeforeCatch)
3114 NeedsUnwrappedLine =
true;
3115 }
else if (FormatTok->isNot(tok::kw_catch)) {
3121 parseStructuralElement();
3124 for (
bool SeenCatch =
false;;) {
3125 if (FormatTok->is(tok::at))
3127 if (FormatTok->isNoneOf(tok::kw_catch, Keywords.kw___except,
3128 tok::kw___finally, tok::objc_catch,
3129 tok::objc_finally) &&
3130 !((Style.isJava() || Style.isJavaScript()) &&
3131 FormatTok->is(Keywords.kw_finally))) {
3134 if (FormatTok->is(tok::kw_catch))
3137 while (FormatTok->isNot(tok::l_brace)) {
3138 if (FormatTok->is(tok::l_paren)) {
3142 if (FormatTok->isOneOf(tok::semi, tok::r_brace) ||
eof()) {
3143 if (Style.RemoveBracesLLVM)
3144 NestedTooDeep.pop_back();
3150 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3153 NeedsUnwrappedLine =
false;
3154 Line->MustBeDeclaration =
false;
3155 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3157 if (Style.BraceWrapping.BeforeCatch)
3160 NeedsUnwrappedLine =
true;
3163 if (Style.RemoveBracesLLVM)
3164 NestedTooDeep.pop_back();
3166 if (NeedsUnwrappedLine)
3170void UnwrappedLineParser::parseNamespaceOrExportBlock(
unsigned AddLevels) {
3171 bool ManageWhitesmithsBraces =
3172 AddLevels == 0u && Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
3176 if (ManageWhitesmithsBraces)
3181 parseBlock(
true, AddLevels,
true,
3182 true,
nullptr, ManageWhitesmithsBraces);
3184 addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep);
3186 if (ManageWhitesmithsBraces)
3190void UnwrappedLineParser::parseNamespace() {
3191 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
3192 "'namespace' expected");
3196 if (InitialToken.is(TT_NamespaceMacro)) {
3199 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
3200 tok::l_square, tok::period, tok::l_paren) ||
3201 (Style.isCSharp() && FormatTok->is(tok::kw_union))) {
3202 if (FormatTok->is(tok::l_square))
3204 else if (FormatTok->is(tok::l_paren))
3210 if (FormatTok->is(tok::l_brace)) {
3211 FormatTok->setFinalizedType(TT_NamespaceLBrace);
3214 Tokens->peekNextToken()->is(tok::r_brace))) {
3218 unsigned AddLevels =
3219 Style.NamespaceIndentation == FormatStyle::NI_All ||
3220 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
3221 DeclarationScopeStack.size() > 1)
3224 parseNamespaceOrExportBlock(AddLevels);
3229void UnwrappedLineParser::parseCppExportBlock() {
3230 parseNamespaceOrExportBlock(Style.IndentExportBlock ? 1 : 0);
3233void UnwrappedLineParser::parseNew() {
3234 assert(FormatTok->is(tok::kw_new) &&
"'new' expected");
3237 if (Style.isCSharp()) {
3240 if (FormatTok->is(tok::l_paren))
3244 if (FormatTok->is(tok::l_brace))
3247 if (FormatTok->isOneOf(tok::semi, tok::comma))
3254 if (!Style.isJava())
3260 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
3264 if (FormatTok->is(tok::l_paren)) {
3268 if (FormatTok->is(tok::l_brace))
3276void UnwrappedLineParser::parseLoopBody(
bool KeepBraces,
bool WrapRightBrace) {
3277 keepAncestorBraces();
3279 if (isBlockBegin(*FormatTok)) {
3280 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3282 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3283 parseBlock(
false, 1u,
3285 setPreviousRBraceType(TT_ControlStatementRBrace);
3287 assert(!NestedTooDeep.empty());
3288 if (!NestedTooDeep.back())
3294 parseUnbracedBody();
3298 NestedTooDeep.pop_back();
3301void UnwrappedLineParser::parseForOrWhileLoop(
bool HasParens) {
3302 assert((FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) ||
3303 (Style.isVerilog() &&
3304 FormatTok->isOneOf(Keywords.kw_always, Keywords.kw_always_comb,
3305 Keywords.kw_always_ff, Keywords.kw_always_latch,
3306 Keywords.kw_final, Keywords.kw_initial,
3307 Keywords.kw_foreach, Keywords.kw_forever,
3308 Keywords.kw_repeat))) &&
3309 "'for', 'while' or foreach macro expected");
3310 const bool KeepBraces = !Style.RemoveBracesLLVM ||
3311 FormatTok->isNoneOf(tok::kw_for, tok::kw_while);
3315 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
3317 if (IsCpp && FormatTok->is(tok::kw_co_await))
3319 if (HasParens && FormatTok->is(tok::l_paren)) {
3323 if (Style.isVerilog())
3324 FormatTok->setFinalizedType(TT_ConditionLParen);
3328 if (Style.isVerilog()) {
3330 parseVerilogSensitivityList();
3331 }
else if (Style.AllowShortLoopsOnASingleLine && FormatTok->is(tok::semi) &&
3332 Tokens->getPreviousToken()->is(tok::r_paren)) {
3339 parseLoopBody(KeepBraces,
true);
3342void UnwrappedLineParser::parseDoWhile() {
3343 assert(FormatTok->is(tok::kw_do) &&
"'do' expected");
3346 parseLoopBody(
true, Style.BraceWrapping.BeforeWhile);
3349 if (FormatTok->isNot(tok::kw_while)) {
3354 FormatTok->setFinalizedType(TT_DoWhile);
3358 if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)
3362 parseStructuralElement();
3365void UnwrappedLineParser::parseLabel(
3366 FormatStyle::IndentGotoLabelStyle IndentGotoLabels) {
3368 unsigned OldLineLevel =
Line->Level;
3370 switch (IndentGotoLabels) {
3371 case FormatStyle::IGLS_NoIndent:
3374 case FormatStyle::IGLS_OuterIndent:
3375 if (
Line->Level > 1 || (!
Line->InPPDirective &&
Line->Level > 0))
3378 case FormatStyle::IGLS_HalfIndent:
3379 case FormatStyle::IGLS_InnerIndent:
3383 if (!Style.IndentCaseBlocks && CommentsBeforeNextToken.empty() &&
3384 FormatTok->is(tok::l_brace)) {
3386 CompoundStatementIndenter Indenter(
this,
Line->Level,
3387 Style.BraceWrapping.AfterCaseLabel,
3388 Style.BraceWrapping.IndentBraces);
3390 if (FormatTok->is(tok::kw_break)) {
3391 if (Style.BraceWrapping.AfterControlStatement ==
3392 FormatStyle::BWACS_Always) {
3394 if (!Style.IndentCaseBlocks &&
3395 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) {
3399 parseStructuralElement();
3403 if (FormatTok->is(tok::semi))
3407 Line->Level = OldLineLevel;
3408 if (FormatTok->isNot(tok::l_brace)) {
3409 parseStructuralElement();
3414void UnwrappedLineParser::parseCaseLabel() {
3415 assert(FormatTok->is(tok::kw_case) &&
"'case' expected");
3416 auto *Case = FormatTok;
3421 if (FormatTok->is(tok::colon)) {
3422 FormatTok->setFinalizedType(TT_CaseLabelColon);
3425 if (Style.isJava() && FormatTok->is(tok::arrow)) {
3426 FormatTok->setFinalizedType(TT_CaseLabelArrow);
3427 Case->setFinalizedType(TT_SwitchExpressionLabel);
3434void UnwrappedLineParser::parseSwitch(
bool IsExpr) {
3435 assert(FormatTok->is(tok::kw_switch) &&
"'switch' expected");
3437 if (FormatTok->is(tok::l_paren))
3440 keepAncestorBraces();
3442 if (FormatTok->is(tok::l_brace)) {
3443 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3444 FormatTok->setFinalizedType(IsExpr ? TT_SwitchExpressionLBrace
3445 : TT_ControlStatementLBrace);
3450 setPreviousRBraceType(TT_ControlStatementRBrace);
3456 parseStructuralElement();
3460 if (Style.RemoveBracesLLVM)
3461 NestedTooDeep.pop_back();
3464void UnwrappedLineParser::parseAccessSpecifier() {
3467 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
3470 if (FormatTok->is(tok::colon))
3478bool UnwrappedLineParser::parseRequires(
bool SeenEqual) {
3479 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3483 switch (Tokens->peekNextToken(
true)->Tok.getKind()) {
3486 parseRequiresExpression();
3493 parseRequiresClause();
3504 auto *PreviousNonComment = FormatTok->getPreviousNonComment();
3506 if (!PreviousNonComment ||
3507 PreviousNonComment->is(TT_RequiresExpressionLBrace)) {
3510 parseRequiresClause();
3514 switch (PreviousNonComment->Tok.getKind()) {
3517 case tok::kw_noexcept:
3522 parseRequiresClause();
3531 auto PrevPrev = PreviousNonComment->getPreviousNonComment();
3532 if ((PrevPrev && PrevPrev->is(tok::kw_const)) || !SeenEqual) {
3533 parseRequiresClause();
3539 if (PreviousNonComment->isTypeOrIdentifier(LangOpts)) {
3541 parseRequiresClause();
3545 parseRequiresExpression();
3555 unsigned StoredPosition = Tokens->getPosition();
3558 auto PeekNext = [&Lookahead, &NextToken,
this] {
3560 NextToken = Tokens->getNextToken();
3563 bool FoundType =
false;
3564 bool LastWasColonColon =
false;
3567 for (; Lookahead < 50; PeekNext()) {
3568 switch (NextToken->Tok.getKind()) {
3569 case tok::kw_volatile:
3572 if (OpenAngles == 0) {
3573 FormatTok = Tokens->setPosition(StoredPosition);
3574 parseRequiresExpression();
3582 case tok::coloncolon:
3583 LastWasColonColon =
true;
3585 case tok::kw_decltype:
3586 case tok::identifier:
3587 if (FoundType && !LastWasColonColon && OpenAngles == 0) {
3588 FormatTok = Tokens->setPosition(StoredPosition);
3589 parseRequiresExpression();
3593 LastWasColonColon =
false;
3602 if (NextToken->isTypeName(LangOpts)) {
3603 FormatTok = Tokens->setPosition(StoredPosition);
3604 parseRequiresExpression();
3611 FormatTok = Tokens->setPosition(StoredPosition);
3612 parseRequiresClause();
3621void UnwrappedLineParser::parseRequiresClause() {
3622 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3627 bool InRequiresExpression =
3628 !FormatTok->Previous ||
3629 FormatTok->Previous->is(TT_RequiresExpressionLBrace);
3631 FormatTok->setFinalizedType(InRequiresExpression
3632 ? TT_RequiresClauseInARequiresExpression
3633 : TT_RequiresClause);
3638 parseConstraintExpression();
3640 if (!InRequiresExpression && FormatTok->Previous)
3641 FormatTok->Previous->ClosesRequiresClause =
true;
3649void UnwrappedLineParser::parseRequiresExpression() {
3650 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3652 FormatTok->setFinalizedType(TT_RequiresExpression);
3655 if (FormatTok->is(tok::l_paren)) {
3656 FormatTok->setFinalizedType(TT_RequiresExpressionLParen);
3660 if (FormatTok->is(tok::l_brace)) {
3661 FormatTok->setFinalizedType(TT_RequiresExpressionLBrace);
3670void UnwrappedLineParser::parseConstraintExpression() {
3677 bool LambdaNextTimeAllowed =
true;
3687 bool TopLevelParensAllowed =
true;
3690 bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed,
false);
3692 switch (FormatTok->Tok.getKind()) {
3693 case tok::kw_requires:
3694 parseRequiresExpression();
3698 if (!TopLevelParensAllowed)
3700 parseParens(TT_BinaryOperator);
3701 TopLevelParensAllowed =
false;
3705 if (!LambdaThisTimeAllowed || !tryToParseLambda())
3712 case tok::kw_struct:
3722 FormatTok->setFinalizedType(TT_BinaryOperator);
3724 LambdaNextTimeAllowed =
true;
3725 TopLevelParensAllowed =
true;
3730 LambdaNextTimeAllowed = LambdaThisTimeAllowed;
3734 case tok::kw_sizeof:
3736 case tok::greaterequal:
3737 case tok::greatergreater:
3739 case tok::lessequal:
3741 case tok::equalequal:
3743 case tok::exclaimequal:
3748 LambdaNextTimeAllowed =
true;
3749 TopLevelParensAllowed =
true;
3754 case tok::numeric_constant:
3755 case tok::coloncolon:
3758 TopLevelParensAllowed =
false;
3763 case tok::kw_static_cast:
3764 case tok::kw_const_cast:
3765 case tok::kw_reinterpret_cast:
3766 case tok::kw_dynamic_cast:
3768 if (FormatTok->isNot(tok::less))
3772 parseBracedList(
true);
3776 if (!FormatTok->Tok.getIdentifierInfo()) {
3786 assert(FormatTok->Previous);
3787 switch (FormatTok->Previous->Tok.getKind()) {
3788 case tok::coloncolon:
3792 case tok::kw_requires:
3801 if (FormatTok->is(tok::less)) {
3803 parseBracedList(
true);
3805 TopLevelParensAllowed =
false;
3811bool UnwrappedLineParser::parseEnum() {
3815 if (FormatTok->is(tok::kw_enum))
3821 if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question))
3825 if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal))
3830 if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
3832 while (FormatTok->is(tok::l_square))
3833 if (!handleCppAttributes())
3837 while (FormatTok->Tok.getIdentifierInfo() ||
3838 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
3839 tok::greater, tok::comma, tok::question,
3841 if (Style.isVerilog()) {
3842 FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
3845 while (FormatTok->is(tok::l_square))
3851 if (FormatTok->is(tok::l_paren))
3853 if (FormatTok->is(tok::identifier)) {
3857 if (IsCpp && FormatTok->is(tok::identifier))
3863 if (FormatTok->isNot(tok::l_brace))
3865 FormatTok->setFinalizedType(TT_EnumLBrace);
3866 FormatTok->setBlockKind(BK_Block);
3868 if (Style.isJava()) {
3870 parseJavaEnumBody();
3873 if (Style.Language == FormatStyle::LK_Proto) {
3878 if (!Style.AllowShortEnumsOnASingleLine &&
3880 Tokens->peekNextToken()->is(tok::r_brace))) {
3885 if (!Style.AllowShortEnumsOnASingleLine) {
3889 bool HasError = !parseBracedList(
false,
true);
3890 if (!Style.AllowShortEnumsOnASingleLine)
3893 if (FormatTok->is(tok::semi))
3897 setPreviousRBraceType(TT_EnumRBrace);
3905bool UnwrappedLineParser::parseStructLike() {
3910 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp()) {
3911 if (FormatTok->is(tok::semi))
3922class ScopedTokenPosition {
3923 unsigned StoredPosition;
3924 FormatTokenSource *Tokens;
3927 ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) {
3928 assert(Tokens &&
"Tokens expected to not be null");
3929 StoredPosition = Tokens->getPosition();
3932 ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); }
3938bool UnwrappedLineParser::tryToParseSimpleAttribute() {
3939 ScopedTokenPosition AutoPosition(Tokens);
3947 if (
Tok->
is(tok::r_square))
3949 Tok = Tokens->getNextToken();
3951 if (
Tok->
is(tok::eof))
3953 Tok = Tokens->getNextToken();
3956 Tok = Tokens->getNextToken();
3957 if (
Tok->
is(tok::semi))
3962void UnwrappedLineParser::parseJavaEnumBody() {
3963 assert(FormatTok->is(tok::l_brace));
3969 unsigned StoredPosition = Tokens->getPosition();
3970 bool IsSimple =
true;
3973 if (
Tok->
is(tok::r_brace))
3981 Tok = Tokens->getNextToken();
3983 FormatTok = Tokens->setPosition(StoredPosition);
4000 if (FormatTok->is(tok::l_brace)) {
4002 parseBlock(
true, 1u,
4004 }
else if (FormatTok->is(tok::l_paren)) {
4006 }
else if (FormatTok->is(tok::comma)) {
4009 }
else if (FormatTok->is(tok::semi)) {
4013 }
else if (FormatTok->is(tok::r_brace)) {
4022 parseLevel(OpeningBrace);
4028void UnwrappedLineParser::parseRecord(
bool ParseAsExpr,
bool IsJavaRecord) {
4029 assert(!IsJavaRecord || FormatTok->is(Keywords.kw_record));
4034 IsJavaRecord && FormatTok->is(tok::identifier) ? FormatTok :
nullptr;
4035 bool IsDerived =
false;
4037 return Tok->
is(tok::identifier) &&
Tok->TokenText !=
Tok->TokenText.upper();
4041 bool JSPastExtendsOrImplements =
false;
4045 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
4046 tok::kw_alignas, tok::l_square) ||
4047 FormatTok->isAttribute() ||
4048 ((Style.isJava() || Style.isJavaScript()) &&
4049 FormatTok->isOneOf(tok::period, tok::comma))) {
4050 if (Style.isJavaScript() &&
4051 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
4052 JSPastExtendsOrImplements =
true;
4057 if (FormatTok->is(tok::l_brace)) {
4058 tryToParseBracedList();
4062 if (FormatTok->is(tok::l_square) && handleCppAttributes())
4066 switch (FormatTok->Tok.getKind()) {
4069 if (IsJavaRecord || !IsNonMacroIdentifier(
Previous) ||
4071 Previous->Previous == &InitialToken) {
4075 case tok::coloncolon:
4079 if (JSPastExtendsOrImplements || ClassName ||
4090 auto IsListInitialization = [&] {
4091 if (!ClassName || IsDerived || JSPastExtendsOrImplements)
4093 assert(FormatTok->is(tok::l_brace));
4094 const auto *Prev = FormatTok->getPreviousNonComment();
4096 return Prev != ClassName && Prev->is(tok::identifier) &&
4097 Prev->isNot(Keywords.kw_final) && tryToParseBracedList();
4100 if (FormatTok->isOneOf(tok::colon, tok::less)) {
4101 int AngleNestingLevel = 0;
4103 if (FormatTok->is(tok::less))
4104 ++AngleNestingLevel;
4105 else if (FormatTok->is(tok::greater))
4106 --AngleNestingLevel;
4108 if (AngleNestingLevel == 0) {
4109 if (FormatTok->is(tok::colon)) {
4111 }
else if (!IsDerived && FormatTok->is(tok::identifier) &&
4112 FormatTok->Previous->is(tok::coloncolon)) {
4113 ClassName = FormatTok;
4114 }
else if (FormatTok->is(tok::l_paren) &&
4115 IsNonMacroIdentifier(FormatTok->Previous)) {
4119 if (FormatTok->is(tok::l_brace)) {
4120 if (AngleNestingLevel == 0 && IsListInitialization())
4122 calculateBraceTypes(
true);
4123 if (!tryToParseBracedList())
4126 if (FormatTok->is(tok::l_square)) {
4129 !
Previous->isTypeOrIdentifier(LangOpts))) {
4132 if (!tryToParseLambda())
4139 if (FormatTok->is(tok::semi))
4141 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
4144 parseCSharpGenericTypeConstraint();
4151 auto GetBraceTypes =
4152 [](
const FormatToken &RecordTok) -> std::pair<TokenType, TokenType> {
4153 switch (RecordTok.Tok.getKind()) {
4155 return {TT_ClassLBrace, TT_ClassRBrace};
4156 case tok::kw_struct:
4157 return {TT_StructLBrace, TT_StructRBrace};
4159 return {TT_UnionLBrace, TT_UnionRBrace};
4162 return {TT_RecordLBrace, TT_RecordRBrace};
4165 if (FormatTok->is(tok::l_brace)) {
4166 if (IsListInitialization())
4169 ClassName->setFinalizedType(TT_ClassHeadName);
4170 auto [OpenBraceType, ClosingBraceType] = GetBraceTypes(InitialToken);
4171 FormatTok->setFinalizedType(OpenBraceType);
4176 Tokens->peekNextToken()->is(tok::r_brace),
4181 unsigned AddLevels = Style.IndentAccessModifiers ? 2u : 1u;
4182 parseBlock(
true, AddLevels,
false);
4184 setPreviousRBraceType(ClosingBraceType);
4191void UnwrappedLineParser::parseObjCMethod() {
4192 assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) &&
4193 "'(' or identifier expected.");
4195 if (FormatTok->is(tok::semi)) {
4199 }
else if (FormatTok->is(tok::l_brace)) {
4200 if (Style.BraceWrapping.AfterFunction)
4211void UnwrappedLineParser::parseObjCProtocolList() {
4212 assert(FormatTok->is(tok::less) &&
"'<' expected.");
4216 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4218 }
while (!
eof() && FormatTok->isNot(tok::greater));
4222void UnwrappedLineParser::parseObjCUntilAtEnd() {
4224 if (FormatTok->is(tok::objc_end)) {
4229 if (FormatTok->is(tok::l_brace)) {
4233 }
else if (FormatTok->is(tok::r_brace)) {
4237 }
else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
4241 parseStructuralElement();
4246void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
4247 assert(FormatTok->isOneOf(tok::objc_interface, tok::objc_implementation));
4253 if (FormatTok->is(tok::less))
4254 parseObjCLightweightGenerics();
4255 if (FormatTok->is(tok::colon)) {
4259 if (FormatTok->is(tok::less))
4260 parseObjCLightweightGenerics();
4261 }
else if (FormatTok->is(tok::l_paren)) {
4266 if (FormatTok->is(tok::less))
4267 parseObjCProtocolList();
4269 if (FormatTok->is(tok::l_brace)) {
4270 if (Style.BraceWrapping.AfterObjCDeclaration)
4279 parseObjCUntilAtEnd();
4282void UnwrappedLineParser::parseObjCLightweightGenerics() {
4283 assert(FormatTok->is(tok::less));
4291 unsigned NumOpenAngles = 1;
4295 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4297 if (FormatTok->is(tok::less)) {
4299 }
else if (FormatTok->is(tok::greater)) {
4300 assert(NumOpenAngles > 0 &&
"'>' makes NumOpenAngles negative");
4303 }
while (!
eof() && NumOpenAngles != 0);
4309bool UnwrappedLineParser::parseObjCProtocol() {
4310 assert(FormatTok->is(tok::objc_protocol));
4313 if (FormatTok->is(tok::l_paren)) {
4325 if (FormatTok->is(tok::less))
4326 parseObjCProtocolList();
4329 if (FormatTok->is(tok::semi)) {
4336 parseObjCUntilAtEnd();
4340void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
4341 bool IsImport = FormatTok->is(Keywords.kw_import);
4342 assert(IsImport || FormatTok->is(tok::kw_export));
4346 if (FormatTok->is(tok::kw_default))
4352 if (FormatTok->is(Keywords.kw_async))
4354 if (FormatTok->is(Keywords.kw_function)) {
4363 if (!IsImport && FormatTok->isNoneOf(tok::l_brace, tok::star) &&
4364 !FormatTok->isStringLiteral() &&
4365 !(FormatTok->is(Keywords.kw_type) &&
4366 Tokens->peekNextToken()->isOneOf(tok::l_brace, tok::star))) {
4371 if (FormatTok->is(tok::semi))
4373 if (
Line->Tokens.empty()) {
4378 if (FormatTok->is(tok::l_brace)) {
4379 FormatTok->setBlockKind(BK_Block);
4388void UnwrappedLineParser::parseStatementMacro() {
4390 if (FormatTok->is(tok::l_paren))
4392 if (FormatTok->is(tok::semi))
4397void UnwrappedLineParser::parseVerilogHierarchyIdentifier() {
4400 if (FormatTok->isOneOf(tok::star, tok::period, tok::periodstar,
4401 tok::coloncolon, tok::hash) ||
4402 Keywords.isVerilogIdentifier(*FormatTok)) {
4404 }
else if (FormatTok->is(tok::l_square)) {
4412void UnwrappedLineParser::parseVerilogSensitivityList() {
4413 if (FormatTok->isNot(tok::at))
4417 if (FormatTok->is(tok::at))
4419 switch (FormatTok->Tok.getKind()) {
4427 parseVerilogHierarchyIdentifier();
4432unsigned UnwrappedLineParser::parseVerilogHierarchyHeader() {
4433 unsigned AddLevels = 0;
4435 if (FormatTok->is(Keywords.kw_clocking)) {
4437 if (Keywords.isVerilogIdentifier(*FormatTok))
4439 parseVerilogSensitivityList();
4440 if (FormatTok->is(tok::semi))
4442 }
else if (FormatTok->isOneOf(tok::kw_case, Keywords.kw_casex,
4443 Keywords.kw_casez, Keywords.kw_randcase,
4444 Keywords.kw_randsequence)) {
4445 if (Style.IndentCaseLabels)
4448 if (FormatTok->is(tok::l_paren)) {
4449 FormatTok->setFinalizedType(TT_ConditionLParen);
4452 if (FormatTok->isOneOf(Keywords.kw_inside, Keywords.kw_matches))
4461 if (FormatTok->is(tok::l_square)) {
4462 auto Prev = FormatTok->getPreviousNonComment();
4463 if (Prev && Keywords.isVerilogIdentifier(*Prev))
4464 Prev->setFinalizedType(TT_VerilogDimensionedTypeName);
4466 }
else if (Keywords.isVerilogIdentifier(*FormatTok) ||
4467 FormatTok->isOneOf(tok::hash, tok::hashhash, tok::coloncolon,
4468 Keywords.kw_automatic, tok::kw_static)) {
4475 auto NewLine = [
this]() {
4477 Line->IsContinuation =
true;
4481 while (FormatTok->is(Keywords.kw_import)) {
4484 parseVerilogHierarchyIdentifier();
4485 if (FormatTok->is(tok::semi))
4490 if (FormatTok->is(Keywords.kw_verilogHash)) {
4493 if (FormatTok->is(tok::l_paren)) {
4494 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4498 if (FormatTok->is(tok::l_paren)) {
4500 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4505 if (FormatTok->is(Keywords.kw_extends)) {
4508 parseVerilogHierarchyIdentifier();
4509 if (FormatTok->is(tok::l_paren))
4512 if (FormatTok->is(Keywords.kw_implements)) {
4516 parseVerilogHierarchyIdentifier();
4517 }
while (FormatTok->is(tok::comma));
4521 if (FormatTok->is(tok::at)) {
4523 parseVerilogSensitivityList();
4526 if (FormatTok->is(tok::semi))
4534void UnwrappedLineParser::parseVerilogTable() {
4535 assert(FormatTok->is(Keywords.kw_table));
4539 auto InitialLevel =
Line->Level++;
4540 while (!
eof() && !Keywords.isVerilogEnd(*FormatTok)) {
4543 if (
Tok->
is(tok::semi))
4545 else if (
Tok->
isOneOf(tok::star, tok::colon, tok::question, tok::minus))
4546 Tok->setFinalizedType(TT_VerilogTableItem);
4548 Line->Level = InitialLevel;
4553void UnwrappedLineParser::parseVerilogCaseLabel() {
4559 auto OrigLevel =
Line->Level;
4560 auto FirstLine = CurrentLines->size();
4561 if (
Line->Level == 0 || (
Line->InPPDirective &&
Line->Level <= 1))
4563 else if (!Style.IndentCaseBlocks && Keywords.isVerilogBegin(*FormatTok))
4565 parseStructuralElement();
4568 if (CurrentLines->size() > FirstLine)
4569 (*CurrentLines)[FirstLine].Level = OrigLevel;
4570 Line->Level = OrigLevel;
4573void UnwrappedLineParser::parseVerilogExtern() {
4575 FormatTok->isOneOf(tok::kw_extern, tok::kw_export, Keywords.kw_import));
4578 if (FormatTok->is(tok::string_literal))
4580 if (FormatTok->isOneOf(Keywords.kw_context, Keywords.kw_pure))
4582 if (Keywords.isVerilogIdentifier(*FormatTok))
4584 if (FormatTok->is(tok::equal))
4586 if (Keywords.isVerilogHierarchy(*FormatTok))
4587 parseVerilogHierarchyHeader();
4590bool UnwrappedLineParser::containsExpansion(
const UnwrappedLine &
Line)
const {
4591 for (
const auto &N :
Line.Tokens) {
4592 if (N.Tok->MacroCtx)
4594 for (
const UnwrappedLine &Child : N.Children)
4595 if (containsExpansion(Child))
4601void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) {
4602 if (
Line->Tokens.empty())
4605 if (!parsingPPDirective()) {
4606 llvm::dbgs() <<
"Adding unwrapped line:\n";
4607 printDebugInfo(*
Line);
4615 bool ClosesWhitesmithsBlock =
4616 Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex &&
4617 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
4622 if (!parsingPPDirective() && !InExpansion && containsExpansion(*
Line)) {
4624 Reconstruct.emplace(
Line->Level, Unexpanded);
4625 Reconstruct->addLine(*
Line);
4630 CurrentExpandedLines.push_back(std::move(*
Line));
4632 if (Reconstruct->finished()) {
4633 UnwrappedLine Reconstructed = std::move(*Reconstruct).takeResult();
4634 assert(!Reconstructed.Tokens.empty() &&
4635 "Reconstructed must at least contain the macro identifier.");
4636 assert(!parsingPPDirective());
4638 llvm::dbgs() <<
"Adding unexpanded line:\n";
4639 printDebugInfo(Reconstructed);
4641 ExpandedLines[Reconstructed.Tokens.begin()->Tok] = CurrentExpandedLines;
4642 Lines.push_back(std::move(Reconstructed));
4643 CurrentExpandedLines.clear();
4644 Reconstruct.reset();
4649 assert(!Reconstruct || (CurrentLines != &Lines) || !PPStack.empty());
4650 CurrentLines->push_back(std::move(*
Line));
4652 Line->Tokens.clear();
4653 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
4654 Line->FirstStartColumn = 0;
4655 Line->IsContinuation =
false;
4656 Line->SeenDecltypeAuto =
false;
4658 if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove)
4660 if (!parsingPPDirective() && !PreprocessorDirectives.empty()) {
4661 CurrentLines->append(
4662 std::make_move_iterator(PreprocessorDirectives.begin()),
4663 std::make_move_iterator(PreprocessorDirectives.end()));
4664 PreprocessorDirectives.clear();
4667 FormatTok->Previous =
nullptr;
4670bool UnwrappedLineParser::eof()
const {
return FormatTok->is(tok::eof); }
4672bool UnwrappedLineParser::isOnNewLine(
const FormatToken &FormatTok) {
4673 return (
Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
4674 FormatTok.NewlinesBefore > 0;
4682 const llvm::Regex &CommentPragmasRegex) {
4683 if (
Line.Tokens.empty() || Style.ReflowComments != FormatStyle::RCS_Always)
4686 StringRef IndentContent = FormatTok.
TokenText;
4687 if (FormatTok.
TokenText.starts_with(
"//") ||
4688 FormatTok.
TokenText.starts_with(
"/*")) {
4689 IndentContent = FormatTok.
TokenText.substr(2);
4691 if (CommentPragmasRegex.match(IndentContent))
4766 if (PreviousToken && PreviousToken->
is(tok::l_brace) &&
4768 MinColumnToken = PreviousToken;
4771 PreviousToken = Node.
Tok;
4775 MinColumnToken = Node.
Tok;
4777 if (PreviousToken && PreviousToken->
is(tok::l_brace))
4778 MinColumnToken = PreviousToken;
4784void UnwrappedLineParser::flushComments(
bool NewlineBeforeNext) {
4785 bool JustComments =
Line->Tokens.empty();
4795 Tok->ContinuesLineCommentSection =
4796 continuesLineCommentSection(*
Tok, *
Line, Style, CommentPragmasRegex);
4797 if (isOnNewLine(*
Tok) && JustComments && !
Tok->ContinuesLineCommentSection)
4801 if (NewlineBeforeNext && JustComments)
4803 CommentsBeforeNextToken.clear();
4806void UnwrappedLineParser::nextToken(
int LevelDifference) {
4809 flushComments(isOnNewLine(*FormatTok));
4810 pushToken(FormatTok);
4812 if (!Style.isJavaScript())
4813 readToken(LevelDifference);
4815 readTokenWithJavaScriptASI();
4817 if (Style.isVerilog()) {
4824 if (Keywords.isVerilogEnd(*FormatTok))
4825 FormatTok->Tok.setKind(tok::r_brace);
4829void UnwrappedLineParser::distributeComments(
4849 if (Comments.empty())
4851 bool ShouldPushCommentsInCurrentLine =
true;
4852 bool HasTrailAlignedWithNextToken =
false;
4853 unsigned StartOfTrailAlignedWithNextToken = 0;
4856 for (
unsigned i = Comments.size() - 1; i > 0; --i) {
4858 HasTrailAlignedWithNextToken =
true;
4859 StartOfTrailAlignedWithNextToken = i;
4863 for (
unsigned i = 0, e = Comments.size(); i < e; ++i) {
4865 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
4866 FormatTok->ContinuesLineCommentSection =
false;
4869 *FormatTok, *
Line, Style, CommentPragmasRegex);
4871 if (!FormatTok->ContinuesLineCommentSection &&
4872 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
4873 ShouldPushCommentsInCurrentLine =
false;
4875 if (ShouldPushCommentsInCurrentLine)
4876 pushToken(FormatTok);
4878 CommentsBeforeNextToken.push_back(FormatTok);
4882void UnwrappedLineParser::readToken(
int LevelDifference) {
4884 bool PreviousWasComment =
false;
4885 bool FirstNonCommentOnLine =
false;
4887 FormatTok = Tokens->getNextToken();
4889 while (FormatTok->isOneOf(TT_ConflictStart, TT_ConflictEnd,
4890 TT_ConflictAlternative)) {
4891 if (FormatTok->is(TT_ConflictStart))
4892 conditionalCompilationStart(
false);
4893 else if (FormatTok->is(TT_ConflictAlternative))
4894 conditionalCompilationAlternative();
4895 else if (FormatTok->is(TT_ConflictEnd))
4896 conditionalCompilationEnd();
4897 FormatTok = Tokens->getNextToken();
4898 FormatTok->MustBreakBefore =
true;
4899 FormatTok->MustBreakBeforeFinalized =
true;
4902 auto IsFirstNonCommentOnLine = [](
bool FirstNonCommentOnLine,
4904 bool PreviousWasComment) {
4906 return Tok.HasUnescapedNewline ||
Tok.IsFirst;
4911 if (PreviousWasComment)
4912 return FirstNonCommentOnLine || IsFirstOnLine(
Tok);
4913 return IsFirstOnLine(
Tok);
4916 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
4917 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
4918 PreviousWasComment = FormatTok->is(tok::comment);
4920 while (!
Line->InPPDirective && FormatTok->is(tok::hash) &&
4921 FirstNonCommentOnLine) {
4924 const auto *
Next = Tokens->peekNextToken();
4925 if ((Style.isVerilog() && !Keywords.isVerilogPPDirective(*
Next)) ||
4926 (Style.isTableGen() &&
4927 Next->isNoneOf(tok::kw_else, tok::pp_define, tok::pp_ifdef,
4928 tok::pp_ifndef, tok::pp_endif))) {
4931 distributeComments(Comments, FormatTok);
4935 bool SwitchToPreprocessorLines = !
Line->Tokens.empty();
4936 ScopedLineState BlockState(*
this, SwitchToPreprocessorLines);
4937 assert((LevelDifference >= 0 ||
4938 static_cast<unsigned>(-LevelDifference) <=
Line->Level) &&
4939 "LevelDifference makes Line->Level negative");
4940 Line->Level += LevelDifference;
4944 if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash &&
4945 PPBranchLevel > 0) {
4946 Line->Level += PPBranchLevel;
4948 assert(
Line->Level >=
Line->UnbracedBodyLevel);
4949 Line->Level -=
Line->UnbracedBodyLevel;
4950 flushComments(isOnNewLine(*FormatTok));
4951 const bool IsEndIf = Tokens->peekNextToken()->is(tok::pp_endif);
4953 PreviousWasComment = FormatTok->is(tok::comment);
4954 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
4955 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
4958 if (IsEndIf && IncludeGuard == IG_Defined && PPBranchLevel == -1 &&
4959 getIncludeGuardState(Style.IndentPPDirectives) == IG_Inited &&
4961 (PreviousWasComment &&
4962 Tokens->peekNextToken(
true)->is(tok::eof)))) {
4963 IncludeGuard = IG_Found;
4967 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
4968 !
Line->InPPDirective) {
4972 if (FormatTok->is(tok::identifier) &&
4973 Macros.defined(FormatTok->TokenText) &&
4975 !
Line->InPPDirective) {
4977 unsigned Position = Tokens->getPosition();
4981 auto PreCall = std::move(
Line);
4982 Line.reset(
new UnwrappedLine);
4983 bool OldInExpansion = InExpansion;
4986 auto Args = parseMacroCall();
4987 InExpansion = OldInExpansion;
4988 assert(
Line->Tokens.front().Tok == ID);
4990 auto UnexpandedLine = std::move(
Line);
4992 Line = std::move(PreCall);
4995 llvm::dbgs() <<
"Macro call: " <<
ID->TokenText <<
"(";
4997 llvm::dbgs() <<
"(";
4998 for (
const auto &Arg : Args.value())
4999 for (
const auto &T : Arg)
5000 llvm::dbgs() << T->TokenText <<
" ";
5001 llvm::dbgs() <<
")";
5003 llvm::dbgs() <<
"\n";
5005 if (
Macros.objectLike(
ID->TokenText) && Args &&
5006 !
Macros.hasArity(
ID->TokenText, Args->size())) {
5012 LLVM_DEBUG(llvm::dbgs()
5013 <<
"Macro \"" <<
ID->TokenText
5014 <<
"\" not overloaded for arity " << Args->size()
5015 <<
"or not function-like, using object-like overload.");
5017 UnexpandedLine->Tokens.resize(1);
5018 Tokens->setPosition(Position);
5020 assert(!Args &&
Macros.objectLike(
ID->TokenText));
5022 if ((!Args &&
Macros.objectLike(
ID->TokenText)) ||
5023 (Args &&
Macros.hasArity(
ID->TokenText, Args->size()))) {
5026 Unexpanded[
ID] = std::move(UnexpandedLine);
5028 Macros.expand(ID, std::move(Args));
5029 if (!Expansion.empty())
5030 FormatTok = Tokens->insertTokens(Expansion);
5033 llvm::dbgs() <<
"Expanded: ";
5034 for (
const auto &T : Expansion)
5035 llvm::dbgs() << T->TokenText <<
" ";
5036 llvm::dbgs() <<
"\n";
5040 llvm::dbgs() <<
"Did not expand macro \"" <<
ID->TokenText
5041 <<
"\", because it was used ";
5043 llvm::dbgs() <<
"with " << Args->size();
5045 llvm::dbgs() <<
"without";
5046 llvm::dbgs() <<
" arguments, which doesn't match any definition.\n";
5048 Tokens->setPosition(Position);
5053 if (FormatTok->isNot(tok::comment)) {
5054 distributeComments(Comments, FormatTok);
5059 Comments.push_back(FormatTok);
5062 distributeComments(Comments,
nullptr);
5067template <
typename Iterator>
5068void pushTokens(Iterator Begin, Iterator End,
5070 for (
auto I = Begin; I != End; ++I) {
5071 Into.push_back(I->Tok);
5072 for (
const auto &Child : I->Children)
5073 pushTokens(Child.Tokens.begin(), Child.Tokens.end(), Into);
5078std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>
5079UnwrappedLineParser::parseMacroCall() {
5080 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>> Args;
5081 assert(
Line->Tokens.empty());
5083 if (FormatTok->isNot(tok::l_paren))
5085 unsigned Position = Tokens->getPosition();
5089 auto ArgStart = std::prev(
Line->Tokens.end());
5093 switch (FormatTok->Tok.getKind()) {
5098 case tok::r_paren: {
5104 Args->push_back({});
5105 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5114 Args->push_back({});
5115 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5117 ArgStart = std::prev(
Line->Tokens.end());
5125 Line->Tokens.resize(1);
5126 Tokens->setPosition(Position);
5132 Line->Tokens.push_back(UnwrappedLineNode(
Tok));
5133 if (AtEndOfPPLine) {
5134 auto &
Tok = *
Line->Tokens.back().Tok;
5135 Tok.MustBreakBefore =
true;
5136 Tok.MustBreakBeforeFinalized =
true;
5137 Tok.FirstAfterPPLine =
true;
5138 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.