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);
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->isNoneOf(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.isNoneOf(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->isNoneOf(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->isNoneOf(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->isNoneOf(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())
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 (Arrow || InTemplateParameterList) {
2355 case tok::kw_requires: {
2356 auto *RequiresToken = FormatTok;
2358 parseRequiresClause(RequiresToken);
2362 if (!InTemplateParameterList)
2371 FormatTok->setFinalizedType(TT_LambdaLBrace);
2372 LSquare.setFinalizedType(TT_LambdaLSquare);
2375 Arrow->setFinalizedType(TT_LambdaArrow);
2377 NestedLambdas.push_back(
Line->SeenDecltypeAuto);
2379 assert(!NestedLambdas.empty());
2380 NestedLambdas.pop_back();
2385bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
2394 const auto *BeforeRParen =
Previous->getPreviousNonComment();
2397 if (!BeforeRParen || BeforeRParen->isNoneOf(tok::greater, tok::r_paren))
2399 }
else if (
Previous->is(tok::star)) {
2403 Previous->isNoneOf(tok::kw_return, tok::kw_co_await, tok::kw_co_yield,
2404 tok::kw_co_return)) {
2408 if (LeftSquare->isCppStructuredBinding(IsCpp))
2410 if (FormatTok->is(tok::l_square) ||
tok::isLiteral(FormatTok->Tok.getKind()))
2412 if (FormatTok->is(tok::r_square)) {
2414 if (
Next->is(tok::greater))
2421void UnwrappedLineParser::tryToParseJSFunction() {
2422 assert(FormatTok->is(Keywords.kw_function));
2423 if (FormatTok->is(Keywords.kw_async))
2429 if (FormatTok->is(tok::star)) {
2430 FormatTok->setFinalizedType(TT_OverloadedOperator);
2435 if (FormatTok->is(tok::identifier))
2438 if (FormatTok->isNot(tok::l_paren))
2444 if (FormatTok->is(tok::colon)) {
2450 if (FormatTok->is(tok::l_brace))
2451 tryToParseBracedList();
2453 while (FormatTok->isNoneOf(tok::l_brace, tok::semi) && !
eof())
2457 if (FormatTok->is(tok::semi))
2463bool UnwrappedLineParser::tryToParseBracedList() {
2464 if (FormatTok->is(BK_Unknown))
2465 calculateBraceTypes();
2466 assert(FormatTok->isNot(BK_Unknown));
2467 if (FormatTok->is(BK_Block))
2474bool UnwrappedLineParser::tryToParseChildBlock() {
2475 assert(Style.isJavaScript() || Style.isCSharp());
2476 assert(FormatTok->is(TT_FatArrow));
2481 if (FormatTok->isNot(tok::l_brace))
2487bool UnwrappedLineParser::parseBracedList(
bool IsAngleBracket,
bool IsEnum) {
2488 assert(!IsAngleBracket || !IsEnum);
2489 bool HasError =
false;
2494 if (Style.isCSharp() && FormatTok->is(TT_FatArrow) &&
2495 tryToParseChildBlock()) {
2498 if (Style.isJavaScript()) {
2499 if (FormatTok->is(Keywords.kw_function)) {
2500 tryToParseJSFunction();
2503 if (FormatTok->is(tok::l_brace)) {
2505 if (tryToParseBracedList())
2510 if (FormatTok->is(IsAngleBracket ? tok::greater : tok::r_brace)) {
2512 FormatTok->setBlockKind(BK_Block);
2513 if (!Style.AllowShortEnumsOnASingleLine)
2519 switch (FormatTok->Tok.getKind()) {
2521 if (Style.isCSharp())
2530 if (Style.isJavaScript()) {
2531 if (FormatTok->is(tok::l_brace))
2539 FormatTok->setBlockKind(BK_BracedInit);
2540 if (!IsAngleBracket) {
2541 auto *Prev = FormatTok->Previous;
2542 if (Prev && Prev->is(tok::greater))
2543 Prev->setFinalizedType(TT_TemplateCloser);
2551 parseBracedList(
true);
2558 if (Style.isJavaScript()) {
2569 if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
2572 case tok::kw_requires: {
2573 auto *RequiresToken = FormatTok;
2575 parseRequiresExpression(RequiresToken);
2591bool UnwrappedLineParser::parseParens(TokenType AmpAmpTokenType,
2593 assert(FormatTok->is(tok::l_paren) &&
"'(' expected.");
2594 auto *LParen = FormatTok;
2595 auto *Prev = FormatTok->Previous;
2596 bool SeenComma =
false;
2597 bool SeenEqual =
false;
2598 bool MightBeFoldExpr =
false;
2600 const bool MightBeStmtExpr = FormatTok->is(tok::l_brace);
2601 if (!InMacroCall && Prev && Prev->is(TT_FunctionLikeMacro))
2604 switch (FormatTok->Tok.getKind()) {
2606 if (parseParens(AmpAmpTokenType, InMacroCall))
2608 if (Style.isJava() && FormatTok->is(tok::l_brace))
2611 case tok::r_paren: {
2612 auto *RParen = FormatTok;
2615 auto OptionalParens = [&] {
2616 if (MightBeStmtExpr || MightBeFoldExpr || SeenComma || InMacroCall ||
2617 Line->InMacroBody ||
2618 Style.RemoveParentheses == FormatStyle::RPS_Leave ||
2619 RParen->getPreviousNonComment() == LParen) {
2622 const bool DoubleParens =
2623 Prev->is(tok::l_paren) && FormatTok->is(tok::r_paren);
2625 const auto *PrevPrev = Prev->getPreviousNonComment();
2626 const bool Excluded =
2628 (PrevPrev->isOneOf(tok::kw___attribute, tok::kw_decltype) ||
2630 (PrevPrev->isOneOf(tok::kw_if, tok::kw_while) ||
2631 PrevPrev->endsSequence(tok::kw_constexpr, tok::kw_if))));
2635 const bool CommaSeparated =
2636 Prev->isOneOf(tok::l_paren, tok::comma) &&
2637 FormatTok->isOneOf(tok::comma, tok::r_paren);
2638 if (CommaSeparated &&
2640 !Prev->endsSequence(tok::comma, tok::ellipsis) &&
2642 !(FormatTok->is(tok::comma) &&
2643 Tokens->peekNextToken()->is(tok::ellipsis))) {
2646 const bool ReturnParens =
2647 Style.RemoveParentheses == FormatStyle::RPS_ReturnStatement &&
2648 ((NestedLambdas.empty() && !IsDecltypeAutoFunction) ||
2649 (!NestedLambdas.empty() && !NestedLambdas.back())) &&
2650 Prev->isOneOf(tok::kw_return, tok::kw_co_return) &&
2651 FormatTok->is(tok::semi);
2657 if (Prev->is(TT_TypenameMacro)) {
2658 LParen->setFinalizedType(TT_TypeDeclarationParen);
2659 RParen->setFinalizedType(TT_TypeDeclarationParen);
2660 }
else if (Prev->is(tok::greater) && RParen->Previous == LParen) {
2661 Prev->setFinalizedType(TT_TemplateCloser);
2662 }
else if (OptionalParens()) {
2663 LParen->Optional =
true;
2664 RParen->Optional =
true;
2676 if (!tryToParseBracedList())
2681 if (FormatTok->is(tok::l_brace)) {
2691 MightBeFoldExpr =
true;
2696 if (Style.isCSharp() && FormatTok->is(TT_FatArrow))
2697 tryToParseChildBlock();
2702 if (Style.isJavaScript())
2707 case tok::identifier:
2708 if (Style.isJavaScript() && (FormatTok->is(Keywords.kw_function)))
2709 tryToParseJSFunction();
2713 case tok::kw_switch:
2719 case tok::kw_requires: {
2720 auto RequiresToken = FormatTok;
2722 parseRequiresExpression(RequiresToken);
2726 if (AmpAmpTokenType != TT_Unknown)
2727 FormatTok->setFinalizedType(AmpAmpTokenType);
2739 assert(FormatTok->is(tok::l_square) &&
"'[' expected.");
2740 if (tryToParseLambda())
2744 switch (FormatTok->Tok.getKind()) {
2757 case tok::l_brace: {
2758 if (!tryToParseBracedList())
2765 if (FormatTok->is(tok::l_brace)) {
2777void UnwrappedLineParser::keepAncestorBraces() {
2778 if (!Style.RemoveBracesLLVM)
2781 const int MaxNestingLevels = 2;
2782 const int Size = NestedTooDeep.size();
2783 if (Size >= MaxNestingLevels)
2784 NestedTooDeep[
Size - MaxNestingLevels] =
true;
2785 NestedTooDeep.push_back(
false);
2789 for (
const auto &
Token : llvm::reverse(
Line.Tokens))
2796void UnwrappedLineParser::parseUnbracedBody(
bool CheckEOF) {
2799 if (Style.InsertBraces && !
Line->InPPDirective && !
Line->Tokens.empty() &&
2800 PreprocessorDirectives.empty() && FormatTok->isNot(tok::semi)) {
2801 Tok = Style.BraceWrapping.AfterControlStatement == FormatStyle::BWACS_Never
2802 ? getLastNonComment(*
Line)
2805 if (
Tok->BraceCount < 0) {
2806 assert(
Tok->BraceCount == -1);
2809 Tok->BraceCount = -1;
2815 ++
Line->UnbracedBodyLevel;
2816 parseStructuralElement();
2817 --
Line->UnbracedBodyLevel;
2820 assert(!
Line->InPPDirective);
2822 for (
const auto &L : llvm::reverse(*CurrentLines)) {
2824 Tok = L.Tokens.back().Tok;
2832 if (CheckEOF &&
eof())
2842 assert(LeftBrace->
is(tok::l_brace));
2850 assert(RightBrace->
is(tok::r_brace));
2858void UnwrappedLineParser::handleAttributes() {
2860 if (FormatTok->isAttribute())
2862 else if (FormatTok->is(tok::l_square))
2863 handleCppAttributes();
2866bool UnwrappedLineParser::handleCppAttributes() {
2868 assert(FormatTok->is(tok::l_square));
2869 if (!tryToParseSimpleAttribute())
2876bool UnwrappedLineParser::isBlockBegin(
const FormatToken &
Tok)
const {
2879 return Style.isVerilog() ? Keywords.isVerilogBegin(
Tok)
2880 :
Tok.
is(tok::l_brace);
2883FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
2885 bool IsVerilogAssert) {
2886 assert((FormatTok->is(tok::kw_if) ||
2887 (Style.isVerilog() &&
2888 FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
2889 Keywords.kw_assume, Keywords.kw_cover))) &&
2893 if (IsVerilogAssert) {
2895 if (FormatTok->is(Keywords.kw_verilogHash)) {
2897 if (FormatTok->is(tok::numeric_constant))
2899 }
else if (FormatTok->isOneOf(Keywords.kw_final, Keywords.kw_property,
2900 Keywords.kw_sequence)) {
2906 if (Style.isTableGen()) {
2907 while (!
eof() && FormatTok->isNot(Keywords.kw_then)) {
2914 if (FormatTok->is(tok::exclaim))
2917 bool KeepIfBraces =
true;
2918 if (FormatTok->is(tok::kw_consteval)) {
2921 KeepIfBraces = !Style.RemoveBracesLLVM || KeepBraces;
2922 if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
2924 if (FormatTok->is(tok::l_paren)) {
2925 FormatTok->setFinalizedType(TT_ConditionLParen);
2931 if (IsVerilogAssert && FormatTok->is(tok::semi)) {
2937 bool NeedsUnwrappedLine =
false;
2938 keepAncestorBraces();
2941 IfStmtKind IfBlockKind = IfStmtKind::NotIf;
2943 if (isBlockBegin(*FormatTok)) {
2944 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
2945 IfLeftBrace = FormatTok;
2946 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
2947 parseBlock(
false, 1u,
2948 true, KeepIfBraces, &IfBlockKind);
2949 setPreviousRBraceType(TT_ControlStatementRBrace);
2950 if (Style.BraceWrapping.BeforeElse)
2953 NeedsUnwrappedLine =
true;
2954 }
else if (IsVerilogAssert && FormatTok->is(tok::kw_else)) {
2957 parseUnbracedBody();
2960 if (Style.RemoveBracesLLVM) {
2961 assert(!NestedTooDeep.empty());
2962 KeepIfBraces = KeepIfBraces ||
2963 (IfLeftBrace && !IfLeftBrace->MatchingParen) ||
2964 NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly ||
2965 IfBlockKind == IfStmtKind::IfElseIf;
2968 bool KeepElseBraces = KeepIfBraces;
2970 IfStmtKind
Kind = IfStmtKind::IfOnly;
2972 if (FormatTok->is(tok::kw_else)) {
2973 if (Style.RemoveBracesLLVM) {
2974 NestedTooDeep.back() =
false;
2975 Kind = IfStmtKind::IfElse;
2979 if (isBlockBegin(*FormatTok)) {
2980 const bool FollowedByIf = Tokens->peekNextToken()->is(tok::kw_if);
2981 FormatTok->setFinalizedType(TT_ElseLBrace);
2982 ElseLeftBrace = FormatTok;
2983 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
2984 IfStmtKind ElseBlockKind = IfStmtKind::NotIf;
2986 parseBlock(
false, 1u,
2987 true, KeepElseBraces, &ElseBlockKind);
2988 setPreviousRBraceType(TT_ElseRBrace);
2989 if (FormatTok->is(tok::kw_else)) {
2990 KeepElseBraces = KeepElseBraces ||
2991 ElseBlockKind == IfStmtKind::IfOnly ||
2992 ElseBlockKind == IfStmtKind::IfElseIf;
2993 }
else if (FollowedByIf && IfLBrace && !IfLBrace->Optional) {
2994 KeepElseBraces =
true;
2995 assert(ElseLeftBrace->MatchingParen);
2999 }
else if (!IsVerilogAssert && FormatTok->is(tok::kw_if)) {
3002 const bool IsPrecededByComment =
Previous->is(tok::comment);
3003 if (IsPrecededByComment) {
3007 bool TooDeep =
true;
3008 if (Style.RemoveBracesLLVM) {
3009 Kind = IfStmtKind::IfElseIf;
3010 TooDeep = NestedTooDeep.pop_back_val();
3012 ElseLeftBrace = parseIfThenElse(
nullptr, KeepIfBraces);
3013 if (Style.RemoveBracesLLVM)
3014 NestedTooDeep.push_back(TooDeep);
3015 if (IsPrecededByComment)
3018 parseUnbracedBody(
true);
3021 KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse;
3022 if (NeedsUnwrappedLine)
3026 if (!Style.RemoveBracesLLVM)
3029 assert(!NestedTooDeep.empty());
3030 KeepElseBraces = KeepElseBraces ||
3031 (ElseLeftBrace && !ElseLeftBrace->MatchingParen) ||
3032 NestedTooDeep.back();
3034 NestedTooDeep.pop_back();
3036 if (!KeepIfBraces && !KeepElseBraces) {
3039 }
else if (IfLeftBrace) {
3040 FormatToken *IfRightBrace = IfLeftBrace->MatchingParen;
3042 assert(IfRightBrace->MatchingParen == IfLeftBrace);
3043 assert(!IfLeftBrace->Optional);
3044 assert(!IfRightBrace->Optional);
3045 IfLeftBrace->MatchingParen =
nullptr;
3046 IfRightBrace->MatchingParen =
nullptr;
3056void UnwrappedLineParser::parseTryCatch() {
3057 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) &&
"'try' expected");
3059 bool NeedsUnwrappedLine =
false;
3060 bool HasCtorInitializer =
false;
3061 if (FormatTok->is(tok::colon)) {
3062 auto *Colon = FormatTok;
3065 if (FormatTok->is(tok::identifier)) {
3066 HasCtorInitializer =
true;
3067 Colon->setFinalizedType(TT_CtorInitializerColon);
3072 while (FormatTok->is(tok::comma))
3075 while (FormatTok->is(tok::identifier)) {
3077 if (FormatTok->is(tok::l_paren)) {
3079 }
else if (FormatTok->is(tok::l_brace)) {
3086 while (FormatTok->is(tok::comma))
3091 if (Style.isJava() && FormatTok->is(tok::l_paren))
3094 keepAncestorBraces();
3096 if (FormatTok->is(tok::l_brace)) {
3097 if (HasCtorInitializer)
3098 FormatTok->setFinalizedType(TT_FunctionLBrace);
3099 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3101 if (Style.BraceWrapping.BeforeCatch)
3104 NeedsUnwrappedLine =
true;
3105 }
else if (FormatTok->isNot(tok::kw_catch)) {
3111 parseStructuralElement();
3114 for (
bool SeenCatch =
false;;) {
3115 if (FormatTok->is(tok::at))
3117 if (FormatTok->isNoneOf(tok::kw_catch, Keywords.kw___except,
3118 tok::kw___finally, tok::objc_catch,
3119 tok::objc_finally) &&
3120 !((Style.isJava() || Style.isJavaScript()) &&
3121 FormatTok->is(Keywords.kw_finally))) {
3124 if (FormatTok->is(tok::kw_catch))
3127 while (FormatTok->isNot(tok::l_brace)) {
3128 if (FormatTok->is(tok::l_paren)) {
3132 if (FormatTok->isOneOf(tok::semi, tok::r_brace) ||
eof()) {
3133 if (Style.RemoveBracesLLVM)
3134 NestedTooDeep.pop_back();
3140 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3143 NeedsUnwrappedLine =
false;
3144 Line->MustBeDeclaration =
false;
3145 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3147 if (Style.BraceWrapping.BeforeCatch)
3150 NeedsUnwrappedLine =
true;
3153 if (Style.RemoveBracesLLVM)
3154 NestedTooDeep.pop_back();
3156 if (NeedsUnwrappedLine)
3160void UnwrappedLineParser::parseNamespaceOrExportBlock(
unsigned AddLevels) {
3161 bool ManageWhitesmithsBraces =
3162 AddLevels == 0u && Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
3166 if (ManageWhitesmithsBraces)
3171 parseBlock(
true, AddLevels,
true,
3172 true,
nullptr, ManageWhitesmithsBraces);
3174 addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep);
3176 if (ManageWhitesmithsBraces)
3180void UnwrappedLineParser::parseNamespace() {
3181 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
3182 "'namespace' expected");
3186 if (InitialToken.is(TT_NamespaceMacro)) {
3189 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
3190 tok::l_square, tok::period, tok::l_paren) ||
3191 (Style.isCSharp() && FormatTok->is(tok::kw_union))) {
3192 if (FormatTok->is(tok::l_square))
3194 else if (FormatTok->is(tok::l_paren))
3200 if (FormatTok->is(tok::l_brace)) {
3201 FormatTok->setFinalizedType(TT_NamespaceLBrace);
3206 unsigned AddLevels =
3207 Style.NamespaceIndentation == FormatStyle::NI_All ||
3208 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
3209 DeclarationScopeStack.size() > 1)
3212 parseNamespaceOrExportBlock(AddLevels);
3217void UnwrappedLineParser::parseCppExportBlock() {
3218 parseNamespaceOrExportBlock(Style.IndentExportBlock ? 1 : 0);
3221void UnwrappedLineParser::parseNew() {
3222 assert(FormatTok->is(tok::kw_new) &&
"'new' expected");
3225 if (Style.isCSharp()) {
3228 if (FormatTok->is(tok::l_paren))
3232 if (FormatTok->is(tok::l_brace))
3235 if (FormatTok->isOneOf(tok::semi, tok::comma))
3242 if (!Style.isJava())
3248 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
3252 if (FormatTok->is(tok::l_paren)) {
3256 if (FormatTok->is(tok::l_brace))
3264void UnwrappedLineParser::parseLoopBody(
bool KeepBraces,
bool WrapRightBrace) {
3265 keepAncestorBraces();
3267 if (isBlockBegin(*FormatTok)) {
3268 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3270 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3271 parseBlock(
false, 1u,
3273 setPreviousRBraceType(TT_ControlStatementRBrace);
3275 assert(!NestedTooDeep.empty());
3276 if (!NestedTooDeep.back())
3282 parseUnbracedBody();
3286 NestedTooDeep.pop_back();
3289void UnwrappedLineParser::parseForOrWhileLoop(
bool HasParens) {
3290 assert((FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) ||
3291 (Style.isVerilog() &&
3292 FormatTok->isOneOf(Keywords.kw_always, Keywords.kw_always_comb,
3293 Keywords.kw_always_ff, Keywords.kw_always_latch,
3294 Keywords.kw_final, Keywords.kw_initial,
3295 Keywords.kw_foreach, Keywords.kw_forever,
3296 Keywords.kw_repeat))) &&
3297 "'for', 'while' or foreach macro expected");
3298 const bool KeepBraces = !Style.RemoveBracesLLVM ||
3299 FormatTok->isNoneOf(tok::kw_for, tok::kw_while);
3303 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
3305 if (IsCpp && FormatTok->is(tok::kw_co_await))
3307 if (HasParens && FormatTok->is(tok::l_paren)) {
3311 if (Style.isVerilog())
3312 FormatTok->setFinalizedType(TT_ConditionLParen);
3316 if (Style.isVerilog()) {
3318 parseVerilogSensitivityList();
3319 }
else if (Style.AllowShortLoopsOnASingleLine && FormatTok->is(tok::semi) &&
3320 Tokens->getPreviousToken()->is(tok::r_paren)) {
3327 parseLoopBody(KeepBraces,
true);
3330void UnwrappedLineParser::parseDoWhile() {
3331 assert(FormatTok->is(tok::kw_do) &&
"'do' expected");
3334 parseLoopBody(
true, Style.BraceWrapping.BeforeWhile);
3337 if (FormatTok->isNot(tok::kw_while)) {
3342 FormatTok->setFinalizedType(TT_DoWhile);
3346 if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)
3350 parseStructuralElement();
3353void UnwrappedLineParser::parseLabel(
bool LeftAlignLabel) {
3355 unsigned OldLineLevel =
Line->Level;
3359 else if (
Line->Level > 1 || (!
Line->InPPDirective &&
Line->Level > 0))
3362 if (!Style.IndentCaseBlocks && CommentsBeforeNextToken.empty() &&
3363 FormatTok->is(tok::l_brace)) {
3365 CompoundStatementIndenter Indenter(
this,
Line->Level,
3366 Style.BraceWrapping.AfterCaseLabel,
3367 Style.BraceWrapping.IndentBraces);
3369 if (FormatTok->is(tok::kw_break)) {
3370 if (Style.BraceWrapping.AfterControlStatement ==
3371 FormatStyle::BWACS_Always) {
3373 if (!Style.IndentCaseBlocks &&
3374 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) {
3378 parseStructuralElement();
3382 if (FormatTok->is(tok::semi))
3386 Line->Level = OldLineLevel;
3387 if (FormatTok->isNot(tok::l_brace)) {
3388 parseStructuralElement();
3393void UnwrappedLineParser::parseCaseLabel() {
3394 assert(FormatTok->is(tok::kw_case) &&
"'case' expected");
3395 auto *Case = FormatTok;
3400 if (FormatTok->is(tok::colon)) {
3401 FormatTok->setFinalizedType(TT_CaseLabelColon);
3404 if (Style.isJava() && FormatTok->is(tok::arrow)) {
3405 FormatTok->setFinalizedType(TT_CaseLabelArrow);
3406 Case->setFinalizedType(TT_SwitchExpressionLabel);
3413void UnwrappedLineParser::parseSwitch(
bool IsExpr) {
3414 assert(FormatTok->is(tok::kw_switch) &&
"'switch' expected");
3416 if (FormatTok->is(tok::l_paren))
3419 keepAncestorBraces();
3421 if (FormatTok->is(tok::l_brace)) {
3422 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3423 FormatTok->setFinalizedType(IsExpr ? TT_SwitchExpressionLBrace
3424 : TT_ControlStatementLBrace);
3429 setPreviousRBraceType(TT_ControlStatementRBrace);
3435 parseStructuralElement();
3439 if (Style.RemoveBracesLLVM)
3440 NestedTooDeep.pop_back();
3443void UnwrappedLineParser::parseAccessSpecifier() {
3446 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
3449 if (FormatTok->is(tok::colon))
3457bool UnwrappedLineParser::parseRequires(
bool SeenEqual) {
3458 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3459 auto RequiresToken = FormatTok;
3465 switch (FormatTok->Tok.getKind()) {
3468 parseRequiresExpression(RequiresToken);
3475 parseRequiresClause(RequiresToken);
3486 auto *PreviousNonComment = RequiresToken->getPreviousNonComment();
3488 if (!PreviousNonComment ||
3489 PreviousNonComment->is(TT_RequiresExpressionLBrace)) {
3492 parseRequiresClause(RequiresToken);
3496 switch (PreviousNonComment->Tok.getKind()) {
3499 case tok::kw_noexcept:
3504 parseRequiresClause(RequiresToken);
3513 auto PrevPrev = PreviousNonComment->getPreviousNonComment();
3514 if ((PrevPrev && PrevPrev->is(tok::kw_const)) || !SeenEqual) {
3515 parseRequiresClause(RequiresToken);
3521 if (PreviousNonComment->isTypeOrIdentifier(LangOpts)) {
3523 parseRequiresClause(RequiresToken);
3527 parseRequiresExpression(RequiresToken);
3537 unsigned StoredPosition = Tokens->getPosition();
3540 auto PeekNext = [&Lookahead, &NextToken,
this] {
3542 NextToken = Tokens->getNextToken();
3545 bool FoundType =
false;
3546 bool LastWasColonColon =
false;
3549 for (; Lookahead < 50; PeekNext()) {
3550 switch (NextToken->Tok.getKind()) {
3551 case tok::kw_volatile:
3554 if (OpenAngles == 0) {
3555 FormatTok = Tokens->setPosition(StoredPosition);
3556 parseRequiresExpression(RequiresToken);
3564 case tok::coloncolon:
3565 LastWasColonColon =
true;
3567 case tok::kw_decltype:
3568 case tok::identifier:
3569 if (FoundType && !LastWasColonColon && OpenAngles == 0) {
3570 FormatTok = Tokens->setPosition(StoredPosition);
3571 parseRequiresExpression(RequiresToken);
3575 LastWasColonColon =
false;
3584 if (NextToken->isTypeName(LangOpts)) {
3585 FormatTok = Tokens->setPosition(StoredPosition);
3586 parseRequiresExpression(RequiresToken);
3593 FormatTok = Tokens->setPosition(StoredPosition);
3594 parseRequiresClause(RequiresToken);
3605void UnwrappedLineParser::parseRequiresClause(
FormatToken *RequiresToken) {
3606 assert(FormatTok->getPreviousNonComment() == RequiresToken);
3607 assert(RequiresToken->is(tok::kw_requires) &&
"'requires' expected");
3612 bool InRequiresExpression =
3613 !RequiresToken->Previous ||
3614 RequiresToken->Previous->is(TT_RequiresExpressionLBrace);
3616 RequiresToken->setFinalizedType(InRequiresExpression
3617 ? TT_RequiresClauseInARequiresExpression
3618 : TT_RequiresClause);
3622 parseConstraintExpression();
3624 if (!InRequiresExpression && FormatTok->Previous)
3625 FormatTok->Previous->ClosesRequiresClause =
true;
3635void UnwrappedLineParser::parseRequiresExpression(
FormatToken *RequiresToken) {
3636 assert(FormatTok->getPreviousNonComment() == RequiresToken);
3637 assert(RequiresToken->is(tok::kw_requires) &&
"'requires' expected");
3639 RequiresToken->setFinalizedType(TT_RequiresExpression);
3641 if (FormatTok->is(tok::l_paren)) {
3642 FormatTok->setFinalizedType(TT_RequiresExpressionLParen);
3646 if (FormatTok->is(tok::l_brace)) {
3647 FormatTok->setFinalizedType(TT_RequiresExpressionLBrace);
3656void UnwrappedLineParser::parseConstraintExpression() {
3663 bool LambdaNextTimeAllowed =
true;
3673 bool TopLevelParensAllowed =
true;
3676 bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed,
false);
3678 switch (FormatTok->Tok.getKind()) {
3679 case tok::kw_requires: {
3680 auto RequiresToken = FormatTok;
3682 parseRequiresExpression(RequiresToken);
3687 if (!TopLevelParensAllowed)
3689 parseParens(TT_BinaryOperator);
3690 TopLevelParensAllowed =
false;
3694 if (!LambdaThisTimeAllowed || !tryToParseLambda())
3701 case tok::kw_struct:
3711 FormatTok->setFinalizedType(TT_BinaryOperator);
3713 LambdaNextTimeAllowed =
true;
3714 TopLevelParensAllowed =
true;
3719 LambdaNextTimeAllowed = LambdaThisTimeAllowed;
3723 case tok::kw_sizeof:
3725 case tok::greaterequal:
3726 case tok::greatergreater:
3728 case tok::lessequal:
3730 case tok::equalequal:
3732 case tok::exclaimequal:
3737 LambdaNextTimeAllowed =
true;
3738 TopLevelParensAllowed =
true;
3743 case tok::numeric_constant:
3744 case tok::coloncolon:
3747 TopLevelParensAllowed =
false;
3752 case tok::kw_static_cast:
3753 case tok::kw_const_cast:
3754 case tok::kw_reinterpret_cast:
3755 case tok::kw_dynamic_cast:
3757 if (FormatTok->isNot(tok::less))
3761 parseBracedList(
true);
3765 if (!FormatTok->Tok.getIdentifierInfo()) {
3775 assert(FormatTok->Previous);
3776 switch (FormatTok->Previous->Tok.getKind()) {
3777 case tok::coloncolon:
3781 case tok::kw_requires:
3790 if (FormatTok->is(tok::less)) {
3792 parseBracedList(
true);
3794 TopLevelParensAllowed =
false;
3800bool UnwrappedLineParser::parseEnum() {
3804 if (FormatTok->is(tok::kw_enum))
3810 if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question))
3814 if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal))
3819 if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
3821 while (FormatTok->is(tok::l_square))
3822 if (!handleCppAttributes())
3826 while (FormatTok->Tok.getIdentifierInfo() ||
3827 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
3828 tok::greater, tok::comma, tok::question,
3830 if (Style.isVerilog()) {
3831 FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
3834 while (FormatTok->is(tok::l_square))
3840 if (FormatTok->is(tok::l_paren))
3842 if (FormatTok->is(tok::identifier)) {
3846 if (IsCpp && FormatTok->is(tok::identifier))
3852 if (FormatTok->isNot(tok::l_brace))
3854 FormatTok->setFinalizedType(TT_EnumLBrace);
3855 FormatTok->setBlockKind(BK_Block);
3857 if (Style.isJava()) {
3859 parseJavaEnumBody();
3862 if (Style.Language == FormatStyle::LK_Proto) {
3867 if (!Style.AllowShortEnumsOnASingleLine &&
3873 if (!Style.AllowShortEnumsOnASingleLine) {
3877 bool HasError = !parseBracedList(
false,
true);
3878 if (!Style.AllowShortEnumsOnASingleLine)
3881 if (FormatTok->is(tok::semi))
3885 setPreviousRBraceType(TT_EnumRBrace);
3893bool UnwrappedLineParser::parseStructLike() {
3898 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp()) {
3899 if (FormatTok->is(tok::semi))
3910class ScopedTokenPosition {
3911 unsigned StoredPosition;
3912 FormatTokenSource *Tokens;
3915 ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) {
3916 assert(Tokens &&
"Tokens expected to not be null");
3917 StoredPosition = Tokens->getPosition();
3920 ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); }
3926bool UnwrappedLineParser::tryToParseSimpleAttribute() {
3927 ScopedTokenPosition AutoPosition(Tokens);
3935 if (
Tok->
is(tok::r_square))
3937 Tok = Tokens->getNextToken();
3939 if (
Tok->
is(tok::eof))
3941 Tok = Tokens->getNextToken();
3944 Tok = Tokens->getNextToken();
3945 if (
Tok->
is(tok::semi))
3950void UnwrappedLineParser::parseJavaEnumBody() {
3951 assert(FormatTok->is(tok::l_brace));
3957 unsigned StoredPosition = Tokens->getPosition();
3958 bool IsSimple =
true;
3961 if (
Tok->
is(tok::r_brace))
3969 Tok = Tokens->getNextToken();
3971 FormatTok = Tokens->setPosition(StoredPosition);
3988 if (FormatTok->is(tok::l_brace)) {
3990 parseBlock(
true, 1u,
3992 }
else if (FormatTok->is(tok::l_paren)) {
3994 }
else if (FormatTok->is(tok::comma)) {
3997 }
else if (FormatTok->is(tok::semi)) {
4001 }
else if (FormatTok->is(tok::r_brace)) {
4010 parseLevel(OpeningBrace);
4016void UnwrappedLineParser::parseRecord(
bool ParseAsExpr,
bool IsJavaRecord) {
4017 assert(!IsJavaRecord || FormatTok->is(Keywords.kw_record));
4022 IsJavaRecord && FormatTok->is(tok::identifier) ? FormatTok :
nullptr;
4023 bool IsDerived =
false;
4025 return Tok->
is(tok::identifier) &&
Tok->TokenText !=
Tok->TokenText.upper();
4029 bool JSPastExtendsOrImplements =
false;
4033 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
4034 tok::kw_alignas, tok::l_square) ||
4035 FormatTok->isAttribute() ||
4036 ((Style.isJava() || Style.isJavaScript()) &&
4037 FormatTok->isOneOf(tok::period, tok::comma))) {
4038 if (Style.isJavaScript() &&
4039 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
4040 JSPastExtendsOrImplements =
true;
4045 if (FormatTok->is(tok::l_brace)) {
4046 tryToParseBracedList();
4050 if (FormatTok->is(tok::l_square) && handleCppAttributes())
4054 switch (FormatTok->Tok.getKind()) {
4057 if (IsJavaRecord || !IsNonMacroIdentifier(
Previous) ||
4059 Previous->Previous == &InitialToken) {
4063 case tok::coloncolon:
4067 if (JSPastExtendsOrImplements || ClassName ||
4078 auto IsListInitialization = [&] {
4079 if (!ClassName || IsDerived || JSPastExtendsOrImplements)
4081 assert(FormatTok->is(tok::l_brace));
4082 const auto *Prev = FormatTok->getPreviousNonComment();
4084 return Prev != ClassName && Prev->is(tok::identifier) &&
4085 Prev->isNot(Keywords.kw_final) && tryToParseBracedList();
4088 if (FormatTok->isOneOf(tok::colon, tok::less)) {
4089 int AngleNestingLevel = 0;
4091 if (FormatTok->is(tok::less))
4092 ++AngleNestingLevel;
4093 else if (FormatTok->is(tok::greater))
4094 --AngleNestingLevel;
4096 if (AngleNestingLevel == 0) {
4097 if (FormatTok->is(tok::colon)) {
4099 }
else if (!IsDerived && FormatTok->is(tok::identifier) &&
4100 FormatTok->Previous->is(tok::coloncolon)) {
4101 ClassName = FormatTok;
4102 }
else if (FormatTok->is(tok::l_paren) &&
4103 IsNonMacroIdentifier(FormatTok->Previous)) {
4107 if (FormatTok->is(tok::l_brace)) {
4108 if (AngleNestingLevel == 0 && IsListInitialization())
4110 calculateBraceTypes(
true);
4111 if (!tryToParseBracedList())
4114 if (FormatTok->is(tok::l_square)) {
4117 !
Previous->isTypeOrIdentifier(LangOpts))) {
4120 if (!tryToParseLambda())
4127 if (FormatTok->is(tok::semi))
4129 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
4132 parseCSharpGenericTypeConstraint();
4139 auto GetBraceTypes =
4140 [](
const FormatToken &RecordTok) -> std::pair<TokenType, TokenType> {
4141 switch (RecordTok.Tok.getKind()) {
4143 return {TT_ClassLBrace, TT_ClassRBrace};
4144 case tok::kw_struct:
4145 return {TT_StructLBrace, TT_StructRBrace};
4147 return {TT_UnionLBrace, TT_UnionRBrace};
4150 return {TT_RecordLBrace, TT_RecordRBrace};
4153 if (FormatTok->is(tok::l_brace)) {
4154 if (IsListInitialization())
4157 ClassName->setFinalizedType(TT_ClassHeadName);
4158 auto [OpenBraceType, ClosingBraceType] = GetBraceTypes(InitialToken);
4159 FormatTok->setFinalizedType(OpenBraceType);
4166 unsigned AddLevels = Style.IndentAccessModifiers ? 2u : 1u;
4167 parseBlock(
true, AddLevels,
false);
4169 setPreviousRBraceType(ClosingBraceType);
4176void UnwrappedLineParser::parseObjCMethod() {
4177 assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) &&
4178 "'(' or identifier expected.");
4180 if (FormatTok->is(tok::semi)) {
4184 }
else if (FormatTok->is(tok::l_brace)) {
4185 if (Style.BraceWrapping.AfterFunction)
4196void UnwrappedLineParser::parseObjCProtocolList() {
4197 assert(FormatTok->is(tok::less) &&
"'<' expected.");
4201 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4203 }
while (!
eof() && FormatTok->isNot(tok::greater));
4207void UnwrappedLineParser::parseObjCUntilAtEnd() {
4209 if (FormatTok->is(tok::objc_end)) {
4214 if (FormatTok->is(tok::l_brace)) {
4218 }
else if (FormatTok->is(tok::r_brace)) {
4222 }
else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
4226 parseStructuralElement();
4231void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
4232 assert(FormatTok->isOneOf(tok::objc_interface, tok::objc_implementation));
4238 if (FormatTok->is(tok::less))
4239 parseObjCLightweightGenerics();
4240 if (FormatTok->is(tok::colon)) {
4244 if (FormatTok->is(tok::less))
4245 parseObjCLightweightGenerics();
4246 }
else if (FormatTok->is(tok::l_paren)) {
4251 if (FormatTok->is(tok::less))
4252 parseObjCProtocolList();
4254 if (FormatTok->is(tok::l_brace)) {
4255 if (Style.BraceWrapping.AfterObjCDeclaration)
4264 parseObjCUntilAtEnd();
4267void UnwrappedLineParser::parseObjCLightweightGenerics() {
4268 assert(FormatTok->is(tok::less));
4276 unsigned NumOpenAngles = 1;
4280 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4282 if (FormatTok->is(tok::less)) {
4284 }
else if (FormatTok->is(tok::greater)) {
4285 assert(NumOpenAngles > 0 &&
"'>' makes NumOpenAngles negative");
4288 }
while (!
eof() && NumOpenAngles != 0);
4294bool UnwrappedLineParser::parseObjCProtocol() {
4295 assert(FormatTok->is(tok::objc_protocol));
4298 if (FormatTok->is(tok::l_paren)) {
4310 if (FormatTok->is(tok::less))
4311 parseObjCProtocolList();
4314 if (FormatTok->is(tok::semi)) {
4321 parseObjCUntilAtEnd();
4325void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
4326 bool IsImport = FormatTok->is(Keywords.kw_import);
4327 assert(IsImport || FormatTok->is(tok::kw_export));
4331 if (FormatTok->is(tok::kw_default))
4337 if (FormatTok->is(Keywords.kw_async))
4339 if (FormatTok->is(Keywords.kw_function)) {
4348 if (!IsImport && FormatTok->isNoneOf(tok::l_brace, tok::star) &&
4349 !FormatTok->isStringLiteral() &&
4350 !(FormatTok->is(Keywords.kw_type) &&
4351 Tokens->peekNextToken()->isOneOf(tok::l_brace, tok::star))) {
4356 if (FormatTok->is(tok::semi))
4358 if (
Line->Tokens.empty()) {
4363 if (FormatTok->is(tok::l_brace)) {
4364 FormatTok->setBlockKind(BK_Block);
4373void UnwrappedLineParser::parseStatementMacro() {
4375 if (FormatTok->is(tok::l_paren))
4377 if (FormatTok->is(tok::semi))
4382void UnwrappedLineParser::parseVerilogHierarchyIdentifier() {
4385 if (FormatTok->isOneOf(tok::star, tok::period, tok::periodstar,
4386 tok::coloncolon, tok::hash) ||
4387 Keywords.isVerilogIdentifier(*FormatTok)) {
4389 }
else if (FormatTok->is(tok::l_square)) {
4397void UnwrappedLineParser::parseVerilogSensitivityList() {
4398 if (FormatTok->isNot(tok::at))
4402 if (FormatTok->is(tok::at))
4404 switch (FormatTok->Tok.getKind()) {
4412 parseVerilogHierarchyIdentifier();
4417unsigned UnwrappedLineParser::parseVerilogHierarchyHeader() {
4418 unsigned AddLevels = 0;
4420 if (FormatTok->is(Keywords.kw_clocking)) {
4422 if (Keywords.isVerilogIdentifier(*FormatTok))
4424 parseVerilogSensitivityList();
4425 if (FormatTok->is(tok::semi))
4427 }
else if (FormatTok->isOneOf(tok::kw_case, Keywords.kw_casex,
4428 Keywords.kw_casez, Keywords.kw_randcase,
4429 Keywords.kw_randsequence)) {
4430 if (Style.IndentCaseLabels)
4433 if (FormatTok->is(tok::l_paren)) {
4434 FormatTok->setFinalizedType(TT_ConditionLParen);
4437 if (FormatTok->isOneOf(Keywords.kw_inside, Keywords.kw_matches))
4446 if (FormatTok->is(tok::l_square)) {
4447 auto Prev = FormatTok->getPreviousNonComment();
4448 if (Prev && Keywords.isVerilogIdentifier(*Prev))
4449 Prev->setFinalizedType(TT_VerilogDimensionedTypeName);
4451 }
else if (Keywords.isVerilogIdentifier(*FormatTok) ||
4452 FormatTok->isOneOf(tok::hash, tok::hashhash, tok::coloncolon,
4453 Keywords.kw_automatic, tok::kw_static)) {
4460 auto NewLine = [
this]() {
4462 Line->IsContinuation =
true;
4466 while (FormatTok->is(Keywords.kw_import)) {
4469 parseVerilogHierarchyIdentifier();
4470 if (FormatTok->is(tok::semi))
4475 if (FormatTok->is(Keywords.kw_verilogHash)) {
4478 if (FormatTok->is(tok::l_paren)) {
4479 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4483 if (FormatTok->is(tok::l_paren)) {
4485 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4490 if (FormatTok->is(Keywords.kw_extends)) {
4493 parseVerilogHierarchyIdentifier();
4494 if (FormatTok->is(tok::l_paren))
4497 if (FormatTok->is(Keywords.kw_implements)) {
4501 parseVerilogHierarchyIdentifier();
4502 }
while (FormatTok->is(tok::comma));
4506 if (FormatTok->is(tok::at)) {
4508 parseVerilogSensitivityList();
4511 if (FormatTok->is(tok::semi))
4519void UnwrappedLineParser::parseVerilogTable() {
4520 assert(FormatTok->is(Keywords.kw_table));
4524 auto InitialLevel =
Line->Level++;
4525 while (!
eof() && !Keywords.isVerilogEnd(*FormatTok)) {
4528 if (
Tok->
is(tok::semi))
4530 else if (
Tok->
isOneOf(tok::star, tok::colon, tok::question, tok::minus))
4531 Tok->setFinalizedType(TT_VerilogTableItem);
4533 Line->Level = InitialLevel;
4538void UnwrappedLineParser::parseVerilogCaseLabel() {
4544 auto OrigLevel =
Line->Level;
4545 auto FirstLine = CurrentLines->size();
4546 if (
Line->Level == 0 || (
Line->InPPDirective &&
Line->Level <= 1))
4548 else if (!Style.IndentCaseBlocks && Keywords.isVerilogBegin(*FormatTok))
4550 parseStructuralElement();
4553 if (CurrentLines->size() > FirstLine)
4554 (*CurrentLines)[FirstLine].Level = OrigLevel;
4555 Line->Level = OrigLevel;
4558bool UnwrappedLineParser::containsExpansion(
const UnwrappedLine &
Line)
const {
4559 for (
const auto &N :
Line.Tokens) {
4560 if (N.Tok->MacroCtx)
4562 for (
const UnwrappedLine &Child : N.Children)
4563 if (containsExpansion(Child))
4569void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) {
4570 if (
Line->Tokens.empty())
4573 if (!parsingPPDirective()) {
4574 llvm::dbgs() <<
"Adding unwrapped line:\n";
4575 printDebugInfo(*
Line);
4583 bool ClosesWhitesmithsBlock =
4584 Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex &&
4585 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
4590 if (!parsingPPDirective() && !InExpansion && containsExpansion(*
Line)) {
4592 Reconstruct.emplace(
Line->Level, Unexpanded);
4593 Reconstruct->addLine(*
Line);
4598 CurrentExpandedLines.push_back(std::move(*
Line));
4600 if (Reconstruct->finished()) {
4601 UnwrappedLine Reconstructed = std::move(*Reconstruct).takeResult();
4602 assert(!Reconstructed.Tokens.empty() &&
4603 "Reconstructed must at least contain the macro identifier.");
4604 assert(!parsingPPDirective());
4606 llvm::dbgs() <<
"Adding unexpanded line:\n";
4607 printDebugInfo(Reconstructed);
4609 ExpandedLines[Reconstructed.Tokens.begin()->Tok] = CurrentExpandedLines;
4610 Lines.push_back(std::move(Reconstructed));
4611 CurrentExpandedLines.clear();
4612 Reconstruct.reset();
4617 assert(!Reconstruct || (CurrentLines != &Lines) || !PPStack.empty());
4618 CurrentLines->push_back(std::move(*
Line));
4620 Line->Tokens.clear();
4621 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
4622 Line->FirstStartColumn = 0;
4623 Line->IsContinuation =
false;
4624 Line->SeenDecltypeAuto =
false;
4626 if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove)
4628 if (!parsingPPDirective() && !PreprocessorDirectives.empty()) {
4629 CurrentLines->append(
4630 std::make_move_iterator(PreprocessorDirectives.begin()),
4631 std::make_move_iterator(PreprocessorDirectives.end()));
4632 PreprocessorDirectives.clear();
4635 FormatTok->Previous =
nullptr;
4638bool UnwrappedLineParser::eof()
const {
return FormatTok->is(tok::eof); }
4640bool UnwrappedLineParser::isOnNewLine(
const FormatToken &FormatTok) {
4641 return (
Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
4642 FormatTok.NewlinesBefore > 0;
4650 const llvm::Regex &CommentPragmasRegex) {
4651 if (
Line.Tokens.empty() || Style.ReflowComments != FormatStyle::RCS_Always)
4654 StringRef IndentContent = FormatTok.
TokenText;
4655 if (FormatTok.
TokenText.starts_with(
"//") ||
4656 FormatTok.
TokenText.starts_with(
"/*")) {
4657 IndentContent = FormatTok.
TokenText.substr(2);
4659 if (CommentPragmasRegex.match(IndentContent))
4734 if (PreviousToken && PreviousToken->
is(tok::l_brace) &&
4736 MinColumnToken = PreviousToken;
4739 PreviousToken = Node.
Tok;
4743 MinColumnToken = Node.
Tok;
4745 if (PreviousToken && PreviousToken->
is(tok::l_brace))
4746 MinColumnToken = PreviousToken;
4752void UnwrappedLineParser::flushComments(
bool NewlineBeforeNext) {
4753 bool JustComments =
Line->Tokens.empty();
4763 Tok->ContinuesLineCommentSection =
4764 continuesLineCommentSection(*
Tok, *
Line, Style, CommentPragmasRegex);
4765 if (isOnNewLine(*
Tok) && JustComments && !
Tok->ContinuesLineCommentSection)
4769 if (NewlineBeforeNext && JustComments)
4771 CommentsBeforeNextToken.clear();
4774void UnwrappedLineParser::nextToken(
int LevelDifference) {
4777 flushComments(isOnNewLine(*FormatTok));
4778 pushToken(FormatTok);
4780 if (!Style.isJavaScript())
4781 readToken(LevelDifference);
4783 readTokenWithJavaScriptASI();
4785 if (Style.isVerilog()) {
4792 if (Keywords.isVerilogEnd(*FormatTok))
4793 FormatTok->Tok.setKind(tok::r_brace);
4797void UnwrappedLineParser::distributeComments(
4817 if (Comments.empty())
4819 bool ShouldPushCommentsInCurrentLine =
true;
4820 bool HasTrailAlignedWithNextToken =
false;
4821 unsigned StartOfTrailAlignedWithNextToken = 0;
4824 for (
unsigned i = Comments.size() - 1; i > 0; --i) {
4826 HasTrailAlignedWithNextToken =
true;
4827 StartOfTrailAlignedWithNextToken = i;
4831 for (
unsigned i = 0, e = Comments.size(); i < e; ++i) {
4833 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
4834 FormatTok->ContinuesLineCommentSection =
false;
4837 *FormatTok, *
Line, Style, CommentPragmasRegex);
4839 if (!FormatTok->ContinuesLineCommentSection &&
4840 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
4841 ShouldPushCommentsInCurrentLine =
false;
4843 if (ShouldPushCommentsInCurrentLine)
4844 pushToken(FormatTok);
4846 CommentsBeforeNextToken.push_back(FormatTok);
4850void UnwrappedLineParser::readToken(
int LevelDifference) {
4852 bool PreviousWasComment =
false;
4853 bool FirstNonCommentOnLine =
false;
4855 FormatTok = Tokens->getNextToken();
4857 while (FormatTok->isOneOf(TT_ConflictStart, TT_ConflictEnd,
4858 TT_ConflictAlternative)) {
4859 if (FormatTok->is(TT_ConflictStart))
4860 conditionalCompilationStart(
false);
4861 else if (FormatTok->is(TT_ConflictAlternative))
4862 conditionalCompilationAlternative();
4863 else if (FormatTok->is(TT_ConflictEnd))
4864 conditionalCompilationEnd();
4865 FormatTok = Tokens->getNextToken();
4866 FormatTok->MustBreakBefore =
true;
4867 FormatTok->MustBreakBeforeFinalized =
true;
4870 auto IsFirstNonCommentOnLine = [](
bool FirstNonCommentOnLine,
4872 bool PreviousWasComment) {
4874 return Tok.HasUnescapedNewline ||
Tok.IsFirst;
4879 if (PreviousWasComment)
4880 return FirstNonCommentOnLine || IsFirstOnLine(
Tok);
4881 return IsFirstOnLine(
Tok);
4884 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
4885 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
4886 PreviousWasComment = FormatTok->is(tok::comment);
4888 while (!
Line->InPPDirective && FormatTok->is(tok::hash) &&
4889 FirstNonCommentOnLine) {
4892 const auto *
Next = Tokens->peekNextToken();
4893 if ((Style.isVerilog() && !Keywords.isVerilogPPDirective(*
Next)) ||
4894 (Style.isTableGen() &&
4895 Next->isNoneOf(tok::kw_else, tok::pp_define, tok::pp_ifdef,
4896 tok::pp_ifndef, tok::pp_endif))) {
4899 distributeComments(Comments, FormatTok);
4903 bool SwitchToPreprocessorLines = !
Line->Tokens.empty();
4904 ScopedLineState BlockState(*
this, SwitchToPreprocessorLines);
4905 assert((LevelDifference >= 0 ||
4906 static_cast<unsigned>(-LevelDifference) <=
Line->Level) &&
4907 "LevelDifference makes Line->Level negative");
4908 Line->Level += LevelDifference;
4912 if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash &&
4913 PPBranchLevel > 0) {
4914 Line->Level += PPBranchLevel;
4916 assert(
Line->Level >=
Line->UnbracedBodyLevel);
4917 Line->Level -=
Line->UnbracedBodyLevel;
4918 flushComments(isOnNewLine(*FormatTok));
4920 PreviousWasComment = FormatTok->is(tok::comment);
4921 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
4922 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
4925 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
4926 !
Line->InPPDirective) {
4930 if (FormatTok->is(tok::identifier) &&
4931 Macros.defined(FormatTok->TokenText) &&
4933 !
Line->InPPDirective) {
4935 unsigned Position = Tokens->getPosition();
4939 auto PreCall = std::move(
Line);
4940 Line.reset(
new UnwrappedLine);
4941 bool OldInExpansion = InExpansion;
4944 auto Args = parseMacroCall();
4945 InExpansion = OldInExpansion;
4946 assert(
Line->Tokens.front().Tok == ID);
4948 auto UnexpandedLine = std::move(
Line);
4950 Line = std::move(PreCall);
4953 llvm::dbgs() <<
"Macro call: " <<
ID->TokenText <<
"(";
4955 llvm::dbgs() <<
"(";
4956 for (
const auto &Arg : Args.value())
4957 for (
const auto &
T : Arg)
4958 llvm::dbgs() <<
T->TokenText <<
" ";
4959 llvm::dbgs() <<
")";
4961 llvm::dbgs() <<
"\n";
4963 if (
Macros.objectLike(
ID->TokenText) && Args &&
4964 !
Macros.hasArity(
ID->TokenText, Args->size())) {
4970 LLVM_DEBUG(llvm::dbgs()
4971 <<
"Macro \"" <<
ID->TokenText
4972 <<
"\" not overloaded for arity " << Args->size()
4973 <<
"or not function-like, using object-like overload.");
4975 UnexpandedLine->Tokens.resize(1);
4976 Tokens->setPosition(Position);
4978 assert(!Args &&
Macros.objectLike(
ID->TokenText));
4980 if ((!Args &&
Macros.objectLike(
ID->TokenText)) ||
4981 (Args &&
Macros.hasArity(
ID->TokenText, Args->size()))) {
4984 Unexpanded[
ID] = std::move(UnexpandedLine);
4986 Macros.expand(ID, std::move(Args));
4987 if (!Expansion.empty())
4988 FormatTok = Tokens->insertTokens(Expansion);
4991 llvm::dbgs() <<
"Expanded: ";
4992 for (
const auto &
T : Expansion)
4993 llvm::dbgs() <<
T->TokenText <<
" ";
4994 llvm::dbgs() <<
"\n";
4998 llvm::dbgs() <<
"Did not expand macro \"" <<
ID->TokenText
4999 <<
"\", because it was used ";
5001 llvm::dbgs() <<
"with " << Args->size();
5003 llvm::dbgs() <<
"without";
5004 llvm::dbgs() <<
" arguments, which doesn't match any definition.\n";
5006 Tokens->setPosition(Position);
5011 if (FormatTok->isNot(tok::comment)) {
5012 distributeComments(Comments, FormatTok);
5017 Comments.push_back(FormatTok);
5020 distributeComments(Comments,
nullptr);
5025template <
typename Iterator>
5026void pushTokens(Iterator Begin, Iterator End,
5028 for (
auto I = Begin; I != End; ++I) {
5029 Into.push_back(I->Tok);
5030 for (
const auto &Child : I->Children)
5031 pushTokens(Child.Tokens.begin(), Child.Tokens.end(), Into);
5036std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>
5037UnwrappedLineParser::parseMacroCall() {
5038 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>> Args;
5039 assert(
Line->Tokens.empty());
5041 if (FormatTok->isNot(tok::l_paren))
5043 unsigned Position = Tokens->getPosition();
5047 auto ArgStart = std::prev(
Line->Tokens.end());
5051 switch (FormatTok->Tok.getKind()) {
5056 case tok::r_paren: {
5062 Args->push_back({});
5063 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5072 Args->push_back({});
5073 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5075 ArgStart = std::prev(
Line->Tokens.end());
5083 Line->Tokens.resize(1);
5084 Tokens->setPosition(Position);
5090 Line->Tokens.push_back(UnwrappedLineNode(
Tok));
5091 if (AtEndOfPPLine) {
5092 auto &
Tok = *
Line->Tokens.back().Tok;
5093 Tok.MustBreakBefore =
true;
5094 Tok.MustBreakBeforeFinalized =
true;
5095 Tok.FirstAfterPPLine =
true;
5096 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.