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)) {
533 LBraceStack.push_back({
Tok, PrevTok});
536 if (LBraceStack.empty())
538 if (
auto *LBrace = LBraceStack.back().Tok; LBrace->is(
BK_Unknown)) {
539 bool ProbablyBracedList =
false;
540 if (Style.Language == FormatStyle::LK_Proto) {
541 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
542 }
else if (LBrace->isNot(TT_EnumLBrace)) {
545 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
546 NextTok->OriginalColumn == 0;
556 ProbablyBracedList = LBrace->is(TT_BracedListLBrace);
558 ProbablyBracedList = ProbablyBracedList ||
559 (Style.isJavaScript() &&
560 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
563 ProbablyBracedList ||
564 (IsCpp && (PrevTok->Tok.isLiteral() ||
565 NextTok->isOneOf(tok::l_paren, tok::arrow)));
572 ProbablyBracedList ||
573 NextTok->isOneOf(tok::comma, tok::period, tok::colon,
574 tok::r_paren, tok::r_square, tok::ellipsis);
579 ProbablyBracedList ||
580 (NextTok->is(tok::l_brace) && LBraceStack.back().PrevTok &&
581 LBraceStack.back().PrevTok->isOneOf(tok::identifier,
585 ProbablyBracedList ||
586 (NextTok->is(tok::identifier) &&
587 PrevTok->isNoneOf(tok::semi, tok::r_brace, tok::l_brace));
589 ProbablyBracedList = ProbablyBracedList ||
590 (NextTok->is(tok::semi) &&
591 (!ExpectClassBody || LBraceStack.size() != 1));
594 ProbablyBracedList ||
595 (NextTok->isBinaryOperator() && !NextIsObjCMethod);
597 if (!Style.isCSharp() && NextTok->is(tok::l_square)) {
600 NextTok = Tokens->getNextToken();
601 ProbablyBracedList = NextTok->isNot(tok::l_square);
605 if (IsCpp && Line->InMacroBody && PrevTok != FormatTok &&
606 !FormatTok->Previous && NextTok->is(tok::eof) &&
610 PrevTok->isNoneOf(tok::semi,
BK_Block, tok::colon)) {
611 ProbablyBracedList =
true;
615 Tok->setBlockKind(BlockKind);
616 LBrace->setBlockKind(BlockKind);
618 LBraceStack.pop_back();
620 case tok::identifier:
621 if (
Tok->isNot(TT_StatementMacro))
632 if (!LBraceStack.empty() && LBraceStack.back().Tok->is(
BK_Unknown))
633 LBraceStack.back().Tok->setBlockKind(
BK_Block);
641 }
while (
Tok->isNot(tok::eof) && !LBraceStack.empty());
644 for (
const auto &Entry : LBraceStack)
648 FormatTok = Tokens->setPosition(StoredPosition);
652void UnwrappedLineParser::setPreviousRBraceType(
TokenType Type) {
653 if (
auto Prev = FormatTok->getPreviousNonComment();
654 Prev && Prev->is(tok::r_brace)) {
655 Prev->setFinalizedType(
Type);
662 seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
665size_t UnwrappedLineParser::computePPHash()
const {
667 for (
const auto &i : PPStack) {
678bool UnwrappedLineParser::mightFitOnOneLine(
680 const auto ColumnLimit = Style.ColumnLimit;
681 if (ColumnLimit == 0)
684 auto &Tokens = ParsedLine.Tokens;
685 assert(!Tokens.empty());
687 const auto *LastToken = Tokens.back().Tok;
690 SmallVector<UnwrappedLineNode> SavedTokens(Tokens.size());
693 for (
const auto &Token : Tokens) {
695 auto &SavedToken = SavedTokens[Index++];
697 SavedToken.Tok->copyFrom(*Token.Tok);
698 SavedToken.Children = std::move(Token.Children);
701 AnnotatedLine
Line(ParsedLine);
702 assert(Line.Last == LastToken);
704 TokenAnnotator Annotator(Style, Keywords);
705 Annotator.annotate(Line);
706 Annotator.calculateFormattingInformation(Line);
708 auto Length = LastToken->TotalLength;
710 assert(OpeningBrace != Tokens.front().Tok);
711 if (
auto Prev = OpeningBrace->Previous;
712 Prev && Prev->TotalLength + ColumnLimit == OpeningBrace->TotalLength) {
713 Length -= ColumnLimit;
715 Length -= OpeningBrace->TokenText.size() + 1;
718 if (
const auto *FirstToken = Line.First; FirstToken->is(tok::r_brace)) {
719 assert(!OpeningBrace || OpeningBrace->is(TT_ControlStatementLBrace));
720 Length -= FirstToken->TokenText.size() + 1;
724 for (
auto &Token : Tokens) {
725 const auto &SavedToken = SavedTokens[Index++];
726 Token.Tok->copyFrom(*SavedToken.Tok);
727 Token.Children = std::move(SavedToken.Children);
728 delete SavedToken.Tok;
732 assert(!Line.InMacroBody);
733 assert(!Line.InPPDirective);
734 return Line.Level * Style.IndentWidth + Length <= ColumnLimit;
737FormatToken *UnwrappedLineParser::parseBlock(
bool MustBeDeclaration,
738 unsigned AddLevels,
bool MunchSemi,
741 bool UnindentWhitesmithsBraces) {
742 auto HandleVerilogBlockLabel = [
this]() {
744 if (Style.isVerilog() && FormatTok->is(tok::colon)) {
746 if (Keywords.isVerilogIdentifier(*FormatTok))
753 const bool VerilogHierarchy =
754 Style.isVerilog() && Keywords.isVerilogHierarchy(*FormatTok);
755 assert((FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) ||
756 (Style.isVerilog() &&
757 (Keywords.isVerilogBegin(*FormatTok) || VerilogHierarchy))) &&
758 "'{' or macro block token expected");
760 const bool FollowedByComment = Tokens->peekNextToken()->is(tok::comment);
761 auto Index = CurrentLines->size();
762 const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
767 if (!VerilogHierarchy && AddLevels > 0 &&
768 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) {
772 size_t PPStartHash = computePPHash();
774 const unsigned InitialLevel = Line->Level;
775 if (VerilogHierarchy) {
776 AddLevels += parseVerilogHierarchyHeader();
778 nextToken(AddLevels);
779 HandleVerilogBlockLabel();
783 if (Line->Level > 300)
786 if (MacroBlock && FormatTok->is(tok::l_paren))
789 size_t NbPreprocessorDirectives =
790 !parsingPPDirective() ? PreprocessorDirectives.size() : 0;
792 size_t OpeningLineIndex =
793 CurrentLines->empty()
795 : (CurrentLines->size() - 1 - NbPreprocessorDirectives);
800 if (UnindentWhitesmithsBraces)
803 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
805 if (AddLevels > 0u && Style.BreakBeforeBraces != FormatStyle::BS_Whitesmiths)
806 Line->Level += AddLevels;
809 const bool SimpleBlock = parseLevel(
Tok, IfKind, &IfLBrace);
814 if (MacroBlock ? FormatTok->isNot(TT_MacroBlockEnd)
815 : FormatTok->isNot(tok::r_brace)) {
816 Line->Level = InitialLevel;
817 FormatTok->setBlockKind(BK_Block);
821 if (FormatTok->is(tok::r_brace)) {
822 FormatTok->setBlockKind(BK_Block);
823 if (Tok->is(TT_NamespaceLBrace))
824 FormatTok->setFinalizedType(TT_NamespaceRBrace);
827 const bool IsFunctionRBrace =
828 FormatTok->is(tok::r_brace) &&
Tok->is(TT_FunctionLBrace);
830 auto RemoveBraces = [=]()
mutable {
833 assert(Tok->isOneOf(TT_ControlStatementLBrace, TT_ElseLBrace));
834 assert(FormatTok->is(tok::r_brace));
835 const bool WrappedOpeningBrace = !Tok->Previous;
836 if (WrappedOpeningBrace && FollowedByComment)
838 const bool HasRequiredIfBraces = IfLBrace && !IfLBrace->Optional;
839 if (KeepBraces && !HasRequiredIfBraces)
841 if (Tok->isNot(TT_ElseLBrace) || !HasRequiredIfBraces) {
842 const FormatToken *Previous = Tokens->getPreviousToken();
844 if (Previous->is(tok::r_brace) && !Previous->Optional)
847 assert(!CurrentLines->empty());
848 auto &LastLine = CurrentLines->back();
849 if (LastLine.Level == InitialLevel + 1 && !mightFitOnOneLine(LastLine))
851 if (
Tok->is(TT_ElseLBrace))
853 if (WrappedOpeningBrace) {
858 return mightFitOnOneLine((*CurrentLines)[Index],
Tok);
860 if (RemoveBraces()) {
861 Tok->MatchingParen = FormatTok;
862 FormatTok->MatchingParen =
Tok;
865 size_t PPEndHash = computePPHash();
868 nextToken(-AddLevels);
873 if (Style.RemoveSemicolon && IsFunctionRBrace) {
874 while (FormatTok->is(tok::semi)) {
875 FormatTok->Optional =
true;
880 HandleVerilogBlockLabel();
882 if (MacroBlock && FormatTok->is(tok::l_paren))
885 Line->Level = InitialLevel;
887 if (FormatTok->is(tok::kw_noexcept)) {
892 if (FormatTok->is(tok::arrow)) {
896 parseStructuralElement();
899 if (MunchSemi && FormatTok->is(tok::semi))
902 if (PPStartHash == PPEndHash) {
903 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
906 (*CurrentLines)[OpeningLineIndex].MatchingClosingBlockLineIndex =
907 CurrentLines->size() - 1;
917 if (
Line.Tokens.size() < 4)
919 auto I =
Line.Tokens.begin();
920 if (I->Tok->TokenText !=
"goog")
923 if (I->Tok->isNot(tok::period))
926 if (I->Tok->TokenText !=
"scope")
929 return I->Tok->is(tok::l_paren);
938 if (
Line.Tokens.size() < 3)
940 auto I =
Line.Tokens.begin();
941 if (I->Tok->isNot(tok::l_paren))
947 return I->Tok->is(tok::l_paren);
952 const bool IsJavaRecord) {
954 return Style.BraceWrapping.AfterClass;
957 if (InitialToken.
is(TT_NamespaceMacro))
958 Kind = tok::kw_namespace;
961 case tok::kw_namespace:
962 return Style.BraceWrapping.AfterNamespace;
964 return Style.BraceWrapping.AfterClass;
966 return Style.BraceWrapping.AfterUnion;
968 return Style.BraceWrapping.AfterStruct;
970 return Style.BraceWrapping.AfterEnum;
976void UnwrappedLineParser::parseChildBlock() {
977 assert(FormatTok->is(tok::l_brace));
978 FormatTok->setBlockKind(BK_Block);
982 bool SkipIndent = (Style.isJavaScript() &&
983 (isGoogScope(*
Line) || isIIFE(*
Line, Keywords)));
984 ScopedLineState LineState(*
this);
985 ScopedDeclarationState DeclarationState(*
Line, DeclarationScopeStack,
987 Line->Level += SkipIndent ? 0 : 1;
988 parseLevel(OpeningBrace);
989 flushComments(isOnNewLine(*FormatTok));
990 Line->Level -= SkipIndent ? 0 : 1;
995void UnwrappedLineParser::parsePPDirective() {
996 assert(FormatTok->is(tok::hash) &&
"'#' expected");
997 ScopedMacroState MacroState(*
Line, Tokens, FormatTok);
1001 if (!FormatTok->Tok.getIdentifierInfo()) {
1006 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
1007 case tok::pp_define:
1014 case tok::pp_ifndef:
1018 case tok::pp_elifdef:
1019 case tok::pp_elifndef:
1026 case tok::pp_pragma:
1030 case tok::pp_warning:
1032 if (!
eof() && Style.isCpp())
1033 FormatTok->setFinalizedType(TT_AfterPPDirective);
1041void UnwrappedLineParser::conditionalCompilationCondition(
bool Unreachable) {
1042 size_t Line = CurrentLines->size();
1043 if (CurrentLines == &PreprocessorDirectives)
1044 Line += Lines.size();
1047 (!PPStack.empty() && PPStack.back().Kind == PP_Unreachable)) {
1048 PPStack.push_back({PP_Unreachable,
Line});
1050 PPStack.push_back({PP_Conditional,
Line});
1054void UnwrappedLineParser::conditionalCompilationStart(
bool Unreachable) {
1056 assert(PPBranchLevel >= 0 && PPBranchLevel <= (
int)PPLevelBranchIndex.size());
1057 if (PPBranchLevel == (
int)PPLevelBranchIndex.size()) {
1058 PPLevelBranchIndex.push_back(0);
1059 PPLevelBranchCount.push_back(0);
1061 PPChainBranchIndex.push(Unreachable ? -1 : 0);
1062 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
1063 conditionalCompilationCondition(Unreachable ||
Skip);
1066void UnwrappedLineParser::conditionalCompilationAlternative() {
1067 if (!PPStack.empty())
1069 assert(PPBranchLevel < (
int)PPLevelBranchIndex.size());
1070 if (!PPChainBranchIndex.empty())
1071 ++PPChainBranchIndex.top();
1072 conditionalCompilationCondition(
1073 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
1074 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
1077void UnwrappedLineParser::conditionalCompilationEnd() {
1078 assert(PPBranchLevel < (
int)PPLevelBranchIndex.size());
1079 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
1080 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel])
1081 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
1084 if (PPBranchLevel > -1)
1086 if (!PPChainBranchIndex.empty())
1087 PPChainBranchIndex.pop();
1088 if (!PPStack.empty())
1092void UnwrappedLineParser::parsePPIf(
bool IfDef) {
1093 bool IfNDef = FormatTok->is(tok::pp_ifndef);
1095 bool Unreachable =
false;
1096 if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText ==
"0"))
1098 if (IfDef && !IfNDef && FormatTok->TokenText ==
"SWIG")
1100 conditionalCompilationStart(Unreachable);
1104 bool MaybeIncludeGuard = IfNDef;
1105 if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
1106 for (
auto &
Line : Lines) {
1107 if (
Line.Tokens.front().Tok->isNot(tok::comment)) {
1108 MaybeIncludeGuard =
false;
1109 IncludeGuard = IG_Rejected;
1117 if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
1118 IncludeGuard = IG_IfNdefed;
1119 IncludeGuardToken = IfCondition;
1123void UnwrappedLineParser::parsePPElse() {
1125 if (IncludeGuard == IG_Defined && PPBranchLevel == 0)
1126 IncludeGuard = IG_Rejected;
1128 assert(PPBranchLevel >= -1);
1129 if (PPBranchLevel == -1)
1130 conditionalCompilationStart(
true);
1131 conditionalCompilationAlternative();
1137void UnwrappedLineParser::parsePPEndIf() {
1138 conditionalCompilationEnd();
1142 if (IncludeGuard == IG_Defined && PPBranchLevel == -1 && Tokens->isEOF() &&
1143 getIncludeGuardState(Style.IndentPPDirectives) == IG_Inited) {
1144 IncludeGuard = IG_Found;
1148void UnwrappedLineParser::parsePPDefine() {
1151 if (!FormatTok->Tok.getIdentifierInfo()) {
1152 IncludeGuard = IG_Rejected;
1153 IncludeGuardToken =
nullptr;
1158 bool MaybeIncludeGuard =
false;
1159 if (IncludeGuard == IG_IfNdefed &&
1160 IncludeGuardToken->TokenText == FormatTok->TokenText) {
1161 IncludeGuard = IG_Defined;
1162 IncludeGuardToken =
nullptr;
1163 for (
auto &
Line : Lines) {
1164 if (
Line.Tokens.front().Tok->isNoneOf(tok::comment, tok::hash)) {
1165 IncludeGuard = IG_Rejected;
1169 MaybeIncludeGuard = IncludeGuard == IG_Defined;
1177 FormatTok->Tok.setKind(tok::identifier);
1178 FormatTok->Tok.setIdentifierInfo(Keywords.kw_internal_ident_after_define);
1182 if (MaybeIncludeGuard && !
eof())
1183 IncludeGuard = IG_Rejected;
1185 if (FormatTok->is(tok::l_paren) && !FormatTok->hasWhitespaceBefore())
1187 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
1188 Line->Level += PPBranchLevel + 1;
1192 Line->PPLevel = PPBranchLevel + (IncludeGuard == IG_Defined ? 0 : 1);
1193 assert((
int)
Line->PPLevel >= 0);
1198 Line->InMacroBody =
true;
1200 if (!Style.SkipMacroDefinitionBody) {
1210 for (
auto *Comment : CommentsBeforeNextToken)
1211 Comment->Finalized =
true;
1214 FormatTok->Finalized =
true;
1215 FormatTok = Tokens->getNextToken();
1221void UnwrappedLineParser::parsePPPragma() {
1222 Line->InPragmaDirective =
true;
1226void UnwrappedLineParser::parsePPUnknown() {
1229 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
1230 Line->Level += PPBranchLevel + 1;
1240 return Tok.isNoneOf(tok::semi, tok::l_brace,
1243 tok::period, tok::periodstar, tok::arrow, tok::arrowstar,
1244 tok::less, tok::greater, tok::slash, tok::percent,
1245 tok::lessless, tok::greatergreater, tok::equal,
1246 tok::plusequal, tok::minusequal, tok::starequal,
1247 tok::slashequal, tok::percentequal, tok::ampequal,
1248 tok::pipeequal, tok::caretequal, tok::greatergreaterequal,
1261 return FormatTok->
is(tok::identifier) &&
1276 FormatTok->
isOneOf(tok::kw_true, tok::kw_false) ||
1287 tok::kw_if, tok::kw_else,
1289 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
1291 tok::kw_switch, tok::kw_case,
1293 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.
kw_finally,
1295 tok::kw_const, tok::kw_class, Keywords.
kw_var, Keywords.
kw_let,
1303 return Tok.isOneOf(tok::kw_char, tok::kw_short, tok::kw_int, tok::kw_long,
1304 tok::kw_unsigned, tok::kw_float, tok::kw_double,
1321 if (FuncName->
isNot(tok::identifier))
1329 Tok->isNoneOf(tok::kw_register, tok::kw_struct, tok::kw_union)) {
1333 if (
Next->isNot(tok::star) && !
Next->Tok.getIdentifierInfo())
1337 if (!
Tok ||
Tok->isNot(tok::r_paren))
1341 if (!
Tok ||
Tok->isNot(tok::identifier))
1344 return Tok->Previous &&
Tok->Previous->isOneOf(tok::l_paren, tok::comma);
1347bool UnwrappedLineParser::parseModuleImport() {
1348 assert(FormatTok->is(Keywords.kw_import) &&
"'import' expected");
1350 if (
auto Token = Tokens->peekNextToken(
true);
1352 Token->isNoneOf(tok::colon, tok::less, tok::string_literal)) {
1358 if (FormatTok->is(tok::colon)) {
1359 FormatTok->setFinalizedType(TT_ModulePartitionColon);
1362 else if (FormatTok->is(tok::less)) {
1364 while (FormatTok->isNoneOf(tok::semi, tok::greater) && !
eof()) {
1367 if (FormatTok->isNot(tok::comment) &&
1368 !FormatTok->TokenText.starts_with(
"//")) {
1369 FormatTok->setFinalizedType(TT_ImplicitStringLiteral);
1374 if (FormatTok->is(tok::semi)) {
1392void UnwrappedLineParser::readTokenWithJavaScriptASI() {
1398 CommentsBeforeNextToken.empty()
1399 ?
Next->NewlinesBefore == 0
1400 : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
1405 bool PreviousStartsTemplateExpr =
1407 if (PreviousMustBeValue ||
Previous->is(tok::r_paren)) {
1410 bool HasAt = llvm::any_of(
Line->Tokens, [](UnwrappedLineNode &LineNode) {
1411 return LineNode.Tok->is(tok::at);
1416 if (
Next->is(tok::exclaim) && PreviousMustBeValue)
1417 return addUnwrappedLine();
1419 bool NextEndsTemplateExpr =
1420 Next->is(TT_TemplateString) &&
Next->TokenText.starts_with(
"}");
1421 if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
1422 (PreviousMustBeValue ||
1423 Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
1424 tok::minusminus))) {
1425 return addUnwrappedLine();
1427 if ((PreviousMustBeValue ||
Previous->is(tok::r_paren)) &&
1429 return addUnwrappedLine();
1433void UnwrappedLineParser::parseStructuralElement(
1434 const FormatToken *OpeningBrace, IfStmtKind *IfKind,
1435 FormatToken **IfLeftBrace,
bool *HasDoWhile,
bool *HasLabel) {
1436 if (Style.isTableGen() && FormatTok->is(tok::pp_include)) {
1438 if (FormatTok->is(tok::string_literal))
1445 while (FormatTok->is(tok::l_square) && handleCppAttributes()) {
1447 }
else if (Style.isVerilog()) {
1448 if (Keywords.isVerilogStructuredProcedure(*FormatTok)) {
1449 parseForOrWhileLoop(
false);
1452 if (FormatTok->isOneOf(Keywords.kw_foreach, Keywords.kw_repeat)) {
1453 parseForOrWhileLoop();
1456 if (FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
1457 Keywords.kw_assume, Keywords.kw_cover)) {
1458 parseIfThenElse(IfKind,
false,
true);
1464 if (FormatTok->isOneOf(Keywords.kw_priority, Keywords.kw_unique,
1465 Keywords.kw_unique0)) {
1467 }
else if (FormatTok->is(tok::l_paren) &&
1468 Tokens->peekNextToken()->is(tok::star)) {
1477 if (FormatTok->isAccessSpecifierKeyword()) {
1478 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp())
1481 parseAccessSpecifier();
1484 switch (FormatTok->Tok.getKind()) {
1487 if (FormatTok->is(tok::l_brace)) {
1488 FormatTok->setFinalizedType(TT_InlineASMBrace);
1490 while (FormatTok && !
eof()) {
1491 if (FormatTok->is(tok::r_brace)) {
1492 FormatTok->setFinalizedType(TT_InlineASMBrace);
1497 FormatTok->Finalized =
true;
1502 case tok::kw_namespace:
1506 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1517 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1521 parseForOrWhileLoop();
1524 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1532 case tok::kw_switch:
1533 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1539 case tok::kw_default: {
1541 if (Style.isVerilog())
1543 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1549 if (FormatTok->is(tok::colon)) {
1550 FormatTok->setFinalizedType(TT_CaseLabelColon);
1554 if (FormatTok->is(tok::arrow)) {
1555 FormatTok->setFinalizedType(TT_CaseLabelArrow);
1556 Default->setFinalizedType(TT_SwitchExpressionLabel);
1565 if (Style.Language == FormatStyle::LK_Proto) {
1569 if (Style.isVerilog()) {
1574 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1583 if (FormatTok->is(tok::kw_case))
1588 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1594 case tok::kw_extern:
1595 if (Style.isVerilog()) {
1598 parseVerilogExtern();
1602 if (FormatTok->is(tok::string_literal)) {
1604 if (FormatTok->is(tok::l_brace)) {
1605 if (Style.BraceWrapping.AfterExternBlock)
1609 unsigned AddLevels =
1610 (Style.IndentExternBlock == FormatStyle::IEBS_Indent) ||
1611 (Style.BraceWrapping.AfterExternBlock &&
1612 Style.IndentExternBlock ==
1613 FormatStyle::IEBS_AfterExternBlock)
1616 parseBlock(
true, AddLevels);
1622 case tok::kw_export:
1623 if (Style.isJavaScript()) {
1624 parseJavaScriptEs6ImportExport();
1627 if (Style.isVerilog()) {
1628 parseVerilogExtern();
1633 if (FormatTok->is(tok::kw_namespace)) {
1637 if (FormatTok->is(tok::l_brace)) {
1638 parseCppExportBlock();
1641 if (FormatTok->is(Keywords.kw_import) && parseModuleImport())
1645 case tok::kw_inline:
1647 if (FormatTok->is(tok::kw_namespace)) {
1652 case tok::identifier:
1653 if (FormatTok->is(TT_ForEachMacro)) {
1654 parseForOrWhileLoop();
1657 if (FormatTok->is(TT_MacroBlockBegin)) {
1658 parseBlock(
false, 1u,
1662 if (FormatTok->is(Keywords.kw_import)) {
1663 if (Style.isJavaScript()) {
1664 parseJavaScriptEs6ImportExport();
1667 if (Style.Language == FormatStyle::LK_Proto) {
1669 if (FormatTok->is(tok::kw_public))
1671 if (FormatTok->isNot(tok::string_literal))
1674 if (FormatTok->is(tok::semi))
1679 if (Style.isVerilog()) {
1680 parseVerilogExtern();
1683 if (IsCpp && parseModuleImport())
1686 if (IsCpp && FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
1687 Keywords.kw_slots, Keywords.kw_qslots)) {
1689 if (FormatTok->is(tok::colon)) {
1695 if (IsCpp && FormatTok->is(TT_StatementMacro)) {
1696 parseStatementMacro();
1699 if (IsCpp && FormatTok->is(TT_NamespaceMacro)) {
1707 if (!Style.isJavaScript() && !Style.isVerilog() && !Style.isTableGen() &&
1708 Tokens->peekNextToken()->is(tok::colon) && !
Line->MustBeDeclaration) {
1710 if (!
Line->InMacroBody || CurrentLines->size() > 1)
1711 Line->Tokens.begin()->Tok->MustBreakBefore =
true;
1712 FormatTok->setFinalizedType(TT_GotoLabelColon);
1713 parseLabel(!Style.IndentGotoLabels);
1718 if (Style.isJava() && FormatTok->is(Keywords.kw_record)) {
1719 parseRecord(
false,
true);
1729 bool SeenEqual =
false;
1730 for (
const bool InRequiresExpression =
1731 OpeningBrace && OpeningBrace->isOneOf(TT_RequiresExpressionLBrace,
1732 TT_CompoundRequirementLBrace);
1735 switch (FormatTok->Tok.getKind()) {
1738 if (FormatTok->is(tok::l_brace)) {
1743 if (Style.isJava() && FormatTok->is(Keywords.kw_interface)) {
1747 switch (
bool IsAutoRelease =
false; FormatTok->Tok.getObjCKeywordID()) {
1748 case tok::objc_public:
1749 case tok::objc_protected:
1750 case tok::objc_package:
1751 case tok::objc_private:
1752 return parseAccessSpecifier();
1753 case tok::objc_interface:
1754 case tok::objc_implementation:
1755 return parseObjCInterfaceOrImplementation();
1756 case tok::objc_protocol:
1757 if (parseObjCProtocol())
1762 case tok::objc_optional:
1763 case tok::objc_required:
1767 case tok::objc_autoreleasepool:
1768 IsAutoRelease =
true;
1770 case tok::objc_synchronized:
1772 if (!IsAutoRelease && FormatTok->is(tok::l_paren)) {
1776 if (FormatTok->is(tok::l_brace)) {
1777 if (Style.BraceWrapping.AfterControlStatement ==
1778 FormatStyle::BWACS_Always) {
1794 case tok::kw_requires: {
1796 bool ParsedClause = parseRequires(SeenEqual);
1817 if (!IsCpp && !Style.isVerilog()) {
1822 case tok::kw_typedef:
1824 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1825 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS,
1826 Keywords.kw_CF_CLOSED_ENUM,
1827 Keywords.kw_NS_CLOSED_ENUM)) {
1832 if (Style.isVerilog()) {
1837 if (Style.isTableGen()) {
1844 case tok::kw_struct:
1846 if (parseStructLike())
1849 case tok::kw_decltype:
1851 if (FormatTok->is(tok::l_paren)) {
1853 if (FormatTok->Previous &&
1854 FormatTok->Previous->endsSequence(tok::r_paren, tok::kw_auto,
1856 Line->SeenDecltypeAuto =
true;
1863 if (Style.isJava() && FormatTok && FormatTok->is(tok::kw_class))
1865 if (Style.isJavaScript() && FormatTok &&
1866 FormatTok->Tok.getIdentifierInfo()) {
1879 case tok::l_paren: {
1886 Tokens->peekNextToken(
true),
1893 case tok::kw_operator:
1895 if (FormatTok->isBinaryOperator())
1899 const auto *Prev = FormatTok->getPreviousNonComment();
1901 if (Prev && Prev->is(tok::identifier))
1904 if (FormatTok->Tok.isAnyIdentifier() || FormatTok->isTypeName(LangOpts)) {
1907 while (FormatTok->is(tok::star))
1911 if (FormatTok->is(tok::l_paren))
1914 if (FormatTok->is(tok::l_brace))
1919 if (InRequiresExpression)
1920 FormatTok->setFinalizedType(TT_BracedListLBrace);
1921 if (!tryToParsePropertyAccessor() && !tryToParseBracedList()) {
1922 IsDecltypeAutoFunction =
Line->SeenDecltypeAuto;
1927 if (Style.isJava() &&
1928 Line->Tokens.front().Tok->is(Keywords.kw_synchronized)) {
1931 if (Style.BraceWrapping.AfterControlStatement ==
1932 FormatStyle::BWACS_Always) {
1935 }
else if (Style.BraceWrapping.AfterFunction) {
1939 FormatTok->setFinalizedType(TT_FunctionLBrace);
1941 IsDecltypeAutoFunction =
false;
1949 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1955 if (Style.BraceWrapping.AfterFunction)
1959 case tok::identifier: {
1960 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where) &&
1961 Line->MustBeDeclaration) {
1963 parseCSharpGenericTypeConstraint();
1966 if (FormatTok->is(TT_MacroBlockEnd)) {
1975 size_t TokenCount =
Line->Tokens.size();
1976 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_function) &&
1979 Line->Tokens.front().Tok->isNot(Keywords.kw_async)))) {
1980 tryToParseJSFunction();
1983 if ((Style.isJavaScript() || Style.isJava()) &&
1984 FormatTok->is(Keywords.kw_interface)) {
1985 if (Style.isJavaScript()) {
1990 unsigned StoredPosition = Tokens->getPosition();
1992 FormatTok = Tokens->setPosition(StoredPosition);
2003 if (Style.isVerilog()) {
2004 if (FormatTok->is(Keywords.kw_table)) {
2005 parseVerilogTable();
2008 if (Keywords.isVerilogBegin(*FormatTok) ||
2009 Keywords.isVerilogHierarchy(*FormatTok)) {
2016 if (!IsCpp && FormatTok->is(Keywords.kw_interface)) {
2017 if (parseStructLike())
2022 if (IsCpp && FormatTok->is(TT_StatementMacro)) {
2023 parseStatementMacro();
2028 StringRef
Text = FormatTok->TokenText;
2035 if (Style.isJavaScript())
2038 auto OneTokenSoFar = [&]() {
2039 auto I =
Line->Tokens.begin(), E =
Line->Tokens.end();
2040 while (I != E && I->Tok->is(tok::comment))
2042 if (Style.isVerilog())
2043 while (I != E && I->Tok->is(tok::hash))
2045 return I != E && (++I == E);
2047 if (OneTokenSoFar()) {
2050 bool FunctionLike = FormatTok->is(tok::l_paren);
2054 bool FollowedByNewline =
2055 CommentsBeforeNextToken.empty()
2056 ? FormatTok->NewlinesBefore > 0
2057 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
2059 if (FollowedByNewline &&
2060 (
Text.size() >= 5 ||
2061 (FunctionLike && FormatTok->isNot(tok::l_paren))) &&
2063 if (PreviousToken->isNot(TT_UntouchableMacroFunc))
2064 PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro);
2072 if ((Style.isJavaScript() || Style.isCSharp()) &&
2073 FormatTok->is(TT_FatArrow)) {
2074 tryToParseChildBlock();
2080 if (FormatTok->is(tok::l_brace)) {
2084 if (Style.isCSharp())
2085 FormatTok->setBlockKind(BK_BracedInit);
2088 if (Style.isTableGen() &&
2089 Line->Tokens.begin()->Tok->is(Keywords.kw_defset)) {
2090 FormatTok->setFinalizedType(TT_FunctionLBrace);
2091 parseBlock(
false, 1u,
2098 }
else if (Style.Language == FormatStyle::LK_Proto &&
2099 FormatTok->is(tok::less)) {
2101 parseBracedList(
true);
2108 if (Style.isCSharp() &&
2109 (Tokens->peekNextToken()->isAccessSpecifierKeyword() ||
2116 case tok::kw_switch:
2124 if (Style.Language == FormatStyle::LK_Proto) {
2129 if (Style.isVerilog()) {
2134 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
2141 case tok::kw_default:
2143 if (Style.isVerilog()) {
2144 if (FormatTok->is(tok::colon)) {
2148 if (FormatTok->is(Keywords.kw_clocking)) {
2154 parseVerilogCaseLabel();
2160 if (Style.isVerilog()) {
2161 parseVerilogCaseLabel();
2167 if (FormatTok->is(tok::l_brace))
2168 FormatTok->Previous->setFinalizedType(TT_TemplateCloser);
2177bool UnwrappedLineParser::tryToParsePropertyAccessor() {
2178 assert(FormatTok->is(tok::l_brace));
2179 if (!Style.isCSharp())
2182 if (!FormatTok->Previous || FormatTok->Previous->isNot(tok::identifier))
2190 unsigned int StoredPosition = Tokens->getPosition();
2196 bool HasSpecialAccessor =
false;
2197 bool IsTrivialPropertyAccessor =
true;
2200 if (
const bool IsAccessorKeyword =
2201 Tok->
isOneOf(Keywords.kw_get, Keywords.kw_init, Keywords.kw_set);
2202 IsAccessorKeyword ||
Tok->isAccessSpecifierKeyword() ||
2203 Tok->
isOneOf(tok::l_square, tok::semi, Keywords.kw_internal)) {
2204 if (IsAccessorKeyword)
2205 HasSpecialAccessor =
true;
2206 else if (
Tok->
is(tok::l_square))
2208 Tok = Tokens->getNextToken();
2212 IsTrivialPropertyAccessor =
false;
2217 Tokens->setPosition(StoredPosition);
2223 Tokens->setPosition(StoredPosition);
2224 if (!IsTrivialPropertyAccessor && Style.BraceWrapping.AfterFunction)
2228 switch (FormatTok->Tok.getKind()) {
2231 if (FormatTok->is(tok::equal)) {
2232 while (!
eof() && FormatTok->isNot(tok::semi))
2245 if (FormatTok->is(TT_FatArrow)) {
2249 }
while (!
eof() && FormatTok->isNot(tok::semi));
2258 if (FormatTok->isOneOf(Keywords.kw_get, Keywords.kw_init,
2260 !IsTrivialPropertyAccessor) {
2272bool UnwrappedLineParser::tryToParseLambda() {
2273 assert(FormatTok->is(tok::l_square));
2279 if (!tryToParseLambdaIntroducer())
2283 bool InTemplateParameterList =
false;
2285 while (FormatTok->isNot(tok::l_brace)) {
2286 if (FormatTok->isTypeName(LangOpts) || FormatTok->isAttribute()) {
2290 switch (FormatTok->Tok.getKind()) {
2294 parseParens(TT_PointerOrReference);
2300 assert(FormatTok->Previous);
2301 if (FormatTok->Previous->is(tok::r_square))
2302 InTemplateParameterList =
true;
2307 case tok::kw_struct:
2309 case tok::kw_template:
2310 case tok::kw_typename:
2314 case tok::kw_constexpr:
2315 case tok::kw_consteval:
2318 case tok::identifier:
2319 case tok::numeric_constant:
2320 case tok::coloncolon:
2321 case tok::kw_mutable:
2322 case tok::kw_noexcept:
2323 case tok::kw_static:
2348 case tok::equalequal:
2349 case tok::exclaimequal:
2350 case tok::greaterequal:
2351 case tok::lessequal:
2357 if (Arrow || InTemplateParameterList) {
2366 case tok::kw_requires:
2367 parseRequiresClause();
2370 if (!InTemplateParameterList)
2379 FormatTok->setFinalizedType(TT_LambdaLBrace);
2380 LSquare.setFinalizedType(TT_LambdaLSquare);
2383 Arrow->setFinalizedType(TT_LambdaArrow);
2385 NestedLambdas.push_back(
Line->SeenDecltypeAuto);
2387 assert(!NestedLambdas.empty());
2388 NestedLambdas.pop_back();
2393bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
2402 const auto *BeforeRParen =
Previous->getPreviousNonComment();
2405 if (!BeforeRParen || BeforeRParen->isNoneOf(tok::greater, tok::r_paren))
2407 }
else if (
Previous->is(tok::star)) {
2411 Previous->isNoneOf(tok::kw_return, tok::kw_co_await, tok::kw_co_yield,
2412 tok::kw_co_return)) {
2416 if (LeftSquare->isCppStructuredBinding(IsCpp))
2418 if (FormatTok->is(tok::l_square) ||
tok::isLiteral(FormatTok->Tok.getKind()))
2420 if (FormatTok->is(tok::r_square)) {
2422 if (
Next->is(tok::greater))
2429void UnwrappedLineParser::tryToParseJSFunction() {
2430 assert(FormatTok->is(Keywords.kw_function));
2431 if (FormatTok->is(Keywords.kw_async))
2437 if (FormatTok->is(tok::star)) {
2438 FormatTok->setFinalizedType(TT_OverloadedOperator);
2443 if (FormatTok->is(tok::identifier))
2446 if (FormatTok->isNot(tok::l_paren))
2452 if (FormatTok->is(tok::colon)) {
2458 if (FormatTok->is(tok::l_brace))
2459 tryToParseBracedList();
2461 while (FormatTok->isNoneOf(tok::l_brace, tok::semi) && !
eof())
2465 if (FormatTok->is(tok::semi))
2471bool UnwrappedLineParser::tryToParseBracedList() {
2472 if (FormatTok->is(BK_Unknown))
2473 calculateBraceTypes();
2474 assert(FormatTok->isNot(BK_Unknown));
2475 if (FormatTok->is(BK_Block))
2482bool UnwrappedLineParser::tryToParseChildBlock() {
2483 assert(Style.isJavaScript() || Style.isCSharp());
2484 assert(FormatTok->is(TT_FatArrow));
2489 if (FormatTok->isNot(tok::l_brace))
2495bool UnwrappedLineParser::parseBracedList(
bool IsAngleBracket,
bool IsEnum) {
2496 assert(!IsAngleBracket || !IsEnum);
2497 bool HasError =
false;
2502 if (Style.isCSharp() && FormatTok->is(TT_FatArrow) &&
2503 tryToParseChildBlock()) {
2506 if (Style.isJavaScript()) {
2507 if (FormatTok->is(Keywords.kw_function)) {
2508 tryToParseJSFunction();
2511 if (FormatTok->is(tok::l_brace)) {
2513 if (tryToParseBracedList())
2518 if (FormatTok->is(IsAngleBracket ? tok::greater : tok::r_brace)) {
2520 FormatTok->setBlockKind(BK_Block);
2521 if (!Style.AllowShortEnumsOnASingleLine)
2527 switch (FormatTok->Tok.getKind()) {
2529 if (Style.isCSharp())
2538 if (Style.isJavaScript()) {
2539 if (FormatTok->is(tok::l_brace))
2547 FormatTok->setBlockKind(BK_BracedInit);
2548 if (!IsAngleBracket) {
2549 auto *Prev = FormatTok->Previous;
2550 if (Prev && Prev->is(tok::greater))
2551 Prev->setFinalizedType(TT_TemplateCloser);
2559 parseBracedList(
true);
2566 if (Style.isJavaScript()) {
2577 if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
2580 case tok::kw_requires:
2581 parseRequiresExpression();
2596bool UnwrappedLineParser::parseParens(TokenType AmpAmpTokenType,
2598 assert(FormatTok->is(tok::l_paren) &&
"'(' expected.");
2599 auto *LParen = FormatTok;
2600 auto *Prev = FormatTok->Previous;
2601 bool SeenComma =
false;
2602 bool SeenEqual =
false;
2603 bool MightBeFoldExpr =
false;
2605 const bool MightBeStmtExpr = FormatTok->is(tok::l_brace);
2606 if (!InMacroCall && Prev && Prev->is(TT_FunctionLikeMacro))
2609 switch (FormatTok->Tok.getKind()) {
2611 if (parseParens(AmpAmpTokenType, InMacroCall))
2613 if (Style.isJava() && FormatTok->is(tok::l_brace))
2616 case tok::r_paren: {
2617 auto *RParen = FormatTok;
2620 auto OptionalParens = [&] {
2621 if (MightBeStmtExpr || MightBeFoldExpr || SeenComma || InMacroCall ||
2622 Line->InMacroBody ||
2623 Style.RemoveParentheses == FormatStyle::RPS_Leave ||
2624 RParen->getPreviousNonComment() == LParen) {
2627 const bool DoubleParens =
2628 Prev->is(tok::l_paren) && FormatTok->is(tok::r_paren);
2630 const auto *PrevPrev = Prev->getPreviousNonComment();
2631 const bool Excluded =
2633 (PrevPrev->isOneOf(tok::kw___attribute, tok::kw_decltype) ||
2635 (PrevPrev->isOneOf(tok::kw_if, tok::kw_while) ||
2636 PrevPrev->endsSequence(tok::kw_constexpr, tok::kw_if))));
2640 const bool CommaSeparated =
2641 Prev->isOneOf(tok::l_paren, tok::comma) &&
2642 FormatTok->isOneOf(tok::comma, tok::r_paren);
2643 if (CommaSeparated &&
2645 !Prev->endsSequence(tok::comma, tok::ellipsis) &&
2647 !(FormatTok->is(tok::comma) &&
2648 Tokens->peekNextToken()->is(tok::ellipsis))) {
2651 const bool ReturnParens =
2652 Style.RemoveParentheses == FormatStyle::RPS_ReturnStatement &&
2653 ((NestedLambdas.empty() && !IsDecltypeAutoFunction) ||
2654 (!NestedLambdas.empty() && !NestedLambdas.back())) &&
2655 Prev->isOneOf(tok::kw_return, tok::kw_co_return) &&
2656 FormatTok->is(tok::semi);
2662 if (Prev->is(TT_TypenameMacro)) {
2663 LParen->setFinalizedType(TT_TypeDeclarationParen);
2664 RParen->setFinalizedType(TT_TypeDeclarationParen);
2665 }
else if (Prev->is(tok::greater) && RParen->Previous == LParen) {
2666 Prev->setFinalizedType(TT_TemplateCloser);
2667 }
else if (OptionalParens()) {
2668 LParen->Optional =
true;
2669 RParen->Optional =
true;
2681 if (!tryToParseBracedList())
2686 if (FormatTok->is(tok::l_brace)) {
2696 MightBeFoldExpr =
true;
2701 if (Style.isCSharp() && FormatTok->is(TT_FatArrow))
2702 tryToParseChildBlock();
2707 if (Style.isJavaScript())
2712 case tok::identifier:
2713 if (Style.isJavaScript() && (FormatTok->is(Keywords.kw_function)))
2714 tryToParseJSFunction();
2718 case tok::kw_switch:
2724 case tok::kw_requires:
2725 parseRequiresExpression();
2728 if (AmpAmpTokenType != TT_Unknown)
2729 FormatTok->setFinalizedType(AmpAmpTokenType);
2741 assert(FormatTok->is(tok::l_square) &&
"'[' expected.");
2742 if (tryToParseLambda())
2746 switch (FormatTok->Tok.getKind()) {
2759 case tok::l_brace: {
2760 if (!tryToParseBracedList())
2767 if (FormatTok->is(tok::l_brace)) {
2779void UnwrappedLineParser::keepAncestorBraces() {
2780 if (!Style.RemoveBracesLLVM)
2783 const int MaxNestingLevels = 2;
2784 const int Size = NestedTooDeep.size();
2785 if (Size >= MaxNestingLevels)
2786 NestedTooDeep[
Size - MaxNestingLevels] =
true;
2787 NestedTooDeep.push_back(
false);
2791 for (
const auto &
Token : llvm::reverse(
Line.Tokens))
2798void UnwrappedLineParser::parseUnbracedBody(
bool CheckEOF) {
2801 if (Style.InsertBraces && !
Line->InPPDirective && !
Line->Tokens.empty() &&
2802 PreprocessorDirectives.empty() && FormatTok->isNot(tok::semi)) {
2803 Tok = Style.BraceWrapping.AfterControlStatement == FormatStyle::BWACS_Never
2804 ? getLastNonComment(*
Line)
2807 if (
Tok->BraceCount < 0) {
2808 assert(
Tok->BraceCount == -1);
2811 Tok->BraceCount = -1;
2817 ++
Line->UnbracedBodyLevel;
2818 parseStructuralElement();
2819 --
Line->UnbracedBodyLevel;
2822 assert(!
Line->InPPDirective);
2824 for (
const auto &L : llvm::reverse(*CurrentLines)) {
2826 Tok = L.Tokens.back().Tok;
2834 if (CheckEOF &&
eof())
2844 assert(LeftBrace->
is(tok::l_brace));
2852 assert(RightBrace->
is(tok::r_brace));
2860void UnwrappedLineParser::handleAttributes() {
2862 if (FormatTok->isAttribute())
2864 else if (FormatTok->is(tok::l_square))
2865 handleCppAttributes();
2868bool UnwrappedLineParser::handleCppAttributes() {
2870 assert(FormatTok->is(tok::l_square));
2871 if (!tryToParseSimpleAttribute())
2878bool UnwrappedLineParser::isBlockBegin(
const FormatToken &
Tok)
const {
2881 return Style.isVerilog() ? Keywords.isVerilogBegin(
Tok)
2882 :
Tok.
is(tok::l_brace);
2885FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
2887 bool IsVerilogAssert) {
2888 assert((FormatTok->is(tok::kw_if) ||
2889 (Style.isVerilog() &&
2890 FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
2891 Keywords.kw_assume, Keywords.kw_cover))) &&
2895 if (IsVerilogAssert) {
2897 if (FormatTok->is(Keywords.kw_verilogHash)) {
2899 if (FormatTok->is(tok::numeric_constant))
2901 }
else if (FormatTok->isOneOf(Keywords.kw_final, Keywords.kw_property,
2902 Keywords.kw_sequence)) {
2908 if (Style.isTableGen()) {
2909 while (!
eof() && FormatTok->isNot(Keywords.kw_then)) {
2916 if (FormatTok->is(tok::exclaim))
2919 bool KeepIfBraces =
true;
2920 if (FormatTok->is(tok::kw_consteval)) {
2923 KeepIfBraces = !Style.RemoveBracesLLVM || KeepBraces;
2924 if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
2926 if (FormatTok->is(tok::l_paren)) {
2927 FormatTok->setFinalizedType(TT_ConditionLParen);
2933 if (IsVerilogAssert && FormatTok->is(tok::semi)) {
2939 bool NeedsUnwrappedLine =
false;
2940 keepAncestorBraces();
2943 IfStmtKind IfBlockKind = IfStmtKind::NotIf;
2945 if (isBlockBegin(*FormatTok)) {
2946 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
2947 IfLeftBrace = FormatTok;
2948 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
2949 parseBlock(
false, 1u,
2950 true, KeepIfBraces, &IfBlockKind);
2951 setPreviousRBraceType(TT_ControlStatementRBrace);
2952 if (Style.BraceWrapping.BeforeElse)
2955 NeedsUnwrappedLine =
true;
2956 }
else if (IsVerilogAssert && FormatTok->is(tok::kw_else)) {
2959 parseUnbracedBody();
2962 if (Style.RemoveBracesLLVM) {
2963 assert(!NestedTooDeep.empty());
2964 KeepIfBraces = KeepIfBraces ||
2965 (IfLeftBrace && !IfLeftBrace->MatchingParen) ||
2966 NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly ||
2967 IfBlockKind == IfStmtKind::IfElseIf;
2970 bool KeepElseBraces = KeepIfBraces;
2972 IfStmtKind
Kind = IfStmtKind::IfOnly;
2974 if (FormatTok->is(tok::kw_else)) {
2975 if (Style.RemoveBracesLLVM) {
2976 NestedTooDeep.back() =
false;
2977 Kind = IfStmtKind::IfElse;
2981 if (isBlockBegin(*FormatTok)) {
2982 const bool FollowedByIf = Tokens->peekNextToken()->is(tok::kw_if);
2983 FormatTok->setFinalizedType(TT_ElseLBrace);
2984 ElseLeftBrace = FormatTok;
2985 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
2986 IfStmtKind ElseBlockKind = IfStmtKind::NotIf;
2988 parseBlock(
false, 1u,
2989 true, KeepElseBraces, &ElseBlockKind);
2990 setPreviousRBraceType(TT_ElseRBrace);
2991 if (FormatTok->is(tok::kw_else)) {
2992 KeepElseBraces = KeepElseBraces ||
2993 ElseBlockKind == IfStmtKind::IfOnly ||
2994 ElseBlockKind == IfStmtKind::IfElseIf;
2995 }
else if (FollowedByIf && IfLBrace && !IfLBrace->Optional) {
2996 KeepElseBraces =
true;
2997 assert(ElseLeftBrace->MatchingParen);
3001 }
else if (!IsVerilogAssert && FormatTok->is(tok::kw_if)) {
3004 const bool IsPrecededByComment =
Previous->is(tok::comment);
3005 if (IsPrecededByComment) {
3009 bool TooDeep =
true;
3010 if (Style.RemoveBracesLLVM) {
3011 Kind = IfStmtKind::IfElseIf;
3012 TooDeep = NestedTooDeep.pop_back_val();
3014 ElseLeftBrace = parseIfThenElse(
nullptr, KeepIfBraces);
3015 if (Style.RemoveBracesLLVM)
3016 NestedTooDeep.push_back(TooDeep);
3017 if (IsPrecededByComment)
3020 parseUnbracedBody(
true);
3023 KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse;
3024 if (NeedsUnwrappedLine)
3028 if (!Style.RemoveBracesLLVM)
3031 assert(!NestedTooDeep.empty());
3032 KeepElseBraces = KeepElseBraces ||
3033 (ElseLeftBrace && !ElseLeftBrace->MatchingParen) ||
3034 NestedTooDeep.back();
3036 NestedTooDeep.pop_back();
3038 if (!KeepIfBraces && !KeepElseBraces) {
3041 }
else if (IfLeftBrace) {
3042 FormatToken *IfRightBrace = IfLeftBrace->MatchingParen;
3044 assert(IfRightBrace->MatchingParen == IfLeftBrace);
3045 assert(!IfLeftBrace->Optional);
3046 assert(!IfRightBrace->Optional);
3047 IfLeftBrace->MatchingParen =
nullptr;
3048 IfRightBrace->MatchingParen =
nullptr;
3058void UnwrappedLineParser::parseTryCatch() {
3059 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) &&
"'try' expected");
3061 bool NeedsUnwrappedLine =
false;
3062 bool HasCtorInitializer =
false;
3063 if (FormatTok->is(tok::colon)) {
3064 auto *Colon = FormatTok;
3067 if (FormatTok->is(tok::identifier)) {
3068 HasCtorInitializer =
true;
3069 Colon->setFinalizedType(TT_CtorInitializerColon);
3074 while (FormatTok->is(tok::comma))
3077 while (FormatTok->is(tok::identifier)) {
3079 if (FormatTok->is(tok::l_paren)) {
3081 }
else if (FormatTok->is(tok::l_brace)) {
3088 while (FormatTok->is(tok::comma))
3093 if (Style.isJava() && FormatTok->is(tok::l_paren))
3096 keepAncestorBraces();
3098 if (FormatTok->is(tok::l_brace)) {
3099 if (HasCtorInitializer)
3100 FormatTok->setFinalizedType(TT_FunctionLBrace);
3101 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3103 if (Style.BraceWrapping.BeforeCatch)
3106 NeedsUnwrappedLine =
true;
3107 }
else if (FormatTok->isNot(tok::kw_catch)) {
3113 parseStructuralElement();
3116 for (
bool SeenCatch =
false;;) {
3117 if (FormatTok->is(tok::at))
3119 if (FormatTok->isNoneOf(tok::kw_catch, Keywords.kw___except,
3120 tok::kw___finally, tok::objc_catch,
3121 tok::objc_finally) &&
3122 !((Style.isJava() || Style.isJavaScript()) &&
3123 FormatTok->is(Keywords.kw_finally))) {
3126 if (FormatTok->is(tok::kw_catch))
3129 while (FormatTok->isNot(tok::l_brace)) {
3130 if (FormatTok->is(tok::l_paren)) {
3134 if (FormatTok->isOneOf(tok::semi, tok::r_brace) ||
eof()) {
3135 if (Style.RemoveBracesLLVM)
3136 NestedTooDeep.pop_back();
3142 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3145 NeedsUnwrappedLine =
false;
3146 Line->MustBeDeclaration =
false;
3147 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3149 if (Style.BraceWrapping.BeforeCatch)
3152 NeedsUnwrappedLine =
true;
3155 if (Style.RemoveBracesLLVM)
3156 NestedTooDeep.pop_back();
3158 if (NeedsUnwrappedLine)
3162void UnwrappedLineParser::parseNamespaceOrExportBlock(
unsigned AddLevels) {
3163 bool ManageWhitesmithsBraces =
3164 AddLevels == 0u && Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
3168 if (ManageWhitesmithsBraces)
3173 parseBlock(
true, AddLevels,
true,
3174 true,
nullptr, ManageWhitesmithsBraces);
3176 addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep);
3178 if (ManageWhitesmithsBraces)
3182void UnwrappedLineParser::parseNamespace() {
3183 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
3184 "'namespace' expected");
3188 if (InitialToken.is(TT_NamespaceMacro)) {
3191 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
3192 tok::l_square, tok::period, tok::l_paren) ||
3193 (Style.isCSharp() && FormatTok->is(tok::kw_union))) {
3194 if (FormatTok->is(tok::l_square))
3196 else if (FormatTok->is(tok::l_paren))
3202 if (FormatTok->is(tok::l_brace)) {
3203 FormatTok->setFinalizedType(TT_NamespaceLBrace);
3208 unsigned AddLevels =
3209 Style.NamespaceIndentation == FormatStyle::NI_All ||
3210 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
3211 DeclarationScopeStack.size() > 1)
3214 parseNamespaceOrExportBlock(AddLevels);
3219void UnwrappedLineParser::parseCppExportBlock() {
3220 parseNamespaceOrExportBlock(Style.IndentExportBlock ? 1 : 0);
3223void UnwrappedLineParser::parseNew() {
3224 assert(FormatTok->is(tok::kw_new) &&
"'new' expected");
3227 if (Style.isCSharp()) {
3230 if (FormatTok->is(tok::l_paren))
3234 if (FormatTok->is(tok::l_brace))
3237 if (FormatTok->isOneOf(tok::semi, tok::comma))
3244 if (!Style.isJava())
3250 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
3254 if (FormatTok->is(tok::l_paren)) {
3258 if (FormatTok->is(tok::l_brace))
3266void UnwrappedLineParser::parseLoopBody(
bool KeepBraces,
bool WrapRightBrace) {
3267 keepAncestorBraces();
3269 if (isBlockBegin(*FormatTok)) {
3270 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3272 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3273 parseBlock(
false, 1u,
3275 setPreviousRBraceType(TT_ControlStatementRBrace);
3277 assert(!NestedTooDeep.empty());
3278 if (!NestedTooDeep.back())
3284 parseUnbracedBody();
3288 NestedTooDeep.pop_back();
3291void UnwrappedLineParser::parseForOrWhileLoop(
bool HasParens) {
3292 assert((FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) ||
3293 (Style.isVerilog() &&
3294 FormatTok->isOneOf(Keywords.kw_always, Keywords.kw_always_comb,
3295 Keywords.kw_always_ff, Keywords.kw_always_latch,
3296 Keywords.kw_final, Keywords.kw_initial,
3297 Keywords.kw_foreach, Keywords.kw_forever,
3298 Keywords.kw_repeat))) &&
3299 "'for', 'while' or foreach macro expected");
3300 const bool KeepBraces = !Style.RemoveBracesLLVM ||
3301 FormatTok->isNoneOf(tok::kw_for, tok::kw_while);
3305 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
3307 if (IsCpp && FormatTok->is(tok::kw_co_await))
3309 if (HasParens && FormatTok->is(tok::l_paren)) {
3313 if (Style.isVerilog())
3314 FormatTok->setFinalizedType(TT_ConditionLParen);
3318 if (Style.isVerilog()) {
3320 parseVerilogSensitivityList();
3321 }
else if (Style.AllowShortLoopsOnASingleLine && FormatTok->is(tok::semi) &&
3322 Tokens->getPreviousToken()->is(tok::r_paren)) {
3329 parseLoopBody(KeepBraces,
true);
3332void UnwrappedLineParser::parseDoWhile() {
3333 assert(FormatTok->is(tok::kw_do) &&
"'do' expected");
3336 parseLoopBody(
true, Style.BraceWrapping.BeforeWhile);
3339 if (FormatTok->isNot(tok::kw_while)) {
3344 FormatTok->setFinalizedType(TT_DoWhile);
3348 if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)
3352 parseStructuralElement();
3355void UnwrappedLineParser::parseLabel(
bool LeftAlignLabel) {
3357 unsigned OldLineLevel =
Line->Level;
3361 else if (
Line->Level > 1 || (!
Line->InPPDirective &&
Line->Level > 0))
3364 if (!Style.IndentCaseBlocks && CommentsBeforeNextToken.empty() &&
3365 FormatTok->is(tok::l_brace)) {
3367 CompoundStatementIndenter Indenter(
this,
Line->Level,
3368 Style.BraceWrapping.AfterCaseLabel,
3369 Style.BraceWrapping.IndentBraces);
3371 if (FormatTok->is(tok::kw_break)) {
3372 if (Style.BraceWrapping.AfterControlStatement ==
3373 FormatStyle::BWACS_Always) {
3375 if (!Style.IndentCaseBlocks &&
3376 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) {
3380 parseStructuralElement();
3384 if (FormatTok->is(tok::semi))
3388 Line->Level = OldLineLevel;
3389 if (FormatTok->isNot(tok::l_brace)) {
3390 parseStructuralElement();
3395void UnwrappedLineParser::parseCaseLabel() {
3396 assert(FormatTok->is(tok::kw_case) &&
"'case' expected");
3397 auto *Case = FormatTok;
3402 if (FormatTok->is(tok::colon)) {
3403 FormatTok->setFinalizedType(TT_CaseLabelColon);
3406 if (Style.isJava() && FormatTok->is(tok::arrow)) {
3407 FormatTok->setFinalizedType(TT_CaseLabelArrow);
3408 Case->setFinalizedType(TT_SwitchExpressionLabel);
3415void UnwrappedLineParser::parseSwitch(
bool IsExpr) {
3416 assert(FormatTok->is(tok::kw_switch) &&
"'switch' expected");
3418 if (FormatTok->is(tok::l_paren))
3421 keepAncestorBraces();
3423 if (FormatTok->is(tok::l_brace)) {
3424 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3425 FormatTok->setFinalizedType(IsExpr ? TT_SwitchExpressionLBrace
3426 : TT_ControlStatementLBrace);
3431 setPreviousRBraceType(TT_ControlStatementRBrace);
3437 parseStructuralElement();
3441 if (Style.RemoveBracesLLVM)
3442 NestedTooDeep.pop_back();
3445void UnwrappedLineParser::parseAccessSpecifier() {
3448 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
3451 if (FormatTok->is(tok::colon))
3459bool UnwrappedLineParser::parseRequires(
bool SeenEqual) {
3460 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3464 switch (Tokens->peekNextToken(
true)->Tok.getKind()) {
3467 parseRequiresExpression();
3474 parseRequiresClause();
3485 auto *PreviousNonComment = FormatTok->getPreviousNonComment();
3487 if (!PreviousNonComment ||
3488 PreviousNonComment->is(TT_RequiresExpressionLBrace)) {
3491 parseRequiresClause();
3495 switch (PreviousNonComment->Tok.getKind()) {
3498 case tok::kw_noexcept:
3503 parseRequiresClause();
3512 auto PrevPrev = PreviousNonComment->getPreviousNonComment();
3513 if ((PrevPrev && PrevPrev->is(tok::kw_const)) || !SeenEqual) {
3514 parseRequiresClause();
3520 if (PreviousNonComment->isTypeOrIdentifier(LangOpts)) {
3522 parseRequiresClause();
3526 parseRequiresExpression();
3536 unsigned StoredPosition = Tokens->getPosition();
3539 auto PeekNext = [&Lookahead, &NextToken,
this] {
3541 NextToken = Tokens->getNextToken();
3544 bool FoundType =
false;
3545 bool LastWasColonColon =
false;
3548 for (; Lookahead < 50; PeekNext()) {
3549 switch (NextToken->Tok.getKind()) {
3550 case tok::kw_volatile:
3553 if (OpenAngles == 0) {
3554 FormatTok = Tokens->setPosition(StoredPosition);
3555 parseRequiresExpression();
3563 case tok::coloncolon:
3564 LastWasColonColon =
true;
3566 case tok::kw_decltype:
3567 case tok::identifier:
3568 if (FoundType && !LastWasColonColon && OpenAngles == 0) {
3569 FormatTok = Tokens->setPosition(StoredPosition);
3570 parseRequiresExpression();
3574 LastWasColonColon =
false;
3583 if (NextToken->isTypeName(LangOpts)) {
3584 FormatTok = Tokens->setPosition(StoredPosition);
3585 parseRequiresExpression();
3592 FormatTok = Tokens->setPosition(StoredPosition);
3593 parseRequiresClause();
3602void UnwrappedLineParser::parseRequiresClause() {
3603 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3608 bool InRequiresExpression =
3609 !FormatTok->Previous ||
3610 FormatTok->Previous->is(TT_RequiresExpressionLBrace);
3612 FormatTok->setFinalizedType(InRequiresExpression
3613 ? TT_RequiresClauseInARequiresExpression
3614 : TT_RequiresClause);
3619 parseConstraintExpression();
3621 if (!InRequiresExpression && FormatTok->Previous)
3622 FormatTok->Previous->ClosesRequiresClause =
true;
3630void UnwrappedLineParser::parseRequiresExpression() {
3631 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3633 FormatTok->setFinalizedType(TT_RequiresExpression);
3636 if (FormatTok->is(tok::l_paren)) {
3637 FormatTok->setFinalizedType(TT_RequiresExpressionLParen);
3641 if (FormatTok->is(tok::l_brace)) {
3642 FormatTok->setFinalizedType(TT_RequiresExpressionLBrace);
3651void UnwrappedLineParser::parseConstraintExpression() {
3658 bool LambdaNextTimeAllowed =
true;
3668 bool TopLevelParensAllowed =
true;
3671 bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed,
false);
3673 switch (FormatTok->Tok.getKind()) {
3674 case tok::kw_requires:
3675 parseRequiresExpression();
3679 if (!TopLevelParensAllowed)
3681 parseParens(TT_BinaryOperator);
3682 TopLevelParensAllowed =
false;
3686 if (!LambdaThisTimeAllowed || !tryToParseLambda())
3693 case tok::kw_struct:
3703 FormatTok->setFinalizedType(TT_BinaryOperator);
3705 LambdaNextTimeAllowed =
true;
3706 TopLevelParensAllowed =
true;
3711 LambdaNextTimeAllowed = LambdaThisTimeAllowed;
3715 case tok::kw_sizeof:
3717 case tok::greaterequal:
3718 case tok::greatergreater:
3720 case tok::lessequal:
3722 case tok::equalequal:
3724 case tok::exclaimequal:
3729 LambdaNextTimeAllowed =
true;
3730 TopLevelParensAllowed =
true;
3735 case tok::numeric_constant:
3736 case tok::coloncolon:
3739 TopLevelParensAllowed =
false;
3744 case tok::kw_static_cast:
3745 case tok::kw_const_cast:
3746 case tok::kw_reinterpret_cast:
3747 case tok::kw_dynamic_cast:
3749 if (FormatTok->isNot(tok::less))
3753 parseBracedList(
true);
3757 if (!FormatTok->Tok.getIdentifierInfo()) {
3767 assert(FormatTok->Previous);
3768 switch (FormatTok->Previous->Tok.getKind()) {
3769 case tok::coloncolon:
3773 case tok::kw_requires:
3782 if (FormatTok->is(tok::less)) {
3784 parseBracedList(
true);
3786 TopLevelParensAllowed =
false;
3792bool UnwrappedLineParser::parseEnum() {
3796 if (FormatTok->is(tok::kw_enum))
3802 if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question))
3806 if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal))
3811 if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
3813 while (FormatTok->is(tok::l_square))
3814 if (!handleCppAttributes())
3818 while (FormatTok->Tok.getIdentifierInfo() ||
3819 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
3820 tok::greater, tok::comma, tok::question,
3822 if (Style.isVerilog()) {
3823 FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
3826 while (FormatTok->is(tok::l_square))
3832 if (FormatTok->is(tok::l_paren))
3834 if (FormatTok->is(tok::identifier)) {
3838 if (IsCpp && FormatTok->is(tok::identifier))
3844 if (FormatTok->isNot(tok::l_brace))
3846 FormatTok->setFinalizedType(TT_EnumLBrace);
3847 FormatTok->setBlockKind(BK_Block);
3849 if (Style.isJava()) {
3851 parseJavaEnumBody();
3854 if (Style.Language == FormatStyle::LK_Proto) {
3859 if (!Style.AllowShortEnumsOnASingleLine &&
3865 if (!Style.AllowShortEnumsOnASingleLine) {
3869 bool HasError = !parseBracedList(
false,
true);
3870 if (!Style.AllowShortEnumsOnASingleLine)
3873 if (FormatTok->is(tok::semi))
3877 setPreviousRBraceType(TT_EnumRBrace);
3885bool UnwrappedLineParser::parseStructLike() {
3890 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp()) {
3891 if (FormatTok->is(tok::semi))
3902class ScopedTokenPosition {
3903 unsigned StoredPosition;
3904 FormatTokenSource *Tokens;
3907 ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) {
3908 assert(Tokens &&
"Tokens expected to not be null");
3909 StoredPosition = Tokens->getPosition();
3912 ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); }
3918bool UnwrappedLineParser::tryToParseSimpleAttribute() {
3919 ScopedTokenPosition AutoPosition(Tokens);
3927 if (
Tok->
is(tok::r_square))
3929 Tok = Tokens->getNextToken();
3931 if (
Tok->
is(tok::eof))
3933 Tok = Tokens->getNextToken();
3936 Tok = Tokens->getNextToken();
3937 if (
Tok->
is(tok::semi))
3942void UnwrappedLineParser::parseJavaEnumBody() {
3943 assert(FormatTok->is(tok::l_brace));
3949 unsigned StoredPosition = Tokens->getPosition();
3950 bool IsSimple =
true;
3953 if (
Tok->
is(tok::r_brace))
3961 Tok = Tokens->getNextToken();
3963 FormatTok = Tokens->setPosition(StoredPosition);
3980 if (FormatTok->is(tok::l_brace)) {
3982 parseBlock(
true, 1u,
3984 }
else if (FormatTok->is(tok::l_paren)) {
3986 }
else if (FormatTok->is(tok::comma)) {
3989 }
else if (FormatTok->is(tok::semi)) {
3993 }
else if (FormatTok->is(tok::r_brace)) {
4002 parseLevel(OpeningBrace);
4008void UnwrappedLineParser::parseRecord(
bool ParseAsExpr,
bool IsJavaRecord) {
4009 assert(!IsJavaRecord || FormatTok->is(Keywords.kw_record));
4014 IsJavaRecord && FormatTok->is(tok::identifier) ? FormatTok :
nullptr;
4015 bool IsDerived =
false;
4017 return Tok->
is(tok::identifier) &&
Tok->TokenText !=
Tok->TokenText.upper();
4021 bool JSPastExtendsOrImplements =
false;
4025 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
4026 tok::kw_alignas, tok::l_square) ||
4027 FormatTok->isAttribute() ||
4028 ((Style.isJava() || Style.isJavaScript()) &&
4029 FormatTok->isOneOf(tok::period, tok::comma))) {
4030 if (Style.isJavaScript() &&
4031 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
4032 JSPastExtendsOrImplements =
true;
4037 if (FormatTok->is(tok::l_brace)) {
4038 tryToParseBracedList();
4042 if (FormatTok->is(tok::l_square) && handleCppAttributes())
4046 switch (FormatTok->Tok.getKind()) {
4049 if (IsJavaRecord || !IsNonMacroIdentifier(
Previous) ||
4051 Previous->Previous == &InitialToken) {
4055 case tok::coloncolon:
4059 if (JSPastExtendsOrImplements || ClassName ||
4070 auto IsListInitialization = [&] {
4071 if (!ClassName || IsDerived || JSPastExtendsOrImplements)
4073 assert(FormatTok->is(tok::l_brace));
4074 const auto *Prev = FormatTok->getPreviousNonComment();
4076 return Prev != ClassName && Prev->is(tok::identifier) &&
4077 Prev->isNot(Keywords.kw_final) && tryToParseBracedList();
4080 if (FormatTok->isOneOf(tok::colon, tok::less)) {
4081 int AngleNestingLevel = 0;
4083 if (FormatTok->is(tok::less))
4084 ++AngleNestingLevel;
4085 else if (FormatTok->is(tok::greater))
4086 --AngleNestingLevel;
4088 if (AngleNestingLevel == 0) {
4089 if (FormatTok->is(tok::colon)) {
4091 }
else if (!IsDerived && FormatTok->is(tok::identifier) &&
4092 FormatTok->Previous->is(tok::coloncolon)) {
4093 ClassName = FormatTok;
4094 }
else if (FormatTok->is(tok::l_paren) &&
4095 IsNonMacroIdentifier(FormatTok->Previous)) {
4099 if (FormatTok->is(tok::l_brace)) {
4100 if (AngleNestingLevel == 0 && IsListInitialization())
4102 calculateBraceTypes(
true);
4103 if (!tryToParseBracedList())
4106 if (FormatTok->is(tok::l_square)) {
4109 !
Previous->isTypeOrIdentifier(LangOpts))) {
4112 if (!tryToParseLambda())
4119 if (FormatTok->is(tok::semi))
4121 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
4124 parseCSharpGenericTypeConstraint();
4131 auto GetBraceTypes =
4132 [](
const FormatToken &RecordTok) -> std::pair<TokenType, TokenType> {
4133 switch (RecordTok.Tok.getKind()) {
4135 return {TT_ClassLBrace, TT_ClassRBrace};
4136 case tok::kw_struct:
4137 return {TT_StructLBrace, TT_StructRBrace};
4139 return {TT_UnionLBrace, TT_UnionRBrace};
4142 return {TT_RecordLBrace, TT_RecordRBrace};
4145 if (FormatTok->is(tok::l_brace)) {
4146 if (IsListInitialization())
4149 ClassName->setFinalizedType(TT_ClassHeadName);
4150 auto [OpenBraceType, ClosingBraceType] = GetBraceTypes(InitialToken);
4151 FormatTok->setFinalizedType(OpenBraceType);
4158 unsigned AddLevels = Style.IndentAccessModifiers ? 2u : 1u;
4159 parseBlock(
true, AddLevels,
false);
4161 setPreviousRBraceType(ClosingBraceType);
4168void UnwrappedLineParser::parseObjCMethod() {
4169 assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) &&
4170 "'(' or identifier expected.");
4172 if (FormatTok->is(tok::semi)) {
4176 }
else if (FormatTok->is(tok::l_brace)) {
4177 if (Style.BraceWrapping.AfterFunction)
4188void UnwrappedLineParser::parseObjCProtocolList() {
4189 assert(FormatTok->is(tok::less) &&
"'<' expected.");
4193 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4195 }
while (!
eof() && FormatTok->isNot(tok::greater));
4199void UnwrappedLineParser::parseObjCUntilAtEnd() {
4201 if (FormatTok->is(tok::objc_end)) {
4206 if (FormatTok->is(tok::l_brace)) {
4210 }
else if (FormatTok->is(tok::r_brace)) {
4214 }
else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
4218 parseStructuralElement();
4223void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
4224 assert(FormatTok->isOneOf(tok::objc_interface, tok::objc_implementation));
4230 if (FormatTok->is(tok::less))
4231 parseObjCLightweightGenerics();
4232 if (FormatTok->is(tok::colon)) {
4236 if (FormatTok->is(tok::less))
4237 parseObjCLightweightGenerics();
4238 }
else if (FormatTok->is(tok::l_paren)) {
4243 if (FormatTok->is(tok::less))
4244 parseObjCProtocolList();
4246 if (FormatTok->is(tok::l_brace)) {
4247 if (Style.BraceWrapping.AfterObjCDeclaration)
4256 parseObjCUntilAtEnd();
4259void UnwrappedLineParser::parseObjCLightweightGenerics() {
4260 assert(FormatTok->is(tok::less));
4268 unsigned NumOpenAngles = 1;
4272 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4274 if (FormatTok->is(tok::less)) {
4276 }
else if (FormatTok->is(tok::greater)) {
4277 assert(NumOpenAngles > 0 &&
"'>' makes NumOpenAngles negative");
4280 }
while (!
eof() && NumOpenAngles != 0);
4286bool UnwrappedLineParser::parseObjCProtocol() {
4287 assert(FormatTok->is(tok::objc_protocol));
4290 if (FormatTok->is(tok::l_paren)) {
4302 if (FormatTok->is(tok::less))
4303 parseObjCProtocolList();
4306 if (FormatTok->is(tok::semi)) {
4313 parseObjCUntilAtEnd();
4317void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
4318 bool IsImport = FormatTok->is(Keywords.kw_import);
4319 assert(IsImport || FormatTok->is(tok::kw_export));
4323 if (FormatTok->is(tok::kw_default))
4329 if (FormatTok->is(Keywords.kw_async))
4331 if (FormatTok->is(Keywords.kw_function)) {
4340 if (!IsImport && FormatTok->isNoneOf(tok::l_brace, tok::star) &&
4341 !FormatTok->isStringLiteral() &&
4342 !(FormatTok->is(Keywords.kw_type) &&
4343 Tokens->peekNextToken()->isOneOf(tok::l_brace, tok::star))) {
4348 if (FormatTok->is(tok::semi))
4350 if (
Line->Tokens.empty()) {
4355 if (FormatTok->is(tok::l_brace)) {
4356 FormatTok->setBlockKind(BK_Block);
4365void UnwrappedLineParser::parseStatementMacro() {
4367 if (FormatTok->is(tok::l_paren))
4369 if (FormatTok->is(tok::semi))
4374void UnwrappedLineParser::parseVerilogHierarchyIdentifier() {
4377 if (FormatTok->isOneOf(tok::star, tok::period, tok::periodstar,
4378 tok::coloncolon, tok::hash) ||
4379 Keywords.isVerilogIdentifier(*FormatTok)) {
4381 }
else if (FormatTok->is(tok::l_square)) {
4389void UnwrappedLineParser::parseVerilogSensitivityList() {
4390 if (FormatTok->isNot(tok::at))
4394 if (FormatTok->is(tok::at))
4396 switch (FormatTok->Tok.getKind()) {
4404 parseVerilogHierarchyIdentifier();
4409unsigned UnwrappedLineParser::parseVerilogHierarchyHeader() {
4410 unsigned AddLevels = 0;
4412 if (FormatTok->is(Keywords.kw_clocking)) {
4414 if (Keywords.isVerilogIdentifier(*FormatTok))
4416 parseVerilogSensitivityList();
4417 if (FormatTok->is(tok::semi))
4419 }
else if (FormatTok->isOneOf(tok::kw_case, Keywords.kw_casex,
4420 Keywords.kw_casez, Keywords.kw_randcase,
4421 Keywords.kw_randsequence)) {
4422 if (Style.IndentCaseLabels)
4425 if (FormatTok->is(tok::l_paren)) {
4426 FormatTok->setFinalizedType(TT_ConditionLParen);
4429 if (FormatTok->isOneOf(Keywords.kw_inside, Keywords.kw_matches))
4438 if (FormatTok->is(tok::l_square)) {
4439 auto Prev = FormatTok->getPreviousNonComment();
4440 if (Prev && Keywords.isVerilogIdentifier(*Prev))
4441 Prev->setFinalizedType(TT_VerilogDimensionedTypeName);
4443 }
else if (Keywords.isVerilogIdentifier(*FormatTok) ||
4444 FormatTok->isOneOf(tok::hash, tok::hashhash, tok::coloncolon,
4445 Keywords.kw_automatic, tok::kw_static)) {
4452 auto NewLine = [
this]() {
4454 Line->IsContinuation =
true;
4458 while (FormatTok->is(Keywords.kw_import)) {
4461 parseVerilogHierarchyIdentifier();
4462 if (FormatTok->is(tok::semi))
4467 if (FormatTok->is(Keywords.kw_verilogHash)) {
4470 if (FormatTok->is(tok::l_paren)) {
4471 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4475 if (FormatTok->is(tok::l_paren)) {
4477 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4482 if (FormatTok->is(Keywords.kw_extends)) {
4485 parseVerilogHierarchyIdentifier();
4486 if (FormatTok->is(tok::l_paren))
4489 if (FormatTok->is(Keywords.kw_implements)) {
4493 parseVerilogHierarchyIdentifier();
4494 }
while (FormatTok->is(tok::comma));
4498 if (FormatTok->is(tok::at)) {
4500 parseVerilogSensitivityList();
4503 if (FormatTok->is(tok::semi))
4511void UnwrappedLineParser::parseVerilogTable() {
4512 assert(FormatTok->is(Keywords.kw_table));
4516 auto InitialLevel =
Line->Level++;
4517 while (!
eof() && !Keywords.isVerilogEnd(*FormatTok)) {
4520 if (
Tok->
is(tok::semi))
4522 else if (
Tok->
isOneOf(tok::star, tok::colon, tok::question, tok::minus))
4523 Tok->setFinalizedType(TT_VerilogTableItem);
4525 Line->Level = InitialLevel;
4530void UnwrappedLineParser::parseVerilogCaseLabel() {
4536 auto OrigLevel =
Line->Level;
4537 auto FirstLine = CurrentLines->size();
4538 if (
Line->Level == 0 || (
Line->InPPDirective &&
Line->Level <= 1))
4540 else if (!Style.IndentCaseBlocks && Keywords.isVerilogBegin(*FormatTok))
4542 parseStructuralElement();
4545 if (CurrentLines->size() > FirstLine)
4546 (*CurrentLines)[FirstLine].Level = OrigLevel;
4547 Line->Level = OrigLevel;
4550void UnwrappedLineParser::parseVerilogExtern() {
4552 FormatTok->isOneOf(tok::kw_extern, tok::kw_export, Keywords.kw_import));
4555 if (FormatTok->is(tok::string_literal))
4557 if (FormatTok->isOneOf(Keywords.kw_context, Keywords.kw_pure))
4559 if (Keywords.isVerilogIdentifier(*FormatTok))
4561 if (FormatTok->is(tok::equal))
4563 if (Keywords.isVerilogHierarchy(*FormatTok))
4564 parseVerilogHierarchyHeader();
4567bool UnwrappedLineParser::containsExpansion(
const UnwrappedLine &
Line)
const {
4568 for (
const auto &N :
Line.Tokens) {
4569 if (N.Tok->MacroCtx)
4571 for (
const UnwrappedLine &Child : N.Children)
4572 if (containsExpansion(Child))
4578void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) {
4579 if (
Line->Tokens.empty())
4582 if (!parsingPPDirective()) {
4583 llvm::dbgs() <<
"Adding unwrapped line:\n";
4584 printDebugInfo(*
Line);
4592 bool ClosesWhitesmithsBlock =
4593 Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex &&
4594 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
4599 if (!parsingPPDirective() && !InExpansion && containsExpansion(*
Line)) {
4601 Reconstruct.emplace(
Line->Level, Unexpanded);
4602 Reconstruct->addLine(*
Line);
4607 CurrentExpandedLines.push_back(std::move(*
Line));
4609 if (Reconstruct->finished()) {
4610 UnwrappedLine Reconstructed = std::move(*Reconstruct).takeResult();
4611 assert(!Reconstructed.Tokens.empty() &&
4612 "Reconstructed must at least contain the macro identifier.");
4613 assert(!parsingPPDirective());
4615 llvm::dbgs() <<
"Adding unexpanded line:\n";
4616 printDebugInfo(Reconstructed);
4618 ExpandedLines[Reconstructed.Tokens.begin()->Tok] = CurrentExpandedLines;
4619 Lines.push_back(std::move(Reconstructed));
4620 CurrentExpandedLines.clear();
4621 Reconstruct.reset();
4626 assert(!Reconstruct || (CurrentLines != &Lines) || !PPStack.empty());
4627 CurrentLines->push_back(std::move(*
Line));
4629 Line->Tokens.clear();
4630 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
4631 Line->FirstStartColumn = 0;
4632 Line->IsContinuation =
false;
4633 Line->SeenDecltypeAuto =
false;
4635 if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove)
4637 if (!parsingPPDirective() && !PreprocessorDirectives.empty()) {
4638 CurrentLines->append(
4639 std::make_move_iterator(PreprocessorDirectives.begin()),
4640 std::make_move_iterator(PreprocessorDirectives.end()));
4641 PreprocessorDirectives.clear();
4644 FormatTok->Previous =
nullptr;
4647bool UnwrappedLineParser::eof()
const {
return FormatTok->is(tok::eof); }
4649bool UnwrappedLineParser::isOnNewLine(
const FormatToken &FormatTok) {
4650 return (
Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
4651 FormatTok.NewlinesBefore > 0;
4659 const llvm::Regex &CommentPragmasRegex) {
4660 if (
Line.Tokens.empty() || Style.ReflowComments != FormatStyle::RCS_Always)
4663 StringRef IndentContent = FormatTok.
TokenText;
4664 if (FormatTok.
TokenText.starts_with(
"//") ||
4665 FormatTok.
TokenText.starts_with(
"/*")) {
4666 IndentContent = FormatTok.
TokenText.substr(2);
4668 if (CommentPragmasRegex.match(IndentContent))
4743 if (PreviousToken && PreviousToken->
is(tok::l_brace) &&
4745 MinColumnToken = PreviousToken;
4748 PreviousToken = Node.
Tok;
4752 MinColumnToken = Node.
Tok;
4754 if (PreviousToken && PreviousToken->
is(tok::l_brace))
4755 MinColumnToken = PreviousToken;
4761void UnwrappedLineParser::flushComments(
bool NewlineBeforeNext) {
4762 bool JustComments =
Line->Tokens.empty();
4772 Tok->ContinuesLineCommentSection =
4773 continuesLineCommentSection(*
Tok, *
Line, Style, CommentPragmasRegex);
4774 if (isOnNewLine(*
Tok) && JustComments && !
Tok->ContinuesLineCommentSection)
4778 if (NewlineBeforeNext && JustComments)
4780 CommentsBeforeNextToken.clear();
4783void UnwrappedLineParser::nextToken(
int LevelDifference) {
4786 flushComments(isOnNewLine(*FormatTok));
4787 pushToken(FormatTok);
4789 if (!Style.isJavaScript())
4790 readToken(LevelDifference);
4792 readTokenWithJavaScriptASI();
4794 if (Style.isVerilog()) {
4801 if (Keywords.isVerilogEnd(*FormatTok))
4802 FormatTok->Tok.setKind(tok::r_brace);
4806void UnwrappedLineParser::distributeComments(
4826 if (Comments.empty())
4828 bool ShouldPushCommentsInCurrentLine =
true;
4829 bool HasTrailAlignedWithNextToken =
false;
4830 unsigned StartOfTrailAlignedWithNextToken = 0;
4833 for (
unsigned i = Comments.size() - 1; i > 0; --i) {
4835 HasTrailAlignedWithNextToken =
true;
4836 StartOfTrailAlignedWithNextToken = i;
4840 for (
unsigned i = 0, e = Comments.size(); i < e; ++i) {
4842 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
4843 FormatTok->ContinuesLineCommentSection =
false;
4846 *FormatTok, *
Line, Style, CommentPragmasRegex);
4848 if (!FormatTok->ContinuesLineCommentSection &&
4849 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
4850 ShouldPushCommentsInCurrentLine =
false;
4852 if (ShouldPushCommentsInCurrentLine)
4853 pushToken(FormatTok);
4855 CommentsBeforeNextToken.push_back(FormatTok);
4859void UnwrappedLineParser::readToken(
int LevelDifference) {
4861 bool PreviousWasComment =
false;
4862 bool FirstNonCommentOnLine =
false;
4864 FormatTok = Tokens->getNextToken();
4866 while (FormatTok->isOneOf(TT_ConflictStart, TT_ConflictEnd,
4867 TT_ConflictAlternative)) {
4868 if (FormatTok->is(TT_ConflictStart))
4869 conditionalCompilationStart(
false);
4870 else if (FormatTok->is(TT_ConflictAlternative))
4871 conditionalCompilationAlternative();
4872 else if (FormatTok->is(TT_ConflictEnd))
4873 conditionalCompilationEnd();
4874 FormatTok = Tokens->getNextToken();
4875 FormatTok->MustBreakBefore =
true;
4876 FormatTok->MustBreakBeforeFinalized =
true;
4879 auto IsFirstNonCommentOnLine = [](
bool FirstNonCommentOnLine,
4881 bool PreviousWasComment) {
4883 return Tok.HasUnescapedNewline ||
Tok.IsFirst;
4888 if (PreviousWasComment)
4889 return FirstNonCommentOnLine || IsFirstOnLine(
Tok);
4890 return IsFirstOnLine(
Tok);
4893 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
4894 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
4895 PreviousWasComment = FormatTok->is(tok::comment);
4897 while (!
Line->InPPDirective && FormatTok->is(tok::hash) &&
4898 FirstNonCommentOnLine) {
4901 const auto *
Next = Tokens->peekNextToken();
4902 if ((Style.isVerilog() && !Keywords.isVerilogPPDirective(*
Next)) ||
4903 (Style.isTableGen() &&
4904 Next->isNoneOf(tok::kw_else, tok::pp_define, tok::pp_ifdef,
4905 tok::pp_ifndef, tok::pp_endif))) {
4908 distributeComments(Comments, FormatTok);
4912 bool SwitchToPreprocessorLines = !
Line->Tokens.empty();
4913 ScopedLineState BlockState(*
this, SwitchToPreprocessorLines);
4914 assert((LevelDifference >= 0 ||
4915 static_cast<unsigned>(-LevelDifference) <=
Line->Level) &&
4916 "LevelDifference makes Line->Level negative");
4917 Line->Level += LevelDifference;
4921 if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash &&
4922 PPBranchLevel > 0) {
4923 Line->Level += PPBranchLevel;
4925 assert(
Line->Level >=
Line->UnbracedBodyLevel);
4926 Line->Level -=
Line->UnbracedBodyLevel;
4927 flushComments(isOnNewLine(*FormatTok));
4929 PreviousWasComment = FormatTok->is(tok::comment);
4930 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
4931 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
4934 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
4935 !
Line->InPPDirective) {
4939 if (FormatTok->is(tok::identifier) &&
4940 Macros.defined(FormatTok->TokenText) &&
4942 !
Line->InPPDirective) {
4944 unsigned Position = Tokens->getPosition();
4948 auto PreCall = std::move(
Line);
4949 Line.reset(
new UnwrappedLine);
4950 bool OldInExpansion = InExpansion;
4953 auto Args = parseMacroCall();
4954 InExpansion = OldInExpansion;
4955 assert(
Line->Tokens.front().Tok == ID);
4957 auto UnexpandedLine = std::move(
Line);
4959 Line = std::move(PreCall);
4962 llvm::dbgs() <<
"Macro call: " <<
ID->TokenText <<
"(";
4964 llvm::dbgs() <<
"(";
4965 for (
const auto &Arg : Args.value())
4966 for (
const auto &
T : Arg)
4967 llvm::dbgs() <<
T->TokenText <<
" ";
4968 llvm::dbgs() <<
")";
4970 llvm::dbgs() <<
"\n";
4972 if (
Macros.objectLike(
ID->TokenText) && Args &&
4973 !
Macros.hasArity(
ID->TokenText, Args->size())) {
4979 LLVM_DEBUG(llvm::dbgs()
4980 <<
"Macro \"" <<
ID->TokenText
4981 <<
"\" not overloaded for arity " << Args->size()
4982 <<
"or not function-like, using object-like overload.");
4984 UnexpandedLine->Tokens.resize(1);
4985 Tokens->setPosition(Position);
4987 assert(!Args &&
Macros.objectLike(
ID->TokenText));
4989 if ((!Args &&
Macros.objectLike(
ID->TokenText)) ||
4990 (Args &&
Macros.hasArity(
ID->TokenText, Args->size()))) {
4993 Unexpanded[
ID] = std::move(UnexpandedLine);
4995 Macros.expand(ID, std::move(Args));
4996 if (!Expansion.empty())
4997 FormatTok = Tokens->insertTokens(Expansion);
5000 llvm::dbgs() <<
"Expanded: ";
5001 for (
const auto &
T : Expansion)
5002 llvm::dbgs() <<
T->TokenText <<
" ";
5003 llvm::dbgs() <<
"\n";
5007 llvm::dbgs() <<
"Did not expand macro \"" <<
ID->TokenText
5008 <<
"\", because it was used ";
5010 llvm::dbgs() <<
"with " << Args->size();
5012 llvm::dbgs() <<
"without";
5013 llvm::dbgs() <<
" arguments, which doesn't match any definition.\n";
5015 Tokens->setPosition(Position);
5020 if (FormatTok->isNot(tok::comment)) {
5021 distributeComments(Comments, FormatTok);
5026 Comments.push_back(FormatTok);
5029 distributeComments(Comments,
nullptr);
5034template <
typename Iterator>
5035void pushTokens(Iterator Begin, Iterator End,
5037 for (
auto I = Begin; I != End; ++I) {
5038 Into.push_back(I->Tok);
5039 for (
const auto &Child : I->Children)
5040 pushTokens(Child.Tokens.begin(), Child.Tokens.end(), Into);
5045std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>
5046UnwrappedLineParser::parseMacroCall() {
5047 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>> Args;
5048 assert(
Line->Tokens.empty());
5050 if (FormatTok->isNot(tok::l_paren))
5052 unsigned Position = Tokens->getPosition();
5056 auto ArgStart = std::prev(
Line->Tokens.end());
5060 switch (FormatTok->Tok.getKind()) {
5065 case tok::r_paren: {
5071 Args->push_back({});
5072 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5081 Args->push_back({});
5082 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5084 ArgStart = std::prev(
Line->Tokens.end());
5092 Line->Tokens.resize(1);
5093 Tokens->setPosition(Position);
5099 Line->Tokens.push_back(UnwrappedLineNode(
Tok));
5100 if (AtEndOfPPLine) {
5101 auto &
Tok = *
Line->Tokens.back().Tok;
5102 Tok.MustBreakBefore =
true;
5103 Tok.MustBreakBeforeFinalized =
true;
5104 Tok.FirstAfterPPLine =
true;
5105 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
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',...
const FunctionProtoType * T
@ 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.