GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Align builtin iterator controls and callback lifetimes by youknowdot · Pull Request #9699 · RustPython/RustPython

Align builtin iterator controls and callback lifetimes #9699

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
youknowone merged 6 commits into RustPython:main from youknowdot:fix/builtin-iterator-controls-20261104
Nov 6, 2026
+578 −230
Merged

Align builtin iterator controls and callback lifetimes #9699

Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
6 commits
Select commit Hold shift + click to select a range
5d227f7
Align builtin iterator controls and callback lifetimes
youknowdot Nov 4, 2026
2bdbe04
Share generic sequence iterator callback controls
youknowdot Nov 4, 2026
3ac5895
Share strict iterator ssize conversion
youknowdot Nov 4, 2026
163c697
Align reversed construction and proxy dispatch
youknowdot Nov 4, 2026
2673882
Return reversed reduction without redundant result wrapper
youknowdot Nov 4, 2026
46ff99a
Return integers from byte sequence item slots
youknowdot Nov 5, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view
Prev Previous commit
Next Next commit
Share generic sequence iterator callback controls
Keep sequence callbacks outside state locks and match forward/reverse state, exhaustion and signed-wrap behavior without changing native container iterators.

Assisted-by: OpenAI Codex:model version not exposed
  • Loading branch information

Uh oh!

There was an error while loading. Please reload this page.

@youknowdot @codex
youknowdot authored and codex committed Nov 6, 2026
commit 2bdbe0427454a64cd509b9ba1210971c0f0322bb

There are no files selected for viewing

37 changes: 14 additions & 23 deletions 37 crates/vm/src/builtins/enumerate.rs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use super::{
IterStatus, PositionIterInternal, PyGenericAlias, PyTupleRef, PyType, PyTypeRef,
iter::builtins_reversed, locked_rev_next,
PyGenericAlias, PyTupleRef, PyType, PyTypeRef,
iter::{SequenceIter, SequenceIterDirection, builtins_reversed},
};
use crate::common::lock::{PyMutex, PyRwLock};
use crate::common::lock::PyRwLock;
use crate::{
AsObject, Context, Py, PyObjectRef, PyPayload, PyResult, VirtualMachine,
class::PyClassImpl,
Expand Down Expand Up @@ -139,7 +139,7 @@ impl IterNext for PyEnumerate {
#[pyclass(module = false, name = "reversed", traverse)]
#[derive(Debug)]
pub(crate) struct PyReverseSequenceIterator {
internal: PyMutex<PositionIterInternal<PyObjectRef>>,
internal: SequenceIter,
}

impl PyPayload for PyReverseSequenceIterator {
Expand All @@ -151,9 +151,9 @@ impl PyPayload for PyReverseSequenceIterator {

impl PyReverseSequenceIterator {
pub(crate) const fn new(obj: PyObjectRef, len: usize) -> Self {
let position = len.saturating_sub(1);
let position = len as isize - 1;
Self {
internal: PyMutex::new(PositionIterInternal::new(obj, position)),
internal: SequenceIter::new(obj, position, SequenceIterDirection::Reverse),
}
}
}
Expand All @@ -162,38 +162,29 @@ impl PyReverseSequenceIterator {
impl Py<PyReverseSequenceIterator> {
#[pymethod]
fn __length_hint__(&self, vm: &VirtualMachine) -> PyResult<usize> {
let internal = self.internal.lock();
if let IterStatus::Active(obj) = &internal.status
&& internal.position <= obj.length(vm)?
{
return Ok(internal.position + 1);
}
Ok(0)
vm.with_recursion(" in __length_hint__", || {
self.internal
.length_hint(vm)
.map(|length| length.unwrap_or(0))
})
}

#[pymethod]
fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.internal.lock().set_state(&state, |_, pos| pos, vm)
self.internal.set_state(&state, vm)
}

#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
let func = builtins_reversed(vm)?;
Ok(self.internal.lock().reduce(
func,
|x| x.clone(),
|vm| vm.ctx.empty_tuple.clone().into(),
vm,
))
Ok(self.internal.reduce(func, vm))
}
}

impl SelfIter for PyReverseSequenceIterator {}
impl IterNext for PyReverseSequenceIterator {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
locked_rev_next(&zelf.internal, |obj, pos| {
PyIterReturn::from_getitem_result(obj.get_item(&pos, vm), vm)
})
zelf.internal.next(vm)
}
}

Expand Down
242 changes: 211 additions & 31 deletions 242 crates/vm/src/builtins/iter.rs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -224,10 +224,212 @@ pub fn builtins_reversed(vm: &VirtualMachine) -> PyResult {
vm.eval_get_builtin(vm.ctx.intern_str("reversed"))
}

#[derive(Debug, Clone, Copy)]
pub(crate) enum SequenceIterDirection {
Forward,
Reverse,
}

#[derive(Debug, Traverse)]
struct SequenceIterState {
sequence: Option<PyObjectRef>,
#[pytraverse(skip)]
index: isize,
}

/// State for generic iterators whose sequence slots can execute Python code.
/// Unlike the concrete container iterators, these must release their state
/// lock before invoking a slot, allocating a Python object, or dropping an owner.
#[derive(Debug, Traverse)]
pub(crate) struct SequenceIter {
state: PyMutex<SequenceIterState>,
#[pytraverse(skip)]
direction: SequenceIterDirection,
}

impl SequenceIter {
pub(crate) const fn new(
sequence: PyObjectRef,
index: isize,
direction: SequenceIterDirection,
) -> Self {
Self {
state: PyMutex::new(SequenceIterState {
sequence: Some(sequence),
index,
}),
direction,
}
}

fn snapshot(&self) -> (Option<PyObjectRef>, isize) {
let state = self.state.lock();
(state.sequence.clone(), state.index)
}

fn exhaust(&self) {
let released = {
let mut state = self.state.lock();
if matches!(self.direction, SequenceIterDirection::Reverse) {
state.index = -1;
}
state.sequence.take()
};
drop(released);
}

fn get_item(sequence: &PyObject, mut index: isize, vm: &VirtualMachine) -> PyResult {
let seq = sequence.sequence_unchecked();
// A reentrant state change can wrap the forward index below zero.
// PySequence_GetItem adjusts it once using the sequence length slot.
// Keep this separate from the concrete containers' index handling.
if index < 0
&& seq.slots().has_item()
&& let Some(length) = seq.length_opt(vm)
{
index = index.wrapping_add(length? as isize);
}
seq.get_item(index, vm)
}

pub(crate) fn next(&self, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
let (sequence, index) = self.snapshot();
let Some(sequence) = sequence else {
return Ok(PyIterReturn::StopIteration(None));
};
match self.direction {
SequenceIterDirection::Forward if index == isize::MAX => {
drop(sequence);
return Err(vm.new_overflow_error("iter index too large"));
}
SequenceIterDirection::Reverse if index < 0 => {
drop(sequence);
self.exhaust();
return Ok(PyIterReturn::StopIteration(None));
}
_ => {}
}

let result = Self::get_item(&sequence, index, vm);
// A reentrant call can have removed the iterator's sequence owner.
// Release our temporary owner before publishing the outer result.
drop(sequence);
match result {
Ok(item) => {
let mut state = self.state.lock();
state.index = match self.direction {
// Forward iteration advances the current index, including
// changes made by __getitem__ or a nested next().
// CPython's default no-strict-overflow build wraps if
// that callback restored PY_SSIZE_T_MAX.
SequenceIterDirection::Forward => state.index.wrapping_add(1),
// Reverse iteration instead advances the captured index.
// Keep the sequence at -1 until the next next() call.
SequenceIterDirection::Reverse => index - 1,
};
drop(state);
Ok(PyIterReturn::Return(item))
}
Err(error)
if error.fast_isinstance(vm.ctx.exceptions.index_error)
|| error.fast_isinstance(vm.ctx.exceptions.stop_iteration) =>
{
// Clear the whole exception, including StopIteration.value,
// before publishing exhaustion. Its finalizer may reenter.
drop(error);
self.exhaust();
Ok(PyIterReturn::StopIteration(None))
}
Err(error) => {
if matches!(self.direction, SequenceIterDirection::Reverse) {
self.exhaust();
}
Err(error)
}
}
}

pub(crate) fn length_hint(&self, vm: &VirtualMachine) -> PyResult<Option<usize>> {
let (sequence, index) = self.snapshot();
let Some(sequence) = sequence else {
return Ok(Some(0));
};
if matches!(self.direction, SequenceIterDirection::Reverse) && index < 0 {
return Ok(Some(0));
}
let seq = sequence.sequence_unchecked();
if matches!(self.direction, SequenceIterDirection::Forward)
&& seq.slots().length.load().is_none()
&& sequence.mapping_unchecked().slots().length.load().is_none()
{
return Ok(None);
}
let length = seq.length(vm)?;
drop(sequence);
let remaining = match self.direction {
SequenceIterDirection::Forward => {
// iter_len reads the index after the length callback.
let index = self.state.lock().index;
(length as isize).wrapping_sub(index).max(0) as usize
}
SequenceIterDirection::Reverse => {
// reversed_len uses the index captured before the callback.
let remaining = index as usize + 1;
if length < remaining { 0 } else { remaining }
}
};
Ok(Some(remaining))
}

pub(crate) fn set_state(&self, state: &PyObject, vm: &VirtualMachine) -> PyResult<()> {
// PyLong_AsSsize_t accepts int subclasses, not __index__. Convert even
// when exhausted, and retain the original argument through callbacks.
let index = state
.downcast_ref::<PyInt>()
.ok_or_else(|| vm.new_type_error("an integer is required"))?;
let index = isize::try_from(index.as_bigint())
.map_err(|_| vm.new_overflow_error("Python int too large to convert to C ssize_t"))?;
match self.direction {
SequenceIterDirection::Forward => {
let mut state = self.state.lock();
if state.sequence.is_some() {
state.index = index.max(0);
}
}
SequenceIterDirection::Reverse => {
let (sequence, current) = self.snapshot();
if current < 0 {
return Ok(());
}
let Some(sequence) = sequence else {
return Ok(());
};
let length = sequence.sequence_unchecked().length(vm)?;
drop(sequence);
self.state.lock().index = index.clamp(-1, length as isize - 1);
}
}
Ok(())
}

/// Resolve the reconstruction function before taking this snapshot. Tuple
/// allocation can also run GC and finalizers, so it follows the lock scope.
pub(crate) fn reduce(&self, func: PyObjectRef, vm: &VirtualMachine) -> PyTupleRef {
let (sequence, index) = self.snapshot();
if let Some(sequence) = sequence
&& (matches!(self.direction, SequenceIterDirection::Forward) || index >= 0)
{
vm.new_tuple((func, (sequence,), index))
} else {
vm.new_tuple((func, (vm.ctx.empty_tuple.clone(),)))
}
}
}

#[pyclass(module = false, name = "iterator", traverse)]
#[derive(Debug)]
pub struct PySequenceIterator {
internal: PyMutex<PositionIterInternal<PyObjectRef>>,
internal: SequenceIter,
}

impl PyPayload for PySequenceIterator {
Expand All @@ -241,7 +443,7 @@ impl PySequenceIterator {
pub fn new(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> {
let _seq = obj.try_sequence(vm)?;
Ok(Self {
internal: PyMutex::new(PositionIterInternal::new(obj, 0)),
internal: SequenceIter::new(obj, 0, SequenceIterDirection::Forward),
})
}
}
Expand All @@ -251,51 +453,29 @@ impl Py<PySequenceIterator> {
#[pymethod]
fn __length_hint__(&self, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
vm.with_recursion(" in __length_hint__", || {
let (obj, position) = {
let internal = self.internal.lock();
match &internal.status {
IterStatus::Active(obj) => (Some(obj.clone()), internal.position),
IterStatus::Exhausted => (None, 0),
}
};
if let Some(obj) = obj {
let seq = obj.sequence_unchecked();
match seq.length_opt(vm) {
Some(len) => {
len.map(|len| PyInt::from(len.saturating_sub(position)).into_pyobject(vm))
}
None => Ok(vm.ctx.not_implemented()),
}
} else {
Ok(PyInt::from(0).into_pyobject(vm))
}
Ok(match self.internal.length_hint(vm)? {
Some(length) => PyInt::from(length).into_pyobject(vm),
None => vm.ctx.not_implemented(),
})
})
}

#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
let func = builtins_iter(vm)?;
Ok(self.internal.lock().reduce(
func,
|x| x.clone(),
|vm| vm.ctx.empty_tuple.clone().into(),
vm,
))
Ok(self.internal.reduce(func, vm))
}

#[pymethod]
fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.internal.lock().set_state(&state, |_, pos| pos, vm)
self.internal.set_state(&state, vm)
}
}

impl SelfIter for PySequenceIterator {}
impl IterNext for PySequenceIterator {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
locked_next(&zelf.internal, |obj, pos| {
let seq = obj.sequence_unchecked();
PyIterReturn::from_getitem_result(seq.get_item(pos as isize, vm), vm)
})
zelf.internal.next(vm)
}
}

Expand Down
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.