Skip to content

Commit 07f6efc

Browse files
committed
Auto merge of rust-lang#13523 - lowr:fix/adjust-expectation-for-if, r=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.
2 parents 8142d1f + db8c752 commit 07f6efc

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

crates/hir-ty/src/infer/expr.rs

+1
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ impl<'a> InferenceContext<'a> {
8585
let ty = match &self.body[tgt_expr] {
8686
Expr::Missing => self.err_ty(),
8787
&Expr::If { condition, then_branch, else_branch } => {
88+
let expected = &expected.adjust_for_branches(&mut self.table);
8889
self.infer_expr(
8990
condition,
9091
&Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(Interner)),

crates/hir-ty/src/tests/coercion.rs

+33
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,23 @@ fn test() {
122122
)
123123
}
124124

125+
#[test]
126+
fn if_else_adjust_for_branches_discard_type_var() {
127+
check_no_mismatches(
128+
r#"
129+
fn test() {
130+
let f = || {
131+
if true {
132+
&""
133+
} else {
134+
""
135+
}
136+
};
137+
}
138+
"#,
139+
);
140+
}
141+
125142
#[test]
126143
fn match_first_coerce() {
127144
check_no_mismatches(
@@ -182,6 +199,22 @@ fn test() {
182199
);
183200
}
184201

202+
#[test]
203+
fn match_adjust_for_branches_discard_type_var() {
204+
check_no_mismatches(
205+
r#"
206+
fn test() {
207+
let f = || {
208+
match 0i32 {
209+
0i32 => &"",
210+
_ => "",
211+
}
212+
};
213+
}
214+
"#,
215+
);
216+
}
217+
185218
#[test]
186219
fn return_coerce_unknown() {
187220
check_types(

0 commit comments

Comments
 (0)