Add note about unsafe functions body not being unsafe

This commit is contained in:
Wim Looman 2023-05-27 22:20:14 +02:00
parent 62a712a8bb
commit 8f3e876e52
No known key found for this signature in database
GPG key ID: C6F5748C6DD1607B
7 changed files with 89 additions and 22 deletions

View file

@ -571,11 +571,16 @@ pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: LocalDefId) {
errors::UnsafeOpInUnsafeFn {
details,
suggest_unsafe_block: suggest_unsafe_block.then(|| {
let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
let fn_sig = tcx
.hir()
.fn_sig_by_hir_id(hir_id)
.expect("this violation only occurs in fn");
let body = tcx.hir().body_owned_by(def_id);
let body_span = tcx.hir().body(body).value.span;
let start = tcx.sess.source_map().start_point(body_span).shrink_to_hi();
let end = tcx.sess.source_map().end_point(body_span).shrink_to_lo();
(start, end)
(start, end, fn_sig.span)
}),
},
);

View file

@ -131,7 +131,12 @@ impl RequiresUnsafeDetail {
pub(crate) struct UnsafeOpInUnsafeFn {
pub details: RequiresUnsafeDetail,
pub suggest_unsafe_block: Option<(Span, Span)>,
/// These spans point to:
/// 1. the start of the function body
/// 2. the end of the function body
/// 3. the function signature
pub suggest_unsafe_block: Option<(Span, Span, Span)>,
}
impl<'a> DecorateLint<'a, ()> for UnsafeOpInUnsafeFn {
@ -146,7 +151,8 @@ impl<'a> DecorateLint<'a, ()> for UnsafeOpInUnsafeFn {
diag.span_label(self.details.span, self.details.label());
diag.note(self.details.note());
if let Some((start, end)) = self.suggest_unsafe_block {
if let Some((start, end, fn_sig)) = self.suggest_unsafe_block {
diag.span_note(fn_sig, crate::fluent_generated::mir_transform_note);
diag.tool_only_multipart_suggestion(
crate::fluent_generated::mir_transform_suggestion,
vec![(start, " unsafe {".into()), (end, "}".into())],