Helper function for formatting with LifetimeSuggestionPosition

This commit is contained in:
Pavel Grigorenko 2024-09-09 14:33:48 +03:00
parent 263a3aeeb8
commit db6361184e
3 changed files with 15 additions and 29 deletions

View File

@ -168,6 +168,19 @@ impl Lifetime {
(LifetimeSuggestionPosition::Normal, self.ident.span) (LifetimeSuggestionPosition::Normal, self.ident.span)
} }
} }
pub fn suggestion(&self, new_lifetime: &str) -> (Span, String) {
debug_assert!(new_lifetime.starts_with('\''));
let (pos, span) = self.suggestion_position();
let code = match pos {
LifetimeSuggestionPosition::Normal => format!("{new_lifetime}"),
LifetimeSuggestionPosition::Ampersand => format!("{new_lifetime} "),
LifetimeSuggestionPosition::ElidedPath => format!("<{new_lifetime}>"),
LifetimeSuggestionPosition::ElidedPathArgument => format!("{new_lifetime}, "),
LifetimeSuggestionPosition::ObjectDefault => format!("+ {new_lifetime}"),
};
(span, code)
}
} }
/// A `Path` is essentially Rust's notion of a name; for instance, /// A `Path` is essentially Rust's notion of a name; for instance,

View File

@ -1191,23 +1191,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> {
(generics.span, "<'a>".to_owned()) (generics.span, "<'a>".to_owned())
}; };
let lifetime_sugg = match lifetime_ref.suggestion_position() { let lifetime_sugg = lifetime_ref.suggestion("'a");
(hir::LifetimeSuggestionPosition::Normal, span) => {
(span, "'a".to_owned())
}
(hir::LifetimeSuggestionPosition::Ampersand, span) => {
(span, "'a ".to_owned())
}
(hir::LifetimeSuggestionPosition::ElidedPath, span) => {
(span, "<'a>".to_owned())
}
(hir::LifetimeSuggestionPosition::ElidedPathArgument, span) => {
(span, "'a, ".to_owned())
}
(hir::LifetimeSuggestionPosition::ObjectDefault, span) => {
(span, "+ 'a".to_owned())
}
};
let suggestions = vec![lifetime_sugg, new_param_sugg]; let suggestions = vec![lifetime_sugg, new_param_sugg];
diag.span_label( diag.span_label(

View File

@ -844,18 +844,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
impl<'hir, 'tcx> hir::intravisit::Visitor<'hir> for LifetimeReplaceVisitor<'tcx, '_> { impl<'hir, 'tcx> hir::intravisit::Visitor<'hir> for LifetimeReplaceVisitor<'tcx, '_> {
fn visit_lifetime(&mut self, lt: &'hir hir::Lifetime) { fn visit_lifetime(&mut self, lt: &'hir hir::Lifetime) {
if lt.res == self.needle { if lt.res == self.needle {
let (pos, span) = lt.suggestion_position(); self.add_lt_suggs.push(lt.suggestion(self.new_lt));
let new_lt = &self.new_lt;
let sugg = match pos {
hir::LifetimeSuggestionPosition::Normal => format!("{new_lt}"),
hir::LifetimeSuggestionPosition::Ampersand => format!("{new_lt} "),
hir::LifetimeSuggestionPosition::ElidedPath => format!("<{new_lt}>"),
hir::LifetimeSuggestionPosition::ElidedPathArgument => {
format!("{new_lt}, ")
}
hir::LifetimeSuggestionPosition::ObjectDefault => format!("+ {new_lt}"),
};
self.add_lt_suggs.push((span, sugg));
} }
} }