Skip to content

Commit 06a5b69

Browse files
committed
Remove unncessary implemeneation
1 parent 33a0522 commit 06a5b69

3 files changed

Lines changed: 49 additions & 112 deletions

File tree

‎Lib/test/test_clinic.py‎

Lines changed: 14 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,7 @@
2323
import libclinic
2424
from libclinic import ClinicError, unspecified, NULL, fail
2525
from libclinic.converters import (
26-
int_converter, object_converter, str_converter, self_converter,
27-
Py_ssize_t_converter)
26+
int_converter, object_converter, str_converter, self_converter)
2827
from libclinic.function import (
2928
Module, Class, Function, FunctionKind, Parameter,
3029
permute_optional_groups, permute_right_option_groups,
@@ -860,13 +859,8 @@ def test_slot_with_parameters_and_return_type(self):
860859
# Slots which take arguments or return something else than an
861860
# object are not supported yet; check the machinery with them.
862861
slots = {
863-
'__contains__': (
864-
SlotSpec(return_converter='int',
865-
parameters=(object_converter,)),
866-
),
867-
'__bool__': (
868-
SlotSpec(return_converter='int'),
869-
),
862+
'__contains__': SlotSpec(return_type='int'),
863+
'__bool__': SlotSpec(return_type='int'),
870864
}
871865
block = """
872866
/*[clinic input]
@@ -3357,65 +3351,38 @@ class Foo "FooObject *" ""
33573351
Foo.__next__
33583352
""", signatures_in_block=3, function_index=2)
33593353
self.assertIs(function.kind, FunctionKind.SLOT)
3360-
self.assertIs(function.slot, SLOTS["__next__"][0])
3354+
self.assertIs(function.slot, SLOTS["__next__"])
33613355
self.assertEqual(function.c_basename, "Foo_next")
33623356
self.assertEqual(function.return_converter.type, "PyObject *")
33633357
self.assertEqual(list(function.parameters), ["self"])
33643358

33653359
def test_slot_parameters(self):
3366-
# __getitem__ is not supported yet: the parameters select the slot
3367-
# (sq_item or mp_subscript).
3368-
slots = (
3369-
SlotSpec(return_converter='object',
3370-
parameters=(Py_ssize_t_converter,)),
3371-
SlotSpec(return_converter='object',
3372-
parameters=(object_converter,)),
3373-
)
3360+
# __getitem__ is not supported yet; its parameter gives the slot
3361+
# (Py_ssize_t for sq_item, object for mp_subscript) and is not parsed.
33743362
block = """
33753363
module foo
33763364
class Foo "FooObject *" ""
33773365
Foo.__getitem__
33783366
key: {converter}
33793367
/
33803368
"""
3369+
errors = [
3370+
("Foo.__getitem__\n key: object",
3371+
"The parameters of '__getitem__' must be positional-only"),
3372+
("Foo.__getitem__\n key: object = None\n /",
3373+
"The parameters of '__getitem__' cannot have a default value"),
3374+
]
33813375
supported = unsupported_special_methods - {'__getitem__'}
3382-
with (mock.patch.dict(SLOTS, {'__getitem__': slots}),
3376+
with (mock.patch.dict(SLOTS, {'__getitem__': SlotSpec(return_type='PyObject *')}),
33833377
mock.patch.object(libclinic.dsl_parser,
33843378
'unsupported_special_methods', supported)):
3385-
for converter, slot in zip(("Py_ssize_t", "object"), slots):
3379+
for converter in "Py_ssize_t", "object":
33863380
with self.subTest(converter=converter):
33873381
function = self.parse_function(
33883382
block.format(converter=converter),
33893383
signatures_in_block=3, function_index=2)
33903384
self.assertIs(function.kind, FunctionKind.SLOT)
3391-
self.assertIs(function.slot, slot)
33923385
self.assertEqual(list(function.parameters), ["self", "key"])
3393-
3394-
def test_slot_parameter_errors(self):
3395-
# __setattr__ is not planned to be supported; its two slots
3396-
# (tp_setattro and tp_setattr) make the error message list the
3397-
# alternatives.
3398-
slots = (
3399-
SlotSpec(return_converter='int',
3400-
parameters=(object_converter, object_converter)),
3401-
SlotSpec(return_converter='int',
3402-
parameters=(str_converter, object_converter)),
3403-
)
3404-
errors = [
3405-
("Foo.__setattr__",
3406-
"'__setattr__' must declare (object, object) or (str, object); "
3407-
"got ()"),
3408-
("Foo.__setattr__\n name: int\n value: object\n /",
3409-
"'__setattr__' must declare"),
3410-
("Foo.__setattr__\n name: object\n value: object",
3411-
"The parameters of '__setattr__' must be positional-only"),
3412-
("Foo.__setattr__\n name: object\n value: object = None\n /",
3413-
"The parameters of '__setattr__' cannot have a default value"),
3414-
]
3415-
supported = unsupported_special_methods - {'__setattr__'}
3416-
with (mock.patch.dict(SLOTS, {'__setattr__': slots}),
3417-
mock.patch.object(libclinic.dsl_parser,
3418-
'unsupported_special_methods', supported)):
34193386
for body, err in errors:
34203387
with self.subTest(block=body):
34213388
body = 'class Foo "FooObject *" "&Foo_Type"\n' + body
@@ -3433,8 +3400,6 @@ def test_slot_errors(self):
34333400
"@coexist cannot be applied to '__next__'"),
34343401
("@vectorcall\nFoo.__next__",
34353402
"@vectorcall can only be used with __init__ and __new__"),
3436-
("Foo.__next__\n a: int",
3437-
"'__next__' methods cannot define parameters"),
34383403
("Foo.__next__ -> int",
34393404
"'Foo.__next__' cannot define a return type"),
34403405
("Foo.__next__\n\nReturn the next item.",

‎Tools/clinic/libclinic/dsl_parser.py‎

Lines changed: 12 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -266,8 +266,7 @@ class DSLParser:
266266
critical_section: bool
267267
target_critical_section: list[str]
268268
disable_fastcall: bool
269-
# The slots which the function can implement (see libclinic.slots).
270-
slots: tuple[SlotSpec, ...]
269+
slot: SlotSpec | None
271270
# Line of the file which is being parsed.
272271
line_number: int | None
273272
from_version_re = re.compile(r'([*/]) +\[from +(.+)\]')
@@ -315,7 +314,7 @@ def reset(self) -> None:
315314
self.target_critical_section = []
316315
self.disable_fastcall = False
317316
self.vectorcall: bool = False
318-
self.slots = ()
317+
self.slot = None
319318
self.permit_long_summary = False
320319
self.permit_long_docstring_body = False
321320

@@ -634,8 +633,8 @@ def normalize_function_kind(self, fullname: str) -> None:
634633
fail("'__new__' must be a class method!")
635634
if self.kind in ACCESSORS and not cls:
636635
fail("@getter and @setter must be methods")
637-
slots = SLOTS.get(name, ())
638-
if slots:
636+
slot = SLOTS.get(name)
637+
if slot is not None:
639638
if self.kind is not CALLABLE:
640639
fail(f"{name!r} must be a normal method; got '{self.kind}'!")
641640
if not cls:
@@ -648,9 +647,9 @@ def normalize_function_kind(self, fullname: str) -> None:
648647
self.kind = METHOD_NEW
649648
elif name == '__init__':
650649
self.kind = METHOD_INIT
651-
elif slots:
650+
elif slot is not None:
652651
self.kind = SLOT
653-
self.slots = slots
652+
self.slot = slot
654653

655654
# Validate @vectorcall usage.
656655
if self.vectorcall:
@@ -694,8 +693,8 @@ def resolve_return_converter(
694693
if self.kind in {METHOD_INIT} | SETTERS:
695694
return int_return_converter()
696695
if self.kind is SLOT:
697-
# Every slot of a special method has the same return type.
698-
return return_converters[self.slots[0].return_converter]()
696+
assert self.slot is not None
697+
return self.slot.return_converter()
699698
return CReturnConverter()
700699

701700
def parse_cloned_function(self, names: FunctionNames, existing: str) -> None:
@@ -727,7 +726,7 @@ def parse_cloned_function(self, names: FunctionNames, existing: str) -> None:
727726
"docstring_line_number": None,
728727
"line_number": self.line_number,
729728
}
730-
if existing_function.kind is SLOT or self.slots:
729+
if existing_function.kind is SLOT or self.slot is not None:
731730
fail("Type slot methods cannot be cloned")
732731
if not (existing_function.kind is self.kind and
733732
existing_function.coexist == self.coexist):
@@ -803,9 +802,7 @@ def state_modulename_name(self, line: str) -> None:
803802
forced_text_signature=self.forced_text_signature,
804803
line_number=self.line_number,
805804
vectorcall=self.vectorcall,
806-
# Replaced by the slot which the parameters select, see
807-
# check_slot_parameters().
808-
slot=self.slots[0] if self.slots else None,
805+
slot=self.slot,
809806
)
810807
self.add_function(func)
811808

@@ -922,10 +919,6 @@ def state_parameters_start(self, line: str) -> None:
922919
assert self.function is not None
923920
if self.function.kind is GETTER:
924921
fail("@getter methods cannot define parameters")
925-
if self.function.kind is SLOT:
926-
if not any(slot.parameters for slot in self.slots):
927-
fail(f"{self.function.name!r} methods cannot define parameters")
928-
929922
self.parameter_continuation = ''
930923
return self.next(self.state_parameter, line)
931924

@@ -1678,22 +1671,12 @@ def check_vectorcall_parameters(self, lineno: int) -> None:
16781671
line_number=lineno)
16791672

16801673
def check_slot_parameters(self, func: Function) -> None:
1681-
"""Select the slot which the parameters of a slot method implement."""
1682-
params = list(func.parameters.values())[1:]
1683-
for p in params:
1674+
"""Check that the parameters of a slot method fit a C signature."""
1675+
for p in list(func.parameters.values())[1:]:
16841676
if not p.is_positional_only():
16851677
fail(f"The parameters of {func.name!r} must be positional-only")
16861678
if p.default is not unspecified:
16871679
fail(f"The parameters of {func.name!r} cannot have a default value")
1688-
converters = [p.converter for p in params]
1689-
for slot in self.slots:
1690-
if slot.matches(converters):
1691-
func.slot = slot
1692-
return
1693-
got = ', '.join(c.dsl_name() for c in converters)
1694-
fail(f"{func.name!r} must declare "
1695-
f"{' or '.join(slot.describe() for slot in self.slots)}; "
1696-
f"got ({got})")
16971680

16981681
def do_post_block_processing_cleanup(self, lineno: int) -> None:
16991682
"""

‎Tools/clinic/libclinic/slots.py‎

Lines changed: 23 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -5,53 +5,42 @@
55
the implementation function. The wrapper is the place where
66
``@critical_section`` acquires the lock.
77
8-
The parameters declared in the DSL only select the C signature; they must be
9-
positional-only, without a default value. When a special method maps to
10-
several slots (``__getitem__`` is ``sq_item`` or ``mp_subscript``),
11-
the converters of its parameters determine which one it implements.
8+
The parameters declared in the DSL only give the C signature of the slot;
9+
they must be positional-only, without a default value.
1210
"""
1311
from __future__ import annotations
1412
import dataclasses as dc
1513
from typing import Final
1614

17-
from libclinic.converter import CConverter
18-
from libclinic.return_converters import return_converters
15+
from libclinic.return_converters import CReturnConverter, return_converters
16+
17+
18+
# The return converter which declares each C return type of a slot.
19+
_RETURN_CONVERTERS: Final[dict[str, str]] = {
20+
'PyObject *': 'object',
21+
'Py_ssize_t': 'Py_ssize_t',
22+
'int': 'int',
23+
}
1924

2025

2126
@dc.dataclass(frozen=True, slots=True, kw_only=True)
2227
class SlotSpec:
23-
# The name of the return converter of the implementation function.
24-
return_converter: str
25-
# The converter classes of the parameters, excluding self.
26-
parameters: tuple[type[CConverter], ...] = ()
27-
28-
@property
29-
def return_type(self) -> str:
30-
"""The C return type of the slot function."""
31-
return return_converters[self.return_converter]().type
28+
# The C return type of the slot function.
29+
return_type: str
3230

3331
@property
3432
def error_value(self) -> str:
3533
"""The value returned by the slot function on error."""
3634
return 'NULL' if self.return_type.endswith('*') else '-1'
3735

38-
def matches(self, converters: list[CConverter]) -> bool:
39-
"""Return whether the parameter converters are those of the slot."""
40-
return tuple(type(c) for c in converters) == self.parameters
41-
42-
def describe(self) -> str:
43-
"""The parameters of the slot as they are declared in the DSL."""
44-
params = ', '.join(c.dsl_name() for c in self.parameters)
45-
return f"({params or 'no parameters'})"
46-
47-
48-
# Maps the name of a special method to the slots it can implement. A name
49-
# listed here must not be in dsl_parser.unsupported_special_methods.
50-
SLOTS: Final[dict[str, tuple[SlotSpec, ...]]] = {
51-
'__next__': (
52-
SlotSpec(return_converter='object'),
53-
),
54-
'__len__': (
55-
SlotSpec(return_converter='Py_ssize_t'),
56-
),
36+
def return_converter(self) -> CReturnConverter:
37+
"""The return converter of the implementation function."""
38+
return return_converters[_RETURN_CONVERTERS[self.return_type]]()
39+
40+
41+
# Maps the name of a special method to its slot. A name listed here must
42+
# not be in dsl_parser.unsupported_special_methods.
43+
SLOTS: Final[dict[str, SlotSpec]] = {
44+
'__next__': SlotSpec(return_type='PyObject *'),
45+
'__len__': SlotSpec(return_type='Py_ssize_t'),
5746
}

0 commit comments

Comments
 (0)