From 44b00aed4a7d7e329fcbfa95a8685437cfb06e41 Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Fri, 20 Dec 2019 18:53:40 +0100 Subject: Coerce closures to fn pointers E.g. `let x: fn(A) -> B = |x| { y };` --- crates/ra_hir_ty/src/infer/coerce.rs | 4 ++++ crates/ra_hir_ty/src/tests/coercion.rs | 39 ++++++++++++++++++++++++++++++++++ crates/ra_hir_ty/src/tests/traits.rs | 10 ++++----- 3 files changed, 48 insertions(+), 5 deletions(-) (limited to 'crates/ra_hir_ty') diff --git a/crates/ra_hir_ty/src/infer/coerce.rs b/crates/ra_hir_ty/src/infer/coerce.rs index 0f4dac45e..83c0c2c3f 100644 --- a/crates/ra_hir_ty/src/infer/coerce.rs +++ b/crates/ra_hir_ty/src/infer/coerce.rs @@ -134,6 +134,10 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { } } + (ty_app!(TypeCtor::Closure { .. }, params), ty_app!(TypeCtor::FnPtr { .. })) => { + from_ty = params[0].clone(); + } + _ => {} } diff --git a/crates/ra_hir_ty/src/tests/coercion.rs b/crates/ra_hir_ty/src/tests/coercion.rs index 793c23e41..7e99a42ed 100644 --- a/crates/ra_hir_ty/src/tests/coercion.rs +++ b/crates/ra_hir_ty/src/tests/coercion.rs @@ -487,3 +487,42 @@ fn foo() { "### ); } + +#[test] +fn coerce_fn_item_to_fn_ptr() { + assert_snapshot!( + infer_with_mismatches(r#" +fn foo(x: u32) -> isize { 1 } +fn test() { + let f: fn(u32) -> isize = foo; +} +"#, true), + @r###" + [8; 9) 'x': u32 + [25; 30) '{ 1 }': isize + [27; 28) '1': isize + [41; 79) '{ ...foo; }': () + [51; 52) 'f': fn(u32) -> isize + [73; 76) 'foo': fn foo(u32) -> isize + "### + ); +} + +#[test] +fn coerce_closure_to_fn_ptr() { + assert_snapshot!( + infer_with_mismatches(r#" +fn test() { + let f: fn(u32) -> isize = |x| { 1 }; +} +"#, true), + @r###" + [11; 55) '{ ...1 }; }': () + [21; 22) 'f': fn(u32) -> isize + [43; 52) '|x| { 1 }': |u32| -> isize + [44; 45) 'x': u32 + [47; 52) '{ 1 }': isize + [49; 50) '1': isize + "### + ); +} diff --git a/crates/ra_hir_ty/src/tests/traits.rs b/crates/ra_hir_ty/src/tests/traits.rs index 2d92a5eec..76e2198b6 100644 --- a/crates/ra_hir_ty/src/tests/traits.rs +++ b/crates/ra_hir_ty/src/tests/traits.rs @@ -393,11 +393,11 @@ fn test() -> u64 { [54; 55) 'a': S [58; 59) 'S': S(fn(u32) -> u64) -> S [58; 68) 'S(|i| 2*i)': S - [60; 67) '|i| 2*i': |i32| -> i32 - [61; 62) 'i': i32 - [64; 65) '2': i32 - [64; 67) '2*i': i32 - [66; 67) 'i': i32 + [60; 67) '|i| 2*i': |u32| -> u64 + [61; 62) 'i': u32 + [64; 65) '2': u32 + [64; 67) '2*i': u32 + [66; 67) 'i': u32 [78; 79) 'b': u64 [82; 83) 'a': S [82; 85) 'a.0': fn(u32) -> u64 -- cgit v1.2.3