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; }