rustpython-vm 0.5.0

RustPython virtual machine.
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
// spell-checker:ignore typevarobject funcobj

pub use typevar::*;

#[pymodule(sub)]
pub(crate) mod typevar {
    use crate::{
        AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
        builtins::{PyTuple, PyTupleRef, PyType, PyTypeRef, make_union},
        common::lock::PyMutex,
        function::{FuncArgs, PyComparisonValue},
        protocol::PyNumberMethods,
        stdlib::_typing::{call_typing_func_object, decl::const_evaluator_alloc},
        types::{AsNumber, Comparable, Constructor, Iterable, PyComparisonOp, Representable},
    };

    fn type_check(arg: PyObjectRef, msg: &str, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
        // Calling typing.py here leads to bootstrapping problems
        if vm.is_none(&arg) {
            return Ok(arg.class().to_owned().into());
        }
        let message_str: PyObjectRef = vm.ctx.new_str(msg).into();
        call_typing_func_object(vm, "_type_check", (arg, message_str))
    }

    fn variance_repr(
        name: &str,
        infer_variance: bool,
        covariant: bool,
        contravariant: bool,
    ) -> String {
        if infer_variance {
            return name.to_owned();
        }
        let prefix = if covariant {
            '+'
        } else if contravariant {
            '-'
        } else {
            '~'
        };
        format!("{prefix}{name}")
    }

    /// Get the module of the caller frame, similar to CPython's caller() function.
    /// Returns the module name or None if not found.
    ///
    /// Note: CPython's implementation (in typevarobject.c) gets the module from the
    /// frame's function object using PyFunction_GetModule(f->f_funcobj). However,
    /// RustPython's Frame doesn't store a reference to the function object, so we
    /// get the module name from the frame's globals dictionary instead.
    fn caller(vm: &VirtualMachine) -> Option<PyObjectRef> {
        let frame = vm.current_frame()?;

        // In RustPython, we get the module name from frame's globals
        // This is similar to CPython's sys._getframe().f_globals.get('__name__')
        frame.globals.get_item("__name__", vm).ok()
    }

    /// Set __module__ attribute for an object based on the caller's module.
    /// This follows CPython's behavior for TypeVar and similar objects.
    fn set_module_from_caller(obj: &PyObject, vm: &VirtualMachine) -> PyResult<()> {
        // Note: CPython gets module from frame->f_funcobj, but RustPython's Frame
        // architecture is different - we use globals['__name__'] instead
        let module_value: PyObjectRef = if let Some(module_name) = caller(vm) {
            // Special handling for certain module names
            if let Ok(name_str) = module_name.str(vm)
                && let Some(name) = name_str.to_str()
                && (name == "builtins" || name.starts_with('<'))
            {
                return Ok(());
            }
            module_name
        } else {
            vm.ctx.none()
        };
        obj.set_attr("__module__", module_value, vm)?;
        Ok(())
    }

    #[pyattr]
    #[pyclass(name = "TypeVar", module = "typing")]
    #[derive(Debug, PyPayload)]
    #[allow(dead_code)]
    pub struct TypeVar {
        name: PyObjectRef, // TODO PyStrRef?
        bound: PyMutex<PyObjectRef>,
        evaluate_bound: PyObjectRef,
        constraints: PyMutex<PyObjectRef>,
        evaluate_constraints: PyObjectRef,
        default_value: PyMutex<PyObjectRef>,
        evaluate_default: PyMutex<PyObjectRef>,
        covariant: bool,
        contravariant: bool,
        infer_variance: bool,
    }
    #[pyclass(
        flags(HAS_DICT, HAS_WEAKREF),
        with(AsNumber, Constructor, Representable)
    )]
    impl TypeVar {
        #[pymethod]
        fn __mro_entries__(&self, _bases: PyObjectRef, vm: &VirtualMachine) -> PyResult {
            Err(vm.new_type_error("Cannot subclass an instance of TypeVar"))
        }

        #[pygetset]
        fn __name__(&self) -> PyObjectRef {
            self.name.clone()
        }

        #[pygetset]
        fn __constraints__(&self, vm: &VirtualMachine) -> PyResult {
            let mut constraints = self.constraints.lock();
            if !vm.is_none(&constraints) {
                return Ok(constraints.clone());
            }
            let r = if !vm.is_none(&self.evaluate_constraints) {
                *constraints = self.evaluate_constraints.call((1i32,), vm)?;
                constraints.clone()
            } else {
                vm.ctx.empty_tuple.clone().into()
            };
            Ok(r)
        }

        #[pygetset]
        fn __bound__(&self, vm: &VirtualMachine) -> PyResult {
            let mut bound = self.bound.lock();
            if !vm.is_none(&bound) {
                return Ok(bound.clone());
            }
            let r = if !vm.is_none(&self.evaluate_bound) {
                *bound = self.evaluate_bound.call((1i32,), vm)?;
                bound.clone()
            } else {
                vm.ctx.none()
            };
            Ok(r)
        }

        #[pygetset]
        const fn __covariant__(&self) -> bool {
            self.covariant
        }

        #[pygetset]
        const fn __contravariant__(&self) -> bool {
            self.contravariant
        }

        #[pygetset]
        const fn __infer_variance__(&self) -> bool {
            self.infer_variance
        }

        #[pygetset]
        fn __default__(&self, vm: &VirtualMachine) -> PyResult {
            {
                let default_value = self.default_value.lock();
                if !default_value.is(&vm.ctx.typing_no_default) {
                    return Ok(default_value.clone());
                }
            }
            let evaluator = self.evaluate_default.lock().clone();
            if !vm.is_none(&evaluator) {
                let result = evaluator.call((1i32,), vm)?;
                *self.default_value.lock() = result.clone();
                Ok(result)
            } else {
                Ok(vm.ctx.typing_no_default.clone().into())
            }
        }

        #[pygetset]
        fn evaluate_bound(&self, vm: &VirtualMachine) -> PyResult {
            if !vm.is_none(&self.evaluate_bound) {
                return Ok(self.evaluate_bound.clone());
            }
            let bound = self.bound.lock();
            if !vm.is_none(&bound) {
                return Ok(const_evaluator_alloc(bound.clone(), vm));
            }
            Ok(vm.ctx.none())
        }

        #[pygetset]
        fn evaluate_constraints(&self, vm: &VirtualMachine) -> PyResult {
            if !vm.is_none(&self.evaluate_constraints) {
                return Ok(self.evaluate_constraints.clone());
            }
            let constraints = self.constraints.lock();
            if !vm.is_none(&constraints) {
                return Ok(const_evaluator_alloc(constraints.clone(), vm));
            }
            Ok(vm.ctx.none())
        }

        #[pygetset]
        fn evaluate_default(&self, vm: &VirtualMachine) -> PyResult {
            let evaluator = self.evaluate_default.lock().clone();
            if !vm.is_none(&evaluator) {
                return Ok(evaluator);
            }
            let default_value = self.default_value.lock().clone();
            if !default_value.is(&vm.ctx.typing_no_default) {
                return Ok(const_evaluator_alloc(default_value, vm));
            }
            Ok(vm.ctx.none())
        }

        #[pymethod]
        fn __typing_subst__(
            zelf: crate::PyRef<Self>,
            arg: PyObjectRef,
            vm: &VirtualMachine,
        ) -> PyResult {
            let self_obj: PyObjectRef = zelf.into();
            call_typing_func_object(vm, "_typevar_subst", (self_obj, arg))
        }

        #[pymethod]
        fn __reduce__(&self) -> PyObjectRef {
            self.name.clone()
        }

        #[pymethod]
        fn has_default(&self, vm: &VirtualMachine) -> bool {
            if !vm.is_none(&self.evaluate_default.lock()) {
                return true;
            }
            let default_value = self.default_value.lock();
            // Check if default_value is not NoDefault
            !default_value.is(&vm.ctx.typing_no_default)
        }

        #[pymethod]
        fn __typing_prepare_subst__(
            zelf: crate::PyRef<Self>,
            alias: PyObjectRef,
            args: PyObjectRef,
            vm: &VirtualMachine,
        ) -> PyResult {
            // Convert args to tuple if needed
            let args_tuple =
                if let Ok(tuple) = args.try_to_ref::<rustpython_vm::builtins::PyTuple>(vm) {
                    tuple
                } else {
                    return Ok(args);
                };

            // Get alias.__parameters__
            let parameters = alias.get_attr(identifier!(vm, __parameters__), vm)?;
            let params_tuple: PyTupleRef = parameters.try_into_value(vm)?;

            // Find our index in parameters
            let self_obj: PyObjectRef = zelf.to_owned().into();
            let param_index = params_tuple.iter().position(|p| p.is(&self_obj));

            if let Some(index) = param_index {
                // Check if we have enough arguments
                if args_tuple.len() <= index && zelf.has_default(vm) {
                    // Need to add default value
                    let mut new_args: Vec<PyObjectRef> = args_tuple.iter().cloned().collect();

                    // Add default value at the correct position
                    while new_args.len() <= index {
                        // For the current parameter, add its default
                        if new_args.len() == index {
                            let default_val = zelf.__default__(vm)?;
                            new_args.push(default_val);
                        } else {
                            // This shouldn't happen in well-formed code
                            break;
                        }
                    }

                    return Ok(rustpython_vm::builtins::PyTuple::new_ref(new_args, &vm.ctx).into());
                }
            }

            // No changes needed
            Ok(args)
        }
    }

    impl Representable for TypeVar {
        #[inline(always)]
        fn repr_str(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
            let name = zelf.name.str_utf8(vm)?;
            Ok(variance_repr(
                name.as_str(),
                zelf.infer_variance,
                zelf.covariant,
                zelf.contravariant,
            ))
        }
    }

    impl AsNumber for TypeVar {
        fn as_number() -> &'static PyNumberMethods {
            static AS_NUMBER: PyNumberMethods = PyNumberMethods {
                or: Some(|a, b, vm| {
                    let args = PyTuple::new_ref(vec![a.to_owned(), b.to_owned()], &vm.ctx);
                    make_union(&args, vm)
                }),
                ..PyNumberMethods::NOT_IMPLEMENTED
            };
            &AS_NUMBER
        }
    }

    impl Constructor for TypeVar {
        type Args = FuncArgs;

        fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
            let typevar = <Self as Constructor>::py_new(&cls, args, vm)?;
            let obj = typevar.into_ref_with_type(vm, cls)?;
            let obj_ref: PyObjectRef = obj.into();
            set_module_from_caller(&obj_ref, vm)?;
            Ok(obj_ref)
        }

        fn py_new(_cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
            let mut kwargs = args.kwargs;
            // Parse arguments manually
            let (name, constraints) = if args.args.is_empty() {
                // Check if name is provided as keyword argument
                if let Some(name) = kwargs.swap_remove("name") {
                    (name, vec![])
                } else {
                    return Err(
                        vm.new_type_error("TypeVar() missing required argument: 'name' (pos 1)")
                    );
                }
            } else if args.args.len() == 1 {
                (args.args[0].clone(), vec![])
            } else {
                let name = args.args[0].clone();
                let constraints = args.args[1..].to_vec();
                (name, constraints)
            };

            let bound = kwargs.swap_remove("bound");
            let covariant = kwargs
                .swap_remove("covariant")
                .map(|v| v.try_to_bool(vm))
                .transpose()?
                .unwrap_or(false);
            let contravariant = kwargs
                .swap_remove("contravariant")
                .map(|v| v.try_to_bool(vm))
                .transpose()?
                .unwrap_or(false);
            let infer_variance = kwargs
                .swap_remove("infer_variance")
                .map(|v| v.try_to_bool(vm))
                .transpose()?
                .unwrap_or(false);
            let default = kwargs.swap_remove("default");

            // Check for unexpected keyword arguments
            if !kwargs.is_empty() {
                let unexpected_keys: Vec<String> = kwargs.keys().map(|s| s.to_string()).collect();
                return Err(vm.new_type_error(format!(
                    "TypeVar() got unexpected keyword argument(s): {}",
                    unexpected_keys.join(", ")
                )));
            }

            // Check for invalid combinations
            if covariant && contravariant {
                return Err(vm.new_value_error("Bivariant type variables are not supported."));
            }

            if infer_variance && (covariant || contravariant) {
                return Err(vm.new_value_error("Variance cannot be specified with infer_variance"));
            }

            // Handle constraints and bound
            let (constraints_obj, evaluate_constraints) = if !constraints.is_empty() {
                // Check for single constraint
                if constraints.len() == 1 {
                    return Err(vm.new_type_error("A single constraint is not allowed"));
                }
                if bound.is_some() {
                    return Err(vm.new_type_error("Constraints cannot be used with bound"));
                }
                let constraints_tuple = vm.ctx.new_tuple(constraints);
                (constraints_tuple.into(), vm.ctx.none())
            } else {
                (vm.ctx.none(), vm.ctx.none())
            };

            // Handle bound
            let (bound_obj, evaluate_bound) = if let Some(bound) = bound {
                if vm.is_none(&bound) {
                    (vm.ctx.none(), vm.ctx.none())
                } else {
                    // Type check the bound
                    let bound = type_check(bound, "Bound must be a type.", vm)?;
                    (bound, vm.ctx.none())
                }
            } else {
                (vm.ctx.none(), vm.ctx.none())
            };

            // Handle default value
            let (default_value, evaluate_default) = if let Some(default) = default {
                (default, vm.ctx.none())
            } else {
                // If no default provided, use NoDefault singleton
                (vm.ctx.typing_no_default.clone().into(), vm.ctx.none())
            };

            Ok(Self {
                name,
                bound: PyMutex::new(bound_obj),
                evaluate_bound,
                constraints: PyMutex::new(constraints_obj),
                evaluate_constraints,
                default_value: PyMutex::new(default_value),
                evaluate_default: PyMutex::new(evaluate_default),
                covariant,
                contravariant,
                infer_variance,
            })
        }
    }

    impl TypeVar {
        pub fn new(
            vm: &VirtualMachine,
            name: PyObjectRef,
            evaluate_bound: PyObjectRef,
            evaluate_constraints: PyObjectRef,
        ) -> Self {
            Self {
                name,
                bound: PyMutex::new(vm.ctx.none()),
                evaluate_bound,
                constraints: PyMutex::new(vm.ctx.none()),
                evaluate_constraints,
                default_value: PyMutex::new(vm.ctx.typing_no_default.clone().into()),
                evaluate_default: PyMutex::new(vm.ctx.none()),
                covariant: false,
                contravariant: false,
                infer_variance: true,
            }
        }
    }

    #[pyattr]
    #[pyclass(name = "ParamSpec", module = "typing")]
    #[derive(Debug, PyPayload)]
    #[allow(dead_code)]
    pub struct ParamSpec {
        name: PyObjectRef,
        bound: Option<PyObjectRef>,
        default_value: PyMutex<PyObjectRef>,
        evaluate_default: PyMutex<PyObjectRef>,
        covariant: bool,
        contravariant: bool,
        infer_variance: bool,
    }

    #[pyclass(
        flags(HAS_DICT, HAS_WEAKREF),
        with(AsNumber, Constructor, Representable)
    )]
    impl ParamSpec {
        #[pymethod]
        fn __mro_entries__(&self, _bases: PyObjectRef, vm: &VirtualMachine) -> PyResult {
            Err(vm.new_type_error("Cannot subclass an instance of ParamSpec"))
        }

        #[pygetset]
        fn __name__(&self) -> PyObjectRef {
            self.name.clone()
        }

        #[pygetset]
        fn args(zelf: crate::PyRef<Self>, vm: &VirtualMachine) -> PyResult {
            let self_obj: PyObjectRef = zelf.into();
            let psa = ParamSpecArgs {
                __origin__: self_obj,
            };
            Ok(psa.into_ref(&vm.ctx).into())
        }

        #[pygetset]
        fn kwargs(zelf: crate::PyRef<Self>, vm: &VirtualMachine) -> PyResult {
            let self_obj: PyObjectRef = zelf.into();
            let psk = ParamSpecKwargs {
                __origin__: self_obj,
            };
            Ok(psk.into_ref(&vm.ctx).into())
        }

        #[pygetset]
        fn __bound__(&self, vm: &VirtualMachine) -> PyObjectRef {
            if let Some(bound) = self.bound.clone() {
                return bound;
            }
            vm.ctx.none()
        }

        #[pygetset]
        const fn __covariant__(&self) -> bool {
            self.covariant
        }

        #[pygetset]
        const fn __contravariant__(&self) -> bool {
            self.contravariant
        }

        #[pygetset]
        const fn __infer_variance__(&self) -> bool {
            self.infer_variance
        }

        #[pygetset]
        fn __default__(&self, vm: &VirtualMachine) -> PyResult {
            {
                let default_value = self.default_value.lock();
                if !default_value.is(&vm.ctx.typing_no_default) {
                    return Ok(default_value.clone());
                }
            }
            let evaluator = self.evaluate_default.lock().clone();
            if !vm.is_none(&evaluator) {
                let result = evaluator.call((1i32,), vm)?;
                *self.default_value.lock() = result.clone();
                Ok(result)
            } else {
                Ok(vm.ctx.typing_no_default.clone().into())
            }
        }

        #[pygetset]
        fn evaluate_default(&self, vm: &VirtualMachine) -> PyResult {
            let evaluator = self.evaluate_default.lock().clone();
            if !vm.is_none(&evaluator) {
                return Ok(evaluator);
            }
            let default_value = self.default_value.lock().clone();
            if !default_value.is(&vm.ctx.typing_no_default) {
                return Ok(const_evaluator_alloc(default_value, vm));
            }
            Ok(vm.ctx.none())
        }

        #[pymethod]
        fn __reduce__(&self) -> PyResult {
            Ok(self.name.clone())
        }

        #[pymethod]
        fn has_default(&self, vm: &VirtualMachine) -> bool {
            if !vm.is_none(&self.evaluate_default.lock()) {
                return true;
            }
            !self.default_value.lock().is(&vm.ctx.typing_no_default)
        }

        #[pymethod]
        fn __typing_subst__(
            zelf: crate::PyRef<Self>,
            arg: PyObjectRef,
            vm: &VirtualMachine,
        ) -> PyResult {
            let self_obj: PyObjectRef = zelf.into();
            call_typing_func_object(vm, "_paramspec_subst", (self_obj, arg))
        }

        #[pymethod]
        fn __typing_prepare_subst__(
            zelf: crate::PyRef<Self>,
            alias: PyObjectRef,
            args: PyObjectRef,
            vm: &VirtualMachine,
        ) -> PyResult {
            let self_obj: PyObjectRef = zelf.into();
            call_typing_func_object(vm, "_paramspec_prepare_subst", (self_obj, alias, args))
        }
    }

    impl AsNumber for ParamSpec {
        fn as_number() -> &'static PyNumberMethods {
            static AS_NUMBER: PyNumberMethods = PyNumberMethods {
                or: Some(|a, b, vm| {
                    let args = PyTuple::new_ref(vec![a.to_owned(), b.to_owned()], &vm.ctx);
                    make_union(&args, vm)
                }),
                ..PyNumberMethods::NOT_IMPLEMENTED
            };
            &AS_NUMBER
        }
    }

    impl Constructor for ParamSpec {
        type Args = FuncArgs;

        fn slot_new(cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult {
            let mut kwargs = args.kwargs;
            // Parse arguments manually
            let name = if args.args.is_empty() {
                // Check if name is provided as keyword argument
                if let Some(name) = kwargs.swap_remove("name") {
                    name
                } else {
                    return Err(
                        vm.new_type_error("ParamSpec() missing required argument: 'name' (pos 1)")
                    );
                }
            } else if args.args.len() == 1 {
                args.args[0].clone()
            } else {
                return Err(vm.new_type_error("ParamSpec() takes at most 1 positional argument"));
            };

            let bound = kwargs
                .swap_remove("bound")
                .map(|b| type_check(b, "Bound must be a type.", vm))
                .transpose()?;
            let covariant = kwargs
                .swap_remove("covariant")
                .map(|v| v.try_to_bool(vm))
                .transpose()?
                .unwrap_or(false);
            let contravariant = kwargs
                .swap_remove("contravariant")
                .map(|v| v.try_to_bool(vm))
                .transpose()?
                .unwrap_or(false);
            let infer_variance = kwargs
                .swap_remove("infer_variance")
                .map(|v| v.try_to_bool(vm))
                .transpose()?
                .unwrap_or(false);
            let default = kwargs.swap_remove("default");

            // Check for unexpected keyword arguments
            if !kwargs.is_empty() {
                let unexpected_keys: Vec<String> = kwargs.keys().map(|s| s.to_string()).collect();
                return Err(vm.new_type_error(format!(
                    "ParamSpec() got unexpected keyword argument(s): {}",
                    unexpected_keys.join(", ")
                )));
            }

            // Check for invalid combinations
            if covariant && contravariant {
                return Err(vm.new_value_error("Bivariant type variables are not supported."));
            }

            if infer_variance && (covariant || contravariant) {
                return Err(vm.new_value_error("Variance cannot be specified with infer_variance"));
            }

            // Handle default value
            let default_value = default.unwrap_or_else(|| vm.ctx.typing_no_default.clone().into());

            let paramspec = Self {
                name,
                bound,
                default_value: PyMutex::new(default_value),
                evaluate_default: PyMutex::new(vm.ctx.none()),
                covariant,
                contravariant,
                infer_variance,
            };

            let obj = paramspec.into_ref_with_type(vm, cls)?;
            let obj_ref: PyObjectRef = obj.into();
            set_module_from_caller(&obj_ref, vm)?;
            Ok(obj_ref)
        }

        fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> {
            unimplemented!("use slot_new")
        }
    }

    impl Representable for ParamSpec {
        #[inline(always)]
        fn repr_str(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
            let name = zelf.__name__().str_utf8(vm)?;
            Ok(variance_repr(
                name.as_str(),
                zelf.infer_variance,
                zelf.covariant,
                zelf.contravariant,
            ))
        }
    }

    impl ParamSpec {
        pub fn new(name: PyObjectRef, vm: &VirtualMachine) -> Self {
            Self {
                name,
                bound: None,
                default_value: PyMutex::new(vm.ctx.typing_no_default.clone().into()),
                evaluate_default: PyMutex::new(vm.ctx.none()),
                covariant: false,
                contravariant: false,
                infer_variance: true,
            }
        }
    }

    #[pyattr]
    #[pyclass(name = "TypeVarTuple", module = "typing")]
    #[derive(Debug, PyPayload)]
    #[allow(dead_code)]
    pub struct TypeVarTuple {
        name: PyObjectRef,
        default_value: PyMutex<PyObjectRef>,
        evaluate_default: PyMutex<PyObjectRef>,
    }
    #[pyclass(
        flags(HAS_DICT, HAS_WEAKREF),
        with(Constructor, Representable, Iterable)
    )]
    impl TypeVarTuple {
        #[pygetset]
        fn __name__(&self) -> PyObjectRef {
            self.name.clone()
        }

        #[pygetset]
        fn __default__(&self, vm: &VirtualMachine) -> PyResult {
            {
                let default_value = self.default_value.lock();
                if !default_value.is(&vm.ctx.typing_no_default) {
                    return Ok(default_value.clone());
                }
            }
            let evaluator = self.evaluate_default.lock().clone();
            if !vm.is_none(&evaluator) {
                let result = evaluator.call((1i32,), vm)?;
                *self.default_value.lock() = result.clone();
                Ok(result)
            } else {
                Ok(vm.ctx.typing_no_default.clone().into())
            }
        }

        #[pygetset]
        fn evaluate_default(&self, vm: &VirtualMachine) -> PyResult {
            let evaluator = self.evaluate_default.lock().clone();
            if !vm.is_none(&evaluator) {
                return Ok(evaluator);
            }
            let default_value = self.default_value.lock().clone();
            if !default_value.is(&vm.ctx.typing_no_default) {
                return Ok(const_evaluator_alloc(default_value, vm));
            }
            Ok(vm.ctx.none())
        }

        #[pymethod]
        fn has_default(&self, vm: &VirtualMachine) -> bool {
            if !vm.is_none(&self.evaluate_default.lock()) {
                return true;
            }
            let default_value = self.default_value.lock();
            !default_value.is(&vm.ctx.typing_no_default)
        }

        #[pymethod]
        fn __reduce__(&self) -> PyObjectRef {
            self.name.clone()
        }

        #[pymethod]
        fn __mro_entries__(&self, _bases: PyObjectRef, vm: &VirtualMachine) -> PyResult {
            Err(vm.new_type_error("Cannot subclass an instance of TypeVarTuple"))
        }

        #[pymethod]
        fn __typing_subst__(&self, _arg: PyObjectRef, vm: &VirtualMachine) -> PyResult {
            Err(vm.new_type_error("Substitution of bare TypeVarTuple is not supported"))
        }

        #[pymethod]
        fn __typing_prepare_subst__(
            zelf: crate::PyRef<Self>,
            alias: PyObjectRef,
            args: PyObjectRef,
            vm: &VirtualMachine,
        ) -> PyResult {
            let self_obj: PyObjectRef = zelf.into();
            call_typing_func_object(vm, "_typevartuple_prepare_subst", (self_obj, alias, args))
        }
    }

    impl Iterable for TypeVarTuple {
        fn iter(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult {
            // When unpacking TypeVarTuple with *, return [Unpack[self]]
            // This is how CPython handles Generic[*Ts]
            let typing = vm.import("typing", 0)?;
            let unpack = typing.get_attr("Unpack", vm)?;
            let zelf_obj: PyObjectRef = zelf.into();
            let unpacked = vm.call_method(&unpack, "__getitem__", (zelf_obj,))?;
            let list = vm.ctx.new_list(vec![unpacked]);
            let list_obj: PyObjectRef = list.into();
            vm.call_method(&list_obj, "__iter__", ())
        }
    }

    impl Constructor for TypeVarTuple {
        type Args = FuncArgs;

        fn slot_new(cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult {
            let mut kwargs = args.kwargs;
            // Parse arguments manually
            let name = if args.args.is_empty() {
                // Check if name is provided as keyword argument
                if let Some(name) = kwargs.swap_remove("name") {
                    name
                } else {
                    return Err(vm.new_type_error(
                        "TypeVarTuple() missing required argument: 'name' (pos 1)",
                    ));
                }
            } else if args.args.len() == 1 {
                args.args[0].clone()
            } else {
                return Err(vm.new_type_error("TypeVarTuple() takes at most 1 positional argument"));
            };

            let default = kwargs.swap_remove("default");

            // Check for unexpected keyword arguments
            if !kwargs.is_empty() {
                let unexpected_keys: Vec<String> = kwargs.keys().map(|s| s.to_string()).collect();
                return Err(vm.new_type_error(format!(
                    "TypeVarTuple() got unexpected keyword argument(s): {}",
                    unexpected_keys.join(", ")
                )));
            }

            // Handle default value
            let (default_value, evaluate_default) = if let Some(default) = default {
                (default, vm.ctx.none())
            } else {
                // If no default provided, use NoDefault singleton
                (vm.ctx.typing_no_default.clone().into(), vm.ctx.none())
            };

            let typevartuple = Self {
                name,
                default_value: PyMutex::new(default_value),
                evaluate_default: PyMutex::new(evaluate_default),
            };

            let obj = typevartuple.into_ref_with_type(vm, cls)?;
            let obj_ref: PyObjectRef = obj.into();
            set_module_from_caller(&obj_ref, vm)?;
            Ok(obj_ref)
        }

        fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> {
            unimplemented!("use slot_new")
        }
    }

    impl Representable for TypeVarTuple {
        #[inline(always)]
        fn repr_str(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
            let name = zelf.name.str(vm)?;
            Ok(name.to_string())
        }
    }

    impl TypeVarTuple {
        pub fn new(name: PyObjectRef, vm: &VirtualMachine) -> Self {
            Self {
                name,
                default_value: PyMutex::new(vm.ctx.typing_no_default.clone().into()),
                evaluate_default: PyMutex::new(vm.ctx.none()),
            }
        }
    }

    #[pyattr]
    #[pyclass(name = "ParamSpecArgs", module = "typing")]
    #[derive(Debug, PyPayload)]
    #[allow(dead_code)]
    pub struct ParamSpecArgs {
        __origin__: PyObjectRef,
    }
    #[pyclass(with(Constructor, Representable, Comparable), flags(HAS_WEAKREF))]
    impl ParamSpecArgs {
        #[pymethod]
        fn __mro_entries__(&self, _bases: PyObjectRef, vm: &VirtualMachine) -> PyResult {
            Err(vm.new_type_error("Cannot subclass an instance of ParamSpecArgs"))
        }

        #[pygetset]
        fn __origin__(&self) -> PyObjectRef {
            self.__origin__.clone()
        }
    }

    impl Constructor for ParamSpecArgs {
        type Args = (PyObjectRef,);

        fn py_new(_cls: &Py<PyType>, args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> {
            let origin = args.0;
            Ok(Self { __origin__: origin })
        }
    }

    impl Representable for ParamSpecArgs {
        #[inline(always)]
        fn repr_str(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
            // Check if origin is a ParamSpec
            if let Ok(name) = zelf.__origin__.get_attr("__name__", vm) {
                return Ok(format!("{name}.args", name = name.str(vm)?));
            }
            Ok(format!("{:?}.args", zelf.__origin__))
        }
    }

    impl Comparable for ParamSpecArgs {
        fn cmp(
            zelf: &crate::Py<Self>,
            other: &PyObject,
            op: PyComparisonOp,
            vm: &VirtualMachine,
        ) -> PyResult<PyComparisonValue> {
            op.eq_only(|| {
                if other.class().is(zelf.class())
                    && let Some(other_args) = other.downcast_ref::<ParamSpecArgs>()
                {
                    let eq = zelf.__origin__.rich_compare_bool(
                        &other_args.__origin__,
                        PyComparisonOp::Eq,
                        vm,
                    )?;
                    return Ok(PyComparisonValue::Implemented(eq));
                }
                Ok(PyComparisonValue::NotImplemented)
            })
        }
    }

    #[pyattr]
    #[pyclass(name = "ParamSpecKwargs", module = "typing")]
    #[derive(Debug, PyPayload)]
    #[allow(dead_code)]
    pub struct ParamSpecKwargs {
        __origin__: PyObjectRef,
    }
    #[pyclass(with(Constructor, Representable, Comparable), flags(HAS_WEAKREF))]
    impl ParamSpecKwargs {
        #[pymethod]
        fn __mro_entries__(&self, _bases: PyObjectRef, vm: &VirtualMachine) -> PyResult {
            Err(vm.new_type_error("Cannot subclass an instance of ParamSpecKwargs"))
        }

        #[pygetset]
        fn __origin__(&self) -> PyObjectRef {
            self.__origin__.clone()
        }
    }

    impl Constructor for ParamSpecKwargs {
        type Args = (PyObjectRef,);

        fn py_new(_cls: &Py<PyType>, args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> {
            let origin = args.0;
            Ok(Self { __origin__: origin })
        }
    }

    impl Representable for ParamSpecKwargs {
        #[inline(always)]
        fn repr_str(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
            // Check if origin is a ParamSpec
            if let Ok(name) = zelf.__origin__.get_attr("__name__", vm) {
                return Ok(format!("{name}.kwargs", name = name.str(vm)?));
            }
            Ok(format!("{:?}.kwargs", zelf.__origin__))
        }
    }

    impl Comparable for ParamSpecKwargs {
        fn cmp(
            zelf: &crate::Py<Self>,
            other: &PyObject,
            op: PyComparisonOp,
            vm: &VirtualMachine,
        ) -> PyResult<PyComparisonValue> {
            op.eq_only(|| {
                if other.class().is(zelf.class())
                    && let Some(other_kwargs) = other.downcast_ref::<ParamSpecKwargs>()
                {
                    let eq = zelf.__origin__.rich_compare_bool(
                        &other_kwargs.__origin__,
                        PyComparisonOp::Eq,
                        vm,
                    )?;
                    return Ok(PyComparisonValue::Implemented(eq));
                }
                Ok(PyComparisonValue::NotImplemented)
            })
        }
    }

    /// Helper function to call typing module functions with cls as first argument
    /// Similar to CPython's call_typing_args_kwargs
    fn call_typing_args_kwargs(
        name: &'static str,
        cls: PyTypeRef,
        args: FuncArgs,
        vm: &VirtualMachine,
    ) -> PyResult {
        let typing = vm.import("typing", 0)?;
        let func = typing.get_attr(name, vm)?;

        // Prepare arguments: (cls, *args)
        let mut call_args = vec![cls.into()];
        call_args.extend(args.args);

        // Call with prepared args and original kwargs
        let func_args = FuncArgs {
            args: call_args,
            kwargs: args.kwargs,
        };

        func.call(func_args, vm)
    }

    #[pyattr]
    #[pyclass(name = "Generic", module = "typing")]
    #[derive(Debug, PyPayload)]
    #[allow(dead_code)]
    pub struct Generic;

    #[pyclass(flags(BASETYPE, HEAPTYPE))]
    impl Generic {
        #[pyattr]
        fn __slots__(ctx: &Context) -> PyTupleRef {
            ctx.empty_tuple.clone()
        }

        #[pyclassmethod]
        fn __class_getitem__(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
            call_typing_args_kwargs("_generic_class_getitem", cls, args, vm)
        }

        #[pyclassmethod]
        fn __init_subclass__(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
            call_typing_args_kwargs("_generic_init_subclass", cls, args, vm)
        }
    }

    /// Sets the default value for a type parameter, equivalent to CPython's _Py_set_typeparam_default
    /// This is used by the CALL_INTRINSIC_2 SetTypeparamDefault instruction
    pub fn set_typeparam_default(
        type_param: PyObjectRef,
        evaluate_default: PyObjectRef,
        vm: &VirtualMachine,
    ) -> PyResult {
        // Inner function to handle common pattern of setting evaluate_default
        fn try_set_default<T>(
            obj: &PyObject,
            evaluate_default: &PyObject,
            get_field: impl FnOnce(&T) -> &PyMutex<PyObjectRef>,
        ) -> bool
        where
            T: PyPayload,
        {
            if let Some(typed_obj) = obj.downcast_ref::<T>() {
                *get_field(typed_obj).lock() = evaluate_default.to_owned();
                true
            } else {
                false
            }
        }

        // Try each type parameter type
        if try_set_default::<TypeVar>(&type_param, &evaluate_default, |tv| &tv.evaluate_default)
            || try_set_default::<ParamSpec>(&type_param, &evaluate_default, |ps| {
                &ps.evaluate_default
            })
            || try_set_default::<TypeVarTuple>(&type_param, &evaluate_default, |tvt| {
                &tvt.evaluate_default
            })
        {
            Ok(type_param)
        } else {
            Err(vm.new_type_error(format!(
                "Expected a type param, got {}",
                type_param.class().name()
            )))
        }
    }
}