Skip to content

Fix accidental type inference in array coercion #140283

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
4 changes: 3 additions & 1 deletion compiler/rustc_hir_typeck/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1760,7 +1760,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let coerce_to = expected
.to_option(self)
.and_then(|uty| match *self.try_structurally_resolve_type(expr.span, uty).kind() {
ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
// Avoid using a type variable as the coerce_to type, as it may resolve
// during the first coercion instead of being based on the common type.
ty::Array(ty, _) | ty::Slice(ty) if !ty.is_ty_var() => Some(ty),
_ => None,
})
.unwrap_or_else(|| self.next_ty_var(expr.span));
Expand Down
25 changes: 25 additions & 0 deletions tests/ui/coercion/coerce-many-with-ty-var.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
//@ run-pass
// Check that least upper bound coercions don't resolve type variable merely based on the first
// coercion. Check issue #136420.

fn foo() {}
fn bar() {}

fn infer<T>(_: T) {}

fn infer_array_element<T>(_: [T; 2]) {}

fn main() {
infer(if false {
foo
} else {
bar
});

infer(match false {
true => foo,
false => bar,
});

infer_array_element([foo, bar]);
}
Loading