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

use indexmap::IndexMap;
use rustpython_parser::ast::{self, Expr};

use super::{
    builtins::{is_exception_type_name, try_builtin},
    dispatch::{call_lambda, call_user_function, call_value_as_function},
    helpers::{SortRequest, dsu_sort, list_sort_type_error},
    method_dispatch::{CallArgs, dispatch_method, resolve_method_args},
};
use crate::{
    error::{EvalError, EvalResult, InterpreterError},
    eval::{eval_expr, place},
    state::{InterpreterState, estimate_value_size},
    tools::Tools,
    value::{ExceptionValue, Value, ValueKey},
};

/// Evaluate a function call expression.
pub async fn eval_call(
    state: &mut InterpreterState,
    node: &ast::ExprCall,
    tools: &Tools,
) -> EvalResult {
    // Resolve the function name for dispatch
    let (func_name, is_method_call, method_obj_expr) = resolve_func_info(&node.func);

    // Evaluate positional arguments
    let mut args = Vec::new();
    for arg_expr in &node.args {
        if let Expr::Starred(starred) = arg_expr {
            // *args unpacking
            let val = eval_expr(state, &starred.value, tools).await?;
            let items = crate::eval::op::iter(state, &val, tools).await?;
            args.extend(items);
        } else {
            args.push(eval_expr(state, arg_expr, tools).await?);
        }
    }

    // Evaluate keyword arguments
    let mut kwargs: IndexMap<String, Value> = IndexMap::new();
    for kw in &node.keywords {
        if let Some(ref arg_name) = kw.arg {
            let val = eval_expr(state, &kw.value, tools).await?;
            kwargs.insert(arg_name.as_str().to_string(), val);
        } else {
            // **kwargs unpacking
            let val = eval_expr(state, &kw.value, tools).await?;
            if let Value::Dict(map) = val {
                for (k, v) in map {
                    if let ValueKey::String(key_str) = k {
                        kwargs.insert(key_str.into(), v);
                    }
                }
            } else {
                return Err(InterpreterError::TypeError(
                    "** operator requires a dictionary".into(),
                )
                .into());
            }
        }
    }

    // Method call dispatch (obj.method())
    if is_method_call {
        if let Some(obj_expr) = method_obj_expr {
            let method_name = func_name.as_deref().unwrap_or("");
            let resolved_args = resolve_method_args(&args).await?;

            // `str.format` / `str.format_map` are printf-equivalent string
            // building, not a security risk. They are special-cased here because
            // they are the only string methods that consume keyword arguments
            // (`"{k}".format(k=v)`), which the positional-only `dispatch_method`
            // signature does not carry. They never mutate the receiver, so it is
            // evaluated by value.
            if matches!(method_name, "format" | "format_map") {
                let obj = eval_expr(state, obj_expr, tools).await?;
                let Value::String(template) = obj else {
                    return Err(InterpreterError::AttributeError(format!(
                        "'{}' object has no attribute '{method_name}'",
                        obj.type_name()
                    ))
                    .into());
                };
                if method_name == "format" {
                    return crate::eval::strings::str_format(&template, &resolved_args, &kwargs);
                }
                // format_map: take the single mapping argument as the keywords.
                let mapping = resolved_args.first().and_then(Value::as_dict).ok_or_else(|| {
                    EvalError::from(InterpreterError::TypeError(
                        "format_map() requires a mapping argument".into(),
                    ))
                })?;
                let kw: IndexMap<String, Value> = mapping
                    .iter()
                    .filter_map(|(k, v)| match k {
                        ValueKey::String(s) => Some((s.as_str().to_string(), v.clone())),
                        _ => None,
                    })
                    .collect();
                return crate::eval::strings::str_format(&template, &[], &kw);
            }

            // `list.sort()` is the only OTHER builtin method (besides
            // str.format/format_map above) that takes kwargs — CPython
            // 3.12: `list.sort(*, key=None, reverse=False)`, both
            // keyword-only. The positional dispatch_method path strips
            // kwargs, so handle it here. Async + receiver mutation +
            // key= dispatch through call_value_as_function: shares
            // `dsu_sort` with the `sorted` builtin so comparator +
            // reversal semantics stay in one place.
            if method_name == "sort" {
                if !resolved_args.is_empty() {
                    return Err(InterpreterError::TypeError(
                        "sort() takes no positional arguments".into(),
                    )
                    .into());
                }
                let key_fn = kwargs.get("key").cloned();
                let reverse = kwargs.get("reverse").is_some_and(Value::is_truthy);

                // Two paths converge on `items: Vec<Value>`:
                //   * Place receiver (`xs.sort()` where xs is a variable / index path): mem::take
                //     from the navigated slot so dsu_sort can hold &mut state across its await
                //     chain. The sorted Vec is written back via a second navigate after the await —
                //     CPython mutates the list in place, so downstream code observing xs sees the
                //     order.
                //   * Temporary receiver (`[1,2].sort()`, `f().sort()`): destructure the owned
                //     Value. No write-back path; matches CPython where the temp is unobservable.
                let raw_place = place::eval_place(state, obj_expr, tools).await?;
                let usable_place =
                    raw_place.filter(|p| p.is_navigable() && state.variables.contains_key(&p.root));

                let items: Vec<Value> = if let Some(place) = &usable_place {
                    let root = state.variables.get_mut(&place.root).ok_or_else(|| {
                        EvalError::from(InterpreterError::name_not_defined(&place.root))
                    })?;
                    place::with_navigate_mut(root, &place.steps, |target| {
                        let Value::List(items) = target else {
                            return Err(list_sort_type_error(target.type_name()));
                        };
                        // Take the contents out under the lock — the
                        // SharedList stays valid and any aliases see an
                        // empty list while the sort is in flight, then
                        // the sorted contents get written back below.
                        Ok(std::mem::take(&mut *items.lock()))
                    })??
                } else {
                    let obj = eval_expr(state, obj_expr, tools).await?;
                    let Value::List(items) = obj else {
                        return Err(list_sort_type_error(obj.type_name()));
                    };
                    // Temporary receiver — extract the Vec; uniquely
                    // owned avoids a clone, aliased clones the contents.
                    match std::sync::Arc::try_unwrap(items) {
                        Ok(mutex) => mutex.into_inner(),
                        Err(shared) => shared.lock().clone(),
                    }
                };

                let sorted =
                    dsu_sort(state, tools, SortRequest { items, key_fn: key_fn.as_ref(), reverse })
                        .await?;

                if let Some(place) = usable_place {
                    let root = state.variables.get_mut(&place.root).ok_or_else(|| {
                        EvalError::from(InterpreterError::name_not_defined(&place.root))
                    })?;
                    place::with_navigate_mut(root, &place.steps, |target| {
                        if let Value::List(items) = target {
                            *items.lock() = sorted;
                        }
                    })?;
                }
                return Ok(Value::None);
            }

            // Lvalue receiver (`groups[1].append(5)`, `p.method()`): navigate a
            // single `&mut` borrow to the real slot. A built-in container method
            // mutates it in place with an O(1) memory delta; an instance method
            // runs through `call_method` and the mutated `self` is written back.
            // Neither path clones the root.
            // Only an actual variable can be navigated as a place; auto-imported
            // modules (`json`, `re`, `datetime`) are resolved on lookup, not
            // stored, so they fall through to the temporary path below.
            //
            // Track E: pre-touch defaultdict entries on the receiver path so
            // `d[key].append(x)` synthesises the missing entry before navigate.
            crate::eval::statements::pretouch_defaultdict(state, obj_expr, tools).await?;
            if let Some(place) = place::eval_place(state, obj_expr, tools).await? {
                if place.is_navigable() && state.variables.contains_key(&place.root) {
                    // Classify the receiver while holding the borrow, then act
                    // after it is released — an instance method call is async and
                    // needs `&mut state` again.
                    enum Dispatch {
                        Done(Value, isize),
                        Instance(Value),
                        Module(String),
                        Class(String),
                    }
                    let dispatch = {
                        let root = state.variables.get_mut(&place.root).ok_or_else(|| {
                            EvalError::from(InterpreterError::name_not_defined(&place.root))
                        })?;
                        let result: Result<Dispatch, EvalError> =
                            place::with_navigate_mut(root, &place.steps, |target| match target {
                                Value::Instance(_) => Ok(Dispatch::Instance(target.clone())),
                                Value::Module(module) => Ok(Dispatch::Module(module.clone())),
                                Value::Class(class_name) => Ok(Dispatch::Class(class_name.clone())),
                                _ => {
                                    let outcome =
                                        dispatch_method(target, method_name, &resolved_args)?;
                                    Ok(Dispatch::Done(outcome.value, outcome.mem_delta))
                                }
                            })?;
                        result?
                    };
                    match dispatch {
                        Dispatch::Done(value, mem_delta) => {
                            place::apply_mem_delta(state, mem_delta)?;
                            return Ok(value);
                        }
                        Dispatch::Module(module) => {
                            return crate::eval::modules::call_function(
                                state,
                                &module,
                                method_name,
                                &resolved_args,
                                &kwargs,
                                tools,
                            )
                            .await;
                        }
                        Dispatch::Class(class_name) => {
                            // Class.method(...) — Track B2:
                            //   * staticmethod: call without receiver
                            //   * classmethod: call with the class as first arg (bound by
                            //     call_method)
                            // Regular instance methods cannot be called
                            // unbound through the class (CPython raises
                            // TypeError "missing 1 required positional
                            // argument: 'self'" when the user forgets).
                            // We surface the same error shape by
                            // falling through to the unbound-call attempt
                            // and letting param binding fail.
                            if let Some(def) = crate::eval::classes::lookup_static_method(
                                state,
                                &class_name,
                                method_name,
                            ) {
                                return call_user_function(
                                    state,
                                    &def,
                                    &resolved_args,
                                    &kwargs,
                                    tools,
                                )
                                .await;
                            }
                            if let Some(def) = crate::eval::classes::lookup_class_method(
                                state,
                                &class_name,
                                method_name,
                            ) {
                                let call =
                                    CallArgs { positional: &resolved_args, keyword: &kwargs };
                                let (returned, _self) = crate::eval::classes::call_method(
                                    state,
                                    &def,
                                    Value::Class(class_name.clone()),
                                    call,
                                    tools,
                                )
                                .await?;
                                return Ok(returned);
                            }
                            return Err(InterpreterError::AttributeError(format!(
                                "type object '{class_name}' has no attribute '{method_name}'"
                            ))
                            .into());
                        }
                        Dispatch::Instance(instance) => {
                            let call = CallArgs { positional: &resolved_args, keyword: &kwargs };
                            let (returned, configured_self) =
                                crate::eval::classes::instance_method_call(
                                    state,
                                    instance,
                                    method_name,
                                    call,
                                    tools,
                                )
                                .await?;
                            let delta = {
                                let root =
                                    state.variables.get_mut(&place.root).ok_or_else(|| {
                                        EvalError::from(InterpreterError::name_not_defined(
                                            &place.root,
                                        ))
                                    })?;
                                place::with_navigate_mut(root, &place.steps, |slot| {
                                    let delta = place::size_delta(
                                        estimate_value_size(slot),
                                        estimate_value_size(&configured_self),
                                    );
                                    *slot = configured_self;
                                    delta
                                })?
                            };
                            place::apply_mem_delta(state, delta)?;
                            return Ok(returned);
                        }
                    }
                }
            }

            // Non-lvalue receiver (literal, call result, or a slice expression):
            // dispatch against a temporary. Any mutation affects only the
            // discarded value, matching CPython where `[1, 2].append(3)` mutates
            // an object that is immediately thrown away.
            let mut temp = eval_expr(state, obj_expr, tools).await?;
            if matches!(temp, Value::Instance(_)) {
                let call = CallArgs { positional: &resolved_args, keyword: &kwargs };
                let (returned, _self) = crate::eval::classes::instance_method_call(
                    state,
                    temp,
                    method_name,
                    call,
                    tools,
                )
                .await?;
                return Ok(returned);
            }
            // super().method(...): walk the MRO starting at the slot
            // AFTER defining_class. The receiver passed to the method
            // is the original instance, not the Super proxy — matches
            // CPython's bound-method-with-overridden-MRO behaviour.
            if let Value::Super { defining_class, instance } = &temp {
                let call = CallArgs { positional: &resolved_args, keyword: &kwargs };
                let recv = crate::eval::classes::SuperReceiver {
                    defining_class,
                    instance: (**instance).clone(),
                };
                let (returned, _self) =
                    crate::eval::classes::super_method_call(state, recv, method_name, call, tools)
                        .await?;
                return Ok(returned);
            }
            if let Value::Module(module) = &temp {
                let module_name = module.clone();
                return crate::eval::modules::call_function(
                    state,
                    &module_name,
                    method_name,
                    &resolved_args,
                    &kwargs,
                    tools,
                )
                .await;
            }
            // Type-as-receiver classmethod: `dict.fromkeys(iterable,
            // value)`. The receiver is a BuiltinName for the type; we
            // route to the classmethod-aware handler in
            // call_value_as_function.
            if let Value::BuiltinName(type_name) = &temp {
                let unbound = Value::BuiltinTypeMethod {
                    type_name: type_name.clone(),
                    method: method_name.to_string(),
                };
                return call_value_as_function(state, &unbound, &resolved_args, tools).await;
            }
            return Ok(dispatch_method(&mut temp, method_name, &resolved_args)?.value);
        }
    }

    let name = func_name.as_deref().unwrap_or("");

    // 1. Tool dispatch — short-circuits on builtins so a host-registered tool named e.g. `print`
    //    cannot shadow the interpreter's own builtin. Delegates to
    //    `tools::resolver::resolve_and_dispatch` so the tool-resolution logic stays isolated and
    //    testable.
    if let Some(value) = crate::tools::resolver::resolve_and_dispatch(
        state,
        crate::tools::resolver::ToolCallDescriptor { name, args: &args, kwargs: &kwargs },
        tools,
    )
    .await?
    {
        return Ok(value);
    }

    // 2. Check builtins
    if let Some(result) = try_builtin(state, name, &args, &kwargs, tools).await? {
        return Ok(result);
    }

    // 4. Check state variables (user-defined functions / lambdas)
    let func_val = state.get_variable(name).cloned();
    if let Some(func_val) = func_val {
        match func_val {
            Value::Function(ref func_def) => {
                return call_user_function(state, func_def, &args, &kwargs, tools).await;
            }
            Value::Lambda(ref lambda_def) => {
                return call_lambda(state, lambda_def, &args, &kwargs, tools).await;
            }
            // Calling a class object instantiates it.
            Value::Class(ref class_name) => {
                return crate::eval::classes::instantiate(state, class_name, &args, &kwargs, tools)
                    .await;
            }
            // A name pulled in via `from module import func` (e.g. `sqrt`).
            Value::ModuleFunction { ref module, name: ref func } => {
                let module_name = module.clone();
                let func_name = func.clone();
                return crate::eval::modules::call_function(
                    state,
                    &module_name,
                    &func_name,
                    &args,
                    &kwargs,
                    tools,
                )
                .await;
            }
            // Everything else — BoundMethod, BuiltinTypeMethod, the
            // `__builtin__`/`__tool__`/`__class_method__` sentinel
            // strings — funnel through `call_value_as_function` so
            // every call surface uses the same dispatch table. The
            // direct-call name-lookup path used to error "'name' is
            // not callable" here, which was the bug that left
            // `fn = d.get; fn('A')` and `f = int; f("42")` broken
            // even after BoundMethod landed.
            ref other => {
                return call_value_as_function(state, other, &args, tools).await;
            }
        }
    }

    // 5. Check if it's an exception type constructor. With the
    // ExceptionType variant in play, indirect calls
    // (`E = ValueError; E("msg")`) route through call_value_as_function;
    // this arm covers the direct-call form where `name` is the raw
    // identifier from the AST. Args are preserved for `e.args`.
    if is_exception_type_name(name) {
        let message = match args.len() {
            0 => String::new(),
            1 => format!("{}", args[0]),
            _ => args.iter().map(|v| format!("{v}")).collect::<Vec<_>>().join(", "),
        };
        return Ok(Value::Exception(ExceptionValue::new(name, message).with_args(args.clone())));
    }

    // `NameError`'s Display already renders `name '{0}' is not defined`, so the
    // variant payload is the bare identifier — passing a pre-formatted sentence
    // here double-wraps it into `name 'name '…' is not defined' is not defined`.
    Err(InterpreterError::name_not_defined(name).into())
}

/// Extract function name and method call info from a Call func expression.
fn resolve_func_info(func_expr: &Expr) -> (Option<String>, bool, Option<&Expr>) {
    match func_expr {
        Expr::Name(name_node) => (Some(name_node.id.as_str().to_string()), false, None),
        Expr::Attribute(attr_node) => {
            (Some(attr_node.attr.as_str().to_string()), true, Some(attr_node.value.as_ref()))
        }
        _ => (None, false, None),
    }
}