Let me stop going in circles. I need to implement the fix now. Let me take a simpler approach.
Looking at the issue more carefully: the problem is that Type::TypeAlias(_) falls through to Bivariant in VarianceInferable::variance_of.
The simplest fix is to handle Type::TypeAlias by looking at the value_type. But as I traced, this gives Bivariant for nested type aliases because the inner formal type vars are different.
However, I think there might be a simpler approach: use the specialization information that's already stored on the TypeAliasType. The specialization maps the formal type vars to their actual types. When we compute variance_of, we should use this mapping.
For a type alias with specialization:
- specialization.generic_context().variables() gives us the formal type vars
- specialization.types() gives us the actual types
- For each formal F with actual A:
- Compute A.variance_of(target)
- Compose with F's variance
But as I traced, this gives Bivariant for nested aliases.
OK, let me try yet another approach. What if the fix is: for TypeAlias, use the specialization to get the actual types, and for each actual type A:
- Compute A.variance_of(target)
- This handles the recursion naturally
For type RefRefBox[T_rr] = RefBox[T_rr]:
- specialization = {T_rr -> T_rr}
- For formal T_rr with actual T_rr:
- T_rr.variance_of(T_rr) = Covariant
- Result: Covariant
But that's Covariant, not Invariant! The issue is that we're not looking at the value_type at all.
Hmm, what if we use a combination? For each formal F with actual A:
- If A is a TypeAlias: recurse into the TypeAlias's value_type
- Otherwise: use the GenericAlias-like formula
For type RefRefBox[T_rr] = RefBox[T_rr]:
- T_rr has actual T_rr
- T_rr is NOT a TypeAlias, so we don't recurse
- T_rr.variance_of(T_rr) = Covariant
- Result: Covariant
Still wrong.
OK, I think the issue is more fundamental. The problem is that when we have RefBox[T_rr] in the raw_value_type, it's just a type alias name, not a specialized type alias. The specialization {T_rb -> T_rr} is implicit.
So the fix should be: when computing variance_of for a type alias, check if the raw_value_type contains other type aliases, and for each, apply the outer specialization.
But this is getting very complicated. Let me try a completely different approach.
What if we just use value_type(db) and then recurse? Even though it gives Bivariant for nested aliases, maybe there's something else going on.
Actually wait, let me reconsider. Maybe the issue is that the raw_value_type DOES carry the specialization information, but it's in a different form than I thought.
When we have type RefRefBox[T_rr] = RefBox[T_rr]:
- The raw_value_type is computed by evaluating the RHS
- The RHS is the type expression
RefBox[T_rr]
- In the context of RefRefBox,
RefBox refers to the type alias, and T_rr refers to RefRefBox's formal
The evaluation of RefBox[T_rr] should produce a specialized type alias. Let me check how this works.
Actually, I just realized something important. When the raw_value_type of RefRefBox is computed, the type expression RefBox[T_rr] is evaluated. In this context:
RefBox is looked up as a name, which resolves to... what?
- It might resolve to the TypeAliasType, or it might resolve to the value_type of the type alias
If it resolves to the TypeAliasType, then RefBox[T_rr] applies the type alias to T_rr, producing a specialized type alias.
But if the specialization is not applied (or if the type alias type doesn't carry specialization info), then RefBox[T_rr] might just be the name RefBox without any application.
Hmm, let me look at how name references to type aliases are resolved.
Actually, I think the key insight might be simpler. Let me look at what raw_value_type actually contains for a PEP 695 type alias.
For type RefRefBox[T] = RefBox[T]:
- The raw_value_type is computed by evaluating
RefBox[T]
RefBox is a name that resolves to... the PEP695TypeAliasType? Or to the value_type of the type alias?
If RefBox resolves to the PEP695TypeAliasType, then RefBox[T] would be... an application? Or just the type alias with a type var?
I think RefBox in a type expression context resolves to the TypeAliasType. And RefBox[T] is just the TypeAliasType with T as a subscript argument.
But the TypeAliasType itself doesn't carry the specialization. The specialization is only applied when we call value_type().
So the raw_value_type is just the TypeAliasType (without specialization), and the specialization is applied separately when we call value_type().
This means: when computing variance_of for TypeAlias(RefBox), the raw_value_type doesn't have the specialization info. It's just the raw value type of RefBox, which is Box[T_rb] where T_rb is RefBox's own formal.
The fix should be: when computing variance_of for TypeAlias(RefRefBox) with target T_rr:
- Get the specialization: {T_rr -> T_rr}
- Get the raw_value_type: RefBox[T_rr]
- Apply the specialization to the raw_value_type: RefBox[T_rr] with T_rr -> T_rr = RefBox[T_rr] (unchanged)
- Compute variance_of(T_rr) on RefBox[T_rr]
But RefBox[T_rr] is just TypeAlias(RefBox), and when we recurse, we get Bivariant.
So the issue is that RefBox[T_rr] doesn't carry the specialization {T_rb -> T_rr}.
I think the fix should be at the level of how the raw_value_type is constructed. When RefBox[T_rr] is evaluated in the context of RefRefBox, the result should be a specialized type alias with T_rb -> T_rr.
But if the implementation doesn't do this, we need to add it.
Hmm, actually, I think maybe the issue is in how the raw_value_type is computed. Let me look at the code that computes the raw_value_type.
When we have type RefRefBox[T_rr] = RefBox[T_rr]:
- The RHS is
RefBox[T_rr]
- This is parsed as an index expression
- The base is
RefBox (a name)
- The subscript is
[T_rr]
When evaluated:
RefBox resolves to the type alias's type
T_rr resolves to the formal type var
- The combination should produce... what?
I think RefBox[T_rr] should produce a specialized PEP695TypeAliasType with the specialization T_rb -> T_rr.
But maybe the implementation stores this as just the raw value type (Box[T_rb]) without the specialization.
OK, I'm going to implement a fix. Let me just add handling for TypeAlias in the variance_of implementation. The approach will be:
- If the alias has a generic context:
- Iterate over formal type vars and their types from the specialization
- For each formal F with actual A:
- Compute A.variance_of(target)
- If A has its own generic context (i.e., A is a TypeAlias), recurse into A's value_type
- Compose
- .collect()
Actually, you know what? Let me look at this from a completely different angle. What if the issue is in how the value_type is computed for a PEP 695 type alias?
When type RefRefBox[T_rr] = RefBox[T_rr] is defined:
- The raw_value_type is RefBox[T_rr]
- When we call value_type(), it applies the specialization
- But the specialization is {T_rr -> T_rr}, which is identity
- So value_type = raw_value_type = RefBox[T_rr]
Now, when we call variance_of(T_rr) on RefBox[T_rr]:
- RefBox is a TypeAliasType
- RefBox has its own generic context
- We need to know that T_rr is the actual type for RefBox's formal T_rb
But RefBox[T_rr] doesn't carry this information. The type is just TypeAlias(RefBox), and the T_rr is just a type var in the expression.
I think the fix should be: when computing variance_of for a type alias, check if the target typevar matches any of the formal type vars. If it does, compute the formal's variance in the raw_value_type.
But wait, that's what I tried before, and it gave Bivariant because the formal of the outer alias (T_rr) doesn't match the formal of the inner alias (T_rb).
OK let me try a different approach. What if the fix is to NOT iterate over formals, but instead to directly use the value_type?
For TypeAlias(alias):
- value_type = alias.value_type(db)
- variance_of(typevar) on value_type
For type RefRefBox[T_rr] = RefBox[T_rr]:
- value_type = RefBox[T_rr] (TypeAlias(RefBox))
- variance_of(T_rr) on TypeAlias(RefBox):
- RefBox's value_type = Box[T_rb]
- variance_of(T_rr) on Box[T_rb]:
Still Bivariant!
The issue is that RefBox's value_type is Box[T_rb] where T_rb is a different type var. The substitution T_rb -> T_rr is lost.
Hmm, but wait. When we compute RefRefBox.value_type(), it applies the specialization {T_rr -> T_rr} to the raw_value_type RefBox[T_rr]. The result is RefBox[T_rr] where T_rr is the formal of RefRefBox.
Then when we call variance_of(T_rr) on RefBox[T_rr], we recurse into RefBox. But RefBox.value_type() = Box[T_rb] where T_rb is RefBox's formal.
The substitution T_rr -> T_rb is NOT applied. The value_type of RefBox doesn't know about the outer context.
I think the fix should be: when computing variance_of for a type alias, we need to apply the OUTER specialization (from the context where the type alias is used) to the inner value_type.
But this is complicated because we'd need to pass the specialization through the recursion.
Actually, I think maybe the fix is simpler. What if we just need to handle the case where the type alias's formal type var is the same as the target?
For type RefRefBox[T_rr] = RefBox[T_rr]:
- T_rr is the target
- T_rr is a formal of RefRefBox
- So we compute T_rr's variance in the raw_value_type
- raw_value_type = RefBox[T_rr]
- We need T_rr's variance in RefBox
For RefBox:
- T_rb is the formal of RefBox
- T_rr replaces T_rb
- T_rr's variance in RefBox = T_rb's variance in RefBox (since T_rr is a substitution for T_rb)
But how do we know that T_rr replaces T_rb? We need to look at the specialization of RefBox.
Wait, RefBox's specialization is {T_rb -> T_rb} (identity). But in the context of RefRefBox, the actual type for T_rb is T_rr.
The issue is that the specialization information is not propagated.
OK, I think I finally understand the root cause. The issue is that:
- When
type RefRefBox[T_rr] = RefBox[T_rr] is evaluated, the raw_value_type is RefBox[T_rr].
- RefBox[T_rr] is just a type alias with the formal T_rr in the expression.
- But RefBox has its OWN formal T_rb.
- The relationship between T_rr and T_rb is: T_rr replaces T_rb.
- This relationship is NOT captured in the type structure.
When we call variance_of(T_rr) on TypeAlias(RefBox):
- RefBox has formal T_rb
- T_rr is not T_rb
- So T_rr is not "in" RefBox
- Result: Bivariant
But the correct result should be: T_rr's variance in RefBox = T_rb's variance in RefBox = Invariant.
The fix: when computing variance_of for a type alias with target X:
- Check if X is equal to any formal type var
- If yes: compute X's variance in raw_value_type
- If no: compute X's variance through the actual types
But "X is equal to any formal type var" requires checking all formals, including nested ones.
Wait, actually, I think the issue is even simpler. Let me re-read the GenericAlias implementation:
.map(|(generic_typevar, ty)| {
if let Some(explicit_variance) = generic_typevar.typevar(db).explicit_variance(db) {
ty.with_polarity(explicit_variance).variance_of(db, typevar)
} else {
let typevar_variance_in_substituted_type = ty.variance_of(db, typevar);
origin
.with_polarity(typevar_variance_in_substituted_type)
.variance_of(db, generic_typevar)
}
})
For each formal F with actual ty:
- If F has explicit variance: ty.with_polarity(F's explicit variance).variance_of(target)
- Else:
- var_in_ty = ty.variance_of(target)
- origin.with_polarity(var_in_ty).variance_of(F)
The key insight: the origin class's variance_of(F) determines F's variance in the class. For Box, F's variance is Invariant.
For type aliases, the "origin" equivalent is the raw_value_type. But raw_value_type might contain other type aliases.
When we compute raw_value_type.variance_of(F):
- raw_value_type = RefBox[T_rr] for RefRefBox
- This calls variance_of(F) on TypeAlias(RefBox)
- TypeAlias(RefBox) has formal T_rb, not T_rr
- So F (= T_rr) is not a formal of RefBox
- Result: Bivariant
But the correct answer should consider that T_rr replaces T_rb.
I think the fix needs to check if F is equal to some formal of the inner alias. But that doesn't make sense because F and the inner alias's formal are different.
OK I think I finally get it. The fix should NOT be to recurse into the raw_value_type. Instead, it should be to use the specialization information to determine the variance.
For type RefRefBox[T_rr] = RefBox[T_rr]:
- RefRefBox has generic context [T_rr]
- RefRefBox's raw_value_type = RefBox[T_rr]
- The raw_value_type contains a reference to RefBox's formal (through the subscript)
Wait, does it? The raw_value_type is computed by evaluating RefBox[T_rr]. The result is...
OK let me just look at what the raw_value_type actually is. Let me check the code that computes it.
Actually, I think the raw_value_type is computed by looking at the AST and evaluating the RHS. For type RefRefBox[T_rr] = RefBox[T_rr], the RHS is the expression RefBox[T_rr]. This is a subscript expression with base RefBox and subscript T_rr.
When evaluated:
RefBox is a name that resolves to... the type of the name RefBox
T_rr is a name that resolves to... the type of T_rr (which is a type var)
The result of RefBox[T_rr] would be... what type?
I think it resolves to the type alias's type (PEP695TypeAliasType for RefBox), and the subscript is just metadata that's not stored.
OR: it resolves to the type alias applied to T_rr, producing a specialized type alias.
I need to check.
Let me just implement a fix and test it. I'll try the simplest approach first.
OK, let me now implement the fix. I'll modify the variance_of implementation for Type in types.rs.
The fix: add a special case for Type::TypeAlias(alias) that looks at the generic context and raw_value_type.
After much deliberation, I think the correct approach is:
For Type::TypeAlias(alias):
- If alias has no generic context: return Bivariant
- If alias has generic context:
- Get the generic context and raw_value_type
- For each formal F in the generic context:
- Get the actual type A (from specialization or F itself)
- Compute F's variance in the raw_value_type
- This is: raw_value_type.variance_of(F) where F is the formal type var
- .collect() joins all formals' variances
- This gives the variance of the type alias as a whole
But this computes the formal's variance, not the target's variance. We need to check if the target is one of the formals.
Actually, wait. For a generic type alias, the variance of the type alias IS the variance of its formals. When we ask "what is the variance of X in this type alias?", we're asking about the type alias's generic parameter variance.
Hmm, but that's not quite right either. When we have type RefRefBox[T_rr] = RefBox[T_rr] and we ask for variance_of(T_rr), we want the variance of the outer T_rr.
Let me think about what GenericAlias.variance_of computes. For Box[T]:
- Formal T with actual T
- T.variance_of(X): if X == T, Covariant
- origin.with_polarity(Covariant).variance_of(T) = Box.variance_of(T) = Invariant
So the result is: for each formal, we compute the contribution to the overall variance. The overall variance is the join of all contributions.
For Box[T]:
- T contributes: Invariant
- Overall: Invariant
For type RefRefBox[T_rr] = RefBox[T_rr]:
- T_rr is the formal
- T_rr contributes: ???
- If T_rr's contribution is Invariant, overall is Invariant
For T_rr to contribute Invariant:
- A.variance_of(T_rr) = Covariant (A = T_rr, X = T_rr)
- F's variance in raw_value_type = Invariant
- Compose: Covariant composed with Invariant = Invariant
So we need F's variance in raw_value_type to be Invariant.
F's variance in raw_value_type = raw_value_type.variance_of(F)
For RefRefBox with raw_value_type = RefBox[T_rr] and F = T_rr:
- raw_value_type.variance_of(T_rr) = RefBox[T_rr].variance_of(T_rr)
This is where the recursion happens. If we handle TypeAlias correctly, we get the right answer.
For TypeAlias(RefBox) with target T_rr:
- RefBox has formal T_rb
- T_rr is not T_rb
- So T_rr is not a formal of RefBox
- Result: Bivariant
But we want Invariant. The issue is that T_rr REPLACES T_rb, so T_rr should inherit T_rb's variance.
I think the fix is: when computing variance_of(X) on a type alias, check if X matches any formal. If X == formal, compute the formal's variance. If X is not a formal, then check if X is in the actual type of any formal.
But X (= T_rr) is not in any actual type of RefBox (the actual types are formal type vars of RefBox).
Hmm, actually, for RefBox, the formal T_rb has actual T_rb (identity). And X (= T_rr) != T_rb. So X is not in the actual type.
But X IS the type that would replace T_rb if RefBox were specialized with T_rr.
I think the issue is that we're computing the variance of X in a UNSPECIALIZED type alias. The unspecialized type alias has formals and raw_value_type, but no knowledge of what actual types will replace them.
So when we ask "what is X's variance in RefBox?" and X is not RefBox's formal, the answer is Bivariant.
But for type RefRefBox[T_rr] = RefBox[T_rr], the T_rr IS RefRefBox's formal, and it replaces RefBox's T_rb. So T_rr's variance in RefRefBox should be determined by T_rb's variance in RefBox.
The question is: how do we compute this?
I think the fix should be: when computing variance_of for a type alias with target X:
- Check if X is equal to any formal of the alias
- If yes: compute X's variance in raw_value_type
- If no: check if X is equal to any formal of a nested type alias (through the actual types)
- Recurse
This is getting very complex. Let me try a different approach.
What if the fix is simply: for TypeAlias, use the value_type and the specialization to compute the variance?
For type RefRefBox[T_rr] = RefBox[T_rr]:
- specialization = {T_rr -> T_rr} (identity)
- value_type = RefBox[T_rr]
- When we compute variance_of(T_rr) on RefBox[T_rr]:
- RefBox has generic context [T_rb]
- The specialization of RefBox is {T_rb -> T_rb} (identity, because RefBox itself is unspecialized)
- But in the context of RefRefBox, T_rr replaces T_rb
The issue is that RefBox's specialization doesn't know about the outer context.
I think the fix needs to propagate the outer specialization through the recursion. When we compute variance_of on a type alias with target X:
- If X is one of the alias's formals:
- Compute X's variance in raw_value_type
- If X is in the actual type of some formal:
- Compute actual_type.variance_of(X) composed with formal's variance
- If X is in a nested type alias:
- Recurse into the nested type alias with the outer specialization
This third case is the tricky one.
OK, let me try the simplest possible fix: just use value_type.
For Type::TypeAlias(alias) => alias.value_type(db).variance_of(db, typevar):
For type RefRefBox[T_rr] = RefBox[T_rr]:
- value_type = RefBox[T_rr] (with identity specialization applied)
- variance_of(T_rr) on RefBox[T_rr]:
- RefBox is a TypeAlias with formal T_rb
- Recurse
- value_type of RefBox = Box[T_rb] (with identity specialization applied)
- variance_of(T_rr) on Box[T_rb]:
- T_rr != T_rb
- T_rr is not in Box[T_rb]
- Bivariant
Still Bivariant.
I think the fundamental issue is that when we recurse into value_type, we lose the connection between T_rr and T_rb.
Wait, actually, maybe I should look at this from a completely different angle. What if the issue is that value_type SHOULD be Box[T_rr] instead of Box[T_rb]?
When we compute RefRefBox.value_type():
- specialization = {T_rr -> T_rr}
- raw_value_type = RefBox[T_rr]
- apply_type_mapping_impl(RefBox[T_rr], {T_rr -> T_rr}):
- This substitutes T_rr -> T_rr in RefBox[T_rr]
- But RefBox[T_rr] doesn't contain T_rr directly; it's the TypeAlias(RefBox) that contains T_rr
- The substitution only affects type vars in RefBox[T_rr], not in the inner RefBox
Hmm, but RefBox[T_rr] IS the type RefBox specialized with T_rr. The TypeAlias(RefBox) carries the type alias definition, and the T_rr is the subscript argument.
Actually, I think the issue is that RefBox[T_rr] as a Type should be represented as a specialized type alias, not just as the name RefBox.
Let me check how this is represented. When RefBox[T_rr] is evaluated:
RefBox resolves to the type alias type (PEP695TypeAliasType for RefBox)
- The subscript
[T_rr] applies it to T_rr
- The result should be: a specialized type alias
But maybe the result is just the unspecialized type alias, and the specialization is stored separately.
Actually, I think the issue might be in how PEP 695 type aliases are represented when they're used as type expressions.
Let me look at how the builder resolves RefBox[T_rr]:
When we have type RefRefBox[T] = RefBox[T]:
- The builder evaluates the RHS
RefBox is a name expression
T is the subscript
- The result should be... a specialized type alias?
I think when RefBox is looked up in the context of RefRefBox, it should be a PEP695TypeAliasType. And when it's subscripted with T, the result should be a specialized version.
But maybe the result is just the PEP695TypeAliasType itself, without the subscript. The subscript might be stored in the subscript expression type, not in the type alias type.
Let me check.
Actually, I think the issue might be simpler than I thought. Let me look at the subscript expression handling.
When we have RefBox[T] in a type expression:
RefBox resolves to the type alias
[T] creates a generic alias
For PEP 695 type aliases, RefBox[T] should produce:
- TypeAlias(RefBox) with specialization {T_refbox -> T}
But maybe the implementation produces:
- Just TypeAlias(RefBox) (without specialization)
If that's the case, the fix should be in the subscript expression handling.
OK, I need to stop theorizing and implement a fix. Let me just add handling for TypeAlias in the variance_of implementation and see what happens.
The simplest fix:
Type::TypeAlias(alias) => {
if let Some(generic_context) = alias.generic_context(db) {
// For PEP 695 type aliases, look at the generic context and raw_value_type
let raw_value_type = alias.raw_value_type(db);
// For each formal type var, compute its variance in the raw_value_type
let variances: Vec<_> = generic_context.variables(db)
.map(|formal| {
// The formal's variance in the raw_value_type
// This may recurse into nested type aliases
raw_value_type.variance_of(db, formal)
})
.collect();
variances.into_iter().collect()
} else {
TypeVarVariance::Bivariant
}
}
For type RefRefBox[T_rr] = RefBox[T_rr]:
- generic_context has formal T_rr
- raw_value_type = RefBox[T_rr]
- T_rr.variance_of(RefBox[T_rr]):
- RefBox has formal T_rb
- T_rr.variance_of(RefBox[T_rr]):
- TypeAlias(RefBox) with formal T_rb
- T_rr is not T_rb
- Recurse using the same logic
- generic_context has formal T_rb
- raw_value_type = Box[T_rb]
- T_rb.variance_of(Box[T_rb]):
- GenericAlias.variance_of:
- origin = Box
- For formal T with actual T_rb:
- T_rb.variance_of(T_rb) = Covariant
- Box.with_polarity(Covariant).variance_of(T) = Invariant
- Result: Invariant
- Result: Invariant
- Result: Invariant
- Result: Invariant
- Result: Invariant
Wait, this gives Invariant! Let me trace through more carefully.
Actually, hold on. The code I proposed is:
Type::TypeAlias(alias) => {
if let Some(generic_context) = alias.generic_context(db) {
let raw_value_type = alias.raw_value_type(db);
let variances: Vec<_> = generic_context.variables(db)
.map(|formal| {
raw_value_type.variance_of(db, formal)
})
.collect();
variances.into_iter().collect()
} else {
TypeVarVariance::Bivariant
}
}
For type RefRefBox[T_rr] = RefBox[T_rr], variance_of(T_rr):
- We hit the Type::TypeAlias case
- RefRefBox has generic context [T_rr]
- raw_value_type = RefBox[T_rr]
- For formal T_rr:
- raw_value_type.variance_of(T_rr) = RefBox[T_rr].variance_of(T_rr)
- RefBox[T_rr] is TypeAlias(RefBox)
- We recurse into the Type::TypeAlias case
- RefBox has generic context [T_rb]
- raw_value_type = Box[T_rb]
- For formal T_rb:
- raw_value_type.variance_of(T_rb) = Box[T_rb].variance_of(T_rb)
- Box[T_rb] is GenericAlias
- GenericAlias.variance_of:
- origin = Box
- For formal T with actual T_rb:
- T_rb.variance_of(T_rb) = Covariant
- Box.with_polarity(Covariant).variance_of(T) = Invariant
- Result: Invariant
- Result: Invariant
- Result: Invariant
- The overall result for RefRefBox is: Invariant (from step 7)
This gives Invariant, which is correct!
Let me verify with another example: type Option[T] = Optional[T] (where Optional is covariant).
For type Option[T_rr] = Optional[T_rr], variance_of(T_rr):
- TypeAlias(Option) with generic context [T_rr]
- raw_value_type = Optional[T_rr]
- For formal T_rr:
- Optional[T_rr].variance_of(T_rr)
- Optional is a type alias or class with covariant T
- If Optional is a class:
- GenericAlias.variance_of:
- origin = Optional
- For formal T with actual T_rr:
- T_rr.variance_of(T_rr) = Covariant
- Optional.with_polarity(Covariant).variance_of(T) = Covariant (if Optional is covariant in T)
- Result: Covariant
- Result: Covariant
- Overall: Covariant ✓
Another example: type MyInt[T] = int (constant alias).
For type MyInt[T_rr] = int, variance_of(T_rr):
- TypeAlias(MyInt) with generic context [T_rr]
- raw_value_type = int
- For formal T_rr:
- int.variance_of(T_rr) = Bivariant (int doesn't contain T_rr)
- Overall: Bivariant ✓
Another example: type ListWrapper[T] = list[T] (invariant).
For type ListWrapper[T_rr] = list[T_rr]:
- TypeAlias(ListWrapper) with generic context [T_rr]
- raw_value_type = list[T_rr]
- For formal T_rr:
- list[T_rr].variance_of(T_rr)
- list is a class with invariant T
- GenericAlias.variance_of:
- origin = list
- For formal T with actual T_rr:
- T_rr.variance_of(T_rr) = Covariant
- list.with_polarity(Covariant).variance_of(T) = Invariant
- Result: Invariant
- Result: Invariant
- Overall: Invariant ✓
And the nested case:
For type RefBox[T_rb] = Box[T_rb]:
- TypeAlias(RefBox) with generic context [T_rb]
- raw_value_type = Box[T_rb]
- For formal T_rb:
- Box[T_rb].variance_of(T_rb) = Invariant
- Overall: Invariant ✓
For type RefRefBox[T_rr] = RefBox[T_rr]:
- TypeAlias(RefRefBox) with generic context [T_rr]
- raw_value_type = RefBox[T_rr]
- For formal T_rr:
- RefBox[T_rr].variance_of(T_rr)
- TypeAlias(RefBox) with generic context [T_rb]
- raw_value_type = Box[T_rb]
- For formal T_rb:
- Box[T_rb].variance_of(T_rb) = Invariant
- Overall for RefBox: Invariant
- Overall for RefRefBox: Invariant ✓
This approach works! The key insight is that for a type alias, the variance of its formal type var is determined by the formal's variance in the raw_value_type.
Now, let me also handle the case where the target typevar is NOT one of the formal type vars. In this case, the target might still be in the value type through the actual types of the formals.
For example: type MyAlias[T] = SomeClass[T, int]:
- Formal T
- raw_value_type = SomeClass[T, int]
- variance_of(T):
- T.variance_of(SomeClass[T, int])
- SomeClass might be invariant in its first param
- Result: Invariant
This works with our approach.
But what about: type MyAlias[T] = SomeClass[int, int] (constant in T):
- Formal T
- raw_value_type = SomeClass[int, int]
- variance_of(T):
- T.variance_of(SomeClass[int, int])
- SomeClass[int, int] doesn't contain T
- But wait, we're computing T.variance_of(SomeClass[int, int])
- T is a type var, SomeClass[int, int] doesn't contain T
- T.variance_of(SomeClass[int, int]) = Bivariant
This is correct! T is not in the type, so it's bivariant.
But what about type MyAlias[T] = T | int?
- Formal T
- raw_value_type = Union[T, int]
- variance_of(T):
- T.variance_of(Union[T, int])
- Union.variance_of:
- T.variance_of(T) = Covariant
- T.variance_of(int) = Bivariant
- .collect() = Covariant (join of Covariant and Bivariant)
- Result: Covariant ✓
Great, this approach handles unions correctly too.
One more edge case: mutually recursive type aliases.
type A[T] = B[T]
type B[T] = A[T]
For type A[T] = B[T]:
- TypeAlias(A) with formal T
- raw_value_type = B[T]
- T.variance_of(B[T]):
- TypeAlias(B) with formal T (a different instance)
- raw_value_type = A[T]
- T.variance_of(A[T]):
- TypeAlias(A) with formal T (yet another instance)
- ...infinite recursion!
We need to handle cycles. The GenericAlias.variance_of already handles cycles via the salsa #[salsa::tracked(cycle_initial=|_, _, _, _| TypeVarVariance::Bivariant, ...)] attribute.
But for our new TypeAlias handling, we don't have that. We need to make sure the recursion terminates.
Actually, since variance_of is called on different TypeAlias instances (A vs B vs A again), and each one computes variance_of(formal) on raw_value_type, we might get infinite recursion.
But wait, the GenericAlias.variance_of IS a tracked Salsa query, so cycles are handled. But my proposed approach calls raw_value_type.variance_of(formal), which goes through the Type::variance_of implementation. For a TypeAlias, it would call my new code, which again calls raw_value_type.variance_of(formal) on the inner alias, etc.
This could lead to infinite recursion between A and B.
To handle this, I need to use a tracked Salsa query, just like GenericAlias.variance_of does.
Actually, I think I can use the same approach as GenericAlias.variance_of: make it a #[salsa::tracked] function with cycle handling.
But Type::variance_of is NOT a tracked function. It's a regular method. So I can't add cycle handling directly.
Hmm, but GenericAlias.variance_of IS a tracked function:
#[salsa::tracked(
cycle_initial=|_, _, _, _| TypeVarVariance::Bivariant,
heap_size=ruff_memory_usage::heap_size
)]
fn variance_of(self, db: &'db dyn Db, typevar: BoundTypeVarInstance<'db>) -> TypeVarVariance {
So GenericAlias.variance_of is a tracked query. And when it calls variance_of on types, those calls go through the VarianceInferable trait, which calls Type::variance_of (not tracked), which then calls GenericAlias.variance_of (tracked).
So the cycle is: GenericAlias.variance_of -> Type.variance_of -> TypeAlias handling -> Type.variance_of -> GenericAlias.variance_of (for the inner GenericAlias)
The tracked query handles the cycle. If the same query is called again during the computation, the cycle handler returns a default value.
For my proposed approach, the cycle would be:
Type.variance_of -> TypeAlias handling -> TypeAlias.variance_of (not tracked!) -> Type.variance_of -> ...
If I make the TypeAlias handling also a tracked query, the cycle would be handled.
But I can't easily add a new tracked query. I'd need to refactor.
Actually, wait. Let me re-read the GenericAlias.variance_of code:
#[salsa::tracked(
cycle_initial=|_, _, _, _| TypeVarVariance::Bivariant,
heap_size=ruff_memory_usage::heap_size
)]
fn variance_of(self, db: &'db dyn Db, typevar: BoundTypeVarInstance<'db>) -> TypeVarVariance {
The tracked query is GenericAlias::variance_of. When it recurses into ty.variance_of(db, typevar), that goes through Type::variance_of. If ty is a GenericAlias, it calls GenericAlias::variance_of again. If it's a TypeAlias, my new code would handle it.
If my new code just calls raw_value_type.variance_of(db, formal), and the raw_value_type is another TypeAlias, it would call my new code again. Without cycle handling, this could loop infinitely.
But actually, the Salsa cache might prevent infinite recursion. When raw_value_type.variance_of(db, formal) is called, it goes through the Type::variance_of method. For a TypeAlias, it calls my new code, which computes variance_by_looking_at_raw_value_type. If this computation involves calling GenericAlias.variance_of (which IS tracked), the cycle would be handled.
But if it involves calling another TypeAlias's variance computation, it's not tracked, so no cycle handling.
Hmm, I think I need to make the TypeAlias variance computation also a tracked query.
Alternatively, I can just check for self-referential cycles manually. If the raw_value_type contains a TypeAlias with the same definition as the current one, return Bivariant (the cycle fallback).
But detecting this is complex.
Actually, let me just implement the simple version first and see if tests pass. If there are cycle issues, I'll add cycle handling.
Wait, actually, I realize that the recursion for type aliases would be:
- RefRefBox.variance_of(T_rr) -> RefRefBox.raw_value_type.variance_of(T_rr)
- RefBox[T_rr].variance_of(T_rr) -> RefBox.raw_value_type.variance_of(T_rr)
- Box[T_rb].variance_of(T_rr) -> GenericAlias.variance_of
Wait, that's not right. Let me re-examine.
For RefRefBox.variance_of(T_rr):
- Type::TypeAlias(RefRefBox)
- For formal T_rr:
- raw_value_type = RefBox[T_rr]
- raw_value_type.variance_of(T_rr) = RefBox[T_rr].variance_of(T_rr)
RefBox[T_rr] is a TypeAlias, so:
3. Type::TypeAlias(RefBox)
4. For formal T_rb:
- raw_value_type = Box[T_rb]
- raw_value_type.variance_of(T_rb) = Box[T_rb].variance_of(T_rb)
Box[T_rb] is a GenericAlias, so:
5. GenericAlias.variance_of(T_rb):
- origin = Box
- For formal T with actual T_rb:
- T_rb.variance_of(T_rb) = Covariant
- Box.with_polarity(Covariant).variance_of(T) = Invariant
- Result: Invariant
- Result: Invariant
So the recursion goes through GenericAlias.variance_of, which is tracked. The cycle is handled.
What about mutual recursion?
type A[T] = B[T]
type B[T] = A[T]
For A.variance_of(T_A):
- TypeAlias(A) with formal T_A
- For formal T_A:
- raw_value_type = B[T_A]
- raw_value_type.variance_of(T_A) = B[T_A].variance_of(T_A)
- TypeAlias(B) with formal T_B
- For formal T_B:
- raw_value_type = A[T_B]
- raw_value_type.variance_of(T_B) = A[T_B].variance_of(T_B)
- TypeAlias(A) with formal T_A
- For formal T_A:
- raw_value_type = B[T_A]
- raw_value_type.variance_of(T_A) = B[T_A].variance_of(T_A)
- This is the same as step 2!
So we have: 2 -> 3 -> 4 -> 5 -> 6 -> 2 -> ...
This is infinite recursion without cycle handling.
But wait, is this actually infinite? The salsa cache might prevent it.
When we compute A.variance_of(T_A):
- This calls TypeAlias.variance_of logic
- raw_value_type.variance_of(T_A) calls... what?
raw_value_type is RefBox[T_rr], which is a TypeAlias. When we call raw_value_type.variance_of(T_rr), this goes through the Type::variance_of match. It matches Type::TypeAlias, and we call our new code.
Our new code calls generic_context.variables(db).map(|formal| raw_value_type.variance_of(db, formal)).collect().
For formal T_rr: raw_value_type.variance_of(db, T_rr).
Wait, raw_value_type IS RefBox[T_rr], which is the same type. So we'd be calling RefBox[T_rr].variance_of(T_rr), which goes through the same logic.
Hmm, actually no. The raw_value_type of RefRefBox is RefBox[T_rr], which is a DIFFERENT TypeAliasType than RefRefBox itself. So when we recurse into RefBox, it's a different query.
But for mutual recursion (A -> B -> A), it IS the same query.
To handle this, I need to use a tracked query.
OK, let me look at how GenericAlias.variance_of is implemented. It's a #[salsa::tracked] function. I could create a similar tracked function for type alias variance.
But that would require a separate struct or modifying the existing code.
Alternatively, I can add the tracked attribute to Type::variance_of itself. But Type::variance_of is not a tracked function, and adding the tracked attribute might be complicated.
Actually, wait. Let me re-read the GenericAlias.variance_of signature:
#[salsa::tracked(
cycle_initial=|_, _, _, _| TypeVarVariance::Bivariant,
heap_size=ruff_memory_usage::heap_size
)]
fn variance_of(self, db: &'db dyn Db, typevar: BoundTypeVarInstance<'db>) -> TypeVarVariance {
This is a tracked function on the GenericAlias type. It takes self (the GenericAlias), db, and typevar.
For TypeAlias, I could create a similar tracked function. But TypeAlias is represented as a Type::TypeAlias variant, not a separate type.
Hmm, maybe I should create a tracked function for the type alias variance computation, similar to GenericAlias.variance_of.
Actually, I think the simpler approach is to make the variance_of call through TypeAlias also go through a tracked query.
Let me look at how the GenericAlias.variance_of is called. It's called from within Type::variance_of:
Type::GenericAlias(generic_alias) => generic_alias.variance_of(db, typevar),
And GenericAlias::variance_of is a tracked query. So the cycle is handled.
For TypeAlias, I could do the same: create a tracked function TypeAliasType::variance_of, and call it from Type::variance_of.
But TypeAliasType is already a salsa::interned struct. Adding a tracked function would require modifying it.
Alternatively, I can create a free function like fn type_alias_variance_of(db, alias, typevar) and mark it as tracked.
Let me check if there's already such a function.
Actually, wait. Let me reconsider. The issue of mutual recursion might not be a problem in practice. The salsa cache prevents re-evaluation of the same query. So if A.variance_of(T_A) is being computed, and it tries to compute A.variance_of(T_A) again, Salsa would detect the cycle and return the cycle_initial value.
But for my approach, the recursion is:
- Type::variance_of (not tracked) -> calls our TypeAlias handler
- Our handler calls raw_value_type.variance_of(formal) -> calls our TypeAlias handler again
- Since raw_value_type is a different TypeAlias (B), step 2 calls B.variance_of(T_B) -> our handler
- Our handler calls A[T_B].variance_of(T_B) -> our handler again
- Our handler calls raw_value_type.variance_of(formal) -> this is where we recurse into A again
At step 5, we're calling A.variance_of(T_A) again. But this is a different Salsa query than step 1 (different formal type var? Actually, T_A and T_B might be different instances).
Hmm, this is getting complicated. Let me just implement the simple version and see if it works. If there are cycle issues, I'll add cycle handling.
Actually, I just realized: for the mutual recursion case, the type vars T_A and T_B are DIFFERENT type vars. T_A is the formal of A, and T_B is the formal of B. So the queries A.variance_of(T_A) and A.variance_of(T_B) are DIFFERENT queries (even though they're the same type alias, the typevar parameter is different).
So the cycle in the computation would be:
- A.variance_of(T_A): formal T_A, raw_value_type = B[T_A]
- B[T_A].variance_of(T_A): formal T_B, raw_value_type = A[T_B]
- A[T_B].variance_of(T_B): formal T_A (A's formal), raw_value_type = B[T_A]
- B[T_A].variance_of(T_A): this is step 2!
So at step 4, we're calling the same query as step 2. But step 2 is not a tracked query (it goes through Type::variance_of which is not tracked). So we'd have infinite recursion.
Unless... the Type::variance_of calls GenericAlias.variance_of (tracked) for the GenericAlias case. But for the TypeAlias case, it calls our new code which is not tracked.
So we DO need to add cycle handling.
The simplest approach: make the TypeAlias variance computation a tracked query.
But how? I'd need to create a new tracked function.
Actually, let me look at this differently. The GenericAlias.variance_of is tracked and handles cycles. When a type alias's raw_value_type is a GenericAlias (like Box[T_rb]), the variance is computed through GenericAlias.variance_of, which is tracked.
For nested type aliases, the variance computation goes:
TypeAlias(A).variance_of(T_A) -> A.raw_value_type.variance_of(T_A) -> TypeAlias(B).variance_of(T_B) -> B.raw_value_type.variance_of(T_B) -> ...
Each step calls Type::variance_of, which matches the type variant and calls the appropriate handler. For TypeAlias, it calls our new code.
If we make the TypeAlias variance computation tracked, the cycle would be handled.
But creating a new tracked function is a significant change. Let me think about whether there's a simpler approach.
Actually, I think I can just use the raw_value_type.variance_of(formal) approach, which will eventually reach a GenericAlias (the class in the raw_value_type). The GenericAlias.variance_of IS tracked, so the cycle would be handled at that level.
Wait, but for mutual recursion, the recursion goes through TypeAlias handlers, not through GenericAlias. The GenericAlias is at the END of the chain (e.g., Box[T_rb]), not in the middle.
So for:
type A[T] = B[T]
type B[T] = A[T]
The chain is:
A -> B -> A -> B -> ... -> GenericAlias (but there's no GenericAlias here!)
A's raw_value_type = B[T_A]
B's raw_value_type = A[T_B]
There's no class in the chain, only type aliases. So the GenericAlias variance handler is never reached, and cycles are not handled.
For this case, we need explicit cycle handling.
OK let me just implement the approach with cycle handling. I'll create a tracked function for type alias variance.
Actually, looking at the code more carefully, I see that PEP695TypeAliasType.raw_value_type is already a tracked query with cycle handling:
#[salsa::tracked(
cycle_initial=|_, id, _| Type::divergent(id),
cycle_fn=|db, cycle, previous: &Type<'db>, value: Type<'db>, _| {
value.cycle_normalized(db, *previous, cycle)
},
heap_size=ruff_memory_usage::heap_size
)]
pub(super) fn raw_value_type(self, db: &'db dyn Db) -> Type<'db> {
So if the raw_value_type computation involves a cycle (mutually recursive type aliases), the cycle handler returns Type::divergent. And when we compute variance_of on Type::Divergent, it returns Bivariant (because Divergent falls through to the default case).
Wait, but the cycle is in the variance computation, not in the raw_value_type computation. The raw_value_type of A is B[T_A], and the raw_value_type of B is A[T_B]. Neither computation involves a cycle on its own. The cycle is in the variance computation.
So I still need to add cycle handling for the variance computation.
OK, I think the cleanest approach is:
- Add handling for Type::TypeAlias in Type::variance_of
- The handling iterates over the alias's generic context and computes the formal's variance in the raw_value_type
- For cycle handling, rely on the GenericAlias variance computation being tracked (since it's the final step in the chain)
But as I discussed, for mutual type alias recursion without a class, the cycle is not handled.
Let me check if mutual type alias recursion is even a common case. In the issue description, the problem is about type RefRefBox[T] = RefBox[T] where both are type aliases. This is a chain, not a cycle. The chain terminates at the class (Box), which is handled by GenericAlias.variance_of.
For mutual recursion (A -> B -> A), there's no class in the chain. This is a pathological case. I'll handle it by returning Bivariant when we detect a cycle.
Actually, I think the simplest approach is:
For Type::TypeAlias(alias):
- If alias has no generic context: Bivariant
- If alias has generic context:
- For each formal F:
- Compute F's variance in raw_value_type
- If the raw_value_type is the same alias (or leads back to it), return Bivariant
- .collect()
But detecting cycles manually is complex.
Alternatively, I can just use alias.value_type(db) instead of raw_value_type. The value_type applies the specialization, which might help with cycles.
Wait, but value_type uses raw_value_type internally, and raw_value_type has cycle handling.
Actually, let me re-read the value_type computation:
pub(crate) fn value_type(self, db: &'db dyn Db) -> Type<'db> {
self.apply_function_specialization(db, self.raw_value_type(db))
}
The raw_value_type has cycle handling. If the raw_value_type involves a cycle, it returns Type::divergent. Then value_type applies the specialization to the divergent type, which still returns divergent.
And variance_of on Type::Divergent returns Bivariant (fall through).
So for mutual recursion A -> B -> A:
- A.variance_of(T_A):
- raw_value_type of A is B[T_A]
- B[T_A].variance_of(T_A):
- raw_value_type of B is A[T_B]
- A[T_B].variance_of(T_B):
- raw_value_type of A is B[T_A]
- But wait, this is computing A.raw_value_type, not A.variance_of
- A.raw_value_type has cycle handling, so if it detects a cycle, it returns divergent
Hmm, but the cycle detection in raw_value_type is per-type-alias. A.raw_value_type and B.raw_value_type are different queries. A.raw_value_type returns B[T_A] (no cycle). B.raw_value_type returns A[T_B] (no cycle). There's no cycle in the raw_value_type computation itself.
The cycle is in the variance computation, which goes: A.variance -> B.variance -> A.variance -> ...
Since variance computation for type aliases is not a tracked query, the cycle is not detected.
OK, I think the fix requires making the type alias variance computation tracked. Let me create a new tracked function.
Actually, let me look at the code structure. GenericAlias has a tracked variance_of function:
#[salsa::tracked(
cycle_initial=|_, _, _, _| TypeVarVariance::Bivariant,
heap_size=ruff_memory_usage::heap_size
)]
fn variance_of(self, db: &'db dyn Db, typevar: BoundTypeVarInstance<'db>) -> TypeVarVariance {
I could create a similar tracked function for type aliases. But PEP695TypeAliasType is an interned struct, and adding a tracked function to it would require modifying it.
Alternatively, I can create a free function:
#[salsa::tracked(
cycle_initial=|_, _, _, _| TypeVarVariance::Bivariant,
heap_size=ruff_memory_usage::heap_size
)]
fn type_alias_variance_of<'db>(
db: &'db dyn Db,
alias: TypeAliasType<'db>,
typevar: BoundTypeVarInstance<'db>,
) -> TypeVarVariance {
And call it from Type::variance_of:
Type::TypeAlias(alias) => type_alias_variance_of(db, alias, typevar),
Let me implement this approach.
Hmm, but wait. Let me reconsider whether the simple approach (without explicit cycle handling) works for the common case.
For type RefRefBox[T_rr] = RefBox[T_rr]:
- RefRefBox.raw_value_type = RefBox[T_rr]
- RefBox[T_rr].variance_of(T_rr):
- RefBox.raw_value_type = Box[T_rb]
- Box[T_rb].variance_of(T_rb):
- GenericAlias.variance_of(T_rb) (tracked!)
- Result: Invariant
- Result: Invariant
- Result: Invariant
The GenericAlias variance computation is tracked, so the chain terminates at the GenericAlias. There's no cycle.
For mutual recursion A -> B -> A:
- A.raw_value_type = B[T_A]
- B[T_A].variance_of(T_A):
- B.raw_value_type = A[T_B]
- A[T_B].variance_of(T_B):
- A.raw_value_type = B[T_A] (same as step 1!)
- But this is the same Salsa query, so Salsa detects the cycle?
Wait, A.raw_value_type is a tracked query. If it's called while it's already being computed, Salsa detects the cycle and returns the cycle_initial value.
But the cycle is in the variance computation, not in the raw_value_type computation. The raw_value_type computation is:
- A.raw_value_type (tracked): computes B[T_A]
- B.raw_value_type (tracked): computes A[T_B]
- A.raw_value_type again? No, we're computing variance, not raw_value_type.
The variance computation is:
- A.variance(T_A): uses A.raw_value_type
- B[T_A].variance(T_A): uses B.raw_value_type
- A[T_B].variance(T_B): uses A.raw_value_type
At step 3, we're calling A.raw_value_type again. But A.raw_value_type was already computed in step 1. Salsa would return the cached result, not recompute.
But the issue is that step 3 involves computing B.variance(T_A) again, which involves B.raw_value_type (already computed in step 2), which involves A.variance(T_B) again, which involves A.raw_value_type (already computed in step 1).
The cycle is in the variance computation, not in the raw_value_type computation. Since variance computation for type aliases is not tracked, we don't get cycle detection.
Hmm, actually wait. Let me re-examine the cycle.
For A -> B -> A (mutual recursion):
type A[T_A] = B[T_A]
type B[T_B] = A[T_B]
When computing A.variance_of(T_A):
- A has formal T_A, raw_value_type = B[T_A]
- T_A.variance_of(B[T_A]):
- B is a TypeAlias with formal T_B
- T_A.variance_of(B[T_A]) via TypeAlias handler
- B has formal T_B, raw_value_type = A[T_B]
- T_B.variance_of(A[T_B]) via TypeAlias handler
- A has formal T_A, raw_value_type = B[T_A]
- T_A.variance_of(B[T_A]) via TypeAlias handler
- This is the same as step 2!
So at step 5, we're trying to do what we did in step 2. This is infinite recursion.
But Salsa might prevent this. The Type::variance_of call in step 2 is not a tracked query. But the GenericAlias.variance_of call (if reached) IS a tracked query. In this case, we never reach GenericAlias because A and B are both type aliases.
So we DO need cycle handling for type alias variance.
OK let me just implement the fix with a tracked function for type alias variance.
Actually wait, I just realized something. In step 5, we're calling Type::variance_of(B[T_A], T_A), which is the SAME call as in step 2. If Salsa caches this, it would prevent infinite recursion.
But Type::variance_of is NOT a tracked query. So Salsa doesn't cache it.
Hmm, but even without caching, we might not have infinite recursion because the actual function call is different (different self or typevar parameter?).
Wait, the call in step 2 is:
- self = RefBox[T_A] (TypeAlias), typevar = T_A
The call in step 5 is:
- self = RefBox[T_A] (TypeAlias), typevar = T_A
These are the SAME call! Same self, same typevar. So if we memoize the result, we'd detect the cycle.
But Type::variance_of is not memoized. So we'd recurse infinitely.
To handle this, I need to make the type alias variance computation memoized (tracked).
OK, let me implement this properly.
Let me create a tracked function for type alias variance. I'll add it to the variance.rs file or create a new module.
Actually, let me look at how to add a tracked function to an interned struct.
PEP695TypeAliasType is defined as:
#[salsa::interned(debug, heap_size=ruff_memory_usage::heap_size)]
pub struct PEP695TypeAliasType<'db> {
#[returns(ref)]
pub name: Name,
rhs_scope: ScopeId<'db>,
pub(super) specialization: Option<Specialization<'db>>,
}
I can add a tracked function to it by adding it to the #[salsa::tracked] impl block.
But for ManualPEP695TypeAliasType, it's also an interned struct. And for the TypeAliasType enum, I'd need to handle both cases.
Hmm, creating a tracked function for the enum would be tricky.
Alternatively, I can create a free function:
#[salsa::tracked(
cycle_initial=|_, _, _, _| TypeVarVariance::Bivariant,
heap_size=ruff_memory_usage::heap_size
)]
fn compute_type_alias_variance<'db>(
db: &'db dyn Db,
alias: TypeAliasType<'db>,
typevar: BoundTypeVarInstance<'db>,
) -> TypeVarVariance {
And use it in Type::variance_of:
Type::TypeAlias(alias) => compute_type_alias_variance(db, alias, typevar),
This should work! Let me implement this.
Now, for the implementation of compute_type_alias_variance:
fn compute_type_alias_variance<'db>(
db: &'db dyn Db,
alias: TypeAliasType<'db>,
typevar: BoundTypeVarInstance<'db>,
) -> TypeVarVariance {
let raw_value_type = alias.raw_value_type(db);
match alias {
TypeAliasType::PEP695(type_alias) => {
if let Some(generic_context) = type_alias.generic_context(db) {
generic_context.variables(db)
.map(|formal| raw_value_type.variance_of(db, formal))
.collect()
} else {
TypeVarVariance::Bivariant
}
}
TypeAliasType::ManualPEP695(_) => {
// TODO: Handle manual type aliases
TypeVarVariance::Bivariant
}
}
}
Wait, but this only handles PEP 695 type aliases. For legacy type aliases (ManualPEP695), there's no generic context.
Actually, looking at the issue description, it says: "Variance inference for both PEP 695 and legacy generic type aliases must recurse through the alias value rather than treating every alias as bivariant."
So I also need to handle legacy type aliases. For legacy type aliases, the GenericContext is different. Let me check how legacy type aliases work.
Looking at the GenericContext::of_node implementation:
NodeWithScopeKind::TypeAlias(type_alias) => {
let definition = index.expect_single_definition(type_alias);
...
.as_type_alias()?
.as_pep_695_type_alias()?
It seems like legacy type aliases (non-PEP 695) are handled differently. Let me look at how they're represented.
For legacy type aliases:
from typing import TypeAlias
T = TypeAlias
ListInt = list[int] # Not a generic type alias
GenericList = list[T] # Generic type alias using TypeVar
The legacy type alias GenericList = list[T] doesn't have a PEP 695 generic context. Instead, the type vars are inferred from the usage.
For variance computation of legacy type aliases, we'd need to look at the raw_value_type and infer the variance of the type vars.
But this is more complex because legacy type aliases don't have explicit formal type vars.
Hmm, actually, let me re-read the issue. It says "Variance inference for both PEP 695 and legacy generic type aliases must recurse through the alias value". This suggests that both PEP 695 and legacy type aliases should have the same fix.
For PEP 695 type aliases, we have explicit formal type vars. For legacy type aliases, we need to infer the formal type vars.
But for legacy type aliases, the variance_of is called on the raw_value_type directly (which is a generic alias). So maybe the fix is the same: just look at the raw_value_type and compute the variance of the formal type vars.
Let me think about this more. For type GenericList[T] = list[T] (PEP 695):
- Formal T
- raw_value_type = list[T]
- T.variance_of(list[T]): GenericAlias.variance_of -> Invariant
For GenericList = list[T] (legacy):
- No formal T (it's inferred)
- The raw_value_type is list[T] where T is a type var
- variance_of(T) on the raw_value_type -> list[T].variance_of(T) -> Invariant
But for the legacy case, we're computing variance_of on the TypeAliasType directly, not on a GenericAlias. So we'd need to:
- Get the raw_value_type
- Compute the formal type vars (inferred from the type vars in the value)
- Compute each formal's variance in the raw_value_type
This is more complex. But maybe for now, I can just handle PEP 695 type aliases and leave legacy type aliases as Bivariant.
Actually, let me look at how legacy type aliases' raw_value_type is computed. The raw_value_type of a legacy type alias is the type of the RHS expression, which might be a generic alias.
For GenericList = list[T]:
- The raw_value_type is list[T] (a generic alias)
- The GenericAlias has origin = list, specialization = {T_list -> T}
So when we compute variance_of(T) on the legacy type alias, we'd need to:
- Get the raw_value_type = list[T]
- The raw_value_type is a GenericAlias
- GenericAlias.variance_of(T):
- origin = list
- specialization = {T_list -> T}
- For formal T_list with actual T:
- T.variance_of(T) = Covariant
- list.with_polarity(Covariant).variance_of(T_list)
- list.variance_of(T_list) = Invariant (list is invariant in its type var)
- Result: Invariant
So the fix for legacy type aliases is: look at the raw_value_type and compute variance_of on it.
For both PEP 695 and legacy type aliases, the fix is:
- Get the raw_value_type
- Compute variance_of(typevar) on the raw_value_type
But wait, for PEP 695 type aliases, I proposed computing the formal's variance in the raw_value_type:
for formal in generic_context.variables(db) {
raw_value_type.variance_of(db, formal)
}
This is different from just computing variance_of(typevar) on the raw_value_type.
For type RefRefBox[T_rr] = RefBox[T_rr]:
- formal T_rr
- raw_value_type.variance_of(T_rr):
- RefBox[T_rr].variance_of(T_rr):
- RefBox has formal T_rb
- T_rr.variance_of(RefBox[T_rr]):
- For formal T_rb:
- T_rb.variance_of(Box[T_rb]) = Invariant
- Result: Invariant
- Result: Invariant
- Result: Invariant
This gives Invariant.
If I instead just did raw_value_type.variance_of(T_rr):
- RefBox[T_rr].variance_of(T_rr):
- Same as above, gives Invariant
So for PEP 695 type aliases, both approaches give the same result.
For legacy type aliases, the raw_value_type is already a GenericAlias, so raw_value_type.variance_of(typevar) works correctly.
So the simpler approach works for both PEP 695 and legacy: just use raw_value_type.variance_of(typevar).
Let me verify with another example.
For type RefBox[T_rb] = Box[T_rb]:
- PEP 695 approach: for formal T_rb, compute T_rb.variance_of(Box[T_rb]) = Invariant
- Simple approach: raw_value_type.variance_of(T_rr) = Box[T_rb].variance_of(T_rr)
Wait, the simple approach computes variance_of(T_rr) on the raw_value_type. But T_rr is not necessarily the formal of the alias!
For type RefBox[T_rb] = Box[T_rb], if we're computing variance_of(X):
- If X == T_rb: the PEP 695 approach gives T_rb.variance_of(Box[T_rb]) = Invariant
- The simple approach gives Box[T_rb].variance_of(X):
- If X == T_rb: Box[T_rb].variance_of(T_rb) = Invariant ✓
- If X != T_rb: Box[T_rb].variance_of(X) = Bivariant ✓
For type RefRefBox[T_rr] = RefBox[T_rr]:
-
PEP 695 approach: for formal T_rr, compute T_rr.variance_of(RefBox[T_rr]):
- RefBox[T_rr].variance_of(T_rr):
- RefBox has formal T_rb
- T_rb.variance_of(Box[T_rb]) = Invariant
- Result: Invariant ✓
-
Simple approach: RefBox[T_rr].variance_of(T_rr):
- Same as above, gives Invariant ✓
So the simple approach works for both PEP 695 and legacy type aliases.
Let me also verify with a case where the target typevar is NOT a formal:
For type MyAlias[T] = SomeClass[T, int] and we compute variance_of(X):
- Simple approach: raw_value_type.variance_of(X) = SomeClass[T, int].variance_of(X)
- If X == T: variance_of(T) = T.variance_of(SomeClass[T, int]) = Invariant (via GenericAlias)
- If X != T and X not in SomeClass: Bivariant ✓
OK, the simple approach works. Let me implement it.
For Type::TypeAlias(alias):
- Get raw_value_type
- Compute raw_value_type.variance_of(typevar)
This handles both PEP 695 and legacy type aliases. For PEP 695 type aliases with formal type vars, the recursion goes through the raw_value_type, which might be another type alias or a class. For legacy type aliases, the raw_value_type is a GenericAlias.
Let me implement this now.
But wait, I need to handle cycles. For mutual recursion A -> B -> A, the recursion is:
- A.raw_value_type.variance_of(T_A)
- B.raw_value_type.variance_of(T_A):
- B.raw_value_type = A[T_B]
- A[T_B].variance_of(T_A):
- A.raw_value_type.variance_of(T_A) (same as step 1!)
So we have infinite recursion without cycle handling.
I need to make this a tracked query. Let me create a tracked function.
Actually, you know what, let me try the simple approach first and see if it causes infinite recursion in tests. If it does, I'll add cycle handling.
Let me implement the fix now.
I'll modify the Type::variance_of implementation in types.rs to handle Type::TypeAlias:
Type::TypeAlias(alias) => alias.raw_value_type(db).variance_of(db, typevar),
This is a one-line change! But it needs to be in the match arm, and it handles both PEP 695 and legacy type aliases.
Wait, but I also need to handle cycles. Let me add the cycle handling by making it a tracked function.
Actually, let me just try the simple approach first and see if it works. If tests pass, great. If not, I'll add cycle handling.
But wait, there's another issue. The raw_value_type for PEP 695 type aliases might be a generic alias (like Box[T_rb]). When we compute raw_value_type.variance_of(typevar) on this:
For type RefBox[T_rb] = Box[T_rb] with typevar = T_rr:
- raw_value_type = Box[T_rb]
- Box[T_rb].variance_of(T_rr):
- GenericAlias.variance_of(T_rr):
- origin = Box
- For formal T with actual T_rb:
- T_rb.variance_of(T_rr) = Bivariant (T_rr != T_rb)
- Box.with_polarity(Bivariant).variance_of(T) = Bivariant
- Result: Bivariant
So for type RefBox[T_rb] = Box[T_rb] with typevar T_rr (not T_rb), the simple approach gives Bivariant. But that's correct! T_rr is not T_rb, so T_rr doesn't appear in RefBox.
For type RefRefBox[T_rr] = RefBox[T_rr] with typevar T_rr:
- raw_value_type = RefBox[T_rr]
- RefBox[T_rr].variance_of(T_rr):
- TypeAlias(RefBox).variance_of(T_rr):
- This calls our new code
- RefBox.raw_value_type = Box[T_rb]
- Box[T_rb].variance_of(T_rr):
- GenericAlias.variance_of(T_rr):
- For formal T with actual T_rb:
- T_rb.variance_of(T_rr) = Bivariant
- Box.with_polarity(Bivariant).variance_of(T) = Bivariant
- Result: Bivariant
- Result: Bivariant
- Result: Bivariant
This gives Bivariant, which is WRONG! We want Invariant.
So the simple approach doesn't work for nested type aliases.
OK so the PEP 695 approach is correct. Let me go back to that.
For type RefRefBox[T_rr] = RefBox[T_rr]:
- For formal T_rr:
- raw_value_type.variance_of(T_rr):
- RefBox[T_rr].variance_of(T_rr):
- RefBox has formal T_rb
- For formal T_rb:
- T_rb.variance_of(Box[T_rb]) = Invariant
- Result: Invariant
- Result: Invariant
- Overall: Invariant ✓
So the PEP 695 approach is:
match alias {
TypeAliasType::PEP695(type_alias) => {
if let Some(generic_context) = type_alias.generic_context(db) {
generic_context.variables(db)
.map(|formal| alias.raw_value_type(db).variance_of(db, formal))
.collect()
} else {
TypeVarVariance::Bivariant
}
}
TypeAliasType::ManualPEP695(_) => {
alias.raw_value_type(db).variance_of(db, typevar)
}
}
For PEP 695 type aliases, we iterate over formals and compute each formal's variance in the raw_value_type.
For legacy type aliases, we directly compute the typevar's variance in the raw_value_type.
But wait, for the PEP 695 case, we're not using the typevar parameter. We're just iterating over formals and computing their variance. This means we're computing the "overall" variance of the alias, not the variance of a specific typevar.
Actually, for a type alias with formals, the variance of the alias IS the variance of its formals. When we ask "what is the variance of X in this type alias?", if X is one of the formals, we return X's variance. If X is not a formal, the typevar doesn't appear, so we return Bivariant.
But the code above computes all formals' variances and joins them. This gives the "overall" variance, which is the variance if X happens to be one of the formals.
Hmm, but that's not correct. The variance of the type alias depends on WHICH typevar we're asking about.
Let me re-think.
For type RefRefBox[T_rr] = RefBox[T_rr]:
- If we ask for variance_of(T_rr): T_rr is a formal, so return T_rr's variance = Invariant
- If we ask for variance_of(int): int is not a formal, so return Bivariant
For the GenericAlias Box[T]:
- If we ask for variance_of(T): T is a formal, return T's variance = Invariant
- If we ask for variance_of(int): int is not a formal, so the GenericAlias's specialization has T -> T. Then:
- T.variance_of(int) = Bivariant
- Box.with_polarity(Bivariant).variance_of(T) = Bivariant
- Result: Bivariant
So for GenericAlias, the algorithm handles both cases (X is a formal or not).
For type aliases, I need the same behavior. Let me look at GenericAlias.variance_of again:
.map(|(generic_typevar, ty)| {
if let Some(explicit_variance) = generic_typevar.typevar(db).explicit_variance(db) {
ty.with_polarity(explicit_variance).variance_of(db, typevar)
} else {
let typevar_variance_in_substituted_type = ty.variance_of(db, typevar);
origin
.with_polarity(typevar_variance_in_substituted_type)
.variance_of(db, generic_typevar)
}
})
.collect()
For each formal F with actual ty:
- explicit_variance = F's explicit variance
- If explicit_variance:
- ty.with_polarity(explicit_variance).variance_of(typevar)
- Else:
- var_in_ty = ty.variance_of(typevar)
- origin.with_polarity(var_in_ty).variance_of(F)
- .collect() joins all results
For Box[T] with typevar = int:
- F = T, ty = T
- explicit_variance = None
- var_in_ty = T.variance_of(int) = Bivariant
- origin.with_polarity(Bivariant).variance_of(T) = Bivariant
- Result: Bivariant
For Box[T] with typevar = T:
- F = T, ty = T
- explicit_variance = None
- var_in_ty = T.variance_of(T) = Covariant
- origin.with_polarity(Covariant).variance_of(T) = Invariant
- Result: Invariant
For type aliases, the equivalent would be:
For each formal F with actual ty:
- explicit_variance = F's explicit variance
- If explicit_variance:
- ty.with_polarity(explicit_variance).variance_of(typevar)
- Else:
- raw_value_type.variance_of(F) // F's variance in the raw_value_type
- Compose with var_in_ty = ty.variance_of(typevar)
But composing is tricky. For GenericAlias:
- origin.with_polarity(var_in_ty).variance_of(F)
- This is: origin's variance_of(F), with polarity flipped by var_in_ty
For type aliases:
- raw_value_type.variance_of(F) is F's variance in the raw_value_type
- But we need to compose with var_in_ty
Actually, the GenericAlias formula is:
- origin.with_polarity(var_in_ty).variance_of(F) = origin.variance_of(F) with variance flipped by var_in_ty
If var_in_ty is Covariant: flip has no effect, so result is origin.variance_of(F)
If var_in_ty is Contravariant: flip, so result is origin.variance_of(F) flipped
If var_in_ty is Invariant: result is Invariant
If var_in_ty is Bivariant: result is Bivariant
This is exactly what with_polarity does:
fn variance_of(self, db: &'db dyn Db, typevar: BoundTypeVarInstance<'db>) -> TypeVarVariance {
let WithPolarity {
variance_inferable,
polarity,
} = self;
polarity.compose_thunk(|| variance_inferable.variance_of(db, typevar))
}
So for type aliases:
- raw_value_type.with_polarity(var_in_ty).variance_of(F)
- = raw_value_type.variance_of(F) composed with var_in_ty
But wait, raw_value_type.variance_of(F) is already the variance of F in the raw_value_type. We don't need to compose it with var_in_ty again.
Actually, let me think about this more carefully.
For GenericAlias:
- origin.with_polarity(var_in_ty).variance_of(F)
- This computes: origin.variance_of(F), with the result composed with var_in_ty
The composition is: variance_of(F) with origin, flipped by var_in_ty.
For type aliases:
- raw_value_type.with_polarity(var_in_ty).variance_of(F)
- This computes: raw_value_type.variance_of(F), with the result composed with var_in_ty
But raw_value_type.variance_of(F) is the variance of F in the raw_value_type. This is already determined by the structure of the raw_value_type.
If raw_value_type = Box[T_rb] and F = T_rb:
- raw_value_type.variance_of(F) = Box[T_rb].variance_of(T_rb) = Invariant
- var_in_ty = ty.variance_of(typevar)
- If typevar == ty: Covariant
- Else: Bivariant
- Compose: Invariant composed with Covariant = Invariant
- Or: Invariant composed with Bivariant = Bivariant
Hmm, that doesn't seem right. If typevar is T and the formal's actual is T, then var_in_ty = Covariant, and Invariant composed with Covariant = Invariant. That's correct.
If typevar is int and the formal's actual is T, then var_in_ty = Bivariant, and Invariant composed with Bivariant = Bivariant. That's correct (int doesn't appear in the type alias).
OK so the formula is:
for (formal F, actual ty) in formal_actual_pairs:
if F has explicit variance:
ty.with_polarity(F's explicit variance).variance_of(typevar)
else:
raw_value_type.with_polarity(ty.variance_of(typevar)).variance_of(F)
Wait, but for type RefRefBox[T_rr] = RefBox[T_rr]:
- F = T_rr, ty = T_rr
- ty.variance_of(T_rr) = T_rr.variance_of(T_rr) = Covariant
- raw_value_type = RefBox[T_rr]
- RefBox[T_rr].with_polarity(Covariant).variance_of(T_rr):
- RefBox[T_rr].variance_of(T_rr) composed with Covariant
- RefBox[T_rr].variance_of(T_rr):
- RefBox has formal T_rb, ty2 = T_rb
- T_rb.variance_of(T_rr) = Bivariant
- RefBox's raw_value_type = Box[T_rb]
- Box[T_rb].with_polarity(Bivariant).variance_of(T_rb):
- Box[T_rb].variance_of(T_rb) = Invariant
- Compose: Bivariant composed with Invariant = Bivariant
- Result: Bivariant
- Compose: Bivariant composed with Covariant = Bivariant
- Result: Bivariant
Still Bivariant! The issue is at T_rb.variance_of(T_rr) = Bivariant.
Hmm wait, but RefBox[T_rr].variance_of(T_rr) should give Invariant (as I computed before). Let me re-trace.
For RefBox[T_rr].variance_of(T_rr):
- RefBox is a TypeAlias
- For formal T_rb with ty2 = T_rb (identity):
- ty2.variance_of(T_rr) = T_rb.variance_of(T_rr) = Bivariant (T_rr != T_rb)
- raw_value_type = Box[T_rb]
- Box[T_rb].with_polarity(Bivariant).variance_of(T_rb):
- Box[T_rb].variance_of(T_rb) = Invariant (via GenericAlias)
- Compose: Bivariant composed with Invariant = Bivariant
- Result: Bivariant
So RefBox[T_rr].variance_of(T_rr) = Bivariant, not Invariant!
But earlier I computed it as Invariant. Let me re-check.
For type RefRefBox[T_rr] = RefBox[T_rr], computing variance_of(T_rr):
- The approach is: for formal T_rr, compute T_rr.variance_of(raw_value_type)
- raw_value_type = RefBox[T_rr]
- T_rr.variance_of(RefBox[T_rr])
But T_rr.variance_of(RefBox[T_rr]) calls RefBox[T_rr].variance_of(T_rr), which goes through the TypeAlias handler.
For the TypeAlias handler:
- RefBox has formal T_rb
- For formal T_rb with actual T_rb:
- T_rb.variance_of(T_rr) = Bivariant (T_rr != T_rb)
- raw_value_type = Box[T_rb]
- Box[T_rb].with_polarity(Bivariant).variance_of(T_rb) = Bivariant
- Result: Bivariant
So the approach gives Bivariant, not Invariant.
But I computed it as Invariant before. Let me re-check my earlier trace.
Earlier, I said:
- RefBox has formal T_rb
- T_rb's variance in raw_value_type:
- Box[T_rb].variance_of(T_rb) = Invariant (via GenericAlias)
- So T_rr's variance in RefBox = Invariant
But this assumes that T_rr replaces T_rb in RefBox, and therefore T_rr's variance is the same as T_rb's variance. But the TypeAlias handler doesn't know that T_rr replaces T_rb! It just sees T_rr as a different typevar from T_rb.
So the issue is: the TypeAlias handler doesn't propagate the "T_rr replaces T_rb" information through the recursion.
OK so neither the simple approach nor the PEP 695 approach works for nested type aliases.
Let me think about this problem from scratch.
The issue is:
type RefRefBox[T_rr] = RefBox[T_rr] has RefBox[T_rr] as its raw_value_type
- RefBox[T_rr] is a TypeAlias with its own formal T_rb
- T_rr is NOT T_rb, so the TypeAlias handler for RefBox doesn't recognize T_rr as a formal
- Therefore, T_rr's variance in RefBox is computed as Bivariant
But the correct answer is: T_rr IS in RefBox (as a substitution for T_rb), so T_rr's variance should be the same as T_rb's variance in RefBox.
The fix needs to:
- Recognize that T_rr replaces T_rb in RefBox
- Compute T_rb's variance in RefBox and use that as T_rr's variance
But how do we know that T_rr replaces T_rb? The only way is through the specialization that was applied to RefBox when it was subscripted with T_rr.
In the raw_value_type of RefRefBox, the type RefBox[T_rr] means "RefBox specialized with T_rb -> T_rr". But this specialization is not stored in the TypeAlias! The TypeAlias is just RefBox.
So the fix should be at the level of how the raw_value_type is constructed. When RefBox[T_rr] is evaluated, it should produce a specialized type alias with T_rb -> T_rr.
Let me check if that's the case.
Actually, I think the raw_value_type IS just TypeAlias(RefBox), without the specialization. The specialization is stored in the PEP695TypeAliasType.specialization field, but this is for the alias itself, not for subscripts applied to it.
Hmm, wait. Let me look at this more carefully.
When we have type RefRefBox[T_rr] = RefBox[T_rr]:
- The raw_value_type is computed by evaluating the RHS
- The RHS is
RefBox[T_rr]
RefBox is a name that resolves to the TypeAliasType for RefBox
[T_rr] is the subscript
When evaluated, what type does RefBox[T_rr] produce?
I think it depends on how subscript expressions with type aliases are handled. Let me check the code.
Actually, you know what, let me just look at what raw_value_type actually contains for RefRefBox. I can add some debug logging or look at the code.
Let me look at how the type expression RefBox[T_rr] is evaluated in the context of a PEP 695 type alias.
<tool_call>
<function=bash_terminal>
<parameter=command>
grep -rn "type_alias|TypeAlias|PEP695" /ruff/crates/ty_python_semantic/src/types/infer/*.rs | grep -i "eval|resolve|infer|raw_value|value_type" | head -30
</tool_call>