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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
// Copyright 2026 Thomas Santerre and Moderately AI Inc.
//
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Emulation of Python's `collections` module — Counter, deque,
//! defaultdict, OrderedDict.

use std::collections::VecDeque;

use indexmap::IndexMap;

use crate::{
    error::{EvalError, EvalResult, InterpreterError},
    eval::{control_flow::iterate_value, literals::value_to_key},
    value::{Value, ValueKey},
};

/// Whether `collections` provides a callable named `name`.
pub fn has_function(name: &str) -> bool {
    matches!(name, "Counter" | "deque" | "defaultdict" | "OrderedDict" | "namedtuple" | "ChainMap")
}

/// Snapshot a `dict` or `Counter` argument's entries into an owned map
/// (Dict is behind a lock; Counter stores an `IndexMap` by value).
fn dict_or_counter_contents(arg: &Value) -> Option<IndexMap<ValueKey, Value>> {
    match arg {
        Value::Dict(map) => Some(map.lock().clone()),
        Value::Counter(map) => Some(map.clone()),
        _ => None,
    }
}

/// Invoke a `collections` callable.
pub fn call(func: &str, args: &[Value], kwargs: &IndexMap<String, Value>) -> EvalResult {
    match func {
        // `Counter(iterable)` tallies element occurrences (Track B3).
        // `Counter(apple=3, banana=2)` seeds counts from keyword args
        // — CPython's documented constructor surface.
        "Counter" => {
            let mut counts: IndexMap<ValueKey, Value> = IndexMap::new();
            if let Some(arg) = args.first() {
                if let Some(map) = dict_or_counter_contents(arg) {
                    for (k, v) in &map {
                        counts.insert(k.clone(), v.clone());
                    }
                } else {
                    for item in iterate_value(arg)? {
                        let key = value_to_key(&item)?;
                        let entry = counts.entry(key).or_insert(Value::Int(0));
                        if let Value::Int(n) = entry {
                            *n += 1;
                        }
                    }
                }
            }
            for (key, value) in kwargs {
                counts.insert(ValueKey::String(key.as_str().into()), value.clone());
            }
            Ok(Value::Counter(counts))
        }
        // `deque([iterable, [maxlen]])` — double-ended queue.
        "deque" => {
            let items: VecDeque<Value> = match args.first() {
                None | Some(Value::None) => VecDeque::new(),
                Some(arg) => iterate_value(arg)?.into_iter().collect(),
            };
            // `maxlen` is accepted positionally (arg 1) or by keyword.
            let maxlen = match args.get(1).or_else(|| kwargs.get("maxlen")) {
                None | Some(Value::None) => None,
                Some(Value::Int(n)) => Some(usize::try_from(*n).map_err(|_| {
                    EvalError::from(InterpreterError::ValueError(
                        "deque maxlen must be non-negative".into(),
                    ))
                })?),
                Some(other) => {
                    return Err(InterpreterError::TypeError(format!(
                        "deque maxlen must be an integer or None (got '{}')",
                        other.type_name()
                    ))
                    .into());
                }
            };
            // Apply maxlen by trimming from the front.
            let mut deque = items;
            if let Some(cap) = maxlen {
                while deque.len() > cap {
                    deque.pop_front();
                }
            }
            Ok(Value::Deque { items: deque, maxlen })
        }
        // `defaultdict(factory[, mapping_or_iterable])` — dict with
        // missing-key synthesis. Factory must be callable.
        "defaultdict" => {
            let factory = args.first().cloned().unwrap_or(Value::None);
            // Accept Function/Lambda/Class/None plus the typed
            // BuiltinName variant that bare names like `int`/`list`/
            // `dict` resolve to. invoke_factory in eval/names.rs
            // handles the BuiltinName-to-empty-container call.
            if !matches!(
                factory,
                Value::Function(_)
                    | Value::Lambda(_)
                    | Value::Class(_)
                    | Value::None
                    | Value::BuiltinName(_)
            ) {
                return Err(InterpreterError::TypeError(format!(
                    "first argument must be callable or None (got '{}')",
                    factory.type_name()
                ))
                .into());
            }
            let mut items: IndexMap<ValueKey, Value> = IndexMap::new();
            if let Some(arg) = args.get(1) {
                if let Value::Dict(map) = arg {
                    for (k, v) in map.lock().iter() {
                        items.insert(k.clone(), v.clone());
                    }
                } else {
                    for pair in iterate_value(arg)? {
                        let pair_items = iterate_value(&pair)?;
                        if pair_items.len() != 2 {
                            return Err(InterpreterError::ValueError(
                                "defaultdict iterable elements must be 2-tuples".into(),
                            )
                            .into());
                        }
                        let key = value_to_key(&pair_items[0])?;
                        items.insert(key, pair_items[1].clone());
                    }
                }
            }
            Ok(Value::DefaultDict(Box::new(crate::value::DefaultDictData { items, factory })))
        }
        // `OrderedDict([mapping_or_iterable])` — Track E thin shim.
        // CPython's dict has been insertion-ordered since 3.7, so we
        // return a regular Dict. `move_to_end` is exposed via dict's
        // method dispatch (Track E batch 3 addition).
        "OrderedDict" => {
            let mut entries: IndexMap<ValueKey, Value> = IndexMap::new();
            if let Some(arg) = args.first() {
                if let Some(map) = dict_or_counter_contents(arg) {
                    for (k, v) in &map {
                        entries.insert(k.clone(), v.clone());
                    }
                } else {
                    for pair in iterate_value(arg)? {
                        let pair_items = iterate_value(&pair)?;
                        if pair_items.len() != 2 {
                            return Err(InterpreterError::ValueError(
                                "OrderedDict iterable elements must be 2-tuples".into(),
                            )
                            .into());
                        }
                        let key = value_to_key(&pair_items[0])?;
                        entries.insert(key, pair_items[1].clone());
                    }
                }
            }
            // Keyword arguments seed additional entries (CPython:
            // `OrderedDict(x=1, y=2)`), applied after the positional source.
            for (k, v) in kwargs {
                entries.insert(ValueKey::String(k.as_str().into()), v.clone());
            }
            Ok(Value::OrderedDict(crate::value::shared_dict(entries)))
        }
        // `ChainMap(*maps)` — search the maps left-to-right; writes hit
        // the first. Each map must be a dict (our mapping model); no
        // args seeds a single empty dict, matching CPython.
        "ChainMap" => {
            let mut maps: Vec<Value> = Vec::with_capacity(args.len().max(1));
            for arg in args {
                if !matches!(arg, Value::Dict(_)) {
                    return Err(InterpreterError::TypeError(format!(
                        "ChainMap() argument must be a mapping, not '{}'",
                        arg.type_name()
                    ))
                    .into());
                }
                maps.push(arg.clone());
            }
            if maps.is_empty() {
                maps.push(Value::Dict(crate::value::shared_dict(IndexMap::new())));
            }
            Ok(Value::ChainMap(maps))
        }
        _ => Err(InterpreterError::AttributeError(format!(
            "module 'collections' has no attribute '{func}'"
        ))
        .into()),
    }
}

/// Render a namedtuple field value to its name string (CPython `str(name)`), so
/// a non-string field is stringified rather than dropped.
fn field_name_str(v: &Value) -> String {
    match v {
        Value::String(s) => s.to_string(),
        other => format!("{other}"),
    }
}

/// Validate a namedtuple typename or field name (CPython rules): a valid
/// identifier and not a keyword; a field name additionally must not start with
/// an underscore.
fn validate_namedtuple_name(name: &str, is_field: bool) -> Result<(), EvalError> {
    use crate::eval::modules::value_error;
    if !is_python_identifier(name) {
        return Err(value_error(format!(
            "Type names and field names must be valid identifiers: {name:?}"
        )));
    }
    if is_python_keyword(name) {
        return Err(value_error(format!(
            "Type names and field names cannot be a keyword: {name:?}"
        )));
    }
    if is_field && name.starts_with('_') {
        return Err(value_error(format!("Field names cannot start with an underscore: {name:?}")));
    }
    Ok(())
}

/// A valid Python identifier: a leading letter or underscore, then letters,
/// digits, or underscores. Unicode letters are accepted (Python 3 allows them).
fn is_python_identifier(s: &str) -> bool {
    let mut chars = s.chars();
    match chars.next() {
        Some(c) if c == '_' || c.is_alphabetic() => {}
        _ => return false,
    }
    chars.all(|c| c == '_' || c.is_alphanumeric())
}

fn is_python_keyword(s: &str) -> bool {
    matches!(
        s,
        "False"
            | "None"
            | "True"
            | "and"
            | "as"
            | "assert"
            | "async"
            | "await"
            | "break"
            | "class"
            | "continue"
            | "def"
            | "del"
            | "elif"
            | "else"
            | "except"
            | "finally"
            | "for"
            | "from"
            | "global"
            | "if"
            | "import"
            | "in"
            | "is"
            | "lambda"
            | "nonlocal"
            | "not"
            | "or"
            | "pass"
            | "raise"
            | "return"
            | "try"
            | "while"
            | "with"
            | "yield"
    )
}

/// Track E batch 3: `namedtuple(name, fields)` — synthesises a class
/// whose `__init__` binds positional args to the named fields. Field
/// access via attribute works; subscript (`nt[i]`) is handled in
/// `eval_subscript`; iteration / `len` use the `_fields` class attr
/// via `op::namedtuple_items` (field order). `_fields` also drives
/// PEP 634 `__match_args__`.
pub(crate) fn call_namedtuple_with_state(
    state: &mut crate::state::InterpreterState,
    args: &[Value],
    kwargs: &indexmap::IndexMap<String, Value>,
) -> EvalResult {
    let class_name = match args.first() {
        Some(Value::String(s)) => s.clone(),
        _ => {
            return Err(InterpreterError::TypeError(
                "namedtuple() first argument must be the class name".into(),
            )
            .into());
        }
    };
    let fields: Vec<String> = match args.get(1) {
        Some(Value::String(s)) => {
            // Accept space-separated or comma-separated field strings.
            s.split(|c: char| c.is_whitespace() || c == ',')
                .filter(|s| !s.is_empty())
                .map(String::from)
                .collect()
        }
        // CPython stringifies each field (`list(map(str, field_names))`), so a
        // non-string is rendered rather than dropped, then validated below.
        Some(Value::List(items)) => items.lock().iter().map(field_name_str).collect(),
        Some(Value::Tuple(items)) => items.iter().map(field_name_str).collect(),
        _ => {
            return Err(InterpreterError::TypeError(
                "namedtuple() second argument must be a sequence of field names".into(),
            )
            .into());
        }
    };
    // Validate the typename and every field name, matching CPython's namedtuple
    // checks (identifier, not a keyword, no leading underscore, no duplicates).
    validate_namedtuple_name(&class_name, false)?;
    let mut seen = std::collections::HashSet::new();
    for f in &fields {
        validate_namedtuple_name(f, true)?;
        if !seen.insert(f.as_str()) {
            return Err(crate::eval::modules::value_error(format!(
                "Encountered duplicate field name: {f}"
            )));
        }
    }
    // Build a synthetic __init__ method that binds each positional
    // arg to the corresponding field. We do this by registering the
    // function bodies under qualified keys and adding the class to
    // state.classes.
    use std::collections::BTreeMap;

    use crate::value::{ClassValue, FunctionDef, FunctionParams, Param};
    // `defaults=` (keyword-only) supplies defaults for the RIGHTMOST fields:
    // `namedtuple("P", "x y z", defaults=[0, 0])` => y and z default to 0.
    let default_values: Vec<Value> = match kwargs.get("defaults") {
        None | Some(Value::None) => Vec::new(),
        Some(Value::List(items)) => items.lock().clone(),
        Some(Value::Tuple(items)) => items.clone(),
        Some(other) => {
            let mut collected = Vec::new();
            for v in crate::eval::control_flow::iterate_value(other)? {
                collected.push(v);
            }
            collected
        }
    };
    if default_values.len() > fields.len() {
        return Err(crate::eval::modules::value_error(
            "Got more default values than field names".to_string(),
        ));
    }
    let init_params = FunctionParams {
        args: std::iter::once(Param { name: "self".to_string(), annotation: None })
            .chain(fields.iter().map(|f| Param { name: f.clone(), annotation: None }))
            .collect(),
        defaults: default_values.iter().map(|v| v.repr()).collect(),
        default_values: default_values.clone(),
        vararg: None,
        kwonlyargs: Vec::new(),
        kw_defaults: Vec::new(),
        kw_default_values: Vec::new(),
        kwarg: None,
        posonly_count: 0,
    };
    // Build the body: self.field_n = field_n for each field.
    use rustpython_parser::{
        ast::{self as ast_, Expr, ExprAttribute, ExprContext, ExprName, Stmt, StmtAssign},
        text_size::TextRange,
    };
    let body: Vec<Stmt> = fields
        .iter()
        .map(|field| {
            let target = Expr::Attribute(ExprAttribute {
                value: Box::new(Expr::Name(ExprName {
                    id: ast_::Identifier::new("self"),
                    ctx: ExprContext::Store,
                    range: TextRange::default(),
                })),
                attr: ast_::Identifier::new(field.clone()),
                ctx: ExprContext::Store,
                range: TextRange::default(),
            });
            let value = Expr::Name(ExprName {
                id: ast_::Identifier::new(field.clone()),
                ctx: ExprContext::Load,
                range: TextRange::default(),
            });
            Stmt::Assign(StmtAssign {
                targets: vec![target],
                value: Box::new(value),
                type_comment: None,
                range: TextRange::default(),
            })
        })
        .collect();
    let init_key = format!("{class_name}.__init__");
    state.function_bodies.insert(init_key.clone(), std::sync::Arc::new(body));
    let init_def = FunctionDef {
        name: init_key,
        body_key: String::new(),
        wraps_name: None,
        params: init_params,
        closure: BTreeMap::new(),
        source: String::new(),
        nonlocal_names: Vec::new(),
        // Synthesized __init__ does not yield.
        is_generator: false,
        nonlocal_cell_id: None,
        // Synthesized namedtuple __init__ assigns to `self.<field>`
        // (attribute set, no local binding), so no checkpoint-tracked
        // names. Globals likewise empty.
        assigned_names: Vec::new(),
        global_names: Vec::new(),
        // Synthesized methods carry empty closures; the flag is
        // immaterial here.
        is_module_level: false,
        docstring: None,
        cell_refreshes: Vec::new(),
        qualname: String::new(),
        annotations: Vec::new(),
        is_async: false,
    };
    let mut methods: BTreeMap<String, FunctionDef> = BTreeMap::new();
    methods.insert("__init__".to_string(), init_def);

    // Synthesize `_asdict(self)` → `{<field>: self.<field>, ...}`.
    // Matches CPython's namedtuple._asdict, which returns a regular
    // dict in field order (no longer an OrderedDict since 3.8).
    use rustpython_parser::ast::{ExprDict, StmtReturn};
    let asdict_body = vec![Stmt::Return(StmtReturn {
        value: Some(Box::new(Expr::Dict(ExprDict {
            keys: fields
                .iter()
                .map(|f| {
                    Some(Expr::Constant(ast_::ExprConstant {
                        value: ast_::Constant::Str(f.clone()),
                        kind: None,
                        range: TextRange::default(),
                    }))
                })
                .collect(),
            values: fields
                .iter()
                .map(|f| {
                    Expr::Attribute(ExprAttribute {
                        value: Box::new(Expr::Name(ExprName {
                            id: ast_::Identifier::new("self"),
                            ctx: ExprContext::Load,
                            range: TextRange::default(),
                        })),
                        attr: ast_::Identifier::new(f.clone()),
                        ctx: ExprContext::Load,
                        range: TextRange::default(),
                    })
                })
                .collect(),
            range: TextRange::default(),
        }))),
        range: TextRange::default(),
    })];
    let asdict_key = format!("{class_name}._asdict");
    state.function_bodies.insert(asdict_key.clone(), std::sync::Arc::new(asdict_body));
    methods.insert(
        "_asdict".to_string(),
        FunctionDef {
            name: asdict_key,
            body_key: String::new(),
            wraps_name: None,
            params: FunctionParams {
                args: vec![Param { name: "self".to_string(), annotation: None }],
                defaults: Vec::new(),
                default_values: Vec::new(),
                vararg: None,
                kwonlyargs: Vec::new(),
                kw_defaults: Vec::new(),
                kw_default_values: Vec::new(),
                kwarg: None,
                posonly_count: 0,
            },
            closure: BTreeMap::new(),
            source: String::new(),
            nonlocal_names: Vec::new(),
            is_generator: false,
            nonlocal_cell_id: None,
            // Synthesized `_asdict` returns a dict literal with no
            // local bindings.
            assigned_names: Vec::new(),
            global_names: Vec::new(),
            is_module_level: false,
            docstring: None,
            cell_refreshes: Vec::new(),
            qualname: String::new(),
            annotations: Vec::new(),
            is_async: false,
        },
    );

    // Synthesize `_make` (staticmethod) and `_replace` (method) as thin
    // wrappers over the constructor:
    //   _make(iterable)  -> ClassName(*iterable)
    //   _replace(self, **kwargs) -> ClassName(**{**self._asdict(), **kwargs})
    use rustpython_parser::ast::{ExprCall, ExprStarred, Keyword};
    let name_expr = |id: &str| {
        Expr::Name(ExprName {
            id: ast_::Identifier::new(id),
            ctx: ExprContext::Load,
            range: TextRange::default(),
        })
    };
    // FunctionDef builder shared by the two synthesized wrappers.
    let mk_def = |key: String, params: FunctionParams| FunctionDef {
        name: key,
        body_key: String::new(),
        wraps_name: None,
        params,
        closure: BTreeMap::new(),
        source: String::new(),
        nonlocal_names: Vec::new(),
        is_generator: false,
        nonlocal_cell_id: None,
        assigned_names: Vec::new(),
        global_names: Vec::new(),
        is_module_level: false,
        docstring: None,
        cell_refreshes: Vec::new(),
        qualname: String::new(),
        annotations: Vec::new(),
        is_async: false,
    };
    let no_defaults = |args: Vec<Param>, kwarg: Option<String>| FunctionParams {
        args,
        defaults: Vec::new(),
        default_values: Vec::new(),
        vararg: None,
        kwonlyargs: Vec::new(),
        kw_defaults: Vec::new(),
        kw_default_values: Vec::new(),
        kwarg,
        posonly_count: 0,
    };

    let make_body = vec![Stmt::Return(StmtReturn {
        value: Some(Box::new(Expr::Call(ExprCall {
            func: Box::new(name_expr(&class_name)),
            args: vec![Expr::Starred(ExprStarred {
                value: Box::new(name_expr("iterable")),
                ctx: ExprContext::Load,
                range: TextRange::default(),
            })],
            keywords: vec![],
            range: TextRange::default(),
        }))),
        range: TextRange::default(),
    })];
    let make_key = format!("{class_name}._make");
    state.function_bodies.insert(make_key.clone(), std::sync::Arc::new(make_body));
    let mut static_methods: BTreeMap<String, FunctionDef> = BTreeMap::new();
    static_methods.insert(
        "_make".to_string(),
        mk_def(
            make_key,
            no_defaults(vec![Param { name: "iterable".to_string(), annotation: None }], None),
        ),
    );

    let merged_dict = Expr::Dict(ExprDict {
        keys: vec![None, None],
        values: vec![
            Expr::Call(ExprCall {
                func: Box::new(Expr::Attribute(ExprAttribute {
                    value: Box::new(name_expr("self")),
                    attr: ast_::Identifier::new("_asdict"),
                    ctx: ExprContext::Load,
                    range: TextRange::default(),
                })),
                args: vec![],
                keywords: vec![],
                range: TextRange::default(),
            }),
            name_expr("kwargs"),
        ],
        range: TextRange::default(),
    });
    let replace_body = vec![Stmt::Return(StmtReturn {
        value: Some(Box::new(Expr::Call(ExprCall {
            func: Box::new(name_expr(&class_name)),
            args: vec![],
            keywords: vec![Keyword { arg: None, value: merged_dict, range: TextRange::default() }],
            range: TextRange::default(),
        }))),
        range: TextRange::default(),
    })];
    let replace_key = format!("{class_name}._replace");
    state.function_bodies.insert(replace_key.clone(), std::sync::Arc::new(replace_body));
    methods.insert(
        "_replace".to_string(),
        mk_def(
            replace_key,
            no_defaults(
                vec![Param { name: "self".to_string(), annotation: None }],
                Some("kwargs".to_string()),
            ),
        ),
    );

    // Class attributes: _fields tuple, __match_args__ tuple (so PEP
    // 634 class patterns work on namedtuple instances).
    let mut class_attrs: BTreeMap<String, Value> = BTreeMap::new();
    let fields_tuple =
        Value::Tuple(fields.iter().map(|s| Value::String(s.as_str().into())).collect());
    class_attrs.insert("_fields".to_string(), fields_tuple.clone());
    class_attrs.insert("__match_args__".to_string(), fields_tuple);
    // `_field_defaults`: {field: default} for the trailing fields with a default,
    // matching CPython (defaults align to the rightmost fields).
    let mut field_defaults: indexmap::IndexMap<crate::value::ValueKey, Value> =
        indexmap::IndexMap::new();
    let default_start = fields.len().saturating_sub(default_values.len());
    for (field, dv) in fields[default_start..].iter().zip(default_values.iter()) {
        field_defaults.insert(crate::value::ValueKey::String(field.as_str().into()), dv.clone());
    }
    class_attrs.insert(
        "_field_defaults".to_string(),
        Value::Dict(crate::value::shared_dict(field_defaults)),
    );
    let class_name_str = class_name.to_string();
    state.classes.insert(class_name_str.clone(), {
        let mut cv = ClassValue::new(class_name_str.clone());
        cv.methods = methods;
        cv.static_methods = static_methods;
        cv.class_attrs = class_attrs;
        cv
    });
    Ok(Value::Class(class_name_str))
}

/// `collections` module registration. Handles the namedtuple special-
/// case (it needs `state` to synthesize a class) inside the trait
/// dispatch so the registry's [`Module::call`] surface stays uniform.
pub struct CollectionsModule;

#[async_trait::async_trait]
impl crate::eval::modules::Module for CollectionsModule {
    fn name(&self) -> &'static str {
        "collections"
    }
    fn has_function(&self, name: &str) -> bool {
        has_function(name)
    }
    async fn call(
        &self,
        state: &mut crate::state::InterpreterState,
        func: &str,
        args: &[Value],
        kwargs: &indexmap::IndexMap<String, Value>,
        tools: &crate::tools::Tools,
    ) -> EvalResult {
        match func {
            "namedtuple" => call_namedtuple_with_state(state, args, kwargs),
            // Counter needs the async hash/eq path when tallying instance
            // elements; the sync `call` handles every other constructor.
            "Counter" if counter_has_instance_items(args) => {
                counter_construct_async(state, args, kwargs, tools).await
            }
            _ => call(func, args, kwargs),
        }
    }
}

/// Whether `Counter(iterable)`'s positional argument is an iterable of
/// instances (so it needs `__hash__`/`__eq__` tallying, not `value_to_key`).
fn counter_has_instance_items(args: &[Value]) -> bool {
    let Some(arg) = args.first() else { return false };
    // A dict/Counter mapping argument keeps its existing (already-keyed) entries.
    if dict_or_counter_contents(arg).is_some() {
        return false;
    }
    iterate_value(arg).is_ok_and(|items| items.iter().any(|v| matches!(v, Value::Instance(_))))
}

/// `Counter(iterable_of_instances)` — tally by `__hash__`/`__eq__` since an
/// instance ValueKey compares by identity and cannot merge equal-but-distinct
/// instances through the sync entry API.
async fn counter_construct_async(
    state: &mut crate::state::InterpreterState,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
    tools: &crate::tools::Tools,
) -> EvalResult {
    let mut counts: IndexMap<ValueKey, Value> = IndexMap::new();
    if let Some(arg) = args.first() {
        for item in iterate_value(arg)? {
            if matches!(item, Value::Instance(_)) {
                let h = crate::eval::op::hash(state, &item, tools).await?;
                let mut found = false;
                for (k, v) in &mut counts {
                    if let ValueKey::Instance { hash: kh, value } = k {
                        if *kh == h && crate::eval::op::eq(state, value, &item, tools).await? {
                            if let Value::Int(n) = v {
                                *n += 1;
                            }
                            found = true;
                            break;
                        }
                    }
                }
                if !found {
                    counts.insert(
                        ValueKey::Instance { hash: h, value: Box::new(item.clone()) },
                        Value::Int(1),
                    );
                }
            } else {
                let key = value_to_key(&item)?;
                let entry = counts.entry(key).or_insert(Value::Int(0));
                if let Value::Int(n) = entry {
                    *n += 1;
                }
            }
        }
    }
    for (key, value) in kwargs {
        counts.insert(ValueKey::String(key.as_str().into()), value.clone());
    }
    Ok(Value::Counter(counts))
}