Fix: Unify TypeVars when indexing generic parameters twice
When a generic function indexes the same TypeVar parameter multiple times, all resulting TypeVars must share a single element type. This change ensures that subsequent indexing operations unify their fresh TypeVar with an existing one if the parameter has already been indexed, preventing incorrect type inference and false negatives. A new test, `test_let_poly_multi_index_all_results_typed`, is added to verify this behavior.
This commit is contained in:
@@ -1438,10 +1438,20 @@ impl TypeChecker {
|
||||
&& matches!(&elems[0], StaticType::Int)
|
||||
);
|
||||
if is_index_call && matches!(ret_ty, StaticType::Any) {
|
||||
let elem_var = self.fresh_var();
|
||||
let StaticType::TypeVar(elem_id) = &elem_var else { unreachable!() };
|
||||
self.index_constraints.borrow_mut().insert(*n, *elem_id);
|
||||
ret_ty = elem_var;
|
||||
let existing = self.index_constraints.borrow().get(n).copied();
|
||||
if let Some(existing_ret_id) = existing {
|
||||
// Same TypeVar indexed again — all index results on the same
|
||||
// parameter must share one element TypeVar. Unify the fresh
|
||||
// var with the existing one so they resolve together.
|
||||
let elem_var = self.fresh_var();
|
||||
self.unify(elem_var.clone(), StaticType::TypeVar(existing_ret_id), diag);
|
||||
ret_ty = Self::apply_subst(elem_var, &self.subst.borrow());
|
||||
} else {
|
||||
let elem_var = self.fresh_var();
|
||||
let StaticType::TypeVar(elem_id) = &elem_var else { unreachable!() };
|
||||
self.index_constraints.borrow_mut().insert(*n, *elem_id);
|
||||
ret_ty = elem_var;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user