Fix constrained TypeVar inference in subtype checking (#2221)#2225
Fix constrained TypeVar inference in subtype checking (#2221)#2225jackulau wants to merge 6 commits intofacebook:mainfrom
Conversation
rchen152
left a comment
There was a problem hiding this comment.
Thanks for the PR! Unfortunately, I don't think this is the right fix. This PR seems to be flipping the direction of the is_subset_eq check we do on vars for constraints (i.e., we currently do is_subset_eq(t2, bound) and this PR changes it to is_subset_eq(c, t2) for each constraint c). That happens to be the right direction to do the check for a contravariant protocol like in #2221, but this PR isn't checking for variance; it's always flipping the check. I'm pretty sure that's the wrong thing do in most cases.
|
This pull request has been automatically marked as stale because it has not had recent activity for more than 2 weeks. If you are still working on this this pull request, please add a comment or push new commits to keep it active. Otherwise, please unassign yourself and allow someone else to take over. Thank you for your contributions! |
|
I'm going to close this PR since it's stale and has some merge conflicts, but please feel free to open another PR if you'd like to take another stab at the issue (or comment on the issue if you'd prefer to discuss ideas first) |
Summary
Fixes #2221
When inferring constrained TypeVars during subtype checking (
Var(TypeVar) <: ConcreteType), pyrefly was incorrectlysetting the TypeVar to the concrete type and then checking if it satisfies the constraint. This fails for constrained
TypeVars which must be inferred to exactly one of their constraint types per PEP 484.
The Bug
This valid code produced:
ERROR
Bufferis not assignable to upper boundbytes | strof type variableAnyStrRoot Cause
shutil.copyfileobj has signature (fsrc: SupportsRead[AnyStr], fdst: SupportsWrite[AnyStr]) where AnyStr = TypeVar("AnyStr",
str, bytes).
When checking BufferedWriter <: SupportsWrite[AnyStr]:
The Fix
For constrained TypeVars, find a constraint that satisfies the subtype relationship rather than directly assigning the
concrete type. This follows PEP 484 semantics: constrained TypeVars must be inferred to exactly one of their constraint
types.
Test Plan