1
Fork 0

fix: Alloc new errorcode E0803 for E0495

Signed-off-by: xizheyin <xizheyin@smail.nju.edu.cn>
This commit is contained in:
xizheyin 2025-02-15 12:18:30 +08:00
parent d88ffcdb8b
commit d22554a996
No known key found for this signature in database
GPG key ID: 0A0D90BE99CEDEAD
11 changed files with 65 additions and 18 deletions

View file

@ -0,0 +1,46 @@
A trait implementation returns a reference without an
explicit lifetime linking it to `self`.
It commonly arises in generic trait implementations
requiring explicit lifetime bounds.
Erroneous code example:
```compile_fail,E0803
trait DataAccess<T> {
fn get_ref(&self) -> T;
}
struct Container<'a> {
value: &'a f64,
}
// Attempting to implement reference return
impl<'a> DataAccess<&f64> for Container<'a> {
fn get_ref(&self) -> &f64 { // Error: Lifetime mismatch
self.value
}
}
```
The trait method returns &f64 requiring an independent lifetime
The struct Container<'a> carries lifetime parameter 'a
The compiler cannot verify if the returned reference satisfies 'a constraints
Solution
Explicitly bind lifetimes to clarify constraints:
```
// Modified trait with explicit lifetime binding
trait DataAccess<'a, T> {
fn get_ref(&'a self) -> T;
}
struct Container<'a> {
value: &'a f64,
}
// Correct implementation (bound lifetimes)
impl<'a> DataAccess<'a, &'a f64> for Container<'a> {
fn get_ref(&'a self) -> &'a f64 {
self.value
}
}
```

View file

@ -546,6 +546,7 @@ E0799: 0799,
E0800: 0800,
E0801: 0801,
E0802: 0802,
E0803: 0803,
);
)
}

View file

@ -2,7 +2,7 @@ use std::iter;
use rustc_data_structures::fx::FxIndexSet;
use rustc_errors::{
Applicability, Diag, E0309, E0310, E0311, E0495, Subdiagnostic, struct_span_code_err,
Applicability, Diag, E0309, E0310, E0311, E0803, Subdiagnostic, struct_span_code_err,
};
use rustc_hir::def::DefKind;
use rustc_hir::def_id::{DefId, LocalDefId};
@ -1032,7 +1032,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
struct_span_code_err!(
self.dcx(),
var_origin.span(),
E0495,
E0803,
"cannot infer an appropriate lifetime{} due to conflicting requirements",
var_description
)