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

use indexmap::IndexMap;

use super::{methods, resolve_proxy};
use crate::{
    error::{EvalError, InterpreterError},
    eval::place,
    value::{Value, shared_list},
};
// EvalError used for BigInt method overflow path.

/// The positional and keyword arguments of a call, bundled so call-machinery
/// signatures stay under the argument-count limit and the pair always travels
/// together.
#[derive(Clone, Copy)]
pub(crate) struct CallArgs<'a> {
    pub positional: &'a [Value],
    pub keyword: &'a IndexMap<String, Value>,
}

/// Outcome of a method dispatch: the Python return value plus the signed change
/// in the receiver's estimated heap size. The caller applies `mem_delta` to the
/// memory budget once the mutable borrow into `state` has ended, keeping memory
/// accounting O(1) (no re-estimating the whole root after each `append`).
pub(crate) struct MethodOutcome {
    pub value: Value,
    pub mem_delta: isize,
}

impl MethodOutcome {
    /// A non-mutating result (no change to the receiver's size).
    pub(crate) const fn pure(value: Value) -> Self {
        Self { value, mem_delta: 0 }
    }

    /// A mutation that added `bytes` to the receiver.
    pub(crate) fn grew(value: Value, bytes: usize) -> Self {
        Self { value, mem_delta: place::to_isize(bytes) }
    }

    /// A mutation that removed `bytes` from the receiver.
    pub(crate) fn shrank(value: Value, bytes: usize) -> Self {
        Self { value, mem_delta: -place::to_isize(bytes) }
    }
}

/// Reject any keyword arguments. Use for methods that take only positionals
/// (or no args) when the caller passed kwargs — CPython raises TypeError
/// rather than silently ignoring them.
pub(crate) fn reject_kwargs(
    method: &str,
    kwargs: &IndexMap<String, Value>,
) -> Result<(), EvalError> {
    if let Some((name, _)) = kwargs.first() {
        return Err(InterpreterError::TypeError(format!(
            "{method}() got an unexpected keyword argument '{name}'"
        ))
        .into());
    }
    Ok(())
}

/// Bind positional + keyword args onto named method parameters.
///
/// Returns one slot per `params` entry (`None` = not supplied). Enforces:
/// - no more positionals than `params.len()`
/// - no unknown kwargs
/// - no argument supplied both positionally and by keyword
///
/// Callers decide which slots are required and supply defaults for the rest.
pub(crate) fn bind_method_params(
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
    params: &[&str],
) -> Result<Vec<Option<Value>>, EvalError> {
    if args.len() > params.len() {
        return Err(InterpreterError::TypeError(format!(
            "{method}() takes at most {} argument{} ({} given)",
            params.len(),
            if params.len() == 1 { "" } else { "s" },
            args.len()
        ))
        .into());
    }
    let mut bound: Vec<Option<Value>> = params.iter().map(|_| None).collect();
    for (i, arg) in args.iter().enumerate() {
        bound[i] = Some(arg.clone());
    }
    for (name, value) in kwargs {
        let Some(idx) = params.iter().position(|p| *p == name.as_str()) else {
            return Err(InterpreterError::TypeError(format!(
                "{method}() got an unexpected keyword argument '{name}'"
            ))
            .into());
        };
        if bound[idx].is_some() {
            return Err(InterpreterError::TypeError(format!(
                "{method}() got multiple values for argument '{name}'"
            ))
            .into());
        }
        bound[idx] = Some(value.clone());
    }
    Ok(bound)
}

/// Require a bound slot (positional or keyword) by index.
pub(crate) fn require_param<'a>(
    method: &str,
    bound: &'a [Option<Value>],
    idx: usize,
    name: &str,
) -> Result<&'a Value, EvalError> {
    bound.get(idx).and_then(Option::as_ref).ok_or_else(|| {
        EvalError::from(InterpreterError::TypeError(format!(
            "{method}() missing required argument: '{name}'"
        )))
    })
}

/// Resolve lazy-proxy method arguments before dispatch. `join` and friends
/// iterate collection items, so proxies one level inside a list/tuple argument
/// are resolved too.
pub(super) async fn resolve_method_args(args: &[Value]) -> Result<Vec<Value>, EvalError> {
    let mut resolved_args = Vec::with_capacity(args.len());
    for arg in args {
        let resolved = resolve_proxy(arg).await?;
        match resolved {
            Value::List(items) => {
                // Snapshot the items under the lock — `resolve_proxy`
                // may suspend on a tool call, so hold the guard only
                // long enough to clone the inner Vec.
                let snapshot = items.lock().clone();
                let mut resolved_items = Vec::with_capacity(snapshot.len());
                for item in &snapshot {
                    resolved_items.push(resolve_proxy(item).await?);
                }
                resolved_args.push(Value::List(shared_list(resolved_items)));
            }
            Value::Tuple(items) => {
                let mut resolved_items = Vec::with_capacity(items.len());
                for item in &items {
                    resolved_items.push(resolve_proxy(item).await?);
                }
                resolved_args.push(Value::Tuple(resolved_items));
            }
            other => resolved_args.push(other),
        }
    }
    Ok(resolved_args)
}

/// Resolve lazy-proxy values nested in keyword arguments.
pub(super) async fn resolve_method_kwargs(
    kwargs: &IndexMap<String, Value>,
) -> Result<IndexMap<String, Value>, EvalError> {
    let mut resolved = IndexMap::with_capacity(kwargs.len());
    for (k, v) in kwargs {
        resolved.insert(k.clone(), resolve_proxy(v).await?);
    }
    Ok(resolved)
}

// ---------------------------------------------------------------------------
// Per-type method handlers (fn-pointer table)
// ---------------------------------------------------------------------------

/// Signature of a builtin method-table entry.
type MethodsHandler =
    fn(&mut Value, &str, &[Value], &IndexMap<String, Value>) -> Result<MethodOutcome, EvalError>;

fn str_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::String(s) = obj else {
        return Err(type_mismatch("str"));
    };
    methods::str::dispatch_string_method(s, method, args, kwargs).map(MethodOutcome::pure)
}

fn list_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::List(items) = obj else {
        return Err(type_mismatch("list"));
    };
    let mut guard = items.lock();
    methods::list::dispatch_list_method(&mut guard, method, args, kwargs)
}

fn dict_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::Dict(map) = obj else {
        return Err(type_mismatch("dict"));
    };
    methods::dict::dispatch_dict_method(map, method, args, kwargs)
}

fn counter_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::Counter(map) = obj else {
        return Err(type_mismatch("Counter"));
    };
    methods::counter::dispatch_counter_method(map, method, args, kwargs)
}

fn deque_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::Deque { items, maxlen } = obj else {
        return Err(type_mismatch("deque"));
    };
    methods::deque::dispatch_deque_method(items, maxlen.as_ref(), method, args, kwargs)
}

fn defaultdict_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::DefaultDict(data) = obj else {
        return Err(type_mismatch("defaultdict"));
    };
    methods::dict::dispatch_dict_method(&mut data.items, method, args, kwargs)
}

fn set_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::Set(items) = obj else {
        return Err(type_mismatch("set"));
    };
    methods::set::dispatch_set_method(items, method, args, kwargs)
}

fn tuple_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::Tuple(items) = obj else {
        return Err(type_mismatch("tuple"));
    };
    methods::tuple::dispatch_tuple_method(items, method, args, kwargs).map(MethodOutcome::pure)
}

fn int_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    match obj {
        Value::Int(i) => {
            methods::int::dispatch_int_method(*i, method, args, kwargs).map(MethodOutcome::pure)
        }
        Value::BigInt(i) => match i64::try_from(i.as_ref()) {
            Ok(n) => {
                methods::int::dispatch_int_method(n, method, args, kwargs).map(MethodOutcome::pure)
            }
            Err(_) => Err(EvalError::Exception(crate::value::ExceptionValue::new(
                "OverflowError",
                "Python int too large to convert to C long",
            ))),
        },
        _ => Err(type_mismatch("int")),
    }
}

fn bytes_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::Bytes(b) = obj else {
        return Err(type_mismatch("bytes"));
    };
    methods::bytes::dispatch_bytes_method(b, method, args, kwargs).map(MethodOutcome::pure)
}

fn date_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::Date(date) = obj else {
        return Err(type_mismatch("date"));
    };
    crate::eval::modules::datetime::dispatch_date_method(*date, method, args, kwargs)
        .map(MethodOutcome::pure)
}

fn datetime_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::DateTime { dt, tz_offset_secs } = obj else {
        return Err(type_mismatch("datetime"));
    };
    crate::eval::modules::datetime::dispatch_datetime_method(
        *dt,
        *tz_offset_secs,
        method,
        args,
        kwargs,
    )
    .map(MethodOutcome::pure)
}

fn time_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::Time(t) = obj else {
        return Err(type_mismatch("time"));
    };
    crate::eval::modules::datetime::dispatch_time_method(*t, method, args, kwargs)
        .map(MethodOutcome::pure)
}

fn timedelta_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::TimeDelta(micros) = obj else {
        return Err(type_mismatch("timedelta"));
    };
    crate::eval::modules::datetime::dispatch_timedelta_method(*micros, method, args, kwargs)
        .map(MethodOutcome::pure)
}

fn re_match_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::ReMatch(m) = obj else {
        return Err(type_mismatch("re.Match"));
    };
    crate::eval::modules::re::dispatch_match_method(m, method, args, kwargs)
        .map(MethodOutcome::pure)
}

fn hash_digest_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::HashDigest { algo, bytes } = obj else {
        return Err(type_mismatch("HASH"));
    };
    crate::eval::modules::hashlib::dispatch_hash_method(algo, bytes, method, args, kwargs)
        .map(MethodOutcome::pure)
}

fn type_mismatch(expected: &str) -> EvalError {
    InterpreterError::TypeError(format!("internal: method table expected {expected}")).into()
}

/// Look up the method-table handler for `obj`'s runtime type.
fn methods_handler_for(obj: &Value) -> Option<MethodsHandler> {
    match obj {
        Value::String(_) => Some(str_methods),
        Value::List(_) => Some(list_methods),
        Value::Dict(_) => Some(dict_methods),
        Value::Counter(_) => Some(counter_methods),
        Value::Deque { .. } => Some(deque_methods),
        Value::DefaultDict(_) => Some(defaultdict_methods),
        Value::Set(_) => Some(set_methods),
        Value::Tuple(_) => Some(tuple_methods),
        Value::Int(_) | Value::BigInt(_) => Some(int_methods),
        Value::Bytes(_) => Some(bytes_methods),
        Value::Date(_) => Some(date_methods),
        Value::DateTime { .. } => Some(datetime_methods),
        Value::Time(_) => Some(time_methods),
        Value::TimeDelta(_) => Some(timedelta_methods),
        Value::ReMatch(_) => Some(re_match_methods),
        Value::HashDigest { .. } => Some(hash_digest_methods),
        _ => None,
    }
}

/// Dispatch a method call against a mutable receiver slot.
///
/// Table-driven: each method-bearing builtin has a dedicated handler
/// (see [`methods_handler_for`]). Read-only methods return a fresh value
/// (`mem_delta == 0`); mutating methods modify `obj` in place and report
/// the byte delta. `args` / `kwargs` must already be proxy-resolved
/// (see [`resolve_method_args`] / [`resolve_method_kwargs`]).
pub(super) fn dispatch_method(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Some(handler) = methods_handler_for(obj) else {
        debug_assert!(
            !crate::types::type_has_methods_table(obj),
            "type {} claims has_methods_table but has no handler",
            crate::types::type_name_of(obj)
        );
        return Err(InterpreterError::AttributeError(format!(
            "'{}' object has no attribute '{method}'",
            obj.type_name()
        ))
        .into());
    };
    handler(obj, method, args, kwargs)
}

/// Fetch the single required positional argument for a method, with a Python-
/// style `TypeError` naming the method when it is missing.
pub(crate) fn arg1<'a>(method: &str, args: &'a [Value]) -> Result<&'a Value, EvalError> {
    args.first().ok_or_else(|| {
        EvalError::from(InterpreterError::TypeError(format!("{method}() takes exactly 1 argument")))
    })
}