Skip to content

Fix TypeParams, TypeAlias compile #5862

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 22 additions & 4 deletions compiler/codegen/src/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1042,14 +1042,32 @@ impl Compiler<'_> {
)));
};
let name_string = name.id.to_string();
if type_params.is_some() {
self.push_symbol_table();
}
self.compile_expression(value)?;

// For PEP 695 syntax, we need to compile type_params first
// so that they're available when compiling the value expression
if let Some(type_params) = type_params {
self.push_symbol_table();

// Compile type params first to define T1, T2, etc.
self.compile_type_params(type_params)?;
// Stack now has type_params tuple at top

// Compile value expression (can now see T1, T2)
self.compile_expression(value)?;
// Stack: [type_params_tuple, value]

// We need [value, type_params_tuple] for TypeAlias instruction
emit!(self, Instruction::Rotate2);

self.pop_symbol_table();
} else {
// No type params - push value first, then None (not empty tuple)
self.compile_expression(value)?;
// Push None for type_params (matching CPython)
self.emit_load_const(ConstantData::None);
}

// Push name last
self.emit_load_const(ConstantData::Str {
value: name_string.clone().into(),
});
Expand Down
16 changes: 12 additions & 4 deletions vm/src/frame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1266,10 +1266,18 @@ impl ExecutingFrame<'_> {
}
bytecode::Instruction::TypeAlias => {
let name = self.pop_value();
let type_params: PyTupleRef = self
.pop_value()
.downcast()
.map_err(|_| vm.new_type_error("Type params must be a tuple."))?;
let type_params_obj = self.pop_value();

// CPython allows None or tuple for type_params
let type_params: PyTupleRef = if vm.is_none(&type_params_obj) {
// If None, use empty tuple (matching CPython's behavior)
vm.ctx.empty_tuple.clone()
} else {
type_params_obj
.downcast()
.map_err(|_| vm.new_type_error("Type params must be a tuple."))?
};

let value = self.pop_value();
let type_alias = typing::TypeAliasType::new(name, type_params, value);
self.push_value(type_alias.into_ref(&vm.ctx).into());
Expand Down
Loading