_Py_subs_parameters
(
alias: PyObjectRef, // = self
args: PyTupleRef,
parameters: PyTupleRef,
item: PyObjectRef,
vm: &VirtualMachine,
)
| 447 | |
| 448 | // _Py_subs_parameters |
| 449 | pub fn subs_parameters( |
| 450 | alias: PyObjectRef, // = self |
| 451 | args: PyTupleRef, |
| 452 | parameters: PyTupleRef, |
| 453 | item: PyObjectRef, |
| 454 | vm: &VirtualMachine, |
| 455 | ) -> PyResult<PyTupleRef> { |
| 456 | let n_params = parameters.len(); |
| 457 | if n_params == 0 { |
| 458 | return Err(vm.new_type_error(format!("{} is not a generic class", alias.repr(vm)?))); |
| 459 | } |
| 460 | |
| 461 | // Step 1: Unpack args |
| 462 | let mut item: PyObjectRef = unpack_args(item, vm)?.into(); |
| 463 | |
| 464 | // Step 2: Call __typing_prepare_subst__ on each parameter |
| 465 | for param in parameters.iter() { |
| 466 | if let Ok(prepare) = param.get_attr(identifier!(vm, __typing_prepare_subst__), vm) |
| 467 | && !prepare.is(&vm.ctx.none) |
| 468 | { |
| 469 | // Call prepare(self, item) |
| 470 | item = if item.try_to_ref::<PyTuple>(vm).is_ok() { |
| 471 | prepare.call((alias.clone(), item.clone()), vm)? |
| 472 | } else { |
| 473 | // Create a tuple with the single item's "O(O)" format |
| 474 | let tuple_args = PyTuple::new_ref(vec![item.clone()], &vm.ctx); |
| 475 | prepare.call((alias.clone(), tuple_args.to_pyobject(vm)), vm)? |
| 476 | }; |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | // Step 3: Extract final arg items |
| 481 | let arg_items = if let Ok(tuple) = item.try_to_ref::<PyTuple>(vm) { |
| 482 | tuple.as_slice().to_vec() |
| 483 | } else { |
| 484 | vec![item.clone()] |
| 485 | }; |
| 486 | let n_items = arg_items.len(); |
| 487 | |
| 488 | if n_items != n_params { |
| 489 | return Err(vm.new_type_error(format!( |
| 490 | "Too {} arguments for {}; actual {}, expected {}", |
| 491 | if n_items > n_params { "many" } else { "few" }, |
| 492 | alias.repr(vm)?, |
| 493 | n_items, |
| 494 | n_params |
| 495 | ))); |
| 496 | } |
| 497 | |
| 498 | // Step 4: Replace all type variables |
| 499 | let mut new_args = Vec::new(); |
| 500 | |
| 501 | for arg in args.iter() { |
| 502 | // Skip PyType objects |
| 503 | if arg.class().is(vm.ctx.types.type_type) { |
| 504 | new_args.push(arg.clone()); |
| 505 | continue; |
| 506 | } |
no test coverage detected