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());
63LLVM_ATTRIBUTE_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->isOneOf(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->isOneOf(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->isOneOf(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->isOneOf(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);
953 if (InitialToken.
is(TT_NamespaceMacro))
954 Kind = tok::kw_namespace;
957 case tok::kw_namespace:
958 return Style.BraceWrapping.AfterNamespace;
960 return Style.BraceWrapping.AfterClass;
962 return Style.BraceWrapping.AfterUnion;
964 return Style.BraceWrapping.AfterStruct;
966 return Style.BraceWrapping.AfterEnum;
972void UnwrappedLineParser::parseChildBlock() {
973 assert(FormatTok->is(tok::l_brace));
974 FormatTok->setBlockKind(BK_Block);
978 bool SkipIndent = (Style.isJavaScript() &&
979 (isGoogScope(*
Line) || isIIFE(*
Line, Keywords)));
980 ScopedLineState LineState(*
this);
981 ScopedDeclarationState DeclarationState(*
Line, DeclarationScopeStack,
983 Line->Level += SkipIndent ? 0 : 1;
984 parseLevel(OpeningBrace);
985 flushComments(isOnNewLine(*FormatTok));
986 Line->Level -= SkipIndent ? 0 : 1;
991void UnwrappedLineParser::parsePPDirective() {
992 assert(FormatTok->is(tok::hash) &&
"'#' expected");
993 ScopedMacroState MacroState(*
Line, Tokens, FormatTok);
997 if (!FormatTok->Tok.getIdentifierInfo()) {
1002 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
1003 case tok::pp_define:
1010 case tok::pp_ifndef:
1014 case tok::pp_elifdef:
1015 case tok::pp_elifndef:
1022 case tok::pp_pragma:
1026 case tok::pp_warning:
1028 if (!
eof() && Style.isCpp())
1029 FormatTok->setFinalizedType(TT_AfterPPDirective);
1037void UnwrappedLineParser::conditionalCompilationCondition(
bool Unreachable) {
1038 size_t Line = CurrentLines->size();
1039 if (CurrentLines == &PreprocessorDirectives)
1040 Line += Lines.size();
1043 (!PPStack.empty() && PPStack.back().Kind == PP_Unreachable)) {
1044 PPStack.push_back({PP_Unreachable,
Line});
1046 PPStack.push_back({PP_Conditional,
Line});
1050void UnwrappedLineParser::conditionalCompilationStart(
bool Unreachable) {
1052 assert(PPBranchLevel >= 0 && PPBranchLevel <= (
int)PPLevelBranchIndex.size());
1053 if (PPBranchLevel == (
int)PPLevelBranchIndex.size()) {
1054 PPLevelBranchIndex.push_back(0);
1055 PPLevelBranchCount.push_back(0);
1057 PPChainBranchIndex.push(Unreachable ? -1 : 0);
1058 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
1059 conditionalCompilationCondition(Unreachable ||
Skip);
1062void UnwrappedLineParser::conditionalCompilationAlternative() {
1063 if (!PPStack.empty())
1065 assert(PPBranchLevel < (
int)PPLevelBranchIndex.size());
1066 if (!PPChainBranchIndex.empty())
1067 ++PPChainBranchIndex.top();
1068 conditionalCompilationCondition(
1069 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
1070 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
1073void UnwrappedLineParser::conditionalCompilationEnd() {
1074 assert(PPBranchLevel < (
int)PPLevelBranchIndex.size());
1075 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
1076 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel])
1077 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
1080 if (PPBranchLevel > -1)
1082 if (!PPChainBranchIndex.empty())
1083 PPChainBranchIndex.pop();
1084 if (!PPStack.empty())
1088void UnwrappedLineParser::parsePPIf(
bool IfDef) {
1089 bool IfNDef = FormatTok->is(tok::pp_ifndef);
1091 bool Unreachable =
false;
1092 if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText ==
"0"))
1094 if (IfDef && !IfNDef && FormatTok->TokenText ==
"SWIG")
1096 conditionalCompilationStart(Unreachable);
1100 bool MaybeIncludeGuard = IfNDef;
1101 if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
1102 for (
auto &
Line : Lines) {
1103 if (
Line.Tokens.front().Tok->isNot(tok::comment)) {
1104 MaybeIncludeGuard =
false;
1105 IncludeGuard = IG_Rejected;
1113 if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
1114 IncludeGuard = IG_IfNdefed;
1115 IncludeGuardToken = IfCondition;
1119void UnwrappedLineParser::parsePPElse() {
1121 if (IncludeGuard == IG_Defined && PPBranchLevel == 0)
1122 IncludeGuard = IG_Rejected;
1124 assert(PPBranchLevel >= -1);
1125 if (PPBranchLevel == -1)
1126 conditionalCompilationStart(
true);
1127 conditionalCompilationAlternative();
1133void UnwrappedLineParser::parsePPEndIf() {
1134 conditionalCompilationEnd();
1138 if (IncludeGuard == IG_Defined && PPBranchLevel == -1 && Tokens->isEOF() &&
1139 getIncludeGuardState(Style.IndentPPDirectives) == IG_Inited) {
1140 IncludeGuard = IG_Found;
1144void UnwrappedLineParser::parsePPDefine() {
1147 if (!FormatTok->Tok.getIdentifierInfo()) {
1148 IncludeGuard = IG_Rejected;
1149 IncludeGuardToken =
nullptr;
1154 bool MaybeIncludeGuard =
false;
1155 if (IncludeGuard == IG_IfNdefed &&
1156 IncludeGuardToken->TokenText == FormatTok->TokenText) {
1157 IncludeGuard = IG_Defined;
1158 IncludeGuardToken =
nullptr;
1159 for (
auto &
Line : Lines) {
1160 if (!
Line.Tokens.front().Tok->isOneOf(tok::comment, tok::hash)) {
1161 IncludeGuard = IG_Rejected;
1165 MaybeIncludeGuard = IncludeGuard == IG_Defined;
1173 FormatTok->Tok.setKind(tok::identifier);
1174 FormatTok->Tok.setIdentifierInfo(Keywords.kw_internal_ident_after_define);
1178 if (MaybeIncludeGuard && !
eof())
1179 IncludeGuard = IG_Rejected;
1181 if (FormatTok->is(tok::l_paren) && !FormatTok->hasWhitespaceBefore())
1183 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
1184 Line->Level += PPBranchLevel + 1;
1188 Line->PPLevel = PPBranchLevel + (IncludeGuard == IG_Defined ? 0 : 1);
1189 assert((
int)
Line->PPLevel >= 0);
1194 Line->InMacroBody =
true;
1196 if (!Style.SkipMacroDefinitionBody) {
1206 for (
auto *Comment : CommentsBeforeNextToken)
1207 Comment->Finalized =
true;
1210 FormatTok->Finalized =
true;
1211 FormatTok = Tokens->getNextToken();
1217void UnwrappedLineParser::parsePPPragma() {
1218 Line->InPragmaDirective =
true;
1222void UnwrappedLineParser::parsePPUnknown() {
1225 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
1226 Line->Level += PPBranchLevel + 1;
1236 return !
Tok.isOneOf(tok::semi, tok::l_brace,
1239 tok::period, tok::periodstar, tok::arrow, tok::arrowstar,
1240 tok::less, tok::greater, tok::slash, tok::percent,
1241 tok::lessless, tok::greatergreater, tok::equal,
1242 tok::plusequal, tok::minusequal, tok::starequal,
1243 tok::slashequal, tok::percentequal, tok::ampequal,
1244 tok::pipeequal, tok::caretequal, tok::greatergreaterequal,
1257 return FormatTok->
is(tok::identifier) &&
1272 FormatTok->
isOneOf(tok::kw_true, tok::kw_false) ||
1283 tok::kw_if, tok::kw_else,
1285 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
1287 tok::kw_switch, tok::kw_case,
1289 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.
kw_finally,
1291 tok::kw_const, tok::kw_class, Keywords.
kw_var, Keywords.
kw_let,
1299 return Tok.isOneOf(tok::kw_char, tok::kw_short, tok::kw_int, tok::kw_long,
1300 tok::kw_unsigned, tok::kw_float, tok::kw_double,
1317 if (FuncName->
isNot(tok::identifier))
1325 !
Tok->isOneOf(tok::kw_register, tok::kw_struct, tok::kw_union)) {
1329 if (
Next->isNot(tok::star) && !
Next->Tok.getIdentifierInfo())
1333 if (!
Tok ||
Tok->isNot(tok::r_paren))
1337 if (!
Tok ||
Tok->isNot(tok::identifier))
1340 return Tok->Previous &&
Tok->Previous->isOneOf(tok::l_paren, tok::comma);
1343bool UnwrappedLineParser::parseModuleImport() {
1344 assert(FormatTok->is(Keywords.kw_import) &&
"'import' expected");
1346 if (
auto Token = Tokens->peekNextToken(
true);
1348 !
Token->
isOneOf(tok::colon, tok::less, tok::string_literal)) {
1354 if (FormatTok->is(tok::colon)) {
1355 FormatTok->setFinalizedType(TT_ModulePartitionColon);
1358 else if (FormatTok->is(tok::less)) {
1360 while (!FormatTok->isOneOf(tok::semi, tok::greater) && !
eof()) {
1363 if (FormatTok->isNot(tok::comment) &&
1364 !FormatTok->TokenText.starts_with(
"//")) {
1365 FormatTok->setFinalizedType(TT_ImplicitStringLiteral);
1370 if (FormatTok->is(tok::semi)) {
1388void UnwrappedLineParser::readTokenWithJavaScriptASI() {
1394 CommentsBeforeNextToken.empty()
1395 ?
Next->NewlinesBefore == 0
1396 : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
1401 bool PreviousStartsTemplateExpr =
1403 if (PreviousMustBeValue ||
Previous->is(tok::r_paren)) {
1406 bool HasAt = llvm::any_of(
Line->Tokens, [](UnwrappedLineNode &LineNode) {
1407 return LineNode.Tok->is(tok::at);
1412 if (
Next->is(tok::exclaim) && PreviousMustBeValue)
1413 return addUnwrappedLine();
1415 bool NextEndsTemplateExpr =
1416 Next->is(TT_TemplateString) &&
Next->TokenText.starts_with(
"}");
1417 if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
1418 (PreviousMustBeValue ||
1419 Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
1420 tok::minusminus))) {
1421 return addUnwrappedLine();
1423 if ((PreviousMustBeValue ||
Previous->is(tok::r_paren)) &&
1425 return addUnwrappedLine();
1429void UnwrappedLineParser::parseStructuralElement(
1430 const FormatToken *OpeningBrace, IfStmtKind *IfKind,
1431 FormatToken **IfLeftBrace,
bool *HasDoWhile,
bool *HasLabel) {
1432 if (Style.isTableGen() && FormatTok->is(tok::pp_include)) {
1434 if (FormatTok->is(tok::string_literal))
1441 while (FormatTok->is(tok::l_square) && handleCppAttributes()) {
1443 }
else if (Style.isVerilog()) {
1444 if (Keywords.isVerilogStructuredProcedure(*FormatTok)) {
1445 parseForOrWhileLoop(
false);
1448 if (FormatTok->isOneOf(Keywords.kw_foreach, Keywords.kw_repeat)) {
1449 parseForOrWhileLoop();
1452 if (FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
1453 Keywords.kw_assume, Keywords.kw_cover)) {
1454 parseIfThenElse(IfKind,
false,
true);
1460 if (FormatTok->isOneOf(Keywords.kw_priority, Keywords.kw_unique,
1461 Keywords.kw_unique0)) {
1463 }
else if (FormatTok->is(tok::l_paren) &&
1464 Tokens->peekNextToken()->is(tok::star)) {
1473 if (FormatTok->isAccessSpecifierKeyword()) {
1474 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp())
1477 parseAccessSpecifier();
1480 switch (FormatTok->Tok.getKind()) {
1483 if (FormatTok->is(tok::l_brace)) {
1484 FormatTok->setFinalizedType(TT_InlineASMBrace);
1486 while (FormatTok && !
eof()) {
1487 if (FormatTok->is(tok::r_brace)) {
1488 FormatTok->setFinalizedType(TT_InlineASMBrace);
1493 FormatTok->Finalized =
true;
1498 case tok::kw_namespace:
1502 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1513 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1517 parseForOrWhileLoop();
1520 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1528 case tok::kw_switch:
1529 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1535 case tok::kw_default: {
1537 if (Style.isVerilog())
1539 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1545 if (FormatTok->is(tok::colon)) {
1546 FormatTok->setFinalizedType(TT_CaseLabelColon);
1550 if (FormatTok->is(tok::arrow)) {
1551 FormatTok->setFinalizedType(TT_CaseLabelArrow);
1552 Default->setFinalizedType(TT_SwitchExpressionLabel);
1561 if (Style.Language == FormatStyle::LK_Proto) {
1565 if (Style.isVerilog()) {
1570 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1579 if (FormatTok->is(tok::kw_case))
1584 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1590 case tok::kw_extern:
1592 if (Style.isVerilog()) {
1595 if (Keywords.isVerilogHierarchy(*FormatTok)) {
1596 parseVerilogHierarchyHeader();
1599 }
else if (FormatTok->is(tok::string_literal)) {
1601 if (FormatTok->is(tok::l_brace)) {
1602 if (Style.BraceWrapping.AfterExternBlock)
1606 unsigned AddLevels =
1607 (Style.IndentExternBlock == FormatStyle::IEBS_Indent) ||
1608 (Style.BraceWrapping.AfterExternBlock &&
1609 Style.IndentExternBlock ==
1610 FormatStyle::IEBS_AfterExternBlock)
1613 parseBlock(
true, AddLevels);
1619 case tok::kw_export:
1620 if (Style.isJavaScript()) {
1621 parseJavaScriptEs6ImportExport();
1626 if (FormatTok->is(tok::kw_namespace)) {
1630 if (FormatTok->is(tok::l_brace)) {
1631 parseCppExportBlock();
1634 if (FormatTok->is(Keywords.kw_import) && parseModuleImport())
1638 case tok::kw_inline:
1640 if (FormatTok->is(tok::kw_namespace)) {
1645 case tok::identifier:
1646 if (FormatTok->is(TT_ForEachMacro)) {
1647 parseForOrWhileLoop();
1650 if (FormatTok->is(TT_MacroBlockBegin)) {
1651 parseBlock(
false, 1u,
1655 if (FormatTok->is(Keywords.kw_import)) {
1656 if (Style.isJavaScript()) {
1657 parseJavaScriptEs6ImportExport();
1660 if (Style.Language == FormatStyle::LK_Proto) {
1662 if (FormatTok->is(tok::kw_public))
1664 if (FormatTok->isNot(tok::string_literal))
1667 if (FormatTok->is(tok::semi))
1672 if (IsCpp && parseModuleImport())
1675 if (IsCpp && FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
1676 Keywords.kw_slots, Keywords.kw_qslots)) {
1678 if (FormatTok->is(tok::colon)) {
1684 if (IsCpp && FormatTok->is(TT_StatementMacro)) {
1685 parseStatementMacro();
1688 if (IsCpp && FormatTok->is(TT_NamespaceMacro)) {
1696 if (!Style.isJavaScript() && !Style.isVerilog() && !Style.isTableGen() &&
1697 Tokens->peekNextToken()->is(tok::colon) && !
Line->MustBeDeclaration) {
1699 if (!
Line->InMacroBody || CurrentLines->size() > 1)
1700 Line->Tokens.begin()->Tok->MustBreakBefore =
true;
1701 FormatTok->setFinalizedType(TT_GotoLabelColon);
1702 parseLabel(!Style.IndentGotoLabels);
1707 if (Style.isJava() && FormatTok->is(Keywords.kw_record)) {
1708 parseRecord(
false,
true);
1718 bool SeenEqual =
false;
1719 for (
const bool InRequiresExpression =
1720 OpeningBrace && OpeningBrace->isOneOf(TT_RequiresExpressionLBrace,
1721 TT_CompoundRequirementLBrace);
1724 switch (FormatTok->Tok.getKind()) {
1727 if (FormatTok->is(tok::l_brace)) {
1732 if (Style.isJava() && FormatTok->is(Keywords.kw_interface)) {
1736 switch (
bool IsAutoRelease =
false; FormatTok->Tok.getObjCKeywordID()) {
1737 case tok::objc_public:
1738 case tok::objc_protected:
1739 case tok::objc_package:
1740 case tok::objc_private:
1741 return parseAccessSpecifier();
1742 case tok::objc_interface:
1743 case tok::objc_implementation:
1744 return parseObjCInterfaceOrImplementation();
1745 case tok::objc_protocol:
1746 if (parseObjCProtocol())
1751 case tok::objc_optional:
1752 case tok::objc_required:
1756 case tok::objc_autoreleasepool:
1757 IsAutoRelease =
true;
1759 case tok::objc_synchronized:
1761 if (!IsAutoRelease && FormatTok->is(tok::l_paren)) {
1765 if (FormatTok->is(tok::l_brace)) {
1766 if (Style.BraceWrapping.AfterControlStatement ==
1767 FormatStyle::BWACS_Always) {
1783 case tok::kw_requires: {
1785 bool ParsedClause = parseRequires(SeenEqual);
1806 if (!IsCpp && !Style.isVerilog()) {
1811 case tok::kw_typedef:
1813 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1814 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS,
1815 Keywords.kw_CF_CLOSED_ENUM,
1816 Keywords.kw_NS_CLOSED_ENUM)) {
1821 if (Style.isVerilog()) {
1826 if (Style.isTableGen()) {
1833 case tok::kw_struct:
1835 if (parseStructLike())
1838 case tok::kw_decltype:
1840 if (FormatTok->is(tok::l_paren)) {
1842 if (FormatTok->Previous &&
1843 FormatTok->Previous->endsSequence(tok::r_paren, tok::kw_auto,
1845 Line->SeenDecltypeAuto =
true;
1852 if (Style.isJava() && FormatTok && FormatTok->is(tok::kw_class))
1854 if (Style.isJavaScript() && FormatTok &&
1855 FormatTok->Tok.getIdentifierInfo()) {
1868 case tok::l_paren: {
1875 Tokens->peekNextToken(
true),
1882 case tok::kw_operator:
1884 if (FormatTok->isBinaryOperator())
1888 const auto *Prev = FormatTok->getPreviousNonComment();
1890 if (Prev && Prev->is(tok::identifier))
1893 if (FormatTok->Tok.isAnyIdentifier() || FormatTok->isTypeName(LangOpts)) {
1896 while (FormatTok->is(tok::star))
1900 if (FormatTok->is(tok::l_paren))
1903 if (FormatTok->is(tok::l_brace))
1908 if (InRequiresExpression)
1909 FormatTok->setFinalizedType(TT_BracedListLBrace);
1910 if (!tryToParsePropertyAccessor() && !tryToParseBracedList()) {
1911 IsDecltypeAutoFunction =
Line->SeenDecltypeAuto;
1916 if (Style.isJava() &&
1917 Line->Tokens.front().Tok->is(Keywords.kw_synchronized)) {
1920 if (Style.BraceWrapping.AfterControlStatement ==
1921 FormatStyle::BWACS_Always) {
1924 }
else if (Style.BraceWrapping.AfterFunction) {
1928 FormatTok->setFinalizedType(TT_FunctionLBrace);
1930 IsDecltypeAutoFunction =
false;
1938 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1944 if (Style.BraceWrapping.AfterFunction)
1948 case tok::identifier: {
1949 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where) &&
1950 Line->MustBeDeclaration) {
1952 parseCSharpGenericTypeConstraint();
1955 if (FormatTok->is(TT_MacroBlockEnd)) {
1964 size_t TokenCount =
Line->Tokens.size();
1965 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_function) &&
1968 Line->Tokens.front().Tok->isNot(Keywords.kw_async)))) {
1969 tryToParseJSFunction();
1972 if ((Style.isJavaScript() || Style.isJava()) &&
1973 FormatTok->is(Keywords.kw_interface)) {
1974 if (Style.isJavaScript()) {
1979 unsigned StoredPosition = Tokens->getPosition();
1981 FormatTok = Tokens->setPosition(StoredPosition);
1992 if (Style.isVerilog()) {
1993 if (FormatTok->is(Keywords.kw_table)) {
1994 parseVerilogTable();
1997 if (Keywords.isVerilogBegin(*FormatTok) ||
1998 Keywords.isVerilogHierarchy(*FormatTok)) {
2005 if (!IsCpp && FormatTok->is(Keywords.kw_interface)) {
2006 if (parseStructLike())
2011 if (IsCpp && FormatTok->is(TT_StatementMacro)) {
2012 parseStatementMacro();
2017 StringRef
Text = FormatTok->TokenText;
2024 if (Style.isJavaScript())
2027 auto OneTokenSoFar = [&]() {
2028 auto I =
Line->Tokens.begin(), E =
Line->Tokens.end();
2029 while (I != E && I->Tok->is(tok::comment))
2031 if (Style.isVerilog())
2032 while (I != E && I->Tok->is(tok::hash))
2034 return I != E && (++I == E);
2036 if (OneTokenSoFar()) {
2039 bool FunctionLike = FormatTok->is(tok::l_paren);
2043 bool FollowedByNewline =
2044 CommentsBeforeNextToken.empty()
2045 ? FormatTok->NewlinesBefore > 0
2046 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
2048 if (FollowedByNewline &&
2049 (
Text.size() >= 5 ||
2050 (FunctionLike && FormatTok->isNot(tok::l_paren))) &&
2052 if (PreviousToken->isNot(TT_UntouchableMacroFunc))
2053 PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro);
2061 if ((Style.isJavaScript() || Style.isCSharp()) &&
2062 FormatTok->is(TT_FatArrow)) {
2063 tryToParseChildBlock();
2069 if (FormatTok->is(tok::l_brace)) {
2073 if (Style.isCSharp())
2074 FormatTok->setBlockKind(BK_BracedInit);
2077 if (Style.isTableGen() &&
2078 Line->Tokens.begin()->Tok->is(Keywords.kw_defset)) {
2079 FormatTok->setFinalizedType(TT_FunctionLBrace);
2080 parseBlock(
false, 1u,
2087 }
else if (Style.Language == FormatStyle::LK_Proto &&
2088 FormatTok->is(tok::less)) {
2090 parseBracedList(
true);
2097 if (Style.isCSharp() &&
2098 (Tokens->peekNextToken()->isAccessSpecifierKeyword() ||
2105 case tok::kw_switch:
2113 if (Style.Language == FormatStyle::LK_Proto) {
2118 if (Style.isVerilog()) {
2123 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
2130 case tok::kw_default:
2132 if (Style.isVerilog()) {
2133 if (FormatTok->is(tok::colon)) {
2137 if (FormatTok->is(Keywords.kw_clocking)) {
2143 parseVerilogCaseLabel();
2149 if (Style.isVerilog()) {
2150 parseVerilogCaseLabel();
2156 if (FormatTok->is(tok::l_brace))
2157 FormatTok->Previous->setFinalizedType(TT_TemplateCloser);
2166bool UnwrappedLineParser::tryToParsePropertyAccessor() {
2167 assert(FormatTok->is(tok::l_brace));
2168 if (!Style.isCSharp())
2171 if (!FormatTok->Previous || FormatTok->Previous->isNot(tok::identifier))
2179 unsigned int StoredPosition = Tokens->getPosition();
2185 bool HasSpecialAccessor =
false;
2186 bool IsTrivialPropertyAccessor =
true;
2189 if (
const bool IsAccessorKeyword =
2190 Tok->
isOneOf(Keywords.kw_get, Keywords.kw_init, Keywords.kw_set);
2191 IsAccessorKeyword ||
Tok->isAccessSpecifierKeyword() ||
2192 Tok->
isOneOf(tok::l_square, tok::semi, Keywords.kw_internal)) {
2193 if (IsAccessorKeyword)
2194 HasSpecialAccessor =
true;
2195 else if (
Tok->
is(tok::l_square))
2197 Tok = Tokens->getNextToken();
2201 IsTrivialPropertyAccessor =
false;
2206 Tokens->setPosition(StoredPosition);
2212 Tokens->setPosition(StoredPosition);
2213 if (!IsTrivialPropertyAccessor && Style.BraceWrapping.AfterFunction)
2217 switch (FormatTok->Tok.getKind()) {
2220 if (FormatTok->is(tok::equal)) {
2221 while (!
eof() && FormatTok->isNot(tok::semi))
2234 if (FormatTok->is(TT_FatArrow)) {
2238 }
while (!
eof() && FormatTok->isNot(tok::semi));
2247 if (FormatTok->isOneOf(Keywords.kw_get, Keywords.kw_init,
2249 !IsTrivialPropertyAccessor) {
2261bool UnwrappedLineParser::tryToParseLambda() {
2262 assert(FormatTok->is(tok::l_square));
2268 if (!tryToParseLambdaIntroducer())
2271 bool SeenArrow =
false;
2272 bool InTemplateParameterList =
false;
2274 while (FormatTok->isNot(tok::l_brace)) {
2275 if (FormatTok->isTypeName(LangOpts) || FormatTok->isAttribute()) {
2279 switch (FormatTok->Tok.getKind()) {
2283 parseParens(TT_PointerOrReference);
2289 assert(FormatTok->Previous);
2290 if (FormatTok->Previous->is(tok::r_square))
2291 InTemplateParameterList =
true;
2296 case tok::kw_struct:
2298 case tok::kw_template:
2299 case tok::kw_typename:
2303 case tok::kw_constexpr:
2304 case tok::kw_consteval:
2307 case tok::identifier:
2308 case tok::numeric_constant:
2309 case tok::coloncolon:
2310 case tok::kw_mutable:
2311 case tok::kw_noexcept:
2312 case tok::kw_static:
2337 case tok::equalequal:
2338 case tok::exclaimequal:
2339 case tok::greaterequal:
2340 case tok::lessequal:
2346 if (SeenArrow || InTemplateParameterList) {
2355 FormatTok->setFinalizedType(TT_LambdaArrow);
2359 case tok::kw_requires: {
2360 auto *RequiresToken = FormatTok;
2362 parseRequiresClause(RequiresToken);
2366 if (!InTemplateParameterList)
2375 FormatTok->setFinalizedType(TT_LambdaLBrace);
2376 LSquare.setFinalizedType(TT_LambdaLSquare);
2378 NestedLambdas.push_back(
Line->SeenDecltypeAuto);
2380 assert(!NestedLambdas.empty());
2381 NestedLambdas.pop_back();
2386bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
2391 if (
Previous->Tok.getIdentifierInfo() &&
2392 !
Previous->isOneOf(tok::kw_return, tok::kw_co_await, tok::kw_co_yield,
2393 tok::kw_co_return)) {
2400 const auto *BeforeRParen =
Previous->getPreviousNonComment();
2403 if (!BeforeRParen || !BeforeRParen->isOneOf(tok::greater, tok::r_paren))
2407 if (LeftSquare->isCppStructuredBinding(IsCpp))
2409 if (FormatTok->is(tok::l_square) ||
tok::isLiteral(FormatTok->Tok.getKind()))
2411 if (FormatTok->is(tok::r_square)) {
2413 if (
Next->is(tok::greater))
2420void UnwrappedLineParser::tryToParseJSFunction() {
2421 assert(FormatTok->is(Keywords.kw_function));
2422 if (FormatTok->is(Keywords.kw_async))
2428 if (FormatTok->is(tok::star)) {
2429 FormatTok->setFinalizedType(TT_OverloadedOperator);
2434 if (FormatTok->is(tok::identifier))
2437 if (FormatTok->isNot(tok::l_paren))
2443 if (FormatTok->is(tok::colon)) {
2449 if (FormatTok->is(tok::l_brace))
2450 tryToParseBracedList();
2452 while (!FormatTok->isOneOf(tok::l_brace, tok::semi) && !
eof())
2456 if (FormatTok->is(tok::semi))
2462bool UnwrappedLineParser::tryToParseBracedList() {
2463 if (FormatTok->is(BK_Unknown))
2464 calculateBraceTypes();
2465 assert(FormatTok->isNot(BK_Unknown));
2466 if (FormatTok->is(BK_Block))
2473bool UnwrappedLineParser::tryToParseChildBlock() {
2474 assert(Style.isJavaScript() || Style.isCSharp());
2475 assert(FormatTok->is(TT_FatArrow));
2480 if (FormatTok->isNot(tok::l_brace))
2486bool UnwrappedLineParser::parseBracedList(
bool IsAngleBracket,
bool IsEnum) {
2487 assert(!IsAngleBracket || !IsEnum);
2488 bool HasError =
false;
2493 if (Style.isCSharp() && FormatTok->is(TT_FatArrow) &&
2494 tryToParseChildBlock()) {
2497 if (Style.isJavaScript()) {
2498 if (FormatTok->is(Keywords.kw_function)) {
2499 tryToParseJSFunction();
2502 if (FormatTok->is(tok::l_brace)) {
2504 if (tryToParseBracedList())
2509 if (FormatTok->is(IsAngleBracket ? tok::greater : tok::r_brace)) {
2511 FormatTok->setBlockKind(BK_Block);
2512 if (!Style.AllowShortEnumsOnASingleLine)
2518 switch (FormatTok->Tok.getKind()) {
2520 if (Style.isCSharp())
2529 if (Style.isJavaScript()) {
2530 if (FormatTok->is(tok::l_brace))
2538 FormatTok->setBlockKind(BK_BracedInit);
2539 if (!IsAngleBracket) {
2540 auto *Prev = FormatTok->Previous;
2541 if (Prev && Prev->is(tok::greater))
2542 Prev->setFinalizedType(TT_TemplateCloser);
2550 parseBracedList(
true);
2557 if (Style.isJavaScript()) {
2568 if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
2584bool UnwrappedLineParser::parseParens(TokenType AmpAmpTokenType,
2586 assert(FormatTok->is(tok::l_paren) &&
"'(' expected.");
2587 auto *LParen = FormatTok;
2588 auto *Prev = FormatTok->Previous;
2589 bool SeenComma =
false;
2590 bool SeenEqual =
false;
2591 bool MightBeFoldExpr =
false;
2593 const bool MightBeStmtExpr = FormatTok->is(tok::l_brace);
2594 if (!InMacroCall && Prev && Prev->is(TT_FunctionLikeMacro))
2597 switch (FormatTok->Tok.getKind()) {
2599 if (parseParens(AmpAmpTokenType, InMacroCall))
2601 if (Style.isJava() && FormatTok->is(tok::l_brace))
2604 case tok::r_paren: {
2605 auto *RParen = FormatTok;
2608 auto OptionalParens = [&] {
2609 if (MightBeStmtExpr || MightBeFoldExpr || SeenComma || InMacroCall ||
2610 Line->InMacroBody ||
2611 Style.RemoveParentheses == FormatStyle::RPS_Leave ||
2612 RParen->getPreviousNonComment() == LParen) {
2615 const bool DoubleParens =
2616 Prev->is(tok::l_paren) && FormatTok->is(tok::r_paren);
2618 const auto *PrevPrev = Prev->getPreviousNonComment();
2619 const bool Excluded =
2621 (PrevPrev->isOneOf(tok::kw___attribute, tok::kw_decltype) ||
2623 (PrevPrev->isOneOf(tok::kw_if, tok::kw_while) ||
2624 PrevPrev->endsSequence(tok::kw_constexpr, tok::kw_if))));
2628 const bool CommaSeparated =
2629 Prev->isOneOf(tok::l_paren, tok::comma) &&
2630 FormatTok->isOneOf(tok::comma, tok::r_paren);
2631 if (CommaSeparated &&
2633 !Prev->endsSequence(tok::comma, tok::ellipsis) &&
2635 !(FormatTok->is(tok::comma) &&
2636 Tokens->peekNextToken()->is(tok::ellipsis))) {
2639 const bool ReturnParens =
2640 Style.RemoveParentheses == FormatStyle::RPS_ReturnStatement &&
2641 ((NestedLambdas.empty() && !IsDecltypeAutoFunction) ||
2642 (!NestedLambdas.empty() && !NestedLambdas.back())) &&
2643 Prev->isOneOf(tok::kw_return, tok::kw_co_return) &&
2644 FormatTok->is(tok::semi);
2650 if (Prev->is(TT_TypenameMacro)) {
2651 LParen->setFinalizedType(TT_TypeDeclarationParen);
2652 RParen->setFinalizedType(TT_TypeDeclarationParen);
2653 }
else if (Prev->is(tok::greater) && RParen->Previous == LParen) {
2654 Prev->setFinalizedType(TT_TemplateCloser);
2655 }
else if (OptionalParens()) {
2656 LParen->Optional =
true;
2657 RParen->Optional =
true;
2669 if (!tryToParseBracedList())
2674 if (FormatTok->is(tok::l_brace)) {
2684 MightBeFoldExpr =
true;
2689 if (Style.isCSharp() && FormatTok->is(TT_FatArrow))
2690 tryToParseChildBlock();
2695 if (Style.isJavaScript())
2700 case tok::identifier:
2701 if (Style.isJavaScript() && (FormatTok->is(Keywords.kw_function)))
2702 tryToParseJSFunction();
2706 case tok::kw_switch:
2712 case tok::kw_requires: {
2713 auto RequiresToken = FormatTok;
2715 parseRequiresExpression(RequiresToken);
2719 if (AmpAmpTokenType != TT_Unknown)
2720 FormatTok->setFinalizedType(AmpAmpTokenType);
2732 assert(FormatTok->is(tok::l_square) &&
"'[' expected.");
2733 if (tryToParseLambda())
2737 switch (FormatTok->Tok.getKind()) {
2750 case tok::l_brace: {
2751 if (!tryToParseBracedList())
2758 if (FormatTok->is(tok::l_brace)) {
2770void UnwrappedLineParser::keepAncestorBraces() {
2771 if (!Style.RemoveBracesLLVM)
2774 const int MaxNestingLevels = 2;
2775 const int Size = NestedTooDeep.size();
2776 if (Size >= MaxNestingLevels)
2777 NestedTooDeep[
Size - MaxNestingLevels] =
true;
2778 NestedTooDeep.push_back(
false);
2782 for (
const auto &
Token : llvm::reverse(
Line.Tokens))
2789void UnwrappedLineParser::parseUnbracedBody(
bool CheckEOF) {
2792 if (Style.InsertBraces && !
Line->InPPDirective && !
Line->Tokens.empty() &&
2793 PreprocessorDirectives.empty() && FormatTok->isNot(tok::semi)) {
2794 Tok = Style.BraceWrapping.AfterControlStatement == FormatStyle::BWACS_Never
2795 ? getLastNonComment(*
Line)
2798 if (
Tok->BraceCount < 0) {
2799 assert(
Tok->BraceCount == -1);
2802 Tok->BraceCount = -1;
2808 ++
Line->UnbracedBodyLevel;
2809 parseStructuralElement();
2810 --
Line->UnbracedBodyLevel;
2813 assert(!
Line->InPPDirective);
2815 for (
const auto &L : llvm::reverse(*CurrentLines)) {
2817 Tok = L.Tokens.back().Tok;
2825 if (CheckEOF &&
eof())
2835 assert(LeftBrace->
is(tok::l_brace));
2843 assert(RightBrace->
is(tok::r_brace));
2851void UnwrappedLineParser::handleAttributes() {
2853 if (FormatTok->isAttribute())
2855 else if (FormatTok->is(tok::l_square))
2856 handleCppAttributes();
2859bool UnwrappedLineParser::handleCppAttributes() {
2861 assert(FormatTok->is(tok::l_square));
2862 if (!tryToParseSimpleAttribute())
2869bool UnwrappedLineParser::isBlockBegin(
const FormatToken &
Tok)
const {
2872 return Style.isVerilog() ? Keywords.isVerilogBegin(
Tok)
2873 :
Tok.
is(tok::l_brace);
2876FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
2878 bool IsVerilogAssert) {
2879 assert((FormatTok->is(tok::kw_if) ||
2880 (Style.isVerilog() &&
2881 FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
2882 Keywords.kw_assume, Keywords.kw_cover))) &&
2886 if (IsVerilogAssert) {
2888 if (FormatTok->is(Keywords.kw_verilogHash)) {
2890 if (FormatTok->is(tok::numeric_constant))
2892 }
else if (FormatTok->isOneOf(Keywords.kw_final, Keywords.kw_property,
2893 Keywords.kw_sequence)) {
2899 if (Style.isTableGen()) {
2900 while (!
eof() && FormatTok->isNot(Keywords.kw_then)) {
2907 if (FormatTok->is(tok::exclaim))
2910 bool KeepIfBraces =
true;
2911 if (FormatTok->is(tok::kw_consteval)) {
2914 KeepIfBraces = !Style.RemoveBracesLLVM || KeepBraces;
2915 if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
2917 if (FormatTok->is(tok::l_paren)) {
2918 FormatTok->setFinalizedType(TT_ConditionLParen);
2924 if (IsVerilogAssert && FormatTok->is(tok::semi)) {
2930 bool NeedsUnwrappedLine =
false;
2931 keepAncestorBraces();
2934 IfStmtKind IfBlockKind = IfStmtKind::NotIf;
2936 if (isBlockBegin(*FormatTok)) {
2937 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
2938 IfLeftBrace = FormatTok;
2939 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
2940 parseBlock(
false, 1u,
2941 true, KeepIfBraces, &IfBlockKind);
2942 setPreviousRBraceType(TT_ControlStatementRBrace);
2943 if (Style.BraceWrapping.BeforeElse)
2946 NeedsUnwrappedLine =
true;
2947 }
else if (IsVerilogAssert && FormatTok->is(tok::kw_else)) {
2950 parseUnbracedBody();
2953 if (Style.RemoveBracesLLVM) {
2954 assert(!NestedTooDeep.empty());
2955 KeepIfBraces = KeepIfBraces ||
2956 (IfLeftBrace && !IfLeftBrace->MatchingParen) ||
2957 NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly ||
2958 IfBlockKind == IfStmtKind::IfElseIf;
2961 bool KeepElseBraces = KeepIfBraces;
2963 IfStmtKind
Kind = IfStmtKind::IfOnly;
2965 if (FormatTok->is(tok::kw_else)) {
2966 if (Style.RemoveBracesLLVM) {
2967 NestedTooDeep.back() =
false;
2968 Kind = IfStmtKind::IfElse;
2972 if (isBlockBegin(*FormatTok)) {
2973 const bool FollowedByIf = Tokens->peekNextToken()->is(tok::kw_if);
2974 FormatTok->setFinalizedType(TT_ElseLBrace);
2975 ElseLeftBrace = FormatTok;
2976 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
2977 IfStmtKind ElseBlockKind = IfStmtKind::NotIf;
2979 parseBlock(
false, 1u,
2980 true, KeepElseBraces, &ElseBlockKind);
2981 setPreviousRBraceType(TT_ElseRBrace);
2982 if (FormatTok->is(tok::kw_else)) {
2983 KeepElseBraces = KeepElseBraces ||
2984 ElseBlockKind == IfStmtKind::IfOnly ||
2985 ElseBlockKind == IfStmtKind::IfElseIf;
2986 }
else if (FollowedByIf && IfLBrace && !IfLBrace->Optional) {
2987 KeepElseBraces =
true;
2988 assert(ElseLeftBrace->MatchingParen);
2992 }
else if (!IsVerilogAssert && FormatTok->is(tok::kw_if)) {
2995 const bool IsPrecededByComment =
Previous->is(tok::comment);
2996 if (IsPrecededByComment) {
3000 bool TooDeep =
true;
3001 if (Style.RemoveBracesLLVM) {
3002 Kind = IfStmtKind::IfElseIf;
3003 TooDeep = NestedTooDeep.pop_back_val();
3005 ElseLeftBrace = parseIfThenElse(
nullptr, KeepIfBraces);
3006 if (Style.RemoveBracesLLVM)
3007 NestedTooDeep.push_back(TooDeep);
3008 if (IsPrecededByComment)
3011 parseUnbracedBody(
true);
3014 KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse;
3015 if (NeedsUnwrappedLine)
3019 if (!Style.RemoveBracesLLVM)
3022 assert(!NestedTooDeep.empty());
3023 KeepElseBraces = KeepElseBraces ||
3024 (ElseLeftBrace && !ElseLeftBrace->MatchingParen) ||
3025 NestedTooDeep.back();
3027 NestedTooDeep.pop_back();
3029 if (!KeepIfBraces && !KeepElseBraces) {
3032 }
else if (IfLeftBrace) {
3033 FormatToken *IfRightBrace = IfLeftBrace->MatchingParen;
3035 assert(IfRightBrace->MatchingParen == IfLeftBrace);
3036 assert(!IfLeftBrace->Optional);
3037 assert(!IfRightBrace->Optional);
3038 IfLeftBrace->MatchingParen =
nullptr;
3039 IfRightBrace->MatchingParen =
nullptr;
3049void UnwrappedLineParser::parseTryCatch() {
3050 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) &&
"'try' expected");
3052 bool NeedsUnwrappedLine =
false;
3053 bool HasCtorInitializer =
false;
3054 if (FormatTok->is(tok::colon)) {
3055 auto *Colon = FormatTok;
3058 if (FormatTok->is(tok::identifier)) {
3059 HasCtorInitializer =
true;
3060 Colon->setFinalizedType(TT_CtorInitializerColon);
3065 while (FormatTok->is(tok::comma))
3068 while (FormatTok->is(tok::identifier)) {
3070 if (FormatTok->is(tok::l_paren)) {
3072 }
else if (FormatTok->is(tok::l_brace)) {
3079 while (FormatTok->is(tok::comma))
3084 if (Style.isJava() && FormatTok->is(tok::l_paren))
3087 keepAncestorBraces();
3089 if (FormatTok->is(tok::l_brace)) {
3090 if (HasCtorInitializer)
3091 FormatTok->setFinalizedType(TT_FunctionLBrace);
3092 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3094 if (Style.BraceWrapping.BeforeCatch)
3097 NeedsUnwrappedLine =
true;
3098 }
else if (FormatTok->isNot(tok::kw_catch)) {
3104 parseStructuralElement();
3107 for (
bool SeenCatch =
false;;) {
3108 if (FormatTok->is(tok::at))
3110 if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
3111 tok::kw___finally, tok::objc_catch,
3112 tok::objc_finally) ||
3113 ((Style.isJava() || Style.isJavaScript()) &&
3114 FormatTok->is(Keywords.kw_finally)))) {
3117 if (FormatTok->is(tok::kw_catch))
3120 while (FormatTok->isNot(tok::l_brace)) {
3121 if (FormatTok->is(tok::l_paren)) {
3125 if (FormatTok->isOneOf(tok::semi, tok::r_brace) ||
eof()) {
3126 if (Style.RemoveBracesLLVM)
3127 NestedTooDeep.pop_back();
3133 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3136 NeedsUnwrappedLine =
false;
3137 Line->MustBeDeclaration =
false;
3138 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3140 if (Style.BraceWrapping.BeforeCatch)
3143 NeedsUnwrappedLine =
true;
3146 if (Style.RemoveBracesLLVM)
3147 NestedTooDeep.pop_back();
3149 if (NeedsUnwrappedLine)
3153void UnwrappedLineParser::parseNamespaceOrExportBlock(
unsigned AddLevels) {
3154 bool ManageWhitesmithsBraces =
3155 AddLevels == 0u && Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
3159 if (ManageWhitesmithsBraces)
3164 parseBlock(
true, AddLevels,
true,
3165 true,
nullptr, ManageWhitesmithsBraces);
3167 addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep);
3169 if (ManageWhitesmithsBraces)
3173void UnwrappedLineParser::parseNamespace() {
3174 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
3175 "'namespace' expected");
3179 if (InitialToken.is(TT_NamespaceMacro)) {
3182 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
3183 tok::l_square, tok::period, tok::l_paren) ||
3184 (Style.isCSharp() && FormatTok->is(tok::kw_union))) {
3185 if (FormatTok->is(tok::l_square))
3187 else if (FormatTok->is(tok::l_paren))
3193 if (FormatTok->is(tok::l_brace)) {
3194 FormatTok->setFinalizedType(TT_NamespaceLBrace);
3199 unsigned AddLevels =
3200 Style.NamespaceIndentation == FormatStyle::NI_All ||
3201 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
3202 DeclarationScopeStack.size() > 1)
3205 parseNamespaceOrExportBlock(AddLevels);
3210void UnwrappedLineParser::parseCppExportBlock() {
3211 parseNamespaceOrExportBlock(Style.IndentExportBlock ? 1 : 0);
3214void UnwrappedLineParser::parseNew() {
3215 assert(FormatTok->is(tok::kw_new) &&
"'new' expected");
3218 if (Style.isCSharp()) {
3221 if (FormatTok->is(tok::l_paren))
3225 if (FormatTok->is(tok::l_brace))
3228 if (FormatTok->isOneOf(tok::semi, tok::comma))
3235 if (!Style.isJava())
3241 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
3245 if (FormatTok->is(tok::l_paren)) {
3249 if (FormatTok->is(tok::l_brace))
3257void UnwrappedLineParser::parseLoopBody(
bool KeepBraces,
bool WrapRightBrace) {
3258 keepAncestorBraces();
3260 if (isBlockBegin(*FormatTok)) {
3261 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3263 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3264 parseBlock(
false, 1u,
3266 setPreviousRBraceType(TT_ControlStatementRBrace);
3268 assert(!NestedTooDeep.empty());
3269 if (!NestedTooDeep.back())
3275 parseUnbracedBody();
3279 NestedTooDeep.pop_back();
3282void UnwrappedLineParser::parseForOrWhileLoop(
bool HasParens) {
3283 assert((FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) ||
3284 (Style.isVerilog() &&
3285 FormatTok->isOneOf(Keywords.kw_always, Keywords.kw_always_comb,
3286 Keywords.kw_always_ff, Keywords.kw_always_latch,
3287 Keywords.kw_final, Keywords.kw_initial,
3288 Keywords.kw_foreach, Keywords.kw_forever,
3289 Keywords.kw_repeat))) &&
3290 "'for', 'while' or foreach macro expected");
3291 const bool KeepBraces = !Style.RemoveBracesLLVM ||
3292 !FormatTok->isOneOf(tok::kw_for, tok::kw_while);
3296 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
3298 if (IsCpp && FormatTok->is(tok::kw_co_await))
3300 if (HasParens && FormatTok->is(tok::l_paren)) {
3304 if (Style.isVerilog())
3305 FormatTok->setFinalizedType(TT_ConditionLParen);
3309 if (Style.isVerilog()) {
3311 parseVerilogSensitivityList();
3312 }
else if (Style.AllowShortLoopsOnASingleLine && FormatTok->is(tok::semi) &&
3313 Tokens->getPreviousToken()->is(tok::r_paren)) {
3320 parseLoopBody(KeepBraces,
true);
3323void UnwrappedLineParser::parseDoWhile() {
3324 assert(FormatTok->is(tok::kw_do) &&
"'do' expected");
3327 parseLoopBody(
true, Style.BraceWrapping.BeforeWhile);
3330 if (FormatTok->isNot(tok::kw_while)) {
3335 FormatTok->setFinalizedType(TT_DoWhile);
3339 if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)
3343 parseStructuralElement();
3346void UnwrappedLineParser::parseLabel(
bool LeftAlignLabel) {
3348 unsigned OldLineLevel =
Line->Level;
3352 else if (
Line->Level > 1 || (!
Line->InPPDirective &&
Line->Level > 0))
3355 if (!Style.IndentCaseBlocks && CommentsBeforeNextToken.empty() &&
3356 FormatTok->is(tok::l_brace)) {
3358 CompoundStatementIndenter Indenter(
this,
Line->Level,
3359 Style.BraceWrapping.AfterCaseLabel,
3360 Style.BraceWrapping.IndentBraces);
3362 if (FormatTok->is(tok::kw_break)) {
3363 if (Style.BraceWrapping.AfterControlStatement ==
3364 FormatStyle::BWACS_Always) {
3366 if (!Style.IndentCaseBlocks &&
3367 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) {
3371 parseStructuralElement();
3375 if (FormatTok->is(tok::semi))
3379 Line->Level = OldLineLevel;
3380 if (FormatTok->isNot(tok::l_brace)) {
3381 parseStructuralElement();
3386void UnwrappedLineParser::parseCaseLabel() {
3387 assert(FormatTok->is(tok::kw_case) &&
"'case' expected");
3388 auto *Case = FormatTok;
3393 if (FormatTok->is(tok::colon)) {
3394 FormatTok->setFinalizedType(TT_CaseLabelColon);
3397 if (Style.isJava() && FormatTok->is(tok::arrow)) {
3398 FormatTok->setFinalizedType(TT_CaseLabelArrow);
3399 Case->setFinalizedType(TT_SwitchExpressionLabel);
3406void UnwrappedLineParser::parseSwitch(
bool IsExpr) {
3407 assert(FormatTok->is(tok::kw_switch) &&
"'switch' expected");
3409 if (FormatTok->is(tok::l_paren))
3412 keepAncestorBraces();
3414 if (FormatTok->is(tok::l_brace)) {
3415 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3416 FormatTok->setFinalizedType(IsExpr ? TT_SwitchExpressionLBrace
3417 : TT_ControlStatementLBrace);
3422 setPreviousRBraceType(TT_ControlStatementRBrace);
3428 parseStructuralElement();
3432 if (Style.RemoveBracesLLVM)
3433 NestedTooDeep.pop_back();
3436void UnwrappedLineParser::parseAccessSpecifier() {
3439 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
3442 if (FormatTok->is(tok::colon))
3450bool UnwrappedLineParser::parseRequires(
bool SeenEqual) {
3451 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3452 auto RequiresToken = FormatTok;
3458 switch (FormatTok->Tok.getKind()) {
3461 parseRequiresExpression(RequiresToken);
3468 parseRequiresClause(RequiresToken);
3479 auto *PreviousNonComment = RequiresToken->getPreviousNonComment();
3481 if (!PreviousNonComment ||
3482 PreviousNonComment->is(TT_RequiresExpressionLBrace)) {
3485 parseRequiresClause(RequiresToken);
3489 switch (PreviousNonComment->Tok.getKind()) {
3492 case tok::kw_noexcept:
3497 parseRequiresClause(RequiresToken);
3506 auto PrevPrev = PreviousNonComment->getPreviousNonComment();
3507 if ((PrevPrev && PrevPrev->is(tok::kw_const)) || !SeenEqual) {
3508 parseRequiresClause(RequiresToken);
3514 if (PreviousNonComment->isTypeOrIdentifier(LangOpts)) {
3516 parseRequiresClause(RequiresToken);
3520 parseRequiresExpression(RequiresToken);
3530 unsigned StoredPosition = Tokens->getPosition();
3533 auto PeekNext = [&Lookahead, &NextToken,
this] {
3535 NextToken = Tokens->getNextToken();
3538 bool FoundType =
false;
3539 bool LastWasColonColon =
false;
3542 for (; Lookahead < 50; PeekNext()) {
3543 switch (NextToken->Tok.getKind()) {
3544 case tok::kw_volatile:
3547 if (OpenAngles == 0) {
3548 FormatTok = Tokens->setPosition(StoredPosition);
3549 parseRequiresExpression(RequiresToken);
3557 case tok::coloncolon:
3558 LastWasColonColon =
true;
3560 case tok::kw_decltype:
3561 case tok::identifier:
3562 if (FoundType && !LastWasColonColon && OpenAngles == 0) {
3563 FormatTok = Tokens->setPosition(StoredPosition);
3564 parseRequiresExpression(RequiresToken);
3568 LastWasColonColon =
false;
3577 if (NextToken->isTypeName(LangOpts)) {
3578 FormatTok = Tokens->setPosition(StoredPosition);
3579 parseRequiresExpression(RequiresToken);
3586 FormatTok = Tokens->setPosition(StoredPosition);
3587 parseRequiresClause(RequiresToken);
3598void UnwrappedLineParser::parseRequiresClause(
FormatToken *RequiresToken) {
3599 assert(FormatTok->getPreviousNonComment() == RequiresToken);
3600 assert(RequiresToken->is(tok::kw_requires) &&
"'requires' expected");
3605 bool InRequiresExpression =
3606 !RequiresToken->Previous ||
3607 RequiresToken->Previous->is(TT_RequiresExpressionLBrace);
3609 RequiresToken->setFinalizedType(InRequiresExpression
3610 ? TT_RequiresClauseInARequiresExpression
3611 : TT_RequiresClause);
3615 parseConstraintExpression();
3617 if (!InRequiresExpression && FormatTok->Previous)
3618 FormatTok->Previous->ClosesRequiresClause =
true;
3628void UnwrappedLineParser::parseRequiresExpression(
FormatToken *RequiresToken) {
3629 assert(FormatTok->getPreviousNonComment() == RequiresToken);
3630 assert(RequiresToken->is(tok::kw_requires) &&
"'requires' expected");
3632 RequiresToken->setFinalizedType(TT_RequiresExpression);
3634 if (FormatTok->is(tok::l_paren)) {
3635 FormatTok->setFinalizedType(TT_RequiresExpressionLParen);
3639 if (FormatTok->is(tok::l_brace)) {
3640 FormatTok->setFinalizedType(TT_RequiresExpressionLBrace);
3649void UnwrappedLineParser::parseConstraintExpression() {
3656 bool LambdaNextTimeAllowed =
true;
3666 bool TopLevelParensAllowed =
true;
3669 bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed,
false);
3671 switch (FormatTok->Tok.getKind()) {
3672 case tok::kw_requires: {
3673 auto RequiresToken = FormatTok;
3675 parseRequiresExpression(RequiresToken);
3680 if (!TopLevelParensAllowed)
3682 parseParens(TT_BinaryOperator);
3683 TopLevelParensAllowed =
false;
3687 if (!LambdaThisTimeAllowed || !tryToParseLambda())
3694 case tok::kw_struct:
3704 FormatTok->setFinalizedType(TT_BinaryOperator);
3706 LambdaNextTimeAllowed =
true;
3707 TopLevelParensAllowed =
true;
3712 LambdaNextTimeAllowed = LambdaThisTimeAllowed;
3716 case tok::kw_sizeof:
3718 case tok::greaterequal:
3719 case tok::greatergreater:
3721 case tok::lessequal:
3723 case tok::equalequal:
3725 case tok::exclaimequal:
3730 LambdaNextTimeAllowed =
true;
3731 TopLevelParensAllowed =
true;
3736 case tok::numeric_constant:
3737 case tok::coloncolon:
3740 TopLevelParensAllowed =
false;
3745 case tok::kw_static_cast:
3746 case tok::kw_const_cast:
3747 case tok::kw_reinterpret_cast:
3748 case tok::kw_dynamic_cast:
3750 if (FormatTok->isNot(tok::less))
3754 parseBracedList(
true);
3758 if (!FormatTok->Tok.getIdentifierInfo()) {
3768 assert(FormatTok->Previous);
3769 switch (FormatTok->Previous->Tok.getKind()) {
3770 case tok::coloncolon:
3774 case tok::kw_requires:
3783 if (FormatTok->is(tok::less)) {
3785 parseBracedList(
true);
3787 TopLevelParensAllowed =
false;
3793bool UnwrappedLineParser::parseEnum() {
3797 if (FormatTok->is(tok::kw_enum))
3803 if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question))
3807 if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal))
3812 if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
3814 while (FormatTok->is(tok::l_square))
3815 if (!handleCppAttributes())
3819 while (FormatTok->Tok.getIdentifierInfo() ||
3820 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
3821 tok::greater, tok::comma, tok::question,
3823 if (Style.isVerilog()) {
3824 FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
3827 while (FormatTok->is(tok::l_square))
3833 if (FormatTok->is(tok::l_paren))
3835 if (FormatTok->is(tok::identifier)) {
3839 if (IsCpp && FormatTok->is(tok::identifier))
3845 if (FormatTok->isNot(tok::l_brace))
3847 FormatTok->setFinalizedType(TT_EnumLBrace);
3848 FormatTok->setBlockKind(BK_Block);
3850 if (Style.isJava()) {
3852 parseJavaEnumBody();
3855 if (Style.Language == FormatStyle::LK_Proto) {
3860 if (!Style.AllowShortEnumsOnASingleLine &&
3866 if (!Style.AllowShortEnumsOnASingleLine) {
3870 bool HasError = !parseBracedList(
false,
true);
3871 if (!Style.AllowShortEnumsOnASingleLine)
3874 if (FormatTok->is(tok::semi))
3878 setPreviousRBraceType(TT_EnumRBrace);
3886bool UnwrappedLineParser::parseStructLike() {
3891 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp()) {
3892 if (FormatTok->is(tok::semi))
3903class ScopedTokenPosition {
3904 unsigned StoredPosition;
3905 FormatTokenSource *Tokens;
3908 ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) {
3909 assert(Tokens &&
"Tokens expected to not be null");
3910 StoredPosition = Tokens->getPosition();
3913 ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); }
3919bool UnwrappedLineParser::tryToParseSimpleAttribute() {
3920 ScopedTokenPosition AutoPosition(Tokens);
3928 if (
Tok->
is(tok::r_square))
3930 Tok = Tokens->getNextToken();
3932 if (
Tok->
is(tok::eof))
3934 Tok = Tokens->getNextToken();
3937 Tok = Tokens->getNextToken();
3938 if (
Tok->
is(tok::semi))
3943void UnwrappedLineParser::parseJavaEnumBody() {
3944 assert(FormatTok->is(tok::l_brace));
3950 unsigned StoredPosition = Tokens->getPosition();
3951 bool IsSimple =
true;
3954 if (
Tok->
is(tok::r_brace))
3962 Tok = Tokens->getNextToken();
3964 FormatTok = Tokens->setPosition(StoredPosition);
3981 if (FormatTok->is(tok::l_brace)) {
3983 parseBlock(
true, 1u,
3985 }
else if (FormatTok->is(tok::l_paren)) {
3987 }
else if (FormatTok->is(tok::comma)) {
3990 }
else if (FormatTok->is(tok::semi)) {
3994 }
else if (FormatTok->is(tok::r_brace)) {
4003 parseLevel(OpeningBrace);
4009void UnwrappedLineParser::parseRecord(
bool ParseAsExpr,
bool IsJavaRecord) {
4010 assert(!IsJavaRecord || FormatTok->is(Keywords.kw_record));
4015 IsJavaRecord && FormatTok->is(tok::identifier) ? FormatTok :
nullptr;
4016 bool IsDerived =
false;
4018 return Tok->
is(tok::identifier) &&
Tok->TokenText !=
Tok->TokenText.upper();
4022 bool JSPastExtendsOrImplements =
false;
4026 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
4027 tok::kw_alignas, tok::l_square) ||
4028 FormatTok->isAttribute() ||
4029 ((Style.isJava() || Style.isJavaScript()) &&
4030 FormatTok->isOneOf(tok::period, tok::comma))) {
4031 if (Style.isJavaScript() &&
4032 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
4033 JSPastExtendsOrImplements =
true;
4038 if (FormatTok->is(tok::l_brace)) {
4039 tryToParseBracedList();
4043 if (FormatTok->is(tok::l_square) && handleCppAttributes())
4047 switch (FormatTok->Tok.getKind()) {
4050 if (IsJavaRecord || !IsNonMacroIdentifier(
Previous) ||
4052 Previous->Previous == &InitialToken) {
4056 case tok::coloncolon:
4060 if (JSPastExtendsOrImplements || ClassName ||
4071 auto IsListInitialization = [&] {
4072 if (!ClassName || IsDerived || JSPastExtendsOrImplements)
4074 assert(FormatTok->is(tok::l_brace));
4075 const auto *Prev = FormatTok->getPreviousNonComment();
4077 return Prev != ClassName && Prev->is(tok::identifier) &&
4078 Prev->isNot(Keywords.kw_final) && tryToParseBracedList();
4081 if (FormatTok->isOneOf(tok::colon, tok::less)) {
4082 int AngleNestingLevel = 0;
4084 if (FormatTok->is(tok::less))
4085 ++AngleNestingLevel;
4086 else if (FormatTok->is(tok::greater))
4087 --AngleNestingLevel;
4089 if (AngleNestingLevel == 0) {
4090 if (FormatTok->is(tok::colon)) {
4092 }
else if (!IsDerived && FormatTok->is(tok::identifier) &&
4093 FormatTok->Previous->is(tok::coloncolon)) {
4094 ClassName = FormatTok;
4095 }
else if (FormatTok->is(tok::l_paren) &&
4096 IsNonMacroIdentifier(FormatTok->Previous)) {
4100 if (FormatTok->is(tok::l_brace)) {
4101 if (AngleNestingLevel == 0 && IsListInitialization())
4103 calculateBraceTypes(
true);
4104 if (!tryToParseBracedList())
4107 if (FormatTok->is(tok::l_square)) {
4110 !
Previous->isTypeOrIdentifier(LangOpts))) {
4113 if (!tryToParseLambda())
4120 if (FormatTok->is(tok::semi))
4122 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
4125 parseCSharpGenericTypeConstraint();
4132 auto GetBraceTypes =
4133 [](
const FormatToken &RecordTok) -> std::pair<TokenType, TokenType> {
4134 switch (RecordTok.Tok.getKind()) {
4136 return {TT_ClassLBrace, TT_ClassRBrace};
4137 case tok::kw_struct:
4138 return {TT_StructLBrace, TT_StructRBrace};
4140 return {TT_UnionLBrace, TT_UnionRBrace};
4143 return {TT_RecordLBrace, TT_RecordRBrace};
4146 if (FormatTok->is(tok::l_brace)) {
4147 if (IsListInitialization())
4150 ClassName->setFinalizedType(TT_ClassHeadName);
4151 auto [OpenBraceType, ClosingBraceType] = GetBraceTypes(InitialToken);
4152 FormatTok->setFinalizedType(OpenBraceType);
4159 unsigned AddLevels = Style.IndentAccessModifiers ? 2u : 1u;
4160 parseBlock(
true, AddLevels,
false);
4162 setPreviousRBraceType(ClosingBraceType);
4169void UnwrappedLineParser::parseObjCMethod() {
4170 assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) &&
4171 "'(' or identifier expected.");
4173 if (FormatTok->is(tok::semi)) {
4177 }
else if (FormatTok->is(tok::l_brace)) {
4178 if (Style.BraceWrapping.AfterFunction)
4189void UnwrappedLineParser::parseObjCProtocolList() {
4190 assert(FormatTok->is(tok::less) &&
"'<' expected.");
4194 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4196 }
while (!
eof() && FormatTok->isNot(tok::greater));
4200void UnwrappedLineParser::parseObjCUntilAtEnd() {
4202 if (FormatTok->is(tok::objc_end)) {
4207 if (FormatTok->is(tok::l_brace)) {
4211 }
else if (FormatTok->is(tok::r_brace)) {
4215 }
else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
4219 parseStructuralElement();
4224void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
4225 assert(FormatTok->isOneOf(tok::objc_interface, tok::objc_implementation));
4231 if (FormatTok->is(tok::less))
4232 parseObjCLightweightGenerics();
4233 if (FormatTok->is(tok::colon)) {
4237 if (FormatTok->is(tok::less))
4238 parseObjCLightweightGenerics();
4239 }
else if (FormatTok->is(tok::l_paren)) {
4244 if (FormatTok->is(tok::less))
4245 parseObjCProtocolList();
4247 if (FormatTok->is(tok::l_brace)) {
4248 if (Style.BraceWrapping.AfterObjCDeclaration)
4257 parseObjCUntilAtEnd();
4260void UnwrappedLineParser::parseObjCLightweightGenerics() {
4261 assert(FormatTok->is(tok::less));
4269 unsigned NumOpenAngles = 1;
4273 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4275 if (FormatTok->is(tok::less)) {
4277 }
else if (FormatTok->is(tok::greater)) {
4278 assert(NumOpenAngles > 0 &&
"'>' makes NumOpenAngles negative");
4281 }
while (!
eof() && NumOpenAngles != 0);
4287bool UnwrappedLineParser::parseObjCProtocol() {
4288 assert(FormatTok->is(tok::objc_protocol));
4291 if (FormatTok->is(tok::l_paren)) {
4303 if (FormatTok->is(tok::less))
4304 parseObjCProtocolList();
4307 if (FormatTok->is(tok::semi)) {
4314 parseObjCUntilAtEnd();
4318void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
4319 bool IsImport = FormatTok->is(Keywords.kw_import);
4320 assert(IsImport || FormatTok->is(tok::kw_export));
4324 if (FormatTok->is(tok::kw_default))
4330 if (FormatTok->is(Keywords.kw_async))
4332 if (FormatTok->is(Keywords.kw_function)) {
4341 if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) &&
4342 !FormatTok->isStringLiteral() &&
4343 !(FormatTok->is(Keywords.kw_type) &&
4344 Tokens->peekNextToken()->isOneOf(tok::l_brace, tok::star))) {
4349 if (FormatTok->is(tok::semi))
4351 if (
Line->Tokens.empty()) {
4356 if (FormatTok->is(tok::l_brace)) {
4357 FormatTok->setBlockKind(BK_Block);
4366void UnwrappedLineParser::parseStatementMacro() {
4368 if (FormatTok->is(tok::l_paren))
4370 if (FormatTok->is(tok::semi))
4375void UnwrappedLineParser::parseVerilogHierarchyIdentifier() {
4378 if (FormatTok->isOneOf(tok::star, tok::period, tok::periodstar,
4379 tok::coloncolon, tok::hash) ||
4380 Keywords.isVerilogIdentifier(*FormatTok)) {
4382 }
else if (FormatTok->is(tok::l_square)) {
4390void UnwrappedLineParser::parseVerilogSensitivityList() {
4391 if (FormatTok->isNot(tok::at))
4395 if (FormatTok->is(tok::at))
4397 switch (FormatTok->Tok.getKind()) {
4405 parseVerilogHierarchyIdentifier();
4410unsigned UnwrappedLineParser::parseVerilogHierarchyHeader() {
4411 unsigned AddLevels = 0;
4413 if (FormatTok->is(Keywords.kw_clocking)) {
4415 if (Keywords.isVerilogIdentifier(*FormatTok))
4417 parseVerilogSensitivityList();
4418 if (FormatTok->is(tok::semi))
4420 }
else if (FormatTok->isOneOf(tok::kw_case, Keywords.kw_casex,
4421 Keywords.kw_casez, Keywords.kw_randcase,
4422 Keywords.kw_randsequence)) {
4423 if (Style.IndentCaseLabels)
4426 if (FormatTok->is(tok::l_paren)) {
4427 FormatTok->setFinalizedType(TT_ConditionLParen);
4430 if (FormatTok->isOneOf(Keywords.kw_inside, Keywords.kw_matches))
4439 if (FormatTok->is(tok::l_square)) {
4440 auto Prev = FormatTok->getPreviousNonComment();
4441 if (Prev && Keywords.isVerilogIdentifier(*Prev))
4442 Prev->setFinalizedType(TT_VerilogDimensionedTypeName);
4444 }
else if (Keywords.isVerilogIdentifier(*FormatTok) ||
4445 FormatTok->isOneOf(tok::hash, tok::hashhash, tok::coloncolon,
4446 Keywords.kw_automatic, tok::kw_static)) {
4453 auto NewLine = [
this]() {
4455 Line->IsContinuation =
true;
4459 while (FormatTok->is(Keywords.kw_import)) {
4462 parseVerilogHierarchyIdentifier();
4463 if (FormatTok->is(tok::semi))
4468 if (FormatTok->is(Keywords.kw_verilogHash)) {
4471 if (FormatTok->is(tok::l_paren)) {
4472 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4476 if (FormatTok->is(tok::l_paren)) {
4478 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4483 if (FormatTok->is(Keywords.kw_extends)) {
4486 parseVerilogHierarchyIdentifier();
4487 if (FormatTok->is(tok::l_paren))
4490 if (FormatTok->is(Keywords.kw_implements)) {
4494 parseVerilogHierarchyIdentifier();
4495 }
while (FormatTok->is(tok::comma));
4499 if (FormatTok->is(tok::at)) {
4501 parseVerilogSensitivityList();
4504 if (FormatTok->is(tok::semi))
4512void UnwrappedLineParser::parseVerilogTable() {
4513 assert(FormatTok->is(Keywords.kw_table));
4517 auto InitialLevel =
Line->Level++;
4518 while (!
eof() && !Keywords.isVerilogEnd(*FormatTok)) {
4521 if (
Tok->
is(tok::semi))
4523 else if (
Tok->
isOneOf(tok::star, tok::colon, tok::question, tok::minus))
4524 Tok->setFinalizedType(TT_VerilogTableItem);
4526 Line->Level = InitialLevel;
4531void UnwrappedLineParser::parseVerilogCaseLabel() {
4537 auto OrigLevel =
Line->Level;
4538 auto FirstLine = CurrentLines->size();
4539 if (
Line->Level == 0 || (
Line->InPPDirective &&
Line->Level <= 1))
4541 else if (!Style.IndentCaseBlocks && Keywords.isVerilogBegin(*FormatTok))
4543 parseStructuralElement();
4546 if (CurrentLines->size() > FirstLine)
4547 (*CurrentLines)[FirstLine].Level = OrigLevel;
4548 Line->Level = OrigLevel;
4551bool UnwrappedLineParser::containsExpansion(
const UnwrappedLine &
Line)
const {
4552 for (
const auto &N :
Line.Tokens) {
4553 if (N.Tok->MacroCtx)
4555 for (
const UnwrappedLine &Child : N.Children)
4556 if (containsExpansion(Child))
4562void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) {
4563 if (
Line->Tokens.empty())
4566 if (!parsingPPDirective()) {
4567 llvm::dbgs() <<
"Adding unwrapped line:\n";
4568 printDebugInfo(*
Line);
4576 bool ClosesWhitesmithsBlock =
4577 Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex &&
4578 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
4583 if (!parsingPPDirective() && !InExpansion && containsExpansion(*
Line)) {
4585 Reconstruct.emplace(
Line->Level, Unexpanded);
4586 Reconstruct->addLine(*
Line);
4591 CurrentExpandedLines.push_back(std::move(*
Line));
4593 if (Reconstruct->finished()) {
4594 UnwrappedLine Reconstructed = std::move(*Reconstruct).takeResult();
4595 assert(!Reconstructed.Tokens.empty() &&
4596 "Reconstructed must at least contain the macro identifier.");
4597 assert(!parsingPPDirective());
4599 llvm::dbgs() <<
"Adding unexpanded line:\n";
4600 printDebugInfo(Reconstructed);
4602 ExpandedLines[Reconstructed.Tokens.begin()->Tok] = CurrentExpandedLines;
4603 Lines.push_back(std::move(Reconstructed));
4604 CurrentExpandedLines.clear();
4605 Reconstruct.reset();
4610 assert(!Reconstruct || (CurrentLines != &Lines) || !PPStack.empty());
4611 CurrentLines->push_back(std::move(*
Line));
4613 Line->Tokens.clear();
4614 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
4615 Line->FirstStartColumn = 0;
4616 Line->IsContinuation =
false;
4617 Line->SeenDecltypeAuto =
false;
4619 if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove)
4621 if (!parsingPPDirective() && !PreprocessorDirectives.empty()) {
4622 CurrentLines->append(
4623 std::make_move_iterator(PreprocessorDirectives.begin()),
4624 std::make_move_iterator(PreprocessorDirectives.end()));
4625 PreprocessorDirectives.clear();
4628 FormatTok->Previous =
nullptr;
4631bool UnwrappedLineParser::eof()
const {
return FormatTok->is(tok::eof); }
4633bool UnwrappedLineParser::isOnNewLine(
const FormatToken &FormatTok) {
4634 return (
Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
4635 FormatTok.NewlinesBefore > 0;
4643 const llvm::Regex &CommentPragmasRegex) {
4644 if (
Line.Tokens.empty() || Style.ReflowComments != FormatStyle::RCS_Always)
4647 StringRef IndentContent = FormatTok.
TokenText;
4648 if (FormatTok.
TokenText.starts_with(
"//") ||
4649 FormatTok.
TokenText.starts_with(
"/*")) {
4650 IndentContent = FormatTok.
TokenText.substr(2);
4652 if (CommentPragmasRegex.match(IndentContent))
4727 if (PreviousToken && PreviousToken->
is(tok::l_brace) &&
4729 MinColumnToken = PreviousToken;
4732 PreviousToken = Node.
Tok;
4736 MinColumnToken = Node.
Tok;
4738 if (PreviousToken && PreviousToken->
is(tok::l_brace))
4739 MinColumnToken = PreviousToken;
4745void UnwrappedLineParser::flushComments(
bool NewlineBeforeNext) {
4746 bool JustComments =
Line->Tokens.empty();
4756 Tok->ContinuesLineCommentSection =
4757 continuesLineCommentSection(*
Tok, *
Line, Style, CommentPragmasRegex);
4758 if (isOnNewLine(*
Tok) && JustComments && !
Tok->ContinuesLineCommentSection)
4762 if (NewlineBeforeNext && JustComments)
4764 CommentsBeforeNextToken.clear();
4767void UnwrappedLineParser::nextToken(
int LevelDifference) {
4770 flushComments(isOnNewLine(*FormatTok));
4771 pushToken(FormatTok);
4773 if (!Style.isJavaScript())
4774 readToken(LevelDifference);
4776 readTokenWithJavaScriptASI();
4778 if (Style.isVerilog()) {
4785 if (Keywords.isVerilogEnd(*FormatTok))
4786 FormatTok->Tok.setKind(tok::r_brace);
4790void UnwrappedLineParser::distributeComments(
4810 if (Comments.empty())
4812 bool ShouldPushCommentsInCurrentLine =
true;
4813 bool HasTrailAlignedWithNextToken =
false;
4814 unsigned StartOfTrailAlignedWithNextToken = 0;
4817 for (
unsigned i = Comments.size() - 1; i > 0; --i) {
4819 HasTrailAlignedWithNextToken =
true;
4820 StartOfTrailAlignedWithNextToken = i;
4824 for (
unsigned i = 0, e = Comments.size(); i < e; ++i) {
4826 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
4827 FormatTok->ContinuesLineCommentSection =
false;
4830 *FormatTok, *
Line, Style, CommentPragmasRegex);
4832 if (!FormatTok->ContinuesLineCommentSection &&
4833 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
4834 ShouldPushCommentsInCurrentLine =
false;
4836 if (ShouldPushCommentsInCurrentLine)
4837 pushToken(FormatTok);
4839 CommentsBeforeNextToken.push_back(FormatTok);
4843void UnwrappedLineParser::readToken(
int LevelDifference) {
4845 bool PreviousWasComment =
false;
4846 bool FirstNonCommentOnLine =
false;
4848 FormatTok = Tokens->getNextToken();
4850 while (FormatTok->isOneOf(TT_ConflictStart, TT_ConflictEnd,
4851 TT_ConflictAlternative)) {
4852 if (FormatTok->is(TT_ConflictStart))
4853 conditionalCompilationStart(
false);
4854 else if (FormatTok->is(TT_ConflictAlternative))
4855 conditionalCompilationAlternative();
4856 else if (FormatTok->is(TT_ConflictEnd))
4857 conditionalCompilationEnd();
4858 FormatTok = Tokens->getNextToken();
4859 FormatTok->MustBreakBefore =
true;
4860 FormatTok->MustBreakBeforeFinalized =
true;
4863 auto IsFirstNonCommentOnLine = [](
bool FirstNonCommentOnLine,
4865 bool PreviousWasComment) {
4867 return Tok.HasUnescapedNewline ||
Tok.IsFirst;
4872 if (PreviousWasComment)
4873 return FirstNonCommentOnLine || IsFirstOnLine(
Tok);
4874 return IsFirstOnLine(
Tok);
4877 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
4878 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
4879 PreviousWasComment = FormatTok->is(tok::comment);
4881 while (!
Line->InPPDirective && FormatTok->is(tok::hash) &&
4882 FirstNonCommentOnLine) {
4885 const auto *
Next = Tokens->peekNextToken();
4886 if ((Style.isVerilog() && !Keywords.isVerilogPPDirective(*
Next)) ||
4887 (Style.isTableGen() &&
4888 !
Next->isOneOf(tok::kw_else, tok::pp_define, tok::pp_ifdef,
4889 tok::pp_ifndef, tok::pp_endif))) {
4892 distributeComments(Comments, FormatTok);
4896 bool SwitchToPreprocessorLines = !
Line->Tokens.empty();
4897 ScopedLineState BlockState(*
this, SwitchToPreprocessorLines);
4898 assert((LevelDifference >= 0 ||
4899 static_cast<unsigned>(-LevelDifference) <=
Line->Level) &&
4900 "LevelDifference makes Line->Level negative");
4901 Line->Level += LevelDifference;
4905 if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash &&
4906 PPBranchLevel > 0) {
4907 Line->Level += PPBranchLevel;
4909 assert(
Line->Level >=
Line->UnbracedBodyLevel);
4910 Line->Level -=
Line->UnbracedBodyLevel;
4911 flushComments(isOnNewLine(*FormatTok));
4913 PreviousWasComment = FormatTok->is(tok::comment);
4914 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
4915 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
4918 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
4919 !
Line->InPPDirective) {
4923 if (FormatTok->is(tok::identifier) &&
4924 Macros.defined(FormatTok->TokenText) &&
4926 !
Line->InPPDirective) {
4928 unsigned Position = Tokens->getPosition();
4932 auto PreCall = std::move(
Line);
4933 Line.reset(
new UnwrappedLine);
4934 bool OldInExpansion = InExpansion;
4937 auto Args = parseMacroCall();
4938 InExpansion = OldInExpansion;
4939 assert(
Line->Tokens.front().Tok == ID);
4941 auto UnexpandedLine = std::move(
Line);
4943 Line = std::move(PreCall);
4946 llvm::dbgs() <<
"Macro call: " <<
ID->TokenText <<
"(";
4948 llvm::dbgs() <<
"(";
4949 for (
const auto &Arg : Args.value())
4950 for (
const auto &
T : Arg)
4951 llvm::dbgs() <<
T->TokenText <<
" ";
4952 llvm::dbgs() <<
")";
4954 llvm::dbgs() <<
"\n";
4956 if (
Macros.objectLike(
ID->TokenText) && Args &&
4957 !
Macros.hasArity(
ID->TokenText, Args->size())) {
4963 LLVM_DEBUG(llvm::dbgs()
4964 <<
"Macro \"" <<
ID->TokenText
4965 <<
"\" not overloaded for arity " << Args->size()
4966 <<
"or not function-like, using object-like overload.");
4968 UnexpandedLine->Tokens.resize(1);
4969 Tokens->setPosition(Position);
4971 assert(!Args &&
Macros.objectLike(
ID->TokenText));
4973 if ((!Args &&
Macros.objectLike(
ID->TokenText)) ||
4974 (Args &&
Macros.hasArity(
ID->TokenText, Args->size()))) {
4977 Unexpanded[
ID] = std::move(UnexpandedLine);
4979 Macros.expand(ID, std::move(Args));
4980 if (!Expansion.empty())
4981 FormatTok = Tokens->insertTokens(Expansion);
4984 llvm::dbgs() <<
"Expanded: ";
4985 for (
const auto &
T : Expansion)
4986 llvm::dbgs() <<
T->TokenText <<
" ";
4987 llvm::dbgs() <<
"\n";
4991 llvm::dbgs() <<
"Did not expand macro \"" <<
ID->TokenText
4992 <<
"\", because it was used ";
4994 llvm::dbgs() <<
"with " << Args->size();
4996 llvm::dbgs() <<
"without";
4997 llvm::dbgs() <<
" arguments, which doesn't match any definition.\n";
4999 Tokens->setPosition(Position);
5004 if (FormatTok->isNot(tok::comment)) {
5005 distributeComments(Comments, FormatTok);
5010 Comments.push_back(FormatTok);
5013 distributeComments(Comments,
nullptr);
5018template <
typename Iterator>
5019void pushTokens(Iterator Begin, Iterator End,
5021 for (
auto I = Begin; I != End; ++I) {
5022 Into.push_back(I->Tok);
5023 for (
const auto &Child : I->Children)
5024 pushTokens(Child.Tokens.begin(), Child.Tokens.end(), Into);
5029std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>
5030UnwrappedLineParser::parseMacroCall() {
5031 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>> Args;
5032 assert(
Line->Tokens.empty());
5034 if (FormatTok->isNot(tok::l_paren))
5036 unsigned Position = Tokens->getPosition();
5040 auto ArgStart = std::prev(
Line->Tokens.end());
5044 switch (FormatTok->Tok.getKind()) {
5049 case tok::r_paren: {
5055 Args->push_back({});
5056 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5065 Args->push_back({});
5066 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5068 ArgStart = std::prev(
Line->Tokens.end());
5076 Line->Tokens.resize(1);
5077 Tokens->setPosition(Position);
5083 Line->Tokens.push_back(UnwrappedLineNode(
Tok));
5084 if (AtEndOfPPLine) {
5085 auto &
Tok = *
Line->Tokens.back().Tok;
5086 Tok.MustBreakBefore =
true;
5087 Tok.MustBreakBeforeFinalized =
true;
5088 Tok.FirstAfterPPLine =
true;
5089 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.