Skip to content

Commit 050ca71

Browse files
committed
Decide tp_new inheritance of static types at type initialization
A static type with no tp_new of its own whose base is object now gets DISALLOW_INSTANTIATION instead of inheriting object's tp_new, following type_ready_set_new. Such types no longer expose an inherited __new__. A natively defined type that inherits tp_new from its base must have the same basicsize as that base; type initialization panics otherwise. _IOBase is flagged HEAPTYPE so that it keeps inheriting object's tp_new. FutureIter, TaskStepMethWrapper, hamt, InstructionSequence and itertools._grouper get constructors of their own. Assisted-by: Claude:claude-opus-5-5 Assisted-by: Grok:grok-4.7
1 parent 76b3b00 commit 050ca71

6 files changed

Lines changed: 112 additions & 16 deletions

File tree

‎crates/stdlib/src/_asyncio.rs‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -965,7 +965,17 @@ pub(crate) mod _asyncio {
965965
future: PyRwLock<Option<PyObjectRef>>,
966966
}
967967

968-
#[pyclass(with(IterNext, Iterable))]
968+
impl Constructor for PyFutureIter {
969+
type Args = ();
970+
971+
fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> {
972+
Ok(Self {
973+
future: PyRwLock::new(None),
974+
})
975+
}
976+
}
977+
978+
#[pyclass(with(Constructor, IterNext, Iterable))]
969979
impl PyFutureIter {
970980
#[pymethod]
971981
fn send(zelf: &Py<Self>, _value: PyObjectRef, vm: &VirtualMachine) -> PyResult {
@@ -2926,7 +2936,17 @@ pub(crate) mod _asyncio {
29262936
task: PyRwLock<Option<PyObjectRef>>,
29272937
}
29282938

2929-
#[pyclass(with(Callable, Representable))]
2939+
impl Constructor for TaskStepMethWrapper {
2940+
type Args = ();
2941+
2942+
fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> {
2943+
Ok(Self {
2944+
task: PyRwLock::new(None),
2945+
})
2946+
}
2947+
}
2948+
2949+
#[pyclass(with(Constructor, Callable, Representable))]
29302950
impl TaskStepMethWrapper {
29312951
fn new(task: PyObjectRef) -> Self {
29322952
Self {

‎crates/vm/src/builtins/type.rs‎

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1213,7 +1213,7 @@ impl PyType {
12131213
// Note: inherit_slots is called in PyClassImpl::init_class after
12141214
// slots are fully initialized by make_slots()
12151215

1216-
Self::set_new(&new_type.slots, new_type.base.deref());
1216+
Self::set_new(&new_type.slots, new_type.base.deref(), false);
12171217
Self::set_alloc(&new_type.slots, new_type.base.deref());
12181218

12191219
let weakref_type = super::PyWeak::static_type();
@@ -1265,7 +1265,7 @@ impl PyType {
12651265
self.update_slot::<true>(attr_name, ctx);
12661266
}
12671267

1268-
Self::set_new(&self.slots, self.base.deref());
1268+
Self::set_new(&self.slots, self.base.deref(), true);
12691269
Self::set_alloc(&self.slots, self.base.deref());
12701270
}
12711271

@@ -1289,11 +1289,38 @@ impl PyType {
12891289
}
12901290
}
12911291

1292-
fn set_new(slots: &PyTypeSlots, base: Option<&Py<Self>>) {
1292+
/// type_ready_set_new: a static type with no tp_new whose base is object
1293+
/// gets DISALLOW_INSTANTIATION and keeps tp_new unset. Heap types inherit
1294+
/// the base's tp_new. A natively defined type that inherits a non-NULL
1295+
/// tp_new must have the same basicsize as that base, because the inherited
1296+
/// function allocates the base payload. `heap` is true only for classes
1297+
/// created at runtime, whose instances reuse the base payload.
1298+
fn set_new(slots: &PyTypeSlots, base: Option<&Py<Self>>, heap: bool) {
1299+
let is_heap = heap || slots.flags.has_feature(PyTypeFlags::HEAPTYPE);
1300+
1301+
if !is_heap
1302+
&& slots.new.load().is_none()
1303+
&& base.is_some_and(|b| core::ptr::eq(b, object::PyBaseObject::static_type()))
1304+
{
1305+
slots.flags.insert(PyTypeFlags::DISALLOW_INSTANTIATION);
1306+
}
1307+
12931308
if slots.flags.has_feature(PyTypeFlags::DISALLOW_INSTANTIATION) {
1294-
slots.new.store(None)
1309+
slots.new.store(None);
12951310
} else if slots.new.load().is_none() {
1296-
slots.new.store(base.and_then(|base| base.slots.new.load()))
1311+
let inherited = base.and_then(|base| base.slots.new.load());
1312+
if !heap
1313+
&& inherited.is_some()
1314+
&& let Some(base) = base
1315+
&& slots.basicsize != base.slots.basicsize
1316+
{
1317+
panic!(
1318+
"static type '{}' inherits tp_new from '{}' but basicsize {} != {}; \
1319+
the inherited tp_new allocates the base payload",
1320+
slots.name, base.slots.name, slots.basicsize, base.slots.basicsize
1321+
);
1322+
}
1323+
slots.new.store(inherited);
12971324
}
12981325
}
12991326

@@ -1306,7 +1333,7 @@ impl PyType {
13061333
}
13071334

13081335
pub(crate) fn finalize_bootstrap_static(typ: &Py<Self>) {
1309-
Self::set_new(&typ.slots, typ.base.deref());
1336+
Self::set_new(&typ.slots, typ.base.deref(), false);
13101337
Self::set_alloc(&typ.slots, typ.base.deref());
13111338
}
13121339

‎crates/vm/src/class.rs‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -367,8 +367,14 @@ pub trait PyClassImpl: PyClassDef {
367367

368368
// Don't add __new__ attribute if slot_new is inherited from object
369369
// (Python doesn't add __new__ to __dict__ for inherited slots)
370-
// Exception: object itself should have __new__ in its dict
371-
if let Some(slot_new) = class.slots().new.load() {
370+
// Exception: object itself should have __new__ in its dict.
371+
// DISALLOW_INSTANTIATION types must not expose an inherited __new__.
372+
if !class
373+
.slots()
374+
.flags
375+
.has_feature(PyTypeFlags::DISALLOW_INSTANTIATION)
376+
&& let Some(slot_new) = class.slots().new.load()
377+
{
372378
let object_new = ctx.types.object_type.slots().new.load();
373379
let is_object_itself = core::ptr::eq(class, ctx.types.object_type);
374380
let is_inherited_from_object = !is_object_itself

‎crates/vm/src/stdlib/_io.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -520,7 +520,7 @@ mod _io {
520520

521521
#[pyclass(
522522
with(IterNext, Iterable, Destructor),
523-
flags(BASETYPE, HAS_DICT, HAS_WEAKREF)
523+
flags(BASETYPE, HAS_DICT, HAS_WEAKREF, HEAPTYPE)
524524
)]
525525
impl _IOBase {
526526
#[pymethod]

‎crates/vm/src/stdlib/_testinternalcapi.rs‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,8 @@ mod _testinternalcapi {
4242
protocol::{PyIterReturn, PyMappingMethods, PySequenceMethods},
4343
stdlib::time::pytime::{self, Round},
4444
types::{
45-
AsMapping, AsSequence, Comparable, IterNext, Iterable, PyComparisonOp, PyTypeFlags,
46-
SelfIter,
45+
AsMapping, AsSequence, Comparable, Constructor, IterNext, Iterable, PyComparisonOp,
46+
PyTypeFlags, SelfIter,
4747
},
4848
};
4949
#[cfg(any(unix, windows))]
@@ -779,7 +779,18 @@ mod _testinternalcapi {
779779
}
780780
}
781781

782-
#[pyclass(flags(HAS_WEAKREF), with(AsMapping, AsSequence, Comparable, Iterable))]
782+
impl Constructor for Hamt {
783+
type Args = ();
784+
785+
fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> {
786+
Ok(Self::default())
787+
}
788+
}
789+
790+
#[pyclass(
791+
flags(HAS_WEAKREF),
792+
with(Constructor, AsMapping, AsSequence, Comparable, Iterable)
793+
)]
783794
impl Py<Hamt> {
784795
#[pymethod]
785796
fn set(
@@ -1122,7 +1133,16 @@ mod _testinternalcapi {
11221133
}
11231134

11241135
#[cfg(feature = "codegen")]
1125-
#[pyclass(with(Py))]
1136+
impl Constructor for PyInstructionSequence {
1137+
type Args = ();
1138+
1139+
fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> {
1140+
Ok(Self::empty())
1141+
}
1142+
}
1143+
1144+
#[cfg(feature = "codegen")]
1145+
#[pyclass(with(Constructor, Py))]
11261146
impl PyInstructionSequence {}
11271147

11281148
#[cfg(feature = "codegen")]

‎crates/vm/src/stdlib/itertools.rs‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -706,7 +706,30 @@ mod decl {
706706
tgtkey: PyObjectRef,
707707
}
708708

709-
#[pyclass(with(IterNext, Iterable), flags(HAS_WEAKREF))]
709+
#[derive(FromArgs)]
710+
struct GrouperArgs {
711+
#[pyarg(positional)]
712+
parent: PyRef<PyItertoolsGroupBy>,
713+
#[pyarg(positional)]
714+
tgtkey: PyObjectRef,
715+
}
716+
717+
impl Constructor for PyItertoolsGrouper {
718+
type Args = GrouperArgs;
719+
720+
fn py_new(
721+
_cls: &Py<PyType>,
722+
Self::Args { parent, tgtkey }: Self::Args,
723+
_vm: &VirtualMachine,
724+
) -> PyResult<Self> {
725+
Ok(Self {
726+
groupby: parent,
727+
tgtkey,
728+
})
729+
}
730+
}
731+
732+
#[pyclass(with(Constructor, IterNext, Iterable), flags(HAS_WEAKREF))]
710733
impl PyItertoolsGrouper {}
711734

712735
impl SelfIter for PyItertoolsGrouper {}

0 commit comments

Comments
 (0)