Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions Lib/test/test_clinic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1847,6 +1847,15 @@ def test_c_name(self):
""")
self.assertEqual("os_stat_fn", function.c_basename)

def test_var_keyword_c_name(self):
function = self.parse_function("""
module foo
foo.bar
**kwargs as kwds: dict
""")
p = function.parameters['kwargs_as_kwds']
self.assertEqual("kwds", p.converter.name)

def test_base_invalid_syntax(self):
block = """
module os
Expand Down Expand Up @@ -5846,6 +5855,20 @@ def test_vc_kwonly_missing_required(self):
with self.assertRaises(TypeError):
ac_tester.VcKwOnly()

def test_vc_kwds(self):
with self.assertRaises(TypeError):
ac_tester.VcKwds()
with self.assertRaises(TypeError):
ac_tester.VcKwds(y='y')
with self.assertRaises(TypeError):
ac_tester.VcKwds(1, 2, 3)
self.assertEqual(ac_tester.VcKwds(1), (1, None, None))
self.assertEqual(ac_tester.VcKwds(1, 2), (1, 2, None))
self.assertEqual(ac_tester.VcKwds(1, a='a', b='b'),
(1, None, {'a': 'a', 'b': 'b'}))
kwds = {'y': 'y', 'z': 'z'}
self.assertEqual(ac_tester.VcKwds(1, 2, **kwds), (1, 2, kwds))

def test_parse_errors_match_slot(self):
# tp_vectorcall and tp_new/tp_init slot should match in argument parsing
# error messages. Explicit calls to __new__ and __init__, as well as
Expand All @@ -5871,6 +5894,7 @@ def through_init(cls):
through_new(ac_tester.VcNew),
through_new(ac_tester.VcNewBase),
through_new(ac_tester.VcKwOnly),
through_new(ac_tester.VcKwds),
through_init(ac_tester.VcInit),
]
invalid_calls = [
Expand Down
33 changes: 33 additions & 0 deletions Modules/_testclinic.c
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ custom_converter(PyObject *obj, custom_t *val)
static PyTypeObject VcNew_Type;
static PyTypeObject VcNewBase_Type;
static PyTypeObject VcKwOnly_Type;
static PyTypeObject VcKwds_Type;
#include "clinic/_testclinic.c.h"


Expand Down Expand Up @@ -2671,6 +2672,37 @@ static PyTypeObject VcKwOnly_Type = {
};


/* VcKwds: @vectorcall + **kwargs. __new__ returns the parsed arguments. */

/*[clinic input]
class _testclinic.VcKwds "PyObject *" "&VcKwds_Type"
@classmethod
@vectorcall
_testclinic.VcKwds.__new__ as vc_kwds_new
a: object
b: object = None
/
**kwds: dict
[clinic start generated code]*/

static PyObject *
vc_kwds_new_impl(PyTypeObject *type, PyObject *a, PyObject *b,
PyObject *kwds)
/*[clinic end generated code: output=481e680d2e76fdbd input=1c27337c5efd9a79]*/
{
return pack_arguments_newref(3, a, b, kwds);
}

static PyTypeObject VcKwds_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "_testclinic.VcKwds",
.tp_basicsize = sizeof(PyObject),
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_new = vc_kwds_new,
.tp_vectorcall = vc_kwds_vectorcall,
};



/*[clinic input]
output push
Expand Down Expand Up @@ -2886,6 +2918,7 @@ _testclinic_exec(PyObject *m)
{
PyTypeObject *static_types[] = {
&TestClass, &VcNew_Type, &VcNewBase_Type, &VcKwOnly_Type,
&VcKwds_Type,
};
for (size_t i = 0; i < Py_ARRAY_LENGTH(static_types); i++) {
if (PyModule_AddType(m, static_types[i]) < 0) {
Expand Down
71 changes: 70 additions & 1 deletion Modules/clinic/_testclinic.c.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 13 additions & 3 deletions Tools/clinic/libclinic/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -1437,7 +1437,7 @@ class VarKeywordCConverter(CConverter):
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
raise AssertionError('should never be called')

def parse_var_keyword(self) -> str:
def parse_var_keyword(self, *, stackargs: bool) -> str:
raise NotImplementedError


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

def parse_var_keyword(self) -> str:
def parse_var_keyword(self, *, stackargs: bool) -> str:
# NULL when there are no keywords: no call allocates an empty dict.
return f"{self.parser_name} = Py_XNewRef(kwargs);\n"
param_name = self.parser_name
if stackargs:
return f"""
if (kwnames != NULL) {{{{
{param_name} = _PyStack_AsDict(args + nargs, kwnames);
if ({param_name} == NULL) {{{{
goto exit;
}}}}
}}}}
"""
return f"{param_name} = Py_XNewRef(kwargs);\n"
2 changes: 1 addition & 1 deletion Tools/clinic/libclinic/dsl_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -996,7 +996,7 @@ def parse_parameter(self, line: str) -> None:

# handle "as" for parameters too
c_name = None
m = re.match(r'(?:\* *)?\w+( +as +(\w+))', line)
m = re.match(r'(?:\*{1,2} *)?\w+( +as +(\w+))', line)
if m:
c_name = m[2]
line = line[:m.start(1)] + line[m.end(1):]
Expand Down
79 changes: 33 additions & 46 deletions Tools/clinic/libclinic/parse_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -933,11 +933,11 @@ def _parse_vararg(self, *, fastcall: bool) -> str:
fastcall=fastcall,
limited_capi=self.limited_capi)

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

def _check_positional(self, nargs: str, *,
indent: int = 4) -> list[str]:
Expand Down Expand Up @@ -967,9 +967,8 @@ def _parse_positional_args(
) -> list[str] | None:
"""Emit per-parameter positional argument parsing.

Shared by parse_pos_only() and the vectorcall paths. Returns the
code snippets, or None if a converter doesn't support parse_arg
(the caller must fall back to a tuple/stack parser).
Returns the code snippets, or None if a converter doesn't support
parse_arg (the caller must fall back to a tuple/stack parser).
"""
parser_code: list[str] = []
for i, p in enumerate(self.parameters):
Expand Down Expand Up @@ -998,9 +997,9 @@ def _parse_positional_args(
if self.varpos:
parser_code.append(libclinic.normalize_snippet(
self._parse_vararg(fastcall=fastcall), indent=4))
elif self.var_keyword:
parser_code.append(libclinic.normalize_snippet(self._parse_kwarg(),
indent=4))
if self.var_keyword:
parser_code.append(libclinic.normalize_snippet(
self._parse_kwarg(stackargs=fastcall), indent=4))
return parser_code

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

def parse_var_keyword(self) -> None:
def parse_var_keyword(self, *, vectorcall: bool = False) -> None:
self.flags = "METH_VARARGS|METH_KEYWORDS"
self.parser_prototype = PARSER_PROTOTYPE_KEYWORD
nargs = 'PyTuple_GET_SIZE(args)'
# The vectorcall gets an array of arguments and kwnames, not a tuple
# and a dict: use the converters' fastcall convention, which handles
# that.
if vectorcall:
nargs, argname_fmt = 'nargs', 'args[%d]'
check, arg = '_PyArg_NoPositionalStack', 'nargs'
parser_code = self._vectorcall_type_check()
else:
self.parser_prototype = PARSER_PROTOTYPE_KEYWORD
nargs, argname_fmt = 'PyTuple_GET_SIZE(args)', 'PyTuple_GET_ITEM(args, %d)'
check, arg = '_PyArg_NoPositional', 'args'
parser_code = []

parser_code = []
if self.varpos is None and self.min_pos == self.max_pos == 0:
self.codegen.add_include('pycore_modsupport.h',
'_PyArg_NoPositional()')
parser_code.append(libclinic.normalize_snippet("""
if (!_PyArg_NoPositional("{name}", args)) {{
self.codegen.add_include('pycore_modsupport.h', f'{check}()')
parser_code.append(libclinic.normalize_snippet(f"""
if (!{check}("{{name}}", {arg})) {{{{
goto exit;
}}
}}}}
""", indent=4))
else:
parser_code.extend(self._check_positional(nargs))

has_optional = False
for i, p in enumerate(self.parameters):
parse_arg = p.converter.parse_arg(
f'PyTuple_GET_ITEM(args, {i})',
p.get_displayname(i+1),
limited_capi=self.limited_capi,
)
assert parse_arg is not None
if has_optional or p.is_optional():
has_optional = True
parser_code.append(libclinic.normalize_snippet("""
if (%s < %d) {{
goto skip_optional;
}}
""", indent=4) % (nargs, i + 1))
parser_code.append(libclinic.normalize_snippet(parse_arg, indent=4))
if has_optional:
parser_code.append("skip_optional:")

if self.varpos:
parser_code.append(libclinic.normalize_snippet(
self._parse_vararg(fastcall=self.fastcall), indent=4))
if self.var_keyword:
parser_code.append(libclinic.normalize_snippet(self._parse_kwarg(), indent=4))
self.parser_body(*parser_code)
pos_code = self._parse_positional_args(
argname_fmt=argname_fmt, nargs=nargs,
limited_capi=self.limited_capi, fastcall=vectorcall)
assert pos_code is not None
parser_code.extend(pos_code)
body = self.vectorcall_body if vectorcall else self.parser_body
body(*parser_code)

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

if self.func.vectorcall and 'METH_KEYWORDS' in self.flags:
if self.parser_prototype == PARSER_PROTOTYPE_KEYWORD_HELPER:
self._new_or_init_delegate_to_helper()
else:
self._new_or_init_parser_body()
Expand Down Expand Up @@ -1624,8 +1613,6 @@ def _vectorcall_positional(self, *,

arity_checked: Already have a number of arguments check.
"""
# The vectorcall gets an array of arguments, not a tuple: use the
# converters' fastcall convention, which handles that.
pos_code = self._parse_positional_args(
argname_fmt='args[%d]', nargs='nargs', limited_capi=False,
fastcall=True)
Expand Down Expand Up @@ -1781,7 +1768,7 @@ def parse_vectorcall(self) -> None:
if not self.parameters and not self.varpos and not self.var_keyword:
self.parse_vectorcall_no_args()
elif self.var_keyword is not None:
self.parse_vectorcall_kw_required()
self.parse_var_keyword(vectorcall=True)
elif self.pos_only == len(self.parameters):
self.parse_vectorcall_pos_only()
elif any(p.is_keyword_only() for p in self.parameters) or self.varpos:
Expand Down
Loading