From ffd30e0a6939d7d25c4ac28bfac4b4e367adcd59 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Thu, 7 Mar 2024 15:44:07 +0000 Subject: Improve error message for opaque captures --- .../rustc_error_codes/src/error_codes/E0657.md | 59 +++++----------------- 1 file changed, 14 insertions(+), 45 deletions(-) (limited to 'compiler/rustc_error_codes') diff --git a/compiler/rustc_error_codes/src/error_codes/E0657.md b/compiler/rustc_error_codes/src/error_codes/E0657.md index 7fe48c51147..477d8e8bb6d 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0657.md +++ b/compiler/rustc_error_codes/src/error_codes/E0657.md @@ -1,57 +1,26 @@ -A lifetime bound on a trait implementation was captured at an incorrect place. +An `impl Trait` captured a higher-ranked lifetime, which is not supported. + +Currently, `impl Trait` types are only allowed to capture lifetimes from +their parent items, and not from any `for<'a>` binders in scope. Erroneous code example: ```compile_fail,E0657 -trait Id {} -trait Lt<'a> {} - -impl<'a> Lt<'a> for () {} -impl Id for T {} - -fn free_fn_capture_hrtb_in_impl_trait() - -> Box Id>> // error! -{ - Box::new(()) -} +trait BorrowInto<'a> { + type Target; -struct Foo; -impl Foo { - fn impl_fn_capture_hrtb_in_impl_trait() - -> Box Id>> // error! - { - Box::new(()) - } + fn borrow_into(&'a self) -> Self::Target; } -``` -Here, you have used the inappropriate lifetime in the `impl Trait`, -The `impl Trait` can only capture lifetimes bound at the fn or impl -level. +impl<'a> BorrowInto<'a> for () { + type Target = &'a (); -To fix this we have to define the lifetime at the function or impl -level and use that lifetime in the `impl Trait`. For example you can -define the lifetime at the function: - -``` -trait Id {} -trait Lt<'a> {} - -impl<'a> Lt<'a> for () {} -impl Id for T {} - -fn free_fn_capture_hrtb_in_impl_trait<'b>() - -> Box Id>> // ok! -{ - Box::new(()) + fn borrow_into(&'a self) -> Self::Target { + self + } } -struct Foo; -impl Foo { - fn impl_fn_capture_hrtb_in_impl_trait<'b>() - -> Box Id>> // ok! - { - Box::new(()) - } +fn opaque() -> impl for<'a> BorrowInto<'a, Target = impl Sized + 'a> { + () } ``` -- cgit 1.4.1-3-g733a5