Merge pull request #20039 from ShoyuVanilla/let-bind-ref-capt

fix: Closure capturing for let exprs
This commit is contained in:
Lukas Wirth 2025-06-19 04:47:50 +00:00 committed by GitHub
commit bb1efeb835
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 43 additions and 1 deletions

View File

@ -1230,11 +1230,15 @@ impl InferenceContext<'_> {
self.select_from_expr(*expr);
}
}
Expr::Let { pat: _, expr } => {
self.walk_expr(*expr);
let place = self.place_of_expr(*expr);
self.ref_expr(*expr, place);
}
Expr::UnaryOp { expr, op: _ }
| Expr::Array(Array::Repeat { initializer: expr, repeat: _ })
| Expr::Await { expr }
| Expr::Loop { body: expr, label: _ }
| Expr::Let { pat: _, expr }
| Expr::Box { expr }
| Expr::Cast { expr, type_ref: _ } => {
self.consume_expr(*expr);

View File

@ -444,3 +444,22 @@ fn main() {
expect!["99..165;49..54;120..121,133..134 ByRef(Mut { kind: Default }) a &'? mut A"],
);
}
#[test]
fn let_binding_is_a_ref_capture() {
check_closure_captures(
r#"
//- minicore:copy
struct S;
fn main() {
let mut s = S;
let s_ref = &mut s;
let closure = || {
if let ref cb = s_ref {
}
};
}
"#,
expect!["83..135;49..54;112..117 ByRef(Shared) s_ref &'? &'? mut S"],
);
}

View File

@ -220,4 +220,23 @@ fn test() {
"#,
)
}
#[test]
fn regression_18201() {
check_diagnostics(
r#"
//- minicore: copy
struct NotCopy;
struct S(NotCopy);
impl S {
fn f(&mut self) {
|| {
if let ref mut _cb = self.0 {
}
};
}
}
"#,
)
}
}