Skip to content

Commit

Permalink
Auto merge of rust-lang#13523 - lowr:fix/adjust-expectation-for-if, r…
Browse files Browse the repository at this point in the history
…=lnicola

fix: disregard type variable expectation for if expressions

Fixes rust-lang#13522

As [the comment](https://github.com/rust-lang/rust-analyzer/blob/8142d1f606dc2e52b1d2b8992671e2bd73379f28/crates/hir-ty/src/infer.rs#L1087-L1090) on `Expectation::adjust_for_branches` explains:

> If the expected type is just a type variable, then don't use an expected type. Otherwise, we might write parts of the type when checking the 'then' block which are incompatible with the 'else' branch.

Note that we already use it in match expressions. I've added tests for them too nevertheless.
  • Loading branch information
bors committed Oct 31, 2022
2 parents 8142d1f + db8c752 commit 07f6efc
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
1 change: 1 addition & 0 deletions crates/hir-ty/src/infer/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ impl<'a> InferenceContext<'a> {
let ty = match &self.body[tgt_expr] {
Expr::Missing => self.err_ty(),
&Expr::If { condition, then_branch, else_branch } => {
let expected = &expected.adjust_for_branches(&mut self.table);
self.infer_expr(
condition,
&Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(Interner)),
Expand Down
33 changes: 33 additions & 0 deletions crates/hir-ty/src/tests/coercion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,23 @@ fn test() {
)
}

#[test]
fn if_else_adjust_for_branches_discard_type_var() {
check_no_mismatches(
r#"
fn test() {
let f = || {
if true {
&""
} else {
""
}
};
}
"#,
);
}

#[test]
fn match_first_coerce() {
check_no_mismatches(
Expand Down Expand Up @@ -182,6 +199,22 @@ fn test() {
);
}

#[test]
fn match_adjust_for_branches_discard_type_var() {
check_no_mismatches(
r#"
fn test() {
let f = || {
match 0i32 {
0i32 => &"",
_ => "",
}
};
}
"#,
);
}

#[test]
fn return_coerce_unknown() {
check_types(
Expand Down

0 comments on commit 07f6efc

Please sign in to comment.