Skip to content

Commit 2dc435f

Browse files
authored
gh-1436: Fix incorrectly rejecting trailing comma after **rest (#1438)
* Add a unittest to expose the issue reported in gh-1436 * Fix issue reported in gh-1436 * formatting * Add roundtrip tests for trailing comma after `**rest`
1 parent d77fc49 commit 2dc435f

3 files changed

Lines changed: 19 additions & 2 deletions

File tree

libcst/_nodes/statement.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3245,8 +3245,6 @@ class MatchMapping(MatchPattern):
32453245
rpar: Sequence[RightParen] = ()
32463246

32473247
def _validate(self) -> None:
3248-
if isinstance(self.trailing_comma, Comma) and self.rest is not None:
3249-
raise CSTValidationError("Cannot have a trailing comma without **rest")
32503248
super(MatchMapping, self)._validate()
32513249

32523250
def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "MatchMapping":

libcst/_nodes/tests/test_match.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,22 @@ class MatchTest(CSTNodeTest):
226226
),
227227
body=cst.SimpleStatementSuite((cst.Pass(),)),
228228
),
229+
cst.MatchCase( # rest with trailing comma - valid syntax (issue #1436)
230+
pattern=cst.MatchMapping(
231+
[
232+
cst.MatchMappingElement(
233+
key=cst.SimpleString('"a"'),
234+
pattern=cst.MatchValue(cst.Integer("1")),
235+
comma=cst.Comma(
236+
whitespace_after=cst.SimpleWhitespace(" ")
237+
),
238+
),
239+
],
240+
rest=cst.Name("keys"),
241+
trailing_comma=cst.Comma(),
242+
),
243+
body=cst.SimpleStatementSuite((cst.Pass(),)),
244+
),
229245
],
230246
),
231247
"code": (
@@ -234,6 +250,7 @@ class MatchTest(CSTNodeTest):
234250
+ ' case {"a": None,"b": None}: pass\n'
235251
+ ' case {"a": None,}: pass\n'
236252
+ " case {**rest}: pass\n"
253+
+ ' case {"a": 1, **keys,}: pass\n'
237254
),
238255
"parser": parser,
239256
},

native/libcst/tests/fixtures/malicious_match.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,6 @@
3939
case 1, 2: pass
4040
case ( Foo ( ) ) : pass
4141
case (lol) if ( True , ) :pass
42+
case {"a": 1, **keys,} : pass
43+
case {**rest,} : pass
4244

0 commit comments

Comments
 (0)