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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
// Copyright 2026 Thomas Santerre and Moderately AI Inc.
//
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::sync::Arc;

use indexmap::IndexMap;

use super::{methods, resolve_proxy};
use crate::{
    error::{EvalError, InterpreterError},
    eval::place,
    value::{Value, shared_dict, 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();
                // Preserve the original shared handle when nothing needs
                // resolving, so functions that mutate a list argument in
                // place (`heapq.heapify`, `list.sort` via a callable, …)
                // affect the caller's list — CPython reference semantics.
                // Only rebuild into a fresh Arc when an inner proxy must
                // be resolved.
                if snapshot.iter().any(|v| matches!(v, Value::LazyProxy(_))) {
                    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)));
                } else {
                    resolved_args.push(Value::List(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"));
    };
    // `l.extend(l)` iterates the argument while the receiver lock is held, which
    // would re-lock the same mutex (deadlock); snapshot an aliasing argument to
    // an independent copy first. This applies ONLY to methods that *iterate* the
    // argument — `append`/`insert` STORE it, so `l.append(l)` must keep the
    // self-reference (snapshotting there would break the cycle).
    let snapped;
    let args = if method == "extend"
        && args.iter().any(|a| matches!(a, Value::List(l) if Arc::ptr_eq(l, items)))
    {
        snapped = args
            .iter()
            .map(|a| match a {
                Value::List(l) if Arc::ptr_eq(l, items) => {
                    Value::List(shared_list(l.lock().clone()))
                }
                other => other.clone(),
            })
            .collect::<Vec<_>>();
        &snapped
    } else {
        args
    };
    let mut guard = items.lock();
    methods::list::dispatch_list_method(&mut guard, method, args, kwargs)
}

fn range_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    crate::eval::functions::reject_kwargs(method, kwargs)?;
    let Value::Range { start, stop, step } = obj else {
        return Err(type_mismatch("range"));
    };
    let (start, stop, step) = (*start, *stop, *step);
    // Membership + position are O(1) arithmetic (never materialise the range).
    let position = |v: &Value| -> Option<i64> {
        let n = match v {
            Value::Int(n) => *n,
            Value::Bool(b) => i64::from(*b),
            _ => return None,
        };
        if step == 0 {
            return None;
        }
        let in_bounds = if step > 0 { n >= start && n < stop } else { n <= start && n > stop };
        if in_bounds && (n - start) % step == 0 { Some((n - start) / step) } else { None }
    };
    match method {
        "index" => {
            let target = arg1(method, args)?;
            match position(target) {
                Some(i) => Ok(MethodOutcome::pure(Value::Int(i))),
                None => {
                    Err(InterpreterError::ValueError(format!("{target} is not in range")).into())
                }
            }
        }
        "count" => {
            let n = i64::from(args.first().is_some_and(|v| position(v).is_some()));
            Ok(MethodOutcome::pure(Value::Int(n)))
        }
        _ => Err(InterpreterError::AttributeError(format!(
            "'range' object has no attribute '{method}'"
        ))
        .into()),
    }
}

fn lru_methods(
    obj: &mut Value,
    method: &str,
    _args: &[Value],
    _kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    use std::sync::atomic::Ordering::Relaxed;
    let Value::LruCache(data) = obj else {
        return Err(type_mismatch("lru_cache"));
    };
    match method {
        // `CacheInfo(hits, misses, maxsize, currsize)` (the class is seeded in
        // InterpreterState::new so it reprs and attribute-accesses like CPython).
        "cache_info" => {
            let mut fields = std::collections::BTreeMap::new();
            fields.insert("hits".to_string(), Value::Int(data.hits.load(Relaxed) as i64));
            fields.insert("misses".to_string(), Value::Int(data.misses.load(Relaxed) as i64));
            fields.insert(
                "maxsize".to_string(),
                data.maxsize.map_or(Value::None, |m| Value::Int(m as i64)),
            );
            fields.insert("currsize".to_string(), Value::Int(data.cache.lock().len() as i64));
            Ok(MethodOutcome::pure(Value::Instance(crate::value::InstanceValue {
                class_name: "CacheInfo".to_string(),
                fields: crate::value::shared_fields(fields),
            })))
        }
        "cache_clear" => {
            data.cache.lock().clear();
            data.hits.store(0, Relaxed);
            data.misses.store(0, Relaxed);
            Ok(MethodOutcome::pure(Value::None))
        }
        _ => Err(InterpreterError::AttributeError(format!(
            "'functools._lru_cache_wrapper' object has no attribute '{method}'"
        ))
        .into()),
    }
}

fn array_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    use crate::eval::modules::array_mod::{coerce_element, itemsize};
    let Value::Array { typecode, items } = obj else {
        return Err(type_mismatch("array.array"));
    };
    let typecode = *typecode;
    match method {
        // Mutators that add elements coerce each to the array's element kind.
        "append" => {
            let coerced = coerce_element(typecode, arg1(method, args)?)?;
            let size = crate::state::estimate_value_size(&coerced);
            items.lock().push(coerced);
            Ok(MethodOutcome::grew(Value::None, size))
        }
        "extend" | "fromlist" => {
            let elems = crate::eval::control_flow::iterate_value(arg1(method, args)?)?;
            let mut guard = items.lock();
            let mut added = 0;
            for e in elems {
                let c = coerce_element(typecode, &e)?;
                added += crate::state::estimate_value_size(&c);
                guard.push(c);
            }
            Ok(MethodOutcome::grew(Value::None, added))
        }
        "insert" => {
            let idx = crate::eval::functions::value_to_i64(arg1(method, args)?)?;
            let value = coerce_element(
                typecode,
                args.get(1).ok_or_else(|| {
                    EvalError::from(InterpreterError::TypeError(
                        "insert() takes exactly 2 arguments".into(),
                    ))
                })?,
            )?;
            let size = crate::state::estimate_value_size(&value);
            let mut guard = items.lock();
            // Clamp the index into `[0, len]` the way list.insert does.
            let len = guard.len() as i64;
            let pos = if idx < 0 { (len + idx).max(0) } else { idx.min(len) } as usize;
            guard.insert(pos, value);
            Ok(MethodOutcome::grew(Value::None, size))
        }
        // A typed list copy.
        "tolist" => {
            let guard = items.lock();
            Ok(MethodOutcome::pure(Value::List(crate::value::shared_list(guard.clone()))))
        }
        // `(address, length)` — no real buffer, so the address is 0.
        "buffer_info" => {
            let len = items.lock().len() as i64;
            Ok(MethodOutcome::pure(Value::Tuple(vec![Value::Int(0), Value::Int(len)])))
        }
        "__len__" => Ok(MethodOutcome::pure(Value::Int(crate::eval::functions::to_len_i64(
            items.lock().len(),
        )?))),
        // pop/remove/index/count/reverse behave exactly as on the element list.
        "pop" | "remove" | "index" | "count" | "reverse" => {
            let _ = itemsize; // itemsize is exposed as an attribute, not a method
            let mut guard = items.lock();
            methods::list::dispatch_list_method(&mut guard, method, args, kwargs)
        }
        _ => Err(InterpreterError::AttributeError(format!(
            "'array.array' object has no attribute '{method}'"
        ))
        .into()),
    }
}

fn dict_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Some(map) = obj.as_dict() else {
        return Err(type_mismatch("dict"));
    };
    // `keys`/`values`/`items` return a LIVE view over the shared dict
    // (reflects later mutations, and keys/items are set-like) rather
    // than a materialised list.
    if let Some(kind) = match method {
        "keys" => Some(crate::value::DictViewKind::Keys),
        "values" => Some(crate::value::DictViewKind::Values),
        "items" => Some(crate::value::DictViewKind::Items),
        _ => None,
    } {
        reject_kwargs(method, kwargs)?;
        if !args.is_empty() {
            return Err(InterpreterError::TypeError(format!(
                "{method}() takes no arguments ({} given)",
                args.len()
            ))
            .into());
        }
        return Ok(MethodOutcome::pure(Value::DictView { dict: map.clone(), kind }));
    }
    // `d.update(d)` reads the argument under the receiver lock, which would
    // re-lock the same mutex (deadlock); snapshot an aliasing argument first.
    // Only for `update`, which iterates the argument — `setdefault`/`pop` STORE
    // it (`d.setdefault(k, d)` must keep the self-reference).
    let snapped;
    let args = if method == "update"
        && args.iter().any(|a| a.as_dict().is_some_and(|d| Arc::ptr_eq(d, map)))
    {
        snapped = args
            .iter()
            .map(|a| match a.as_dict() {
                Some(d) if Arc::ptr_eq(d, map) => Value::Dict(shared_dict(d.lock().clone())),
                _ => a.clone(),
            })
            .collect::<Vec<_>>();
        &snapped
    } else {
        args
    };
    // The dict methods are sync and mutate through the guard, so holding the
    // lock across the call is deadlock-free (the aliasing case is handled above).
    let mut guard = map.lock();
    methods::dict::dispatch_dict_method(&mut guard, 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 template_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::Template(template) = obj else {
        return Err(type_mismatch("Template"));
    };
    match method {
        // `substitute` raises on a missing key / bad placeholder;
        // `safe_substitute` leaves them in place.
        "substitute" | "safe_substitute" => {
            let safe = method == "safe_substitute";
            let rendered =
                super::super::strings::template_substitute(template, args, kwargs, safe)?;
            Ok(MethodOutcome::pure(Value::String(rendered.into())))
        }
        _ => Err(InterpreterError::AttributeError(format!(
            "'string.Template' object has no attribute '{method}'"
        ))
        .into()),
    }
}

fn chainmap_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::ChainMap(maps) = obj else {
        return Err(type_mismatch("ChainMap"));
    };
    match method {
        // `new_child(m=None)` prepends `m` (or a fresh empty dict).
        "new_child" => {
            let child = match args.first() {
                Some(v @ Value::Dict(_)) => v.clone(),
                None | Some(Value::None) => Value::Dict(crate::value::shared_dict(IndexMap::new())),
                Some(other) => {
                    return Err(InterpreterError::TypeError(format!(
                        "ChainMap.new_child() argument must be a mapping, not '{}'",
                        other.type_name()
                    ))
                    .into());
                }
            };
            let mut new_maps = Vec::with_capacity(maps.len() + 1);
            new_maps.push(child);
            new_maps.extend(maps.iter().cloned());
            Ok(MethodOutcome::pure(Value::ChainMap(new_maps)))
        }
        // `copy()` copies the first map, sharing the rest (CPython).
        "copy" => {
            let mut new_maps = maps.clone();
            let copied = match new_maps.first() {
                Some(Value::Dict(first)) => Some(crate::value::shared_dict(first.lock().clone())),
                _ => None,
            };
            if let Some(c) = copied {
                new_maps[0] = Value::Dict(c);
            }
            Ok(MethodOutcome::pure(Value::ChainMap(new_maps)))
        }
        // Read-only views search all maps (first-map value wins).
        "keys" | "values" | "items" | "get" | "__contains__" => {
            let mut merged = crate::types::chainmap_contents(maps);
            methods::dict::dispatch_dict_method(&mut merged, method, args, kwargs)
        }
        // Mutating methods (pop/popitem/clear/setdefault/update/…)
        // target the first map, matching CPython.
        _ => {
            if let Some(Value::Dict(first)) = maps.first() {
                let mut guard = first.lock();
                methods::dict::dispatch_dict_method(&mut guard, method, args, kwargs)
            } else {
                Err(InterpreterError::AttributeError(format!(
                    "'ChainMap' object has no attribute '{method}'"
                ))
                .into())
            }
        }
    }
}

fn set_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::Set(body) = obj else {
        return Err(type_mismatch("set"));
    };
    // Pass the shared handle, NOT a held guard: set methods lock narrowly so
    // `s.update(s)` / `s.union(s)` (an arg that is the receiver) don't re-lock
    // the one mutex while it is already held (deadlock).
    methods::set::dispatch_set_method(body, method, args, kwargs)
}

fn frozenset_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::Frozenset(body) = obj else {
        return Err(type_mismatch("frozenset"));
    };
    methods::set::dispatch_frozenset_method(body, 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> {
    // `to_bytes` needs the full value (large ints included), so handle it here
    // before the i64 narrowing below would reject a BigInt receiver.
    if method == "to_bytes" {
        let value = match obj {
            Value::Int(i) => num_bigint::BigInt::from(*i),
            Value::BigInt(b) => (**b).clone(),
            Value::Bool(b) => num_bigint::BigInt::from(i64::from(*b)),
            _ => return Err(type_mismatch("int")),
        };
        return super::helpers::int_to_bytes(&value, args, kwargs).map(MethodOutcome::pure);
    }
    match obj {
        Value::Int(i) => {
            methods::int::dispatch_int_method(*i, method, args, kwargs).map(MethodOutcome::pure)
        }
        // `bool` dispatches through the int method table as its `int` value.
        Value::Bool(b) => methods::int::dispatch_int_method(i64::from(*b), 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)
            }
            // Beyond i64: stay in arbitrary precision so
            // `bit_length`/`__index__`/`__abs__`/... don't raise a
            // spurious OverflowError from narrowing.
            Err(_) => methods::int::dispatch_bigint_method(i, method, args, kwargs)
                .map(MethodOutcome::pure),
        },
        _ => Err(type_mismatch("int")),
    }
}

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

/// `complex` methods: `conjugate()` (and `real`/`imag` for parity with `int`,
/// though those are normally read as attributes). All are argument-less.
fn complex_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::Complex(c) = obj else { return Err(type_mismatch("complex")) };
    reject_kwargs(method, kwargs)?;
    // Binary dunders delegate to the same arithmetic `+ - * / **` use, so
    // `(1+2j).__add__(3)` matches `(1+2j) + 3`.
    let binop = match method {
        "__add__" => Some(crate::types::BinOp::Add),
        "__sub__" => Some(crate::types::BinOp::Sub),
        "__mul__" => Some(crate::types::BinOp::Mul),
        "__truediv__" => Some(crate::types::BinOp::Div),
        "__pow__" => Some(crate::types::BinOp::Pow),
        _ => None,
    };
    if let Some(op) = binop {
        let rhs = args.first().ok_or_else(|| {
            EvalError::from(InterpreterError::TypeError(format!(
                "{method}() takes exactly one argument (0 given)"
            )))
        })?;
        return crate::eval::operations::apply_binop_builtin(op, obj, rhs).map(MethodOutcome::pure);
    }
    if !args.is_empty() {
        return Err(InterpreterError::TypeError(format!("{method}() takes no arguments")).into());
    }
    match method {
        "conjugate" => Ok(MethodOutcome::pure(Value::Complex(Box::new(c.conj())))),
        "real" => Ok(MethodOutcome::pure(Value::Float(c.re))),
        "imag" => Ok(MethodOutcome::pure(Value::Float(c.im))),
        // `abs(z)` is the magnitude (a float); the unary dunders mirror the
        // operators so the explicit `z.__abs__()` / `z.__neg__()` forms work.
        "__abs__" => Ok(MethodOutcome::pure(Value::Float(c.norm()))),
        "__neg__" => Ok(MethodOutcome::pure(Value::Complex(Box::new(-**c)))),
        "__pos__" | "__complex__" => Ok(MethodOutcome::pure(Value::Complex(c.clone()))),
        "__bool__" => Ok(MethodOutcome::pure(Value::Bool(c.re != 0.0 || c.im != 0.0))),
        _ => Err(InterpreterError::AttributeError(format!(
            "'complex' object has no attribute '{method}'"
        ))
        .into()),
    }
}

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 bytearray_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::ByteArray(b) = obj else {
        return Err(type_mismatch("bytearray"));
    };
    methods::bytes::dispatch_bytearray_method(b, method, args, kwargs)
}

fn stringio_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::StringIO(io) = obj else {
        return Err(type_mismatch("StringIO"));
    };
    let stream = io.clone();
    methods::stringio::dispatch_stringio_method(&stream, method, args, kwargs)
}

fn memoryview_methods(
    obj: &mut Value,
    method: &str,
    _args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::MemoryView(_) = obj else {
        return Err(type_mismatch("memoryview"));
    };
    crate::eval::functions::reject_kwargs(method, kwargs)?;
    let raw = crate::types::memoryview_bytes(obj);
    methods::bytes::dispatch_memoryview_method(&raw, method).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)
}

/// A slice bound as an int (`None` -> absent). `TypeError` for a non-int,
/// non-None component, matching `slice.indices`.
fn slice_component(v: &Value) -> Result<Option<i64>, EvalError> {
    match v {
        Value::None => Ok(None),
        Value::Int(n) => Ok(Some(*n)),
        Value::Bool(b) => Ok(Some(i64::from(*b))),
        Value::BigInt(b) => {
            use num_traits::{Signed as _, ToPrimitive as _};
            // A magnitude beyond i64 saturates by sign; `indices` then clamps it
            // to the sequence bounds, so the exact value is immaterial.
            Ok(Some(b.to_i64().unwrap_or(if b.is_negative() { i64::MIN } else { i64::MAX })))
        }
        _ => Err(InterpreterError::TypeError(
            "slice indices must be integers or None or have an __index__ method".into(),
        )
        .into()),
    }
}

fn slice_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::Slice(slice) = obj else {
        return Err(type_mismatch("slice"));
    };
    crate::eval::functions::reject_kwargs(method, kwargs)?;
    match method {
        // `slice.indices(length)` -> the `(start, stop, step)` a sequence of
        // `length` would use, per CPython's `PySlice_GetIndicesEx`.
        "indices" => {
            let length = arg1(method, args)?.as_int().ok_or_else(|| {
                EvalError::from(InterpreterError::TypeError(
                    "slice indices must be integers".into(),
                ))
            })?;
            if length < 0 {
                return Err(
                    InterpreterError::ValueError("length should not be negative".into()).into()
                );
            }
            let step = slice_component(&slice.step)?.unwrap_or(1);
            if step == 0 {
                return Err(InterpreterError::ValueError("slice step cannot be zero".into()).into());
            }
            let negative = step < 0;
            let (lower, upper) = if negative { (-1, length - 1) } else { (0, length) };
            let clamp = |raw: Option<i64>, default: i64| -> i64 {
                match raw {
                    None => default,
                    Some(mut v) => {
                        if v < 0 {
                            v += length;
                            v.max(lower)
                        } else {
                            v.min(upper)
                        }
                    }
                }
            };
            let start = clamp(slice_component(&slice.start)?, if negative { upper } else { lower });
            let stop = clamp(slice_component(&slice.stop)?, if negative { lower } else { upper });
            Ok(MethodOutcome::pure(Value::Tuple(vec![
                Value::Int(start),
                Value::Int(stop),
                Value::Int(step),
            ])))
        }
        _ => Err(InterpreterError::AttributeError(format!(
            "'slice' object has no attribute '{method}'"
        ))
        .into()),
    }
}

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 re_pattern_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::RePattern(p) = obj else {
        return Err(type_mismatch("re.Pattern"));
    };
    crate::eval::modules::re::dispatch_pattern_method(p, method, args, kwargs)
        .map(MethodOutcome::pure)
}

fn fraction_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::Fraction(f) = obj else {
        return Err(type_mismatch("Fraction"));
    };
    crate::eval::functions::reject_kwargs(method, kwargs)?;
    match method {
        "limit_denominator" => {
            let max_denom = match args.first() {
                None => num_bigint::BigInt::from(1_000_000),
                Some(v) => crate::value::value_as_bigint(v).ok_or_else(|| {
                    EvalError::from(InterpreterError::TypeError(
                        "limit_denominator() argument must be an integer".into(),
                    ))
                })?,
            };
            Ok(MethodOutcome::pure(Value::Fraction(Box::new(limit_denominator(f, &max_denom)))))
        }
        "as_integer_ratio" => Ok(MethodOutcome::pure(Value::Tuple(vec![
            crate::value::int_from_bigint(f.numer().clone()),
            crate::value::int_from_bigint(f.denom().clone()),
        ]))),
        "__floor__" | "__ceil__" | "__trunc__" => {
            let r = match method {
                "__floor__" => f.floor(),
                "__ceil__" => f.ceil(),
                _ => f.trunc(),
            };
            Ok(MethodOutcome::pure(crate::value::int_from_bigint(r.to_integer())))
        }
        _ => Err(InterpreterError::AttributeError(format!(
            "'Fraction' object has no attribute '{method}'"
        ))
        .into()),
    }
}

/// CPython's `Fraction.limit_denominator` — the closest fraction with a
/// denominator not exceeding `max_denominator`, via the continued-fraction
/// convergents.
fn limit_denominator(
    f: &num_rational::BigRational,
    max_denominator: &num_bigint::BigInt,
) -> num_rational::BigRational {
    use num_bigint::BigInt;
    use num_rational::BigRational;
    use num_traits::{One as _, Signed as _, Zero as _};
    if max_denominator < &BigInt::one() {
        return f.clone();
    }
    if f.denom() <= max_denominator {
        return f.clone();
    }
    let (mut p0, mut q0, mut p1, mut q1) =
        (BigInt::zero(), BigInt::one(), BigInt::one(), BigInt::zero());
    let (mut n, mut d) = (f.numer().clone(), f.denom().clone());
    loop {
        let a = &n / &d;
        let q2 = &q0 + &a * &q1;
        if &q2 > max_denominator {
            break;
        }
        let new_p1 = &p0 + &a * &p1;
        p0 = std::mem::replace(&mut p1, new_p1);
        q0 = std::mem::replace(&mut q1, q2);
        let new_d = &n - &a * &d;
        n = std::mem::replace(&mut d, new_d);
    }
    let k = (max_denominator - &q0) / &q1;
    let bound1 = BigRational::new(&p0 + &k * &p1, &q0 + &k * &q1);
    let bound2 = BigRational::new(p1, q1);
    if (&bound2 - f).abs() <= (&bound1 - f).abs() { bound2 } else { bound1 }
}

fn decimal_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    let Value::Decimal(d, kind) = obj else {
        return Err(type_mismatch("Decimal"));
    };
    // `quantize`/`to_integral*` take a `rounding=` keyword; every other Decimal
    // method rejects kwargs as CPython does.
    if !matches!(method, "quantize" | "to_integral_value" | "to_integral" | "to_integral_exact") {
        crate::eval::functions::reject_kwargs(method, kwargs)?;
    }
    crate::eval::modules::decimal::dispatch_decimal_method(d, *kind, 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 { bytes, .. } = obj else {
        return Err(type_mismatch("HASH"));
    };
    // `update(data)` appends to the accumulated buffer (the digest is computed
    // lazily), so the incremental create-then-update pattern works.
    if method == "update" {
        crate::eval::functions::reject_kwargs(method, kwargs)?;
        let data = match args.first() {
            Some(Value::Bytes(b)) => b.clone(),
            Some(Value::ByteArray(b)) => b.lock().clone(),
            _ => {
                return Err(InterpreterError::TypeError(
                    "update() argument must be a bytes-like object".into(),
                )
                .into());
            }
        };
        let grew = data.len();
        bytes.extend_from_slice(&data);
        return Ok(MethodOutcome::grew(Value::None, grew));
    }
    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 single_dispatch_methods(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    _kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    // `dispatcher.register(...)` reached as a method call (`@f.register(int)`).
    // Mirrors the internal `functools::_sd_register`: an explicit type yields a
    // decorator bound to (dispatcher, type); an annotated implementation is
    // registered immediately from its first-parameter annotation.
    let dispatcher = obj.clone();
    let Value::SingleDispatch(sd) = obj else {
        return Err(type_mismatch("singledispatch"));
    };
    match method {
        "register" => {
            let subject = args.first().cloned().ok_or_else(|| {
                EvalError::from(InterpreterError::TypeError(
                    "register() missing required argument".into(),
                ))
            })?;
            if let Some(type_name) = crate::eval::modules::functools::dispatch_type_name(&subject) {
                return Ok(MethodOutcome::pure(Value::Partial(Box::new(
                    crate::value::PartialData {
                        func: Value::ModuleFunction {
                            module: "functools".into(),
                            name: "_sd_register_typed".into(),
                        },
                        args: vec![dispatcher, Value::String(type_name.into())],
                        keywords: IndexMap::new(),
                    },
                ))));
            }
            let type_name = crate::eval::modules::functools::first_param_annotation(&subject)
                .ok_or_else(|| {
                    EvalError::from(InterpreterError::TypeError(
                        "Invalid first argument to `register()`: it must be a type or a callable \
                         with a type-annotated first argument"
                            .into(),
                    ))
                })?;
            sd.registry.lock().insert(type_name, subject.clone());
            Ok(MethodOutcome::pure(subject))
        }
        _ => Err(InterpreterError::AttributeError(format!(
            "'function' object has no attribute '{method}'"
        ))
        .into()),
    }
}

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::Array { .. } => Some(array_methods),
        Value::LruCache(_) => Some(lru_methods),
        Value::SingleDispatch(_) => Some(single_dispatch_methods),
        Value::Dict(_) | Value::OrderedDict(_) => Some(dict_methods),
        Value::StringIO(_) => Some(stringio_methods),
        Value::Counter(_) => Some(counter_methods),
        Value::Deque { .. } => Some(deque_methods),
        Value::DefaultDict(_) => Some(defaultdict_methods),
        Value::ChainMap(_) => Some(chainmap_methods),
        Value::Template(_) => Some(template_methods),
        Value::Set(_) => Some(set_methods),
        Value::Frozenset(_) => Some(frozenset_methods),
        Value::Tuple(_) => Some(tuple_methods),
        Value::Slice(_) => Some(slice_methods),
        Value::Range { .. } => Some(range_methods),
        // `bool` is an `int` subclass, so it carries every int method
        // (`True.bit_length()`, `False.to_bytes(...)`, ...).
        Value::Int(_) | Value::BigInt(_) | Value::Bool(_) => Some(int_methods),
        Value::Float(_) => Some(float_methods),
        Value::Complex(_) => Some(complex_methods),
        Value::Bytes(_) => Some(bytes_methods),
        Value::ByteArray(_) => Some(bytearray_methods),
        Value::MemoryView(_) => Some(memoryview_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::RePattern(_) => Some(re_pattern_methods),
        Value::Decimal(..) => Some(decimal_methods),
        Value::Fraction(_) => Some(fraction_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`]).
/// Map a reflective builtin dunder call (`[1, 2].__len__()`, `"ab".__getitem__(0)`)
/// to the sync operator it wraps. Returns `Ok(Some(_))` when handled,
/// `Ok(None)` to fall through to the type's method table (and its
/// AttributeError for a genuinely absent dunder). Only the sync-computable
/// dunders are covered; ones needing `&mut state` (`__iter__`, `__add__`, …)
/// are left to the normal call path.
fn try_builtin_dunder(
    obj: &Value,
    method: &str,
    args: &[Value],
) -> Result<Option<MethodOutcome>, EvalError> {
    let pure = |v: Value| Ok(Some(MethodOutcome::pure(v)));
    match method {
        // Only expose `__len__` on sized types (int has none), so a failure
        // falls through to AttributeError rather than surfacing a len error.
        "__len__" => match crate::types::dispatch_len(obj) {
            Ok(n) => pure(Value::Int(crate::eval::functions::to_len_i64(n)?)),
            Err(_) => Ok(None),
        },
        "__contains__" => match crate::types::dispatch_contains(obj, arg1(method, args)?) {
            Ok(b) => pure(Value::Bool(b)),
            Err(_) => Ok(None),
        },
        "__getitem__" => match crate::types::dispatch_getitem(obj, arg1(method, args)?) {
            Ok(v) => pure(v),
            Err(e) => Err(e),
        },
        "__str__" => pure(Value::String(format!("{obj}").into())),
        "__repr__" => pure(Value::String(obj.repr().into())),
        // `x.__format__(spec)` on a builtin: an empty spec is `str(x)`, a
        // non-empty spec runs the format-spec mini-language — the same paths the
        // `format()` builtin takes for a builtin receiver.
        "__format__" => {
            let spec = match args.first() {
                Some(Value::String(s)) => s.as_str(),
                None => "",
                Some(other) => {
                    return Err(InterpreterError::TypeError(format!(
                        "__format__() argument 1 must be str, not {}",
                        other.type_name()
                    ))
                    .into());
                }
            };
            if spec.is_empty() {
                pure(Value::String(format!("{obj}").into()))
            } else {
                crate::eval::strings::apply_format_spec(obj, spec)
                    .map(|v| Some(MethodOutcome::pure(v)))
            }
        }
        "__bool__" => pure(Value::Bool(obj.is_truthy())),
        // `__floor__`/`__ceil__`/`__trunc__` return the integral part per the
        // numeric type (exact for Fraction/Decimal/int, truncating floor/ceil
        // for float). Non-numeric types fall through to AttributeError.
        "__floor__" | "__ceil__" | "__trunc__" => match numeric_integral(obj, method) {
            Some(v) => pure(v),
            None => Ok(None),
        },
        // `x.__int__()` truncates toward zero to an int (numeric receivers only);
        // `__index__` is the lossless int for the integer types only.
        "__int__" => match numeric_integral(obj, "__trunc__") {
            Some(v) => pure(v),
            None => Ok(None),
        },
        "__index__" => match obj {
            Value::Int(_) | Value::BigInt(_) => pure(obj.clone()),
            Value::Bool(b) => pure(Value::Int(i64::from(*b))),
            _ => Ok(None),
        },
        // `x.__float__()` — numeric receivers only.
        "__float__" => match obj {
            Value::Int(_)
            | Value::BigInt(_)
            | Value::Float(_)
            | Value::Bool(_)
            | Value::Decimal(..)
            | Value::Fraction(_) => match obj.as_float() {
                Some(f) => pure(Value::Float(f)),
                None => Ok(None),
            },
            _ => Ok(None),
        },
        // `x.__round__()` returns an int (round-half-to-even); `x.__round__(n)`
        // returns the same numeric type rounded to that scale. Mirrors the
        // `round()` builtin so both surfaces agree.
        "__round__" => {
            use crate::eval::functions::{
                round_bigint, round_decimal, round_float, round_fraction, round_int, value_to_i64,
            };
            let ndigits = match args.first() {
                Some(v) => Some(value_to_i64(v)?),
                None => None,
            };
            match obj {
                Value::Int(i) => pure(round_int(*i, ndigits)),
                Value::BigInt(b) => pure(crate::value::int_from_bigint(round_bigint(b, ndigits))),
                Value::Bool(b) => pure(round_int(i64::from(*b), ndigits)),
                Value::Float(f) => pure(round_float(*f, ndigits)?),
                Value::Decimal(d, _) => pure(round_decimal(d, ndigits)),
                Value::Fraction(fr) => pure(round_fraction(fr, ndigits)),
                _ => Ok(None),
            }
        }
        // `x.__hash__()` on a hashable builtin — the CPython-exact value
        // (matching the `hash()` builtin). Unhashable/unsupported receivers
        // fall through to AttributeError.
        "__hash__" if !matches!(obj, Value::Instance(_) | Value::Class(_)) => {
            match crate::pyhash::python_hash(obj) {
                Some(h) => pure(Value::Int(h)),
                None => Ok(None),
            }
        }
        // Rich-comparison dunders on builtins (`(1.5).__eq__(1.5)`,
        // `(10).__lt__(20)`). `__eq__`/`__ne__` use the shared value equality
        // (which honours the numeric tower); the ordering dunders return
        // NotImplemented for incomparable operand types, as CPython does.
        // Instances keep their own user-defined comparison dunders.
        "__eq__" | "__ne__" | "__lt__" | "__le__" | "__gt__" | "__ge__"
            if !matches!(obj, Value::Instance(_) | Value::Class(_)) =>
        {
            let Some(other) = args.first() else {
                return Ok(None);
            };
            use crate::eval::operations::{compare_lt, values_equal_pub};
            // `__eq__`/`__ne__` return `NotImplemented` (not a bool) when the
            // operand types are unrelated — CPython's asymmetric per-type rule,
            // e.g. `(5).__eq__("x")` and even `(5).__eq__(5.0)` (int doesn't know
            // float; the reflected `float.__eq__(int)` is what makes `5 == 5.0`).
            let eq_bool = |equal: bool| if eq_yields_bool(obj, other) { Some(equal) } else { None };
            let outcome: Option<bool> = match method {
                "__eq__" => eq_bool(values_equal_pub(obj, other)),
                "__ne__" => eq_bool(!values_equal_pub(obj, other)),
                "__lt__" => compare_lt(obj, other).ok(),
                "__le__" => {
                    compare_lt(obj, other).ok().map(|lt| lt || values_equal_pub(obj, other))
                }
                "__gt__" => compare_lt(other, obj).ok(),
                "__ge__" => {
                    compare_lt(other, obj).ok().map(|gt| gt || values_equal_pub(obj, other))
                }
                _ => None,
            };
            match outcome {
                Some(b) => pure(Value::Bool(b)),
                None => pure(Value::NotImplemented),
            }
        }
        // Binary arithmetic / bitwise dunders on builtins (`(10).__add__(5)`,
        // `(100).__divmod__(7)`). Routed through the shared sync binop with
        // default context (prec 28, 1 Mibit) — the only divergence is a Decimal
        // op made through an explicit dunder while a non-default getcontext()
        // precision is active, which is vanishingly rare. Instances keep their
        // own user-defined dunders (handled before this shim is reached).
        _ if !matches!(obj, Value::Instance(_) | Value::Class(_)) => {
            let Some((op, reflected)) = arith_dunder_op(method) else {
                return Ok(None);
            };
            let Some(other) = args.first() else {
                return Ok(None);
            };
            let (lhs, rhs) = if reflected { (other, obj) } else { (obj, other) };
            if method == "__divmod__" || method == "__rdivmod__" {
                let q = crate::eval::operations::apply_binop(
                    lhs,
                    rhs,
                    rustpython_parser::ast::Operator::FloorDiv,
                    28,
                    1_048_576,
                )?;
                let r = crate::eval::operations::apply_binop(
                    lhs,
                    rhs,
                    rustpython_parser::ast::Operator::Mod,
                    28,
                    1_048_576,
                )?;
                return pure(Value::Tuple(vec![q, r]));
            }
            match crate::eval::operations::apply_binop(lhs, rhs, op, 28, 1_048_576) {
                Ok(v) => pure(v),
                // On a type mismatch CPython's behaviour splits by receiver: a
                // NUMERIC dunder returns NotImplemented (`(5).__add__("x")`),
                // while a SEQUENCE concat/repeat dunder raises the TypeError
                // (`[1].__add__(5)` → "can only concatenate list ..."). A real
                // failure of an applicable op (ZeroDivisionError, OverflowError,
                // ValueError) always propagates, e.g. `(10).__floordiv__(0)`.
                Err(EvalError::Interpreter(InterpreterError::TypeError(_)))
                    if is_numeric_value(obj) =>
                {
                    pure(Value::NotImplemented)
                }
                Err(e) => Err(e),
            }
        }
        _ => Ok(None),
    }
}

/// Whether `lhs.__eq__(rhs)` / `lhs.__ne__(rhs)` yields a bool rather than
/// `NotImplemented`, for a builtin `lhs`. CPython's rule is asymmetric and
/// per-type: a numeric type accepts only the numeric types it promotes FROM
/// (`int`/`bool` accept int/bool only; `float` also int/bool; `complex` also
/// float; `Decimal`/`Fraction` their own tower), and each non-numeric family
/// accepts only its own members (bytes↔bytearray, set↔frozenset, the dict
/// subclasses, date↔datetime). Unrelated types yield `NotImplemented`. Types not
/// covered here keep the prior always-bool behaviour (no regression).
fn eq_yields_bool(lhs: &Value, rhs: &Value) -> bool {
    use crate::value::EnumKind;
    let int_like = |v: &Value| {
        matches!(
            v,
            Value::Int(_)
                | Value::BigInt(_)
                | Value::Bool(_)
                | Value::EnumMember { kind: EnumKind::Int | EnumKind::IntFlag, .. }
        )
    };
    let same_enum = |rhs: &Value, class: &str| matches!(rhs, Value::EnumMember { class_name, .. } if class_name == class);
    match lhs {
        Value::Int(_) | Value::BigInt(_) | Value::Bool(_) => int_like(rhs),
        Value::Float(_) => int_like(rhs) || matches!(rhs, Value::Float(_)),
        Value::Complex(_) => int_like(rhs) || matches!(rhs, Value::Float(_) | Value::Complex(_)),
        Value::Decimal(..) => {
            int_like(rhs)
                || matches!(rhs, Value::Float(_) | Value::Decimal(..) | Value::Fraction(_))
        }
        Value::Fraction(_) => int_like(rhs) || matches!(rhs, Value::Float(_) | Value::Fraction(_)),
        Value::String(_) => matches!(rhs, Value::String(_)),
        Value::Bytes(_) => matches!(rhs, Value::Bytes(_)),
        Value::ByteArray(_) => matches!(rhs, Value::Bytes(_) | Value::ByteArray(_)),
        Value::List(_) => matches!(rhs, Value::List(_)),
        Value::Tuple(_) => matches!(rhs, Value::Tuple(_)),
        Value::Dict(_) | Value::OrderedDict(_) | Value::Counter(_) => {
            matches!(rhs, Value::Dict(_) | Value::OrderedDict(_) | Value::Counter(_))
        }
        Value::Set(_) | Value::Frozenset(_) => matches!(rhs, Value::Set(_) | Value::Frozenset(_)),
        Value::None => matches!(rhs, Value::None),
        Value::Range { .. } => matches!(rhs, Value::Range { .. }),
        Value::Date(_) | Value::DateTime { .. } => {
            matches!(rhs, Value::Date(_) | Value::DateTime { .. })
        }
        Value::Time(_) => matches!(rhs, Value::Time(_)),
        Value::TimeDelta(_) => matches!(rhs, Value::TimeDelta(_)),
        Value::TimeZone(_) => matches!(rhs, Value::TimeZone(_)),
        Value::EnumMember { kind, class_name, .. } => match kind {
            EnumKind::Int | EnumKind::IntFlag => int_like(rhs) || same_enum(rhs, class_name),
            EnumKind::Str => matches!(rhs, Value::String(_)) || same_enum(rhs, class_name),
            EnumKind::Plain | EnumKind::Flag => same_enum(rhs, class_name),
        },
        // Unknown/other builtins keep the pre-existing always-bool behaviour.
        _ => true,
    }
}

/// A numeric receiver — its arithmetic dunders return `NotImplemented` on a
/// type mismatch (sequence concat/repeat dunders raise instead).
fn is_numeric_value(v: &Value) -> bool {
    use crate::value::EnumKind;
    matches!(
        v,
        Value::Int(_)
            | Value::BigInt(_)
            | Value::Bool(_)
            | Value::Float(_)
            | Value::Complex(_)
            | Value::Decimal(..)
            | Value::Fraction(_)
            | Value::EnumMember { kind: EnumKind::Int | EnumKind::IntFlag, .. }
    )
}

/// Map a binary arithmetic/bitwise dunder name to its operator and whether it
/// is the reflected form (operands swapped). `__divmod__`/`__rdivmod__` return a
/// placeholder operator (`Add`) — the caller special-cases them.
fn arith_dunder_op(method: &str) -> Option<(rustpython_parser::ast::Operator, bool)> {
    use rustpython_parser::ast::Operator::{
        Add, BitAnd, BitOr, BitXor, Div, FloorDiv, LShift, MatMult, Mod, Mult, Pow, RShift, Sub,
    };
    let (op, reflected) = match method {
        "__add__" => (Add, false),
        "__radd__" => (Add, true),
        "__sub__" => (Sub, false),
        "__rsub__" => (Sub, true),
        "__mul__" => (Mult, false),
        "__rmul__" => (Mult, true),
        "__truediv__" => (Div, false),
        "__rtruediv__" => (Div, true),
        "__floordiv__" => (FloorDiv, false),
        "__rfloordiv__" => (FloorDiv, true),
        "__mod__" => (Mod, false),
        "__rmod__" => (Mod, true),
        "__pow__" => (Pow, false),
        "__rpow__" => (Pow, true),
        "__matmul__" => (MatMult, false),
        "__rmatmul__" => (MatMult, true),
        "__and__" => (BitAnd, false),
        "__rand__" => (BitAnd, true),
        "__or__" => (BitOr, false),
        "__ror__" => (BitOr, true),
        "__xor__" => (BitXor, false),
        "__rxor__" => (BitXor, true),
        "__lshift__" => (LShift, false),
        "__rlshift__" => (LShift, true),
        "__rshift__" => (RShift, false),
        "__rrshift__" => (RShift, true),
        // divmod uses a placeholder op; the caller builds the (q, r) tuple.
        "__divmod__" => (Add, false),
        "__rdivmod__" => (Add, true),
        _ => return None,
    };
    Some((op, reflected))
}

/// Integral part of a numeric value for `__floor__`/`__ceil__`/`__trunc__`.
/// Returns `None` for a non-numeric receiver.
fn numeric_integral(obj: &Value, method: &str) -> Option<Value> {
    use num_traits::ToPrimitive as _;
    match obj {
        Value::Int(_) | Value::BigInt(_) => Some(obj.clone()),
        Value::Bool(b) => Some(Value::Int(i64::from(*b))),
        Value::Float(f) => {
            let r = match method {
                "__floor__" => f.floor(),
                "__ceil__" => f.ceil(),
                _ => f.trunc(),
            };
            r.to_i64().map(Value::Int)
        }
        Value::Fraction(fr) => {
            let r = match method {
                "__floor__" => fr.floor(),
                "__ceil__" => fr.ceil(),
                _ => fr.trunc(),
            };
            Some(crate::value::int_from_bigint(r.to_integer()))
        }
        Value::Decimal(d, _) => {
            use bigdecimal::BigDecimal;
            let rounding = match method {
                "__floor__" => bigdecimal::RoundingMode::Floor,
                "__ceil__" => bigdecimal::RoundingMode::Ceiling,
                _ => bigdecimal::RoundingMode::Down,
            };
            let int_dec: BigDecimal = d.with_scale_round(0, rounding);
            let (bigint, _) = int_dec.as_bigint_and_exponent();
            Some(crate::value::int_from_bigint(bigint))
        }
        _ => None,
    }
}

pub(super) fn dispatch_method(
    obj: &mut Value,
    method: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
) -> Result<MethodOutcome, EvalError> {
    // Reflective dunder calls on builtins map to their sync operator.
    if method.starts_with("__") {
        if let Some(outcome) = try_builtin_dunder(obj, method, args)? {
            return Ok(outcome);
        }
    }
    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")))
    })
}