Skip to content

Commit 102a03c

Browse files
cmaloneyclaude
andauthored
gh-87613: Support kwargs in Argument Clinic vectorcall (#162465)
`@vectorcall` with `**kwargs` always delegated to the keyword helper, which only reads a kwargs dict, so it couldn't be generated. The vectorcall now parses positionals with the shared positional emitter and builds the dict from kwnames only when there are keywords, otherwise passing NULL, as the tuple parser does. The `*args` and `**kwargs` parsers take the calling convention explicitly rather than reading `self.fastcall`, which describes the Python-visible entry point having stack style args, not the vectorcall. Fix `as` in AC **kwargs parameters: `*args as name` already set the C name; `**kwargs as name` failed to parse because the 'as' regex only allowed a single leading star. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 2005753 commit 102a03c

6 files changed

Lines changed: 176 additions & 52 deletions

File tree

‎Lib/test/test_clinic.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1847,6 +1847,15 @@ def test_c_name(self):
18471847
""")
18481848
self.assertEqual("os_stat_fn", function.c_basename)
18491849

1850+
def test_var_keyword_c_name(self):
1851+
function = self.parse_function("""
1852+
module foo
1853+
foo.bar
1854+
**kwargs as kwds: dict
1855+
""")
1856+
p = function.parameters['kwargs_as_kwds']
1857+
self.assertEqual("kwds", p.converter.name)
1858+
18501859
def test_base_invalid_syntax(self):
18511860
block = """
18521861
module os
@@ -5846,6 +5855,20 @@ def test_vc_kwonly_missing_required(self):
58465855
with self.assertRaises(TypeError):
58475856
ac_tester.VcKwOnly()
58485857

5858+
def test_vc_kwds(self):
5859+
with self.assertRaises(TypeError):
5860+
ac_tester.VcKwds()
5861+
with self.assertRaises(TypeError):
5862+
ac_tester.VcKwds(y='y')
5863+
with self.assertRaises(TypeError):
5864+
ac_tester.VcKwds(1, 2, 3)
5865+
self.assertEqual(ac_tester.VcKwds(1), (1, None, None))
5866+
self.assertEqual(ac_tester.VcKwds(1, 2), (1, 2, None))
5867+
self.assertEqual(ac_tester.VcKwds(1, a='a', b='b'),
5868+
(1, None, {'a': 'a', 'b': 'b'}))
5869+
kwds = {'y': 'y', 'z': 'z'}
5870+
self.assertEqual(ac_tester.VcKwds(1, 2, **kwds), (1, 2, kwds))
5871+
58495872
def test_parse_errors_match_slot(self):
58505873
# tp_vectorcall and tp_new/tp_init slot should match in argument parsing
58515874
# error messages. Explicit calls to __new__ and __init__, as well as
@@ -5871,6 +5894,7 @@ def through_init(cls):
58715894
through_new(ac_tester.VcNew),
58725895
through_new(ac_tester.VcNewBase),
58735896
through_new(ac_tester.VcKwOnly),
5897+
through_new(ac_tester.VcKwds),
58745898
through_init(ac_tester.VcInit),
58755899
]
58765900
invalid_calls = [

‎Modules/_testclinic.c‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2671,6 +2671,40 @@ static PyTypeObject VcKwOnly_Type = {
26712671
};
26722672

26732673

2674+
/* VcKwds: @vectorcall + **kwargs. __new__ returns the parsed arguments. */
2675+
2676+
/*[clinic input]
2677+
class _testclinic.VcKwds "PyObject *" ""
2678+
@classmethod
2679+
@vectorcall
2680+
_testclinic.VcKwds.__new__ as vc_kwds_new
2681+
a: object
2682+
b: object = None
2683+
/
2684+
**kwds: dict
2685+
[clinic start generated code]*/
2686+
2687+
static PyObject *
2688+
vc_kwds_new_impl(PyTypeObject *type, PyObject *a, PyObject *b,
2689+
PyObject *kwds)
2690+
/*[clinic end generated code: output=481e680d2e76fdbd input=3d8e5218fd593383]*/
2691+
{
2692+
return pack_arguments_newref(3, a, b, kwds);
2693+
}
2694+
2695+
static PyType_Slot VcKwds_slots[] = {
2696+
{Py_tp_new, vc_kwds_new},
2697+
{Py_tp_vectorcall, vc_kwds_vectorcall},
2698+
{0, NULL},
2699+
};
2700+
static PyType_Spec VcKwds_spec = {
2701+
.name = "_testclinic.VcKwds",
2702+
.basicsize = sizeof(PyObject),
2703+
.flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE,
2704+
.slots = VcKwds_slots,
2705+
};
2706+
2707+
26742708

26752709
/*[clinic input]
26762710
output push
@@ -2897,7 +2931,7 @@ _testclinic_exec(PyObject *m)
28972931
&HeapTestClass_spec,
28982932
&DeprStarNew_spec, &DeprStarInit_spec, &DeprStarInitNoInline_spec,
28992933
&DeprKwdNew_spec, &DeprKwdInit_spec, &DeprKwdInitNoInline_spec,
2900-
&VcInit_spec,
2934+
&VcInit_spec, &VcKwds_spec,
29012935
};
29022936
for (size_t i = 0; i < Py_ARRAY_LENGTH(heap_specs); i++) {
29032937
PyObject *type = PyType_FromModuleAndSpec(m, heap_specs[i], NULL);

‎Modules/clinic/_testclinic.c.h‎

Lines changed: 70 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Tools/clinic/libclinic/converters.py‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1437,7 +1437,7 @@ class VarKeywordCConverter(CConverter):
14371437
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
14381438
raise AssertionError('should never be called')
14391439

1440-
def parse_var_keyword(self) -> str:
1440+
def parse_var_keyword(self, *, stackargs: bool) -> str:
14411441
raise NotImplementedError
14421442

14431443

@@ -1448,6 +1448,16 @@ class var_keyword_dict_converter(VarKeywordCConverter):
14481448
def cleanup(self) -> str:
14491449
return f'Py_XDECREF({self.parser_name});\n'
14501450

1451-
def parse_var_keyword(self) -> str:
1451+
def parse_var_keyword(self, *, stackargs: bool) -> str:
14521452
# NULL when there are no keywords: no call allocates an empty dict.
1453-
return f"{self.parser_name} = Py_XNewRef(kwargs);\n"
1453+
param_name = self.parser_name
1454+
if stackargs:
1455+
return f"""
1456+
if (kwnames != NULL) {{{{
1457+
{param_name} = _PyStack_AsDict(args + nargs, kwnames);
1458+
if ({param_name} == NULL) {{{{
1459+
goto exit;
1460+
}}}}
1461+
}}}}
1462+
"""
1463+
return f"{param_name} = Py_XNewRef(kwargs);\n"

‎Tools/clinic/libclinic/dsl_parser.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -996,7 +996,7 @@ def parse_parameter(self, line: str) -> None:
996996

997997
# handle "as" for parameters too
998998
c_name = None
999-
m = re.match(r'(?:\* *)?\w+( +as +(\w+))', line)
999+
m = re.match(r'(?:\*{1,2} *)?\w+( +as +(\w+))', line)
10001000
if m:
10011001
c_name = m[2]
10021002
line = line[:m.start(1)] + line[m.end(1):]

‎Tools/clinic/libclinic/parse_args.py‎

Lines changed: 33 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -933,11 +933,11 @@ def _parse_vararg(self, *, fastcall: bool) -> str:
933933
fastcall=fastcall,
934934
limited_capi=self.limited_capi)
935935

936-
def _parse_kwarg(self) -> str:
936+
def _parse_kwarg(self, *, stackargs: bool) -> str:
937937
assert self.var_keyword is not None
938938
c = self.var_keyword.converter
939939
assert isinstance(c, libclinic.converters.VarKeywordCConverter)
940-
return c.parse_var_keyword()
940+
return c.parse_var_keyword(stackargs=stackargs)
941941

942942
def _check_positional(self, nargs: str, *,
943943
indent: int = 4) -> list[str]:
@@ -967,9 +967,8 @@ def _parse_positional_args(
967967
) -> list[str] | None:
968968
"""Emit per-parameter positional argument parsing.
969969
970-
Shared by parse_pos_only() and the vectorcall paths. Returns the
971-
code snippets, or None if a converter doesn't support parse_arg
972-
(the caller must fall back to a tuple/stack parser).
970+
Returns the code snippets, or None if a converter doesn't support
971+
parse_arg (the caller must fall back to a tuple/stack parser).
973972
"""
974973
parser_code: list[str] = []
975974
for i, p in enumerate(self.parameters):
@@ -998,9 +997,9 @@ def _parse_positional_args(
998997
if self.varpos:
999998
parser_code.append(libclinic.normalize_snippet(
1000999
self._parse_vararg(fastcall=fastcall), indent=4))
1001-
elif self.var_keyword:
1002-
parser_code.append(libclinic.normalize_snippet(self._parse_kwarg(),
1003-
indent=4))
1000+
if self.var_keyword:
1001+
parser_code.append(libclinic.normalize_snippet(
1002+
self._parse_kwarg(stackargs=fastcall), indent=4))
10041003
return parser_code
10051004

10061005
def select_positional_convention(self) -> tuple[str, str]:
@@ -1112,48 +1111,38 @@ def parse_pos_only(self) -> None:
11121111
""", indent=4))
11131112
self.parser_body(*parser_code)
11141113

1115-
def parse_var_keyword(self) -> None:
1114+
def parse_var_keyword(self, *, vectorcall: bool = False) -> None:
11161115
self.flags = "METH_VARARGS|METH_KEYWORDS"
1117-
self.parser_prototype = PARSER_PROTOTYPE_KEYWORD
1118-
nargs = 'PyTuple_GET_SIZE(args)'
1116+
# The vectorcall gets an array of arguments and kwnames, not a tuple
1117+
# and a dict: use the converters' fastcall convention, which handles
1118+
# that.
1119+
if vectorcall:
1120+
nargs, argname_fmt = 'nargs', 'args[%d]'
1121+
check, arg = '_PyArg_NoPositionalStack', 'nargs'
1122+
parser_code = self._vectorcall_type_check()
1123+
else:
1124+
self.parser_prototype = PARSER_PROTOTYPE_KEYWORD
1125+
nargs, argname_fmt = 'PyTuple_GET_SIZE(args)', 'PyTuple_GET_ITEM(args, %d)'
1126+
check, arg = '_PyArg_NoPositional', 'args'
1127+
parser_code = []
11191128

1120-
parser_code = []
11211129
if self.varpos is None and self.min_pos == self.max_pos == 0:
1122-
self.codegen.add_include('pycore_modsupport.h',
1123-
'_PyArg_NoPositional()')
1124-
parser_code.append(libclinic.normalize_snippet("""
1125-
if (!_PyArg_NoPositional("{name}", args)) {{
1130+
self.codegen.add_include('pycore_modsupport.h', f'{check}()')
1131+
parser_code.append(libclinic.normalize_snippet(f"""
1132+
if (!{check}("{{name}}", {arg})) {{{{
11261133
goto exit;
1127-
}}
1134+
}}}}
11281135
""", indent=4))
11291136
else:
11301137
parser_code.extend(self._check_positional(nargs))
11311138

1132-
has_optional = False
1133-
for i, p in enumerate(self.parameters):
1134-
parse_arg = p.converter.parse_arg(
1135-
f'PyTuple_GET_ITEM(args, {i})',
1136-
p.get_displayname(i+1),
1137-
limited_capi=self.limited_capi,
1138-
)
1139-
assert parse_arg is not None
1140-
if has_optional or p.is_optional():
1141-
has_optional = True
1142-
parser_code.append(libclinic.normalize_snippet("""
1143-
if (%s < %d) {{
1144-
goto skip_optional;
1145-
}}
1146-
""", indent=4) % (nargs, i + 1))
1147-
parser_code.append(libclinic.normalize_snippet(parse_arg, indent=4))
1148-
if has_optional:
1149-
parser_code.append("skip_optional:")
1150-
1151-
if self.varpos:
1152-
parser_code.append(libclinic.normalize_snippet(
1153-
self._parse_vararg(fastcall=self.fastcall), indent=4))
1154-
if self.var_keyword:
1155-
parser_code.append(libclinic.normalize_snippet(self._parse_kwarg(), indent=4))
1156-
self.parser_body(*parser_code)
1139+
pos_code = self._parse_positional_args(
1140+
argname_fmt=argname_fmt, nargs=nargs,
1141+
limited_capi=self.limited_capi, fastcall=vectorcall)
1142+
assert pos_code is not None
1143+
parser_code.extend(pos_code)
1144+
body = self.vectorcall_body if vectorcall else self.parser_body
1145+
body(*parser_code)
11571146

11581147
def use_converters(self) -> None:
11591148
"""Prepare for parsing all arguments by a single call.
@@ -1456,7 +1445,7 @@ def handle_new_or_init(self) -> None:
14561445
if self.func.kind is METHOD_INIT:
14571446
self.return_value_declaration = "int {parser_retval} = -1;"
14581447

1459-
if self.func.vectorcall and 'METH_KEYWORDS' in self.flags:
1448+
if self.parser_prototype == PARSER_PROTOTYPE_KEYWORD_HELPER:
14601449
self._new_or_init_delegate_to_helper()
14611450
else:
14621451
self._new_or_init_parser_body()
@@ -1624,8 +1613,6 @@ def _vectorcall_positional(self, *,
16241613
16251614
arity_checked: Already have a number of arguments check.
16261615
"""
1627-
# The vectorcall gets an array of arguments, not a tuple: use the
1628-
# converters' fastcall convention, which handles that.
16291616
pos_code = self._parse_positional_args(
16301617
argname_fmt='args[%d]', nargs='nargs', limited_capi=False,
16311618
fastcall=True)
@@ -1781,7 +1768,7 @@ def parse_vectorcall(self) -> None:
17811768
if not self.parameters and not self.varpos and not self.var_keyword:
17821769
self.parse_vectorcall_no_args()
17831770
elif self.var_keyword is not None:
1784-
self.parse_vectorcall_kw_required()
1771+
self.parse_var_keyword(vectorcall=True)
17851772
elif self.pos_only == len(self.parameters):
17861773
self.parse_vectorcall_pos_only()
17871774
elif any(p.is_keyword_only() for p in self.parameters) or self.varpos:

0 commit comments

Comments
 (0)