interpretthis 0.3.0

Sandboxed Python AST interpreter for untrusted and LLM-generated code
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
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
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
// Copyright 2026 Thomas Santerre and Moderately AI Inc.
//
// SPDX-License-Identifier: MIT OR Apache-2.0

//! User-defined classes: `class` definition, instantiation, and method calls.
//!
//! A class definition registers a [`ClassValue`] (its methods and class
//! attributes) in `InterpreterState::classes` and binds a lightweight
//! [`Value::Class`] handle as the class-named variable. Instances carry only
//! their class name plus their own fields; methods are looked up in the registry
//! at call time, so an instance never copies its class's methods.
//!
//! Because the value model is owned (no reference aliasing), a method that
//! mutates `self` mutates a *copy*. [`call_method`] therefore reads `self` back
//! out of the method's scope after the body runs and returns it, and the caller
//! writes it back into the receiver's slot — the same place-based write-back the
//! built-in mutating methods use.
//!
//! Inheritance: multi-level inheritance and the `super()` family are
//! supported via a C3-linearized MRO computed at class-definition time.
//! Method and attribute lookups walk `ClassValue::mro` in order. The
//! implicit `object` tail is omitted from the MRO (no registered class) —
//! lookups fall through to a not-found / AttributeError once the explicit
//! chain is exhausted, matching CPython's behaviour without modelling
//! `object`'s instance methods.
//!
//! Scope limits (rejected with a clear error rather than silently mis-handled):
//! metaclass / keyword arguments (out-of-scope) and inheritance cycles
//! or C3 conflicts (raise `TypeError("Cannot create a consistent method
//! resolution order")` matching CPython). Class-level decorators
//! (`@property`-style + `@dataclass` + user callables) are supported;
//! method-level decorators route through `classify_decorated_method`.

use std::{collections::BTreeMap, sync::Arc};

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

use crate::{
    error::{EvalError, EvalResult, InterpreterError},
    eval::{
        eval_expr,
        functions::{
            CallArgs, bind_params, build_function_params, call_lambda, call_user_function,
            execute_body, extract_function_source,
        },
    },
    state::InterpreterState,
    tools::Tools,
    value::{ClassValue, FunctionDef, InstanceValue, PropertyDef, Value, shared_list},
};

/// Evaluate a `class` definition: build the [`ClassValue`], register it, and
/// bind the class-named variable to a [`Value::Class`] handle.
pub async fn eval_class_def(
    state: &mut InterpreterState,
    node: &ast::StmtClassDef,
    tools: &Tools,
) -> EvalResult {
    let class_name = node.name.as_str();
    crate::security::validator::validate_name(
        crate::security::validator::NameContext::Assignment,
        class_name,
    )?;

    // Optional `metaclass=` (other class keywords still rejected).
    let mut metaclass_name: Option<String> = None;
    for kw in &node.keywords {
        let key = kw.arg.as_ref().map(|a| a.as_str());
        if key != Some("metaclass") {
            return Err(InterpreterError::TypeError(format!(
                "class keyword argument '{}' is not supported",
                key.unwrap_or("<unknown>")
            ))
            .into());
        }
        let val = eval_expr(state, &kw.value, tools).await?;
        match val {
            Value::BuiltinName(n) | Value::Type(n) if n == "type" => {}
            Value::Class(n) => metaclass_name = Some(n),
            other => {
                return Err(InterpreterError::TypeError(format!(
                    "metaclass must be a type, not '{}'",
                    other.type_name()
                ))
                .into());
            }
        }
    }

    // Collect declared bases (excluding the implicit `object`, which we
    // don't materialize as a registered class). typing.* and enum.*
    // aliases (`Enum`, `IntEnum`, `NamedTuple`, etc.) resolve to
    // Value::Type / Value::ModuleFunction sentinels and are
    // recognised here for enum-kind detection.
    let mut bases: Vec<String> = Vec::new();
    let mut enum_kind: Option<crate::value::EnumKind> = None;
    for base in &node.bases {
        // Resolve bare names from the environment, or evaluate computed
        // base expressions (`collections.UserList`, `mod.Base`, …).
        let (base_name, resolved): (String, Option<Value>) = match base {
            Expr::Name(name_node) => {
                let base_name = name_node.id.as_str().to_string();
                let resolved = state.variables.get(&base_name).cloned();
                (base_name, resolved)
            }
            other => {
                let val = eval_expr(state, other, tools).await?;
                match &val {
                    Value::Class(n) | Value::ExceptionType(n) => (n.clone(), Some(val)),
                    Value::Type(n) => (n.clone(), Some(val)),
                    other_v => {
                        return Err(InterpreterError::TypeError(format!(
                            "bases must be types, not '{}'",
                            other_v.type_name()
                        ))
                        .into());
                    }
                }
            }
        };
        if base_name == "object" {
            continue;
        }
        // Check resolved value for the enum sentinels (`enum.Enum`,
        // `enum.IntEnum`, `enum.StrEnum`, etc.) so aliased imports
        // (`from enum import Enum as MyBase`) work too.
        if let Some(Value::Type(type_name)) = &resolved {
            match type_name.as_str() {
                "enum.Enum" | "enum.Flag" => enum_kind = Some(crate::value::EnumKind::Plain),
                "enum.IntEnum" | "enum.IntFlag" => {
                    enum_kind = Some(crate::value::EnumKind::Int);
                }
                "enum.StrEnum" => enum_kind = Some(crate::value::EnumKind::Str),
                _ => {}
            }
            continue;
        }
        if matches!(resolved, Some(Value::ModuleFunction { .. })) {
            continue;
        }
        // Builtin exception types (`Exception`, `ValueError`, …) are
        // not registered in `state.classes` — they resolve as
        // ExceptionType sentinels on bare-name lookup. Allow them as
        // bases so `class AppError(Exception)` works; MRO stores the
        // name string and except-matching walks it via the hard-coded
        // hierarchy + user MRO.
        let is_exception_base = crate::eval::functions::is_exception_type_name(&base_name)
            || matches!(resolved, Some(Value::ExceptionType(_)));
        if !state.classes.contains_key(&base_name) && !is_exception_base {
            return Err(InterpreterError::name_not_defined(&base_name).into());
        }
        bases.push(base_name);
    }

    let mut methods: BTreeMap<String, FunctionDef> = BTreeMap::new();
    let mut class_attrs: BTreeMap<String, Value> = BTreeMap::new();
    let mut properties: BTreeMap<String, PropertyDef> = BTreeMap::new();
    let mut static_methods: BTreeMap<String, FunctionDef> = BTreeMap::new();
    let mut class_methods: BTreeMap<String, FunctionDef> = BTreeMap::new();
    // Annotated attribute names in declaration order. `@dataclass` consumes
    // this to compute its field list — class_attrs (BTreeMap) would
    // re-order them alphabetically and break the synthesized `__init__`
    // parameter order.
    let mut annotations: Vec<String> = Vec::new();

    // PEP 3115: Meta.__prepare__(name, bases) may supply the initial namespace.
    if let Some(ref meta) = metaclass_name {
        if let Some(prepared) =
            invoke_metaclass_prepare(state, meta, class_name, &bases, tools).await?
        {
            for (k, v) in prepared {
                if let crate::value::ValueKey::String(s) = k {
                    class_attrs.insert(s.to_string(), v);
                }
            }
        }
    }

    for stmt in &node.body {
        match stmt {
            Stmt::FunctionDef(method) => {
                let mut params = build_function_params(&method.args);
                // Evaluate the method's default args at def time in
                // the class body scope — same CPython semantics as
                // top-level `def` (the `i=i` capture idiom + mutable
                // default sharing).
                crate::eval::functions::evaluate_param_defaults(state, &mut params, tools).await?;
                let source = extract_function_source(&state.current_source, method);
                let method_name = method.name.as_str().to_string();
                // The body cache key gets a per-decorator suffix so
                // `@property def x` / `@x.setter def x` / `@x.deleter
                // def x` don't collide. Regular methods use the plain
                // `Class.name` key.
                classify_decorated_method(
                    state,
                    &method.decorator_list,
                    class_name,
                    method_name,
                    params,
                    method.body.clone(),
                    source,
                    &mut methods,
                    &mut properties,
                    &mut static_methods,
                    &mut class_methods,
                )?;
            }
            Stmt::Assign(assign) => {
                if let [Expr::Name(target)] = assign.targets.as_slice() {
                    let value = eval_expr(state, &assign.value, tools).await?;
                    let attr_name = target.id.as_str().to_string();
                    let wrapped = wrap_enum_member(enum_kind, class_name, &attr_name, value);
                    class_attrs.insert(attr_name, wrapped);
                }
            }
            Stmt::AnnAssign(ann) => {
                if let Expr::Name(target) = ann.target.as_ref() {
                    let attr_name = target.id.as_str().to_string();
                    // Record every annotated name, with or without a value,
                    // in declaration order so `@dataclass` can read fields.
                    if !annotations.contains(&attr_name) {
                        annotations.push(attr_name.clone());
                    }
                    if let Some(value_expr) = &ann.value {
                        let value = eval_expr(state, value_expr, tools).await?;
                        let wrapped = wrap_enum_member(enum_kind, class_name, &attr_name, value);
                        class_attrs.insert(attr_name, wrapped);
                    }
                }
            }
            // Docstrings and `pass` carry no class state; other statements in a
            // class body (nested classes, etc.) are not modelled and ignored.
            _ => {}
        }
    }

    // C3 linearization gives the method resolution order for this
    // class. Each base's MRO is in the registry already (because B1's
    // single-pass eval registers bases before their derivatives).
    let mro = build_mro(class_name, &bases, &state.classes)?;
    let bases_for_hook = bases.clone();
    // Snapshot class attrs for PEP 487 `__set_name__` before move into registry.
    let attrs_for_set_name: Vec<(String, Value)> =
        class_attrs.iter().map(|(k, v)| (k.clone(), v.clone())).collect();

    // Class-body `__slots__ = ('x', 'y')` / `"x"` / `["x"]`.
    // Inherit parent slot names when any base uses slots (CPython merges).
    let (mut slots, mut slot_names) = parse_slots_attr(class_attrs.get("__slots__"));
    for base in &bases {
        if let Some(b) = state.classes.get(base) {
            if b.slots {
                slots = true;
                for n in &b.slot_names {
                    if !slot_names.iter().any(|s| s == n) {
                        slot_names.push(n.clone());
                    }
                }
            }
        }
    }

    state.classes.insert(class_name.to_string(), {
        let mut cv = ClassValue::new(class_name);
        cv.methods = methods;
        cv.class_attrs = class_attrs;
        cv.bases = bases;
        cv.mro = mro;
        cv.properties = properties;
        cv.static_methods = static_methods;
        cv.class_methods = class_methods;
        cv.enum_kind = enum_kind;
        cv.annotations = annotations;
        cv.slots = slots;
        cv.slot_names = slot_names;
        cv
    });
    state
        .set_variable(class_name, Value::Class(class_name.to_string()))
        .map_err(EvalError::Interpreter)?;

    // Metaclass `__new__` / `__init__` (PEP 3115 subset).
    if let Some(meta) = metaclass_name {
        // Preserve method tables across type() rebuilds that only carry attrs.
        let saved_methods = state.classes.get(class_name).map(|c| {
            (
                c.methods.clone(),
                c.properties.clone(),
                c.static_methods.clone(),
                c.class_methods.clone(),
            )
        });
        invoke_metaclass_new(state, class_name, &meta, tools).await?;
        if let Some((methods, properties, static_methods, class_methods)) = saved_methods {
            if let Some(cv) = state.classes.get_mut(class_name) {
                if cv.methods.is_empty() && !methods.is_empty() {
                    cv.methods = methods;
                    cv.properties = properties;
                    cv.static_methods = static_methods;
                    cv.class_methods = class_methods;
                }
            }
        }
        invoke_metaclass_init(state, class_name, &meta, tools).await?;
    }

    // PEP 487: after the class dict is built, call `__set_name__(cls, name)`
    // on each attribute that defines it (descriptors / named objects).
    invoke_set_name(state, class_name, &attrs_for_set_name, tools).await?;

    // PEP 487: invoke each base's `__init_subclass__` (classmethod-style)
    // with the newly created class. Walk direct bases only; each base
    // is responsible for chaining to its own parents if needed.
    invoke_init_subclass(state, class_name, &bases_for_hook, tools).await?;

    // Apply class-level decorators in REVERSE order (bottom-up,
    // matching CPython): the innermost decorator wraps the class
    // first. Class decorators take the class and return a value
    // — usually the same class transformed, but anything callable is
    // accepted. The result is rebound to the class name in scope.
    if !node.decorator_list.is_empty() {
        let mut result = Value::Class(class_name.to_string());
        for decorator in node.decorator_list.iter().rev() {
            let dec_val = eval_expr(state, decorator, tools).await?;
            result = apply_decorator(state, &dec_val, result, tools).await?;
        }
        state.set_variable(class_name, result).map_err(EvalError::Interpreter)?;
    }

    Ok(Value::None)
}

/// Dispatch a method's decorator list to the right ClassValue bucket
/// and insert its body into `state.function_bodies` under a key that
/// stays unique across the three property accessors. Regular methods
/// use the plain `Class.name` key; property accessors disambiguate
/// with a `__get` / `__set` / `__del` suffix so a `@balance.setter`
/// doesn't overwrite the getter's body.
#[expect(
    clippy::too_many_arguments,
    reason = "the buckets travel as four separate `&mut BTreeMap`s by design; bundling them into a struct would just reify the same fan-out at the call site"
)]
fn classify_decorated_method(
    state: &mut InterpreterState,
    decorators: &[Expr],
    class_name: &str,
    method_name: String,
    params: crate::value::FunctionParams,
    body: Vec<Stmt>,
    source: String,
    methods: &mut BTreeMap<String, FunctionDef>,
    properties: &mut BTreeMap<String, PropertyDef>,
    static_methods: &mut BTreeMap<String, FunctionDef>,
    class_methods: &mut BTreeMap<String, FunctionDef>,
) -> Result<(), EvalError> {
    let mut register = |key: String, body: Vec<Stmt>, source: String| -> FunctionDef {
        // Walk the method body for `assigned_names` / `global_names`
        // so `VariableCheckpoint` can snapshot only the names this
        // frame can touch instead of cloning all of `state.variables`
        // per call. `nonlocal` isn't supported inside class methods
        // today (it would route through a cell at the enclosing
        // function scope, not the class), so nonlocal_names stays
        // empty.
        let (mut assigned_names, global_names) =
            crate::eval::functions::collect_assigned_names(&body);
        assigned_names.retain(|n| !global_names.contains(n));
        let is_generator = crate::eval::functions::contains_yield_stmts(&body);
        state.function_bodies.insert(key.clone(), Arc::new(body));
        FunctionDef {
            name: key,
            params: params.clone(),
            closure: BTreeMap::new(),
            source,
            nonlocal_names: Vec::new(),
            is_generator,
            nonlocal_cell_id: None,
            assigned_names,
            global_names,
            // Methods have an empty closure, so overlay suppression
            // is moot here. The flag is kept consistent with how
            // top-level `def` would have been classified.
            is_module_level: false,
        }
    };
    // No decorators: regular method.
    if decorators.is_empty() {
        let key = format!("{class_name}.{method_name}");
        let func = register(key, body, source);
        methods.insert(method_name, func);
        return Ok(());
    }
    // Single decorator is the common case for the four builtin shapes.
    if decorators.len() == 1 {
        match &decorators[0] {
            Expr::Name(n) if n.id.as_str() == "property" => {
                let key = format!("{class_name}.{method_name}__get");
                let func = register(key, body, source);
                properties
                    .insert(method_name, PropertyDef { getter: func, setter: None, deleter: None });
                return Ok(());
            }
            Expr::Name(n) if n.id.as_str() == "staticmethod" => {
                let key = format!("{class_name}.{method_name}__static");
                let func = register(key, body, source);
                static_methods.insert(method_name, func);
                return Ok(());
            }
            Expr::Name(n) if n.id.as_str() == "classmethod" => {
                let key = format!("{class_name}.{method_name}__class");
                let func = register(key, body, source);
                class_methods.insert(method_name, func);
                return Ok(());
            }
            // `@x.setter` / `@x.deleter`: attribute access on an
            // existing property. We resolve x by name in the current
            // class scope (the method_name must equal x.attr — Python
            // requires the property and accessor share the same name).
            Expr::Attribute(attr) => {
                if let Expr::Name(prop_name) = attr.value.as_ref() {
                    let prop_key = prop_name.id.as_str().to_string();
                    let kind = attr.attr.as_str();
                    if properties.contains_key(&prop_key) {
                        let suffix = match kind {
                            "setter" => "__set",
                            "deleter" => "__del",
                            _ => "",
                        };
                        if !suffix.is_empty() {
                            let key = format!("{class_name}.{prop_key}{suffix}");
                            let func = register(key, body, source);
                            if let Some(prop) = properties.get_mut(&prop_key) {
                                match kind {
                                    "setter" => {
                                        prop.setter = Some(func);
                                        return Ok(());
                                    }
                                    "deleter" => {
                                        prop.deleter = Some(func);
                                        return Ok(());
                                    }
                                    _ => {}
                                }
                            }
                        }
                    }
                }
            }
            _ => {}
        }
    }
    Err(InterpreterError::Security(format!(
        "method-level decorator stack on '{method_name}' is not one of the supported \
         shapes (@property, @<name>.setter, @<name>.deleter, @staticmethod, @classmethod). \
         See CONFORMANCE.md#unsupported-language-features.",
    ))
    .into())
}

/// Apply a single decorator (any callable Value) to a target Value.
/// Used by class-decorator and function-decorator paths. Only
/// Function / Lambda values are accepted as callables; other forms
/// (Class instances with __call__, builtin sentinels) are out of scope
/// for B2 and rejected with a clear error.
pub(crate) async fn apply_decorator(
    state: &mut InterpreterState,
    decorator: &Value,
    target: Value,
    tools: &Tools,
) -> EvalResult {
    let kwargs: IndexMap<String, Value> = IndexMap::new();
    match decorator {
        Value::Function(def) => {
            let positional = [target];
            call_user_function(state, def, &positional, &kwargs, tools).await
        }
        Value::Lambda(def) => {
            let positional = [target];
            call_lambda(state, def, &positional, &kwargs, tools).await
        }
        // `@dataclasses.dataclass` (bare form): rewrites the target
        // class in-place to record its [`DataclassField`] list. The
        // class identity does not change — the same `Value::Class`
        // handle is returned. The same path handles
        // `dataclasses.dataclass(C)` (call form), which is
        // `@dataclass`-equivalent per CPython.
        Value::ModuleFunction { module, name }
            if module == "dataclasses" && name == "dataclass" =>
        {
            let class_name = match &target {
                Value::Class(n) => n.clone(),
                other => {
                    return Err(InterpreterError::TypeError(format!(
                        "@dataclass requires a class target (got '{}')",
                        other.type_name()
                    ))
                    .into());
                }
            };
            crate::eval::modules::dataclasses::apply_dataclass(state, &class_name, &kwargs)?;
            Ok(Value::Class(class_name))
        }
        // @lru_cache / @cache as bare ModuleFunction decorator.
        Value::ModuleFunction { module, name }
            if module == "functools" && (name == "lru_cache" || name == "cache") =>
        {
            let maxsize = if name == "cache" { None } else { Some(128) };
            Ok(crate::eval::modules::functools::make_lru_cache_pub(target, maxsize))
        }
        // Partial: `@dataclass(frozen=True)` carries kwargs; `@lru_cache(n)`
        // carries maxsize. Generic path: call the partial with the target.
        Value::Partial(data) => {
            if let Value::ModuleFunction { module, name } = &data.func {
                if module == "dataclasses" && name == "dataclass" {
                    let class_name = match &target {
                        Value::Class(n) => n.clone(),
                        other => {
                            return Err(InterpreterError::TypeError(format!(
                                "@dataclass requires a class target (got '{}')",
                                other.type_name()
                            ))
                            .into());
                        }
                    };
                    crate::eval::modules::dataclasses::apply_dataclass(
                        state,
                        &class_name,
                        &data.keywords,
                    )?;
                    return Ok(Value::Class(class_name));
                }
            }
            // General: decorator = partial; result = partial(target)
            let mut combined = data.args.clone();
            combined.push(target);
            crate::eval::functions::call_value_as_function(state, &data.func, &combined, tools)
                .await
        }
        other => Err(InterpreterError::TypeError(format!(
            "decorator is not callable (got '{}')",
            other.type_name()
        ))
        .into()),
    }
}

/// Wrap a class-body assignment as an EnumMember when the class is
/// an enum subclass. Methods (FunctionDef / Lambda) inside an enum
/// body stay unwrapped so they can be invoked. Non-method values
/// (the typical case: `RED = 1`) become EnumMember.
/// Call `attr.__set_name__(owner, name)` for each class attribute that
/// defines `__set_name__` (PEP 487).
async fn invoke_set_name(
    state: &mut InterpreterState,
    class_name: &str,
    attrs: &[(String, Value)],
    tools: &Tools,
) -> Result<(), EvalError> {
    let owner = Value::Class(class_name.to_string());
    let empty_kwargs = IndexMap::new();
    for (name, value) in attrs {
        let Value::Instance(inst) = value else {
            continue;
        };
        let Some((_, def)) = lookup_method_in_mro(state, &inst.class_name, "__set_name__") else {
            continue;
        };
        let name_val = Value::String(name.as_str().into());
        let call = CallArgs { positional: &[owner.clone(), name_val], keyword: &empty_kwargs };
        let (_ret, _self) = call_method(state, &def, value.clone(), call, tools).await?;
    }
    Ok(())
}

/// Call `Base.__init_subclass__(cls)` for each direct base that defines it.
/// CPython always treats `__init_subclass__` as a classmethod; the new
/// subclass is passed as the first argument (`cls`).
async fn invoke_init_subclass(
    state: &mut InterpreterState,
    class_name: &str,
    bases: &[String],
    tools: &Tools,
) -> Result<(), EvalError> {
    let empty_kwargs = IndexMap::new();
    let new_cls = Value::Class(class_name.to_string());
    for base in bases {
        // Look on the base's own MRO for __init_subclass__ (classmethod or plain).
        let method = lookup_class_method(state, base, "__init_subclass__")
            .or_else(|| lookup_method_in_mro(state, base, "__init_subclass__").map(|(_, d)| d));
        let Some(def) = method else {
            continue;
        };
        // Receiver = new subclass so classmethod binding yields
        // `__init_subclass__(cls=NewSubclass)`.
        let call = CallArgs { positional: &[], keyword: &empty_kwargs };
        let (_ret, _self) = call_method(state, &def, new_cls.clone(), call, tools).await?;
    }
    Ok(())
}

fn wrap_enum_member(
    enum_kind: Option<crate::value::EnumKind>,
    class_name: &str,
    member_name: &str,
    value: Value,
) -> Value {
    let Some(kind) = enum_kind else { return value };
    // Don't wrap methods / lambdas — they're enum methods.
    if matches!(value, Value::Function(_) | Value::Lambda(_)) {
        return value;
    }
    // Don't double-wrap. Don't wrap dunders (_value_ etc.) — they're
    // metadata.
    if matches!(value, Value::EnumMember { .. }) || member_name.starts_with('_') {
        return value;
    }
    Value::EnumMember {
        class_name: class_name.to_string(),
        member_name: member_name.to_string(),
        value: Box::new(value),
        kind,
    }
}

/// Compute the C3-linearized MRO for `class_name` over `bases`. The
/// algorithm is CPython's: the MRO of a class is itself, followed by the
/// merge of (a) the MROs of each base in declaration order and (b) the
/// list of bases themselves. The merge picks the head of the first list
/// whose head does not appear in the tail of any other list; if no such
/// head exists, raise `TypeError` matching CPython's exact wording.
/// Source: <https://en.wikipedia.org/wiki/C3_linearization>.
fn build_mro(
    class_name: &str,
    bases: &[String],
    registry: &rustc_hash::FxHashMap<String, ClassValue>,
) -> Result<Vec<String>, EvalError> {
    let mut sequences: Vec<Vec<String>> = bases
        .iter()
        .map(|b| registry.get(b).map_or_else(|| vec![b.clone()], |cls| cls.mro.clone()))
        .collect();
    sequences.push(bases.to_vec());

    let mut result: Vec<String> = vec![class_name.to_string()];

    while !sequences.iter().all(Vec::is_empty) {
        // Find a "good head" — a class that appears at the head of some
        // non-empty sequence and nowhere in the tail of any other.
        let candidate = sequences
            .iter()
            .filter_map(|seq| seq.first())
            .find(|head| sequences.iter().all(|seq| !seq.iter().skip(1).any(|n| n == *head)))
            .cloned();

        let Some(head) = candidate else {
            // CPython 3.12 includes a literal newline between
            // "resolution" and "order" in the format string. The
            // surrounding character-for-character match is what lets a
            // planner LLM trained on cpython tracebacks recognise the
            // error precisely.
            return Err(InterpreterError::TypeError(format!(
                "Cannot create a consistent method resolution\norder (MRO) for bases of class '{class_name}'"
            ))
            .into());
        };

        result.push(head.clone());

        // Strip `head` from the front of every sequence where it appears.
        for seq in &mut sequences {
            if seq.first() == Some(&head) {
                seq.remove(0);
            }
        }
        sequences.retain(|seq| !seq.is_empty());
    }

    Ok(result)
}

/// Instantiate `class_name(args, kwargs)`: allocate an empty instance and run
/// `__init__` if the class defines one.
pub async fn instantiate(
    state: &mut InterpreterState,
    class_name: &str,
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
    tools: &Tools,
) -> EvalResult {
    // Enum value-construction: `Color(1)` returns the member whose
    // value equals the arg. Customer pattern is
    // `Color.from_value = Color(value)`; matching CPython's
    // `Enum(value)` constructor.
    if let Some(class) = state.classes.get(class_name) {
        if class.enum_kind.is_some() && args.len() == 1 && kwargs.is_empty() {
            let needle = &args[0];
            for (member_name, member_value) in &class.class_attrs {
                if let Value::EnumMember { value, .. } = member_value {
                    if crate::eval::operations::values_equal_pub(value, needle) {
                        return Ok(member_value.clone());
                    }
                    let _ = member_name;
                }
            }
            return Err(crate::error::EvalError::Exception(crate::value::ExceptionValue::new(
                "ValueError",
                format!("{needle} is not a valid {class_name}"),
            )));
        }
        // Exception subclasses: `class E(Exception): ...; raise E("msg")`
        // constructs a Value::Exception with the class name as type_name so
        // except-matching can walk the MRO. Mirrors ExceptionType constructors.
        let is_exception_subclass = class.mro.iter().any(|b| {
            b == "Exception"
                || b == "BaseException"
                || crate::eval::functions::is_exception_type_name(b)
        });
        if is_exception_subclass {
            let message = match args.len() {
                0 => String::new(),
                1 => format!("{}", args[0]),
                _ => args.iter().map(|v| format!("{v}")).collect::<Vec<_>>().join(", "),
            };
            return Ok(Value::Exception(
                crate::value::ExceptionValue::new(class_name.to_string(), message)
                    .with_args(args.to_vec()),
            ));
        }
    }
    let instance = Value::Instance(InstanceValue {
        class_name: class_name.to_string(),
        fields: crate::value::shared_fields(BTreeMap::new()),
    });

    // `@dataclass`-synthesized __init__: if the class is a dataclass
    // and no user-defined `__init__` overrides the synthesis, bind
    // positional + keyword args onto the instance's fields per the
    // declared field order. CPython's @dataclass produces the same
    // mapping; doing it directly avoids generating source code for an
    // `__init__` method just to re-parse and execute it.
    let has_user_init =
        state.classes.get(class_name).is_some_and(|c| c.methods.contains_key("__init__"));
    if !has_user_init {
        if let Some(fields) = state.classes.get(class_name).and_then(|c| c.dataclass_fields.clone())
        {
            return dataclass_instantiate(state, class_name, &fields, args, kwargs, tools).await;
        }
    }

    // Walk the MRO to find an `__init__`. CPython uses
    // `type(instance).__init__`, which after MRO resolution finds the
    // most-derived class that defines it. A class without its own
    // `__init__` inherits its base's.
    let init = lookup_method_in_mro(state, class_name, "__init__");
    let Some((_defining_class, init_def)) = init else {
        // No `__init__` anywhere in the MRO: only a zero-argument call
        // is valid, as in CPython.
        if !args.is_empty() || !kwargs.is_empty() {
            return Err(
                InterpreterError::TypeError(format!("{class_name}() takes no arguments")).into()
            );
        }
        return Ok(instance);
    };
    let call = CallArgs { positional: args, keyword: kwargs };
    let (_returned, configured_self) = call_method(state, &init_def, instance, call, tools).await?;
    Ok(configured_self)
}

/// Bind `args` / `kwargs` onto a dataclass instance's fields per the
/// declared field order, applying defaults / default factories for
/// missing init-fields. Fields whose `init` flag is False are seeded
/// directly from `default` / `default_factory` without participating in
/// the positional/keyword binding.
///
/// Errors match CPython:
///   * `TypeError("'X' got multiple values for argument 'name'")` when a positional and keyword
///     both name the same field.
///   * `TypeError("'X' missing required argument: 'name'")` when an init field has no default and
///     no value was supplied.
///   * `TypeError("'X' got unexpected keyword argument 'name'")` when a keyword arg does not match
///     any init field.
async fn dataclass_instantiate(
    state: &mut InterpreterState,
    class_name: &str,
    fields: &[crate::value::DataclassField],
    args: &[Value],
    kwargs: &IndexMap<String, Value>,
    tools: &Tools,
) -> EvalResult {
    let init_fields: Vec<&crate::value::DataclassField> =
        fields.iter().filter(|f| f.init).collect();
    if args.len() > init_fields.len() {
        return Err(InterpreterError::TypeError(format!(
            "{class_name}() takes {} positional arguments but {} were given",
            init_fields.len(),
            args.len()
        ))
        .into());
    }
    // Validate keyword args against known init-field names early so a
    // typo surfaces with the same message CPython produces.
    for key in kwargs.keys() {
        if !init_fields.iter().any(|f| &f.name == key) {
            return Err(InterpreterError::TypeError(format!(
                "{class_name}() got an unexpected keyword argument '{key}'"
            ))
            .into());
        }
    }

    let mut instance_fields: BTreeMap<String, Value> = BTreeMap::new();

    for (index, field) in init_fields.iter().enumerate() {
        let positional = args.get(index).cloned();
        let keyword = kwargs.get(&field.name).cloned();
        let value = match (positional, keyword) {
            (Some(_), Some(_)) => {
                return Err(InterpreterError::TypeError(format!(
                    "{class_name}() got multiple values for argument '{}'",
                    field.name
                ))
                .into());
            }
            (Some(v), None) | (None, Some(v)) => v,
            (None, None) => {
                if let Some(default) = field.default.clone() {
                    default
                } else if let Some(factory) = field.default_factory.clone() {
                    invoke_default_factory(state, &factory, tools).await?
                } else {
                    return Err(InterpreterError::TypeError(format!(
                        "{class_name}() missing required argument: '{}'",
                        field.name
                    ))
                    .into());
                }
            }
        };
        instance_fields.insert(field.name.clone(), value);
    }

    // Non-init fields: seed from default / default_factory unconditionally.
    for field in fields.iter().filter(|f| !f.init) {
        let value = if let Some(default) = field.default.clone() {
            default
        } else if let Some(factory) = field.default_factory.clone() {
            invoke_default_factory(state, &factory, tools).await?
        } else {
            continue;
        };
        instance_fields.insert(field.name.clone(), value);
    }

    Ok(Value::Instance(InstanceValue {
        class_name: class_name.to_string(),
        fields: crate::value::shared_fields(instance_fields),
    }))
}

fn empty_for_builtin_factory(name: &str) -> EvalResult {
    match name {
        "list" => Ok(Value::List(shared_list(Vec::new()))),
        "dict" => Ok(Value::Dict(IndexMap::new())),
        "set" => Ok(Value::Set(Vec::new())),
        "tuple" => Ok(Value::Tuple(Vec::new())),
        "str" => Ok(Value::String("".into())),
        other => {
            Err(InterpreterError::TypeError(format!("default_factory '{other}' is not callable"))
                .into())
        }
    }
}

async fn invoke_default_factory(
    state: &mut InterpreterState,
    factory: &Value,
    tools: &Tools,
) -> EvalResult {
    let empty_kwargs: IndexMap<String, Value> = IndexMap::new();
    match factory {
        Value::Function(def) => call_user_function(state, def, &[], &empty_kwargs, tools).await,
        Value::Lambda(def) => call_lambda(state, def, &[], &empty_kwargs, tools).await,
        // Boxed: `invoke_default_factory` is called from
        // `dataclass_instantiate`, which is itself called from
        // `instantiate` — without the indirection the async closure
        // type would be infinitely-sized.
        Value::Class(name) => Box::pin(instantiate(state, name, &[], &empty_kwargs, tools)).await,
        Value::ModuleFunction { module, name } => {
            crate::eval::modules::call_function(state, module, name, &[], &empty_kwargs, tools)
                .await
        }
        // Built-in factory names invoked directly (e.g.
        // `default_factory=list`): `Value::Type` is the explicit-type
        // form, `Value::BuiltinName` is what bare-name lookup produces.
        // Both route to the same empty-container shim.
        Value::Type(t) => empty_for_builtin_factory(t.as_str()),
        Value::BuiltinName(name) => empty_for_builtin_factory(name.as_str()),
        other => Err(InterpreterError::TypeError(format!(
            "default_factory is not callable (got '{}')",
            other.type_name()
        ))
        .into()),
    }
}

/// Look up and call `instance.method(args)`, returning `(return_value, self)`
/// where `self` reflects any mutations the method made — the caller writes it
/// back into the receiver's slot.
pub async fn instance_method_call(
    state: &mut InterpreterState,
    instance: Value,
    method_name: &str,
    call: CallArgs<'_>,
    tools: &Tools,
) -> Result<(Value, Value), EvalError> {
    let Value::Instance(inst) = &instance else {
        return Err(
            InterpreterError::Runtime("instance_method_call on a non-instance".into()).into()
        );
    };
    let class_name = inst.class_name.clone();
    // staticmethod beats regular method per CPython's
    // __getattribute__ order. A staticmethod is called without
    // binding `self` — we route through call_user_function instead of
    // call_method (which expects a receiver).
    if let Some(def) = lookup_static_method(state, &class_name, method_name) {
        let result = call_user_function(state, &def, call.positional, call.keyword, tools).await?;
        return Ok((result, instance));
    }
    // classmethod beats regular method too. The first arg bound is
    // the class (Value::Class), not the instance.
    if let Some(def) = lookup_class_method(state, &class_name, method_name) {
        return call_method(state, &def, Value::Class(class_name.clone()), call, tools).await;
    }
    // Walk the MRO: a method defined in any ancestor is callable on
    // `instance`, with `__class__` bound to the defining class so
    // zero-arg `super()` inside that method resumes at the next slot.
    let method = lookup_method_in_mro(state, &class_name, method_name);
    let Some((_defining_class, def)) = method else {
        return Err(InterpreterError::AttributeError(format!(
            "'{class_name}' object has no attribute '{method_name}'"
        ))
        .into());
    };
    call_method(state, &def, instance, call, tools).await
}

/// Run a method body with `self` bound to `self_value`, returning the method's
/// return value and the post-execution `self` (carrying any mutations).
///
/// Unlike a free function, a method sees the *current* global scope (not a
/// def-time closure snapshot), so no closure is applied — `self` and the
/// parameters are layered over the live variables and removed on return.
/// Apply a method frame's local-scope bindings (parameters including
/// `self`) onto `state.variables`. Extracted as a sync helper so the
/// per-step state doesn't survive across `execute_body(...).await` —
/// see the matching helpers in `eval::functions::mod` for the
/// stack-budget reasoning.
fn apply_method_scope(
    state: &mut InterpreterState,
    local_scope: &std::collections::HashMap<String, Value>,
) -> Result<(), EvalError> {
    for (name, value) in local_scope {
        state.set_variable(name, value.clone()).map_err(EvalError::Interpreter)?;
    }
    Ok(())
}

pub async fn call_method(
    state: &mut InterpreterState,
    method: &FunctionDef,
    self_value: Value,
    call: CallArgs<'_>,
    tools: &Tools,
) -> Result<(Value, Value), EvalError> {
    state.enter_call().map_err(EvalError::Interpreter)?;
    // Method frames also own a cell-owners scope; nested `def` inside
    // a method body that declares `nonlocal` registers here.
    state.frame_cell_owners.push(rustc_hash::FxHashMap::default());

    // Push a method frame so zero-arg `super()` can read the defining
    // class + `self` from the top of the stack. The defining class is
    // encoded in the method's qualified name (`Class.method`).
    let defining_class =
        method.name.split_once('.').map_or_else(|| method.name.clone(), |(cls, _)| cls.to_string());
    let self_local_name = method.params.args.first().map(|p| p.name.clone());
    let frame_pushed = if let Value::Instance(_) = &self_value {
        state.method_frame_stack.push(crate::state::MethodFrame {
            defining_class,
            self_value: self_value.clone(),
            self_local_name: self_local_name.clone(),
        });
        true
    } else {
        false
    };

    // The receiver is the first positional parameter (conventionally `self`).
    let mut full_args = Vec::with_capacity(call.positional.len() + 1);
    full_args.push(self_value);
    full_args.extend_from_slice(call.positional);

    let local_scope =
        match bind_params(&method.params, &full_args, call.keyword, state, tools).await {
            Ok(scope) => scope,
            Err(e) => {
                if frame_pushed {
                    state.method_frame_stack.pop();
                }
                state.frame_cell_owners.pop();
                state.exit_call();
                return Err(e);
            }
        };
    let self_param = self_local_name.clone();

    // Snapshot only the names this method frame can touch — its
    // parameters (including `self`) plus the statically-collected
    // `assigned_names` from the body walker. Methods don't capture a
    // closure (they look up free names against the live module
    // scope), so the closure bucket is empty here. Same rationale as
    // call_user_function: this replaces an unconditional
    // state.variables.clone() that previously dominated per-call cost.
    let touched: Vec<String> = method
        .params
        .args
        .iter()
        .map(|p| p.name.clone())
        .chain(method.params.vararg.iter().cloned())
        .chain(method.params.kwonlyargs.iter().map(|p| p.name.clone()))
        .chain(method.params.kwarg.iter().cloned())
        .chain(method.assigned_names.iter().cloned())
        .filter(|n| !method.global_names.contains(n))
        .collect();
    let checkpoint = crate::eval::functions::VariableCheckpoint::capture(state, touched);

    // Apply param/self bindings via a sync helper — same future-size
    // reasoning as `call_user_function`.
    if let Err(e) = apply_method_scope(state, &local_scope) {
        checkpoint.restore(state);
        if frame_pushed {
            state.method_frame_stack.pop();
        }
        state.frame_cell_owners.pop();
        state.exit_call();
        return Err(e);
    }

    let body = state.function_bodies.get(&method.name).cloned();
    let exec_result = match body {
        Some(stmts) => execute_body(state, stmts.as_slice(), tools).await,
        None => Ok(Value::None),
    };

    // Capture the possibly-mutated `self` before the frame's scope is dropped.
    let configured_self =
        self_param.and_then(|name| state.variables.get(&name).cloned()).unwrap_or(Value::None);

    checkpoint.restore(state);
    if frame_pushed {
        state.method_frame_stack.pop();
    }
    state.frame_cell_owners.pop();
    state.exit_call();

    let returned = match exec_result {
        Ok(val) => val,
        Err(EvalError::Signal(crate::error::ControlFlow::Return(val))) => *val,
        Err(e) => return Err(e),
    };
    Ok((returned, configured_self))
}

/// Read `instance.attr`: instance field, then walk the class's MRO
/// for a class attribute. Property dispatch lives one level up in
/// `eval/names.rs::eval_attribute` because invoking a getter requires
/// async; this sync helper handles the non-descriptor cases.
pub fn instance_attribute(
    state: &InterpreterState,
    inst: &InstanceValue,
    attr: &str,
) -> EvalResult {
    if let Some(value) = inst.fields.lock().get(attr) {
        return Ok(value.clone());
    }
    if let Some(value) = lookup_class_attr(state, &inst.class_name, attr) {
        return Ok(value);
    }
    Err(InterpreterError::AttributeError(format!(
        "'{}' object has no attribute '{attr}'",
        inst.class_name
    ))
    .into())
}

/// Walk MRO for a class attribute that is a user instance (descriptor
/// candidate). First hit wins.
pub fn lookup_class_attr_instance(
    state: &InterpreterState,
    class_name: &str,
    attr: &str,
) -> Option<InstanceValue> {
    let class = state.classes.get(class_name)?;
    for ancestor_name in &class.mro {
        if let Some(ancestor) = state.classes.get(ancestor_name) {
            if let Some(Value::Instance(inst)) = ancestor.class_attrs.get(attr) {
                return Some(inst.clone());
            }
        }
    }
    None
}

/// Walk `class_name`'s MRO looking for a `@property` descriptor named
/// `attr`. Returns the first match.
pub fn lookup_property(
    state: &InterpreterState,
    class_name: &str,
    attr: &str,
) -> Option<PropertyDef> {
    let class = state.classes.get(class_name)?;
    for ancestor_name in &class.mro {
        if let Some(ancestor) = state.classes.get(ancestor_name) {
            if let Some(prop) = ancestor.properties.get(attr) {
                return Some(prop.clone());
            }
        }
    }
    None
}

/// Walk `class_name`'s MRO looking for a `@staticmethod`-marked entry.
pub fn lookup_static_method(
    state: &InterpreterState,
    class_name: &str,
    method_name: &str,
) -> Option<FunctionDef> {
    let class = state.classes.get(class_name)?;
    for ancestor_name in &class.mro {
        if let Some(ancestor) = state.classes.get(ancestor_name) {
            if let Some(def) = ancestor.static_methods.get(method_name) {
                return Some(def.clone());
            }
        }
    }
    None
}

/// Walk `class_name`'s MRO looking for a `@classmethod`-marked entry.
pub fn lookup_class_method(
    state: &InterpreterState,
    class_name: &str,
    method_name: &str,
) -> Option<FunctionDef> {
    let class = state.classes.get(class_name)?;
    for ancestor_name in &class.mro {
        if let Some(ancestor) = state.classes.get(ancestor_name) {
            if let Some(def) = ancestor.class_methods.get(method_name) {
                return Some(def.clone());
            }
        }
    }
    None
}

/// Invoke a `@property` getter: call_method binds `instance` as `self`
/// and the property's body runs. The getter takes no extra arguments.
/// Post-call self-mutation is captured by call_method but discarded
/// here — getters that mutate `self` are a contortion CPython doesn't
/// guarantee to support uniformly.
pub async fn invoke_property_getter(
    state: &mut InterpreterState,
    getter: &FunctionDef,
    instance: Value,
    tools: &Tools,
) -> EvalResult {
    let call = CallArgs { positional: &[], keyword: &IndexMap::new() };
    let (returned, _self) = call_method(state, getter, instance, call, tools).await?;
    Ok(returned)
}

/// Invoke a `@property` setter: call_method binds `instance` as
/// `self` and the value as the explicit setter arg. The configured
/// self is returned so the caller can write it back to the receiver
/// slot.
pub async fn invoke_property_setter(
    state: &mut InterpreterState,
    setter: &FunctionDef,
    instance: Value,
    value: Value,
    tools: &Tools,
) -> Result<Value, EvalError> {
    let call = CallArgs { positional: &[value], keyword: &IndexMap::new() };
    let (_returned, configured_self) = call_method(state, setter, instance, call, tools).await?;
    Ok(configured_self)
}

/// Invoke a `@property` deleter: call_method binds `instance` as
/// `self`. The configured self is returned for write-back.
pub async fn invoke_property_deleter(
    state: &mut InterpreterState,
    deleter: &FunctionDef,
    instance: Value,
    tools: &Tools,
) -> Result<Value, EvalError> {
    let call = CallArgs { positional: &[], keyword: &IndexMap::new() };
    let (_returned, configured_self) = call_method(state, deleter, instance, call, tools).await?;
    Ok(configured_self)
}

/// Read `Class.attr`: `__name__`/`__qualname__`, then walk the MRO
/// for staticmethods, classmethods, and class attributes. Returns the
/// callable directly for static/class methods so `Math.add(...)` and
/// `Counter.factory(...)` both work without going through the
/// instance-method path.
pub fn class_attribute(state: &InterpreterState, class_name: &str, attr: &str) -> EvalResult {
    if attr == "__name__" || attr == "__qualname__" {
        return Ok(Value::String(class_name.into()));
    }
    if let Some(def) = lookup_static_method(state, class_name, attr) {
        return Ok(Value::Function(std::sync::Arc::new(def)));
    }
    if let Some(def) = lookup_class_method(state, class_name, attr) {
        // Bind the class as the first arg by wrapping in a class-method
        // marker. For now, expose the bare FunctionDef and rely on the
        // call path to prepend Value::Class(class_name) — the
        // dispatch fast-path for `Class.method(...)` calls `call_method`
        // with the class as receiver, which already binds it as the
        // first param.
        let _ = def;
        // Returning a method-marker sentinel so the call path handles
        // binding. The sentinel re-uses the legacy `__method__self__`
        // shape; the call evaluator's class-method dispatch builds the
        // bound call.
        return Ok(Value::UnboundClassMethod {
            class: class_name.to_string(),
            method: attr.to_string(),
        });
    }
    if let Some(value) = lookup_class_attr(state, class_name, attr) {
        return Ok(value);
    }
    Err(InterpreterError::AttributeError(format!(
        "type object '{class_name}' has no attribute '{attr}'"
    ))
    .into())
}

/// Walk `class_name`'s MRO looking for `attr` in each ancestor's
/// `class_attrs`. Returns the first match per CPython's MRO rule (most
/// derived wins). Returns `None` if no class in the MRO defines `attr`.
fn lookup_class_attr(state: &InterpreterState, class_name: &str, attr: &str) -> Option<Value> {
    let class = state.classes.get(class_name)?;
    for ancestor_name in &class.mro {
        if let Some(ancestor) = state.classes.get(ancestor_name) {
            if let Some(value) = ancestor.class_attrs.get(attr) {
                return Some(value.clone());
            }
        }
    }
    None
}

/// Receiver context for `super_method_call`: the super proxy's defining
/// class plus the bound instance. Bundled into a struct so the per-call
/// surface stays under the workspace's 4-positional-arg threshold for
/// `pub` functions (see `.claude/rules/rust.md`).
pub struct SuperReceiver<'a> {
    pub defining_class: &'a str,
    pub instance: InstanceValue,
}

/// Call a method via `super()` — find the next method named
/// `method_name` in `recv.instance.class_name`'s MRO starting at the
/// slot AFTER `recv.defining_class`, then run it with the instance as
/// the receiver. CPython's `super().method(...)` dispatches against the
/// original receiver but skips the calling class's own implementation,
/// which is how cooperative multiple inheritance composes correctly.
pub async fn super_method_call(
    state: &mut InterpreterState,
    recv: SuperReceiver<'_>,
    method_name: &str,
    call: CallArgs<'_>,
    tools: &Tools,
) -> Result<(Value, Value), EvalError> {
    let SuperReceiver { defining_class, instance } = recv;
    let Some(class) = state.classes.get(&instance.class_name) else {
        return Err(InterpreterError::Runtime(format!(
            "super(): instance's class '{}' is not registered",
            instance.class_name
        ))
        .into());
    };
    // Find `defining_class`'s position in the MRO, then scan everything
    // after it for the method.
    let start = class.mro.iter().position(|c| c == defining_class).ok_or_else(|| {
        EvalError::from(InterpreterError::TypeError(format!(
            "super(): '{defining_class}' is not in MRO of '{}'",
            instance.class_name
        )))
    })?;
    let mut found = None;
    for ancestor_name in class.mro.iter().skip(start + 1) {
        if let Some(ancestor) = state.classes.get(ancestor_name) {
            if let Some(def) = ancestor.methods.get(method_name) {
                found = Some(def.clone());
                break;
            }
        }
    }
    let Some(def) = found else {
        // CPython's `object` is the implicit base when the MRO is
        // exhausted. We don't model `object` as a registered class,
        // but the default impls of `__setattr__` / `__delattr__` /
        // `__getattribute__` need to do real work — without them the
        // common idiom `super().__setattr__(name, value)` from a
        // user `__setattr__` has nowhere to land. Implement those
        // three slots inline as the object-level defaults.
        return match method_name {
            "__setattr__" => {
                let attr_name = call
                    .positional
                    .first()
                    .and_then(|v| if let Value::String(s) = v { Some(s.clone()) } else { None })
                    .ok_or_else(|| {
                        EvalError::from(InterpreterError::TypeError(
                            "object.__setattr__: first argument must be str".into(),
                        ))
                    })?;
                let value = call.positional.get(1).cloned().ok_or_else(|| {
                    EvalError::from(InterpreterError::TypeError(
                        "object.__setattr__: missing value argument".into(),
                    ))
                })?;
                let inst = instance;
                inst.fields.lock().insert(attr_name.into(), value);
                let updated = Value::Instance(inst);
                if let Some(name) =
                    state.method_frame_stack.last().and_then(|f| f.self_local_name.clone())
                {
                    state.set_variable(&name, updated.clone()).map_err(EvalError::Interpreter)?;
                }
                Ok((Value::None, updated))
            }
            "__delattr__" => {
                let attr_name = call
                    .positional
                    .first()
                    .and_then(|v| if let Value::String(s) = v { Some(s.clone()) } else { None })
                    .ok_or_else(|| {
                        EvalError::from(InterpreterError::TypeError(
                            "object.__delattr__: argument must be str".into(),
                        ))
                    })?;
                let inst = instance;
                let class_name = inst.class_name.clone();
                if inst.fields.lock().remove(attr_name.as_str()).is_none() {
                    return Err(InterpreterError::AttributeError(format!(
                        "'{class_name}' object has no attribute '{attr_name}'"
                    ))
                    .into());
                }
                let updated = Value::Instance(inst);
                if let Some(name) =
                    state.method_frame_stack.last().and_then(|f| f.self_local_name.clone())
                {
                    state.set_variable(&name, updated.clone()).map_err(EvalError::Interpreter)?;
                }
                Ok((Value::None, updated))
            }
            _ => Err(InterpreterError::AttributeError(format!(
                "'super' object has no attribute '{method_name}'"
            ))
            .into()),
        };
    };
    // Capture the caller's `self` local-name BEFORE entering call_method
    // (which pushes its own frame). After the parent method mutates its
    // own copy of self, write the result back to the calling method's
    // self variable so its subsequent statements see the mutation —
    // matching CPython's reference semantics through our owned model.
    let caller_self_name = state.method_frame_stack.last().and_then(|f| f.self_local_name.clone());
    let (returned, configured_self) =
        call_method(state, &def, Value::Instance(instance), call, tools).await?;
    if let Some(name) = caller_self_name {
        let _ = state.set_variable(&name, configured_self.clone());
    }
    Ok((returned, configured_self))
}

/// Walk `class_name`'s MRO looking for a method definition. Used by the
/// call path (`instance_method_call`) and by `instantiate` for
/// `__init__` lookup. Returns the first matching `(defining_class,
/// FunctionDef)` so callers can build the per-frame `__class__` binding
/// for zero-arg `super()`.
/// Method or classmethod named `method_name` on `class_name`'s MRO.
fn lookup_method_or_classmethod(
    state: &InterpreterState,
    class_name: &str,
    method_name: &str,
) -> Option<(String, FunctionDef)> {
    if let Some(found) = lookup_method_in_mro(state, class_name, method_name) {
        return Some(found);
    }
    let class = state.classes.get(class_name)?;
    for ancestor_name in &class.mro {
        if let Some(ancestor) = state.classes.get(ancestor_name) {
            if let Some(def) = ancestor.class_methods.get(method_name) {
                return Some((ancestor_name.clone(), def.clone()));
            }
        }
    }
    None
}

pub fn lookup_method_in_mro(
    state: &InterpreterState,
    class_name: &str,
    method_name: &str,
) -> Option<(String, FunctionDef)> {
    let class = state.classes.get(class_name)?;
    for ancestor_name in &class.mro {
        if let Some(ancestor) = state.classes.get(ancestor_name) {
            if let Some(def) = ancestor.methods.get(method_name) {
                return Some((ancestor_name.clone(), def.clone()));
            }
        }
    }
    None
}

/// `type(name, bases, dict)` — dynamic class creation.
pub(crate) fn dynamic_type_new(
    state: &mut InterpreterState,
    name_v: &Value,
    bases_v: &Value,
    dict_v: &Value,
) -> Result<Value, EvalError> {
    let Value::String(name) = name_v else {
        return Err(InterpreterError::TypeError("type() argument 1 must be str".into()).into());
    };
    let class_name = name.to_string();
    let mut bases: Vec<String> = Vec::new();
    let base_items: Vec<Value> = match bases_v {
        Value::Tuple(items) => items.clone(),
        Value::List(l) => l.lock().clone(),
        _ => {
            return Err(
                InterpreterError::TypeError("type() argument 2 must be a tuple".into()).into()
            );
        }
    };
    for b in base_items {
        match b {
            Value::Class(n) => bases.push(n),
            Value::ExceptionType(n) => bases.push(n),
            Value::Type(n) | Value::BuiltinName(n) if n == "object" || n == "type" => {}
            other => {
                return Err(InterpreterError::TypeError(format!(
                    "type() bases must be types, not '{}'",
                    other.type_name()
                ))
                .into());
            }
        }
    }
    let mut class_attrs = BTreeMap::new();
    if let Value::Dict(map) = dict_v {
        for (k, v) in map {
            if let crate::value::ValueKey::String(s) = k {
                class_attrs.insert(s.to_string(), v.clone());
            }
        }
    } else {
        return Err(InterpreterError::TypeError("type() argument 3 must be a dict".into()).into());
    }
    let mro = build_mro(&class_name, &bases, &state.classes)?;
    let (slots, slot_names) = parse_slots_attr(class_attrs.get("__slots__"));
    state.classes.insert(class_name.clone(), {
        let mut cv = ClassValue::new(class_name.clone());
        cv.class_attrs = class_attrs;
        cv.bases = bases;
        cv.mro = mro;
        cv.slots = slots;
        cv.slot_names = slot_names;
        cv
    });
    Ok(Value::Class(class_name))
}

/// `Meta.__prepare__(name, bases)` → optional initial namespace dict.
async fn invoke_metaclass_prepare(
    state: &mut InterpreterState,
    meta: &str,
    class_name: &str,
    bases: &[String],
    tools: &Tools,
) -> Result<Option<IndexMap<crate::value::ValueKey, Value>>, EvalError> {
    let Some((_, method)) = lookup_method_or_classmethod(state, meta, "__prepare__") else {
        return Ok(None);
    };
    // PEP 3115: `namespace = metaclass.__prepare__(name, bases)` — NOT bound
    // as an instance method; only (name, bases) are passed.
    let name_v = Value::String(class_name.into());
    let bases_t = Value::Tuple(bases.iter().map(|b| Value::Class(b.clone())).collect());
    let empty_kw = IndexMap::new();
    let returned = crate::eval::functions::call_user_function(
        state,
        &method,
        &[name_v, bases_t],
        &empty_kw,
        tools,
    )
    .await?;
    let _ = meta;
    match returned {
        Value::Dict(map) => Ok(Some(map)),
        Value::None => Ok(None),
        other => Err(InterpreterError::TypeError(format!(
            "__prepare__() must return a mapping, not '{}'",
            other.type_name()
        ))
        .into()),
    }
}

/// Call `Meta.__init__(cls, name, bases, namespace)` when present.
async fn invoke_metaclass_init(
    state: &mut InterpreterState,
    class_name: &str,
    meta: &str,
    tools: &Tools,
) -> Result<(), EvalError> {
    let Some((_, method)) = lookup_method_or_classmethod(state, meta, "__init__") else {
        return Ok(());
    };
    let class = state
        .classes
        .get(class_name)
        .cloned()
        .ok_or_else(|| EvalError::from(InterpreterError::name_not_defined(class_name)))?;
    let mut ns = IndexMap::new();
    for (k, v) in &class.class_attrs {
        ns.insert(crate::value::ValueKey::String(k.as_str().into()), v.clone());
    }
    let bases_t = Value::Tuple(class.bases.iter().map(|b| Value::Class(b.clone())).collect());
    let name_v = Value::String(class_name.into());
    let ns_v = Value::Dict(ns);
    // CPython: Meta.__init__(cls, name, bases, ns) with cls = the new class.
    let cls_v = Value::Class(class_name.to_string());
    let call = crate::eval::functions::CallArgs {
        positional: &[name_v, bases_t, ns_v],
        keyword: &IndexMap::new(),
    };
    let _ = call_method(state, &method, cls_v, call, tools).await?;
    let _ = meta; // used for MRO lookup above
    Ok(())
}

/// Call `Meta.__new__(Meta, name, bases, namespace)` when present.
async fn invoke_metaclass_new(
    state: &mut InterpreterState,
    class_name: &str,
    meta: &str,
    tools: &Tools,
) -> Result<(), EvalError> {
    let Some((_, method)) = lookup_method_or_classmethod(state, meta, "__new__") else {
        return Ok(());
    };
    let class = state
        .classes
        .get(class_name)
        .cloned()
        .ok_or_else(|| EvalError::from(InterpreterError::name_not_defined(class_name)))?;
    let mut ns = IndexMap::new();
    for (k, v) in &class.class_attrs {
        ns.insert(crate::value::ValueKey::String(k.as_str().into()), v.clone());
    }
    let bases_t = Value::Tuple(class.bases.iter().map(|b| Value::Class(b.clone())).collect());
    let name_v = Value::String(class_name.into());
    let ns_v = Value::Dict(ns);
    let meta_v = Value::Class(meta.to_string());
    // call_method prepends the receiver as `self`/`cls`.
    let call = crate::eval::functions::CallArgs {
        positional: &[name_v, bases_t, ns_v],
        keyword: &IndexMap::new(),
    };
    let (returned, _) = call_method(state, &method, meta_v, call, tools).await?;
    match returned {
        Value::Class(n) => {
            state.set_variable(class_name, Value::Class(n)).map_err(EvalError::Interpreter)?;
        }
        Value::None => {}
        other => {
            state.set_variable(class_name, other).map_err(EvalError::Interpreter)?;
        }
    }
    Ok(())
}

/// Parse class-body `__slots__` into (enabled, names).
fn parse_slots_attr(attr: Option<&Value>) -> (bool, Vec<String>) {
    let Some(attr) = attr else {
        return (false, Vec::new());
    };
    let names = match attr {
        Value::String(s) => vec![s.to_string()],
        Value::Tuple(items) => items
            .iter()
            .filter_map(|v| match v {
                Value::String(s) => Some(s.to_string()),
                _ => None,
            })
            .collect(),
        Value::List(shared) => {
            let guard = shared.lock();
            guard
                .iter()
                .filter_map(|v| match v {
                    Value::String(s) => Some(s.to_string()),
                    _ => None,
                })
                .collect()
        }
        _ => return (false, Vec::new()),
    };
    (true, names)
}