21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/Support/raw_os_ostream.h"
25#include "llvm/Support/raw_ostream.h"
29#define DEBUG_TYPE "format-parser"
36void printLine(llvm::raw_ostream &OS,
const UnwrappedLine &
Line,
37 StringRef Prefix =
"",
bool PrintText =
false) {
38 OS << Prefix <<
"Line(" <<
Line.Level <<
", FSC=" <<
Line.FirstStartColumn
39 <<
")" << (
Line.InPPDirective ?
" MACRO" :
"") <<
": ";
41 for (std::list<UnwrappedLineNode>::const_iterator I =
Line.Tokens.begin(),
42 E =
Line.Tokens.end();
48 OS << I->Tok->Tok.getName() <<
"["
49 <<
"T=" << (
unsigned)I->Tok->getType()
50 <<
", OC=" << I->Tok->OriginalColumn <<
", \"" << I->Tok->TokenText
52 for (
const auto *CI = I->Children.begin(), *CE = I->Children.end();
55 printLine(OS, *CI, (Prefix +
" ").str());
63[[maybe_unused]]
static void printDebugInfo(
const UnwrappedLine &
Line) {
64 printLine(llvm::dbgs(),
Line);
67class ScopedDeclarationState {
69 ScopedDeclarationState(UnwrappedLine &
Line, llvm::BitVector &Stack,
70 bool MustBeDeclaration)
72 Line.MustBeDeclaration = MustBeDeclaration;
73 Stack.push_back(MustBeDeclaration);
75 ~ScopedDeclarationState() {
78 Line.MustBeDeclaration = Stack.back();
80 Line.MustBeDeclaration =
true;
85 llvm::BitVector &Stack;
91 llvm::raw_os_ostream OS(Stream);
99 bool SwitchToPreprocessorLines =
false)
100 : Parser(Parser), OriginalLines(Parser.CurrentLines) {
101 if (SwitchToPreprocessorLines)
102 Parser.CurrentLines = &Parser.PreprocessorDirectives;
103 else if (!Parser.Line->Tokens.empty())
104 Parser.CurrentLines = &Parser.Line->Tokens.back().Children;
105 PreBlockLine = std::move(Parser.Line);
106 Parser.Line = std::make_unique<UnwrappedLine>();
107 Parser.Line->Level = PreBlockLine->Level;
108 Parser.Line->PPLevel = PreBlockLine->PPLevel;
109 Parser.Line->InPPDirective = PreBlockLine->InPPDirective;
110 Parser.Line->InMacroBody = PreBlockLine->InMacroBody;
111 Parser.Line->UnbracedBodyLevel = PreBlockLine->UnbracedBodyLevel;
115 if (!Parser.Line->Tokens.empty())
116 Parser.addUnwrappedLine();
117 assert(Parser.Line->Tokens.empty());
118 Parser.Line = std::move(PreBlockLine);
119 if (Parser.CurrentLines == &Parser.PreprocessorDirectives)
120 Parser.AtEndOfPPLine =
true;
121 Parser.CurrentLines = OriginalLines;
127 std::unique_ptr<UnwrappedLine> PreBlockLine;
134 const FormatStyle &Style,
unsigned &LineLevel)
136 Style.BraceWrapping.AfterControlStatement ==
137 FormatStyle::BWACS_Always,
138 Style.BraceWrapping.IndentBraces) {}
140 bool WrapBrace,
bool IndentBrace)
141 : LineLevel(LineLevel), OldLineLevel(LineLevel) {
143 Parser->addUnwrappedLine();
151 unsigned OldLineLevel;
158 llvm::SpecificBumpPtrAllocator<FormatToken> &Allocator,
161 Style(Style), IsCpp(Style.
isCpp()),
163 CommentPragmasRegex(Style.CommentPragmas), Tokens(
nullptr),
164 Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1),
165 IncludeGuard(getIncludeGuardState(Style.IndentPPDirectives)),
166 IncludeGuardToken(
nullptr), FirstStartColumn(FirstStartColumn),
167 Macros(Style.Macros, SourceMgr, Style, Allocator, IdentTable) {}
169void UnwrappedLineParser::reset() {
171 IncludeGuard = getIncludeGuardState(Style.IndentPPDirectives);
172 IncludeGuardToken =
nullptr;
174 CommentsBeforeNextToken.clear();
176 AtEndOfPPLine =
false;
177 IsDecltypeAutoFunction =
false;
178 PreprocessorDirectives.clear();
179 CurrentLines = &Lines;
180 DeclarationScopeStack.clear();
181 NestedTooDeep.clear();
182 NestedLambdas.clear();
184 Line->FirstStartColumn = FirstStartColumn;
186 if (!Unexpanded.empty())
188 Token->MacroCtx.reset();
189 CurrentExpandedLines.clear();
190 ExpandedLines.clear();
198 Line->FirstStartColumn = FirstStartColumn;
200 LLVM_DEBUG(llvm::dbgs() <<
"----\n");
202 Tokens = &TokenSource;
210 if (IncludeGuard == IG_Found) {
211 for (
auto &Line : Lines)
212 if (Line.InPPDirective && Line.Level > 0)
218 pushToken(FormatTok);
223 if (!ExpandedLines.empty()) {
224 LLVM_DEBUG(llvm::dbgs() <<
"Expanded lines:\n");
225 for (
const auto &Line : Lines) {
226 if (!Line.Tokens.empty()) {
227 auto it = ExpandedLines.find(Line.Tokens.begin()->Tok);
228 if (it != ExpandedLines.end()) {
229 for (
const auto &Expanded : it->second) {
230 LLVM_DEBUG(printDebugInfo(Expanded));
231 Callback.consumeUnwrappedLine(Expanded);
236 LLVM_DEBUG(printDebugInfo(Line));
237 Callback.consumeUnwrappedLine(Line);
239 Callback.finishRun();
242 LLVM_DEBUG(llvm::dbgs() <<
"Unwrapped lines:\n");
244 LLVM_DEBUG(printDebugInfo(Line));
245 Callback.consumeUnwrappedLine(Line);
247 Callback.finishRun();
249 while (!PPLevelBranchIndex.empty() &&
250 PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) {
251 PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1);
252 PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1);
254 if (!PPLevelBranchIndex.empty()) {
255 ++PPLevelBranchIndex.back();
256 assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size());
257 assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back());
259 }
while (!PPLevelBranchIndex.empty());
262void UnwrappedLineParser::parseFile() {
265 bool MustBeDeclaration = !
Line->InPPDirective && !Style.isJavaScript();
266 ScopedDeclarationState DeclarationState(*
Line, DeclarationScopeStack,
268 if (Style.isTextProto() || (Style.isJson() && FormatTok->
IsFirst))
282 if (Style.isTextProto() && !CommentsBeforeNextToken.empty())
288void UnwrappedLineParser::parseCSharpGenericTypeConstraint() {
298 parseCSharpGenericTypeConstraint();
307void UnwrappedLineParser::parseCSharpAttribute() {
308 int UnpairedSquareBrackets = 1;
310 switch (FormatTok->Tok.getKind()) {
313 --UnpairedSquareBrackets;
314 if (UnpairedSquareBrackets == 0) {
320 ++UnpairedSquareBrackets;
330bool UnwrappedLineParser::precededByCommentOrPPDirective()
const {
331 if (!Lines.empty() && Lines.back().InPPDirective)
345bool UnwrappedLineParser::parseLevel(
const FormatToken *OpeningBrace,
348 const bool InRequiresExpression =
349 OpeningBrace && OpeningBrace->is(TT_RequiresExpressionLBrace);
350 const bool IsPrecededByCommentOrPPDirective =
351 !Style.RemoveBracesLLVM || precededByCommentOrPPDirective();
353 bool HasDoWhile =
false;
354 bool HasLabel =
false;
355 unsigned StatementCount = 0;
356 bool SwitchLabelEncountered =
false;
359 if (FormatTok->isAttribute()) {
361 if (FormatTok->is(tok::l_paren))
366 if (FormatTok->is(TT_MacroBlockBegin))
368 else if (FormatTok->is(TT_MacroBlockEnd))
371 auto ParseDefault = [
this, OpeningBrace, IfKind, &IfLBrace, &HasDoWhile,
372 &HasLabel, &StatementCount] {
373 parseStructuralElement(OpeningBrace, IfKind, &IfLBrace,
374 HasDoWhile ?
nullptr : &HasDoWhile,
375 HasLabel ?
nullptr : &HasLabel);
377 assert(StatementCount > 0 &&
"StatementCount overflow!");
386 if (InRequiresExpression) {
387 FormatTok->setFinalizedType(TT_CompoundRequirementLBrace);
388 }
else if (FormatTok->Previous &&
389 FormatTok->Previous->ClosesRequiresClause) {
395 if (!InRequiresExpression && FormatTok->isNot(TT_MacroBlockBegin)) {
396 if (tryToParseBracedList())
398 FormatTok->setFinalizedType(TT_BlockLBrace);
402 assert(StatementCount > 0 &&
"StatementCount overflow!");
407 if (!Style.RemoveBracesLLVM || Line->InPPDirective ||
408 OpeningBrace->isNoneOf(TT_ControlStatementLBrace, TT_ElseLBrace)) {
411 if (FormatTok->isNot(tok::r_brace) || StatementCount != 1 || HasLabel ||
412 HasDoWhile || IsPrecededByCommentOrPPDirective ||
413 precededByCommentOrPPDirective()) {
417 if (
Next->is(tok::comment) &&
Next->NewlinesBefore == 0)
420 *IfLeftBrace = IfLBrace;
426 case tok::kw_default: {
427 unsigned StoredPosition = Tokens->getPosition();
428 auto *
Next = Tokens->getNextNonComment();
429 FormatTok = Tokens->setPosition(StoredPosition);
430 if (
Next->isNoneOf(tok::colon, tok::arrow)) {
433 parseStructuralElement();
440 if (Style.Language == FormatStyle::LK_Proto || Style.isVerilog() ||
441 (Style.isJavaScript() && Line->MustBeDeclaration)) {
449 if (!SwitchLabelEncountered &&
450 (Style.IndentCaseLabels ||
451 (OpeningBrace && OpeningBrace->is(TT_SwitchExpressionLBrace)) ||
452 (Line->InPPDirective && Line->Level == 1))) {
455 SwitchLabelEncountered =
true;
456 parseStructuralElement();
459 if (Style.isCSharp()) {
461 parseCSharpAttribute();
464 if (handleCppAttributes())
476void UnwrappedLineParser::calculateBraceTypes(
bool ExpectClassBody) {
481 unsigned StoredPosition = Tokens->getPosition();
491 SmallVector<StackEntry, 8> LBraceStack;
492 assert(
Tok->is(tok::l_brace));
495 auto *NextTok = Tokens->getNextNonComment();
497 if (!Line->InMacroBody && !Style.isTableGen()) {
499 while (NextTok->is(tok::hash)) {
500 NextTok = Tokens->getNextToken();
501 if (NextTok->isOneOf(tok::pp_not_keyword, tok::pp_define))
504 NextTok = Tokens->getNextToken();
505 }
while (!NextTok->HasUnescapedNewline && NextTok->isNot(tok::eof));
507 while (NextTok->is(tok::comment))
508 NextTok = Tokens->getNextToken();
512 switch (
Tok->Tok.getKind()) {
514 if (Style.isJavaScript() && PrevTok) {
515 if (PrevTok->isOneOf(tok::colon, tok::less)) {
526 }
else if (PrevTok->is(tok::r_paren)) {
533 LBraceStack.push_back({
Tok, PrevTok});
536 if (LBraceStack.empty())
538 if (
auto *LBrace = LBraceStack.back().Tok; LBrace->is(
BK_Unknown)) {
539 bool ProbablyBracedList =
false;
540 if (Style.Language == FormatStyle::LK_Proto) {
541 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
542 }
else if (LBrace->isNot(TT_EnumLBrace)) {
545 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
546 NextTok->OriginalColumn == 0;
556 ProbablyBracedList = LBrace->is(TT_BracedListLBrace);
558 ProbablyBracedList = ProbablyBracedList ||
559 (Style.isJavaScript() &&
560 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
563 ProbablyBracedList ||
564 (IsCpp && (PrevTok->Tok.isLiteral() ||
565 NextTok->isOneOf(tok::l_paren, tok::arrow)));
572 ProbablyBracedList ||
573 NextTok->isOneOf(tok::comma, tok::period, tok::colon,
574 tok::r_paren, tok::r_square, tok::ellipsis);
579 ProbablyBracedList ||
580 (NextTok->is(tok::l_brace) && LBraceStack.back().PrevTok &&
581 LBraceStack.back().PrevTok->isOneOf(tok::identifier,
585 ProbablyBracedList ||
586 (NextTok->is(tok::identifier) &&
587 PrevTok->isNoneOf(tok::semi, tok::r_brace, tok::l_brace));
589 ProbablyBracedList = ProbablyBracedList ||
590 (NextTok->is(tok::semi) &&
591 (!ExpectClassBody || LBraceStack.size() != 1));
594 ProbablyBracedList ||
595 (NextTok->isBinaryOperator() && !NextIsObjCMethod);
597 if (!Style.isCSharp() && NextTok->is(tok::l_square)) {
600 NextTok = Tokens->getNextToken();
601 ProbablyBracedList = NextTok->isNot(tok::l_square);
605 if (IsCpp && Line->InMacroBody && PrevTok != FormatTok &&
606 !FormatTok->Previous && NextTok->is(tok::eof) &&
610 PrevTok->isNoneOf(tok::semi,
BK_Block, tok::colon)) {
611 ProbablyBracedList =
true;
615 Tok->setBlockKind(BlockKind);
616 LBrace->setBlockKind(BlockKind);
618 LBraceStack.pop_back();
620 case tok::identifier:
621 if (
Tok->isNot(TT_StatementMacro))
632 if (!LBraceStack.empty() && LBraceStack.back().Tok->is(
BK_Unknown))
633 LBraceStack.back().Tok->setBlockKind(
BK_Block);
641 }
while (
Tok->isNot(tok::eof) && !LBraceStack.empty());
644 for (
const auto &Entry : LBraceStack)
648 FormatTok = Tokens->setPosition(StoredPosition);
652void UnwrappedLineParser::setPreviousRBraceType(
TokenType Type) {
653 if (
auto Prev = FormatTok->getPreviousNonComment();
654 Prev && Prev->is(tok::r_brace)) {
655 Prev->setFinalizedType(
Type);
662 seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
665size_t UnwrappedLineParser::computePPHash()
const {
667 for (
const auto &i : PPStack) {
678bool UnwrappedLineParser::mightFitOnOneLine(
680 const auto ColumnLimit = Style.ColumnLimit;
681 if (ColumnLimit == 0)
684 auto &Tokens = ParsedLine.Tokens;
685 assert(!Tokens.empty());
687 const auto *LastToken = Tokens.back().Tok;
690 SmallVector<UnwrappedLineNode> SavedTokens(Tokens.size());
693 for (
const auto &Token : Tokens) {
695 auto &SavedToken = SavedTokens[Index++];
697 SavedToken.Tok->copyFrom(*Token.Tok);
698 SavedToken.Children = std::move(Token.Children);
701 AnnotatedLine
Line(ParsedLine);
702 assert(Line.Last == LastToken);
704 TokenAnnotator Annotator(Style, Keywords);
705 Annotator.annotate(Line);
706 Annotator.calculateFormattingInformation(Line);
708 auto Length = LastToken->TotalLength;
710 assert(OpeningBrace != Tokens.front().Tok);
711 if (
auto Prev = OpeningBrace->Previous;
712 Prev && Prev->TotalLength + ColumnLimit == OpeningBrace->TotalLength) {
713 Length -= ColumnLimit;
715 Length -= OpeningBrace->TokenText.size() + 1;
718 if (
const auto *FirstToken = Line.First; FirstToken->is(tok::r_brace)) {
719 assert(!OpeningBrace || OpeningBrace->is(TT_ControlStatementLBrace));
720 Length -= FirstToken->TokenText.size() + 1;
724 for (
auto &Token : Tokens) {
725 const auto &SavedToken = SavedTokens[Index++];
726 Token.Tok->copyFrom(*SavedToken.Tok);
727 Token.Children = std::move(SavedToken.Children);
728 delete SavedToken.Tok;
732 assert(!Line.InMacroBody);
733 assert(!Line.InPPDirective);
734 return Line.Level * Style.IndentWidth + Length <= ColumnLimit;
737FormatToken *UnwrappedLineParser::parseBlock(
bool MustBeDeclaration,
738 unsigned AddLevels,
bool MunchSemi,
741 bool UnindentWhitesmithsBraces) {
742 auto HandleVerilogBlockLabel = [
this]() {
744 if (Style.isVerilog() && FormatTok->is(tok::colon)) {
746 if (Keywords.isVerilogIdentifier(*FormatTok))
753 const bool VerilogHierarchy =
754 Style.isVerilog() && Keywords.isVerilogHierarchy(*FormatTok);
755 assert((FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) ||
756 (Style.isVerilog() &&
757 (Keywords.isVerilogBegin(*FormatTok) || VerilogHierarchy))) &&
758 "'{' or macro block token expected");
760 const bool FollowedByComment = Tokens->peekNextToken()->is(tok::comment);
761 auto Index = CurrentLines->size();
762 const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
767 if (!VerilogHierarchy && AddLevels > 0 &&
768 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) {
772 size_t PPStartHash = computePPHash();
774 const unsigned InitialLevel = Line->Level;
775 if (VerilogHierarchy) {
776 AddLevels += parseVerilogHierarchyHeader();
778 nextToken(AddLevels);
779 HandleVerilogBlockLabel();
783 if (Line->Level > 300)
786 if (MacroBlock && FormatTok->is(tok::l_paren))
789 size_t NbPreprocessorDirectives =
790 !parsingPPDirective() ? PreprocessorDirectives.size() : 0;
792 size_t OpeningLineIndex =
793 CurrentLines->empty()
795 : (CurrentLines->size() - 1 - NbPreprocessorDirectives);
800 if (UnindentWhitesmithsBraces)
803 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
805 if (AddLevels > 0u && Style.BreakBeforeBraces != FormatStyle::BS_Whitesmiths)
806 Line->Level += AddLevels;
809 const bool SimpleBlock = parseLevel(
Tok, IfKind, &IfLBrace);
814 if (MacroBlock ? FormatTok->isNot(TT_MacroBlockEnd)
815 : FormatTok->isNot(tok::r_brace)) {
816 Line->Level = InitialLevel;
817 FormatTok->setBlockKind(BK_Block);
821 if (FormatTok->is(tok::r_brace)) {
822 FormatTok->setBlockKind(BK_Block);
823 if (Tok->is(TT_NamespaceLBrace))
824 FormatTok->setFinalizedType(TT_NamespaceRBrace);
827 const bool IsFunctionRBrace =
828 FormatTok->is(tok::r_brace) &&
Tok->is(TT_FunctionLBrace);
830 auto RemoveBraces = [=]()
mutable {
833 assert(Tok->isOneOf(TT_ControlStatementLBrace, TT_ElseLBrace));
834 assert(FormatTok->is(tok::r_brace));
835 const bool WrappedOpeningBrace = !Tok->Previous;
836 if (WrappedOpeningBrace && FollowedByComment)
838 const bool HasRequiredIfBraces = IfLBrace && !IfLBrace->Optional;
839 if (KeepBraces && !HasRequiredIfBraces)
841 if (Tok->isNot(TT_ElseLBrace) || !HasRequiredIfBraces) {
842 const FormatToken *Previous = Tokens->getPreviousToken();
844 if (Previous->is(tok::r_brace) && !Previous->Optional)
847 assert(!CurrentLines->empty());
848 auto &LastLine = CurrentLines->back();
849 if (LastLine.Level == InitialLevel + 1 && !mightFitOnOneLine(LastLine))
851 if (
Tok->is(TT_ElseLBrace))
853 if (WrappedOpeningBrace) {
858 return mightFitOnOneLine((*CurrentLines)[Index],
Tok);
860 if (RemoveBraces()) {
861 Tok->MatchingParen = FormatTok;
862 FormatTok->MatchingParen =
Tok;
865 size_t PPEndHash = computePPHash();
868 nextToken(-AddLevels);
873 if (Style.RemoveSemicolon && IsFunctionRBrace) {
874 while (FormatTok->is(tok::semi)) {
875 FormatTok->Optional =
true;
880 HandleVerilogBlockLabel();
882 if (MacroBlock && FormatTok->is(tok::l_paren))
885 Line->Level = InitialLevel;
887 if (FormatTok->is(tok::kw_noexcept)) {
892 if (FormatTok->is(tok::arrow)) {
896 parseStructuralElement();
899 if (MunchSemi && FormatTok->is(tok::semi))
902 if (PPStartHash == PPEndHash) {
903 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
906 (*CurrentLines)[OpeningLineIndex].MatchingClosingBlockLineIndex =
907 CurrentLines->size() - 1;
917 if (
Line.Tokens.size() < 4)
919 auto I =
Line.Tokens.begin();
920 if (I->Tok->TokenText !=
"goog")
923 if (I->Tok->isNot(tok::period))
926 if (I->Tok->TokenText !=
"scope")
929 return I->Tok->is(tok::l_paren);
938 if (
Line.Tokens.size() < 3)
940 auto I =
Line.Tokens.begin();
941 if (I->Tok->isNot(tok::l_paren))
947 return I->Tok->is(tok::l_paren);
952 const bool IsJavaRecord) {
954 return Style.BraceWrapping.AfterClass;
957 if (InitialToken.
is(TT_NamespaceMacro))
958 Kind = tok::kw_namespace;
961 case tok::kw_namespace:
962 return Style.BraceWrapping.AfterNamespace;
964 return Style.BraceWrapping.AfterClass;
966 return Style.BraceWrapping.AfterUnion;
968 return Style.BraceWrapping.AfterStruct;
970 return Style.BraceWrapping.AfterEnum;
976void UnwrappedLineParser::parseChildBlock() {
977 assert(FormatTok->is(tok::l_brace));
978 FormatTok->setBlockKind(BK_Block);
982 bool SkipIndent = (Style.isJavaScript() &&
983 (isGoogScope(*
Line) || isIIFE(*
Line, Keywords)));
984 ScopedLineState LineState(*
this);
985 ScopedDeclarationState DeclarationState(*
Line, DeclarationScopeStack,
987 Line->Level += SkipIndent ? 0 : 1;
988 parseLevel(OpeningBrace);
989 flushComments(isOnNewLine(*FormatTok));
990 Line->Level -= SkipIndent ? 0 : 1;
995void UnwrappedLineParser::parsePPDirective() {
996 assert(FormatTok->is(tok::hash) &&
"'#' expected");
997 ScopedMacroState MacroState(*
Line, Tokens, FormatTok);
1001 if (!FormatTok->Tok.getIdentifierInfo()) {
1006 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
1007 case tok::pp_define:
1014 case tok::pp_ifndef:
1018 case tok::pp_elifdef:
1019 case tok::pp_elifndef:
1026 case tok::pp_pragma:
1030 case tok::pp_warning:
1032 if (!
eof() && Style.isCpp())
1033 FormatTok->setFinalizedType(TT_AfterPPDirective);
1041void UnwrappedLineParser::conditionalCompilationCondition(
bool Unreachable) {
1042 size_t Line = CurrentLines->size();
1043 if (CurrentLines == &PreprocessorDirectives)
1044 Line += Lines.size();
1047 (!PPStack.empty() && PPStack.back().Kind == PP_Unreachable)) {
1048 PPStack.push_back({PP_Unreachable,
Line});
1050 PPStack.push_back({PP_Conditional,
Line});
1054void UnwrappedLineParser::conditionalCompilationStart(
bool Unreachable) {
1056 assert(PPBranchLevel >= 0 && PPBranchLevel <= (
int)PPLevelBranchIndex.size());
1057 if (PPBranchLevel == (
int)PPLevelBranchIndex.size()) {
1058 PPLevelBranchIndex.push_back(0);
1059 PPLevelBranchCount.push_back(0);
1061 PPChainBranchIndex.push(Unreachable ? -1 : 0);
1062 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
1063 conditionalCompilationCondition(Unreachable ||
Skip);
1066void UnwrappedLineParser::conditionalCompilationAlternative() {
1067 if (!PPStack.empty())
1069 assert(PPBranchLevel < (
int)PPLevelBranchIndex.size());
1070 if (!PPChainBranchIndex.empty())
1071 ++PPChainBranchIndex.top();
1072 conditionalCompilationCondition(
1073 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
1074 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
1077void UnwrappedLineParser::conditionalCompilationEnd() {
1078 assert(PPBranchLevel < (
int)PPLevelBranchIndex.size());
1079 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
1080 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel])
1081 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
1084 if (PPBranchLevel > -1)
1086 if (!PPChainBranchIndex.empty())
1087 PPChainBranchIndex.pop();
1088 if (!PPStack.empty())
1092void UnwrappedLineParser::parsePPIf(
bool IfDef) {
1093 bool IfNDef = FormatTok->is(tok::pp_ifndef);
1095 bool Unreachable =
false;
1096 if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText ==
"0"))
1098 if (IfDef && !IfNDef && FormatTok->TokenText ==
"SWIG")
1100 conditionalCompilationStart(Unreachable);
1104 bool MaybeIncludeGuard = IfNDef;
1105 if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
1106 for (
auto &
Line : Lines) {
1107 if (
Line.Tokens.front().Tok->isNot(tok::comment)) {
1108 MaybeIncludeGuard =
false;
1109 IncludeGuard = IG_Rejected;
1117 if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
1118 IncludeGuard = IG_IfNdefed;
1119 IncludeGuardToken = IfCondition;
1123void UnwrappedLineParser::parsePPElse() {
1125 if (IncludeGuard == IG_Defined && PPBranchLevel == 0)
1126 IncludeGuard = IG_Rejected;
1128 assert(PPBranchLevel >= -1);
1129 if (PPBranchLevel == -1)
1130 conditionalCompilationStart(
true);
1131 conditionalCompilationAlternative();
1137void UnwrappedLineParser::parsePPEndIf() {
1138 conditionalCompilationEnd();
1142 if (IncludeGuard == IG_Defined && PPBranchLevel == -1 && Tokens->isEOF() &&
1143 getIncludeGuardState(Style.IndentPPDirectives) == IG_Inited) {
1144 IncludeGuard = IG_Found;
1148void UnwrappedLineParser::parsePPDefine() {
1151 if (!FormatTok->Tok.getIdentifierInfo()) {
1152 IncludeGuard = IG_Rejected;
1153 IncludeGuardToken =
nullptr;
1158 bool MaybeIncludeGuard =
false;
1159 if (IncludeGuard == IG_IfNdefed &&
1160 IncludeGuardToken->TokenText == FormatTok->TokenText) {
1161 IncludeGuard = IG_Defined;
1162 IncludeGuardToken =
nullptr;
1163 for (
auto &
Line : Lines) {
1164 if (
Line.Tokens.front().Tok->isNoneOf(tok::comment, tok::hash)) {
1165 IncludeGuard = IG_Rejected;
1169 MaybeIncludeGuard = IncludeGuard == IG_Defined;
1177 FormatTok->Tok.setKind(tok::identifier);
1178 FormatTok->Tok.setIdentifierInfo(Keywords.kw_internal_ident_after_define);
1182 if (MaybeIncludeGuard && !
eof())
1183 IncludeGuard = IG_Rejected;
1185 if (FormatTok->is(tok::l_paren) && !FormatTok->hasWhitespaceBefore())
1187 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
1188 Line->Level += PPBranchLevel + 1;
1192 Line->PPLevel = PPBranchLevel + (IncludeGuard == IG_Defined ? 0 : 1);
1193 assert((
int)
Line->PPLevel >= 0);
1198 Line->InMacroBody =
true;
1200 if (!Style.SkipMacroDefinitionBody) {
1210 for (
auto *Comment : CommentsBeforeNextToken)
1211 Comment->Finalized =
true;
1214 FormatTok->Finalized =
true;
1215 FormatTok = Tokens->getNextToken();
1221void UnwrappedLineParser::parsePPPragma() {
1222 Line->InPragmaDirective =
true;
1226void UnwrappedLineParser::parsePPUnknown() {
1229 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
1230 Line->Level += PPBranchLevel + 1;
1240 return Tok.isNoneOf(tok::semi, tok::l_brace,
1243 tok::period, tok::periodstar, tok::arrow, tok::arrowstar,
1244 tok::less, tok::greater, tok::slash, tok::percent,
1245 tok::lessless, tok::greatergreater, tok::equal,
1246 tok::plusequal, tok::minusequal, tok::starequal,
1247 tok::slashequal, tok::percentequal, tok::ampequal,
1248 tok::pipeequal, tok::caretequal, tok::greatergreaterequal,
1261 return FormatTok->
is(tok::identifier) &&
1276 FormatTok->
isOneOf(tok::kw_true, tok::kw_false) ||
1287 tok::kw_if, tok::kw_else,
1289 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
1291 tok::kw_switch, tok::kw_case,
1293 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.
kw_finally,
1295 tok::kw_const, tok::kw_class, Keywords.
kw_var, Keywords.
kw_let,
1303 return Tok.isOneOf(tok::kw_char, tok::kw_short, tok::kw_int, tok::kw_long,
1304 tok::kw_unsigned, tok::kw_float, tok::kw_double,
1321 if (FuncName->
isNot(tok::identifier))
1329 Tok->isNoneOf(tok::kw_register, tok::kw_struct, tok::kw_union)) {
1333 if (
Next->isNot(tok::star) && !
Next->Tok.getIdentifierInfo())
1337 if (!
Tok ||
Tok->isNot(tok::r_paren))
1341 if (!
Tok ||
Tok->isNot(tok::identifier))
1344 return Tok->Previous &&
Tok->Previous->isOneOf(tok::l_paren, tok::comma);
1347bool UnwrappedLineParser::parseModuleImport() {
1348 assert(FormatTok->is(Keywords.kw_import) &&
"'import' expected");
1350 if (
auto Token = Tokens->peekNextToken(
true);
1352 Token->isNoneOf(tok::colon, tok::less, tok::string_literal)) {
1358 if (FormatTok->is(tok::colon)) {
1359 FormatTok->setFinalizedType(TT_ModulePartitionColon);
1362 else if (FormatTok->is(tok::less)) {
1364 while (FormatTok->isNoneOf(tok::semi, tok::greater) && !
eof()) {
1367 if (FormatTok->isNot(tok::comment) &&
1368 !FormatTok->TokenText.starts_with(
"//")) {
1369 FormatTok->setFinalizedType(TT_ImplicitStringLiteral);
1374 if (FormatTok->is(tok::semi)) {
1392void UnwrappedLineParser::readTokenWithJavaScriptASI() {
1398 CommentsBeforeNextToken.empty()
1399 ?
Next->NewlinesBefore == 0
1400 : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
1405 bool PreviousStartsTemplateExpr =
1407 if (PreviousMustBeValue ||
Previous->is(tok::r_paren)) {
1410 bool HasAt = llvm::any_of(
Line->Tokens, [](UnwrappedLineNode &LineNode) {
1411 return LineNode.Tok->is(tok::at);
1416 if (
Next->is(tok::exclaim) && PreviousMustBeValue)
1417 return addUnwrappedLine();
1419 bool NextEndsTemplateExpr =
1420 Next->is(TT_TemplateString) &&
Next->TokenText.starts_with(
"}");
1421 if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
1422 (PreviousMustBeValue ||
1423 Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
1424 tok::minusminus))) {
1425 return addUnwrappedLine();
1427 if ((PreviousMustBeValue ||
Previous->is(tok::r_paren)) &&
1429 return addUnwrappedLine();
1433void UnwrappedLineParser::parseStructuralElement(
1434 const FormatToken *OpeningBrace, IfStmtKind *IfKind,
1435 FormatToken **IfLeftBrace,
bool *HasDoWhile,
bool *HasLabel) {
1436 if (Style.isTableGen() && FormatTok->is(tok::pp_include)) {
1438 if (FormatTok->is(tok::string_literal))
1445 while (FormatTok->is(tok::l_square) && handleCppAttributes()) {
1447 }
else if (Style.isVerilog()) {
1448 if (Keywords.isVerilogStructuredProcedure(*FormatTok)) {
1449 parseForOrWhileLoop(
false);
1452 if (FormatTok->isOneOf(Keywords.kw_foreach, Keywords.kw_repeat)) {
1453 parseForOrWhileLoop();
1456 if (FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
1457 Keywords.kw_assume, Keywords.kw_cover)) {
1458 parseIfThenElse(IfKind,
false,
true);
1464 if (FormatTok->isOneOf(Keywords.kw_priority, Keywords.kw_unique,
1465 Keywords.kw_unique0)) {
1467 }
else if (FormatTok->is(tok::l_paren) &&
1468 Tokens->peekNextToken()->is(tok::star)) {
1477 if (FormatTok->isAccessSpecifierKeyword()) {
1478 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp())
1481 parseAccessSpecifier();
1484 switch (FormatTok->Tok.getKind()) {
1487 if (FormatTok->is(tok::l_brace)) {
1488 FormatTok->setFinalizedType(TT_InlineASMBrace);
1490 while (FormatTok && !
eof()) {
1491 if (FormatTok->is(tok::r_brace)) {
1492 FormatTok->setFinalizedType(TT_InlineASMBrace);
1497 FormatTok->Finalized =
true;
1502 case tok::kw_namespace:
1506 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1517 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1521 parseForOrWhileLoop();
1524 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1532 case tok::kw_switch:
1533 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1539 case tok::kw_default: {
1541 if (Style.isVerilog())
1543 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1549 if (FormatTok->is(tok::colon)) {
1550 FormatTok->setFinalizedType(TT_CaseLabelColon);
1554 if (FormatTok->is(tok::arrow)) {
1555 FormatTok->setFinalizedType(TT_CaseLabelArrow);
1556 Default->setFinalizedType(TT_SwitchExpressionLabel);
1565 if (Style.Language == FormatStyle::LK_Proto) {
1569 if (Style.isVerilog()) {
1574 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1583 if (FormatTok->is(tok::kw_case))
1588 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1594 case tok::kw_extern:
1596 if (Style.isVerilog()) {
1599 if (Keywords.isVerilogHierarchy(*FormatTok)) {
1600 parseVerilogHierarchyHeader();
1603 }
else if (FormatTok->is(tok::string_literal)) {
1605 if (FormatTok->is(tok::l_brace)) {
1606 if (Style.BraceWrapping.AfterExternBlock)
1610 unsigned AddLevels =
1611 (Style.IndentExternBlock == FormatStyle::IEBS_Indent) ||
1612 (Style.BraceWrapping.AfterExternBlock &&
1613 Style.IndentExternBlock ==
1614 FormatStyle::IEBS_AfterExternBlock)
1617 parseBlock(
true, AddLevels);
1623 case tok::kw_export:
1624 if (Style.isJavaScript()) {
1625 parseJavaScriptEs6ImportExport();
1630 if (FormatTok->is(tok::kw_namespace)) {
1634 if (FormatTok->is(tok::l_brace)) {
1635 parseCppExportBlock();
1638 if (FormatTok->is(Keywords.kw_import) && parseModuleImport())
1642 case tok::kw_inline:
1644 if (FormatTok->is(tok::kw_namespace)) {
1649 case tok::identifier:
1650 if (FormatTok->is(TT_ForEachMacro)) {
1651 parseForOrWhileLoop();
1654 if (FormatTok->is(TT_MacroBlockBegin)) {
1655 parseBlock(
false, 1u,
1659 if (FormatTok->is(Keywords.kw_import)) {
1660 if (Style.isJavaScript()) {
1661 parseJavaScriptEs6ImportExport();
1664 if (Style.Language == FormatStyle::LK_Proto) {
1666 if (FormatTok->is(tok::kw_public))
1668 if (FormatTok->isNot(tok::string_literal))
1671 if (FormatTok->is(tok::semi))
1676 if (IsCpp && parseModuleImport())
1679 if (IsCpp && FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
1680 Keywords.kw_slots, Keywords.kw_qslots)) {
1682 if (FormatTok->is(tok::colon)) {
1688 if (IsCpp && FormatTok->is(TT_StatementMacro)) {
1689 parseStatementMacro();
1692 if (IsCpp && FormatTok->is(TT_NamespaceMacro)) {
1700 if (!Style.isJavaScript() && !Style.isVerilog() && !Style.isTableGen() &&
1701 Tokens->peekNextToken()->is(tok::colon) && !
Line->MustBeDeclaration) {
1703 if (!
Line->InMacroBody || CurrentLines->size() > 1)
1704 Line->Tokens.begin()->Tok->MustBreakBefore =
true;
1705 FormatTok->setFinalizedType(TT_GotoLabelColon);
1706 parseLabel(!Style.IndentGotoLabels);
1711 if (Style.isJava() && FormatTok->is(Keywords.kw_record)) {
1712 parseRecord(
false,
true);
1722 bool SeenEqual =
false;
1723 for (
const bool InRequiresExpression =
1724 OpeningBrace && OpeningBrace->isOneOf(TT_RequiresExpressionLBrace,
1725 TT_CompoundRequirementLBrace);
1728 switch (FormatTok->Tok.getKind()) {
1731 if (FormatTok->is(tok::l_brace)) {
1736 if (Style.isJava() && FormatTok->is(Keywords.kw_interface)) {
1740 switch (
bool IsAutoRelease =
false; FormatTok->Tok.getObjCKeywordID()) {
1741 case tok::objc_public:
1742 case tok::objc_protected:
1743 case tok::objc_package:
1744 case tok::objc_private:
1745 return parseAccessSpecifier();
1746 case tok::objc_interface:
1747 case tok::objc_implementation:
1748 return parseObjCInterfaceOrImplementation();
1749 case tok::objc_protocol:
1750 if (parseObjCProtocol())
1755 case tok::objc_optional:
1756 case tok::objc_required:
1760 case tok::objc_autoreleasepool:
1761 IsAutoRelease =
true;
1763 case tok::objc_synchronized:
1765 if (!IsAutoRelease && FormatTok->is(tok::l_paren)) {
1769 if (FormatTok->is(tok::l_brace)) {
1770 if (Style.BraceWrapping.AfterControlStatement ==
1771 FormatStyle::BWACS_Always) {
1787 case tok::kw_requires: {
1789 bool ParsedClause = parseRequires(SeenEqual);
1810 if (!IsCpp && !Style.isVerilog()) {
1815 case tok::kw_typedef:
1817 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1818 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS,
1819 Keywords.kw_CF_CLOSED_ENUM,
1820 Keywords.kw_NS_CLOSED_ENUM)) {
1825 if (Style.isVerilog()) {
1830 if (Style.isTableGen()) {
1837 case tok::kw_struct:
1839 if (parseStructLike())
1842 case tok::kw_decltype:
1844 if (FormatTok->is(tok::l_paren)) {
1846 if (FormatTok->Previous &&
1847 FormatTok->Previous->endsSequence(tok::r_paren, tok::kw_auto,
1849 Line->SeenDecltypeAuto =
true;
1856 if (Style.isJava() && FormatTok && FormatTok->is(tok::kw_class))
1858 if (Style.isJavaScript() && FormatTok &&
1859 FormatTok->Tok.getIdentifierInfo()) {
1872 case tok::l_paren: {
1879 Tokens->peekNextToken(
true),
1886 case tok::kw_operator:
1888 if (FormatTok->isBinaryOperator())
1892 const auto *Prev = FormatTok->getPreviousNonComment();
1894 if (Prev && Prev->is(tok::identifier))
1897 if (FormatTok->Tok.isAnyIdentifier() || FormatTok->isTypeName(LangOpts)) {
1900 while (FormatTok->is(tok::star))
1904 if (FormatTok->is(tok::l_paren))
1907 if (FormatTok->is(tok::l_brace))
1912 if (InRequiresExpression)
1913 FormatTok->setFinalizedType(TT_BracedListLBrace);
1914 if (!tryToParsePropertyAccessor() && !tryToParseBracedList()) {
1915 IsDecltypeAutoFunction =
Line->SeenDecltypeAuto;
1920 if (Style.isJava() &&
1921 Line->Tokens.front().Tok->is(Keywords.kw_synchronized)) {
1924 if (Style.BraceWrapping.AfterControlStatement ==
1925 FormatStyle::BWACS_Always) {
1928 }
else if (Style.BraceWrapping.AfterFunction) {
1932 FormatTok->setFinalizedType(TT_FunctionLBrace);
1934 IsDecltypeAutoFunction =
false;
1942 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1948 if (Style.BraceWrapping.AfterFunction)
1952 case tok::identifier: {
1953 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where) &&
1954 Line->MustBeDeclaration) {
1956 parseCSharpGenericTypeConstraint();
1959 if (FormatTok->is(TT_MacroBlockEnd)) {
1968 size_t TokenCount =
Line->Tokens.size();
1969 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_function) &&
1972 Line->Tokens.front().Tok->isNot(Keywords.kw_async)))) {
1973 tryToParseJSFunction();
1976 if ((Style.isJavaScript() || Style.isJava()) &&
1977 FormatTok->is(Keywords.kw_interface)) {
1978 if (Style.isJavaScript()) {
1983 unsigned StoredPosition = Tokens->getPosition();
1985 FormatTok = Tokens->setPosition(StoredPosition);
1996 if (Style.isVerilog()) {
1997 if (FormatTok->is(Keywords.kw_table)) {
1998 parseVerilogTable();
2001 if (Keywords.isVerilogBegin(*FormatTok) ||
2002 Keywords.isVerilogHierarchy(*FormatTok)) {
2009 if (!IsCpp && FormatTok->is(Keywords.kw_interface)) {
2010 if (parseStructLike())
2015 if (IsCpp && FormatTok->is(TT_StatementMacro)) {
2016 parseStatementMacro();
2021 StringRef
Text = FormatTok->TokenText;
2028 if (Style.isJavaScript())
2031 auto OneTokenSoFar = [&]() {
2032 auto I =
Line->Tokens.begin(), E =
Line->Tokens.end();
2033 while (I != E && I->Tok->is(tok::comment))
2035 if (Style.isVerilog())
2036 while (I != E && I->Tok->is(tok::hash))
2038 return I != E && (++I == E);
2040 if (OneTokenSoFar()) {
2043 bool FunctionLike = FormatTok->is(tok::l_paren);
2047 bool FollowedByNewline =
2048 CommentsBeforeNextToken.empty()
2049 ? FormatTok->NewlinesBefore > 0
2050 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
2052 if (FollowedByNewline &&
2053 (
Text.size() >= 5 ||
2054 (FunctionLike && FormatTok->isNot(tok::l_paren))) &&
2056 if (PreviousToken->isNot(TT_UntouchableMacroFunc))
2057 PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro);
2065 if ((Style.isJavaScript() || Style.isCSharp()) &&
2066 FormatTok->is(TT_FatArrow)) {
2067 tryToParseChildBlock();
2073 if (FormatTok->is(tok::l_brace)) {
2077 if (Style.isCSharp())
2078 FormatTok->setBlockKind(BK_BracedInit);
2081 if (Style.isTableGen() &&
2082 Line->Tokens.begin()->Tok->is(Keywords.kw_defset)) {
2083 FormatTok->setFinalizedType(TT_FunctionLBrace);
2084 parseBlock(
false, 1u,
2091 }
else if (Style.Language == FormatStyle::LK_Proto &&
2092 FormatTok->is(tok::less)) {
2094 parseBracedList(
true);
2101 if (Style.isCSharp() &&
2102 (Tokens->peekNextToken()->isAccessSpecifierKeyword() ||
2109 case tok::kw_switch:
2117 if (Style.Language == FormatStyle::LK_Proto) {
2122 if (Style.isVerilog()) {
2127 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
2134 case tok::kw_default:
2136 if (Style.isVerilog()) {
2137 if (FormatTok->is(tok::colon)) {
2141 if (FormatTok->is(Keywords.kw_clocking)) {
2147 parseVerilogCaseLabel();
2153 if (Style.isVerilog()) {
2154 parseVerilogCaseLabel();
2160 if (FormatTok->is(tok::l_brace))
2161 FormatTok->Previous->setFinalizedType(TT_TemplateCloser);
2170bool UnwrappedLineParser::tryToParsePropertyAccessor() {
2171 assert(FormatTok->is(tok::l_brace));
2172 if (!Style.isCSharp())
2175 if (!FormatTok->Previous || FormatTok->Previous->isNot(tok::identifier))
2183 unsigned int StoredPosition = Tokens->getPosition();
2189 bool HasSpecialAccessor =
false;
2190 bool IsTrivialPropertyAccessor =
true;
2193 if (
const bool IsAccessorKeyword =
2194 Tok->
isOneOf(Keywords.kw_get, Keywords.kw_init, Keywords.kw_set);
2195 IsAccessorKeyword ||
Tok->isAccessSpecifierKeyword() ||
2196 Tok->
isOneOf(tok::l_square, tok::semi, Keywords.kw_internal)) {
2197 if (IsAccessorKeyword)
2198 HasSpecialAccessor =
true;
2199 else if (
Tok->
is(tok::l_square))
2201 Tok = Tokens->getNextToken();
2205 IsTrivialPropertyAccessor =
false;
2210 Tokens->setPosition(StoredPosition);
2216 Tokens->setPosition(StoredPosition);
2217 if (!IsTrivialPropertyAccessor && Style.BraceWrapping.AfterFunction)
2221 switch (FormatTok->Tok.getKind()) {
2224 if (FormatTok->is(tok::equal)) {
2225 while (!
eof() && FormatTok->isNot(tok::semi))
2238 if (FormatTok->is(TT_FatArrow)) {
2242 }
while (!
eof() && FormatTok->isNot(tok::semi));
2251 if (FormatTok->isOneOf(Keywords.kw_get, Keywords.kw_init,
2253 !IsTrivialPropertyAccessor) {
2265bool UnwrappedLineParser::tryToParseLambda() {
2266 assert(FormatTok->is(tok::l_square));
2272 if (!tryToParseLambdaIntroducer())
2276 bool InTemplateParameterList =
false;
2278 while (FormatTok->isNot(tok::l_brace)) {
2279 if (FormatTok->isTypeName(LangOpts) || FormatTok->isAttribute()) {
2283 switch (FormatTok->Tok.getKind()) {
2287 parseParens(TT_PointerOrReference);
2293 assert(FormatTok->Previous);
2294 if (FormatTok->Previous->is(tok::r_square))
2295 InTemplateParameterList =
true;
2300 case tok::kw_struct:
2302 case tok::kw_template:
2303 case tok::kw_typename:
2307 case tok::kw_constexpr:
2308 case tok::kw_consteval:
2311 case tok::identifier:
2312 case tok::numeric_constant:
2313 case tok::coloncolon:
2314 case tok::kw_mutable:
2315 case tok::kw_noexcept:
2316 case tok::kw_static:
2341 case tok::equalequal:
2342 case tok::exclaimequal:
2343 case tok::greaterequal:
2344 case tok::lessequal:
2350 if (Arrow || InTemplateParameterList) {
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);
2379 Arrow->setFinalizedType(TT_LambdaArrow);
2381 NestedLambdas.push_back(
Line->SeenDecltypeAuto);
2383 assert(!NestedLambdas.empty());
2384 NestedLambdas.pop_back();
2389bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
2398 const auto *BeforeRParen =
Previous->getPreviousNonComment();
2401 if (!BeforeRParen || BeforeRParen->isNoneOf(tok::greater, tok::r_paren))
2403 }
else if (
Previous->is(tok::star)) {
2407 Previous->isNoneOf(tok::kw_return, tok::kw_co_await, tok::kw_co_yield,
2408 tok::kw_co_return)) {
2412 if (LeftSquare->isCppStructuredBinding(IsCpp))
2414 if (FormatTok->is(tok::l_square) ||
tok::isLiteral(FormatTok->Tok.getKind()))
2416 if (FormatTok->is(tok::r_square)) {
2418 if (
Next->is(tok::greater))
2425void UnwrappedLineParser::tryToParseJSFunction() {
2426 assert(FormatTok->is(Keywords.kw_function));
2427 if (FormatTok->is(Keywords.kw_async))
2433 if (FormatTok->is(tok::star)) {
2434 FormatTok->setFinalizedType(TT_OverloadedOperator);
2439 if (FormatTok->is(tok::identifier))
2442 if (FormatTok->isNot(tok::l_paren))
2448 if (FormatTok->is(tok::colon)) {
2454 if (FormatTok->is(tok::l_brace))
2455 tryToParseBracedList();
2457 while (FormatTok->isNoneOf(tok::l_brace, tok::semi) && !
eof())
2461 if (FormatTok->is(tok::semi))
2467bool UnwrappedLineParser::tryToParseBracedList() {
2468 if (FormatTok->is(BK_Unknown))
2469 calculateBraceTypes();
2470 assert(FormatTok->isNot(BK_Unknown));
2471 if (FormatTok->is(BK_Block))
2478bool UnwrappedLineParser::tryToParseChildBlock() {
2479 assert(Style.isJavaScript() || Style.isCSharp());
2480 assert(FormatTok->is(TT_FatArrow));
2485 if (FormatTok->isNot(tok::l_brace))
2491bool UnwrappedLineParser::parseBracedList(
bool IsAngleBracket,
bool IsEnum) {
2492 assert(!IsAngleBracket || !IsEnum);
2493 bool HasError =
false;
2498 if (Style.isCSharp() && FormatTok->is(TT_FatArrow) &&
2499 tryToParseChildBlock()) {
2502 if (Style.isJavaScript()) {
2503 if (FormatTok->is(Keywords.kw_function)) {
2504 tryToParseJSFunction();
2507 if (FormatTok->is(tok::l_brace)) {
2509 if (tryToParseBracedList())
2514 if (FormatTok->is(IsAngleBracket ? tok::greater : tok::r_brace)) {
2516 FormatTok->setBlockKind(BK_Block);
2517 if (!Style.AllowShortEnumsOnASingleLine)
2523 switch (FormatTok->Tok.getKind()) {
2525 if (Style.isCSharp())
2534 if (Style.isJavaScript()) {
2535 if (FormatTok->is(tok::l_brace))
2543 FormatTok->setBlockKind(BK_BracedInit);
2544 if (!IsAngleBracket) {
2545 auto *Prev = FormatTok->Previous;
2546 if (Prev && Prev->is(tok::greater))
2547 Prev->setFinalizedType(TT_TemplateCloser);
2555 parseBracedList(
true);
2562 if (Style.isJavaScript()) {
2573 if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
2576 case tok::kw_requires: {
2577 auto *RequiresToken = FormatTok;
2579 parseRequiresExpression(RequiresToken);
2595bool UnwrappedLineParser::parseParens(TokenType AmpAmpTokenType,
2597 assert(FormatTok->is(tok::l_paren) &&
"'(' expected.");
2598 auto *LParen = FormatTok;
2599 auto *Prev = FormatTok->Previous;
2600 bool SeenComma =
false;
2601 bool SeenEqual =
false;
2602 bool MightBeFoldExpr =
false;
2604 const bool MightBeStmtExpr = FormatTok->is(tok::l_brace);
2605 if (!InMacroCall && Prev && Prev->is(TT_FunctionLikeMacro))
2608 switch (FormatTok->Tok.getKind()) {
2610 if (parseParens(AmpAmpTokenType, InMacroCall))
2612 if (Style.isJava() && FormatTok->is(tok::l_brace))
2615 case tok::r_paren: {
2616 auto *RParen = FormatTok;
2619 auto OptionalParens = [&] {
2620 if (MightBeStmtExpr || MightBeFoldExpr || SeenComma || InMacroCall ||
2621 Line->InMacroBody ||
2622 Style.RemoveParentheses == FormatStyle::RPS_Leave ||
2623 RParen->getPreviousNonComment() == LParen) {
2626 const bool DoubleParens =
2627 Prev->is(tok::l_paren) && FormatTok->is(tok::r_paren);
2629 const auto *PrevPrev = Prev->getPreviousNonComment();
2630 const bool Excluded =
2632 (PrevPrev->isOneOf(tok::kw___attribute, tok::kw_decltype) ||
2634 (PrevPrev->isOneOf(tok::kw_if, tok::kw_while) ||
2635 PrevPrev->endsSequence(tok::kw_constexpr, tok::kw_if))));
2639 const bool CommaSeparated =
2640 Prev->isOneOf(tok::l_paren, tok::comma) &&
2641 FormatTok->isOneOf(tok::comma, tok::r_paren);
2642 if (CommaSeparated &&
2644 !Prev->endsSequence(tok::comma, tok::ellipsis) &&
2646 !(FormatTok->is(tok::comma) &&
2647 Tokens->peekNextToken()->is(tok::ellipsis))) {
2650 const bool ReturnParens =
2651 Style.RemoveParentheses == FormatStyle::RPS_ReturnStatement &&
2652 ((NestedLambdas.empty() && !IsDecltypeAutoFunction) ||
2653 (!NestedLambdas.empty() && !NestedLambdas.back())) &&
2654 Prev->isOneOf(tok::kw_return, tok::kw_co_return) &&
2655 FormatTok->is(tok::semi);
2661 if (Prev->is(TT_TypenameMacro)) {
2662 LParen->setFinalizedType(TT_TypeDeclarationParen);
2663 RParen->setFinalizedType(TT_TypeDeclarationParen);
2664 }
else if (Prev->is(tok::greater) && RParen->Previous == LParen) {
2665 Prev->setFinalizedType(TT_TemplateCloser);
2666 }
else if (OptionalParens()) {
2667 LParen->Optional =
true;
2668 RParen->Optional =
true;
2680 if (!tryToParseBracedList())
2685 if (FormatTok->is(tok::l_brace)) {
2695 MightBeFoldExpr =
true;
2700 if (Style.isCSharp() && FormatTok->is(TT_FatArrow))
2701 tryToParseChildBlock();
2706 if (Style.isJavaScript())
2711 case tok::identifier:
2712 if (Style.isJavaScript() && (FormatTok->is(Keywords.kw_function)))
2713 tryToParseJSFunction();
2717 case tok::kw_switch:
2723 case tok::kw_requires: {
2724 auto RequiresToken = FormatTok;
2726 parseRequiresExpression(RequiresToken);
2730 if (AmpAmpTokenType != TT_Unknown)
2731 FormatTok->setFinalizedType(AmpAmpTokenType);
2743 assert(FormatTok->is(tok::l_square) &&
"'[' expected.");
2744 if (tryToParseLambda())
2748 switch (FormatTok->Tok.getKind()) {
2761 case tok::l_brace: {
2762 if (!tryToParseBracedList())
2769 if (FormatTok->is(tok::l_brace)) {
2781void UnwrappedLineParser::keepAncestorBraces() {
2782 if (!Style.RemoveBracesLLVM)
2785 const int MaxNestingLevels = 2;
2786 const int Size = NestedTooDeep.size();
2787 if (Size >= MaxNestingLevels)
2788 NestedTooDeep[
Size - MaxNestingLevels] =
true;
2789 NestedTooDeep.push_back(
false);
2793 for (
const auto &
Token : llvm::reverse(
Line.Tokens))
2800void UnwrappedLineParser::parseUnbracedBody(
bool CheckEOF) {
2803 if (Style.InsertBraces && !
Line->InPPDirective && !
Line->Tokens.empty() &&
2804 PreprocessorDirectives.empty() && FormatTok->isNot(tok::semi)) {
2805 Tok = Style.BraceWrapping.AfterControlStatement == FormatStyle::BWACS_Never
2806 ? getLastNonComment(*
Line)
2809 if (
Tok->BraceCount < 0) {
2810 assert(
Tok->BraceCount == -1);
2813 Tok->BraceCount = -1;
2819 ++
Line->UnbracedBodyLevel;
2820 parseStructuralElement();
2821 --
Line->UnbracedBodyLevel;
2824 assert(!
Line->InPPDirective);
2826 for (
const auto &L : llvm::reverse(*CurrentLines)) {
2828 Tok = L.Tokens.back().Tok;
2836 if (CheckEOF &&
eof())
2846 assert(LeftBrace->
is(tok::l_brace));
2854 assert(RightBrace->
is(tok::r_brace));
2862void UnwrappedLineParser::handleAttributes() {
2864 if (FormatTok->isAttribute())
2866 else if (FormatTok->is(tok::l_square))
2867 handleCppAttributes();
2870bool UnwrappedLineParser::handleCppAttributes() {
2872 assert(FormatTok->is(tok::l_square));
2873 if (!tryToParseSimpleAttribute())
2880bool UnwrappedLineParser::isBlockBegin(
const FormatToken &
Tok)
const {
2883 return Style.isVerilog() ? Keywords.isVerilogBegin(
Tok)
2884 :
Tok.
is(tok::l_brace);
2887FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
2889 bool IsVerilogAssert) {
2890 assert((FormatTok->is(tok::kw_if) ||
2891 (Style.isVerilog() &&
2892 FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
2893 Keywords.kw_assume, Keywords.kw_cover))) &&
2897 if (IsVerilogAssert) {
2899 if (FormatTok->is(Keywords.kw_verilogHash)) {
2901 if (FormatTok->is(tok::numeric_constant))
2903 }
else if (FormatTok->isOneOf(Keywords.kw_final, Keywords.kw_property,
2904 Keywords.kw_sequence)) {
2910 if (Style.isTableGen()) {
2911 while (!
eof() && FormatTok->isNot(Keywords.kw_then)) {
2918 if (FormatTok->is(tok::exclaim))
2921 bool KeepIfBraces =
true;
2922 if (FormatTok->is(tok::kw_consteval)) {
2925 KeepIfBraces = !Style.RemoveBracesLLVM || KeepBraces;
2926 if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
2928 if (FormatTok->is(tok::l_paren)) {
2929 FormatTok->setFinalizedType(TT_ConditionLParen);
2935 if (IsVerilogAssert && FormatTok->is(tok::semi)) {
2941 bool NeedsUnwrappedLine =
false;
2942 keepAncestorBraces();
2945 IfStmtKind IfBlockKind = IfStmtKind::NotIf;
2947 if (isBlockBegin(*FormatTok)) {
2948 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
2949 IfLeftBrace = FormatTok;
2950 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
2951 parseBlock(
false, 1u,
2952 true, KeepIfBraces, &IfBlockKind);
2953 setPreviousRBraceType(TT_ControlStatementRBrace);
2954 if (Style.BraceWrapping.BeforeElse)
2957 NeedsUnwrappedLine =
true;
2958 }
else if (IsVerilogAssert && FormatTok->is(tok::kw_else)) {
2961 parseUnbracedBody();
2964 if (Style.RemoveBracesLLVM) {
2965 assert(!NestedTooDeep.empty());
2966 KeepIfBraces = KeepIfBraces ||
2967 (IfLeftBrace && !IfLeftBrace->MatchingParen) ||
2968 NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly ||
2969 IfBlockKind == IfStmtKind::IfElseIf;
2972 bool KeepElseBraces = KeepIfBraces;
2974 IfStmtKind
Kind = IfStmtKind::IfOnly;
2976 if (FormatTok->is(tok::kw_else)) {
2977 if (Style.RemoveBracesLLVM) {
2978 NestedTooDeep.back() =
false;
2979 Kind = IfStmtKind::IfElse;
2983 if (isBlockBegin(*FormatTok)) {
2984 const bool FollowedByIf = Tokens->peekNextToken()->is(tok::kw_if);
2985 FormatTok->setFinalizedType(TT_ElseLBrace);
2986 ElseLeftBrace = FormatTok;
2987 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
2988 IfStmtKind ElseBlockKind = IfStmtKind::NotIf;
2990 parseBlock(
false, 1u,
2991 true, KeepElseBraces, &ElseBlockKind);
2992 setPreviousRBraceType(TT_ElseRBrace);
2993 if (FormatTok->is(tok::kw_else)) {
2994 KeepElseBraces = KeepElseBraces ||
2995 ElseBlockKind == IfStmtKind::IfOnly ||
2996 ElseBlockKind == IfStmtKind::IfElseIf;
2997 }
else if (FollowedByIf && IfLBrace && !IfLBrace->Optional) {
2998 KeepElseBraces =
true;
2999 assert(ElseLeftBrace->MatchingParen);
3003 }
else if (!IsVerilogAssert && FormatTok->is(tok::kw_if)) {
3006 const bool IsPrecededByComment =
Previous->is(tok::comment);
3007 if (IsPrecededByComment) {
3011 bool TooDeep =
true;
3012 if (Style.RemoveBracesLLVM) {
3013 Kind = IfStmtKind::IfElseIf;
3014 TooDeep = NestedTooDeep.pop_back_val();
3016 ElseLeftBrace = parseIfThenElse(
nullptr, KeepIfBraces);
3017 if (Style.RemoveBracesLLVM)
3018 NestedTooDeep.push_back(TooDeep);
3019 if (IsPrecededByComment)
3022 parseUnbracedBody(
true);
3025 KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse;
3026 if (NeedsUnwrappedLine)
3030 if (!Style.RemoveBracesLLVM)
3033 assert(!NestedTooDeep.empty());
3034 KeepElseBraces = KeepElseBraces ||
3035 (ElseLeftBrace && !ElseLeftBrace->MatchingParen) ||
3036 NestedTooDeep.back();
3038 NestedTooDeep.pop_back();
3040 if (!KeepIfBraces && !KeepElseBraces) {
3043 }
else if (IfLeftBrace) {
3044 FormatToken *IfRightBrace = IfLeftBrace->MatchingParen;
3046 assert(IfRightBrace->MatchingParen == IfLeftBrace);
3047 assert(!IfLeftBrace->Optional);
3048 assert(!IfRightBrace->Optional);
3049 IfLeftBrace->MatchingParen =
nullptr;
3050 IfRightBrace->MatchingParen =
nullptr;
3060void UnwrappedLineParser::parseTryCatch() {
3061 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) &&
"'try' expected");
3063 bool NeedsUnwrappedLine =
false;
3064 bool HasCtorInitializer =
false;
3065 if (FormatTok->is(tok::colon)) {
3066 auto *Colon = FormatTok;
3069 if (FormatTok->is(tok::identifier)) {
3070 HasCtorInitializer =
true;
3071 Colon->setFinalizedType(TT_CtorInitializerColon);
3076 while (FormatTok->is(tok::comma))
3079 while (FormatTok->is(tok::identifier)) {
3081 if (FormatTok->is(tok::l_paren)) {
3083 }
else if (FormatTok->is(tok::l_brace)) {
3090 while (FormatTok->is(tok::comma))
3095 if (Style.isJava() && FormatTok->is(tok::l_paren))
3098 keepAncestorBraces();
3100 if (FormatTok->is(tok::l_brace)) {
3101 if (HasCtorInitializer)
3102 FormatTok->setFinalizedType(TT_FunctionLBrace);
3103 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3105 if (Style.BraceWrapping.BeforeCatch)
3108 NeedsUnwrappedLine =
true;
3109 }
else if (FormatTok->isNot(tok::kw_catch)) {
3115 parseStructuralElement();
3118 for (
bool SeenCatch =
false;;) {
3119 if (FormatTok->is(tok::at))
3121 if (FormatTok->isNoneOf(tok::kw_catch, Keywords.kw___except,
3122 tok::kw___finally, tok::objc_catch,
3123 tok::objc_finally) &&
3124 !((Style.isJava() || Style.isJavaScript()) &&
3125 FormatTok->is(Keywords.kw_finally))) {
3128 if (FormatTok->is(tok::kw_catch))
3131 while (FormatTok->isNot(tok::l_brace)) {
3132 if (FormatTok->is(tok::l_paren)) {
3136 if (FormatTok->isOneOf(tok::semi, tok::r_brace) ||
eof()) {
3137 if (Style.RemoveBracesLLVM)
3138 NestedTooDeep.pop_back();
3144 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3147 NeedsUnwrappedLine =
false;
3148 Line->MustBeDeclaration =
false;
3149 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3151 if (Style.BraceWrapping.BeforeCatch)
3154 NeedsUnwrappedLine =
true;
3157 if (Style.RemoveBracesLLVM)
3158 NestedTooDeep.pop_back();
3160 if (NeedsUnwrappedLine)
3164void UnwrappedLineParser::parseNamespaceOrExportBlock(
unsigned AddLevels) {
3165 bool ManageWhitesmithsBraces =
3166 AddLevels == 0u && Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
3170 if (ManageWhitesmithsBraces)
3175 parseBlock(
true, AddLevels,
true,
3176 true,
nullptr, ManageWhitesmithsBraces);
3178 addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep);
3180 if (ManageWhitesmithsBraces)
3184void UnwrappedLineParser::parseNamespace() {
3185 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
3186 "'namespace' expected");
3190 if (InitialToken.is(TT_NamespaceMacro)) {
3193 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
3194 tok::l_square, tok::period, tok::l_paren) ||
3195 (Style.isCSharp() && FormatTok->is(tok::kw_union))) {
3196 if (FormatTok->is(tok::l_square))
3198 else if (FormatTok->is(tok::l_paren))
3204 if (FormatTok->is(tok::l_brace)) {
3205 FormatTok->setFinalizedType(TT_NamespaceLBrace);
3210 unsigned AddLevels =
3211 Style.NamespaceIndentation == FormatStyle::NI_All ||
3212 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
3213 DeclarationScopeStack.size() > 1)
3216 parseNamespaceOrExportBlock(AddLevels);
3221void UnwrappedLineParser::parseCppExportBlock() {
3222 parseNamespaceOrExportBlock(Style.IndentExportBlock ? 1 : 0);
3225void UnwrappedLineParser::parseNew() {
3226 assert(FormatTok->is(tok::kw_new) &&
"'new' expected");
3229 if (Style.isCSharp()) {
3232 if (FormatTok->is(tok::l_paren))
3236 if (FormatTok->is(tok::l_brace))
3239 if (FormatTok->isOneOf(tok::semi, tok::comma))
3246 if (!Style.isJava())
3252 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
3256 if (FormatTok->is(tok::l_paren)) {
3260 if (FormatTok->is(tok::l_brace))
3268void UnwrappedLineParser::parseLoopBody(
bool KeepBraces,
bool WrapRightBrace) {
3269 keepAncestorBraces();
3271 if (isBlockBegin(*FormatTok)) {
3272 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3274 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3275 parseBlock(
false, 1u,
3277 setPreviousRBraceType(TT_ControlStatementRBrace);
3279 assert(!NestedTooDeep.empty());
3280 if (!NestedTooDeep.back())
3286 parseUnbracedBody();
3290 NestedTooDeep.pop_back();
3293void UnwrappedLineParser::parseForOrWhileLoop(
bool HasParens) {
3294 assert((FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) ||
3295 (Style.isVerilog() &&
3296 FormatTok->isOneOf(Keywords.kw_always, Keywords.kw_always_comb,
3297 Keywords.kw_always_ff, Keywords.kw_always_latch,
3298 Keywords.kw_final, Keywords.kw_initial,
3299 Keywords.kw_foreach, Keywords.kw_forever,
3300 Keywords.kw_repeat))) &&
3301 "'for', 'while' or foreach macro expected");
3302 const bool KeepBraces = !Style.RemoveBracesLLVM ||
3303 FormatTok->isNoneOf(tok::kw_for, tok::kw_while);
3307 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
3309 if (IsCpp && FormatTok->is(tok::kw_co_await))
3311 if (HasParens && FormatTok->is(tok::l_paren)) {
3315 if (Style.isVerilog())
3316 FormatTok->setFinalizedType(TT_ConditionLParen);
3320 if (Style.isVerilog()) {
3322 parseVerilogSensitivityList();
3323 }
else if (Style.AllowShortLoopsOnASingleLine && FormatTok->is(tok::semi) &&
3324 Tokens->getPreviousToken()->is(tok::r_paren)) {
3331 parseLoopBody(KeepBraces,
true);
3334void UnwrappedLineParser::parseDoWhile() {
3335 assert(FormatTok->is(tok::kw_do) &&
"'do' expected");
3338 parseLoopBody(
true, Style.BraceWrapping.BeforeWhile);
3341 if (FormatTok->isNot(tok::kw_while)) {
3346 FormatTok->setFinalizedType(TT_DoWhile);
3350 if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)
3354 parseStructuralElement();
3357void UnwrappedLineParser::parseLabel(
bool LeftAlignLabel) {
3359 unsigned OldLineLevel =
Line->Level;
3363 else if (
Line->Level > 1 || (!
Line->InPPDirective &&
Line->Level > 0))
3366 if (!Style.IndentCaseBlocks && CommentsBeforeNextToken.empty() &&
3367 FormatTok->is(tok::l_brace)) {
3369 CompoundStatementIndenter Indenter(
this,
Line->Level,
3370 Style.BraceWrapping.AfterCaseLabel,
3371 Style.BraceWrapping.IndentBraces);
3373 if (FormatTok->is(tok::kw_break)) {
3374 if (Style.BraceWrapping.AfterControlStatement ==
3375 FormatStyle::BWACS_Always) {
3377 if (!Style.IndentCaseBlocks &&
3378 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) {
3382 parseStructuralElement();
3386 if (FormatTok->is(tok::semi))
3390 Line->Level = OldLineLevel;
3391 if (FormatTok->isNot(tok::l_brace)) {
3392 parseStructuralElement();
3397void UnwrappedLineParser::parseCaseLabel() {
3398 assert(FormatTok->is(tok::kw_case) &&
"'case' expected");
3399 auto *Case = FormatTok;
3404 if (FormatTok->is(tok::colon)) {
3405 FormatTok->setFinalizedType(TT_CaseLabelColon);
3408 if (Style.isJava() && FormatTok->is(tok::arrow)) {
3409 FormatTok->setFinalizedType(TT_CaseLabelArrow);
3410 Case->setFinalizedType(TT_SwitchExpressionLabel);
3417void UnwrappedLineParser::parseSwitch(
bool IsExpr) {
3418 assert(FormatTok->is(tok::kw_switch) &&
"'switch' expected");
3420 if (FormatTok->is(tok::l_paren))
3423 keepAncestorBraces();
3425 if (FormatTok->is(tok::l_brace)) {
3426 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3427 FormatTok->setFinalizedType(IsExpr ? TT_SwitchExpressionLBrace
3428 : TT_ControlStatementLBrace);
3433 setPreviousRBraceType(TT_ControlStatementRBrace);
3439 parseStructuralElement();
3443 if (Style.RemoveBracesLLVM)
3444 NestedTooDeep.pop_back();
3447void UnwrappedLineParser::parseAccessSpecifier() {
3450 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
3453 if (FormatTok->is(tok::colon))
3461bool UnwrappedLineParser::parseRequires(
bool SeenEqual) {
3462 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3463 auto RequiresToken = FormatTok;
3469 switch (FormatTok->Tok.getKind()) {
3472 parseRequiresExpression(RequiresToken);
3479 parseRequiresClause(RequiresToken);
3490 auto *PreviousNonComment = RequiresToken->getPreviousNonComment();
3492 if (!PreviousNonComment ||
3493 PreviousNonComment->is(TT_RequiresExpressionLBrace)) {
3496 parseRequiresClause(RequiresToken);
3500 switch (PreviousNonComment->Tok.getKind()) {
3503 case tok::kw_noexcept:
3508 parseRequiresClause(RequiresToken);
3517 auto PrevPrev = PreviousNonComment->getPreviousNonComment();
3518 if ((PrevPrev && PrevPrev->is(tok::kw_const)) || !SeenEqual) {
3519 parseRequiresClause(RequiresToken);
3525 if (PreviousNonComment->isTypeOrIdentifier(LangOpts)) {
3527 parseRequiresClause(RequiresToken);
3531 parseRequiresExpression(RequiresToken);
3541 unsigned StoredPosition = Tokens->getPosition();
3544 auto PeekNext = [&Lookahead, &NextToken,
this] {
3546 NextToken = Tokens->getNextToken();
3549 bool FoundType =
false;
3550 bool LastWasColonColon =
false;
3553 for (; Lookahead < 50; PeekNext()) {
3554 switch (NextToken->Tok.getKind()) {
3555 case tok::kw_volatile:
3558 if (OpenAngles == 0) {
3559 FormatTok = Tokens->setPosition(StoredPosition);
3560 parseRequiresExpression(RequiresToken);
3568 case tok::coloncolon:
3569 LastWasColonColon =
true;
3571 case tok::kw_decltype:
3572 case tok::identifier:
3573 if (FoundType && !LastWasColonColon && OpenAngles == 0) {
3574 FormatTok = Tokens->setPosition(StoredPosition);
3575 parseRequiresExpression(RequiresToken);
3579 LastWasColonColon =
false;
3588 if (NextToken->isTypeName(LangOpts)) {
3589 FormatTok = Tokens->setPosition(StoredPosition);
3590 parseRequiresExpression(RequiresToken);
3597 FormatTok = Tokens->setPosition(StoredPosition);
3598 parseRequiresClause(RequiresToken);
3609void UnwrappedLineParser::parseRequiresClause(
FormatToken *RequiresToken) {
3610 assert(FormatTok->getPreviousNonComment() == RequiresToken);
3611 assert(RequiresToken->is(tok::kw_requires) &&
"'requires' expected");
3616 bool InRequiresExpression =
3617 !RequiresToken->Previous ||
3618 RequiresToken->Previous->is(TT_RequiresExpressionLBrace);
3620 RequiresToken->setFinalizedType(InRequiresExpression
3621 ? TT_RequiresClauseInARequiresExpression
3622 : TT_RequiresClause);
3626 parseConstraintExpression();
3628 if (!InRequiresExpression && FormatTok->Previous)
3629 FormatTok->Previous->ClosesRequiresClause =
true;
3639void UnwrappedLineParser::parseRequiresExpression(
FormatToken *RequiresToken) {
3640 assert(FormatTok->getPreviousNonComment() == RequiresToken);
3641 assert(RequiresToken->is(tok::kw_requires) &&
"'requires' expected");
3643 RequiresToken->setFinalizedType(TT_RequiresExpression);
3645 if (FormatTok->is(tok::l_paren)) {
3646 FormatTok->setFinalizedType(TT_RequiresExpressionLParen);
3650 if (FormatTok->is(tok::l_brace)) {
3651 FormatTok->setFinalizedType(TT_RequiresExpressionLBrace);
3660void UnwrappedLineParser::parseConstraintExpression() {
3667 bool LambdaNextTimeAllowed =
true;
3677 bool TopLevelParensAllowed =
true;
3680 bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed,
false);
3682 switch (FormatTok->Tok.getKind()) {
3683 case tok::kw_requires: {
3684 auto RequiresToken = FormatTok;
3686 parseRequiresExpression(RequiresToken);
3691 if (!TopLevelParensAllowed)
3693 parseParens(TT_BinaryOperator);
3694 TopLevelParensAllowed =
false;
3698 if (!LambdaThisTimeAllowed || !tryToParseLambda())
3705 case tok::kw_struct:
3715 FormatTok->setFinalizedType(TT_BinaryOperator);
3717 LambdaNextTimeAllowed =
true;
3718 TopLevelParensAllowed =
true;
3723 LambdaNextTimeAllowed = LambdaThisTimeAllowed;
3727 case tok::kw_sizeof:
3729 case tok::greaterequal:
3730 case tok::greatergreater:
3732 case tok::lessequal:
3734 case tok::equalequal:
3736 case tok::exclaimequal:
3741 LambdaNextTimeAllowed =
true;
3742 TopLevelParensAllowed =
true;
3747 case tok::numeric_constant:
3748 case tok::coloncolon:
3751 TopLevelParensAllowed =
false;
3756 case tok::kw_static_cast:
3757 case tok::kw_const_cast:
3758 case tok::kw_reinterpret_cast:
3759 case tok::kw_dynamic_cast:
3761 if (FormatTok->isNot(tok::less))
3765 parseBracedList(
true);
3769 if (!FormatTok->Tok.getIdentifierInfo()) {
3779 assert(FormatTok->Previous);
3780 switch (FormatTok->Previous->Tok.getKind()) {
3781 case tok::coloncolon:
3785 case tok::kw_requires:
3794 if (FormatTok->is(tok::less)) {
3796 parseBracedList(
true);
3798 TopLevelParensAllowed =
false;
3804bool UnwrappedLineParser::parseEnum() {
3808 if (FormatTok->is(tok::kw_enum))
3814 if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question))
3818 if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal))
3823 if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
3825 while (FormatTok->is(tok::l_square))
3826 if (!handleCppAttributes())
3830 while (FormatTok->Tok.getIdentifierInfo() ||
3831 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
3832 tok::greater, tok::comma, tok::question,
3834 if (Style.isVerilog()) {
3835 FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
3838 while (FormatTok->is(tok::l_square))
3844 if (FormatTok->is(tok::l_paren))
3846 if (FormatTok->is(tok::identifier)) {
3850 if (IsCpp && FormatTok->is(tok::identifier))
3856 if (FormatTok->isNot(tok::l_brace))
3858 FormatTok->setFinalizedType(TT_EnumLBrace);
3859 FormatTok->setBlockKind(BK_Block);
3861 if (Style.isJava()) {
3863 parseJavaEnumBody();
3866 if (Style.Language == FormatStyle::LK_Proto) {
3871 if (!Style.AllowShortEnumsOnASingleLine &&
3877 if (!Style.AllowShortEnumsOnASingleLine) {
3881 bool HasError = !parseBracedList(
false,
true);
3882 if (!Style.AllowShortEnumsOnASingleLine)
3885 if (FormatTok->is(tok::semi))
3889 setPreviousRBraceType(TT_EnumRBrace);
3897bool UnwrappedLineParser::parseStructLike() {
3902 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp()) {
3903 if (FormatTok->is(tok::semi))
3914class ScopedTokenPosition {
3915 unsigned StoredPosition;
3916 FormatTokenSource *Tokens;
3919 ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) {
3920 assert(Tokens &&
"Tokens expected to not be null");
3921 StoredPosition = Tokens->getPosition();
3924 ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); }
3930bool UnwrappedLineParser::tryToParseSimpleAttribute() {
3931 ScopedTokenPosition AutoPosition(Tokens);
3939 if (
Tok->
is(tok::r_square))
3941 Tok = Tokens->getNextToken();
3943 if (
Tok->
is(tok::eof))
3945 Tok = Tokens->getNextToken();
3948 Tok = Tokens->getNextToken();
3949 if (
Tok->
is(tok::semi))
3954void UnwrappedLineParser::parseJavaEnumBody() {
3955 assert(FormatTok->is(tok::l_brace));
3961 unsigned StoredPosition = Tokens->getPosition();
3962 bool IsSimple =
true;
3965 if (
Tok->
is(tok::r_brace))
3973 Tok = Tokens->getNextToken();
3975 FormatTok = Tokens->setPosition(StoredPosition);
3992 if (FormatTok->is(tok::l_brace)) {
3994 parseBlock(
true, 1u,
3996 }
else if (FormatTok->is(tok::l_paren)) {
3998 }
else if (FormatTok->is(tok::comma)) {
4001 }
else if (FormatTok->is(tok::semi)) {
4005 }
else if (FormatTok->is(tok::r_brace)) {
4014 parseLevel(OpeningBrace);
4020void UnwrappedLineParser::parseRecord(
bool ParseAsExpr,
bool IsJavaRecord) {
4021 assert(!IsJavaRecord || FormatTok->is(Keywords.kw_record));
4026 IsJavaRecord && FormatTok->is(tok::identifier) ? FormatTok :
nullptr;
4027 bool IsDerived =
false;
4029 return Tok->
is(tok::identifier) &&
Tok->TokenText !=
Tok->TokenText.upper();
4033 bool JSPastExtendsOrImplements =
false;
4037 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
4038 tok::kw_alignas, tok::l_square) ||
4039 FormatTok->isAttribute() ||
4040 ((Style.isJava() || Style.isJavaScript()) &&
4041 FormatTok->isOneOf(tok::period, tok::comma))) {
4042 if (Style.isJavaScript() &&
4043 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
4044 JSPastExtendsOrImplements =
true;
4049 if (FormatTok->is(tok::l_brace)) {
4050 tryToParseBracedList();
4054 if (FormatTok->is(tok::l_square) && handleCppAttributes())
4058 switch (FormatTok->Tok.getKind()) {
4061 if (IsJavaRecord || !IsNonMacroIdentifier(
Previous) ||
4063 Previous->Previous == &InitialToken) {
4067 case tok::coloncolon:
4071 if (JSPastExtendsOrImplements || ClassName ||
4082 auto IsListInitialization = [&] {
4083 if (!ClassName || IsDerived || JSPastExtendsOrImplements)
4085 assert(FormatTok->is(tok::l_brace));
4086 const auto *Prev = FormatTok->getPreviousNonComment();
4088 return Prev != ClassName && Prev->is(tok::identifier) &&
4089 Prev->isNot(Keywords.kw_final) && tryToParseBracedList();
4092 if (FormatTok->isOneOf(tok::colon, tok::less)) {
4093 int AngleNestingLevel = 0;
4095 if (FormatTok->is(tok::less))
4096 ++AngleNestingLevel;
4097 else if (FormatTok->is(tok::greater))
4098 --AngleNestingLevel;
4100 if (AngleNestingLevel == 0) {
4101 if (FormatTok->is(tok::colon)) {
4103 }
else if (!IsDerived && FormatTok->is(tok::identifier) &&
4104 FormatTok->Previous->is(tok::coloncolon)) {
4105 ClassName = FormatTok;
4106 }
else if (FormatTok->is(tok::l_paren) &&
4107 IsNonMacroIdentifier(FormatTok->Previous)) {
4111 if (FormatTok->is(tok::l_brace)) {
4112 if (AngleNestingLevel == 0 && IsListInitialization())
4114 calculateBraceTypes(
true);
4115 if (!tryToParseBracedList())
4118 if (FormatTok->is(tok::l_square)) {
4121 !
Previous->isTypeOrIdentifier(LangOpts))) {
4124 if (!tryToParseLambda())
4131 if (FormatTok->is(tok::semi))
4133 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
4136 parseCSharpGenericTypeConstraint();
4143 auto GetBraceTypes =
4144 [](
const FormatToken &RecordTok) -> std::pair<TokenType, TokenType> {
4145 switch (RecordTok.Tok.getKind()) {
4147 return {TT_ClassLBrace, TT_ClassRBrace};
4148 case tok::kw_struct:
4149 return {TT_StructLBrace, TT_StructRBrace};
4151 return {TT_UnionLBrace, TT_UnionRBrace};
4154 return {TT_RecordLBrace, TT_RecordRBrace};
4157 if (FormatTok->is(tok::l_brace)) {
4158 if (IsListInitialization())
4161 ClassName->setFinalizedType(TT_ClassHeadName);
4162 auto [OpenBraceType, ClosingBraceType] = GetBraceTypes(InitialToken);
4163 FormatTok->setFinalizedType(OpenBraceType);
4170 unsigned AddLevels = Style.IndentAccessModifiers ? 2u : 1u;
4171 parseBlock(
true, AddLevels,
false);
4173 setPreviousRBraceType(ClosingBraceType);
4180void UnwrappedLineParser::parseObjCMethod() {
4181 assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) &&
4182 "'(' or identifier expected.");
4184 if (FormatTok->is(tok::semi)) {
4188 }
else if (FormatTok->is(tok::l_brace)) {
4189 if (Style.BraceWrapping.AfterFunction)
4200void UnwrappedLineParser::parseObjCProtocolList() {
4201 assert(FormatTok->is(tok::less) &&
"'<' expected.");
4205 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4207 }
while (!
eof() && FormatTok->isNot(tok::greater));
4211void UnwrappedLineParser::parseObjCUntilAtEnd() {
4213 if (FormatTok->is(tok::objc_end)) {
4218 if (FormatTok->is(tok::l_brace)) {
4222 }
else if (FormatTok->is(tok::r_brace)) {
4226 }
else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
4230 parseStructuralElement();
4235void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
4236 assert(FormatTok->isOneOf(tok::objc_interface, tok::objc_implementation));
4242 if (FormatTok->is(tok::less))
4243 parseObjCLightweightGenerics();
4244 if (FormatTok->is(tok::colon)) {
4248 if (FormatTok->is(tok::less))
4249 parseObjCLightweightGenerics();
4250 }
else if (FormatTok->is(tok::l_paren)) {
4255 if (FormatTok->is(tok::less))
4256 parseObjCProtocolList();
4258 if (FormatTok->is(tok::l_brace)) {
4259 if (Style.BraceWrapping.AfterObjCDeclaration)
4268 parseObjCUntilAtEnd();
4271void UnwrappedLineParser::parseObjCLightweightGenerics() {
4272 assert(FormatTok->is(tok::less));
4280 unsigned NumOpenAngles = 1;
4284 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4286 if (FormatTok->is(tok::less)) {
4288 }
else if (FormatTok->is(tok::greater)) {
4289 assert(NumOpenAngles > 0 &&
"'>' makes NumOpenAngles negative");
4292 }
while (!
eof() && NumOpenAngles != 0);
4298bool UnwrappedLineParser::parseObjCProtocol() {
4299 assert(FormatTok->is(tok::objc_protocol));
4302 if (FormatTok->is(tok::l_paren)) {
4314 if (FormatTok->is(tok::less))
4315 parseObjCProtocolList();
4318 if (FormatTok->is(tok::semi)) {
4325 parseObjCUntilAtEnd();
4329void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
4330 bool IsImport = FormatTok->is(Keywords.kw_import);
4331 assert(IsImport || FormatTok->is(tok::kw_export));
4335 if (FormatTok->is(tok::kw_default))
4341 if (FormatTok->is(Keywords.kw_async))
4343 if (FormatTok->is(Keywords.kw_function)) {
4352 if (!IsImport && FormatTok->isNoneOf(tok::l_brace, tok::star) &&
4353 !FormatTok->isStringLiteral() &&
4354 !(FormatTok->is(Keywords.kw_type) &&
4355 Tokens->peekNextToken()->isOneOf(tok::l_brace, tok::star))) {
4360 if (FormatTok->is(tok::semi))
4362 if (
Line->Tokens.empty()) {
4367 if (FormatTok->is(tok::l_brace)) {
4368 FormatTok->setBlockKind(BK_Block);
4377void UnwrappedLineParser::parseStatementMacro() {
4379 if (FormatTok->is(tok::l_paren))
4381 if (FormatTok->is(tok::semi))
4386void UnwrappedLineParser::parseVerilogHierarchyIdentifier() {
4389 if (FormatTok->isOneOf(tok::star, tok::period, tok::periodstar,
4390 tok::coloncolon, tok::hash) ||
4391 Keywords.isVerilogIdentifier(*FormatTok)) {
4393 }
else if (FormatTok->is(tok::l_square)) {
4401void UnwrappedLineParser::parseVerilogSensitivityList() {
4402 if (FormatTok->isNot(tok::at))
4406 if (FormatTok->is(tok::at))
4408 switch (FormatTok->Tok.getKind()) {
4416 parseVerilogHierarchyIdentifier();
4421unsigned UnwrappedLineParser::parseVerilogHierarchyHeader() {
4422 unsigned AddLevels = 0;
4424 if (FormatTok->is(Keywords.kw_clocking)) {
4426 if (Keywords.isVerilogIdentifier(*FormatTok))
4428 parseVerilogSensitivityList();
4429 if (FormatTok->is(tok::semi))
4431 }
else if (FormatTok->isOneOf(tok::kw_case, Keywords.kw_casex,
4432 Keywords.kw_casez, Keywords.kw_randcase,
4433 Keywords.kw_randsequence)) {
4434 if (Style.IndentCaseLabels)
4437 if (FormatTok->is(tok::l_paren)) {
4438 FormatTok->setFinalizedType(TT_ConditionLParen);
4441 if (FormatTok->isOneOf(Keywords.kw_inside, Keywords.kw_matches))
4450 if (FormatTok->is(tok::l_square)) {
4451 auto Prev = FormatTok->getPreviousNonComment();
4452 if (Prev && Keywords.isVerilogIdentifier(*Prev))
4453 Prev->setFinalizedType(TT_VerilogDimensionedTypeName);
4455 }
else if (Keywords.isVerilogIdentifier(*FormatTok) ||
4456 FormatTok->isOneOf(tok::hash, tok::hashhash, tok::coloncolon,
4457 Keywords.kw_automatic, tok::kw_static)) {
4464 auto NewLine = [
this]() {
4466 Line->IsContinuation =
true;
4470 while (FormatTok->is(Keywords.kw_import)) {
4473 parseVerilogHierarchyIdentifier();
4474 if (FormatTok->is(tok::semi))
4479 if (FormatTok->is(Keywords.kw_verilogHash)) {
4482 if (FormatTok->is(tok::l_paren)) {
4483 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4487 if (FormatTok->is(tok::l_paren)) {
4489 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4494 if (FormatTok->is(Keywords.kw_extends)) {
4497 parseVerilogHierarchyIdentifier();
4498 if (FormatTok->is(tok::l_paren))
4501 if (FormatTok->is(Keywords.kw_implements)) {
4505 parseVerilogHierarchyIdentifier();
4506 }
while (FormatTok->is(tok::comma));
4510 if (FormatTok->is(tok::at)) {
4512 parseVerilogSensitivityList();
4515 if (FormatTok->is(tok::semi))
4523void UnwrappedLineParser::parseVerilogTable() {
4524 assert(FormatTok->is(Keywords.kw_table));
4528 auto InitialLevel =
Line->Level++;
4529 while (!
eof() && !Keywords.isVerilogEnd(*FormatTok)) {
4532 if (
Tok->
is(tok::semi))
4534 else if (
Tok->
isOneOf(tok::star, tok::colon, tok::question, tok::minus))
4535 Tok->setFinalizedType(TT_VerilogTableItem);
4537 Line->Level = InitialLevel;
4542void UnwrappedLineParser::parseVerilogCaseLabel() {
4548 auto OrigLevel =
Line->Level;
4549 auto FirstLine = CurrentLines->size();
4550 if (
Line->Level == 0 || (
Line->InPPDirective &&
Line->Level <= 1))
4552 else if (!Style.IndentCaseBlocks && Keywords.isVerilogBegin(*FormatTok))
4554 parseStructuralElement();
4557 if (CurrentLines->size() > FirstLine)
4558 (*CurrentLines)[FirstLine].Level = OrigLevel;
4559 Line->Level = OrigLevel;
4562bool UnwrappedLineParser::containsExpansion(
const UnwrappedLine &
Line)
const {
4563 for (
const auto &N :
Line.Tokens) {
4564 if (N.Tok->MacroCtx)
4566 for (
const UnwrappedLine &Child : N.Children)
4567 if (containsExpansion(Child))
4573void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) {
4574 if (
Line->Tokens.empty())
4577 if (!parsingPPDirective()) {
4578 llvm::dbgs() <<
"Adding unwrapped line:\n";
4579 printDebugInfo(*
Line);
4587 bool ClosesWhitesmithsBlock =
4588 Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex &&
4589 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
4594 if (!parsingPPDirective() && !InExpansion && containsExpansion(*
Line)) {
4596 Reconstruct.emplace(
Line->Level, Unexpanded);
4597 Reconstruct->addLine(*
Line);
4602 CurrentExpandedLines.push_back(std::move(*
Line));
4604 if (Reconstruct->finished()) {
4605 UnwrappedLine Reconstructed = std::move(*Reconstruct).takeResult();
4606 assert(!Reconstructed.Tokens.empty() &&
4607 "Reconstructed must at least contain the macro identifier.");
4608 assert(!parsingPPDirective());
4610 llvm::dbgs() <<
"Adding unexpanded line:\n";
4611 printDebugInfo(Reconstructed);
4613 ExpandedLines[Reconstructed.Tokens.begin()->Tok] = CurrentExpandedLines;
4614 Lines.push_back(std::move(Reconstructed));
4615 CurrentExpandedLines.clear();
4616 Reconstruct.reset();
4621 assert(!Reconstruct || (CurrentLines != &Lines) || !PPStack.empty());
4622 CurrentLines->push_back(std::move(*
Line));
4624 Line->Tokens.clear();
4625 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
4626 Line->FirstStartColumn = 0;
4627 Line->IsContinuation =
false;
4628 Line->SeenDecltypeAuto =
false;
4630 if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove)
4632 if (!parsingPPDirective() && !PreprocessorDirectives.empty()) {
4633 CurrentLines->append(
4634 std::make_move_iterator(PreprocessorDirectives.begin()),
4635 std::make_move_iterator(PreprocessorDirectives.end()));
4636 PreprocessorDirectives.clear();
4639 FormatTok->Previous =
nullptr;
4642bool UnwrappedLineParser::eof()
const {
return FormatTok->is(tok::eof); }
4644bool UnwrappedLineParser::isOnNewLine(
const FormatToken &FormatTok) {
4645 return (
Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
4646 FormatTok.NewlinesBefore > 0;
4654 const llvm::Regex &CommentPragmasRegex) {
4655 if (
Line.Tokens.empty() || Style.ReflowComments != FormatStyle::RCS_Always)
4658 StringRef IndentContent = FormatTok.
TokenText;
4659 if (FormatTok.
TokenText.starts_with(
"//") ||
4660 FormatTok.
TokenText.starts_with(
"/*")) {
4661 IndentContent = FormatTok.
TokenText.substr(2);
4663 if (CommentPragmasRegex.match(IndentContent))
4738 if (PreviousToken && PreviousToken->
is(tok::l_brace) &&
4740 MinColumnToken = PreviousToken;
4743 PreviousToken = Node.
Tok;
4747 MinColumnToken = Node.
Tok;
4749 if (PreviousToken && PreviousToken->
is(tok::l_brace))
4750 MinColumnToken = PreviousToken;
4756void UnwrappedLineParser::flushComments(
bool NewlineBeforeNext) {
4757 bool JustComments =
Line->Tokens.empty();
4767 Tok->ContinuesLineCommentSection =
4768 continuesLineCommentSection(*
Tok, *
Line, Style, CommentPragmasRegex);
4769 if (isOnNewLine(*
Tok) && JustComments && !
Tok->ContinuesLineCommentSection)
4773 if (NewlineBeforeNext && JustComments)
4775 CommentsBeforeNextToken.clear();
4778void UnwrappedLineParser::nextToken(
int LevelDifference) {
4781 flushComments(isOnNewLine(*FormatTok));
4782 pushToken(FormatTok);
4784 if (!Style.isJavaScript())
4785 readToken(LevelDifference);
4787 readTokenWithJavaScriptASI();
4789 if (Style.isVerilog()) {
4796 if (Keywords.isVerilogEnd(*FormatTok))
4797 FormatTok->Tok.setKind(tok::r_brace);
4801void UnwrappedLineParser::distributeComments(
4821 if (Comments.empty())
4823 bool ShouldPushCommentsInCurrentLine =
true;
4824 bool HasTrailAlignedWithNextToken =
false;
4825 unsigned StartOfTrailAlignedWithNextToken = 0;
4828 for (
unsigned i = Comments.size() - 1; i > 0; --i) {
4830 HasTrailAlignedWithNextToken =
true;
4831 StartOfTrailAlignedWithNextToken = i;
4835 for (
unsigned i = 0, e = Comments.size(); i < e; ++i) {
4837 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
4838 FormatTok->ContinuesLineCommentSection =
false;
4841 *FormatTok, *
Line, Style, CommentPragmasRegex);
4843 if (!FormatTok->ContinuesLineCommentSection &&
4844 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
4845 ShouldPushCommentsInCurrentLine =
false;
4847 if (ShouldPushCommentsInCurrentLine)
4848 pushToken(FormatTok);
4850 CommentsBeforeNextToken.push_back(FormatTok);
4854void UnwrappedLineParser::readToken(
int LevelDifference) {
4856 bool PreviousWasComment =
false;
4857 bool FirstNonCommentOnLine =
false;
4859 FormatTok = Tokens->getNextToken();
4861 while (FormatTok->isOneOf(TT_ConflictStart, TT_ConflictEnd,
4862 TT_ConflictAlternative)) {
4863 if (FormatTok->is(TT_ConflictStart))
4864 conditionalCompilationStart(
false);
4865 else if (FormatTok->is(TT_ConflictAlternative))
4866 conditionalCompilationAlternative();
4867 else if (FormatTok->is(TT_ConflictEnd))
4868 conditionalCompilationEnd();
4869 FormatTok = Tokens->getNextToken();
4870 FormatTok->MustBreakBefore =
true;
4871 FormatTok->MustBreakBeforeFinalized =
true;
4874 auto IsFirstNonCommentOnLine = [](
bool FirstNonCommentOnLine,
4876 bool PreviousWasComment) {
4878 return Tok.HasUnescapedNewline ||
Tok.IsFirst;
4883 if (PreviousWasComment)
4884 return FirstNonCommentOnLine || IsFirstOnLine(
Tok);
4885 return IsFirstOnLine(
Tok);
4888 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
4889 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
4890 PreviousWasComment = FormatTok->is(tok::comment);
4892 while (!
Line->InPPDirective && FormatTok->is(tok::hash) &&
4893 FirstNonCommentOnLine) {
4896 const auto *
Next = Tokens->peekNextToken();
4897 if ((Style.isVerilog() && !Keywords.isVerilogPPDirective(*
Next)) ||
4898 (Style.isTableGen() &&
4899 Next->isNoneOf(tok::kw_else, tok::pp_define, tok::pp_ifdef,
4900 tok::pp_ifndef, tok::pp_endif))) {
4903 distributeComments(Comments, FormatTok);
4907 bool SwitchToPreprocessorLines = !
Line->Tokens.empty();
4908 ScopedLineState BlockState(*
this, SwitchToPreprocessorLines);
4909 assert((LevelDifference >= 0 ||
4910 static_cast<unsigned>(-LevelDifference) <=
Line->Level) &&
4911 "LevelDifference makes Line->Level negative");
4912 Line->Level += LevelDifference;
4916 if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash &&
4917 PPBranchLevel > 0) {
4918 Line->Level += PPBranchLevel;
4920 assert(
Line->Level >=
Line->UnbracedBodyLevel);
4921 Line->Level -=
Line->UnbracedBodyLevel;
4922 flushComments(isOnNewLine(*FormatTok));
4924 PreviousWasComment = FormatTok->is(tok::comment);
4925 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
4926 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
4929 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
4930 !
Line->InPPDirective) {
4934 if (FormatTok->is(tok::identifier) &&
4935 Macros.defined(FormatTok->TokenText) &&
4937 !
Line->InPPDirective) {
4939 unsigned Position = Tokens->getPosition();
4943 auto PreCall = std::move(
Line);
4944 Line.reset(
new UnwrappedLine);
4945 bool OldInExpansion = InExpansion;
4948 auto Args = parseMacroCall();
4949 InExpansion = OldInExpansion;
4950 assert(
Line->Tokens.front().Tok == ID);
4952 auto UnexpandedLine = std::move(
Line);
4954 Line = std::move(PreCall);
4957 llvm::dbgs() <<
"Macro call: " <<
ID->TokenText <<
"(";
4959 llvm::dbgs() <<
"(";
4960 for (
const auto &Arg : Args.value())
4961 for (
const auto &
T : Arg)
4962 llvm::dbgs() <<
T->TokenText <<
" ";
4963 llvm::dbgs() <<
")";
4965 llvm::dbgs() <<
"\n";
4967 if (
Macros.objectLike(
ID->TokenText) && Args &&
4968 !
Macros.hasArity(
ID->TokenText, Args->size())) {
4974 LLVM_DEBUG(llvm::dbgs()
4975 <<
"Macro \"" <<
ID->TokenText
4976 <<
"\" not overloaded for arity " << Args->size()
4977 <<
"or not function-like, using object-like overload.");
4979 UnexpandedLine->Tokens.resize(1);
4980 Tokens->setPosition(Position);
4982 assert(!Args &&
Macros.objectLike(
ID->TokenText));
4984 if ((!Args &&
Macros.objectLike(
ID->TokenText)) ||
4985 (Args &&
Macros.hasArity(
ID->TokenText, Args->size()))) {
4988 Unexpanded[
ID] = std::move(UnexpandedLine);
4990 Macros.expand(ID, std::move(Args));
4991 if (!Expansion.empty())
4992 FormatTok = Tokens->insertTokens(Expansion);
4995 llvm::dbgs() <<
"Expanded: ";
4996 for (
const auto &
T : Expansion)
4997 llvm::dbgs() <<
T->TokenText <<
" ";
4998 llvm::dbgs() <<
"\n";
5002 llvm::dbgs() <<
"Did not expand macro \"" <<
ID->TokenText
5003 <<
"\", because it was used ";
5005 llvm::dbgs() <<
"with " << Args->size();
5007 llvm::dbgs() <<
"without";
5008 llvm::dbgs() <<
" arguments, which doesn't match any definition.\n";
5010 Tokens->setPosition(Position);
5015 if (FormatTok->isNot(tok::comment)) {
5016 distributeComments(Comments, FormatTok);
5021 Comments.push_back(FormatTok);
5024 distributeComments(Comments,
nullptr);
5029template <
typename Iterator>
5030void pushTokens(Iterator Begin, Iterator End,
5032 for (
auto I = Begin; I != End; ++I) {
5033 Into.push_back(I->Tok);
5034 for (
const auto &Child : I->Children)
5035 pushTokens(Child.Tokens.begin(), Child.Tokens.end(), Into);
5040std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>
5041UnwrappedLineParser::parseMacroCall() {
5042 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>> Args;
5043 assert(
Line->Tokens.empty());
5045 if (FormatTok->isNot(tok::l_paren))
5047 unsigned Position = Tokens->getPosition();
5051 auto ArgStart = std::prev(
Line->Tokens.end());
5055 switch (FormatTok->Tok.getKind()) {
5060 case tok::r_paren: {
5066 Args->push_back({});
5067 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5076 Args->push_back({});
5077 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5079 ArgStart = std::prev(
Line->Tokens.end());
5087 Line->Tokens.resize(1);
5088 Tokens->setPosition(Position);
5094 Line->Tokens.push_back(UnwrappedLineNode(
Tok));
5095 if (AtEndOfPPLine) {
5096 auto &
Tok = *
Line->Tokens.back().Tok;
5097 Tok.MustBreakBefore =
true;
5098 Tok.MustBreakBeforeFinalized =
true;
5099 Tok.FirstAfterPPLine =
true;
5100 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.