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68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
diff --git a/Lib/test/test_patma_aug.py b/Lib/test/test_patma_aug.py
new file mode 100644
--- /dev/null
+++ b/Lib/test/test_patma_aug.py
@@ -0,0 +1,362 @@
+import ast
+import keyword
+import symtable
+import unittest
+from collections import namedtuple
+from dataclasses import dataclass, field
+
+
+class PatternMatchingAugmentedTests(unittest.TestCase):
+    def test_soft_keywords_and_standard_library_match_args(self):
+        self.assertFalse(keyword.iskeyword("match"))
+        self.assertFalse(keyword.iskeyword("case"))
+        self.assertTrue(keyword.issoftkeyword("match"))
+        self.assertTrue(keyword.issoftkeyword("case"))
+        self.assertTrue(keyword.issoftkeyword("_"))
+
+        Point = namedtuple("Point", "x y")
+        self.assertEqual(Point.__match_args__, ("x", "y"))
+
+        def match_namedtuple(value):
+            match value:
+                case Point(x, y):
+                    return x, y
+                case _:
+                    return None
+
+        self.assertEqual(match_namedtuple(Point(3, 4)), (3, 4))
+
+        @dataclass
+        class Item:
+            visible: int
+            hidden: int = field(init=False, default=9)
+
+        self.assertEqual(Item.__match_args__, ("visible",))
+
+        def match_dataclass(value):
+            match value:
+                case Item(visible):
+                    return visible
+                case _:
+                    return None
+
+        self.assertEqual(match_dataclass(Item(11)), 11)
+
+    def test_builtin_and_subclass_self_match_patterns(self):
+        def match_int(value):
+            match value:
+                case int(bound):
+                    return bound
+                case _:
+                    return None
+
+        self.assertEqual(match_int(3), 3)
+
+        class MyInt(int):
+            pass
+
+        def match_subclass(value):
+            match value:
+                case MyInt(bound):
+                    return bound
+                case _:
+                    return None
+
+        result = match_subclass(MyInt(7))
+        self.assertIs(type(result), MyInt)
+        self.assertEqual(result, 7)
+
+    def test_sequence_and_mapping_pattern_runtime_contracts(self):
+        def sequence_result(value):
+            match value:
+                case ["a", "b"]:
+                    return "sequence"
+                case _:
+                    return "other"
+
+        self.assertEqual(sequence_result(["a", "b"]), "sequence")
+        self.assertEqual(sequence_result("ab"), "other")
+        self.assertEqual(sequence_result(b"ab"), "other")
+        self.assertEqual(sequence_result(bytearray(b"ab")), "other")
+
+        def fixed_sequence_result(value):
+            match value:
+                case [1, 2]:
+                    return "two"
+                case _:
+                    return "other"
+
+        self.assertEqual(fixed_sequence_result([1, 2]), "two")
+        self.assertEqual(fixed_sequence_result([1, 2, 3]), "other")
+
+        def mapping_result(value):
+            match value:
+                case {"x": bound}:
+                    return bound
+                case _:
+                    return None
+
+        self.assertEqual(mapping_result({"x": 1}), 1)
+        self.assertEqual(mapping_result({"x": 1, "y": 2}), 1)
+
+    def test_class_pattern_match_args_and_duplicate_keywords(self):
+        class Point:
+            __match_args__ = ("x", "y")
+
+            def __init__(self, x, y):
+                self.x = x
+                self.y = y
+
+        def match_point(value):
+            match value:
+                case Point(x, y):
+                    return x, y
+                case _:
+                    return None
+
+        self.assertEqual(match_point(Point(5, 8)), (5, 8))
+
+        duplicate_keyword = """
+def f(value):
+    match value:
+        case Point(x=1, x=2):
+            return True
+"""
+        with self.assertRaises(SyntaxError):
+            compile(duplicate_keyword, "<duplicate class keyword>", "exec")
+
+    def test_literal_singletons_guards_and_bindings(self):
+        class EqualsNone:
+            def __eq__(self, other):
+                return other is None
+
+        def classify_singleton(value):
+            match value:
+                case None:
+                    return "none"
+                case _:
+                    return "other"
+
+        self.assertEqual(classify_singleton(EqualsNone()), "other")
+
+        def guard_true(value):
+            match value:
+                case 1 if True:
+                    return "guarded"
+                case 1:
+                    return "fallback"
+                case _:
+                    return "other"
+
+        def guard_false(value):
+            match value:
+                case 1 if False:
+                    return "guarded"
+                case 1:
+                    return "fallback"
+                case _:
+                    return "other"
+
+        self.assertEqual(guard_true(1), "guarded")
+        self.assertEqual(guard_false(1), "fallback")
+
+        def as_pattern(value):
+            match value:
+                case (1, y) as pair:
+                    return pair, y
+                case _:
+                    return None
+
+        self.assertEqual(as_pattern((1, 2)), ((1, 2), 2))
+
+        def capture_pattern(value):
+            match value:
+                case captured:
+                    return captured
+
+        self.assertEqual(capture_pattern("bound"), "bound")
+
+    def test_static_pattern_validation_rules(self):
+        nonfinal_irrefutable = """
+def f(value):
+    match value:
+        case captured:
+            return captured
+        case 1:
+            return "one"
+"""
+        with self.assertRaises(SyntaxError):
+            compile(nonfinal_irrefutable, "<nonfinal irrefutable>", "exec")
+
+        duplicate_capture = """
+def f(value):
+    match value:
+        case (x, x):
+            return x
+"""
+        with self.assertRaises(SyntaxError):
+            compile(duplicate_capture, "<duplicate capture>", "exec")
+
+        inconsistent_or_bindings = """
+def f(value):
+    match value:
+        case [x] | [x, y]:
+            return x
+"""
+        with self.assertRaises(SyntaxError):
+            compile(inconsistent_or_bindings, "<inconsistent or bindings>", "exec")
+
+        wildcard_source = """
+def f(value):
+    match value:
+        case _:
+            return 1
+"""
+        table = symtable.symtable(wildcard_source, "<wildcard>", "exec")
+        function_table = table.get_children()[0]
+        locals_in_function = {
+            symbol.get_name()
+            for symbol in function_table.get_symbols()
+            if symbol.is_local()
+        }
+        self.assertNotIn("_", locals_in_function)
+
+    def test_ast_validation_rejects_match_without_cases(self):
+        tree = ast.Module(
+            body=[
+                ast.Match(
+                    subject=ast.Constant(value=1),
+                    cases=[],
+                )
+            ],
+            type_ignores=[],
+        )
+        ast.fix_missing_locations(tree)
+        with self.assertRaises(ValueError):
+            compile(tree, "<empty match cases>", "exec")
+
+    def test_parser_accepts_and_rejects_pattern_grammar_forms(self):
+        def case_source(pattern, guard=""):
+            return (
+                "def f(subject):\n"
+                "    match subject:\n"
+                f"        case {pattern}{guard}:\n"
+                "            return 1\n"
+            )
+
+        valid_patterns = [
+            "None",
+            "True",
+            "False",
+            "0",
+            "-1",
+            "1.5",
+            "-2.5",
+            "3j",
+            "-4j",
+            "1 + 2j",
+            "1 - 2j",
+            "-1 + 2j",
+            "'text'",
+            "b'bytes'",
+            "name",
+            "_",
+            "Color.RED",
+            "pkg.mod.VALUE",
+            "(Color.RED)",
+            "((1))",
+            "[]",
+            "[x]",
+            "[x,]",
+            "[first, second]",
+            "[head, *tail]",
+            "[*prefix, last]",
+            "[first, *middle, last]",
+            "()",
+            "(x,)",
+            "(x, y)",
+            "x, y",
+            "{}",
+            "{'x': x}",
+            "{1: one, 2: two}",
+            "{Color.RED: value}",
+            "{'x': x, **rest}",
+            "{**rest}",
+            "{'x': [a, b], 'y': C(z)}",
+            "C()",
+            "C(x)",
+            "C(x, y)",
+            "C(attr=x)",
+            "C(x, attr=y)",
+            "pkg.mod.C(1, attr=2)",
+            "C([a, *b], {'x': y})",
+            "1 | 2 | 3",
+            "[1] | (1,)",
+            "[x] | (x,)",
+            "(1 | 2) as value",
+            "[x] as value",
+        ]
+
+        valid_sources = [case_source(pattern) for pattern in valid_patterns]
+        valid_sources.extend(
+            [
+                (
+                    "def f(a, b):\n"
+                    "    match a, b:\n"
+                    "        case (1, 2):\n"
+                    "            return 1\n"
+                ),
+                (
+                    "def f(subject):\n"
+                    "    match subject:\n"
+                    "        case 1 if subject:\n"
+                    "            return 1\n"
+                    "        case _:\n"
+                    "            return 2\n"
+                ),
+                (
+                    "def f(subject):\n"
+                    "    match subject:\n"
+                    "        case [first, second] | (first, second):\n"
+                    "            return first, second\n"
+                ),
+            ]
+        )
+
+        for source in valid_sources:
+            with self.subTest(kind="valid", source=source):
+                compile(source, "<valid pattern grammar>", "exec")
+
+        invalid_patterns = [
+            "*rest",
+            "**rest",
+            "...",
+            "+1",
+            ".value",
+            "C(,)",
+            "C(a=)",
+            "C(x=1, x=2)",
+            "{'x': }",
+            "{'x': x, **_}",
+            "{**rest, 'x': value}",
+            "[*x, *y]",
+            "[x,, y]",
+            "1 | x",
+            "x | y",
+            "[x, x]",
+            "_ as _",
+        ]
+
+        for pattern in invalid_patterns:
+            source = case_source(pattern)
+            with self.subTest(kind="invalid", source=source):
+                try:
+                    compile(source, "<invalid pattern grammar>", "exec")
+                except SyntaxError:
+                    pass
+                else:
+                    self.fail(f"accepted invalid pattern: {pattern}")
+
+
+if __name__ == "__main__":
+    unittest.main()
diff --git a/Lib/test/test_patma_stability_aug.py b/Lib/test/test_patma_stability_aug.py
new file mode 100644
--- /dev/null
+++ b/Lib/test/test_patma_stability_aug.py
@@ -0,0 +1,64 @@
+import ast
+import keyword
+import unittest
+from collections import namedtuple
+from dataclasses import dataclass, field
+
+
+class PatternMatchingStabilityAugmentedTests(unittest.TestCase):
+    def test_soft_keyword_names_remain_ordinary_identifiers(self):
+        self.assertFalse(keyword.iskeyword("match"))
+        self.assertFalse(keyword.iskeyword("case"))
+
+        namespace = {}
+        exec(
+            "match = 2\n"
+            "case = 3\n"
+            "_ = 4\n"
+            "result = match * case + _\n",
+            namespace,
+        )
+        self.assertEqual(namespace["result"], 10)
+
+    def test_namedtuple_existing_contracts_are_unchanged(self):
+        Point = namedtuple("Point", ["x", "y"], defaults=[99])
+
+        point = Point(4)
+        self.assertEqual(point.x, 4)
+        self.assertEqual(point.y, 99)
+        self.assertEqual(point[0], 4)
+        self.assertEqual(point._asdict(), {"x": 4, "y": 99})
+        self.assertEqual(Point._fields, ("x", "y"))
+
+    def test_dataclass_existing_init_defaults_and_repr_are_unchanged(self):
+        @dataclass
+        class Item:
+            value: int
+            label: str = "default"
+            cached: int = field(init=False, default=5)
+
+        item = Item(3)
+        self.assertEqual((item.value, item.label, item.cached), (3, "default", 5))
+        self.assertIn("Item(value=3, label='default', cached=5)", repr(item))
+
+        with self.assertRaises(TypeError):
+            Item(3, "name", 7)
+
+    def test_ast_compile_existing_control_flow_is_unchanged(self):
+        source = """
+def f(values):
+    total = 0
+    for value in values:
+        if value % 2:
+            total += value
+    return total
+"""
+        tree = ast.parse(source)
+        code = compile(tree, "<ordinary control flow>", "exec")
+        namespace = {}
+        exec(code, namespace)
+        self.assertEqual(namespace["f"]([1, 2, 3, 4, 5]), 9)
+
+
+if __name__ == "__main__":
+    unittest.main()