https://github.com/backes updated https://github.com/llvm/llvm-project/pull/240902
>From 4d675b7b42bb5ea14e32e10f1db35eb6ee41c845 Mon Sep 17 00:00:00 2001 From: Clemens Backes <[email protected]> Date: Mon, 9 Nov 2026 17:06:02 +0000 Subject: [PATCH 1/2] [clang-format] Break and align items after trailing-comma __VA_OPT__ When `__VA_OPT__(..., )` (or `__VA_OPT__(,)`) ends with a top-level comma inside an enum, braced list, parameter list, or expression (for example when migrating unnamed variadic macros from the non-standard `, ##__VA_ARGS__` extension to C++20 `__VA_OPT__(__VA_ARGS__, )`), its closing `)` acts as an item separator. Previously, `clang-format` did not recognize the trailing comma inside `__VA_OPT__`, keeping the following item on the same line (or continuation-indenting it after `)`). Classify the closing `)` of a C/C++ `__VA_OPT__` ending in a top-level non-operator comma as `TT_TrailingCommaVaOptRParen` and treat it as a comma separator across token annotation, parameter counting and column layout, bin-packing, continuation indentation, trailing-comma handling, and expression grouping. Before: ```cpp #define DEFINE_PARAMETER_INDICES(...) \ enum ParameterIndices { \ kTarget = -1, \ __VA_OPT__(__VA_ARGS__, ) kNext, \ kParameterCount, \ }; ``` After: ```cpp #define DEFINE_PARAMETER_INDICES(...) \ enum ParameterIndices { \ kTarget = -1, \ __VA_OPT__(__VA_ARGS__, ) \ kNext, \ kParameterCount, \ }; ``` Assisted-by: Gemini --- clang/lib/Format/ContinuationIndenter.cpp | 34 ++-- clang/lib/Format/Format.cpp | 3 +- clang/lib/Format/FormatToken.cpp | 4 +- clang/lib/Format/FormatToken.h | 7 + clang/lib/Format/TokenAnnotator.cpp | 149 +++++++++++----- clang/lib/Format/UnwrappedLineParser.cpp | 14 +- clang/unittests/Format/FormatTest.cpp | 204 ++++++++++++++++++++++ 7 files changed, 353 insertions(+), 62 deletions(-) diff --git a/clang/lib/Format/ContinuationIndenter.cpp b/clang/lib/Format/ContinuationIndenter.cpp index 384bad64923150..cec5e693ff6e31 100644 --- a/clang/lib/Format/ContinuationIndenter.cpp +++ b/clang/lib/Format/ContinuationIndenter.cpp @@ -382,7 +382,8 @@ bool ContinuationIndenter::canBreak(const LineState &State) { if (!Current.MustBreakBefore && Previous.is(tok::l_brace) && Previous.isNot(TT_DictLiteral) && Previous.is(BK_BracedInit) && Previous.Previous && - Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma)) { + Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma, + TT_TrailingCommaVaOptRParen)) { return false; } // This prevents breaks like: @@ -608,7 +609,7 @@ bool ContinuationIndenter::mustBreak(const LineState &State) { if (Style.AlwaysBreakBeforeMultilineStrings && (NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth || - Previous.is(tok::comma) || Current.NestingLevel < 2) && + Previous.isCommaOrTrailingCommaVaOpt() || Current.NestingLevel < 2) && Previous.isNoneOf(tok::kw_return, tok::lessless, tok::at, Keywords.kw_dollar) && Previous.isNoneOf(TT_InlineASMColon, TT_ConditionalExpr) && @@ -1070,7 +1071,7 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun, // have the LHS 'left' of the RHS. const FormatToken *P = Current.getPreviousNonComment(); if (Current.isNot(tok::comment) && P && - (P->isOneOf(TT_BinaryOperator, tok::comma) || + (P->isOneOf(TT_BinaryOperator, tok::comma, TT_TrailingCommaVaOptRParen) || (P->is(TT_ConditionalExpr) && P->is(tok::colon))) && P->isNoneOf(TT_OverloadedOperator, TT_CtorInitializerComma) && P->getPrecedence() != prec::Assignment && @@ -1103,7 +1104,7 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun, CurrentState.LastSpace = State.Column; CurrentState.NestedBlockIndent = State.Column; } else if (Current.isNoneOf(tok::comment, tok::caret) && - ((Previous.is(tok::comma) && + ((Previous.isCommaOrTrailingCommaVaOpt() && Previous.isNot(TT_OverloadedOperator)) || (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) { CurrentState.LastSpace = State.Column; @@ -1273,7 +1274,8 @@ unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State, } if ((PreviousNonComment && - PreviousNonComment->isOneOf(tok::comma, tok::semi) && + PreviousNonComment->isOneOf(tok::comma, TT_TrailingCommaVaOptRParen, + tok::semi) && !CurrentState.AvoidBinPacking) || Previous.is(TT_BinaryOperator)) { CurrentState.BreakBeforeParameter = false; @@ -1392,7 +1394,8 @@ unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State, } if (PreviousNonComment && - PreviousNonComment->isNoneOf(tok::comma, tok::colon, tok::semi) && + PreviousNonComment->isNoneOf(tok::comma, TT_TrailingCommaVaOptRParen, + tok::colon, tok::semi) && ((PreviousNonComment->isNot(TT_TemplateCloser) && !PreviousNonComment->ClosesRequiresClause) || Current.NestingLevel != 0) && @@ -1667,7 +1670,7 @@ ContinuationIndenter::getNewLineColumn(const LineState &State) { } return CurrentState.QuestionColumn; } - if (Previous.is(tok::comma) && CurrentState.VariablePos != 0) + if (Previous.isCommaOrTrailingCommaVaOpt() && CurrentState.VariablePos != 0) return CurrentState.VariablePos; if (Current.is(TT_RequiresClause)) { if (Style.IndentRequiresClause) @@ -1778,7 +1781,8 @@ ContinuationIndenter::getNewLineColumn(const LineState &State) { return CurrentState.Indent; } if (Previous.is(tok::r_paren) && - Previous.isNot(TT_TableGenDAGArgOperatorToBreak) && + Previous.isNoneOf(TT_TableGenDAGArgOperatorToBreak, + TT_TrailingCommaVaOptRParen) && !Current.isBinaryOperator() && Current.isNoneOf(tok::colon, tok::comment)) { return ContinuationIndent; @@ -1936,10 +1940,12 @@ unsigned ContinuationIndenter::moveStateToNextToken(LineState &State, PState.NoLineBreak = true; State.Stack[State.Stack.size() - 2].NestedBlockInlined = false; } - if (Previous && (Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr) || - (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) && - Previous->isNoneOf(TT_DictLiteral, TT_ObjCMethodExpr, - TT_CtorInitializerColon)))) { + if (Previous && + (Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr) || + (Previous->isOneOf(tok::l_paren, tok::comma, TT_TrailingCommaVaOptRParen, + tok::colon) && + Previous->isNoneOf(TT_DictLiteral, TT_ObjCMethodExpr, + TT_CtorInitializerColon)))) { CurrentState.NestedBlockInlined = !Newline && hasNestedBlockInlined(Previous, Current, Style); } @@ -1952,6 +1958,8 @@ unsigned ContinuationIndenter::moveStateToNextToken(LineState &State, !State.Stack.back().NoLineBreakInOperand; moveStatePastScopeOpener(State, Newline); moveStatePastFakeRParens(State); + if (Current.is(TT_TrailingCommaVaOptRParen)) + State.Stack.back().NoLineBreakInOperand = false; if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0) State.StartOfStringLiteral = State.Column + 1; @@ -2151,7 +2159,7 @@ void ContinuationIndenter::moveStatePastScopeOpener(LineState &State, const auto *Prev = Tok->getPreviousNonComment(); if (!Prev) return false; - return Prev->is(tok::comma); + return Prev->isCommaOrTrailingCommaVaOpt(); }(Current.MatchingParen); IndentationAndAlignment NewIndent = 0; diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp index e21926cd367907..05e259efbaaa87 100644 --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -2911,7 +2911,8 @@ class EnumTrailingCommaEditor : public TokenAnalyzer { if (BeforeRBrace->is(tok::comma)) { if (Style.EnumTrailingComma == FormatStyle::ETC_Remove) replaceToken(*BeforeRBrace, BeforeRBrace->Next, SourceMgr, Result); - } else if (Style.EnumTrailingComma == FormatStyle::ETC_Insert) { + } else if (Style.EnumTrailingComma == FormatStyle::ETC_Insert && + BeforeRBrace->isNot(TT_TrailingCommaVaOptRParen)) { cantFail(Result.add(tooling::Replacement( SourceMgr, BeforeRBrace->Tok.getEndLoc(), 0, ","))); } diff --git a/clang/lib/Format/FormatToken.cpp b/clang/lib/Format/FormatToken.cpp index c6c051dbfdce29..f76a12c5c94210 100644 --- a/clang/lib/Format/FormatToken.cpp +++ b/clang/lib/Format/FormatToken.cpp @@ -357,7 +357,9 @@ bool startsNextParameter(const FormatToken &Current, const FormatStyle &Style) { return true; if (Current.is(TT_QtProperty)) return true; - return Previous.is(tok::comma) && !Current.isTrailingComment() && + return Previous.isCommaOrTrailingCommaVaOpt() && + Current.isNot(TT_TrailingCommaVaOptRParen) && + !Current.isTrailingComment() && ((Previous.isNot(TT_CtorInitializerComma) || Style.BreakConstructorInitializers != FormatStyle::BCIS_BeforeComma) && diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h index 35de3c5d07aca5..72f7db0c360c0e 100644 --- a/clang/lib/Format/FormatToken.h +++ b/clang/lib/Format/FormatToken.h @@ -198,6 +198,7 @@ namespace format { TYPE(TemplateOpener) \ TYPE(TemplateString) \ TYPE(TrailingAnnotation) \ + TYPE(TrailingCommaVaOptRParen) \ TYPE(TrailingReturnArrow) \ TYPE(TrailingUnaryOperator) \ TYPE(TypeDeclarationParen) \ @@ -679,6 +680,10 @@ struct FormatToken { return !isOneOf(Ks...); } + bool isCommaOrTrailingCommaVaOpt() const { + return isOneOf(tok::comma, TT_TrailingCommaVaOptRParen); + } + bool isIf(bool AllowConstexprMacro = true) const { return is(tok::kw_if) || endsSequence(tok::kw_constexpr, tok::kw_if) || (endsSequence(tok::identifier, tok::kw_if) && AllowConstexprMacro); @@ -1164,6 +1169,7 @@ struct AdditionalKeywords { kw___except = &IdentTable.get("__except"); kw___has_include = &IdentTable.get("__has_include"); kw___has_include_next = &IdentTable.get("__has_include_next"); + kw___va_opt__ = &IdentTable.get("__VA_OPT__"); kw_mark = &IdentTable.get("mark"); kw_region = &IdentTable.get("region"); @@ -1553,6 +1559,7 @@ struct AdditionalKeywords { IdentifierInfo *kw___except; IdentifierInfo *kw___has_include; IdentifierInfo *kw___has_include_next; + IdentifierInfo *kw___va_opt__; // JavaScript keywords. IdentifierInfo *kw_as; diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index 9bbce9552bb9de..7505d3194dbf9d 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -248,7 +248,7 @@ class AnnotatingParser { } if (Prev.isOneOf(tok::question, tok::colon) && !Style.isProto()) SeenTernaryOperator = true; - updateParameterCount(Left, CurrentToken); + FormatToken *Tok = CurrentToken; if (Style.Language == FormatStyle::LK_Proto) { if (FormatToken *Previous = CurrentToken->getPreviousNonComment()) { if (CurrentToken->is(tok::colon) || @@ -258,6 +258,7 @@ class AnnotatingParser { } } } else if (Style.isTableGen()) { + updateParameterCount(Left, Tok); if (CurrentToken->isOneOf(tok::comma, tok::equal)) { // They appear as separators. Unless they are not in class definition. next(); @@ -271,6 +272,7 @@ class AnnotatingParser { } if (!consumeToken()) return false; + updateParameterCount(Left, Tok); } return false; } @@ -547,11 +549,6 @@ class AnnotatingParser { if (CurrentToken->is(tok::l_brace) && OpeningParen.is(TT_ObjCBlockLParen)) OpeningParen.setType(TT_Unknown); - if (CurrentToken->is(tok::comma) && CurrentToken->Next && - !CurrentToken->Next->HasUnescapedNewline && - !CurrentToken->Next->isTrailingComment()) { - HasMultipleParametersOnALine = true; - } bool ProbablyFunctionTypeLParen = (CurrentToken->is(tok::l_paren) && CurrentToken->Next && CurrentToken->Next->isOneOf(tok::star, tok::amp, tok::caret)); @@ -581,14 +578,6 @@ class AnnotatingParser { PossibleObjCForInToken = CurrentToken; PossibleObjCForInToken->setType(TT_ObjCForIn); } - // When we discover a 'new', we set CanBeExpression to 'false' in order to - // parse the type correctly. Reset that after a comma. - if (CurrentToken->is(tok::comma)) { - if (IsStaticAssert) - Contexts.back().InStaticAssertFirstArgument = false; - else - Contexts.back().CanBeExpression = true; - } if (Style.isTableGen()) { if (CurrentToken->is(tok::comma)) { @@ -610,6 +599,20 @@ class AnnotatingParser { if (!consumeToken()) return false; updateParameterCount(&OpeningParen, Tok); + // When we discover a 'new', we set CanBeExpression to 'false' in order to + // parse the type correctly. Reset that after a comma. + if (Tok->is(tok::comma) || + (Tok->MatchingParen && + Tok->MatchingParen->is(TT_TrailingCommaVaOptRParen))) { + if (IsStaticAssert) + Contexts.back().InStaticAssertFirstArgument = false; + else + Contexts.back().CanBeExpression = true; + if (CurrentToken && !CurrentToken->HasUnescapedNewline && + !CurrentToken->isTrailingComment()) { + HasMultipleParametersOnALine = true; + } + } if (CurrentToken && CurrentToken->HasUnescapedNewline) HasMultipleLines = true; } @@ -706,7 +709,7 @@ class AnnotatingParser { // Do not consider '[' after a comma inside a braced initializer the // start of an ObjC method expression. In braced initializer lists, // commas are list separators and should not trigger ObjC parsing. - (!Parent || !Parent->is(tok::comma) || + (!Parent || !Parent->isCommaOrTrailingCommaVaOpt() || Contexts.back().ContextKind != tok::l_brace) && (!Parent || Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren, @@ -737,7 +740,9 @@ class AnnotatingParser { Parent->isOneOf(tok::l_brace, tok::comma)) { Left->setType(TT_JsComputedPropertyName); } else if (IsCpp && Contexts.back().ContextKind == tok::l_brace && - Parent && Parent->isOneOf(tok::l_brace, tok::comma)) { + Parent && + Parent->isOneOf(tok::l_brace, tok::comma, + TT_TrailingCommaVaOptRParen)) { Left->setType(TT_DesignatedInitializerLSquare); } else if (IsCSharpAttributeSpecifier) { Left->setType(TT_AttributeLSquare); @@ -782,8 +787,9 @@ class AnnotatingParser { } } else if (!CppArrayTemplates && Parent && Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at, - tok::comma, tok::l_paren, tok::l_square, - tok::question, tok::colon, tok::kw_return, + tok::comma, TT_TrailingCommaVaOptRParen, + tok::l_paren, tok::l_square, tok::question, + tok::colon, tok::kw_return, // Should only be relevant to JavaScript: tok::kw_default)) { Left->setType(TT_ArrayInitializerLSquare); @@ -1220,7 +1226,6 @@ class AnnotatingParser { } if (CurrentToken->isOneOf(tok::r_paren, tok::r_square)) return false; - updateParameterCount(&OpeningBrace, CurrentToken); if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) { FormatToken *Previous = CurrentToken->getPreviousNonComment(); if (Previous->is(TT_JsTypeOptionalQuestion)) @@ -1244,20 +1249,21 @@ class AnnotatingParser { Scopes.back() = getScopeType(OpeningBrace); } } - bool IsBracedListComma = false; - if (CurrentToken->is(tok::comma)) { + FormatToken *Tok = CurrentToken; + if (!consumeToken()) + return false; + updateParameterCount(&OpeningBrace, Tok); + if (Tok->is(tok::comma) || + (Tok->MatchingParen && + Tok->MatchingParen->is(TT_TrailingCommaVaOptRParen))) { if (Style.isJavaScript()) { OpeningBrace.overwriteFixedType(TT_DictLiteral); Scopes.back() = getScopeType(OpeningBrace); - } else { - IsBracedListComma = OpeningBrace.is(BK_BracedInit); + } else if (OpeningBrace.is(BK_BracedInit)) { + Contexts.back().IsExpression = true; } ++CommaCount; } - if (!consumeToken()) - return false; - if (IsBracedListComma) - Contexts.back().IsExpression = true; } return true; } @@ -1268,11 +1274,17 @@ class AnnotatingParser { // inside a bracket scope). if (Current->is(tok::l_brace) && Current->is(BK_Block)) ++Left->BlockParameterCount; - if (Current->is(tok::comma)) { + FormatToken *Comma = + Current->is(tok::comma) ? Current + : (Current->is(tok::l_paren) && Current->MatchingParen && + Current->MatchingParen->is(TT_TrailingCommaVaOptRParen)) + ? Current->MatchingParen + : nullptr; + if (Comma) { ++Left->ParameterCount; if (!Left->Role) Left->Role.reset(new CommaSeparatedList(Style)); - Left->Role->CommaFound(Current); + Left->Role->CommaFound(Comma); } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) { Left->ParameterCount = 1; } @@ -1574,6 +1586,20 @@ class AnnotatingParser { if (!parseParens()) return false; + if (Tok->MatchingParen && + Tok->MatchingParen->is(TT_TrailingCommaVaOptRParen)) { + if (Line.MustBeDeclaration && + Contexts.front().ContextType != Context::CtorInitializer) { + Contexts.back().IsExpression = false; + } + if (Contexts.back().FirstStartOfName && + (Contexts.size() == 1 || startsWithInitStatement(Line))) { + Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true; + Line.IsMultiVariableDeclStmt = true; + } + if (Contexts.back().ContextType == Context::ForEachMacro) + Contexts.back().IsExpression = true; + } if (Line.MustBeDeclaration && Contexts.size() == 1 && !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) && !Line.startsWith(tok::l_paren) && @@ -1581,7 +1607,7 @@ class AnnotatingParser { if (!Prev || (!Prev->isAttribute() && Prev->isNoneOf(TT_RequiresClause, TT_LeadingJavaAnnotation, - TT_BinaryOperator))) { + TT_BinaryOperator, Keywords.kw___va_opt__))) { Line.MightBeFunctionDecl = true; Tok->MightBeFunctionDeclParen = true; } @@ -2286,9 +2312,12 @@ class AnnotatingParser { if (!Line.startsWith(TT_UnaryOperator)) { for (FormatToken *Previous = Current.Previous; Previous && Previous->Previous && - Previous->Previous->isNoneOf(tok::comma, tok::semi); + !Previous->Previous->isCommaOrTrailingCommaVaOpt() && + Previous->Previous->isNot(tok::semi); Previous = Previous->Previous) { if (Previous->isOneOf(tok::r_square, tok::r_paren, tok::greater)) { + if (Previous->is(TT_TrailingCommaVaOptRParen)) + break; Previous = Previous->MatchingParen; if (!Previous) break; @@ -2573,7 +2602,8 @@ class AnnotatingParser { } else if (Current.is(tok::period)) { FormatToken *PreviousNoComment = Current.getPreviousNonComment(); if (PreviousNoComment && - PreviousNoComment->isOneOf(tok::comma, tok::l_brace)) { + PreviousNoComment->isOneOf(tok::comma, TT_TrailingCommaVaOptRParen, + tok::l_brace)) { Current.setType(TT_DesignatedInitializerPeriod); } else if (Style.isJava() && Current.Previous && Current.Previous->isOneOf(TT_JavaAnnotation, @@ -2998,11 +3028,12 @@ class AnnotatingParser { // // @ - It may be followed by a unary `-` in Objective-C literals. We don't // know how they can be followed by a star or amp. - if (PrevToken->isOneOf( - TT_ConditionalExpr, tok::l_paren, tok::comma, tok::colon, tok::semi, - tok::equal, tok::question, tok::l_square, tok::l_brace, - tok::kw_case, tok::kw_co_await, tok::kw_co_return, tok::kw_co_yield, - tok::kw_delete, tok::kw_return, tok::kw_throw)) { + if (PrevToken->isOneOf(TT_ConditionalExpr, TT_TrailingCommaVaOptRParen, + tok::l_paren, tok::comma, tok::colon, tok::semi, + tok::equal, tok::question, tok::l_square, + tok::l_brace, tok::kw_case, tok::kw_co_await, + tok::kw_co_return, tok::kw_co_yield, tok::kw_delete, + tok::kw_return, tok::kw_throw)) { return true; } @@ -3202,8 +3233,10 @@ class AnnotatingParser { /// Determine whether ++/-- are pre- or post-increments/-decrements. TokenType determineIncrementUsage(const FormatToken &Tok) { const FormatToken *PrevToken = Tok.getPreviousNonComment(); - if (!PrevToken || PrevToken->is(TT_CastRParen)) + if (!PrevToken || + PrevToken->isOneOf(TT_CastRParen, TT_TrailingCommaVaOptRParen)) { return TT_UnaryOperator; + } if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier)) return TT_TrailingUnaryOperator; @@ -3289,6 +3322,18 @@ class ExpressionParser { // Consume operators with higher precedence. parse(Precedence + 1); + if (TrailingCommaRParen) { + if (Precedence > prec::Comma) + break; + if (LatestOperator) + LatestOperator->NextOperator = TrailingCommaRParen; + LatestOperator = TrailingCommaRParen; + TrailingCommaRParen->OperatorIndex = OperatorIndex; + ++OperatorIndex; + TrailingCommaRParen = nullptr; + continue; + } + int CurrentPrecedence = getCurrentPrecedence(); if (CurrentPrecedence > prec::Conditional && CurrentPrecedence < prec::PointerToMember) { @@ -3347,7 +3392,11 @@ class ExpressionParser { next(); parse(); } + if (Current && Current->is(TT_TrailingCommaVaOptRParen)) + TrailingCommaRParen = Current; next(); + if (TrailingCommaRParen) + break; } else { // Operator found. if (CurrentPrecedence == Precedence) { @@ -3484,11 +3533,11 @@ class ExpressionParser { next(); FormatToken *Start = Current; parse(prec::LogicalOr); - if (!Current || Current->isNot(tok::question)) + if (TrailingCommaRParen || !Current || Current->isNot(tok::question)) return; next(); parse(prec::Assignment); - if (!Current || Current->isNot(TT_ConditionalExpr)) + if (TrailingCommaRParen || !Current || Current->isNot(TT_ConditionalExpr)) return; next(); parse(prec::Assignment); @@ -3644,6 +3693,7 @@ class ExpressionParser { const AdditionalKeywords &Keywords; const AnnotatedLine &Line; FormatToken *Current; + FormatToken *TrailingCommaRParen = nullptr; }; } // end anonymous namespace @@ -4290,7 +4340,8 @@ void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) const { Parameter = Parameter->Previous) { if (Parameter->isOneOf(tok::comment, tok::r_brace)) break; - if (Parameter->Previous && Parameter->Previous->is(tok::comma)) { + if (Parameter->Previous && + Parameter->Previous->isCommaOrTrailingCommaVaOpt()) { if (Parameter->Previous->isNot(TT_CtorInitializerComma) && Parameter->HasUnescapedNewline) { Parameter->MustBreakBefore = true; @@ -4665,7 +4716,7 @@ unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line, (Right.NextOperator || Right.OperatorIndex != 0)) { return 25; } - if (Left.is(tok::comma)) + if (Left.isCommaOrTrailingCommaVaOpt()) return 1; if (Right.is(tok::lessless) && Left.isLabelString() && (Right.NextOperator || Right.OperatorIndex != 1)) { @@ -5651,6 +5702,10 @@ bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, (Left.Children.empty() || !Left.MacroParent)) { return true; } + if (Left.is(TT_TrailingCommaVaOptRParen) && !Right.closesScope() && + Right.isNoneOf(tok::comma, tok::semi)) { + return true; + } if (Right.is(tok::comma)) return false; if (Right.is(TT_ObjCBlockLParen)) @@ -6041,8 +6096,9 @@ bool TokenAnnotator::mustBreakBefore(AnnotatedLine &Line, Right.MatchingParen->is(tok::l_paren)))) { BeforeClosingBrace = &Left; } - if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) || - BeforeClosingBrace->isTrailingComment())) { + if (BeforeClosingBrace && + (BeforeClosingBrace->isCommaOrTrailingCommaVaOpt() || + BeforeClosingBrace->isTrailingComment())) { return true; } } @@ -6749,8 +6805,9 @@ bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line, } } - return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace, - tok::kw_class, tok::kw_struct, tok::comment) || + return Left.isOneOf(tok::comma, TT_TrailingCommaVaOptRParen, tok::coloncolon, + tok::semi, tok::l_brace, tok::kw_class, tok::kw_struct, + tok::comment) || Right.isMemberAccess() || Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless, tok::colon, tok::l_square, tok::at) || diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index ae507a0e96a572..497aeb6e7af85b 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -2509,7 +2509,8 @@ bool UnwrappedLineParser::tryToParseLambdaIntroducer() { const auto *PrevPrev = Previous->getPreviousNonComment(); if (Previous->is(tok::star) && PrevPrev && PrevPrev->isTypeName(LangOpts)) return false; - if (Previous->closesScope()) { + if (Previous->closesScope() && + Previous->isNot(TT_TrailingCommaVaOptRParen)) { // Not a potential C-style cast. if (Previous->isNot(tok::r_paren)) return false; @@ -2651,6 +2652,11 @@ bool UnwrappedLineParser::parseBracedList(bool IsAngleBracket, bool IsEnum) { parseChildBlock(); break; } + if (IsEnum && !Style.AllowShortEnumsOnASingleLine && + FormatTok->Previous && + FormatTok->Previous->is(TT_TrailingCommaVaOptRParen)) { + addUnwrappedLine(); + } break; case tok::l_brace: // Assume there are no blocks inside a braced init list apart @@ -2732,6 +2738,9 @@ bool UnwrappedLineParser::parseParens(TokenType StarAndAmpTokenType, break; case tok::r_paren: { auto *RParen = FormatTok; + const bool EndsInComma = + RParen->Previous && RParen->Previous->is(tok::comma) && + !RParen->Previous->endsSequence(tok::comma, tok::kw_operator); nextToken(); if (Prev) { auto OptionalParens = [&] { @@ -2781,6 +2790,9 @@ bool UnwrappedLineParser::parseParens(TokenType StarAndAmpTokenType, } else if (Prev->is(TT_TypenameMacro)) { LParen->setFinalizedType(TT_TypeDeclarationParen); RParen->setFinalizedType(TT_TypeDeclarationParen); + } else if (Prev->is(Keywords.kw___va_opt__) && EndsInComma && + Style.isCpp()) { + RParen->setFinalizedType(TT_TrailingCommaVaOptRParen); } else if (Prev->is(tok::greater) && RParen->Previous == LParen) { Prev->setFinalizedType(TT_TemplateCloser); } else if (FormatTok->is(tok::l_brace) && Prev->is(tok::amp) && diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index da1587641311bc..8bb695d739c7a0 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -4266,6 +4266,210 @@ TEST_F(FormatTest, FormatsTypedefEnum) { Style); } +TEST_F(FormatTest, FormatsVaOptWithTrailingComma) { + verifyFormat("#define DEFINE_DESCRIPTOR(Name, ...) \\\n" + " enum ParameterIndices { \\\n" + " kJSTarget = -1, \\\n" + " __VA_OPT__(__VA_ARGS__, ) \\\n" + " kNewTarget, \\\n" + " kActualArgumentsCount, \\\n" + " kContext, \\\n" + " kParameterCount, \\\n" + " };", + getChromiumStyle(FormatStyle::LK_Cpp)); + + verifyFormat("enum E {\n" + " __VA_OPT__(__VA_ARGS__, )\n" + " kFirst = 1,\n" + " kSecond = 2,\n" + "};"); + + // Nested parentheses: only a top-level trailing comma inside __VA_OPT__ + // acts as an item separator. + verifyFormat("enum E {\n" + " __VA_OPT__(FOO(a, b), )\n" + " kFirst,\n" + " kSecond,\n" + "};"); + verifyFormat("enum E {\n" + " __VA_OPT__(FOO(a, )) kFirst,\n" + " kSecond,\n" + "};"); + + // Short single-line enums remain on one line when allowed. + verifyFormat("enum E { __VA_OPT__(__VA_ARGS__, ) kOnly };"); + FormatStyle NoShortEnums = getLLVMStyle(); + NoShortEnums.AllowShortEnumsOnASingleLine = false; + verifyFormat("enum E {\n" + " __VA_OPT__(__VA_ARGS__, )\n" + " kOnly\n" + "};", + NoShortEnums); + + // Trailing-comma __VA_OPT__ at the end of a braced list, enum, or call. + verifyFormat("enum E {\n" + " kFirst,\n" + " __VA_OPT__(__VA_ARGS__, )\n" + "};"); + verifyFormat("int x[] = {\n" + " 1,\n" + " __VA_OPT__(__VA_ARGS__, )\n" + " 2,\n" + "};"); + verifyFormat("void f(__VA_OPT__(__VA_ARGS__, )\n" + " int first_arg,\n" + " int second_arg);", + getLLVMStyleWithColumns(32)); + + // Leading-comma __VA_OPT__ stays attached to the preceding item, while + // lone-comma __VA_OPT__(,) acts as a conditional separator. + verifyFormat("enum E {\n" + " kFirst __VA_OPT__(, __VA_ARGS__),\n" + " kSecond,\n" + "};"); + verifyFormat("void f(int a __VA_OPT__(, __VA_ARGS__));"); + verifyFormat("enum E {\n" + " kFirst __VA_OPT__(, )\n" + " __VA_ARGS__\n" + "};", + "enum E { kFirst __VA_OPT__(,) __VA_ARGS__ };", NoShortEnums); + + // Unary operators, designated initializers, lambdas, parens, and braces + // immediately following __VA_OPT__(..., ). + verifyFormat("int x[] = {\n" + " __VA_OPT__(__VA_ARGS__, )\n" + " -1,\n" + " +2,\n" + "};"); + verifyFormat("void f() {\n" + " foo(__VA_OPT__(a, ) *b, &c, ++d);\n" + " auto l = [__VA_OPT__(a, ) &b, &c]() {};\n" + " foo(__VA_OPT__(a, ) [x]() { return x; });\n" + " foo(__VA_OPT__(a, ) (b + c), {1, 2});\n" + "}"); + verifyFormat("S s = {.a = 1, __VA_OPT__(.b = 2, ) .c = 3};"); + verifyFormat("S s = {\n" + " .a = 1,\n" + " __VA_OPT__(__VA_ARGS__, )\n" + " .b = 2,\n" + "};"); + verifyFormat("int a[] = {[0] = 1, __VA_OPT__([1] = 2, ) [2] = 3};"); + + // Bin-packing parameters and constructor initializers after wrapping at + // __VA_OPT__(..., ). + verifyFormat("void f(__VA_OPT__(int very_long_first_param_here, )\n" + " int a, int b, int c);", + getLLVMStyleWithColumns(55)); + verifyFormat("class C {\n" + " C()\n" + " : a_(0), __VA_OPT__(b_(1), )\n" + " c_(2), d_(3) {}\n" + "};", + getLLVMStyleWithColumns(40)); + + // Expressions, operand line-break tracking, consecutive __VA_OPT__, and + // conditional expressions. + verifyFormat("SomeFunction(x, a + b __VA_OPT__(, )\n" + " ccccccccccccccc + ddddddddddddddd, y);", + getLLVMStyleWithColumns(55)); + verifyFormat("SomeFunction(__VA_OPT__(a, )\n" + " bbbbbbbbbbbbbbb + ccccccccccccccc,\n" + " d);", + getLLVMStyleWithColumns(50)); + verifyFormat("foo(!__VA_OPT__(a, ) __VA_OPT__(b, ) c);"); + verifyFormat("int x = foo(cond ? a : __VA_OPT__(bbbbbbbbbbbb, )\n" + " cccccccccccc, dddddddddddd);", + getLLVMStyleWithColumns(50)); + verifyNoCrash("int x = foo(cond ? __VA_OPT__(a, ) b : c, d);"); + verifyNoCrash("int x = foo(cond ? __VA_OPT__(a, ) : b + c, d);"); + verifyNoCrash("int x = foo(__VA_OPT__(a, ) ? b : c + d, e);"); + + // Nested call indentation when AlignAfterOpenBracket is disabled. + FormatStyle DontAlign = getLLVMStyleWithColumns(50); + DontAlign.AlignAfterOpenBracket = false; + verifyFormat("void g() {\n" + " foo(__VA_OPT__(a, ) bar(bbbbbbbbbbbbbbbbbb,\n" + " cccccccccccccccccc));\n" + "}", + DontAlign); + + // Multi-column braced list layout and template parameter lists. + verifyFormat("int x[] = {__VA_OPT__(a, ) 1, 1000000000, 2000000000,\n" + " 3000000000, 4, 5000000000, 6000000000};"); + verifyFormat("template <__VA_OPT__(typename T, )\n" + " typename U, typename V>\n" + "struct S;", + getLLVMStyleWithColumns(42)); + + // Overloaded operator, inside __VA_OPT__ is not a trailing comma. + verifyFormat("#define CALL_COMMA(...) \\\n" + " foo(__VA_OPT__(x.operator, ) + \\\n" + " yyyyyyyyyyyyyyyyyyyy)", + getLLVMStyleWithColumns(40)); + + // EnumTrailingComma: Insert/Remove with trailing-comma __VA_OPT__. + FormatStyle InsertComma = NoShortEnums; + InsertComma.EnumTrailingComma = FormatStyle::ETC_Insert; + verifyFormat("enum E {\n" + " kFirst,\n" + " __VA_OPT__(__VA_ARGS__, )\n" + "};", + InsertComma); + FormatStyle RemoveComma = NoShortEnums; + RemoveComma.EnumTrailingComma = FormatStyle::ETC_Remove; + verifyFormat("enum E {\n" + " kFirst,\n" + " __VA_OPT__(__VA_ARGS__, )\n" + "};", + RemoveComma); + + // Parameter packing, function declaration heuristics, and Google-style + // left-aligned pointers / multi-variable declarations. + FormatStyle OnePerLine = getLLVMStyle(); + OnePerLine.PackParameters.BinPack = FormatStyle::BPPS_AlwaysOnePerLine; + verifyFormat("void f(__VA_OPT__(int a, )\n" + " int b,\n" + " int c);", + OnePerLine); + FormatStyle BreakDeclParams = getLLVMStyle(); + BreakDeclParams.BreakFunctionDeclarationParameters = true; + verifyFormat("int __VA_OPT__(a, ) b;", BreakDeclParams); + FormatStyle AutoBinPack = getLLVMStyleWithColumns(50); + AutoBinPack.ExperimentalAutoDetectBinPacking = true; + verifyNoChange("void f() {\n" + " foo(__VA_OPT__(aaaaaaaaaaaa, ) bbbbbbbbbbbb,\n" + " cccccccccccc);\n" + "}", + AutoBinPack); + verifyGoogleFormat("void g() { foo(__VA_OPT__(a, ) *x = 1); }"); + verifyGoogleFormat("int __VA_OPT__(a = 1, ) *b = nullptr;"); + verifyGoogleFormat("int a = 1 __VA_OPT__(, ) *const b = nullptr;"); + FormatStyle Google30 = getGoogleStyle(); + Google30.ColumnLimit = 30; + verifyFormat("int __VA_OPT__(aaaa = 1, )\n" + " *bbbb = nullptr;", + Google30); + verifyFormat("long int aa = 1 __VA_OPT__(, )\n" + " *bb = nullptr;", + Google30); + + // Comments inside and after __VA_OPT__, and non-C++ language guard. + verifyFormat("enum E {\n" + " __VA_OPT__(__VA_ARGS__, /*comment*/)\n" + " kFirst,\n" + "};"); + verifyNoChange("void f() {\n" + " SomeFunction(__VA_OPT__(a, )\n" + " b, // comment\n" + " c);\n" + "}"); + verifyFormat("enum E {\n" + " __VA_OPT__(a, ) kFirst,\n" + " kSecond,\n" + "}", + getLLVMStyle(FormatStyle::LK_Java)); +} + TEST_F(FormatTest, FormatsNSEnums) { verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }"); verifyGoogleFormat( >From 34d4290704ff2633ee1c0d7ed4f41fabd82dbd4b Mon Sep 17 00:00:00 2001 From: Clemens Backes <[email protected]> Date: Tue, 17 Nov 2026 13:10:01 +0000 Subject: [PATCH 2/2] Address review feedback - Drop FormatToken::isCommaOrTrailingCommaVaOpt() helper and inline isOneOf/isNoneOf. - Simplify EndsInComma check in UnwrappedLineParser::parseParens(). - Add TokenAnnotatorTest.VaOptWithTrailingComma. - Wrap C++ FormatTest cases in #define, trim redundant cases, and reduce comments. Assisted-by: Gemini --- clang/lib/Format/ContinuationIndenter.cpp | 11 +- clang/lib/Format/FormatToken.cpp | 2 +- clang/lib/Format/FormatToken.h | 4 - clang/lib/Format/TokenAnnotator.cpp | 13 +- clang/lib/Format/UnwrappedLineParser.cpp | 3 +- clang/unittests/Format/FormatTest.cpp | 301 ++++++++---------- clang/unittests/Format/TokenAnnotatorTest.cpp | 65 ++++ 7 files changed, 208 insertions(+), 191 deletions(-) diff --git a/clang/lib/Format/ContinuationIndenter.cpp b/clang/lib/Format/ContinuationIndenter.cpp index cec5e693ff6e31..97ae525c8369c5 100644 --- a/clang/lib/Format/ContinuationIndenter.cpp +++ b/clang/lib/Format/ContinuationIndenter.cpp @@ -609,7 +609,8 @@ bool ContinuationIndenter::mustBreak(const LineState &State) { if (Style.AlwaysBreakBeforeMultilineStrings && (NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth || - Previous.isCommaOrTrailingCommaVaOpt() || Current.NestingLevel < 2) && + Previous.isOneOf(tok::comma, TT_TrailingCommaVaOptRParen) || + Current.NestingLevel < 2) && Previous.isNoneOf(tok::kw_return, tok::lessless, tok::at, Keywords.kw_dollar) && Previous.isNoneOf(TT_InlineASMColon, TT_ConditionalExpr) && @@ -1104,7 +1105,7 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun, CurrentState.LastSpace = State.Column; CurrentState.NestedBlockIndent = State.Column; } else if (Current.isNoneOf(tok::comment, tok::caret) && - ((Previous.isCommaOrTrailingCommaVaOpt() && + ((Previous.isOneOf(tok::comma, TT_TrailingCommaVaOptRParen) && Previous.isNot(TT_OverloadedOperator)) || (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) { CurrentState.LastSpace = State.Column; @@ -1670,8 +1671,10 @@ ContinuationIndenter::getNewLineColumn(const LineState &State) { } return CurrentState.QuestionColumn; } - if (Previous.isCommaOrTrailingCommaVaOpt() && CurrentState.VariablePos != 0) + if (Previous.isOneOf(tok::comma, TT_TrailingCommaVaOptRParen) && + CurrentState.VariablePos != 0) { return CurrentState.VariablePos; + } if (Current.is(TT_RequiresClause)) { if (Style.IndentRequiresClause) return CurrentState.Indent + Style.IndentWidth; @@ -2159,7 +2162,7 @@ void ContinuationIndenter::moveStatePastScopeOpener(LineState &State, const auto *Prev = Tok->getPreviousNonComment(); if (!Prev) return false; - return Prev->isCommaOrTrailingCommaVaOpt(); + return Prev->isOneOf(tok::comma, TT_TrailingCommaVaOptRParen); }(Current.MatchingParen); IndentationAndAlignment NewIndent = 0; diff --git a/clang/lib/Format/FormatToken.cpp b/clang/lib/Format/FormatToken.cpp index f76a12c5c94210..bfcebdb458391b 100644 --- a/clang/lib/Format/FormatToken.cpp +++ b/clang/lib/Format/FormatToken.cpp @@ -357,7 +357,7 @@ bool startsNextParameter(const FormatToken &Current, const FormatStyle &Style) { return true; if (Current.is(TT_QtProperty)) return true; - return Previous.isCommaOrTrailingCommaVaOpt() && + return Previous.isOneOf(tok::comma, TT_TrailingCommaVaOptRParen) && Current.isNot(TT_TrailingCommaVaOptRParen) && !Current.isTrailingComment() && ((Previous.isNot(TT_CtorInitializerComma) || diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h index 72f7db0c360c0e..0ce023c280756f 100644 --- a/clang/lib/Format/FormatToken.h +++ b/clang/lib/Format/FormatToken.h @@ -680,10 +680,6 @@ struct FormatToken { return !isOneOf(Ks...); } - bool isCommaOrTrailingCommaVaOpt() const { - return isOneOf(tok::comma, TT_TrailingCommaVaOptRParen); - } - bool isIf(bool AllowConstexprMacro = true) const { return is(tok::kw_if) || endsSequence(tok::kw_constexpr, tok::kw_if) || (endsSequence(tok::identifier, tok::kw_if) && AllowConstexprMacro); diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index 7505d3194dbf9d..014fbd66d5b0b2 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -709,7 +709,7 @@ class AnnotatingParser { // Do not consider '[' after a comma inside a braced initializer the // start of an ObjC method expression. In braced initializer lists, // commas are list separators and should not trigger ObjC parsing. - (!Parent || !Parent->isCommaOrTrailingCommaVaOpt() || + (!Parent || Parent->isNoneOf(tok::comma, TT_TrailingCommaVaOptRParen) || Contexts.back().ContextKind != tok::l_brace) && (!Parent || Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren, @@ -2312,8 +2312,8 @@ class AnnotatingParser { if (!Line.startsWith(TT_UnaryOperator)) { for (FormatToken *Previous = Current.Previous; Previous && Previous->Previous && - !Previous->Previous->isCommaOrTrailingCommaVaOpt() && - Previous->Previous->isNot(tok::semi); + Previous->Previous->isNoneOf( + tok::comma, TT_TrailingCommaVaOptRParen, tok::semi); Previous = Previous->Previous) { if (Previous->isOneOf(tok::r_square, tok::r_paren, tok::greater)) { if (Previous->is(TT_TrailingCommaVaOptRParen)) @@ -4341,7 +4341,8 @@ void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) const { if (Parameter->isOneOf(tok::comment, tok::r_brace)) break; if (Parameter->Previous && - Parameter->Previous->isCommaOrTrailingCommaVaOpt()) { + Parameter->Previous->isOneOf(tok::comma, + TT_TrailingCommaVaOptRParen)) { if (Parameter->Previous->isNot(TT_CtorInitializerComma) && Parameter->HasUnescapedNewline) { Parameter->MustBreakBefore = true; @@ -4716,7 +4717,7 @@ unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line, (Right.NextOperator || Right.OperatorIndex != 0)) { return 25; } - if (Left.isCommaOrTrailingCommaVaOpt()) + if (Left.isOneOf(tok::comma, TT_TrailingCommaVaOptRParen)) return 1; if (Right.is(tok::lessless) && Left.isLabelString() && (Right.NextOperator || Right.OperatorIndex != 1)) { @@ -6097,7 +6098,7 @@ bool TokenAnnotator::mustBreakBefore(AnnotatedLine &Line, BeforeClosingBrace = &Left; } if (BeforeClosingBrace && - (BeforeClosingBrace->isCommaOrTrailingCommaVaOpt() || + (BeforeClosingBrace->isOneOf(tok::comma, TT_TrailingCommaVaOptRParen) || BeforeClosingBrace->isTrailingComment())) { return true; } diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index 497aeb6e7af85b..fa892ffb349e11 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -2740,7 +2740,8 @@ bool UnwrappedLineParser::parseParens(TokenType StarAndAmpTokenType, auto *RParen = FormatTok; const bool EndsInComma = RParen->Previous && RParen->Previous->is(tok::comma) && - !RParen->Previous->endsSequence(tok::comma, tok::kw_operator); + (!RParen->Previous->Previous || + RParen->Previous->Previous->isNot(tok::kw_operator)); nextToken(); if (Prev) { auto OptionalParens = [&] { diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 8bb695d739c7a0..75c787d83586da 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -4278,196 +4278,147 @@ TEST_F(FormatTest, FormatsVaOptWithTrailingComma) { " };", getChromiumStyle(FormatStyle::LK_Cpp)); - verifyFormat("enum E {\n" - " __VA_OPT__(__VA_ARGS__, )\n" - " kFirst = 1,\n" - " kSecond = 2,\n" - "};"); - - // Nested parentheses: only a top-level trailing comma inside __VA_OPT__ - // acts as an item separator. - verifyFormat("enum E {\n" - " __VA_OPT__(FOO(a, b), )\n" - " kFirst,\n" - " kSecond,\n" - "};"); - verifyFormat("enum E {\n" - " __VA_OPT__(FOO(a, )) kFirst,\n" - " kSecond,\n" - "};"); + FormatStyle Style = getLLVMStyle(); + Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; - // Short single-line enums remain on one line when allowed. - verifyFormat("enum E { __VA_OPT__(__VA_ARGS__, ) kOnly };"); - FormatStyle NoShortEnums = getLLVMStyle(); + verifyFormat("#define M(...) enum E { __VA_OPT__(__VA_ARGS__, ) kOnly };", + Style); + FormatStyle NoShortEnums = Style; NoShortEnums.AllowShortEnumsOnASingleLine = false; - verifyFormat("enum E {\n" - " __VA_OPT__(__VA_ARGS__, )\n" - " kOnly\n" - "};", + verifyFormat("#define M(...) \\\n" + " enum E { \\\n" + " __VA_OPT__(__VA_ARGS__, ) \\\n" + " kOnly \\\n" + " };", + NoShortEnums); + verifyFormat("#define M(...) \\\n" + " enum E { \\\n" + " kFirst __VA_OPT__(, ) \\\n" + " __VA_ARGS__ \\\n" + " };", + "#define M(...) enum E { kFirst __VA_OPT__(,) __VA_ARGS__ };", NoShortEnums); - // Trailing-comma __VA_OPT__ at the end of a braced list, enum, or call. - verifyFormat("enum E {\n" - " kFirst,\n" - " __VA_OPT__(__VA_ARGS__, )\n" - "};"); - verifyFormat("int x[] = {\n" - " 1,\n" - " __VA_OPT__(__VA_ARGS__, )\n" - " 2,\n" - "};"); - verifyFormat("void f(__VA_OPT__(__VA_ARGS__, )\n" - " int first_arg,\n" - " int second_arg);", - getLLVMStyleWithColumns(32)); - - // Leading-comma __VA_OPT__ stays attached to the preceding item, while - // lone-comma __VA_OPT__(,) acts as a conditional separator. - verifyFormat("enum E {\n" - " kFirst __VA_OPT__(, __VA_ARGS__),\n" - " kSecond,\n" - "};"); - verifyFormat("void f(int a __VA_OPT__(, __VA_ARGS__));"); - verifyFormat("enum E {\n" - " kFirst __VA_OPT__(, )\n" - " __VA_ARGS__\n" - "};", - "enum E { kFirst __VA_OPT__(,) __VA_ARGS__ };", NoShortEnums); - - // Unary operators, designated initializers, lambdas, parens, and braces - // immediately following __VA_OPT__(..., ). - verifyFormat("int x[] = {\n" - " __VA_OPT__(__VA_ARGS__, )\n" - " -1,\n" - " +2,\n" - "};"); - verifyFormat("void f() {\n" - " foo(__VA_OPT__(a, ) *b, &c, ++d);\n" - " auto l = [__VA_OPT__(a, ) &b, &c]() {};\n" - " foo(__VA_OPT__(a, ) [x]() { return x; });\n" - " foo(__VA_OPT__(a, ) (b + c), {1, 2});\n" - "}"); - verifyFormat("S s = {.a = 1, __VA_OPT__(.b = 2, ) .c = 3};"); - verifyFormat("S s = {\n" - " .a = 1,\n" - " __VA_OPT__(__VA_ARGS__, )\n" - " .b = 2,\n" - "};"); - verifyFormat("int a[] = {[0] = 1, __VA_OPT__([1] = 2, ) [2] = 3};"); - - // Bin-packing parameters and constructor initializers after wrapping at - // __VA_OPT__(..., ). - verifyFormat("void f(__VA_OPT__(int very_long_first_param_here, )\n" - " int a, int b, int c);", - getLLVMStyleWithColumns(55)); - verifyFormat("class C {\n" - " C()\n" - " : a_(0), __VA_OPT__(b_(1), )\n" - " c_(2), d_(3) {}\n" - "};", - getLLVMStyleWithColumns(40)); - - // Expressions, operand line-break tracking, consecutive __VA_OPT__, and - // conditional expressions. - verifyFormat("SomeFunction(x, a + b __VA_OPT__(, )\n" - " ccccccccccccccc + ddddddddddddddd, y);", - getLLVMStyleWithColumns(55)); - verifyFormat("SomeFunction(__VA_OPT__(a, )\n" - " bbbbbbbbbbbbbbb + ccccccccccccccc,\n" - " d);", - getLLVMStyleWithColumns(50)); - verifyFormat("foo(!__VA_OPT__(a, ) __VA_OPT__(b, ) c);"); - verifyFormat("int x = foo(cond ? a : __VA_OPT__(bbbbbbbbbbbb, )\n" - " cccccccccccc, dddddddddddd);", - getLLVMStyleWithColumns(50)); - verifyNoCrash("int x = foo(cond ? __VA_OPT__(a, ) b : c, d);"); - verifyNoCrash("int x = foo(cond ? __VA_OPT__(a, ) : b + c, d);"); - verifyNoCrash("int x = foo(__VA_OPT__(a, ) ? b : c + d, e);"); - - // Nested call indentation when AlignAfterOpenBracket is disabled. - FormatStyle DontAlign = getLLVMStyleWithColumns(50); - DontAlign.AlignAfterOpenBracket = false; - verifyFormat("void g() {\n" - " foo(__VA_OPT__(a, ) bar(bbbbbbbbbbbbbbbbbb,\n" - " cccccccccccccccccc));\n" - "}", - DontAlign); - - // Multi-column braced list layout and template parameter lists. - verifyFormat("int x[] = {__VA_OPT__(a, ) 1, 1000000000, 2000000000,\n" - " 3000000000, 4, 5000000000, 6000000000};"); - verifyFormat("template <__VA_OPT__(typename T, )\n" - " typename U, typename V>\n" - "struct S;", - getLLVMStyleWithColumns(42)); - - // Overloaded operator, inside __VA_OPT__ is not a trailing comma. - verifyFormat("#define CALL_COMMA(...) \\\n" - " foo(__VA_OPT__(x.operator, ) + \\\n" - " yyyyyyyyyyyyyyyyyyyy)", - getLLVMStyleWithColumns(40)); - - // EnumTrailingComma: Insert/Remove with trailing-comma __VA_OPT__. FormatStyle InsertComma = NoShortEnums; InsertComma.EnumTrailingComma = FormatStyle::ETC_Insert; - verifyFormat("enum E {\n" - " kFirst,\n" - " __VA_OPT__(__VA_ARGS__, )\n" - "};", + verifyFormat("#define M(...) \\\n" + " enum E { \\\n" + " kFirst, \\\n" + " __VA_OPT__(__VA_ARGS__, ) \\\n" + " };", InsertComma); FormatStyle RemoveComma = NoShortEnums; RemoveComma.EnumTrailingComma = FormatStyle::ETC_Remove; - verifyFormat("enum E {\n" - " kFirst,\n" - " __VA_OPT__(__VA_ARGS__, )\n" - "};", + verifyFormat("#define M(...) \\\n" + " enum E { \\\n" + " kFirst, \\\n" + " __VA_OPT__(__VA_ARGS__, ) \\\n" + " };", RemoveComma); - // Parameter packing, function declaration heuristics, and Google-style - // left-aligned pointers / multi-variable declarations. - FormatStyle OnePerLine = getLLVMStyle(); + verifyFormat("#define M(...) \\\n" + " int x[] = { \\\n" + " 1, \\\n" + " __VA_OPT__(__VA_ARGS__, ) \\\n" + " 2, \\\n" + " };", + Style); + verifyFormat("#define M(...) \\\n" + " int x[] = {__VA_OPT__(a, ) 1, 1000000000, 2000000000, \\\n" + " 3000000000, 4, 5000000000, 6000000000};", + Style); + + verifyFormat("#define M(...) void f(int a __VA_OPT__(, __VA_ARGS__));", + Style); + FormatStyle Style58 = Style; + Style58.ColumnLimit = 58; + verifyFormat("#define M(...) \\\n" + " void f(__VA_OPT__(int very_long_first_param_here, ) \\\n" + " int a, int b, int c);", + Style58); + FormatStyle OnePerLine = Style; OnePerLine.PackParameters.BinPack = FormatStyle::BPPS_AlwaysOnePerLine; - verifyFormat("void f(__VA_OPT__(int a, )\n" - " int b,\n" - " int c);", + verifyFormat("#define M(...) \\\n" + " struct S { \\\n" + " void f(__VA_OPT__(int a, ) \\\n" + " int b, \\\n" + " int c); \\\n" + " };", OnePerLine); - FormatStyle BreakDeclParams = getLLVMStyle(); - BreakDeclParams.BreakFunctionDeclarationParameters = true; - verifyFormat("int __VA_OPT__(a, ) b;", BreakDeclParams); - FormatStyle AutoBinPack = getLLVMStyleWithColumns(50); + FormatStyle AutoBinPack = Style; + AutoBinPack.ColumnLimit = 55; AutoBinPack.ExperimentalAutoDetectBinPacking = true; - verifyNoChange("void f() {\n" - " foo(__VA_OPT__(aaaaaaaaaaaa, ) bbbbbbbbbbbb,\n" - " cccccccccccc);\n" - "}", + verifyNoChange("#define M(...) \\\n" + " void f() { \\\n" + " foo(__VA_OPT__(aaaaaaaaaaaa, ) bbbbbbbbbbbb, \\\n" + " cccccccccccc); \\\n" + " }", AutoBinPack); - verifyGoogleFormat("void g() { foo(__VA_OPT__(a, ) *x = 1); }"); - verifyGoogleFormat("int __VA_OPT__(a = 1, ) *b = nullptr;"); - verifyGoogleFormat("int a = 1 __VA_OPT__(, ) *const b = nullptr;"); - FormatStyle Google30 = getGoogleStyle(); - Google30.ColumnLimit = 30; - verifyFormat("int __VA_OPT__(aaaa = 1, )\n" - " *bbbb = nullptr;", - Google30); - verifyFormat("long int aa = 1 __VA_OPT__(, )\n" - " *bb = nullptr;", - Google30); - - // Comments inside and after __VA_OPT__, and non-C++ language guard. - verifyFormat("enum E {\n" - " __VA_OPT__(__VA_ARGS__, /*comment*/)\n" - " kFirst,\n" - "};"); - verifyNoChange("void f() {\n" - " SomeFunction(__VA_OPT__(a, )\n" - " b, // comment\n" - " c);\n" - "}"); - verifyFormat("enum E {\n" - " __VA_OPT__(a, ) kFirst,\n" - " kSecond,\n" - "}", - getLLVMStyle(FormatStyle::LK_Java)); + FormatStyle BreakDeclParams = Style; + BreakDeclParams.BreakFunctionDeclarationParameters = true; + verifyFormat("#define M(...) \\\n" + " struct S { \\\n" + " int __VA_OPT__(a, ) b; \\\n" + " };", + BreakDeclParams); + + FormatStyle Style40 = Style; + Style40.ColumnLimit = 40; + verifyFormat("#define M(...) \\\n" + " class C { \\\n" + " C() \\\n" + " : a_(0), __VA_OPT__(b_(1), ) \\\n" + " c_(2), d_(3) {} \\\n" + " };", + Style40); + + verifyFormat("#define M(...) \\\n" + " SomeFunction(x, a + b __VA_OPT__(, ) \\\n" + " ccccccccccccccc + ddddddddddddddd, y);", + Style58); + FormatStyle Style53 = Style; + Style53.ColumnLimit = 53; + verifyFormat("#define M(...) \\\n" + " SomeFunction(__VA_OPT__(a, ) \\\n" + " bbbbbbbbbbbbbbb + ccccccccccccccc, \\\n" + " d);", + Style53); + verifyFormat("#define M(...) \\\n" + " int x = foo(cond ? a : __VA_OPT__(bbbbbbbbbbbb, ) \\\n" + " cccccccccccc, dddddddddddd);", + Style53); + // Malformed ternary with trailing-comma __VA_OPT__. + verifyNoCrash("#define M(...) int x = foo(cond ? __VA_OPT__(a, ) b : c, d);"); + verifyNoCrash("#define M(...) int x = foo(__VA_OPT__(a, ) ? b : c + d, e);"); + + FormatStyle DontAlign = Style; + DontAlign.ColumnLimit = 55; + DontAlign.AlignAfterOpenBracket = false; + verifyFormat("#define M(...) \\\n" + " void g() { \\\n" + " foo(__VA_OPT__(a, ) bar(bbbbbbbbbbbbbbbbbbbbbb, \\\n" + " cccccccccccccccccccccc)); \\\n" + " }", + DontAlign); + + FormatStyle Style45 = Style; + Style45.ColumnLimit = 45; + verifyFormat("#define M(...) \\\n" + " template <__VA_OPT__(typename T, ) \\\n" + " typename U, typename V> \\\n" + " struct S;", + Style45); + + verifyFormat("#define M(...) foo(__VA_OPT__(a, ) *b, (c + d), {1, 2})", + Style); + verifyFormat("#define M(...) S s = {.a = 1, __VA_OPT__(.b = 2, ) .c = 3};", + Style); + FormatStyle Google35 = getGoogleStyle(); + Google35.ColumnLimit = 35; + verifyFormat("#define M(...) \\\n" + " long int aa = 1 __VA_OPT__(, ) \\\n" + " *bb = nullptr;", + Google35); } TEST_F(FormatTest, FormatsNSEnums) { diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp index 138486071b3306..90ec125c59c819 100644 --- a/clang/unittests/Format/TokenAnnotatorTest.cpp +++ b/clang/unittests/Format/TokenAnnotatorTest.cpp @@ -4642,6 +4642,71 @@ TEST_F(TokenAnnotatorTest, CSharpUtf8StringLiterals) { EXPECT_TOKEN(Tokens[4], tok::identifier, TT_Unknown); } +TEST_F(TokenAnnotatorTest, VaOptWithTrailingComma) { + auto Tokens = + annotate("#define M(...) enum E { __VA_OPT__(__VA_ARGS__, ) kFirst };"); + ASSERT_EQ(Tokens.size(), 18u) << Tokens; + EXPECT_TOKEN(Tokens[13], tok::r_paren, TT_TrailingCommaVaOptRParen); + + Tokens = + annotate("#define M(...) enum E { __VA_OPT__(FOO(a, b), ) kFirst };"); + ASSERT_EQ(Tokens.size(), 23u) << Tokens; + EXPECT_TOKEN(Tokens[16], tok::r_paren, TT_Unknown); + EXPECT_TOKEN(Tokens[18], tok::r_paren, TT_TrailingCommaVaOptRParen); + + Tokens = annotate("#define M(...) enum E { __VA_OPT__(FOO(a, )) kFirst };"); + ASSERT_EQ(Tokens.size(), 21u) << Tokens; + EXPECT_TOKEN(Tokens[16], tok::r_paren, TT_Unknown); + + Tokens = + annotate("#define M(...) enum E { kFirst __VA_OPT__(, __VA_ARGS__) };"); + ASSERT_EQ(Tokens.size(), 18u) << Tokens; + EXPECT_TOKEN(Tokens[14], tok::r_paren, TT_Unknown); + + Tokens = annotate("#define M(...) foo(__VA_OPT__(x.operator, ) + y)"); + ASSERT_EQ(Tokens.size(), 19u) << Tokens; + EXPECT_TOKEN(Tokens[14], tok::r_paren, TT_Unknown); + + Tokens = annotate( + "#define M(...) enum E { __VA_OPT__(__VA_ARGS__, /*c*/) kFirst };"); + ASSERT_EQ(Tokens.size(), 19u) << Tokens; + EXPECT_TOKEN(Tokens[14], tok::r_paren, TT_TrailingCommaVaOptRParen); + + Tokens = + annotate("#define M(...) foo(__VA_OPT__(a, ) *b, __VA_OPT__(a, ) &c, " + "__VA_OPT__(a, ) -d, __VA_OPT__(a, ) ++e)"); + ASSERT_EQ(Tokens.size(), 41u) << Tokens; + EXPECT_TOKEN(Tokens[12], tok::r_paren, TT_TrailingCommaVaOptRParen); + EXPECT_TOKEN(Tokens[13], tok::star, TT_UnaryOperator); + EXPECT_TOKEN(Tokens[20], tok::r_paren, TT_TrailingCommaVaOptRParen); + EXPECT_TOKEN(Tokens[21], tok::amp, TT_UnaryOperator); + EXPECT_TOKEN(Tokens[28], tok::r_paren, TT_TrailingCommaVaOptRParen); + EXPECT_TOKEN(Tokens[29], tok::minus, TT_UnaryOperator); + EXPECT_TOKEN(Tokens[36], tok::r_paren, TT_TrailingCommaVaOptRParen); + EXPECT_TOKEN(Tokens[37], tok::plusplus, TT_UnaryOperator); + + Tokens = annotate("#define M(...) S s = {__VA_OPT__(.a = 1, ) .b = 2};"); + ASSERT_EQ(Tokens.size(), 25u) << Tokens; + EXPECT_TOKEN(Tokens[17], tok::r_paren, TT_TrailingCommaVaOptRParen); + EXPECT_TOKEN(Tokens[18], tok::period, TT_DesignatedInitializerPeriod); + + Tokens = + annotate("#define M(...) int a[] = {__VA_OPT__([0] = 1, ) [1] = 2};"); + ASSERT_EQ(Tokens.size(), 29u) << Tokens; + EXPECT_TOKEN(Tokens[20], tok::r_paren, TT_TrailingCommaVaOptRParen); + EXPECT_TOKEN(Tokens[21], tok::l_square, TT_DesignatedInitializerLSquare); + + Tokens = annotate("#define M(...) foo(__VA_OPT__(a, ) [x]() { return x; })"); + ASSERT_EQ(Tokens.size(), 25u) << Tokens; + EXPECT_TOKEN(Tokens[12], tok::r_paren, TT_TrailingCommaVaOptRParen); + EXPECT_TOKEN(Tokens[13], tok::l_square, TT_LambdaLSquare); + + Tokens = annotate("enum E { __VA_OPT__(a, ) kFirst };", + getLLVMStyle(FormatStyle::LK_Java)); + ASSERT_EQ(Tokens.size(), 12u) << Tokens; + EXPECT_TOKEN(Tokens[7], tok::r_paren, TT_Unknown); +} + } // namespace } // namespace format } // namespace clang _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
