Skip to content

Commit 16f6ab0

Browse files
committed
optimize MATCH_SEQUENCE/MAPPING
1 parent 1f36a51 commit 16f6ab0

File tree

3 files changed

+65
-2
lines changed

3 files changed

+65
-2
lines changed

Lib/test/test_capi/test_opt.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4684,6 +4684,41 @@ class A:
46844684
self.assertIn("_MATCH_CLASS", uops)
46854685
self.assertEqual(count_ops(ex, "_POP_TOP_NOP"), 4)
46864686

4687+
def test_match_mapping(self):
4688+
def testfunc(n):
4689+
x = {}
4690+
ret = 0
4691+
for _ in range(n):
4692+
x["a"] = 1
4693+
match x:
4694+
case {}:
4695+
ret += 1
4696+
return ret
4697+
4698+
res, ex = self._run_with_optimizer(testfunc, TIER2_THRESHOLD)
4699+
self.assertEqual(res, TIER2_THRESHOLD)
4700+
uops = get_opnames(ex)
4701+
4702+
self.assertIn("_MATCH_MAPPING", uops)
4703+
self.assertNotIn("_GUARD_BIT_IS_SET_POP", uops)
4704+
4705+
def test_match_sequence(self):
4706+
def testfunc(n):
4707+
ret = 0
4708+
for _ in range(n):
4709+
x = 1, 2
4710+
match x:
4711+
case a, b:
4712+
ret += 1
4713+
return ret
4714+
4715+
res, ex = self._run_with_optimizer(testfunc, TIER2_THRESHOLD)
4716+
self.assertEqual(res, TIER2_THRESHOLD)
4717+
uops = get_opnames(ex)
4718+
4719+
self.assertIn("_MATCH_SEQUENCE", uops)
4720+
self.assertNotIn("_GUARD_BIT_IS_SET_POP", uops)
4721+
46874722
def test_dict_update(self):
46884723
def testfunc(n):
46894724
d = {1: 2, 3: 4}

Python/optimizer_bytecodes.c

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2071,6 +2071,22 @@ dummy_func(void) {
20712071
n = names;
20722072
}
20732073

2074+
op(_MATCH_MAPPING, (subject -- subject, res)) {
2075+
if (sym_has_type(subject)) {
2076+
PyTypeObject *type = sym_get_type(subject);
2077+
int match = type->tp_flags & Py_TPFLAGS_MAPPING;
2078+
res = match ? sym_new_const(ctx, Py_True) : sym_new_const(ctx, Py_False);
2079+
}
2080+
}
2081+
2082+
op(_MATCH_SEQUENCE, (subject -- subject, res)) {
2083+
if (sym_has_type(subject)) {
2084+
PyTypeObject *type = sym_get_type(subject);
2085+
int match = type->tp_flags & Py_TPFLAGS_SEQUENCE;
2086+
res = match ? sym_new_const(ctx, Py_True) : sym_new_const(ctx, Py_False);
2087+
}
2088+
}
2089+
20742090
op(_DICT_UPDATE, (dict, unused[oparg - 1], update -- dict, unused[oparg - 1], upd)) {
20752091
(void)dict;
20762092
upd = update;

Python/optimizer_cases.c.h

Lines changed: 14 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)