Skip to content

Commit aaa682c

Browse files
committed
Implement try{} block type inference
1 parent ef303f2 commit aaa682c

File tree

2 files changed

+27
-18
lines changed

2 files changed

+27
-18
lines changed

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

+13-4
Original file line numberDiff line numberDiff line change
@@ -152,11 +152,20 @@ impl<'a> InferenceContext<'a> {
152152
.1
153153
}
154154
Expr::TryBlock { body } => {
155-
self.with_breakable_ctx(BreakableKind::Block, self.err_ty(), None, |this| {
156-
let _inner = this.infer_expr(*body, expected);
155+
// The type that is returned from the try block
156+
let try_ty = self.table.new_type_var();
157+
if let Some(ty) = expected.only_has_type(&mut self.table) {
158+
self.unify(&try_ty, &ty);
159+
}
160+
161+
// The ok-ish type that is expected from the last expression
162+
let ok_ty = self.resolve_associated_type(try_ty.clone(), self.resolve_ops_try_ok());
163+
164+
self.with_breakable_ctx(BreakableKind::Block, ok_ty.clone(), None, |this| {
165+
this.infer_expr(*body, &Expectation::has_type(ok_ty));
157166
});
158-
// FIXME should be std::result::Result<{inner}, _>
159-
self.err_ty()
167+
168+
try_ty
160169
}
161170
Expr::Async { body } => {
162171
let ret_ty = self.table.new_type_var();

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

+14-14
Original file line numberDiff line numberDiff line change
@@ -2064,17 +2064,17 @@ fn fn_pointer_return() {
20642064
fn block_modifiers_smoke_test() {
20652065
check_infer(
20662066
r#"
2067-
//- minicore: future
2067+
//- minicore: future, try
20682068
async fn main() {
20692069
let x = unsafe { 92 };
20702070
let y = async { async { () }.await };
2071-
let z = try { () };
2071+
let z: core::ops::ControlFlow<(), _> = try { () };
20722072
let w = const { 92 };
20732073
let t = 'a: { 92 };
20742074
}
20752075
"#,
20762076
expect![[r#"
2077-
16..162 '{ ...2 }; }': ()
2077+
16..193 '{ ...2 }; }': ()
20782078
26..27 'x': i32
20792079
30..43 'unsafe { 92 }': i32
20802080
30..43 'unsafe { 92 }': i32
@@ -2086,17 +2086,17 @@ async fn main() {
20862086
65..77 'async { () }': impl Future<Output = ()>
20872087
65..83 'async ....await': ()
20882088
73..75 '()': ()
2089-
95..96 'z': {unknown}
2090-
99..109 'try { () }': ()
2091-
99..109 'try { () }': {unknown}
2092-
105..107 '()': ()
2093-
119..120 'w': i32
2094-
123..135 'const { 92 }': i32
2095-
123..135 'const { 92 }': i32
2096-
131..133 '92': i32
2097-
145..146 't': i32
2098-
149..159 ''a: { 92 }': i32
2099-
155..157 '92': i32
2089+
95..96 'z': ControlFlow<(), ()>
2090+
130..140 'try { () }': ()
2091+
130..140 'try { () }': ControlFlow<(), ()>
2092+
136..138 '()': ()
2093+
150..151 'w': i32
2094+
154..166 'const { 92 }': i32
2095+
154..166 'const { 92 }': i32
2096+
162..164 '92': i32
2097+
176..177 't': i32
2098+
180..190 ''a: { 92 }': i32
2099+
186..188 '92': i32
21002100
"#]],
21012101
)
21022102
}

0 commit comments

Comments
 (0)