From 9e8e3a155501232dbc83432f7c75a95c60e06632 Mon Sep 17 00:00:00 2001 From: Jelly <77585130+jellynoone@users.noreply.github.com> Date: Fri, 4 Apr 2025 14:12:38 +0200 Subject: [PATCH] Preserve trailing commas for enums with members when commas are preserved --- lib/src/front_end/ast_node_visitor.dart | 14 +++++++++++++- test/tall/preserve_trailing_commas/enum.unit | 5 +++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/lib/src/front_end/ast_node_visitor.dart b/lib/src/front_end/ast_node_visitor.dart index 6f0d5ba8..2f505290 100644 --- a/lib/src/front_end/ast_node_visitor.dart +++ b/lib/src/front_end/ast_node_visitor.dart @@ -648,14 +648,26 @@ final class AstNodeVisitor extends ThrowingAstVisitor with PieceFactory { builder.leftBracket(node.leftBracket); for (var constant in node.constants) { + var isLast = constant == node.constants.last; + var treatAsLast = isLast; + if (isLast && formatter.trailingCommas == TrailingCommas.preserve) { + treatAsLast = constant.commaAfter == null; + } builder.addCommentsBefore(constant.firstNonCommentToken); builder.add( createEnumConstant( constant, - isLastConstant: constant == node.constants.last, + isLastConstant: treatAsLast, semicolon: node.semicolon, ), ); + // If this the last constant and wasn't treated as last, we need + // to append the ending semicolon. + if (isLast && !treatAsLast) { + if (node.semicolon case var token?) { + builder.add(tokenPiece(token)); + } + } } // Insert a blank line between the constants and members. diff --git a/test/tall/preserve_trailing_commas/enum.unit b/test/tall/preserve_trailing_commas/enum.unit index 8e58e68c..d940acdf 100644 --- a/test/tall/preserve_trailing_commas/enum.unit +++ b/test/tall/preserve_trailing_commas/enum.unit @@ -25,13 +25,14 @@ enum E {e,;} enum E { e, } ->>> Remove trailing comma and split if there are members. +>>> Preserve trailing comma and split if there are members. enum E { a, b, c,; int x; } <<< enum E { a, b, - c; + c, + ; int x; }