interpretthis 0.1.0

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
// Copyright 2026 Thomas Santerre and Moderately AI Inc.
//
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Unified async dispatch entry points for Python operators.
//!
//! Every operator surface (`obj[k]`, `obj[k] = v`, `del obj[k]`,
//! `for x in obj`, `len(obj)`, `x in obj`, `bool(obj)`, …) has one
//! async entry point here. The entry point:
//!
//! 1. If the lhs / container / value is a `Value::Instance` and the class defines the corresponding
//!    dunder slot, call it via `call_method` and return the slot's result (or its truthiness, for
//!    predicate-shaped ops).
//! 2. Otherwise fall through to the per-type-object slot table in `crate::types` for the
//!    builtin-pair fast path.
//! 3. If neither applies, the slot table raises the appropriate CPython-shaped TypeError.
//!
//! This replaces the per-site instance-slot intercepts that
//! previously lived in `eval_binop`, `eval_compare`, `eval_for`,
//! `eval_subscript`, `eval_assign`, `eval_delete`, etc. Each call
//! site now reads as a single op::X invocation; the dunder lookup
//! and method dispatch live in one place.
//!
//! Predicate-shaped ops (`truthy`, `contains`) return `bool`;
//! materialising ops (`iter`) return `Vec<Value>`; mutators return
//! their per-op shape (`setitem` returns nothing, `delitem` returns
//! the memory delta). The shape of each function follows what the
//! call site actually needs — there is no uniform "Op trait" for the
//! sake of uniformity.

use indexmap::IndexMap;

use crate::{
    error::{EvalError, EvalResult, InterpreterError},
    eval::{
        classes::{call_method, lookup_method_in_mro},
        functions::CallArgs,
    },
    state::InterpreterState,
    tools::Tools,
    value::Value,
};

/// Look up `slot_name` on `value` as a user-class dunder slot. Returns
/// the bound method definition if the value is an Instance and the
/// class (or any MRO ancestor) defines the slot.
fn instance_slot(
    state: &InterpreterState,
    value: &Value,
    slot_name: &str,
) -> Option<crate::value::FunctionDef> {
    let Value::Instance(inst) = value else { return None };
    lookup_method_in_mro(state, &inst.class_name, slot_name).map(|(_, method)| method)
}

/// Invoke a Python slot method on a receiver with positional args.
/// Returns the slot's return value plus the post-call self (which the
/// caller may write back to the source binding for mutating ops).
async fn invoke_slot(
    state: &mut InterpreterState,
    receiver: &Value,
    method: &crate::value::FunctionDef,
    args: &[Value],
    tools: &Tools,
) -> Result<(Value, Value), EvalError> {
    let call = CallArgs { positional: args, keyword: &IndexMap::new() };
    call_method(state, method, receiver.clone(), call, tools).await
}

// ---------------------------------------------------------------------------
// Subscript protocol — getitem / setitem / delitem.
// ---------------------------------------------------------------------------

/// `container[key]` — dispatches `__getitem__` on user-class instances,
/// falls through to `types::dispatch_getitem` for builtin containers.
///
/// When the container is a Dict and the key is a user-class Instance,
/// we compute the key via `op::key` (which dispatches `__hash__`)
/// before the sync dict lookup. Without this, `d[CustomKey()]` would
/// fail at the sync `value_to_key` step inside `dispatch_getitem`.
pub async fn getitem(
    state: &mut InterpreterState,
    container: &Value,
    index: &Value,
    tools: &Tools,
) -> EvalResult {
    if let Some(method) = instance_slot(state, container, "__getitem__") {
        let (returned, _self) =
            invoke_slot(state, container, &method, std::slice::from_ref(index), tools).await?;
        return Ok(returned);
    }
    if let (Value::Dict(map), Value::Instance(_)) = (container, index) {
        let k = key(state, index, tools).await?;
        return map
            .get(&k)
            .cloned()
            .ok_or_else(|| EvalError::Exception(crate::value::ExceptionValue::key_error(&k)));
    }
    crate::types::dispatch_getitem(container, index)
}

/// `container[key] = value` for a user-class instance: dispatches
/// `__setitem__` and returns the post-call self so the caller can
/// write it back to the source binding. Returns `Ok(None)` if the
/// container is not an Instance (or has no `__setitem__` slot) —
/// the caller is then responsible for the builtin path through the
/// place machinery, which handles nested targets in a way that's
/// expensive to replicate here.
pub async fn setitem(
    state: &mut InterpreterState,
    container: &Value,
    key: &Value,
    value: Value,
    tools: &Tools,
) -> Result<Option<Value>, EvalError> {
    let Some(method) = instance_slot(state, container, "__setitem__") else {
        return Ok(None);
    };
    let (_returned, updated_self) =
        invoke_slot(state, container, &method, &[key.clone(), value], tools).await?;
    Ok(Some(updated_self))
}

/// `del container[key]` for a user-class instance. Same shape as
/// `setitem` — returns `Ok(Some(post-call self))` when a slot
/// dispatched, `Ok(None)` when no slot exists.
pub async fn delitem(
    state: &mut InterpreterState,
    container: &Value,
    key: &Value,
    tools: &Tools,
) -> Result<Option<Value>, EvalError> {
    let Some(method) = instance_slot(state, container, "__delitem__") else {
        return Ok(None);
    };
    let (_returned, updated_self) =
        invoke_slot(state, container, &method, std::slice::from_ref(key), tools).await?;
    Ok(Some(updated_self))
}

// ---------------------------------------------------------------------------
// Iteration protocol — iter / next.
// ---------------------------------------------------------------------------

/// Materialise an iterable into a `Vec<Value>`. Dispatches
/// `__iter__`/`__next__` on user-class instances (capped by the
/// configured while-iteration budget so a runaway iterator fails
/// LimitExceeded rather than hanging); falls through to the sync
/// `types::dispatch_iter` for builtin iterables.
pub async fn iter(
    state: &mut InterpreterState,
    value: &Value,
    tools: &Tools,
) -> Result<Vec<Value>, EvalError> {
    // Generator iterators: yield items[cursor..] and advance the
    // cursor to end. Subsequent iter() calls return empty (matching
    // CPython's "a generator can be iterated only once").
    if let Value::Lazy { items, cursor_id } = value {
        let cursor = state.lazy_cursors.get(cursor_id).copied().unwrap_or(0);
        let remaining: Vec<Value> = items.iter().skip(cursor).cloned().collect();
        state.lazy_cursors.insert(*cursor_id, items.len());
        return Ok(remaining);
    }
    let Some(iter_method) = instance_slot(state, value, "__iter__") else {
        return crate::types::dispatch_iter(value);
    };

    let (iterator, _self) = invoke_slot(state, value, &iter_method, &[], tools).await?;
    let Value::Instance(iter_inst) = &iterator else {
        return Err(InterpreterError::TypeError(format!(
            "iter() returned non-iterator of type '{}'",
            iterator.type_name()
        ))
        .into());
    };
    let next_method = lookup_method_in_mro(state, &iter_inst.class_name, "__next__")
        .map(|(_, m)| m)
        .ok_or_else(|| {
            InterpreterError::TypeError(format!(
                "iter() returned non-iterator of type '{}' (no __next__)",
                iter_inst.class_name
            ))
        })?;

    let max_iters = state.config.max_while_iterations;
    let mut items: Vec<Value> = Vec::new();
    let mut iterator_value = iterator;
    for _ in 0..max_iters {
        let next_result = invoke_slot(state, &iterator_value, &next_method, &[], tools).await;
        match next_result {
            Ok((item, updated_self)) => {
                items.push(item);
                iterator_value = updated_self;
            }
            Err(EvalError::Exception(exc)) if exc.type_name == "StopIteration" => {
                return Ok(items);
            }
            Err(other) => return Err(other),
        }
    }
    Err(InterpreterError::LimitExceeded(format!(
        "iterator exceeded maximum iterations ({max_iters})"
    ))
    .into())
}

// ---------------------------------------------------------------------------
// Binary operators — arithmetic + bitwise with __op__ / __rop__ slots.
// ---------------------------------------------------------------------------

/// Apply an augmented binary operator (`x += y`, `x *= y`, …).
/// Dispatches the in-place slot (`__iadd__` / `__imul__` / …) on a
/// user-class lhs first. Per CPython, when the in-place slot is
/// absent the operation falls back to the non-in-place form
/// (`__add__` etc.) — the caller then rebinds the target to the new
/// value rather than mutating in place. Builtin pairs route through
/// the sync `apply_binop` kernel.
pub async fn aug_binop(
    state: &mut InterpreterState,
    op: rustpython_parser::ast::Operator,
    left: &Value,
    right: &Value,
    tools: &Tools,
) -> EvalResult {
    if let Some(method) = instance_slot(state, left, inplace_arith_slot(op)) {
        let (returned, _self) =
            invoke_slot(state, left, &method, std::slice::from_ref(right), tools).await?;
        return Ok(returned);
    }
    binop(state, op, left, right, tools).await
}

const fn inplace_arith_slot(op: rustpython_parser::ast::Operator) -> &'static str {
    use rustpython_parser::ast::Operator;
    match op {
        Operator::Add => "__iadd__",
        Operator::Sub => "__isub__",
        Operator::Mult => "__imul__",
        Operator::Div => "__itruediv__",
        Operator::FloorDiv => "__ifloordiv__",
        Operator::Mod => "__imod__",
        Operator::Pow => "__ipow__",
        Operator::MatMult => "__imatmul__",
        Operator::LShift => "__ilshift__",
        Operator::RShift => "__irshift__",
        Operator::BitOr => "__ior__",
        Operator::BitXor => "__ixor__",
        Operator::BitAnd => "__iand__",
    }
}

/// Apply a binary operator. Dispatches the matching forward slot
/// (`__add__` / `__sub__` / …) on a user-class lhs; falls back to the
/// reflected slot (`__radd__` / `__rsub__` / …) on the rhs when the
/// lhs has no forward slot. Builtin pairs route through the
/// sync `apply_binop` kernel.
pub async fn binop(
    state: &mut InterpreterState,
    op: rustpython_parser::ast::Operator,
    left: &Value,
    right: &Value,
    tools: &Tools,
) -> EvalResult {
    if let Some(method) = instance_slot(state, left, arith_slot(op)) {
        let (returned, _self) =
            invoke_slot(state, left, &method, std::slice::from_ref(right), tools).await?;
        return Ok(returned);
    }
    if let Some(method) = instance_slot(state, right, reflected_arith_slot(op)) {
        let (returned, _self) =
            invoke_slot(state, right, &method, std::slice::from_ref(left), tools).await?;
        return Ok(returned);
    }
    crate::eval::operations::apply_binop(left, right, op)
}

const fn arith_slot(op: rustpython_parser::ast::Operator) -> &'static str {
    use rustpython_parser::ast::Operator;
    match op {
        Operator::Add => "__add__",
        Operator::Sub => "__sub__",
        Operator::Mult => "__mul__",
        Operator::Div => "__truediv__",
        Operator::FloorDiv => "__floordiv__",
        Operator::Mod => "__mod__",
        Operator::Pow => "__pow__",
        Operator::MatMult => "__matmul__",
        Operator::LShift => "__lshift__",
        Operator::RShift => "__rshift__",
        Operator::BitOr => "__or__",
        Operator::BitXor => "__xor__",
        Operator::BitAnd => "__and__",
    }
}

const fn reflected_arith_slot(op: rustpython_parser::ast::Operator) -> &'static str {
    use rustpython_parser::ast::Operator;
    match op {
        Operator::Add => "__radd__",
        Operator::Sub => "__rsub__",
        Operator::Mult => "__rmul__",
        Operator::Div => "__rtruediv__",
        Operator::FloorDiv => "__rfloordiv__",
        Operator::Mod => "__rmod__",
        Operator::Pow => "__rpow__",
        Operator::MatMult => "__rmatmul__",
        Operator::LShift => "__rlshift__",
        Operator::RShift => "__rrshift__",
        Operator::BitOr => "__ror__",
        Operator::BitXor => "__rxor__",
        Operator::BitAnd => "__rand__",
    }
}

// ---------------------------------------------------------------------------
// Rich comparison — __eq__ / __lt__ / __le__ / __gt__ / __ge__.
// ---------------------------------------------------------------------------

/// Evaluate a rich-compare op (`==`, `!=`, `<`, `<=`, `>`, `>=`) on
/// two values. User-class instances dispatch the matching dunder slot
/// (with the reflected slot as fallback when the lhs has none); builtin
/// pairs route through the sync `dispatch_eq` / `dispatch_lt` slot
/// table. Identity (`is` / `is not`) and membership (`in` / `not in`)
/// are NOT handled here — they're either trivial (identity) or have
/// their own `op::contains` entry point.
/// Returns the boolean comparison result plus the post-slot LHS and
/// RHS instance values when a user-class slot ran. Callers (e.g.
/// `eval_compare`) write these back to the originating variable
/// names so attribute mutations performed inside `__lt__` / `__eq__`
/// etc. don't get dropped after the expression evaluates.
pub async fn compare(
    state: &mut InterpreterState,
    op: rustpython_parser::ast::CmpOp,
    left: &Value,
    right: &Value,
    tools: &Tools,
) -> Result<(bool, Option<Value>, Option<Value>), EvalError> {
    use rustpython_parser::ast::CmpOp;
    if let Some(slot) = forward_compare_slot(op) {
        if let Some(method) = instance_slot(state, left, slot) {
            let (returned, post_self) =
                invoke_slot(state, left, &method, std::slice::from_ref(right), tools).await?;
            let result = if matches!(op, CmpOp::NotEq) {
                !returned.is_truthy()
            } else {
                returned.is_truthy()
            };
            return Ok((result, Some(post_self), None));
        }
        if let Some(reflected) = reflected_compare_slot(op) {
            if let Some(method) = instance_slot(state, right, reflected) {
                let (returned, post_self) =
                    invoke_slot(state, right, &method, std::slice::from_ref(left), tools).await?;
                return Ok((returned.is_truthy(), None, Some(post_self)));
            }
        }
    }
    let r = crate::eval::operations::compare_builtin(state, op, left, right)?;
    Ok((r, None, None))
}

/// Async-aware `<` for sorted / min / max. Dispatches `__lt__` on a
/// user-class lhs, then reflected `__gt__` on the rhs, then the sync
/// builtin `dispatch_lt`.
pub async fn lt(
    state: &mut InterpreterState,
    left: &Value,
    right: &Value,
    tools: &Tools,
) -> Result<bool, EvalError> {
    if let Some(method) = instance_slot(state, left, "__lt__") {
        let (returned, _self) =
            invoke_slot(state, left, &method, std::slice::from_ref(right), tools).await?;
        return Ok(returned.is_truthy());
    }
    if let Some(method) = instance_slot(state, right, "__gt__") {
        let (returned, _self) =
            invoke_slot(state, right, &method, std::slice::from_ref(left), tools).await?;
        return Ok(returned.is_truthy());
    }
    crate::types::dispatch_lt(left, right)
}

const fn forward_compare_slot(op: rustpython_parser::ast::CmpOp) -> Option<&'static str> {
    use rustpython_parser::ast::CmpOp;
    match op {
        CmpOp::Eq | CmpOp::NotEq => Some("__eq__"),
        CmpOp::Lt => Some("__lt__"),
        CmpOp::LtE => Some("__le__"),
        CmpOp::Gt => Some("__gt__"),
        CmpOp::GtE => Some("__ge__"),
        _ => None,
    }
}

const fn reflected_compare_slot(op: rustpython_parser::ast::CmpOp) -> Option<&'static str> {
    use rustpython_parser::ast::CmpOp;
    match op {
        CmpOp::Lt => Some("__gt__"),
        CmpOp::LtE => Some("__ge__"),
        CmpOp::Gt => Some("__lt__"),
        CmpOp::GtE => Some("__le__"),
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// Hash / key construction — __hash__ for user classes.
// ---------------------------------------------------------------------------

/// Compute `hash(value)`. User-class instances dispatch `__hash__`
/// and the return value is coerced to `i64`; non-Instance values
/// route through the sync `dispatch_hash` slot table. The state
/// borrow accepts `&InterpreterState` so callers from the sync hash
/// path (which need it for class-registry lookups in the
/// `instance_eq` shortcut) keep working.
pub async fn hash(
    state: &mut InterpreterState,
    value: &Value,
    tools: &Tools,
) -> Result<i64, EvalError> {
    if let Some(method) = instance_slot(state, value, "__hash__") {
        let (returned, _self) = invoke_slot(state, value, &method, &[], tools).await?;
        return match returned {
            Value::Int(n) => Ok(n),
            Value::Bool(b) => Ok(i64::from(b)),
            other => Err(InterpreterError::TypeError(format!(
                "__hash__ method should return an integer, returned {}",
                other.type_name()
            ))
            .into()),
        };
    }
    crate::types::dispatch_hash(state, value)
}

/// Convert a `Value` to a `ValueKey` for dict/set storage,
/// dispatching `__hash__` on user-class instances. Falls through to
/// the sync `value_to_key` for non-Instance values (which materialises
/// the existing builtin-key folds — bool↔int unification, integral-
/// float fold, tuple recursion).
pub async fn key(
    state: &mut InterpreterState,
    value: &Value,
    tools: &Tools,
) -> Result<crate::value::ValueKey, EvalError> {
    if matches!(value, Value::Instance(_)) {
        let h = hash(state, value, tools).await?;
        return Ok(crate::value::ValueKey::Instance { hash: h, value: Box::new(value.clone()) });
    }
    crate::eval::literals::value_to_key(value)
}

// ---------------------------------------------------------------------------
// Predicate protocols — len / contains / truthy.
// ---------------------------------------------------------------------------

/// `len(value)` — dispatches `__len__` on user-class instances (must
/// return an int; non-int returns raise TypeError matching CPython's
/// "object cannot be interpreted as an integer"). Falls through to
/// the sync `types::dispatch_len` for builtin containers.
pub async fn len(
    state: &mut InterpreterState,
    value: &Value,
    tools: &Tools,
) -> Result<usize, EvalError> {
    if let Some(method) = instance_slot(state, value, "__len__") {
        let (returned, _self) = invoke_slot(state, value, &method, &[], tools).await?;
        return match returned {
            Value::Int(n) => usize::try_from(n).map_err(|_| {
                InterpreterError::ValueError("__len__() should return >= 0".into()).into()
            }),
            other => Err(InterpreterError::TypeError(format!(
                "'{}' object cannot be interpreted as an integer",
                other.type_name()
            ))
            .into()),
        };
    }
    crate::types::dispatch_len(value)
}

/// `item in container` — dispatches `__contains__` on user-class
/// instances (result interpreted via truthiness); falls through to
/// `types::dispatch_contains` for builtin containers.
///
/// (Dict, Instance) and (Set, Instance) pairs need an async key
/// computation before the sync membership test — same reason as
/// `getitem`.
pub async fn contains(
    state: &mut InterpreterState,
    container: &Value,
    item: &Value,
    tools: &Tools,
) -> Result<bool, EvalError> {
    if let Some(method) = instance_slot(state, container, "__contains__") {
        let (returned, _self) =
            invoke_slot(state, container, &method, std::slice::from_ref(item), tools).await?;
        return Ok(returned.is_truthy());
    }
    if matches!(item, Value::Instance(_)) {
        if let Value::Dict(map) = container {
            let k = key(state, item, tools).await?;
            return Ok(map.contains_key(&k));
        }
        if let Value::Set(items) = container {
            for stored in items {
                if let Value::Instance(_) = stored {
                    if crate::eval::operations::values_equal_pub(stored, item) {
                        return Ok(true);
                    }
                }
            }
            return Ok(false);
        }
    }
    crate::types::dispatch_contains(container, item)
}

/// Try to compute truthiness synchronously, without allocating a
/// `Box::pin`'d future. Returns `Some(b)` for every shape that doesn't
/// need to await user-class `__bool__` / `__len__` dispatch.
///
/// `Value::Instance` is the only shape that can return `None` — every
/// builtin's truthiness is the sync `Value::is_truthy` table lookup.
/// Hot callers (`if`-clauses inside comprehensions, `while`/`if`
/// conditions on plain values) try this first and avoid the future box
/// on the common case.
#[inline]
#[must_use]
pub fn try_truthy_sync(value: &Value) -> Option<bool> {
    match value {
        Value::Instance(_) => None,
        other => Some(other.is_truthy()),
    }
}

/// `bool(value)` / `if value:` — dispatches `__bool__` then `__len__`
/// on user-class instances; falls through to the sync `Value::is_truthy`
/// for builtins (None / 0 / "" / [] / etc. are falsy; everything else
/// truthy).
pub async fn truthy(
    state: &mut InterpreterState,
    value: &Value,
    tools: &Tools,
) -> Result<bool, EvalError> {
    if matches!(value, Value::Instance(_)) {
        if let Some(method) = instance_slot(state, value, "__bool__") {
            let (returned, _self) = invoke_slot(state, value, &method, &[], tools).await?;
            return match returned {
                Value::Bool(b) => Ok(b),
                other => Err(InterpreterError::TypeError(format!(
                    "__bool__ should return bool, returned {}",
                    other.type_name()
                ))
                .into()),
            };
        }
        if let Some(method) = instance_slot(state, value, "__len__") {
            let (returned, _self) = invoke_slot(state, value, &method, &[], tools).await?;
            return match returned {
                Value::Int(n) => Ok(n != 0),
                Value::Bool(b) => Ok(b),
                other => Err(InterpreterError::TypeError(format!(
                    "'{}' object cannot be interpreted as an integer",
                    other.type_name()
                ))
                .into()),
            };
        }
    }
    Ok(value.is_truthy())
}