Skip to content

Commit a5b24a4

Browse files
committed
Prepare interpreter-local runtime state and thread lifecycle
Assisted-by: Codex:GPT-6
1 parent ada43c4 commit a5b24a4

183 files changed

Lines changed: 7215 additions & 3380 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎Lib/test/test_descr.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1865,7 +1865,6 @@ class D(C):
18651865
self.assertEqual(b.foo, 3)
18661866
self.assertEqual(b.__class__, D)
18671867

1868-
@unittest.expectedSuccess # TODO: RUSTPYTHON; The `expectedFailure` here is from CPython, so this test must fail
18691868
@unittest.expectedFailure
18701869
def test_bad_new(self):
18711870
self.assertRaises(TypeError, object.__new__)

‎benches/execution.rs‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -39,17 +39,19 @@ fn bench_rustpython_code(b: &mut Bencher<'_>, name: &str, source: &str) {
3939
settings.write_bytecode = false;
4040
settings.user_site_directory = false;
4141
let builder = Interpreter::builder(settings);
42-
let defs = rustpython_stdlib::stdlib_module_defs(&builder.ctx);
43-
builder.add_native_modules(&defs).build().enter(|vm| {
44-
// Note: bench_cpython is both compiling and executing the code.
45-
// As such we compile the code in the benchmark loop as well.
46-
b.iter(|| {
47-
let code = vm.compile(source, Mode::Exec, name).unwrap();
48-
let scope = vm.new_scope_with_builtins();
49-
let res: PyResult = vm.run_code_obj(code, scope);
50-
vm.unwrap_pyresult(res);
42+
let defs = rustpython_stdlib::stdlib_module_defs(unsafe { builder.context() });
43+
unsafe { builder.add_native_modules(&defs) }
44+
.build()
45+
.enter(|vm| {
46+
// Note: bench_cpython is both compiling and executing the code.
47+
// As such we compile the code in the benchmark loop as well.
48+
b.iter(|| {
49+
let code = vm.compile(source, Mode::Exec, name).unwrap();
50+
let scope = vm.new_scope_with_builtins();
51+
let res: PyResult = vm.run_code_obj(code, scope);
52+
vm.unwrap_pyresult(res);
53+
})
5154
})
52-
})
5355
}
5456

5557
pub fn benchmark_file_execution(

‎benches/microbenchmarks.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,8 +111,8 @@ fn bench_rustpython_code(group: &mut BenchmarkGroup<'_, WallTime>, bench: &Micro
111111
settings.user_site_directory = false;
112112

113113
let builder = Interpreter::builder(settings);
114-
let defs = rustpython_stdlib::stdlib_module_defs(&builder.ctx);
115-
let interp = builder.add_native_modules(&defs).build();
114+
let defs = rustpython_stdlib::stdlib_module_defs(unsafe { builder.context() });
115+
let interp = unsafe { builder.add_native_modules(&defs) }.build();
116116
interp.enter(|vm| {
117117
let setup_code = vm
118118
.compile(&bench.setup, Mode::Exec, &bench.name)

‎crates/capi/src/bytearrayobject.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,9 @@ pub unsafe extern "C" fn PyByteArray_Size(bytearray: *mut PyObject) -> isize {
5959
pub unsafe extern "C" fn PyByteArray_AsString(bytearray: *mut PyObject) -> *mut c_char {
6060
with_vm(|vm| {
6161
let bytearray = unsafe { bytearray.assume_borrowed_and_cast::<PyByteArray>(vm) }?;
62-
Ok(bytearray.borrow_buf_mut().as_mut_ptr())
62+
// SAFETY: the C caller owns the PyByteArray_AsString lifetime and
63+
// synchronization contract; no resizable Rust Vec escapes this API.
64+
Ok(unsafe { bytearray.as_mut_ptr_unchecked() })
6365
})
6466
}
6567

‎crates/capi/src/ceval.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ mod tests {
180180
#[pyfunction]
181181
fn legacy_locals_is_frame_mapping() -> bool {
182182
let locals = super::PyEval_GetLocals();
183-
rustpython_vm::vm::thread::with_current_vm(|vm| {
183+
crate::pystate::with_current_vm(|vm| {
184184
let frame = vm.current_frame().unwrap();
185185
core::ptr::eq(
186186
locals.cast_const(),

‎crates/capi/src/descrobject.rs‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use crate::pystate::with_vm;
55
use crate::util::{CStrExt, FfiPtrExt};
66
use core::ffi::{c_char, c_int, c_void};
77
use rustpython_vm::builtins::{
8-
DescriptorMemberDef, MemberAccess, MemberKind, PyDescriptorOwned, PyGetSet, PyMappingProxy,
8+
DescriptorMemberDef, MemberAccess, MemberKind, PyDescriptor, PyGetSet, PyMappingProxy,
99
PyMemberDescriptor, PyMemberFlags, PyType,
1010
};
1111
use rustpython_vm::common::lock::PyRwLock;
@@ -40,11 +40,7 @@ impl PyGetSetDef {
4040
}
4141
})
4242
}
43-
pub(crate) fn build(
44-
&self,
45-
ty: &'static Py<PyType>,
46-
vm: &VirtualMachine,
47-
) -> PyResult<PyRef<PyGetSet>> {
43+
pub(crate) fn build(&self, ty: &Py<PyType>, vm: &VirtualMachine) -> PyResult<PyRef<PyGetSet>> {
4844
let name = unsafe { self.name.try_as_str(vm) }?;
4945
let closure = self.closure as usize;
5046

@@ -167,7 +163,7 @@ impl PyMemberDef {
167163
});
168164

169165
let descriptor = PyMemberDescriptor {
170-
common: PyDescriptorOwned {
166+
common: PyDescriptor {
171167
typ: ty.to_owned(),
172168
name: vm.ctx.intern_str(name),
173169
qualname: PyRwLock::new(None),

‎crates/capi/src/lib.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ pub fn init_main_interpreter(interpreter: Interpreter) {
6363
let mut interp = get_main_interpreter();
6464
assert!(interp.is_none(), "Main interpreter is already set");
6565
// Safety: Interpreter was not initialized before, so we can safely assume the statics are not used
66-
unsafe { init_exception_statics(&Context::genesis().exceptions) };
66+
unsafe { init_exception_statics(&Context::genesis_unchecked().exceptions) };
6767
*interp = Some(interpreter);
6868
MAIN_INTERP_PTR.store(
6969
interp.as_ref().unwrap() as *const _ as *mut _,

‎crates/capi/src/object/pytype.rs‎

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ pub unsafe extern "C" fn Py_IS_TYPE(op: *mut PyObject, ty: *mut PyTypeObject) ->
5858
#[unsafe(no_mangle)]
5959
pub unsafe extern "C" fn PyType_GetFlags(ptr: *mut PyTypeObject) -> c_ulong {
6060
let ty = unsafe { ptr.assume_borrowed() };
61-
ty.slots.flags.load().bits() as u32 as c_ulong
61+
ty.effective_flags().bits() as u32 as c_ulong
6262
}
6363

6464
#[unsafe(no_mangle)]
@@ -227,27 +227,20 @@ pub extern "C" fn PyType_FromSlots(slots: *const PySlot) -> *mut PyObject {
227227
|msg| vm.new_system_error(format!("Failed to create type from slots: {msg}")),
228228
)?;
229229

230-
let attrs = &class.attributes;
231-
let class_static = unsafe { &*((&*class) as *const _) };
230+
let attrs = class.attributes();
232231
for (name, method) in methods {
233232
attrs.insert(
234233
vm.ctx.intern_str(name),
235-
method.build_method(class_static, vm).into(),
234+
method.build_method(&class, vm).into(),
236235
);
237236
}
238237
for getset in getsets {
239238
let name = unsafe { getset.name.try_as_str(vm)? };
240-
attrs.insert(
241-
vm.ctx.intern_str(name),
242-
getset.build(class_static, vm)?.into(),
243-
);
239+
attrs.insert(vm.ctx.intern_str(name), getset.build(&class, vm)?.into());
244240
}
245241
for member in members {
246242
let name = unsafe { member.name.try_as_str(vm)? };
247-
attrs.insert(
248-
vm.ctx.intern_str(name),
249-
member.build(class_static, vm)?.into(),
250-
);
243+
attrs.insert(vm.ctx.intern_str(name), member.build(&class, vm)?.into());
251244
}
252245

253246
Ok(class)

‎crates/capi/src/pyframe.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ mod tests {
4141
use rustpython_vm::AsObject;
4242

4343
fn current_frame_ptr() -> *mut super::PyFrameObject {
44-
rustpython_vm::vm::thread::with_current_vm(|vm| {
44+
crate::pystate::with_current_vm(|vm| {
4545
vm.current_frame()
4646
.unwrap()
4747
.as_object()
@@ -83,7 +83,7 @@ mod tests {
8383

8484
#[pyfunction]
8585
fn frame_globals_is_globals() -> bool {
86-
rustpython_vm::vm::thread::with_current_vm(|vm| {
86+
crate::pystate::with_current_vm(|vm| {
8787
let frame = vm.current_frame().unwrap();
8888
let got = unsafe { super::PyFrame_GetGlobals(current_frame_ptr()) };
8989
let expected = frame.iframe().globals().as_object().as_raw();
@@ -95,7 +95,7 @@ mod tests {
9595

9696
#[pyfunction]
9797
fn frame_builtins_is_builtins() -> bool {
98-
rustpython_vm::vm::thread::with_current_vm(|vm| {
98+
crate::pystate::with_current_vm(|vm| {
9999
let frame = vm.current_frame().unwrap();
100100
let got = unsafe { super::PyFrame_GetBuiltins(current_frame_ptr()) };
101101
let expected = frame.iframe().builtins().as_object().as_raw();

‎crates/capi/src/pylifecycle.rs‎

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ use crate::pystate::ensure_thread_has_vm_attached;
44
use alloc::ffi::CString;
55
use core::ffi::{c_char, c_int, c_ulong};
66
use core::sync::atomic::{AtomicPtr, Ordering};
7-
use rustpython_vm::common::rc::PyRc;
87
use rustpython_vm::stdlib::sys;
98
use rustpython_vm::version::{MAJOR, MICRO, MINOR, RUSTPYTHON_BUILD_INFO, VERSION_HEX};
109
use rustpython_vm::vm::thread::ThreadedVirtualMachine;
@@ -19,7 +18,7 @@ pub(crate) fn request_vm_from_interpreter() -> ThreadedVirtualMachine {
1918
get_main_interpreter()
2019
.as_ref()
2120
.expect("Interpreter not initialized")
22-
.enter(|vm| vm.new_thread())
21+
.new_thread()
2322
}
2423

2524
#[unsafe(no_mangle)]
@@ -40,20 +39,21 @@ pub extern "C" fn Py_InitializeEx(_initsigs: c_int) {
4039
let mut interp = get_main_interpreter();
4140
if interp.is_none() {
4241
// Safety: Interpreter was not initialized before, so we can safely assume the statics are not used
43-
unsafe { init_exception_statics(&Context::genesis().exceptions) };
42+
unsafe { init_exception_statics(&Context::genesis_unchecked().exceptions) };
4443
let builder = Interpreter::builder(Default::default());
45-
let defs = rustpython_stdlib::stdlib_module_defs(&builder.ctx);
46-
*interp = builder
47-
.add_native_modules(&defs)
48-
.init_hook(|vm| {
49-
let state = PyRc::get_mut(&mut vm.state).unwrap();
50-
let path = rustpython_pylib::LIB_PATH.to_owned();
51-
52-
state.config.paths.stdlib_dir = Some(path.clone());
53-
state.config.paths.module_search_paths.insert(0, path);
54-
})
55-
.build()
56-
.into();
44+
let defs = rustpython_stdlib::stdlib_module_defs(unsafe { builder.context() });
45+
*interp = unsafe {
46+
builder
47+
.add_native_modules(&defs)
48+
.configure(|config| {
49+
let path = rustpython_pylib::LIB_PATH.to_owned();
50+
51+
config.paths.stdlib_dir = Some(path.clone());
52+
config.paths.module_search_paths.insert(0, path);
53+
})
54+
.build()
55+
.into()
56+
};
5757
MAIN_INTERP_PTR.store(
5858
interp.as_ref().unwrap() as *const _ as *mut _,
5959
Ordering::Release,

0 commit comments

Comments
 (0)