interpretthis 0.4.1

Sandboxed Python AST interpreter for untrusted and LLM-generated code
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
// Copyright 2026 Thomas Santerre and Moderately AI Inc.
//
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Lvalue (assignment-target) resolution.
//!
//! A *place* is a root variable plus a chain of already-evaluated accessor steps
//! — the address of a mutable slot in the value tree. It backs every operation
//! that has to write *through* an expression rather than to a bare name:
//!
//!   * subscript / attribute assignment   — `d["a"]["x"] = v`, `obj.attr = v`
//!   * slice assignment                    — `lst[1:] = xs`
//!   * augmented assignment                — `d["a"]["x"] += 1`
//!   * in-place mutating method calls      — `groups[1].append(5)`
//!
//! The design resolves the place once (evaluating any index expressions) and
//! then navigates a *single* `&mut` borrow into `state.variables` to reach the
//! slot. Nothing is cloned: the previous implementation cloned the receiver and
//! then scanned every variable's `Debug` string to discover where to write the
//! mutation back — O(variables × value size) per call, and wrong for any slot
//! that was not a top-level variable. Navigation is O(path length); memory
//! accounting is an O(1) signed byte delta applied after the borrow ends.

use rustpython_parser::ast::Expr;

use crate::{
    error::{EvalError, InterpreterError},
    eval::{control_flow::iterate_value, eval_expr, literals::value_to_key},
    state::{InterpreterState, estimate_value_size},
    tools::Tools,
    value::{ExceptionValue, Value, ValueKey},
};

/// One accessor in a place path, with index/slice expressions already evaluated.
pub(crate) enum PlaceStep {
    /// `obj[key]` — `key` evaluated to a value.
    Index(Value),
    /// `obj[lower:upper:step]` — bounds evaluated. Only valid as the terminal
    /// step of a plain assignment; it is not a navigable intermediate slot.
    /// Boxed because the three optional bound `Value`s make it far larger than
    /// the other variants.
    Slice(Box<SliceSpec>),
    /// `obj.attr`.
    Attr(String),
}

/// Evaluated bounds of a slice target.
pub(crate) struct SliceSpec {
    pub lower: Option<Value>,
    pub upper: Option<Value>,
    pub step: Option<Value>,
}

/// A resolved assignment target: a root variable and the path to the slot.
pub(crate) struct Place {
    pub root: String,
    pub steps: Vec<PlaceStep>,
}

impl Place {
    /// True when every step can be navigated as a persistent mutable slot.
    /// A `Slice` step cannot (it denotes a fresh sub-sequence), so a receiver
    /// containing one is treated as a temporary by the method-call path —
    /// matching CPython, where `lst[1:].append(x)` mutates a throwaway list.
    pub(crate) fn is_navigable(&self) -> bool {
        self.steps.iter().all(|s| !matches!(s, PlaceStep::Slice(_)))
    }
}

/// Resolve an expression to a [`Place`], evaluating any index/slice
/// sub-expressions left-to-right. Returns `Ok(None)` when the expression is not
/// rooted in a bare variable (e.g. `f()[0]`, a literal) and therefore cannot
/// name a persistent slot.
pub(crate) fn eval_place<'a>(
    state: &'a mut InterpreterState,
    expr: &'a Expr,
    tools: &'a Tools,
) -> std::pin::Pin<
    Box<dyn std::future::Future<Output = Result<Option<Place>, EvalError>> + Send + 'a>,
> {
    // Recursive place resolution (`a.b.c.d…`, `a[0][0][0]…`) is grown on demand
    // like the eval spine so a deep chain reaches the expression-depth limit
    // (below) instead of overflowing the host stack first.
    Box::pin(crate::eval::functions::dispatch::grow_stack(async move {
        // Bound recursive place resolution by the same expression-depth limit as
        // the eval spine, so a pathological chain raises RecursionError.
        state.enter_expr().map_err(EvalError::Interpreter)?;
        let result = async {
            match expr {
                Expr::Name(name_node) => {
                    Ok(Some(Place { root: name_node.id.as_str().to_string(), steps: Vec::new() }))
                }
                Expr::Subscript(sub) => {
                    let Some(mut place) = eval_place(state, &sub.value, tools).await? else {
                        return Ok(None);
                    };
                    if let Expr::Slice(slice) = sub.slice.as_ref() {
                        let lower = eval_opt(state, slice.lower.as_deref(), tools).await?;
                        let upper = eval_opt(state, slice.upper.as_deref(), tools).await?;
                        let step = eval_opt(state, slice.step.as_deref(), tools).await?;
                        place.steps.push(PlaceStep::Slice(Box::new(SliceSpec {
                            lower,
                            upper,
                            step,
                        })));
                    } else {
                        let key = eval_expr(state, &sub.slice, tools).await?;
                        // A computed `slice()` object subscript (`lst[s] = v` where
                        // `s = slice(...)`) is slice assignment, exactly like the
                        // `lst[i:j:k]` syntax — turn it into a Slice step rather than
                        // an integer-index step.
                        if let Value::Slice(s) = key {
                            let to_opt =
                                |v: Value| if matches!(v, Value::None) { None } else { Some(v) };
                            place.steps.push(PlaceStep::Slice(Box::new(SliceSpec {
                                lower: to_opt(s.start),
                                upper: to_opt(s.stop),
                                step: to_opt(s.step),
                            })));
                        } else {
                            place.steps.push(PlaceStep::Index(key));
                        }
                    }
                    Ok(Some(place))
                }
                Expr::Attribute(attr) => {
                    // Universal object attributes (`__class__`) may appear in a
                    // read receiver chain (`x.__class__.__name__`), so don't block
                    // them while *building* a place — peek-navigation fails
                    // cleanly and the caller re-evaluates. A *write* through such a
                    // place is still rejected at `set_attr` below.
                    if !crate::eval::names::is_object_attr(attr.attr.as_str()) {
                        crate::security::validator::validate_attribute(attr.attr.as_str())?;
                    }
                    // A class attribute (`Base.registry`) is not a navigable variable
                    // slot — its storage lives in `state.classes` and is a shared
                    // handle. Return None so the caller takes the non-place path
                    // (evaluate the attribute to its shared Dict/List and mutate it),
                    // which keeps `Base.registry[k] = v` visible on the class.
                    if let Expr::Name(base) = attr.value.as_ref() {
                        if matches!(state.variables.get(base.id.as_str()), Some(Value::Class(_))) {
                            return Ok(None);
                        }
                    }
                    let Some(mut place) = eval_place(state, &attr.value, tools).await? else {
                        return Ok(None);
                    };
                    place.steps.push(PlaceStep::Attr(attr.attr.as_str().to_string()));
                    Ok(Some(place))
                }
                _ => Ok(None),
            }
        }
        .await;
        state.exit_expr();
        result
    }))
}

/// Assign `receiver[slice] = value` for a computed (non-place)
/// receiver such as `f()[0] = v` or a literal `(1, 2)[0] = 5`. Mutable
/// builtin containers are mutated through their shared handle (the
/// mutation is observable only if the receiver is retained elsewhere,
/// matching CPython's throwaway semantics); immutable ones raise
/// CPython's `TypeError: '<type>' object does not support item
/// assignment`. The byte delta is discarded because the receiver is not
/// bound to any name the memory accounting tracks.
pub(crate) async fn assign_computed_subscript(
    state: &mut InterpreterState,
    receiver: &mut Value,
    slice: &Expr,
    value: Value,
    tools: &Tools,
) -> Result<(), EvalError> {
    let step = if let Expr::Slice(s) = slice {
        let lower = eval_opt(state, s.lower.as_deref(), tools).await?;
        let upper = eval_opt(state, s.upper.as_deref(), tools).await?;
        let step = eval_opt(state, s.step.as_deref(), tools).await?;
        PlaceStep::Slice(Box::new(SliceSpec { lower, upper, step }))
    } else {
        PlaceStep::Index(eval_expr(state, slice, tools).await?)
    };
    assign_terminal(receiver, &step, value).map(|_delta| ())
}

/// Evaluate an optional slice-bound expression.
async fn eval_opt(
    state: &mut InterpreterState,
    expr: Option<&Expr>,
    tools: &Tools,
) -> Result<Option<Value>, EvalError> {
    match expr {
        Some(e) => Ok(Some(eval_expr(state, e, tools).await?)),
        None => Ok(None),
    }
}

/// Navigate `root` along `steps`, then invoke `f` with a mutable
/// reference to the final slot. The callback shape is the API that
/// shared-container types need (List wrapped in `Arc<Mutex<Vec>>`,
/// etc.): the lock guard is held only for the duration of `f`, so the
/// caller can mutate the slot in-place without lifetime gymnastics on
/// the returned borrow.
///
/// Walks the steps recursively, holding any intermediate
/// `parking_lot::MutexGuard`s on the stack so the lock guard's scope
/// covers `f`'s execution. Callers pass an `FnOnce(&mut Value) -> R`
/// and never see the locking machinery. Type erasure via
/// `Box<dyn FnOnce>` is used to make the recursion's chained-closure
/// type compile without monomorphisation blowup.
pub(crate) fn with_navigate_mut<R, F: FnOnce(&mut Value) -> R>(
    root: &mut Value,
    steps: &[PlaceStep],
    f: F,
) -> Result<R, EvalError> {
    let f_boxed: NavCallback<'_, R> = Box::new(move |v| Ok(f(v)));
    nav_recurse(root, steps, f_boxed)
}

/// Type-erased navigation callback: takes a `&mut Value` slot and
/// returns either a successful value of type `R` or an `EvalError`.
/// The boxed dyn FnOnce is what makes the recursion compile — without
/// it, the chained-closure type grows unboundedly with step depth.
type NavCallback<'a, R> = Box<dyn FnOnce(&mut Value) -> Result<R, EvalError> + 'a>;

fn nav_recurse<R>(
    cur: &mut Value,
    steps: &[PlaceStep],
    f: NavCallback<'_, R>,
) -> Result<R, EvalError> {
    let Some((head, tail)) = steps.split_first() else {
        return f(cur);
    };
    match head {
        PlaceStep::Index(key) => match cur {
            Value::List(items) => {
                let mut guard = items.lock();
                let idx = seq_index(guard.len(), key)?;
                nav_recurse(&mut guard[idx], tail, f)
            }
            Value::Dict(map) => {
                let k = value_to_key(key)?;
                let mut guard = map.lock();
                let v = guard
                    .get_mut(&k)
                    .ok_or_else(|| EvalError::Exception(ExceptionValue::key_error(&k)))?;
                nav_recurse(v, tail, f)
            }
            Value::DefaultDict(data) => {
                let k = value_to_key(key)?;
                // The aug-assign pre-touch synthesised the entry before
                // navigation; if it's still missing, the caller didn't
                // go through eval_aug_assign and the synth-on-miss
                // contract was bypassed. Raise KeyError to signal that.
                let v = data
                    .items
                    .get_mut(&k)
                    .ok_or_else(|| EvalError::Exception(ExceptionValue::key_error(&k)))?;
                nav_recurse(v, tail, f)
            }
            Value::Counter(map) => {
                // Counter's `__missing__` yields 0 without inserting; for the
                // aug-assign navigation (`c[k] += 1`, the canonical counting
                // idiom) the entry is materialised at 0 so the write-back lands.
                let k = value_to_key(key)?;
                let v = map.entry(k).or_insert(Value::Int(0));
                nav_recurse(v, tail, f)
            }
            Value::OrderedDict(map) => {
                let k = value_to_key(key)?;
                let mut guard = map.lock();
                let v = guard
                    .get_mut(&k)
                    .ok_or_else(|| EvalError::Exception(ExceptionValue::key_error(&k)))?;
                nav_recurse(v, tail, f)
            }
            Value::Deque { items, .. } => {
                // `seq_index` has already bounds-checked (and normalised a
                // negative index), so `get_mut` cannot miss here.
                let idx = seq_index(items.len(), key)?;
                let v = items.get_mut(idx).ok_or_else(|| {
                    EvalError::from(InterpreterError::Runtime("deque index out of range".into()))
                })?;
                nav_recurse(v, tail, f)
            }
            other => Err(InterpreterError::TypeError(format!(
                "'{}' object is not subscriptable",
                other.type_name()
            ))
            .into()),
        },
        PlaceStep::Attr(name) => match cur {
            Value::Dict(map) => {
                let mut guard = map.lock();
                let v = guard.get_mut(&ValueKey::String(name.as_str().into())).ok_or_else(
                    || -> EvalError {
                        InterpreterError::AttributeError(format!(
                            "'dict' object has no attribute '{name}'"
                        ))
                        .into()
                    },
                )?;
                nav_recurse(v, tail, f)
            }
            Value::Instance(inst) => {
                let class_name = inst.class_name.clone();
                let mut fields = inst.fields.lock();
                let v = fields.get_mut(name.as_str()).ok_or_else(|| -> EvalError {
                    InterpreterError::AttributeError(format!(
                        "'{class_name}' object has no attribute '{name}'"
                    ))
                    .into()
                })?;
                nav_recurse(v, tail, f)
            }
            other => Err(InterpreterError::AttributeError(format!(
                "'{}' object has no attribute '{name}'",
                other.type_name()
            ))
            .into()),
        },
        PlaceStep::Slice(_) => Err(InterpreterError::Runtime(
            "a slice cannot be used as an intermediate assignment target".into(),
        )
        .into()),
    }
}

/// Resolve a sequence index (supports `True`/`False` as 1/0 and negatives),
/// bounds-checked against `len`.
fn seq_index(len: usize, key: &Value) -> Result<usize, EvalError> {
    let raw = match key {
        Value::Int(i) => *i,
        Value::Bool(b) => i64::from(*b),
        other => {
            return Err(InterpreterError::TypeError(format!(
                "list indices must be integers or slices, not {}",
                other.type_name()
            ))
            .into());
        }
    };
    let len_i = i64::try_from(len).map_err(|_| {
        EvalError::from(InterpreterError::Runtime("sequence length overflows i64".into()))
    })?;
    let idx = if raw < 0 { len_i + raw } else { raw };
    if idx < 0 || idx >= len_i {
        return Err(EvalError::Exception(ExceptionValue::index_error("list")));
    }
    usize::try_from(idx).map_err(|_| {
        EvalError::from(InterpreterError::Runtime("index overflow (internal invariant)".into()))
    })
}

/// Apply the terminal accessor of an assignment target, writing `value` into the
/// slot. Returns the signed change in the container's estimated heap size so the
/// caller can update the memory budget in O(1) without re-estimating the root.
pub(crate) fn assign_terminal(
    container: &mut Value,
    step: &PlaceStep,
    value: Value,
) -> Result<isize, EvalError> {
    match step {
        PlaceStep::Index(key) => set_index(container, key, value),
        PlaceStep::Attr(name) => set_attr(container, name, value),
        PlaceStep::Slice(spec) => set_slice(container, spec, value),
    }
}

/// `container[key] = value`.
///
/// Routes through `types::dispatch_setitem` so the per-type write logic
/// lives in one place; the dispatch returns the signed byte delta the
/// caller folds into the memory budget.
fn set_index(container: &mut Value, key: &Value, value: Value) -> Result<isize, EvalError> {
    // Counter is a dict subclass — `c[k] = n` assigns like a dict (it stores
    // value-semantic, so it has no `set_item_slot` type-object entry).
    if let Value::Counter(map) = container {
        let k = value_to_key(key)?;
        let new_size = estimate_value_size(&value);
        let delta = map.insert(k.clone(), value).map_or_else(
            || to_isize(crate::state::estimate_key_size(&k) + new_size),
            |old| size_delta(estimate_value_size(&old), new_size),
        );
        return Ok(delta);
    }
    crate::types::dispatch_setitem(container, key, value)
}

/// `container.attr = value` — Instance fields stay on the legacy path
/// here until B1 promotes `Value::Instance` to its own TypeObject with
/// a populated `set_attr_slot`. All other types (including Dict) route
/// through `types::dispatch_setattr`, which raises CPython's
/// `AttributeError("'<name>' object has no attribute '<name>'")` shape
/// for read-only types like list/tuple/str.
fn set_attr(container: &mut Value, name: &str, value: Value) -> Result<isize, EvalError> {
    // Authoritative attribute-WRITE block: every blocked dunder — including
    // `__class__`, which is READ-allowed (aliases `type(x)`) but must never be
    // assigned (type confusion) — is rejected here, the single funnel every
    // `obj.attr = …` place write passes through.
    crate::security::validator::validate_attribute(name)?;
    if let Value::Instance(inst) = container {
        let new_size = estimate_value_size(&value);
        let delta = inst.fields.lock().insert(name.to_string(), value).map_or_else(
            || to_isize(name.len() + new_size),
            |old| size_delta(estimate_value_size(&old), new_size),
        );
        return Ok(delta);
    }
    crate::types::dispatch_setattr(container, name, value)
}

/// Read `container[lower:upper:step]` as a new list (list only).
pub(crate) fn get_slice(container: &Value, spec: &SliceSpec) -> Result<Value, EvalError> {
    let Value::List(items) = container else {
        return Err(InterpreterError::TypeError(format!(
            "'{}' object is not subscriptable",
            container.type_name()
        ))
        .into());
    };
    let stride = resolve_step(spec.step.as_ref())?;
    let guard = items.lock();
    let len = i64::try_from(guard.len()).map_err(|_| {
        EvalError::from(InterpreterError::Runtime("sequence length overflows i64".into()))
    })?;
    let mut out = Vec::new();
    if stride == 1 {
        let start = clamp_index(resolve_bound(spec.lower.as_ref(), 0)?, len);
        let stop = clamp_index(resolve_bound(spec.upper.as_ref(), len)?, len).max(start);
        let lo = to_index(start)?;
        let hi = to_index(stop)?;
        out.extend(guard[lo..hi].iter().cloned());
    } else {
        for idx in extended_indices(len, spec, stride)? {
            out.push(guard[idx].clone());
        }
    }
    Ok(Value::List(crate::value::shared_list(out)))
}

/// `container[lower:upper:step] = iterable`. List is the only container
/// that supports slice assignment in CPython.
pub(crate) fn set_slice(
    container: &mut Value,
    spec: &SliceSpec,
    value: Value,
) -> Result<isize, EvalError> {
    // `bytearray[i:j] = bytes-like` — replace the slice with new bytes.
    if let Value::ByteArray(ba) = container {
        return set_bytearray_slice(ba, spec, &value);
    }
    // `array[i:j] = array` — CPython only accepts another array as the RHS.
    if let Value::Array { items, .. } = container {
        let Value::Array { items: rhs, .. } = &value else {
            return Err(InterpreterError::TypeError(format!(
                "can only assign array (not \"{}\") to array slice",
                value.type_name()
            ))
            .into());
        };
        let rhs_items = Value::List(rhs.clone());
        let mut list = Value::List(items.clone());
        return set_slice(&mut list, spec, rhs_items);
    }
    let Value::List(items) = container else {
        return Err(InterpreterError::TypeError(format!(
            "'{}' object does not support slice assignment",
            container.type_name()
        ))
        .into());
    };
    let new_items = iterate_value(&value)?;
    let stride = resolve_step(spec.step.as_ref())?;
    let mut guard = items.lock();
    let len = i64::try_from(guard.len()).map_err(|_| {
        EvalError::from(InterpreterError::Runtime("sequence length overflows i64".into()))
    })?;

    if stride == 1 {
        let start = clamp_index(resolve_bound(spec.lower.as_ref(), 0)?, len);
        let stop = clamp_index(resolve_bound(spec.upper.as_ref(), len)?, len).max(start);
        let lo = to_index(start)?;
        let hi = to_index(stop)?;
        let removed_size: usize = guard[lo..hi].iter().map(estimate_value_size).sum();
        let added_size: usize = new_items.iter().map(estimate_value_size).sum();
        guard.splice(lo..hi, new_items);
        return Ok(size_delta(removed_size, added_size));
    }

    // Extended slice: indices are fixed, so the RHS length must match exactly.
    let indices = extended_indices(len, spec, stride)?;
    if indices.len() != new_items.len() {
        return Err(InterpreterError::ValueError(format!(
            "attempt to assign sequence of size {} to extended slice of size {}",
            new_items.len(),
            indices.len()
        ))
        .into());
    }
    let mut delta = 0isize;
    for (idx, val) in indices.into_iter().zip(new_items) {
        delta = delta.saturating_add(size_delta(
            estimate_value_size(&guard[idx]),
            estimate_value_size(&val),
        ));
        guard[idx] = val;
    }
    drop(guard);
    Ok(delta)
}

/// `bytearray[i:j:k] = bytes-like` — splice new bytes into the shared storage.
fn set_bytearray_slice(
    ba: &crate::value::SharedByteArray,
    spec: &SliceSpec,
    value: &Value,
) -> Result<isize, EvalError> {
    // The RHS is any bytes-like / iterable of ints.
    let new_bytes: Vec<u8> = match value {
        Value::Bytes(b) => b.clone(),
        Value::ByteArray(b) => b.lock().clone(),
        other => iterate_value(other)?
            .iter()
            .map(|v| match v {
                Value::Int(n) if (0..=255).contains(n) => Ok(*n as u8),
                Value::Bool(b) => Ok(u8::from(*b)),
                _ => Err(EvalError::from(InterpreterError::ValueError(
                    "bytes must be in range(0, 256)".into(),
                ))),
            })
            .collect::<Result<_, _>>()?,
    };
    let stride = resolve_step(spec.step.as_ref())?;
    let mut b = ba.lock();
    let len = i64::try_from(b.len()).map_err(|_| {
        EvalError::from(InterpreterError::Runtime("sequence length overflows i64".into()))
    })?;
    if stride == 1 {
        let start = clamp_index(resolve_bound(spec.lower.as_ref(), 0)?, len);
        let stop = clamp_index(resolve_bound(spec.upper.as_ref(), len)?, len).max(start);
        let lo = to_index(start)?;
        let hi = to_index(stop)?;
        let removed = hi - lo;
        b.splice(lo..hi, new_bytes.iter().copied());
        return Ok(size_delta(removed, new_bytes.len()));
    }
    let indices = extended_indices(len, spec, stride)?;
    if indices.len() != new_bytes.len() {
        return Err(InterpreterError::ValueError(format!(
            "attempt to assign bytes of size {} to extended slice of size {}",
            new_bytes.len(),
            indices.len()
        ))
        .into());
    }
    for (idx, byte) in indices.into_iter().zip(new_bytes) {
        b[idx] = byte;
    }
    Ok(0)
}

/// Collect the concrete indices selected by an extended (step != 1) slice.
fn extended_indices(len: i64, spec: &SliceSpec, stride: i64) -> Result<Vec<usize>, EvalError> {
    let mut indices = Vec::new();
    if stride > 0 {
        let start = clamp_index(resolve_bound(spec.lower.as_ref(), 0)?, len);
        let stop = clamp_index(resolve_bound(spec.upper.as_ref(), len)?, len);
        let mut i = start;
        while i < stop {
            indices.push(to_index(i)?);
            i += stride;
        }
    } else {
        let start = clamp_index_neg(resolve_bound(spec.lower.as_ref(), len - 1)?, len);
        let stop = clamp_index_neg(resolve_bound(spec.upper.as_ref(), -(len + 1))?, len);
        let mut i = start;
        while i > stop {
            indices.push(to_index(i)?);
            i += stride;
        }
    }
    Ok(indices)
}

/// Resolve a slice step value to a non-zero i64 stride (default 1).
fn resolve_step(step: Option<&Value>) -> Result<i64, EvalError> {
    // `bool` is an `int` subclass: `True` is a stride of 1, but `False` is a
    // stride of 0 — a ValueError, not a silent 1.
    let zero = || EvalError::from(InterpreterError::ValueError("slice step cannot be zero".into()));
    match step {
        None | Some(Value::None) => Ok(1),
        Some(Value::Int(0)) => Err(zero()),
        Some(Value::Int(s)) => Ok(*s),
        Some(Value::Bool(false)) => Err(zero()),
        Some(Value::Bool(true)) => Ok(1),
        Some(_) => Err(InterpreterError::TypeError(
            "slice indices must be integers or None or have an __index__ method".to_string(),
        )
        .into()),
    }
}

/// Resolve a slice bound value to an i64, using `default` for absent/`None`.
fn resolve_bound(val: Option<&Value>, default: i64) -> Result<i64, EvalError> {
    match val {
        None | Some(Value::None) => Ok(default),
        Some(Value::Int(i)) => Ok(*i),
        Some(Value::Bool(b)) => Ok(i64::from(*b)),
        Some(_) => Err(InterpreterError::TypeError(
            "slice indices must be integers or None or have an __index__ method".to_string(),
        )
        .into()),
    }
}

/// Clamp a positive-step slice index into `[0, len]`.
fn clamp_index(idx: i64, len: i64) -> i64 {
    let adjusted = if idx < 0 { idx + len } else { idx };
    adjusted.clamp(0, len)
}

/// Clamp a negative-step slice index into `[-1, len - 1]`.
fn clamp_index_neg(idx: i64, len: i64) -> i64 {
    let adjusted = if idx < 0 { idx + len } else { idx };
    adjusted.clamp(-1, len - 1)
}

/// Convert a non-negative slice index into a `usize`. Callers keep the value in
/// range, so the conversion cannot fail in practice.
fn to_index(i: i64) -> Result<usize, EvalError> {
    usize::try_from(i).map_err(|_| {
        EvalError::from(InterpreterError::Runtime(
            "slice index overflow (internal invariant)".into(),
        ))
    })
}

/// Signed `new - old` byte delta, saturating rather than wrapping.
pub(crate) fn size_delta(old: usize, new: usize) -> isize {
    to_isize(new).saturating_sub(to_isize(old))
}

/// Convert a byte count into `isize`, saturating at `isize::MAX`. Sizes are
/// bounded by the memory limit (well under `isize::MAX`), so this never clamps
/// in practice — it is the lint-clean conversion at the boundary.
pub(crate) fn to_isize(n: usize) -> isize {
    isize::try_from(n).unwrap_or(isize::MAX)
}

/// Apply a signed memory delta to the interpreter's budget, enforcing the limit
/// on growth. Called after the mutable borrow into `state` has ended.
pub(crate) fn apply_mem_delta(state: &mut InterpreterState, delta: isize) -> Result<(), EvalError> {
    if delta >= 0 {
        state.track_allocation(usize::try_from(delta).unwrap_or(0)).map_err(EvalError::Interpreter)
    } else {
        state.release_allocation(usize::try_from(-delta).unwrap_or(0));
        Ok(())
    }
}