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);
100 bool SwitchToPreprocessorLines =
false,
101 bool DiscardLines =
false)
102 : Parser(Parser), OriginalLines(Parser.CurrentLines),
103 DiscardLines(DiscardLines) {
104 if (SwitchToPreprocessorLines)
105 Parser.CurrentLines = &Parser.PreprocessorDirectives;
106 else if (!Parser.Line->Tokens.empty())
107 Parser.CurrentLines = &Parser.Line->Tokens.back().Children;
108 OriginalNumLines = Parser.CurrentLines->size();
109 PreBlockLine = std::move(Parser.Line);
110 Parser.Line = std::make_unique<UnwrappedLine>();
111 Parser.Line->Level = PreBlockLine->Level;
112 Parser.Line->PPLevel = PreBlockLine->PPLevel;
113 Parser.Line->InPPDirective = PreBlockLine->InPPDirective;
114 Parser.Line->InMacroBody = PreBlockLine->InMacroBody;
115 Parser.Line->UnbracedBodyLevel = PreBlockLine->UnbracedBodyLevel;
119 if (!Parser.Line->Tokens.empty())
120 Parser.addUnwrappedLine();
121 assert(Parser.Line->Tokens.empty());
123 Parser.CurrentLines->truncate(OriginalNumLines);
124 Parser.Line = std::move(PreBlockLine);
125 if (Parser.CurrentLines == &Parser.PreprocessorDirectives)
126 Parser.PP.AtEndOfPPLine =
true;
127 Parser.CurrentLines = OriginalLines;
133 std::unique_ptr<UnwrappedLine> PreBlockLine;
135 size_t OriginalNumLines;
144 Style.BraceWrapping.AfterControlStatement ==
146 Style.BraceWrapping.IndentBraces) {}
148 bool WrapBrace,
bool IndentBrace)
149 : LineLevel(LineLevel), OldLineLevel(LineLevel) {
151 Parser->addUnwrappedLine();
159 unsigned OldLineLevel;
166 llvm::SpecificBumpPtrAllocator<FormatToken> &Allocator,
168 : Line(new
UnwrappedLine), CurrentLines(&Lines), Style(Style),
170 Keywords(Keywords), CommentPragmasRegex(Style.CommentPragmas),
171 Tokens(
nullptr), Callback(Callback), AllTokens(Tokens),
172 PP(getIncludeGuardState(Style.IndentPPDirectives)),
173 FirstStartColumn(FirstStartColumn),
174 Macros(Style.Macros, SourceMgr, Style, Allocator, IdentTable) {}
176void UnwrappedLineParser::reset() {
178 PP.IncludeGuard = getIncludeGuardState(Style.IndentPPDirectives);
179 PP.IncludeGuardToken =
nullptr;
180 ParsedPPDirectives.clear();
182 CommentsBeforeNextToken.clear();
184 PP.AtEndOfPPLine =
false;
185 IsDecltypeAutoFunction =
false;
186 PreprocessorDirectives.clear();
187 CurrentLines = &Lines;
188 DeclarationScopeStack.clear();
189 NestedTooDeep.clear();
190 NestedLambdas.clear();
192 Line->FirstStartColumn = FirstStartColumn;
194 if (!Unexpanded.empty())
196 Token->MacroCtx.reset();
197 CurrentExpandedLines.clear();
198 ExpandedLines.clear();
206 Line->FirstStartColumn = FirstStartColumn;
208 LLVM_DEBUG(llvm::dbgs() <<
"----\n");
210 Tokens = &TokenSource;
218 if (PP.IncludeGuard == IG_Found) {
219 for (
auto &Line : Lines)
220 if (Line.InPPDirective && Line.Level > 0)
226 pushToken(FormatTok);
231 if (!ExpandedLines.empty()) {
232 LLVM_DEBUG(llvm::dbgs() <<
"Expanded lines:\n");
233 for (
auto &Line : Lines) {
234 if (!Line.Tokens.empty()) {
235 auto it = ExpandedLines.find(Line.Tokens.begin()->Tok);
236 if (it != ExpandedLines.end()) {
237 for (
auto &Expanded : it->second) {
238 Expanded.InMacroExpansion =
true;
239 LLVM_DEBUG(printDebugInfo(Expanded));
240 Callback.consumeUnwrappedLine(Expanded);
245 Line.InMacroExpansion =
true;
246 LLVM_DEBUG(printDebugInfo(Line));
247 Callback.consumeUnwrappedLine(Line);
248 Line.InMacroExpansion =
false;
250 Callback.finishRun();
253 LLVM_DEBUG(llvm::dbgs() <<
"Unwrapped lines:\n");
255 LLVM_DEBUG(printDebugInfo(Line));
256 Callback.consumeUnwrappedLine(Line);
258 Callback.finishRun();
260 while (!PP.LevelBranchIndex.empty() &&
261 PP.LevelBranchIndex.back() + 1 >= PP.LevelBranchCount.back()) {
262 PP.LevelBranchIndex.resize(PP.LevelBranchIndex.size() - 1);
263 PP.LevelBranchCount.resize(PP.LevelBranchCount.size() - 1);
265 if (!PP.LevelBranchIndex.empty()) {
266 ++PP.LevelBranchIndex.back();
267 assert(PP.LevelBranchIndex.size() == PP.LevelBranchCount.size());
268 assert(PP.LevelBranchIndex.back() <= PP.LevelBranchCount.back());
270 }
while (!PP.LevelBranchIndex.empty());
273void UnwrappedLineParser::parseFile() {
276 bool MustBeDeclaration = !
Line->InPPDirective && !Style.isJavaScript();
277 ScopedDeclarationState DeclarationState(*
Line, DeclarationScopeStack,
279 if (Style.isTextProto() || (Style.isJson() && FormatTok->
IsFirst))
294 if (Style.isTextProto() && !CommentsBeforeNextToken.empty())
300void UnwrappedLineParser::parseCSharpGenericTypeConstraint() {
310 parseCSharpGenericTypeConstraint();
319void UnwrappedLineParser::parseCSharpAttribute() {
320 int UnpairedSquareBrackets = 1;
322 switch (FormatTok->Tok.getKind()) {
325 --UnpairedSquareBrackets;
326 if (UnpairedSquareBrackets == 0) {
332 ++UnpairedSquareBrackets;
342bool UnwrappedLineParser::precededByCommentOrPPDirective()
const {
343 if (!Lines.empty() && Lines.back().InPPDirective)
357bool UnwrappedLineParser::parseLevel(
const FormatToken *OpeningBrace,
360 bool *SeenExplicitAccessModifier) {
361 const bool InRequiresExpression =
362 OpeningBrace && OpeningBrace->is(TT_RequiresExpressionLBrace);
363 const bool IsPrecededByCommentOrPPDirective =
364 !Style.RemoveBracesLLVM || precededByCommentOrPPDirective();
366 bool HasDoWhile =
false;
367 bool HasLabel =
false;
368 unsigned StatementCount = 0;
369 bool SwitchLabelEncountered =
false;
372 if (FormatTok->isAttribute()) {
374 if (FormatTok->is(tok::l_paren))
379 if (FormatTok->is(TT_MacroBlockBegin))
381 else if (FormatTok->is(TT_MacroBlockEnd))
384 auto ParseDefault = [
this, OpeningBrace, IfKind, &IfLBrace, &HasDoWhile,
385 &HasLabel, &StatementCount,
386 SeenExplicitAccessModifier] {
387 if (SeenExplicitAccessModifier && !*SeenExplicitAccessModifier) {
388 const bool IsQtAccessLabel =
389 FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
390 Keywords.kw_slots, Keywords.kw_qslots) &&
391 Tokens->peekNextToken(
true)->is(tok::colon);
392 if (FormatTok->isAccessSpecifierKeyword() || IsQtAccessLabel) {
394 *SeenExplicitAccessModifier =
true;
397 parseStructuralElement(OpeningBrace, IfKind, &IfLBrace,
398 HasDoWhile ?
nullptr : &HasDoWhile,
399 HasLabel ?
nullptr : &HasLabel);
401 assert(StatementCount > 0 &&
"StatementCount overflow!");
410 if (InRequiresExpression) {
411 FormatTok->setFinalizedType(TT_CompoundRequirementLBrace);
412 }
else if (FormatTok->Previous &&
413 FormatTok->Previous->ClosesRequiresClause) {
419 if (!InRequiresExpression && FormatTok->isNot(TT_MacroBlockBegin)) {
420 if (tryToParseBracedList())
422 FormatTok->setFinalizedType(TT_BlockLBrace);
426 assert(StatementCount > 0 &&
"StatementCount overflow!");
431 if (!Style.RemoveBracesLLVM || Line->InPPDirective ||
432 OpeningBrace->isNoneOf(TT_ControlStatementLBrace, TT_ElseLBrace)) {
435 if (FormatTok->isNot(tok::r_brace) || StatementCount != 1 || HasLabel ||
436 HasDoWhile || IsPrecededByCommentOrPPDirective ||
437 precededByCommentOrPPDirective()) {
441 if (
Next->is(tok::comment) &&
Next->NewlinesBefore == 0)
444 *IfLeftBrace = IfLBrace;
450 case tok::kw_default: {
451 unsigned StoredPosition = Tokens->getPosition();
452 auto *
Next = Tokens->getNextNonComment();
453 FormatTok = Tokens->setPosition(StoredPosition);
454 if (
Next->isNoneOf(tok::colon, tok::arrow)) {
457 parseStructuralElement();
465 (Style.isJavaScript() && Line->MustBeDeclaration)) {
473 if (!SwitchLabelEncountered &&
474 (Style.IndentCaseLabels ||
475 (OpeningBrace && OpeningBrace->is(TT_SwitchExpressionLBrace)) ||
476 (Line->InPPDirective && Line->Level == 1))) {
479 SwitchLabelEncountered =
true;
480 parseStructuralElement();
483 if (Style.isCSharp()) {
485 parseCSharpAttribute();
488 if (handleCppAttributes())
500void UnwrappedLineParser::calculateBraceTypes(
bool ExpectClassBody) {
505 unsigned StoredPosition = Tokens->getPosition();
515 SmallVector<StackEntry, 8> LBraceStack;
516 assert(
Tok->is(tok::l_brace));
519 auto *NextTok = Tokens->getNextNonComment();
521 if (!Line->InMacroBody && !Style.isTableGen()) {
523 while (NextTok->is(tok::hash)) {
524 NextTok = Tokens->getNextToken();
525 if (NextTok->isOneOf(tok::pp_not_keyword, tok::pp_define))
528 NextTok = Tokens->getNextToken();
529 }
while (!NextTok->HasUnescapedNewline && NextTok->isNot(tok::eof));
531 while (NextTok->is(tok::comment))
532 NextTok = Tokens->getNextToken();
536 switch (
Tok->Tok.getKind()) {
538 if (Style.isJavaScript() && PrevTok) {
539 if (PrevTok->isOneOf(tok::colon, tok::less)) {
550 }
else if (PrevTok->is(tok::r_paren)) {
554 }
else if (Style.isJava() && PrevTok && PrevTok->is(tok::arrow)) {
559 LBraceStack.push_back({
Tok, PrevTok});
562 if (LBraceStack.empty())
564 if (
auto *LBrace = LBraceStack.back().Tok; LBrace->is(
BK_Unknown)) {
565 bool ProbablyBracedList =
false;
567 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
568 }
else if (LBrace->isNot(TT_EnumLBrace)) {
571 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
572 NextTok->OriginalColumn == 0;
582 ProbablyBracedList = LBrace->is(TT_BracedListLBrace);
584 ProbablyBracedList = ProbablyBracedList ||
585 (Style.isJavaScript() &&
586 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
589 ProbablyBracedList ||
590 (IsCpp && (PrevTok->Tok.isLiteral() ||
591 NextTok->isOneOf(tok::l_paren, tok::arrow)));
598 ProbablyBracedList ||
599 NextTok->isOneOf(tok::comma, tok::period, tok::colon,
600 tok::r_paren, tok::r_square, tok::ellipsis);
605 ProbablyBracedList ||
606 (NextTok->is(tok::l_brace) && LBraceStack.back().PrevTok &&
607 LBraceStack.back().PrevTok->isOneOf(tok::identifier,
611 ProbablyBracedList ||
612 (NextTok->is(tok::identifier) &&
613 PrevTok->isNoneOf(tok::semi, tok::r_brace, tok::l_brace));
615 ProbablyBracedList = ProbablyBracedList ||
616 (NextTok->is(tok::semi) &&
617 (!ExpectClassBody || LBraceStack.size() != 1));
620 ProbablyBracedList ||
621 (NextTok->isBinaryOperator() && !NextIsObjCMethod);
623 if (!Style.isCSharp() && NextTok->is(tok::l_square)) {
626 NextTok = Tokens->getNextToken();
627 ProbablyBracedList = NextTok->isNot(tok::l_square);
631 if (IsCpp && Line->InMacroBody && PrevTok != FormatTok &&
632 !FormatTok->Previous && NextTok->is(tok::eof) &&
636 PrevTok->isNoneOf(tok::semi,
BK_Block, tok::colon)) {
637 ProbablyBracedList =
true;
641 Tok->setBlockKind(BlockKind);
642 LBrace->setBlockKind(BlockKind);
644 LBraceStack.pop_back();
646 case tok::identifier:
647 if (
Tok->isNot(TT_StatementMacro))
658 if (!LBraceStack.empty() && LBraceStack.back().Tok->is(
BK_Unknown))
659 LBraceStack.back().Tok->setBlockKind(
BK_Block);
667 }
while (
Tok->isNot(tok::eof) && !LBraceStack.empty());
670 for (
const auto &Entry : LBraceStack)
674 FormatTok = Tokens->setPosition(StoredPosition);
678void UnwrappedLineParser::setPreviousRBraceType(
TokenType Type) {
679 if (
auto Prev = FormatTok->getPreviousNonComment();
680 Prev && Prev->is(tok::r_brace)) {
681 Prev->setFinalizedType(
Type);
688 seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
691size_t UnwrappedLineParser::computePPHash()
const {
693 for (
const auto &i : PP.Stack) {
704bool UnwrappedLineParser::mightFitOnOneLine(
706 const auto ColumnLimit = Style.ColumnLimit;
707 if (ColumnLimit == 0)
710 auto &Tokens = ParsedLine.Tokens;
711 assert(!Tokens.empty());
713 const auto *LastToken = Tokens.back().Tok;
716 SmallVector<UnwrappedLineNode> SavedTokens(Tokens.size());
719 for (
const auto &Token : Tokens) {
721 auto &SavedToken = SavedTokens[Index++];
723 SavedToken.Tok->copyFrom(*Token.Tok);
724 SavedToken.Children = std::move(Token.Children);
727 AnnotatedLine
Line(ParsedLine);
728 assert(Line.Last == LastToken);
730 TokenAnnotator Annotator(Style, Keywords);
731 Annotator.annotate(Line);
732 Annotator.calculateFormattingInformation(Line);
734 auto Length = LastToken->TotalLength;
736 assert(OpeningBrace != Tokens.front().Tok);
737 if (
auto Prev = OpeningBrace->Previous;
738 Prev && Prev->TotalLength + ColumnLimit == OpeningBrace->TotalLength) {
739 Length -= ColumnLimit;
741 Length -= OpeningBrace->TokenText.size() + 1;
744 if (
const auto *FirstToken = Line.First; FirstToken->is(tok::r_brace)) {
745 assert(!OpeningBrace || OpeningBrace->is(TT_ControlStatementLBrace));
746 Length -= FirstToken->TokenText.size() + 1;
750 for (
auto &Token : Tokens) {
751 const auto &SavedToken = SavedTokens[Index++];
752 Token.Tok->copyFrom(*SavedToken.Tok);
753 Token.Children = std::move(SavedToken.Children);
754 delete SavedToken.Tok;
758 assert(!Line.InMacroBody);
759 assert(!Line.InPPDirective);
760 return Line.Level * Style.IndentWidth + Length <= ColumnLimit;
764 bool MustBeDeclaration,
unsigned AddLevels,
bool MunchSemi,
bool KeepBraces,
765 IfStmtKind *IfKind,
bool UnindentWhitesmithsBraces,
766 bool IndentAfterExplicitAccessModifier) {
767 auto HandleVerilogBlockLabel = [
this]() {
769 if (Style.isVerilog() && FormatTok->is(tok::colon)) {
771 if (Keywords.isVerilogIdentifier(*FormatTok))
778 const bool VerilogHierarchy =
779 Style.isVerilog() && Keywords.isVerilogHierarchy(*FormatTok);
780 assert((FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) ||
781 (Style.isVerilog() &&
782 (Keywords.isVerilogBegin(*FormatTok) || VerilogHierarchy))) &&
783 "'{' or macro block token expected");
785 const bool FollowedByComment = Tokens->peekNextToken()->is(tok::comment);
786 auto Index = CurrentLines->size();
787 const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
790 const bool IsWhitesmiths =
795 if (!VerilogHierarchy && AddLevels > 0 && IsWhitesmiths)
798 size_t PPStartHash = computePPHash();
800 const unsigned InitialLevel = Line->Level;
801 if (VerilogHierarchy) {
802 AddLevels += parseVerilogHierarchyHeader();
804 nextToken(AddLevels);
805 HandleVerilogBlockLabel();
809 if (Line->Level > 300)
812 if (MacroBlock && FormatTok->is(tok::l_paren))
815 size_t NbPreprocessorDirectives =
816 !parsingPPDirective() ? PreprocessorDirectives.size() : 0;
818 size_t OpeningLineIndex =
819 CurrentLines->empty() || !CurrentExpandedLines.empty()
821 : (CurrentLines->size() - 1 - NbPreprocessorDirectives);
826 if (UnindentWhitesmithsBraces)
829 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
835 Line->Level += AddLevels - (IsWhitesmiths ? 1 : 0);
838 bool SeenExplicitAccessModifier =
false;
839 const bool SimpleBlock =
840 parseLevel(
Tok, IfKind, &IfLBrace,
841 IndentAfterExplicitAccessModifier ? &SeenExplicitAccessModifier
847 if (MacroBlock ? FormatTok->isNot(TT_MacroBlockEnd)
848 : FormatTok->isNot(tok::r_brace)) {
849 Line->Level = InitialLevel;
850 FormatTok->setBlockKind(BK_Block);
854 if (FormatTok->is(tok::r_brace)) {
855 FormatTok->setBlockKind(BK_Block);
856 if (Tok->is(TT_NamespaceLBrace))
857 FormatTok->setFinalizedType(TT_NamespaceRBrace);
860 const bool IsFunctionRBrace =
861 FormatTok->is(tok::r_brace) &&
Tok->is(TT_FunctionLBrace);
863 auto RemoveBraces = [=]()
mutable {
866 assert(Tok->isOneOf(TT_ControlStatementLBrace, TT_ElseLBrace));
867 assert(FormatTok->is(tok::r_brace));
868 const bool WrappedOpeningBrace = !Tok->Previous;
869 if (WrappedOpeningBrace && FollowedByComment)
871 const bool HasRequiredIfBraces = IfLBrace && !IfLBrace->Optional;
872 if (KeepBraces && !HasRequiredIfBraces)
874 if (Tok->isNot(TT_ElseLBrace) || !HasRequiredIfBraces) {
875 const FormatToken *Previous = Tokens->getPreviousToken();
877 if (Previous->is(tok::r_brace) && !Previous->Optional)
882 assert(!CurrentLines->empty());
883 auto &LastLine = CurrentLines->back();
884 if (LastLine.Level == InitialLevel + 1 && !mightFitOnOneLine(LastLine))
886 if (
Tok->is(TT_ElseLBrace))
888 if (WrappedOpeningBrace) {
893 return mightFitOnOneLine((*CurrentLines)[Index],
Tok);
895 if (RemoveBraces()) {
896 Tok->MatchingParen = FormatTok;
897 FormatTok->MatchingParen =
Tok;
900 size_t PPEndHash = computePPHash();
902 if (SeenExplicitAccessModifier)
905 nextToken(-AddLevels);
910 if (Style.RemoveSemicolon && IsFunctionRBrace) {
911 while (FormatTok->is(tok::semi)) {
912 FormatTok->Optional =
true;
917 HandleVerilogBlockLabel();
919 if (MacroBlock && FormatTok->is(tok::l_paren))
922 Line->Level = InitialLevel;
924 if (FormatTok->is(tok::kw_noexcept)) {
929 if (FormatTok->is(tok::arrow)) {
933 parseStructuralElement();
936 if (MunchSemi && FormatTok->is(tok::semi))
939 if (PPStartHash == PPEndHash && CurrentExpandedLines.empty() &&
940 !containsExpansion(*
Line)) {
941 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
944 (*CurrentLines)[OpeningLineIndex].MatchingClosingBlockLineIndex =
945 CurrentLines->size() - 1;
955 if (
Line.Tokens.size() < 4)
957 auto I =
Line.Tokens.begin();
958 if (I->Tok->TokenText !=
"goog")
961 if (I->Tok->isNot(tok::period))
964 if (I->Tok->TokenText !=
"scope")
967 return I->Tok->is(tok::l_paren);
976 if (
Line.Tokens.size() < 3)
978 auto I =
Line.Tokens.begin();
979 if (I->Tok->isNot(tok::l_paren))
985 return I->Tok->is(tok::l_paren);
991 bool IsJavaRecord =
false) {
993 return Style.BraceWrapping.AfterClass;
996 if (InitialToken.
is(TT_NamespaceMacro))
997 Kind = tok::kw_namespace;
999 const bool WrapRecordAllowed =
1002 Style.BraceWrapping.SplitEmptyRecord;
1005 case tok::kw_namespace:
1006 return Style.BraceWrapping.AfterNamespace;
1008 return Style.BraceWrapping.AfterClass && WrapRecordAllowed;
1010 return Style.BraceWrapping.AfterUnion && WrapRecordAllowed;
1011 case tok::kw_struct:
1012 return Style.BraceWrapping.AfterStruct && WrapRecordAllowed;
1014 return Style.BraceWrapping.AfterEnum;
1020void UnwrappedLineParser::parseChildBlock() {
1021 assert(FormatTok->is(tok::l_brace));
1022 FormatTok->setBlockKind(BK_Block);
1026 bool SkipIndent = (Style.isJavaScript() &&
1027 (isGoogScope(*
Line) || isIIFE(*
Line, Keywords)));
1028 ScopedLineState LineState(*
this);
1029 ScopedDeclarationState DeclarationState(*
Line, DeclarationScopeStack,
1031 Line->Level += SkipIndent ? 0 : 1;
1032 parseLevel(OpeningBrace);
1033 flushComments(isOnNewLine(*FormatTok));
1034 Line->Level -= SkipIndent ? 0 : 1;
1039void UnwrappedLineParser::parsePPDirective() {
1040 assert(FormatTok->is(tok::hash) &&
"'#' expected");
1041 ScopedMacroState MacroState(*
Line, Tokens, FormatTok);
1045 if (!FormatTok->Tok.getIdentifierInfo()) {
1050 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
1051 case tok::pp_define:
1058 case tok::pp_ifndef:
1062 case tok::pp_elifdef:
1063 case tok::pp_elifndef:
1070 case tok::pp_pragma:
1074 case tok::pp_warning:
1076 if (!
eof() && Style.isCpp())
1077 FormatTok->setFinalizedType(TT_AfterPPDirective);
1085void UnwrappedLineParser::conditionalCompilationCondition(
bool Unreachable) {
1086 size_t Line = CurrentLines->size();
1087 if (CurrentLines == &PreprocessorDirectives)
1088 Line += Lines.size();
1091 (!PP.Stack.empty() && PP.Stack.back().Kind == PP_Unreachable)) {
1092 PP.Stack.push_back({PP_Unreachable,
Line});
1094 PP.Stack.push_back({PP_Conditional,
Line});
1098void UnwrappedLineParser::conditionalCompilationStart(
bool Unreachable) {
1100 assert(PP.BranchLevel >= 0 &&
1101 PP.BranchLevel <= (
int)PP.LevelBranchIndex.size());
1102 if (PP.BranchLevel == (
int)PP.LevelBranchIndex.size()) {
1103 PP.LevelBranchIndex.push_back(0);
1104 PP.LevelBranchCount.push_back(0);
1106 PP.ChainBranchIndex.push(Unreachable ? -1 : 0);
1107 bool Skip = PP.LevelBranchIndex[PP.BranchLevel] > 0;
1108 conditionalCompilationCondition(Unreachable ||
Skip);
1111void UnwrappedLineParser::conditionalCompilationAlternative() {
1112 if (!PP.Stack.empty())
1113 PP.Stack.pop_back();
1114 assert(PP.BranchLevel < (
int)PP.LevelBranchIndex.size());
1115 if (!PP.ChainBranchIndex.empty())
1116 ++PP.ChainBranchIndex.top();
1117 conditionalCompilationCondition(
1118 PP.BranchLevel >= 0 && !PP.ChainBranchIndex.empty() &&
1119 PP.LevelBranchIndex[PP.BranchLevel] != PP.ChainBranchIndex.top());
1122void UnwrappedLineParser::conditionalCompilationEnd() {
1123 assert(PP.BranchLevel < (
int)PP.LevelBranchIndex.size());
1124 if (PP.BranchLevel >= 0 && !PP.ChainBranchIndex.empty()) {
1125 if (PP.ChainBranchIndex.top() + 1 > PP.LevelBranchCount[PP.BranchLevel])
1126 PP.LevelBranchCount[PP.BranchLevel] = PP.ChainBranchIndex.top() + 1;
1129 if (PP.BranchLevel > -1)
1131 if (!PP.ChainBranchIndex.empty())
1132 PP.ChainBranchIndex.pop();
1133 if (!PP.Stack.empty())
1134 PP.Stack.pop_back();
1137void UnwrappedLineParser::parsePPIf(
bool IfDef) {
1138 bool IfNDef = FormatTok->is(tok::pp_ifndef);
1140 bool Unreachable =
false;
1141 if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText ==
"0"))
1143 if (IfDef && !IfNDef && FormatTok->TokenText ==
"SWIG")
1145 conditionalCompilationStart(Unreachable);
1149 bool MaybeIncludeGuard = IfNDef;
1150 if (PP.IncludeGuard == IG_Inited && MaybeIncludeGuard) {
1151 for (
auto &
Line : Lines) {
1152 if (
Line.Tokens.front().Tok->isNot(tok::comment)) {
1153 MaybeIncludeGuard =
false;
1154 PP.IncludeGuard = IG_Rejected;
1162 if (PP.IncludeGuard == IG_Inited && MaybeIncludeGuard) {
1163 PP.IncludeGuard = IG_IfNdefed;
1164 PP.IncludeGuardToken = IfCondition;
1168void UnwrappedLineParser::parsePPElse() {
1170 if (PP.IncludeGuard == IG_Defined && PP.BranchLevel == 0)
1171 PP.IncludeGuard = IG_Rejected;
1173 assert(PP.BranchLevel >= -1);
1174 if (PP.BranchLevel == -1)
1175 conditionalCompilationStart(
true);
1176 conditionalCompilationAlternative();
1182void UnwrappedLineParser::parsePPEndIf() {
1183 conditionalCompilationEnd();
1187void UnwrappedLineParser::parsePPDefine() {
1190 if (!FormatTok->Tok.getIdentifierInfo()) {
1191 PP.IncludeGuard = IG_Rejected;
1192 PP.IncludeGuardToken =
nullptr;
1197 bool MaybeIncludeGuard =
false;
1198 if (PP.IncludeGuard == IG_IfNdefed &&
1199 PP.IncludeGuardToken->TokenText == FormatTok->TokenText) {
1200 PP.IncludeGuard = IG_Defined;
1201 PP.IncludeGuardToken =
nullptr;
1202 for (
auto &
Line : Lines) {
1203 if (
Line.Tokens.front().Tok->isNoneOf(tok::comment, tok::hash)) {
1204 PP.IncludeGuard = IG_Rejected;
1208 MaybeIncludeGuard = PP.IncludeGuard == IG_Defined;
1216 FormatTok->Tok.setKind(tok::identifier);
1217 FormatTok->Tok.setIdentifierInfo(Keywords.kw_internal_ident_after_define);
1221 if (MaybeIncludeGuard && !
eof())
1222 PP.IncludeGuard = IG_Rejected;
1224 if (FormatTok->is(tok::l_paren) && !FormatTok->hasWhitespaceBefore())
1227 Line->Level += PP.BranchLevel + 1;
1231 Line->PPLevel = PP.BranchLevel + (PP.IncludeGuard == IG_Defined ? 0 : 1);
1232 assert((
int)
Line->PPLevel >= 0);
1237 Line->InMacroBody =
true;
1239 if (!Style.SkipMacroDefinitionBody) {
1249 for (
auto *Comment : CommentsBeforeNextToken)
1250 Comment->Finalized =
true;
1253 FormatTok->Finalized =
true;
1254 FormatTok = Tokens->getNextToken();
1260void UnwrappedLineParser::parsePPPragma() {
1261 Line->InPragmaDirective =
true;
1265void UnwrappedLineParser::parsePPUnknown() {
1269 Line->Level += PP.BranchLevel + 1;
1279 return Tok.isNoneOf(tok::semi, tok::l_brace,
1282 tok::period, tok::periodstar, tok::arrow, tok::arrowstar,
1283 tok::less, tok::greater, tok::slash, tok::percent,
1284 tok::lessless, tok::greatergreater, tok::equal,
1285 tok::plusequal, tok::minusequal, tok::starequal,
1286 tok::slashequal, tok::percentequal, tok::ampequal,
1287 tok::pipeequal, tok::caretequal, tok::greatergreaterequal,
1300 return FormatTok->
is(tok::identifier) &&
1315 FormatTok->
isOneOf(tok::kw_true, tok::kw_false) ||
1326 tok::kw_if, tok::kw_else,
1328 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
1330 tok::kw_switch, tok::kw_case,
1332 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.
kw_finally,
1334 tok::kw_const, tok::kw_class, Keywords.
kw_var, Keywords.
kw_let,
1342 return Tok.isOneOf(tok::kw_char, tok::kw_short, tok::kw_int, tok::kw_long,
1343 tok::kw_unsigned, tok::kw_float, tok::kw_double,
1360 if (FuncName->
isNot(tok::identifier))
1368 Tok->isNoneOf(tok::kw_register, tok::kw_struct, tok::kw_union)) {
1372 if (
Next->isNot(tok::star) && !
Next->Tok.getIdentifierInfo())
1376 if (!
Tok ||
Tok->isNot(tok::r_paren))
1380 if (!
Tok ||
Tok->isNot(tok::identifier))
1383 return Tok->Previous &&
Tok->Previous->isOneOf(tok::l_paren, tok::comma);
1386bool UnwrappedLineParser::parseModuleDecl() {
1388 assert(FormatTok->is(Keywords.kw_module));
1396 if (FormatTok->isNot(tok::identifier))
1399 for (nextToken(); FormatTok->isNoneOf(tok::semi, tok::eof); nextToken())
1400 if (FormatTok->is(tok::colon))
1401 FormatTok->setFinalizedType(TT_ModulePartitionColon);
1404 Line->IsModuleOrImportDecl =
true;
1409bool UnwrappedLineParser::parseImportDecl() {
1411 assert(FormatTok->is(Keywords.kw_import) &&
"'import' expected");
1419 if (FormatTok->is(tok::colon)) {
1420 FormatTok->setFinalizedType(TT_ModulePartitionColon);
1423 if (FormatTok->isNoneOf(tok::identifier, tok::less, tok::string_literal))
1426 for (; FormatTok->isNoneOf(tok::semi, tok::eof); nextToken()) {
1428 if (FormatTok->is(tok::less)) {
1429 for (nextToken(); FormatTok->isNoneOf(tok::greater, tok::semi, tok::eof);
1433 FormatTok->setFinalizedType(TT_ImplicitStringLiteral);
1439 Line->IsModuleOrImportDecl =
true;
1451void UnwrappedLineParser::readTokenWithJavaScriptASI() {
1457 CommentsBeforeNextToken.empty()
1458 ?
Next->NewlinesBefore == 0
1459 : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
1464 bool PreviousStartsTemplateExpr =
1466 if (PreviousMustBeValue ||
Previous->is(tok::r_paren)) {
1469 bool HasAt = llvm::any_of(
Line->Tokens, [](UnwrappedLineNode &LineNode) {
1470 return LineNode.Tok->is(tok::at);
1475 if (
Next->is(tok::exclaim) && PreviousMustBeValue)
1476 return addUnwrappedLine();
1478 bool NextEndsTemplateExpr =
1479 Next->is(TT_TemplateString) &&
Next->TokenText.starts_with(
"}");
1480 if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
1481 (PreviousMustBeValue ||
1482 Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
1483 tok::minusminus))) {
1484 return addUnwrappedLine();
1486 if ((PreviousMustBeValue ||
Previous->is(tok::r_paren)) &&
1488 return addUnwrappedLine();
1492void UnwrappedLineParser::parseStructuralElement(
1493 const FormatToken *OpeningBrace, IfStmtKind *IfKind,
1494 FormatToken **IfLeftBrace,
bool *HasDoWhile,
bool *HasLabel) {
1495 if (Style.isTableGen() && FormatTok->is(tok::pp_include)) {
1497 if (FormatTok->is(tok::string_literal))
1504 while (FormatTok->is(tok::l_square) && handleCppAttributes()) {
1506 }
else if (Style.isVerilog()) {
1508 while (FormatTok->is(tok::l_paren) &&
1509 Tokens->peekNextToken()->is(tok::star)) {
1512 skipVerilogQualifiers();
1514 if (FormatTok->isOneOf(Keywords.kw_priority, Keywords.kw_unique,
1515 Keywords.kw_unique0)) {
1519 if (Keywords.isVerilogStructuredProcedure(*FormatTok)) {
1520 parseForOrWhileLoop(
false);
1523 if (FormatTok->isOneOf(Keywords.kw_foreach, Keywords.kw_repeat)) {
1524 parseForOrWhileLoop();
1527 if (FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
1528 Keywords.kw_assume, Keywords.kw_cover)) {
1529 parseIfThenElse(IfKind,
false,
true);
1535 if (FormatTok->isAccessSpecifierKeyword()) {
1536 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp())
1539 parseAccessSpecifier();
1542 switch (FormatTok->Tok.getKind()) {
1547 bool DoNotFormat =
false;
1552 FormatTok->isOneOf(tok::kw_volatile, tok::kw_inline, tok::kw_goto)) {
1557 if (FormatTok->is(tok::l_brace)) {
1558 FormatTok->setFinalizedType(TT_InlineASMBrace);
1559 OpenType = tok::l_brace;
1560 CloseType = tok::r_brace;
1562 }
else if (FormatTok->is(tok::l_paren)) {
1563 OpenType = tok::l_paren;
1564 CloseType = tok::r_paren;
1565 FormatTok->setFinalizedType(TT_InlineASMParen);
1573 while (FormatTok && !
eof()) {
1574 if (FormatTok->is(OpenType)) {
1576 }
else if (FormatTok->is(CloseType)) {
1578 if (NestLevel < 1) {
1579 FormatTok->setFinalizedType(OpenTok->getType());
1585 FormatTok->Finalized =
true;
1591 case tok::kw_namespace:
1595 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1606 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1610 parseForOrWhileLoop();
1613 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1621 case tok::kw_switch:
1622 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1628 case tok::kw_default: {
1630 if (Style.isVerilog())
1632 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1638 if (FormatTok->is(tok::colon)) {
1639 FormatTok->setFinalizedType(TT_CaseLabelColon);
1643 if (FormatTok->is(tok::arrow)) {
1644 FormatTok->setFinalizedType(TT_CaseLabelArrow);
1645 Default->setFinalizedType(TT_SwitchExpressionLabel);
1658 if (Style.isVerilog()) {
1663 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1672 if (FormatTok->is(tok::kw_case))
1677 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
1683 case tok::kw_extern:
1684 if (Style.isVerilog()) {
1687 parseVerilogExtern();
1691 if (FormatTok->is(tok::string_literal)) {
1693 if (FormatTok->is(tok::l_brace)) {
1694 if (Style.BraceWrapping.AfterExternBlock)
1698 unsigned AddLevels =
1700 (Style.BraceWrapping.AfterExternBlock &&
1701 Style.IndentExternBlock ==
1705 parseBlock(
true, AddLevels);
1711 case tok::kw_export:
1714 if (FormatTok->is(tok::kw_namespace)) {
1718 if (FormatTok->is(tok::l_brace)) {
1719 parseCppExportBlock();
1722 if (FormatTok->is(Keywords.kw_module) && parseModuleDecl())
1724 if (FormatTok->is(Keywords.kw_import) && parseImportDecl())
1728 if (Style.isJavaScript()) {
1729 parseJavaScriptEs6ImportExport();
1732 if (Style.isVerilog()) {
1733 parseVerilogExtern();
1737 case tok::kw_inline:
1739 if (FormatTok->is(tok::kw_namespace)) {
1744 case tok::identifier:
1745 if (FormatTok->is(TT_ForEachMacro)) {
1746 parseForOrWhileLoop();
1749 if (FormatTok->is(TT_MacroBlockBegin)) {
1750 parseBlock(
false, 1u,
1754 if (FormatTok->is(Keywords.kw_import)) {
1755 if (IsCpp && parseImportDecl())
1757 if (Style.isJavaScript()) {
1758 parseJavaScriptEs6ImportExport();
1763 if (FormatTok->is(tok::kw_public))
1765 if (FormatTok->isNot(tok::string_literal))
1768 if (FormatTok->is(tok::semi))
1773 if (Style.isVerilog()) {
1774 parseVerilogExtern();
1779 if (FormatTok->is(Keywords.kw_module) && parseModuleDecl())
1781 if (FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
1782 Keywords.kw_slots, Keywords.kw_qslots)) {
1784 if (FormatTok->is(tok::colon)) {
1790 if (FormatTok->is(TT_StatementMacro)) {
1791 parseStatementMacro();
1794 if (FormatTok->is(TT_NamespaceMacro)) {
1803 if (!Style.isJavaScript() && !Style.isVerilog() && !Style.isTableGen() &&
1804 Tokens->peekNextToken()->is(tok::colon) && !
Line->MustBeDeclaration) {
1806 if (!
Line->InMacroBody || CurrentLines->size() > 1)
1807 Line->Tokens.begin()->Tok->MustBreakBefore =
true;
1808 FormatTok->setFinalizedType(TT_GotoLabelColon);
1814 if (Style.isJava() && FormatTok->is(Keywords.kw_record)) {
1815 parseRecord(
false,
true);
1825 bool SeenEqual =
false;
1826 for (
const bool InRequiresExpression =
1827 OpeningBrace && OpeningBrace->isOneOf(TT_RequiresExpressionLBrace,
1828 TT_CompoundRequirementLBrace);
1831 switch (FormatTok->Tok.getKind()) {
1834 if (FormatTok->is(tok::l_brace)) {
1839 if (Style.isJava() && FormatTok->is(Keywords.kw_interface)) {
1843 switch (
bool IsAutoRelease =
false; FormatTok->Tok.getObjCKeywordID()) {
1844 case tok::objc_public:
1845 case tok::objc_protected:
1846 case tok::objc_package:
1847 case tok::objc_private:
1848 return parseAccessSpecifier();
1849 case tok::objc_interface:
1850 case tok::objc_implementation:
1851 return parseObjCInterfaceOrImplementation();
1852 case tok::objc_protocol:
1853 if (parseObjCProtocol())
1858 case tok::objc_optional:
1859 case tok::objc_required:
1863 case tok::objc_autoreleasepool:
1864 IsAutoRelease =
true;
1866 case tok::objc_synchronized:
1868 if (!IsAutoRelease && FormatTok->is(tok::l_paren)) {
1872 if (FormatTok->is(tok::l_brace)) {
1873 if (Style.BraceWrapping.AfterControlStatement ==
1890 case tok::kw_requires: {
1892 bool ParsedClause = parseRequires(SeenEqual);
1913 if (!IsCpp && !Style.isVerilog()) {
1918 case tok::kw_typedef:
1920 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1921 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS,
1922 Keywords.kw_CF_CLOSED_ENUM,
1923 Keywords.kw_NS_CLOSED_ENUM)) {
1928 if (Style.isVerilog()) {
1933 if (Style.isTableGen()) {
1940 case tok::kw_struct:
1942 if (parseStructLike())
1945 case tok::kw_decltype:
1947 if (FormatTok->is(tok::l_paren)) {
1949 if (FormatTok->Previous &&
1950 FormatTok->Previous->endsSequence(tok::r_paren, tok::kw_auto,
1952 Line->SeenDecltypeAuto =
true;
1959 if (Style.isJava() && FormatTok && FormatTok->is(tok::kw_class))
1961 if (Style.isJavaScript() && FormatTok &&
1962 FormatTok->Tok.getIdentifierInfo()) {
1975 case tok::string_literal:
1976 if (Style.isVerilog() && FormatTok->is(TT_VerilogProtected)) {
1977 FormatTok->Finalized =
true;
1984 case tok::l_paren: {
1991 Tokens->peekNextToken(
true),
1998 case tok::kw_operator:
2000 if (FormatTok->isBinaryOperator())
2004 const auto *Prev = FormatTok->getPreviousNonComment();
2006 if (Prev && Prev->is(tok::identifier))
2009 if (FormatTok->Tok.isAnyIdentifier() || FormatTok->isTypeName(LangOpts)) {
2012 if (FormatTok->is(tok::less)) {
2014 parseBracedList(
true);
2017 while (FormatTok->is(tok::star))
2021 if (FormatTok->is(tok::l_paren))
2024 if (FormatTok->is(tok::l_brace))
2029 if (InRequiresExpression)
2030 FormatTok->setFinalizedType(TT_BracedListLBrace);
2031 if (!tryToParsePropertyAccessor() && !tryToParseBracedList()) {
2032 IsDecltypeAutoFunction =
Line->SeenDecltypeAuto;
2037 if (Style.isJava() &&
2038 Line->Tokens.front().Tok->is(Keywords.kw_synchronized)) {
2041 if (Style.BraceWrapping.AfterControlStatement ==
2045 }
else if (Style.BraceWrapping.AfterFunction) {
2049 FormatTok->setFinalizedType(TT_FunctionLBrace);
2051 IsDecltypeAutoFunction =
false;
2059 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
2065 if (Style.BraceWrapping.AfterFunction)
2069 case tok::identifier: {
2070 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where) &&
2071 Line->MustBeDeclaration) {
2073 parseCSharpGenericTypeConstraint();
2076 if (FormatTok->is(TT_MacroBlockEnd)) {
2085 size_t TokenCount =
Line->Tokens.size();
2086 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_function) &&
2089 Line->Tokens.front().Tok->isNot(Keywords.kw_async)))) {
2090 tryToParseJSFunction();
2093 if ((Style.isJavaScript() || Style.isJava()) &&
2094 FormatTok->is(Keywords.kw_interface)) {
2095 if (Style.isJavaScript()) {
2100 unsigned StoredPosition = Tokens->getPosition();
2102 FormatTok = Tokens->setPosition(StoredPosition);
2113 if (Style.isVerilog()) {
2114 if (FormatTok->is(Keywords.kw_table)) {
2115 parseVerilogTable();
2118 if (Keywords.isVerilogBegin(*FormatTok) ||
2119 Keywords.isVerilogHierarchy(*FormatTok)) {
2126 if (!IsCpp && FormatTok->is(Keywords.kw_interface)) {
2127 if (parseStructLike())
2132 if (IsCpp && FormatTok->is(TT_StatementMacro)) {
2133 parseStatementMacro();
2138 StringRef
Text = FormatTok->TokenText;
2145 if (Style.isJavaScript())
2148 auto OneTokenSoFar = [&]() {
2149 auto I =
Line->Tokens.begin(), E =
Line->Tokens.end();
2150 while (I != E && I->Tok->is(tok::comment))
2152 if (Style.isVerilog())
2153 while (I != E && I->Tok->is(tok::hash))
2155 return I != E && (++I == E);
2157 if (OneTokenSoFar()) {
2160 bool FunctionLike = FormatTok->is(tok::l_paren);
2164 bool FollowedByNewline =
2165 CommentsBeforeNextToken.empty()
2166 ? FormatTok->NewlinesBefore > 0
2167 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
2169 if (FollowedByNewline &&
2170 (
Text.size() >= 5 ||
2171 (FunctionLike && FormatTok->isNot(tok::l_paren))) &&
2173 if (PreviousToken->isNot(TT_UntouchableMacroFunc))
2174 PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro);
2182 if ((Style.isJavaScript() || Style.isCSharp()) &&
2183 FormatTok->is(TT_FatArrow)) {
2184 tryToParseChildBlock();
2190 if (FormatTok->is(tok::l_brace)) {
2194 if (!Style.isJavaScript())
2195 FormatTok->setBlockKind(BK_BracedInit);
2198 if (Style.isTableGen() &&
2199 Line->Tokens.begin()->Tok->is(Keywords.kw_defset)) {
2200 FormatTok->setFinalizedType(TT_FunctionLBrace);
2201 parseBlock(
false, 1u,
2209 FormatTok->is(tok::less)) {
2211 parseBracedList(
true);
2218 if ((Style.isCSharp() &&
2219 (Tokens->peekNextToken()->isAccessSpecifierKeyword() ||
2221 FormatTok->endsSequence(tok::kw_new, tok::kw_operator)) {
2227 case tok::kw_switch:
2240 if (Style.isVerilog()) {
2245 if (Style.isJavaScript() &&
Line->MustBeDeclaration) {
2252 case tok::kw_default:
2254 if (Style.isVerilog()) {
2255 if (FormatTok->is(tok::colon)) {
2259 if (FormatTok->is(Keywords.kw_clocking)) {
2265 parseVerilogCaseLabel();
2271 if (Style.isVerilog()) {
2272 parseVerilogCaseLabel();
2278 if (FormatTok->is(tok::l_brace))
2279 FormatTok->Previous->setFinalizedType(TT_TemplateCloser);
2288bool UnwrappedLineParser::tryToParsePropertyAccessor() {
2289 assert(FormatTok->is(tok::l_brace));
2290 if (!Style.isCSharp())
2293 if (!FormatTok->Previous || FormatTok->Previous->isNot(tok::identifier))
2301 unsigned int StoredPosition = Tokens->getPosition();
2307 bool HasSpecialAccessor =
false;
2308 bool IsTrivialPropertyAccessor =
true;
2311 if (
const bool IsAccessorKeyword =
2312 Tok->
isOneOf(Keywords.kw_get, Keywords.kw_init, Keywords.kw_set);
2313 IsAccessorKeyword ||
Tok->isAccessSpecifierKeyword() ||
2314 Tok->
isOneOf(tok::l_square, tok::semi, Keywords.kw_internal)) {
2315 if (IsAccessorKeyword)
2316 HasSpecialAccessor =
true;
2317 else if (
Tok->
is(tok::l_square))
2319 Tok = Tokens->getNextToken();
2323 IsTrivialPropertyAccessor =
false;
2328 Tokens->setPosition(StoredPosition);
2334 Tokens->setPosition(StoredPosition);
2335 if (!IsTrivialPropertyAccessor && Style.BraceWrapping.AfterFunction)
2339 switch (FormatTok->Tok.getKind()) {
2342 if (FormatTok->is(tok::equal)) {
2343 while (!
eof() && FormatTok->isNot(tok::semi))
2356 if (FormatTok->is(TT_FatArrow)) {
2360 }
while (!
eof() && FormatTok->isNot(tok::semi));
2369 if (FormatTok->isOneOf(Keywords.kw_get, Keywords.kw_init,
2371 !IsTrivialPropertyAccessor) {
2383bool UnwrappedLineParser::tryToParseLambda() {
2384 assert(FormatTok->is(tok::l_square));
2390 if (!tryToParseLambdaIntroducer())
2394 bool InTemplateParameterList =
false;
2396 while (FormatTok->isNot(tok::l_brace)) {
2397 if (FormatTok->isTypeName(LangOpts) || FormatTok->isAttribute()) {
2401 switch (FormatTok->Tok.getKind()) {
2405 parseParens(TT_PointerOrReference);
2411 assert(FormatTok->Previous);
2412 if (FormatTok->Previous->is(tok::r_square))
2413 InTemplateParameterList =
true;
2418 case tok::kw_struct:
2420 case tok::kw_template:
2421 case tok::kw_typename:
2425 case tok::kw_constexpr:
2426 case tok::kw_consteval:
2429 case tok::identifier:
2430 case tok::numeric_constant:
2431 case tok::coloncolon:
2432 case tok::kw_mutable:
2433 case tok::kw_noexcept:
2434 case tok::kw_static:
2459 case tok::equalequal:
2460 case tok::exclaimequal:
2461 case tok::greaterequal:
2462 case tok::lessequal:
2468 if (Arrow || InTemplateParameterList) {
2477 case tok::kw_requires:
2478 parseRequiresClause();
2481 if (!InTemplateParameterList)
2490 FormatTok->setFinalizedType(TT_LambdaLBrace);
2491 LSquare.setFinalizedType(TT_LambdaLSquare);
2494 Arrow->setFinalizedType(TT_LambdaArrow);
2496 NestedLambdas.push_back(
Line->SeenDecltypeAuto);
2498 assert(!NestedLambdas.empty());
2499 NestedLambdas.pop_back();
2504bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
2509 const auto *PrevPrev =
Previous->getPreviousNonComment();
2510 if (
Previous->is(tok::star) && PrevPrev && PrevPrev->isTypeName(LangOpts))
2518 if (!PrevPrev || PrevPrev->isNoneOf(tok::greater, tok::r_paren))
2522 Previous->isNoneOf(tok::kw_return, tok::kw_co_await, tok::kw_co_yield,
2523 tok::kw_co_return)) {
2527 if (LeftSquare->isCppStructuredBinding(IsCpp))
2529 if (FormatTok->is(tok::l_square) ||
tok::isLiteral(FormatTok->Tok.getKind()))
2531 if (FormatTok->is(tok::r_square)) {
2533 if (
Next->is(tok::greater))
2540void UnwrappedLineParser::tryToParseJSFunction() {
2541 assert(FormatTok->is(Keywords.kw_function));
2542 if (FormatTok->is(Keywords.kw_async))
2548 if (FormatTok->is(tok::star)) {
2549 FormatTok->setFinalizedType(TT_OverloadedOperator);
2554 if (FormatTok->is(tok::identifier))
2557 if (FormatTok->isNot(tok::l_paren))
2563 if (FormatTok->is(tok::colon)) {
2569 if (FormatTok->is(tok::l_brace))
2570 tryToParseBracedList();
2572 while (FormatTok->isNoneOf(tok::l_brace, tok::semi) && !
eof())
2576 if (FormatTok->is(tok::semi))
2582bool UnwrappedLineParser::tryToParseBracedList() {
2583 if (FormatTok->is(BK_Unknown))
2584 calculateBraceTypes();
2585 assert(FormatTok->isNot(BK_Unknown));
2586 if (FormatTok->is(BK_Block))
2593bool UnwrappedLineParser::tryToParseChildBlock() {
2594 assert(Style.isJavaScript() || Style.isCSharp());
2595 assert(FormatTok->is(TT_FatArrow));
2600 if (FormatTok->isNot(tok::l_brace))
2606bool UnwrappedLineParser::parseBracedList(
bool IsAngleBracket,
bool IsEnum) {
2607 assert(!IsAngleBracket || !IsEnum);
2608 bool HasError =
false;
2613 if (Style.isCSharp() && FormatTok->is(TT_FatArrow) &&
2614 tryToParseChildBlock()) {
2617 if (Style.isJavaScript()) {
2618 if (FormatTok->is(Keywords.kw_function)) {
2619 tryToParseJSFunction();
2622 if (FormatTok->is(tok::l_brace)) {
2624 if (tryToParseBracedList())
2629 if (FormatTok->is(IsAngleBracket ? tok::greater : tok::r_brace)) {
2631 FormatTok->setBlockKind(BK_Block);
2632 if (!Style.AllowShortEnumsOnASingleLine)
2638 switch (FormatTok->Tok.getKind()) {
2640 if (Style.isCSharp())
2649 if (Style.isJavaScript()) {
2650 if (FormatTok->is(tok::l_brace))
2658 FormatTok->setBlockKind(BK_BracedInit);
2659 if (!IsAngleBracket) {
2660 auto *Prev = FormatTok->Previous;
2661 if (Prev && Prev->is(tok::greater))
2662 Prev->setFinalizedType(TT_TemplateCloser);
2670 parseBracedList(
true);
2678 if (Style.isJavaScript() || Style.isProto() || Style.isJson()) {
2689 if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
2692 case tok::kw_requires:
2693 parseRequiresExpression();
2710bool UnwrappedLineParser::parseParens(TokenType StarAndAmpTokenType,
2712 assert(FormatTok->is(tok::l_paren) &&
"'(' expected.");
2713 auto *LParen = FormatTok;
2714 auto *Prev = FormatTok->Previous;
2715 bool SeenComma =
false;
2716 bool SeenEqual =
false;
2717 bool MightBeFoldExpr =
false;
2718 unsigned ExcessLess = 0;
2720 const bool MightBeStmtExpr = FormatTok->is(tok::l_brace);
2721 if (!InMacroCall && Prev && Prev->is(TT_FunctionLikeMacro))
2724 switch (FormatTok->Tok.getKind()) {
2726 if (parseParens(ExcessLess == 0 ? StarAndAmpTokenType : TT_Unknown,
2730 if (Style.isJava() && FormatTok->is(tok::l_brace))
2733 case tok::r_paren: {
2734 auto *RParen = FormatTok;
2737 auto OptionalParens = [&] {
2739 MightBeStmtExpr || MightBeFoldExpr || SeenComma || InMacroCall ||
2740 Line->InMacroBody || RParen->getPreviousNonComment() == LParen) {
2743 const bool DoubleParens =
2744 Prev->is(tok::l_paren) && FormatTok->is(tok::r_paren);
2746 const auto *PrevPrev = Prev->getPreviousNonComment();
2747 const bool Excluded =
2749 (PrevPrev->isOneOf(tok::kw___attribute, tok::kw_decltype) ||
2751 (PrevPrev->isOneOf(tok::kw_if, tok::kw_while) ||
2752 PrevPrev->endsSequence(tok::kw_constexpr, tok::kw_if))));
2756 const bool CommaSeparated =
2757 Prev->isOneOf(tok::l_paren, tok::comma) &&
2758 FormatTok->isOneOf(tok::comma, tok::r_paren);
2759 if (CommaSeparated &&
2761 !Prev->endsSequence(tok::comma, tok::ellipsis) &&
2763 !(FormatTok->is(tok::comma) &&
2764 Tokens->peekNextToken()->is(tok::ellipsis))) {
2767 const bool ReturnParens =
2769 ((NestedLambdas.empty() && !IsDecltypeAutoFunction) ||
2770 (!NestedLambdas.empty() && !NestedLambdas.back())) &&
2771 Prev->isOneOf(tok::kw_return, tok::kw_co_return) &&
2772 FormatTok->is(tok::semi);
2778 if (OptionalParens()) {
2779 LParen->Optional =
true;
2780 RParen->Optional =
true;
2781 }
else if (Prev->is(TT_TypenameMacro)) {
2782 LParen->setFinalizedType(TT_TypeDeclarationParen);
2783 RParen->setFinalizedType(TT_TypeDeclarationParen);
2784 }
else if (Prev->is(tok::greater) && RParen->Previous == LParen) {
2785 Prev->setFinalizedType(TT_TemplateCloser);
2786 }
else if (FormatTok->is(tok::l_brace) && Prev->is(tok::amp) &&
2788 FormatTok->setBlockKind(BK_BracedInit);
2800 if (!tryToParseBracedList())
2805 if (FormatTok->is(tok::l_brace)) {
2815 MightBeFoldExpr =
true;
2820 if (Style.isCSharp() && FormatTok->is(TT_FatArrow))
2821 tryToParseChildBlock();
2826 if (Style.isJavaScript())
2831 case tok::identifier:
2832 if (Style.isJavaScript() && (FormatTok->is(Keywords.kw_function)))
2833 tryToParseJSFunction();
2837 case tok::kw_switch:
2843 case tok::kw_requires:
2844 parseRequiresExpression();
2860 if (StarAndAmpTokenType != TT_Unknown && ExcessLess == 0)
2861 FormatTok->setFinalizedType(StarAndAmpTokenType);
2871void UnwrappedLineParser::parseSquare(
bool SkipLambda) {
2873 assert(FormatTok->is(tok::l_square) &&
"'[' expected.");
2874 if (tryToParseLambda())
2878 switch (FormatTok->Tok.getKind()) {
2891 case tok::l_brace: {
2892 if (!tryToParseBracedList())
2899 if (FormatTok->is(tok::l_brace)) {
2911void UnwrappedLineParser::keepAncestorBraces() {
2912 if (!Style.RemoveBracesLLVM)
2915 const int MaxNestingLevels = 2;
2916 const int Size = NestedTooDeep.size();
2917 if (Size >= MaxNestingLevels)
2918 NestedTooDeep[
Size - MaxNestingLevels] =
true;
2919 NestedTooDeep.push_back(
false);
2923 for (
const auto &
Token : llvm::reverse(
Line.Tokens))
2930void UnwrappedLineParser::parseUnbracedBody(
bool CheckEOF) {
2933 if (Style.InsertBraces && !
Line->InPPDirective && !
Line->Tokens.empty() &&
2934 PreprocessorDirectives.empty() && FormatTok->isNot(tok::semi)) {
2936 ? getLastNonComment(*
Line)
2939 if (
Tok->BraceCount < 0) {
2940 assert(
Tok->BraceCount == -1);
2943 Tok->BraceCount = -1;
2948 const auto BodyStart = CurrentLines->size();
2950 ++
Line->UnbracedBodyLevel;
2951 parseStructuralElement();
2952 --
Line->UnbracedBodyLevel;
2955 assert(!
Line->InPPDirective);
2958 auto BodyEnd = CurrentLines->size();
2959 while (BodyEnd > 0) {
2960 const auto &L = (*CurrentLines)[--BodyEnd];
2962 Tok = L.Tokens.back().Tok;
2968 bool EnclosesPPDirective =
false;
2969 for (
size_t I = BodyStart; I <= BodyEnd && !EnclosesPPDirective; ++I) {
2970 const auto &BodyLine = (*CurrentLines)[I];
2971 EnclosesPPDirective =
2972 BodyLine.InPPDirective ||
2973 llvm::any_of(BodyLine.Tokens, [](
const UnwrappedLineNode &Node) {
2974 return Node.Tok->FirstAfterPPLine;
2977 if (EnclosesPPDirective)
2978 LBraceTok->BraceCount = 0;
2983 if (CheckEOF &&
eof())
2993 assert(LeftBrace->
is(tok::l_brace));
3001 assert(RightBrace->
is(tok::r_brace));
3009void UnwrappedLineParser::handleAttributes() {
3011 if (FormatTok->isAttribute())
3013 else if (FormatTok->is(tok::l_square))
3014 handleCppAttributes();
3017bool UnwrappedLineParser::handleCppAttributes() {
3019 assert(FormatTok->is(tok::l_square));
3020 if (!tryToParseSimpleAttribute())
3027bool UnwrappedLineParser::isBlockBegin(
const FormatToken &
Tok)
const {
3030 return Style.isVerilog() ? Keywords.isVerilogBegin(
Tok)
3031 :
Tok.
is(tok::l_brace);
3034FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
3036 bool IsVerilogAssert) {
3037 assert((FormatTok->is(tok::kw_if) ||
3038 (Style.isVerilog() &&
3039 FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
3040 Keywords.kw_assume, Keywords.kw_cover))) &&
3044 if (IsVerilogAssert) {
3046 if (FormatTok->is(Keywords.kw_verilogHash)) {
3048 if (FormatTok->is(tok::numeric_constant))
3050 }
else if (FormatTok->isOneOf(Keywords.kw_final, Keywords.kw_property,
3051 Keywords.kw_sequence)) {
3057 if (Style.isTableGen()) {
3058 while (!
eof() && FormatTok->isNot(Keywords.kw_then)) {
3065 if (FormatTok->is(tok::exclaim))
3068 bool KeepIfBraces =
true;
3069 if (FormatTok->is(tok::kw_consteval)) {
3072 KeepIfBraces = !Style.RemoveBracesLLVM || KeepBraces;
3073 if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
3075 if (FormatTok->is(tok::l_paren)) {
3076 FormatTok->setFinalizedType(TT_ConditionLParen);
3082 if (IsVerilogAssert && FormatTok->is(tok::semi)) {
3088 bool NeedsUnwrappedLine =
false;
3089 keepAncestorBraces();
3092 IfStmtKind IfBlockKind = IfStmtKind::NotIf;
3094 if (isBlockBegin(*FormatTok)) {
3095 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3096 IfLeftBrace = FormatTok;
3097 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3098 parseBlock(
false, 1u,
3099 true, KeepIfBraces, &IfBlockKind);
3100 setPreviousRBraceType(TT_ControlStatementRBrace);
3101 if (Style.BraceWrapping.BeforeElse)
3104 NeedsUnwrappedLine =
true;
3105 }
else if (IsVerilogAssert && FormatTok->is(tok::kw_else)) {
3108 parseUnbracedBody();
3111 if (Style.RemoveBracesLLVM) {
3112 assert(!NestedTooDeep.empty());
3113 KeepIfBraces = KeepIfBraces ||
3114 (IfLeftBrace && !IfLeftBrace->MatchingParen) ||
3115 NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly ||
3116 IfBlockKind == IfStmtKind::IfElseIf;
3119 bool KeepElseBraces = KeepIfBraces;
3121 IfStmtKind
Kind = IfStmtKind::IfOnly;
3123 if (FormatTok->is(tok::kw_else)) {
3124 if (Style.RemoveBracesLLVM) {
3125 NestedTooDeep.back() =
false;
3126 Kind = IfStmtKind::IfElse;
3130 if (isBlockBegin(*FormatTok)) {
3131 const bool FollowedByIf = Tokens->peekNextToken()->is(tok::kw_if);
3132 FormatTok->setFinalizedType(TT_ElseLBrace);
3133 ElseLeftBrace = FormatTok;
3134 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3135 IfStmtKind ElseBlockKind = IfStmtKind::NotIf;
3137 parseBlock(
false, 1u,
3138 true, KeepElseBraces, &ElseBlockKind);
3139 setPreviousRBraceType(TT_ElseRBrace);
3140 if (FormatTok->is(tok::kw_else)) {
3141 KeepElseBraces = KeepElseBraces ||
3142 ElseBlockKind == IfStmtKind::IfOnly ||
3143 ElseBlockKind == IfStmtKind::IfElseIf;
3144 }
else if (FollowedByIf && IfLBrace && !IfLBrace->Optional) {
3145 KeepElseBraces =
true;
3146 assert(ElseLeftBrace->MatchingParen);
3150 }
else if (!IsVerilogAssert && FormatTok->is(tok::kw_if)) {
3153 const bool IsPrecededByComment =
Previous->is(tok::comment);
3154 if (IsPrecededByComment) {
3158 bool TooDeep =
true;
3159 if (Style.RemoveBracesLLVM) {
3160 Kind = IfStmtKind::IfElseIf;
3161 TooDeep = NestedTooDeep.pop_back_val();
3163 ElseLeftBrace = parseIfThenElse(
nullptr, KeepIfBraces);
3164 if (Style.RemoveBracesLLVM)
3165 NestedTooDeep.push_back(TooDeep);
3166 if (IsPrecededByComment)
3169 parseUnbracedBody(
true);
3172 KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse;
3173 if (NeedsUnwrappedLine)
3177 if (!Style.RemoveBracesLLVM)
3180 assert(!NestedTooDeep.empty());
3181 KeepElseBraces = KeepElseBraces ||
3182 (ElseLeftBrace && !ElseLeftBrace->MatchingParen) ||
3183 NestedTooDeep.back();
3185 NestedTooDeep.pop_back();
3187 if (!KeepIfBraces && !KeepElseBraces) {
3190 }
else if (IfLeftBrace) {
3191 FormatToken *IfRightBrace = IfLeftBrace->MatchingParen;
3193 assert(IfRightBrace->MatchingParen == IfLeftBrace);
3194 assert(!IfLeftBrace->Optional);
3195 assert(!IfRightBrace->Optional);
3196 IfLeftBrace->MatchingParen =
nullptr;
3197 IfRightBrace->MatchingParen =
nullptr;
3207void UnwrappedLineParser::parseTryCatch() {
3208 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) &&
"'try' expected");
3210 bool NeedsUnwrappedLine =
false;
3211 bool HasCtorInitializer =
false;
3212 if (FormatTok->is(tok::colon)) {
3213 auto *Colon = FormatTok;
3216 if (FormatTok->is(tok::identifier)) {
3217 HasCtorInitializer =
true;
3218 Colon->setFinalizedType(TT_CtorInitializerColon);
3223 while (FormatTok->is(tok::comma))
3226 while (FormatTok->is(tok::identifier)) {
3228 if (FormatTok->is(tok::l_paren)) {
3230 }
else if (FormatTok->is(tok::l_brace)) {
3237 while (FormatTok->is(tok::comma))
3242 if (Style.isJava() && FormatTok->is(tok::l_paren))
3245 keepAncestorBraces();
3247 if (FormatTok->is(tok::l_brace)) {
3248 if (HasCtorInitializer)
3249 FormatTok->setFinalizedType(TT_FunctionLBrace);
3250 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3252 if (Style.BraceWrapping.BeforeCatch)
3255 NeedsUnwrappedLine =
true;
3256 }
else if (FormatTok->isNot(tok::kw_catch)) {
3262 parseStructuralElement();
3265 for (
bool SeenCatch =
false;;) {
3266 if (FormatTok->is(tok::at))
3268 if (FormatTok->isNoneOf(tok::kw_catch, Keywords.kw___except,
3269 tok::kw___finally, tok::objc_catch,
3270 tok::objc_finally) &&
3271 !((Style.isJava() || Style.isJavaScript()) &&
3272 FormatTok->is(Keywords.kw_finally))) {
3275 if (FormatTok->is(tok::kw_catch))
3278 while (FormatTok->isNot(tok::l_brace)) {
3279 if (FormatTok->is(tok::l_paren)) {
3283 if (FormatTok->isOneOf(tok::semi, tok::r_brace) ||
eof()) {
3284 if (Style.RemoveBracesLLVM)
3285 NestedTooDeep.pop_back();
3291 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3294 NeedsUnwrappedLine =
false;
3295 Line->MustBeDeclaration =
false;
3296 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3298 if (Style.BraceWrapping.BeforeCatch)
3301 NeedsUnwrappedLine =
true;
3304 if (Style.RemoveBracesLLVM)
3305 NestedTooDeep.pop_back();
3307 if (NeedsUnwrappedLine)
3311void UnwrappedLineParser::parseNamespaceOrExportBlock(
unsigned AddLevels) {
3312 bool ManageWhitesmithsBraces =
3317 if (ManageWhitesmithsBraces)
3322 parseBlock(
true, AddLevels,
true,
3323 true,
nullptr, ManageWhitesmithsBraces);
3325 addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep);
3327 if (ManageWhitesmithsBraces)
3331void UnwrappedLineParser::parseNamespace() {
3332 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
3333 "'namespace' expected");
3337 if (InitialToken.is(TT_NamespaceMacro)) {
3340 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
3341 tok::l_square, tok::period, tok::l_paren) ||
3342 (Style.isCSharp() && FormatTok->is(tok::kw_union))) {
3343 if (FormatTok->is(tok::l_square))
3345 else if (FormatTok->is(tok::l_paren))
3351 if (FormatTok->is(tok::l_brace)) {
3352 FormatTok->setFinalizedType(TT_NamespaceLBrace);
3355 Tokens->peekNextToken()->is(tok::r_brace))) {
3359 unsigned AddLevels =
3362 DeclarationScopeStack.size() > 1)
3365 parseNamespaceOrExportBlock(AddLevels);
3370void UnwrappedLineParser::parseCppExportBlock() {
3371 if (FormatTok->is(tok::l_brace)) {
3372 FormatTok->setFinalizedType(TT_ExportLBrace);
3373 if (Style.BraceWrapping.AfterExportBlock)
3376 parseNamespaceOrExportBlock(Style.IndentExportBlock ? 1 : 0);
3379void UnwrappedLineParser::parseNew() {
3380 assert(FormatTok->is(tok::kw_new) &&
"'new' expected");
3383 if (Style.isCSharp()) {
3386 if (FormatTok->is(tok::l_paren))
3390 if (FormatTok->is(tok::l_brace))
3393 if (FormatTok->isOneOf(tok::semi, tok::comma))
3398 }
else if (Style.isJava()) {
3402 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
3406 if (FormatTok->is(tok::l_paren)) {
3411 if (FormatTok->is(tok::l_brace))
3417 }
else if (Style.isCpp()) {
3421 if (FormatTok->is(tok::l_brace))
3423 if (FormatTok->is(tok::l_paren))
3425 if (FormatTok->is(tok::l_paren)) {
3431 if (FormatTok->isOneOf(tok::kw_alignas, tok::kw_decltype)) {
3433 if (FormatTok->is(tok::l_paren))
3435 }
else if (FormatTok->is(tok::l_square)) {
3438 }
else if (FormatTok->is(tok::less)) {
3440 parseBracedList(
true);
3441 }
else if (FormatTok->Tok.getIdentifierInfo() ||
3442 FormatTok->isOneOf(tok::coloncolon, tok::star)) {
3449 if (FormatTok->is(tok::l_brace))
3451 else if (FormatTok->is(tok::l_paren))
3456void UnwrappedLineParser::parseLoopBody(
bool KeepBraces,
bool WrapRightBrace) {
3457 keepAncestorBraces();
3459 if (isBlockBegin(*FormatTok)) {
3460 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3462 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3463 parseBlock(
false, 1u,
3465 setPreviousRBraceType(TT_ControlStatementRBrace);
3467 assert(!NestedTooDeep.empty());
3468 if (!NestedTooDeep.back())
3474 parseUnbracedBody();
3478 NestedTooDeep.pop_back();
3481void UnwrappedLineParser::parseForOrWhileLoop(
bool HasParens) {
3482 assert((FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) ||
3483 (Style.isVerilog() &&
3484 FormatTok->isOneOf(Keywords.kw_always, Keywords.kw_always_comb,
3485 Keywords.kw_always_ff, Keywords.kw_always_latch,
3486 Keywords.kw_final, Keywords.kw_initial,
3487 Keywords.kw_foreach, Keywords.kw_forever,
3488 Keywords.kw_repeat))) &&
3489 "'for', 'while' or foreach macro expected");
3490 const bool KeepBraces = !Style.RemoveBracesLLVM ||
3491 FormatTok->isNoneOf(tok::kw_for, tok::kw_while);
3495 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
3497 if (IsCpp && FormatTok->is(tok::kw_co_await))
3499 if (HasParens && FormatTok->is(tok::l_paren)) {
3503 if (Style.isVerilog())
3504 FormatTok->setFinalizedType(TT_ConditionLParen);
3508 if (Style.isVerilog()) {
3510 parseVerilogSensitivityList();
3511 }
else if (Style.AllowShortLoopsOnASingleLine && FormatTok->is(tok::semi) &&
3512 Tokens->getPreviousToken()->is(tok::r_paren)) {
3519 parseLoopBody(KeepBraces,
true);
3522void UnwrappedLineParser::parseDoWhile() {
3523 assert(FormatTok->is(tok::kw_do) &&
"'do' expected");
3526 parseLoopBody(
true, Style.BraceWrapping.BeforeWhile);
3529 if (FormatTok->isNot(tok::kw_while)) {
3534 FormatTok->setFinalizedType(TT_DoWhile);
3542 parseStructuralElement();
3545void UnwrappedLineParser::parseLabel(
bool IsGotoLabel) {
3548 const auto IndentGotoLabel = Style.IndentGotoLabels;
3549 const auto OldLineLevel =
Line->Level;
3556 if (OldLineLevel > 1 || (!
Line->InPPDirective && OldLineLevel > 0))
3560 if (!IsGotoLabel && !Style.IndentCaseBlocks &&
3561 CommentsBeforeNextToken.empty() && FormatTok->is(tok::l_brace)) {
3562 CompoundStatementIndenter Indenter(
this,
Level,
3563 Style.BraceWrapping.AfterCaseLabel,
3564 Style.BraceWrapping.IndentBraces);
3566 if (FormatTok->is(tok::kw_break)) {
3567 if (Style.BraceWrapping.AfterControlStatement ==
3569 Style.CompactCaseLabels) {
3571 if (!Style.IndentCaseBlocks &&
3576 parseStructuralElement();
3580 if (FormatTok->is(tok::semi))
3585 Level = OldLineLevel;
3587 if (FormatTok->isNot(tok::l_brace)) {
3588 parseStructuralElement();
3593void UnwrappedLineParser::parseCaseLabel() {
3594 assert(FormatTok->is(tok::kw_case) &&
"'case' expected");
3595 auto *Case = FormatTok;
3600 if (FormatTok->is(tok::colon)) {
3601 FormatTok->setFinalizedType(TT_CaseLabelColon);
3604 if (Style.isJava() && FormatTok->is(tok::arrow)) {
3605 FormatTok->setFinalizedType(TT_CaseLabelArrow);
3606 Case->setFinalizedType(TT_SwitchExpressionLabel);
3613void UnwrappedLineParser::parseSwitch(
bool IsExpr) {
3614 assert(FormatTok->is(tok::kw_switch) &&
"'switch' expected");
3616 if (FormatTok->is(tok::l_paren))
3619 keepAncestorBraces();
3621 if (FormatTok->is(tok::l_brace)) {
3622 CompoundStatementIndenter Indenter(
this, Style,
Line->Level);
3623 FormatTok->setFinalizedType(IsExpr ? TT_SwitchExpressionLBrace
3624 : TT_ControlStatementLBrace);
3629 setPreviousRBraceType(TT_ControlStatementRBrace);
3635 parseStructuralElement();
3639 if (Style.RemoveBracesLLVM)
3640 NestedTooDeep.pop_back();
3643void UnwrappedLineParser::parseAccessSpecifier() {
3646 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
3649 if (FormatTok->is(tok::colon))
3657bool UnwrappedLineParser::parseRequires(
bool SeenEqual) {
3658 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3662 switch (Tokens->peekNextToken(
true)->Tok.getKind()) {
3665 parseRequiresExpression();
3672 parseRequiresClause();
3683 auto *PreviousNonComment = FormatTok->getPreviousNonComment();
3685 if (!PreviousNonComment ||
3686 PreviousNonComment->is(TT_RequiresExpressionLBrace)) {
3689 parseRequiresClause();
3693 switch (PreviousNonComment->Tok.getKind()) {
3696 case tok::kw_noexcept:
3701 parseRequiresClause();
3710 auto PrevPrev = PreviousNonComment->getPreviousNonComment();
3711 if ((PrevPrev && PrevPrev->is(tok::kw_const)) || !SeenEqual) {
3712 parseRequiresClause();
3718 if (PreviousNonComment->isTypeOrIdentifier(LangOpts)) {
3720 parseRequiresClause();
3724 parseRequiresExpression();
3734 unsigned StoredPosition = Tokens->getPosition();
3737 auto PeekNext = [&Lookahead, &NextToken,
this] {
3739 NextToken = Tokens->getNextToken();
3742 bool FoundType =
false;
3743 bool LastWasColonColon =
false;
3746 for (; Lookahead < 50; PeekNext()) {
3747 switch (NextToken->Tok.getKind()) {
3748 case tok::kw_volatile:
3751 if (OpenAngles == 0) {
3752 FormatTok = Tokens->setPosition(StoredPosition);
3753 parseRequiresExpression();
3761 case tok::coloncolon:
3762 LastWasColonColon =
true;
3764 case tok::kw_decltype:
3765 case tok::identifier:
3766 if (FoundType && !LastWasColonColon && OpenAngles == 0) {
3767 FormatTok = Tokens->setPosition(StoredPosition);
3768 parseRequiresExpression();
3772 LastWasColonColon =
false;
3781 if (NextToken->isTypeName(LangOpts)) {
3782 FormatTok = Tokens->setPosition(StoredPosition);
3783 parseRequiresExpression();
3790 FormatTok = Tokens->setPosition(StoredPosition);
3791 parseRequiresClause();
3800void UnwrappedLineParser::parseRequiresClause() {
3801 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3806 bool InRequiresExpression =
3807 !FormatTok->Previous ||
3808 FormatTok->Previous->is(TT_RequiresExpressionLBrace);
3810 FormatTok->setFinalizedType(InRequiresExpression
3811 ? TT_RequiresClauseInARequiresExpression
3812 : TT_RequiresClause);
3817 parseConstraintExpression();
3819 if (!InRequiresExpression && FormatTok->Previous)
3820 FormatTok->Previous->ClosesRequiresClause =
true;
3828void UnwrappedLineParser::parseRequiresExpression() {
3829 assert(FormatTok->is(tok::kw_requires) &&
"'requires' expected");
3831 FormatTok->setFinalizedType(TT_RequiresExpression);
3834 if (FormatTok->is(tok::l_paren)) {
3835 FormatTok->setFinalizedType(TT_RequiresExpressionLParen);
3839 if (FormatTok->is(tok::l_brace)) {
3840 FormatTok->setFinalizedType(TT_RequiresExpressionLBrace);
3849void UnwrappedLineParser::parseConstraintExpression() {
3856 bool LambdaNextTimeAllowed =
true;
3866 bool TopLevelParensAllowed =
true;
3869 bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed,
false);
3871 switch (FormatTok->Tok.getKind()) {
3872 case tok::kw_requires:
3873 parseRequiresExpression();
3877 if (!TopLevelParensAllowed)
3879 parseParens(TT_BinaryOperator);
3880 TopLevelParensAllowed =
false;
3884 if (!LambdaThisTimeAllowed || !tryToParseLambda())
3891 case tok::kw_struct:
3901 FormatTok->setFinalizedType(TT_BinaryOperator);
3903 LambdaNextTimeAllowed =
true;
3904 TopLevelParensAllowed =
true;
3909 LambdaNextTimeAllowed = LambdaThisTimeAllowed;
3913 case tok::kw_sizeof:
3915 case tok::greaterequal:
3916 case tok::greatergreater:
3918 case tok::lessequal:
3920 case tok::equalequal:
3922 case tok::exclaimequal:
3927 LambdaNextTimeAllowed =
true;
3928 TopLevelParensAllowed =
true;
3933 case tok::numeric_constant:
3934 case tok::coloncolon:
3937 TopLevelParensAllowed =
false;
3942 case tok::kw_static_cast:
3943 case tok::kw_const_cast:
3944 case tok::kw_reinterpret_cast:
3945 case tok::kw_dynamic_cast:
3947 if (FormatTok->isNot(tok::less))
3951 parseBracedList(
true);
3955 if (!FormatTok->Tok.getIdentifierInfo()) {
3965 assert(FormatTok->Previous);
3966 switch (FormatTok->Previous->Tok.getKind()) {
3967 case tok::coloncolon:
3971 case tok::kw_requires:
3973 case tok::kw_template:
3981 if (FormatTok->is(tok::less)) {
3983 parseBracedList(
true);
3985 TopLevelParensAllowed =
false;
3991bool UnwrappedLineParser::parseEnum() {
3995 if (FormatTok->is(tok::kw_enum))
4001 if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question))
4010 if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
4012 while (FormatTok->is(tok::l_square))
4013 if (!handleCppAttributes())
4017 while (FormatTok->Tok.getIdentifierInfo() ||
4018 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
4019 tok::greater, tok::comma, tok::question,
4021 if (FormatTok->is(tok::colon))
4022 FormatTok->setFinalizedType(TT_EnumUnderlyingTypeColon);
4023 if (Style.isVerilog()) {
4024 FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
4027 while (FormatTok->is(tok::l_square))
4033 if (FormatTok->is(tok::l_paren))
4035 if (FormatTok->is(tok::identifier)) {
4039 if (IsCpp && FormatTok->is(tok::identifier))
4045 if (FormatTok->isNot(tok::l_brace))
4047 FormatTok->setFinalizedType(TT_EnumLBrace);
4048 FormatTok->setBlockKind(BK_Block);
4050 if (Style.isJava()) {
4052 parseJavaEnumBody();
4060 const bool ManageWhitesmithsBraces =
4063 if (!Style.AllowShortEnumsOnASingleLine &&
4065 Tokens->peekNextToken()->is(tok::r_brace))) {
4070 if (ManageWhitesmithsBraces)
4075 if (!Style.AllowShortEnumsOnASingleLine) {
4077 if (!ManageWhitesmithsBraces)
4080 const auto OpeningLineIndex =
4081 CurrentLines->empty() || !CurrentExpandedLines.empty()
4082 ? UnwrappedLine::kInvalidIndex
4083 : CurrentLines->size() - 1;
4084 bool HasError = !parseBracedList(
false,
true);
4085 if (!Style.AllowShortEnumsOnASingleLine && !ManageWhitesmithsBraces)
4088 if (FormatTok->is(tok::semi))
4092 setPreviousRBraceType(TT_EnumRBrace);
4093 if (ManageWhitesmithsBraces && CurrentExpandedLines.empty() &&
4094 !containsExpansion(*
Line)) {
4095 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
4104bool UnwrappedLineParser::parseStructLike() {
4109 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp()) {
4110 if (FormatTok->is(tok::semi))
4121class ScopedTokenPosition {
4122 unsigned StoredPosition;
4123 FormatTokenSource *Tokens;
4126 ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) {
4127 assert(Tokens &&
"Tokens expected to not be null");
4128 StoredPosition = Tokens->getPosition();
4131 ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); }
4137bool UnwrappedLineParser::tryToParseSimpleAttribute() {
4138 ScopedTokenPosition AutoPosition(Tokens);
4146 if (
Tok->
is(tok::r_square))
4148 Tok = Tokens->getNextToken();
4150 if (
Tok->
is(tok::eof))
4152 Tok = Tokens->getNextToken();
4155 Tok = Tokens->getNextToken();
4156 if (
Tok->
is(tok::semi))
4161void UnwrappedLineParser::parseJavaEnumBody() {
4162 assert(FormatTok->is(tok::l_brace));
4168 unsigned StoredPosition = Tokens->getPosition();
4169 bool IsSimple =
true;
4172 if (
Tok->
is(tok::r_brace))
4180 Tok = Tokens->getNextToken();
4182 FormatTok = Tokens->setPosition(StoredPosition);
4199 if (FormatTok->is(tok::l_brace)) {
4201 parseBlock(
true, 1u,
4203 }
else if (FormatTok->is(tok::l_paren)) {
4205 }
else if (FormatTok->is(tok::comma)) {
4208 }
else if (FormatTok->is(tok::semi)) {
4212 }
else if (FormatTok->is(tok::r_brace)) {
4221 parseLevel(OpeningBrace);
4227void UnwrappedLineParser::parseRecord(
bool ParseAsExpr,
bool IsJavaRecord) {
4228 assert(!IsJavaRecord || FormatTok->is(Keywords.kw_record));
4233 IsJavaRecord && FormatTok->is(tok::identifier) ? FormatTok :
nullptr;
4234 bool IsDerived =
false;
4236 return Tok->
is(tok::identifier) &&
Tok->TokenText !=
Tok->TokenText.upper();
4240 bool JSPastExtendsOrImplements =
false;
4244 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
4245 tok::kw_alignas, tok::l_square) ||
4246 FormatTok->isAttribute() ||
4247 ((Style.isJava() || Style.isJavaScript()) &&
4248 FormatTok->isOneOf(tok::period, tok::comma)) ||
4249 (Style.isVerilog() &&
4250 FormatTok->isOneOf(tok::kw_signed, tok::kw_unsigned))) {
4251 if (Style.isJavaScript() &&
4252 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
4253 JSPastExtendsOrImplements =
true;
4258 if (FormatTok->is(tok::l_brace)) {
4259 tryToParseBracedList();
4263 if (FormatTok->is(tok::l_square) && handleCppAttributes())
4267 switch (FormatTok->Tok.getKind()) {
4270 if (IsJavaRecord || !IsNonMacroIdentifier(
Previous) ||
4272 Previous->Previous == &InitialToken) {
4276 case tok::coloncolon:
4280 if (JSPastExtendsOrImplements || ClassName ||
4291 auto IsListInitialization = [&] {
4292 if (!ClassName || IsDerived || JSPastExtendsOrImplements)
4294 assert(FormatTok->is(tok::l_brace));
4295 const auto *Prev = FormatTok->getPreviousNonComment();
4297 return Prev != ClassName && Prev->is(tok::identifier) &&
4298 Prev->isNot(Keywords.kw_final) && tryToParseBracedList();
4301 if (FormatTok->isOneOf(tok::colon, tok::less)) {
4302 int AngleNestingLevel = 0;
4304 if (FormatTok->is(tok::less))
4305 ++AngleNestingLevel;
4306 else if (FormatTok->is(tok::greater))
4307 --AngleNestingLevel;
4309 if (AngleNestingLevel == 0) {
4310 if (FormatTok->is(tok::colon)) {
4312 }
else if (!IsDerived && FormatTok->is(tok::identifier) &&
4313 FormatTok->Previous->is(tok::coloncolon)) {
4314 ClassName = FormatTok;
4315 }
else if (FormatTok->is(tok::l_paren) &&
4316 IsNonMacroIdentifier(FormatTok->Previous)) {
4320 if (FormatTok->is(tok::l_brace)) {
4321 if (AngleNestingLevel == 0 && IsListInitialization())
4323 calculateBraceTypes(
true);
4324 if (!tryToParseBracedList())
4327 if (FormatTok->is(tok::l_square)) {
4330 !
Previous->isTypeOrIdentifier(LangOpts))) {
4333 if (!tryToParseLambda())
4340 if (FormatTok->is(tok::semi))
4342 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
4345 parseCSharpGenericTypeConstraint();
4352 auto GetBraceTypes =
4353 [](
const FormatToken &RecordTok) -> std::pair<TokenType, TokenType> {
4354 switch (RecordTok.Tok.getKind()) {
4356 return {TT_ClassLBrace, TT_ClassRBrace};
4357 case tok::kw_struct:
4358 return {TT_StructLBrace, TT_StructRBrace};
4360 return {TT_UnionLBrace, TT_UnionRBrace};
4363 return {TT_RecordLBrace, TT_RecordRBrace};
4366 if (FormatTok->is(tok::l_brace)) {
4367 if (IsListInitialization())
4370 ClassName->setFinalizedType(TT_ClassHeadName);
4371 auto [OpenBraceType, ClosingBraceType] = GetBraceTypes(InitialToken);
4372 FormatTok->setFinalizedType(OpenBraceType);
4377 Tokens->peekNextToken()->is(tok::r_brace),
4382 bool IndentAfterExplicitAccessModifier =
false;
4383 unsigned AddLevels = 1u;
4384 switch (Style.IndentAccessModifiers) {
4388 if (Style.isCpp()) {
4389 IndentAfterExplicitAccessModifier =
true;
4398 parseBlock(
true, AddLevels,
false,
4401 IndentAfterExplicitAccessModifier);
4403 setPreviousRBraceType(ClosingBraceType);
4410void UnwrappedLineParser::parseObjCMethod() {
4411 assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) &&
4412 "'(' or identifier expected.");
4414 if (FormatTok->is(tok::semi)) {
4418 }
else if (FormatTok->is(tok::l_brace)) {
4419 if (Style.BraceWrapping.AfterFunction)
4430void UnwrappedLineParser::parseObjCProtocolList() {
4431 assert(FormatTok->is(tok::less) &&
"'<' expected.");
4435 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4437 }
while (!
eof() && FormatTok->isNot(tok::greater));
4441void UnwrappedLineParser::parseObjCUntilAtEnd() {
4443 if (FormatTok->is(tok::objc_end)) {
4448 if (FormatTok->is(tok::l_brace)) {
4452 }
else if (FormatTok->is(tok::r_brace)) {
4456 }
else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
4458 if (FormatTok->isOneOf(tok::l_paren, tok::identifier))
4461 parseStructuralElement();
4466void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
4467 assert(FormatTok->isOneOf(tok::objc_interface, tok::objc_implementation));
4473 if (FormatTok->is(tok::less))
4474 parseObjCLightweightGenerics();
4475 if (FormatTok->is(tok::colon)) {
4479 if (FormatTok->is(tok::less))
4480 parseObjCLightweightGenerics();
4481 }
else if (FormatTok->is(tok::l_paren)) {
4486 if (FormatTok->is(tok::less))
4487 parseObjCProtocolList();
4489 if (FormatTok->is(tok::l_brace)) {
4490 if (Style.BraceWrapping.AfterObjCDeclaration)
4499 parseObjCUntilAtEnd();
4502void UnwrappedLineParser::parseObjCLightweightGenerics() {
4503 assert(FormatTok->is(tok::less));
4511 unsigned NumOpenAngles = 1;
4515 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4517 if (FormatTok->is(tok::less)) {
4519 }
else if (FormatTok->is(tok::greater)) {
4520 assert(NumOpenAngles > 0 &&
"'>' makes NumOpenAngles negative");
4523 }
while (!
eof() && NumOpenAngles != 0);
4529bool UnwrappedLineParser::parseObjCProtocol() {
4530 assert(FormatTok->is(tok::objc_protocol));
4533 if (FormatTok->is(tok::l_paren)) {
4545 if (FormatTok->is(tok::less))
4546 parseObjCProtocolList();
4549 if (FormatTok->is(tok::semi)) {
4556 parseObjCUntilAtEnd();
4560void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
4561 bool IsImport = FormatTok->is(Keywords.kw_import);
4562 assert(IsImport || FormatTok->is(tok::kw_export));
4566 if (FormatTok->is(tok::kw_default))
4572 if (FormatTok->is(Keywords.kw_async))
4574 if (FormatTok->is(Keywords.kw_function)) {
4583 if (!IsImport && FormatTok->isNoneOf(tok::l_brace, tok::star) &&
4584 !FormatTok->isStringLiteral() &&
4585 !(FormatTok->is(Keywords.kw_type) &&
4586 Tokens->peekNextToken()->isOneOf(tok::l_brace, tok::star))) {
4591 if (FormatTok->is(tok::semi))
4593 if (
Line->Tokens.empty()) {
4598 if (FormatTok->is(tok::l_brace)) {
4599 FormatTok->setBlockKind(BK_Block);
4608void UnwrappedLineParser::parseStatementMacro() {
4610 if (FormatTok->is(tok::l_paren))
4612 if (FormatTok->is(tok::semi))
4617void UnwrappedLineParser::parseVerilogHierarchyIdentifier() {
4620 if (FormatTok->isOneOf(tok::star, tok::period, tok::periodstar,
4621 tok::coloncolon, tok::hash) ||
4622 Keywords.isVerilogIdentifier(*FormatTok)) {
4624 }
else if (FormatTok->is(tok::l_square)) {
4632void UnwrappedLineParser::parseVerilogSensitivityList() {
4633 if (FormatTok->isNot(tok::at))
4637 if (FormatTok->is(tok::at))
4639 switch (FormatTok->Tok.getKind()) {
4647 parseVerilogHierarchyIdentifier();
4652unsigned UnwrappedLineParser::parseVerilogHierarchyHeader() {
4653 unsigned AddLevels = 0;
4655 if (FormatTok->is(Keywords.kw_clocking)) {
4657 if (Keywords.isVerilogIdentifier(*FormatTok))
4659 parseVerilogSensitivityList();
4660 if (FormatTok->is(tok::semi))
4662 }
else if (FormatTok->isOneOf(tok::kw_case, Keywords.kw_casex,
4663 Keywords.kw_casez, Keywords.kw_randcase,
4664 Keywords.kw_randsequence)) {
4665 if (Style.IndentCaseLabels)
4668 if (FormatTok->is(tok::l_paren)) {
4669 FormatTok->setFinalizedType(TT_ConditionLParen);
4672 if (FormatTok->isOneOf(Keywords.kw_inside, Keywords.kw_matches))
4681 if (FormatTok->is(tok::l_square)) {
4682 auto Prev = FormatTok->getPreviousNonComment();
4683 if (Prev && Keywords.isVerilogIdentifier(*Prev))
4684 Prev->setFinalizedType(TT_VerilogDimensionedTypeName);
4686 }
else if (Keywords.isVerilogIdentifier(*FormatTok) ||
4687 FormatTok->isOneOf(tok::hash, tok::hashhash, tok::coloncolon,
4688 Keywords.kw_automatic, tok::kw_static)) {
4695 auto NewLine = [
this]() {
4697 Line->IsContinuation =
true;
4701 while (FormatTok->is(Keywords.kw_import)) {
4704 parseVerilogHierarchyIdentifier();
4705 if (FormatTok->is(tok::semi))
4710 if (FormatTok->is(Keywords.kw_verilogHash)) {
4713 if (FormatTok->is(tok::l_paren)) {
4714 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4718 if (FormatTok->is(tok::l_paren)) {
4720 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4725 if (FormatTok->is(Keywords.kw_extends)) {
4728 parseVerilogHierarchyIdentifier();
4729 if (FormatTok->is(tok::l_paren))
4732 if (FormatTok->is(Keywords.kw_implements)) {
4736 parseVerilogHierarchyIdentifier();
4737 }
while (FormatTok->is(tok::comma));
4741 if (FormatTok->is(tok::at)) {
4743 parseVerilogSensitivityList();
4746 if (FormatTok->is(tok::semi))
4754void UnwrappedLineParser::parseVerilogTable() {
4755 assert(FormatTok->is(Keywords.kw_table));
4759 auto InitialLevel =
Line->Level++;
4760 while (!
eof() && !Keywords.isVerilogEnd(*FormatTok)) {
4763 if (
Tok->
is(tok::semi))
4765 else if (
Tok->
isOneOf(tok::star, tok::colon, tok::question, tok::minus))
4766 Tok->setFinalizedType(TT_VerilogTableItem);
4768 Line->Level = InitialLevel;
4773void UnwrappedLineParser::parseVerilogCaseLabel() {
4779 auto OrigLevel =
Line->Level;
4780 auto FirstLine = CurrentLines->size();
4781 if (
Line->Level == 0 || (
Line->InPPDirective &&
Line->Level <= 1))
4783 else if (!Style.IndentCaseBlocks && Keywords.isVerilogBegin(*FormatTok))
4785 parseStructuralElement();
4788 if (CurrentLines->size() > FirstLine)
4789 (*CurrentLines)[FirstLine].Level = OrigLevel;
4790 Line->Level = OrigLevel;
4793void UnwrappedLineParser::parseVerilogExtern() {
4795 FormatTok->isOneOf(tok::kw_extern, tok::kw_export, Keywords.kw_import));
4798 if (FormatTok->is(tok::string_literal))
4800 skipVerilogQualifiers();
4801 if (Keywords.isVerilogIdentifier(*FormatTok))
4803 if (FormatTok->is(tok::equal))
4805 if (Keywords.isVerilogHierarchy(*FormatTok))
4806 parseVerilogHierarchyHeader();
4809void UnwrappedLineParser::skipVerilogQualifiers() {
4810 while (FormatTok->isOneOf(tok::kw_protected, tok::kw_virtual, tok::kw_static,
4811 Keywords.kw_rand, Keywords.kw_context,
4812 Keywords.kw_pure, Keywords.kw_randc,
4813 Keywords.kw_local)) {
4818bool UnwrappedLineParser::containsExpansion(
const UnwrappedLine &
Line)
const {
4819 for (
const auto &N :
Line.Tokens) {
4820 if (N.Tok->MacroCtx)
4822 for (
const UnwrappedLine &Child : N.Children)
4823 if (containsExpansion(Child))
4829void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) {
4830 if (
Line->Tokens.empty())
4833 if (!parsingPPDirective()) {
4834 llvm::dbgs() <<
"Adding unwrapped line:\n";
4835 printDebugInfo(*
Line);
4843 bool ClosesWhitesmithsBlock =
4844 Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex &&
4850 if (!parsingPPDirective() && !InExpansion && containsExpansion(*
Line)) {
4852 Reconstruct.emplace(
Line->Level, Unexpanded);
4853 Reconstruct->addLine(*
Line);
4858 CurrentExpandedLines.push_back(std::move(*
Line));
4860 if (Reconstruct->finished()) {
4861 UnwrappedLine Reconstructed = std::move(*Reconstruct).takeResult();
4862 assert(!Reconstructed.Tokens.empty() &&
4863 "Reconstructed must at least contain the macro identifier.");
4864 assert(!parsingPPDirective());
4866 llvm::dbgs() <<
"Adding unexpanded line:\n";
4867 printDebugInfo(Reconstructed);
4869 ExpandedLines[Reconstructed.Tokens.begin()->Tok] = CurrentExpandedLines;
4870 Lines.push_back(std::move(Reconstructed));
4871 CurrentExpandedLines.clear();
4872 Reconstruct.reset();
4877 assert(!Reconstruct || (CurrentLines != &Lines) || !PP.Stack.empty());
4878 CurrentLines->push_back(std::move(*
Line));
4880 Line->Tokens.clear();
4881 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
4882 Line->FirstStartColumn = 0;
4883 Line->IsContinuation =
false;
4884 Line->SeenDecltypeAuto =
false;
4885 Line->IsModuleOrImportDecl =
false;
4887 if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove)
4889 if (!parsingPPDirective() && !PreprocessorDirectives.empty()) {
4890 CurrentLines->append(
4891 std::make_move_iterator(PreprocessorDirectives.begin()),
4892 std::make_move_iterator(PreprocessorDirectives.end()));
4893 PreprocessorDirectives.clear();
4896 FormatTok->Previous =
nullptr;
4899bool UnwrappedLineParser::eof()
const {
return FormatTok->is(tok::eof); }
4901bool UnwrappedLineParser::isOnNewLine(
const FormatToken &FormatTok) {
4902 return (
Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
4903 FormatTok.NewlinesBefore > 0;
4911 const llvm::Regex &CommentPragmasRegex) {
4915 StringRef IndentContent = FormatTok.
TokenText;
4916 if (FormatTok.
TokenText.starts_with(
"//") ||
4917 FormatTok.
TokenText.starts_with(
"/*")) {
4918 IndentContent = FormatTok.
TokenText.substr(2);
4920 if (CommentPragmasRegex.match(IndentContent))
4995 if (PreviousToken && PreviousToken->
is(tok::l_brace) &&
4997 MinColumnToken = PreviousToken;
5000 PreviousToken = Node.
Tok;
5004 MinColumnToken = Node.
Tok;
5006 if (PreviousToken && PreviousToken->
is(tok::l_brace))
5007 MinColumnToken = PreviousToken;
5013void UnwrappedLineParser::flushComments(
bool NewlineBeforeNext) {
5014 bool JustComments =
Line->Tokens.empty();
5024 Tok->ContinuesLineCommentSection =
5025 continuesLineCommentSection(*
Tok, *
Line, Style, CommentPragmasRegex);
5026 if (isOnNewLine(*
Tok) && JustComments && !
Tok->ContinuesLineCommentSection)
5030 if (NewlineBeforeNext && JustComments)
5032 CommentsBeforeNextToken.clear();
5035void UnwrappedLineParser::nextToken(
int LevelDifference) {
5038 flushComments(isOnNewLine(*FormatTok));
5039 pushToken(FormatTok);
5041 if (!Style.isJavaScript())
5042 readToken(LevelDifference);
5044 readTokenWithJavaScriptASI();
5046 if (Style.isVerilog()) {
5053 if (Keywords.isVerilogEnd(*FormatTok))
5054 FormatTok->Tok.setKind(tok::r_brace);
5058void UnwrappedLineParser::distributeComments(
5078 if (Comments.empty())
5080 bool ShouldPushCommentsInCurrentLine =
true;
5081 bool HasTrailAlignedWithNextToken =
false;
5082 unsigned StartOfTrailAlignedWithNextToken = 0;
5085 for (
unsigned i = Comments.size() - 1; i > 0; --i) {
5087 HasTrailAlignedWithNextToken =
true;
5088 StartOfTrailAlignedWithNextToken = i;
5092 for (
unsigned i = 0, e = Comments.size(); i < e; ++i) {
5094 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
5095 FormatTok->ContinuesLineCommentSection =
false;
5098 *FormatTok, *
Line, Style, CommentPragmasRegex);
5100 if (!FormatTok->ContinuesLineCommentSection &&
5101 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
5102 ShouldPushCommentsInCurrentLine =
false;
5104 if (ShouldPushCommentsInCurrentLine)
5105 pushToken(FormatTok);
5107 CommentsBeforeNextToken.push_back(FormatTok);
5111void UnwrappedLineParser::readToken(
int LevelDifference) {
5113 bool PreviousWasComment =
false;
5114 bool FirstNonCommentOnLine =
false;
5116 FormatTok = Tokens->getNextToken();
5118 while (FormatTok->isOneOf(TT_ConflictStart, TT_ConflictEnd,
5119 TT_ConflictAlternative)) {
5120 if (FormatTok->is(TT_ConflictStart))
5121 conditionalCompilationStart(
false);
5122 else if (FormatTok->is(TT_ConflictAlternative))
5123 conditionalCompilationAlternative();
5124 else if (FormatTok->is(TT_ConflictEnd))
5125 conditionalCompilationEnd();
5126 FormatTok = Tokens->getNextToken();
5127 FormatTok->MustBreakBefore =
true;
5128 FormatTok->MustBreakBeforeFinalized =
true;
5131 auto IsFirstNonCommentOnLine = [](
bool FirstNonCommentOnLine,
5133 bool PreviousWasComment) {
5135 return Tok.HasUnescapedNewline ||
Tok.IsFirst;
5140 if (PreviousWasComment)
5141 return FirstNonCommentOnLine || IsFirstOnLine(
Tok);
5142 return IsFirstOnLine(
Tok);
5145 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
5146 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
5147 PreviousWasComment = FormatTok->is(tok::comment);
5149 while (!
Line->InPPDirective && FormatTok->is(tok::hash) &&
5150 FirstNonCommentOnLine) {
5153 const auto *
Next = Tokens->peekNextToken();
5154 if ((Style.isVerilog() && !Keywords.isVerilogPPDirective(*
Next)) ||
5155 (Style.isTableGen() &&
5156 Next->isNoneOf(tok::kw_else, tok::pp_define, tok::pp_ifdef,
5157 tok::pp_ifndef, tok::pp_endif))) {
5160 distributeComments(Comments, FormatTok);
5165 const bool ParsedBefore = !ParsedPPDirectives.insert(FormatTok).second;
5168 bool SwitchToPreprocessorLines = !
Line->Tokens.empty();
5169 ScopedLineState BlockState(*
this, SwitchToPreprocessorLines,
5171 assert((LevelDifference >= 0 ||
5172 static_cast<unsigned>(-LevelDifference) <=
Line->Level) &&
5173 "LevelDifference makes Line->Level negative");
5174 Line->Level += LevelDifference;
5179 PP.BranchLevel > 0) {
5180 Line->Level += PP.BranchLevel;
5182 assert(
Line->Level >=
Line->UnbracedBodyLevel);
5183 Line->Level -=
Line->UnbracedBodyLevel;
5184 flushComments(isOnNewLine(*FormatTok));
5185 const bool IsEndIf = Tokens->peekNextToken()->is(tok::pp_endif);
5187 PreviousWasComment = FormatTok->is(tok::comment);
5188 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
5189 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
5192 if (IsEndIf && PP.IncludeGuard == IG_Defined && PP.BranchLevel == -1 &&
5193 getIncludeGuardState(Style.IndentPPDirectives) == IG_Inited &&
5195 (PreviousWasComment &&
5196 Tokens->peekNextToken(
true)->is(tok::eof)))) {
5197 PP.IncludeGuard = IG_Found;
5201 if (!PP.Stack.empty() && (PP.Stack.back().Kind == PP_Unreachable) &&
5202 !
Line->InPPDirective) {
5206 if (FormatTok->is(tok::identifier) &&
5207 Macros.defined(FormatTok->TokenText) &&
5209 !
Line->InPPDirective) {
5211 unsigned Position = Tokens->getPosition();
5216 const auto SavedPPState = PP;
5220 auto PreCall = std::move(
Line);
5221 Line.reset(
new UnwrappedLine);
5222 bool OldInExpansion = InExpansion;
5225 auto Args = parseMacroCall(SavedPPState);
5226 InExpansion = OldInExpansion;
5227 assert(
Line->Tokens.front().Tok == ID);
5229 auto UnexpandedLine = std::move(
Line);
5231 Line = std::move(PreCall);
5234 llvm::dbgs() <<
"Macro call: " <<
ID->TokenText <<
"(";
5236 llvm::dbgs() <<
"(";
5237 for (
const auto &Arg : Args.value())
5238 for (
const auto &
T : Arg)
5239 llvm::dbgs() <<
T->TokenText <<
" ";
5240 llvm::dbgs() <<
")";
5242 llvm::dbgs() <<
"\n";
5244 if (
Macros.objectLike(
ID->TokenText) && Args &&
5245 !
Macros.hasArity(
ID->TokenText, Args->size())) {
5251 LLVM_DEBUG(llvm::dbgs()
5252 <<
"Macro \"" <<
ID->TokenText
5253 <<
"\" not overloaded for arity " << Args->size()
5254 <<
"or not function-like, using object-like overload.");
5256 UnexpandedLine->Tokens.resize(1);
5257 Tokens->setPosition(Position);
5259 FormatTok = Tokens->getNextToken();
5261 assert(!Args &&
Macros.objectLike(
ID->TokenText));
5263 if ((!Args &&
Macros.objectLike(
ID->TokenText)) ||
5264 (Args &&
Macros.hasArity(
ID->TokenText, Args->size()))) {
5267 Unexpanded[
ID] = std::move(UnexpandedLine);
5269 Macros.expand(ID, std::move(Args));
5270 if (!Expansion.empty())
5271 FormatTok = Tokens->insertTokens(Expansion);
5274 llvm::dbgs() <<
"Expanded: ";
5275 for (
const auto &
T : Expansion)
5276 llvm::dbgs() <<
T->TokenText <<
" ";
5277 llvm::dbgs() <<
"\n";
5281 llvm::dbgs() <<
"Did not expand macro \"" <<
ID->TokenText
5282 <<
"\", because it was used ";
5284 llvm::dbgs() <<
"with " << Args->size();
5286 llvm::dbgs() <<
"without";
5287 llvm::dbgs() <<
" arguments, which doesn't match any definition.\n";
5289 Tokens->setPosition(Position);
5295 if (FormatTok->isNot(tok::comment)) {
5296 distributeComments(Comments, FormatTok);
5301 Comments.push_back(FormatTok);
5304 distributeComments(Comments,
nullptr);
5309template <
typename Iterator>
5310void pushTokens(Iterator Begin, Iterator End,
5312 for (
auto I = Begin; I != End; ++I) {
5313 Into.push_back(I->Tok);
5314 for (
const auto &Child : I->Children)
5315 pushTokens(Child.Tokens.begin(), Child.Tokens.end(), Into);
5320std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>
5321UnwrappedLineParser::parseMacroCall(
const PPState &SavedPPState) {
5322 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>> Args;
5323 assert(
Line->Tokens.empty());
5326 auto ConsumeLastTokenOfCall = [
this] {
5327 flushComments(isOnNewLine(*FormatTok));
5328 pushToken(FormatTok);
5329 FormatTok = Tokens->getNextToken();
5331 if (Tokens->peekNextToken(
true)->isNot(tok::l_paren)) {
5332 ConsumeLastTokenOfCall();
5336 assert(FormatTok->is(tok::l_paren));
5337 unsigned Position = Tokens->getPosition();
5341 auto ArgStart = std::prev(
Line->Tokens.end());
5345 switch (FormatTok->Tok.getKind()) {
5350 case tok::r_paren: {
5356 Args->push_back({});
5357 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5358 ConsumeLastTokenOfCall();
5366 Args->push_back({});
5367 pushTokens(std::next(ArgStart),
Line->Tokens.end(), Args->back());
5369 ArgStart = std::prev(
Line->Tokens.end());
5377 Line->Tokens.resize(1);
5378 Tokens->setPosition(Position);
5385 Line->Tokens.push_back(UnwrappedLineNode(
Tok));
5386 if (PP.AtEndOfPPLine) {
5387 auto &
Tok = *
Line->Tokens.back().Tok;
5388 Tok.MustBreakBefore =
true;
5389 Tok.MustBreakBeforeFinalized =
true;
5390 Tok.FirstAfterPPLine =
true;
5391 PP.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
@ Macros
Canonicalize -D and -U options.
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.
Top level wrappers for InstallAPI frontend operations.
bool isLineComment(const FormatToken &FormatTok)
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Default
Set to the current date and time.
const FunctionProtoType * T
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