misnamed_getters: Trigger on unsafe with _unchecked

This commit is contained in:
Sosthène Guédon 2022-11-02 19:11:27 +01:00
parent a867c17ab3
commit 3f1a186bd1
2 changed files with 45 additions and 3 deletions

View File

@ -1,7 +1,7 @@
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::source::snippet;
use rustc_errors::Applicability;
use rustc_hir::{intravisit::FnKind, Body, ExprKind, FnDecl, HirId, ImplicitSelfKind};
use rustc_hir::{intravisit::FnKind, Body, ExprKind, FnDecl, HirId, ImplicitSelfKind, Unsafety};
use rustc_lint::LateContext;
use rustc_middle::ty;
use rustc_span::Span;
@ -16,7 +16,7 @@ pub fn check_fn(
span: Span,
_hir_id: HirId,
) {
let FnKind::Method(ref ident, _) = kind else {
let FnKind::Method(ref ident, sig) = kind else {
return;
};
@ -38,6 +38,12 @@ pub fn check_fn(
ImplicitSelfKind::None => return,
};
let name = if sig.header.unsafety == Unsafety::Unsafe {
name.strip_suffix("_unchecked").unwrap_or(name)
} else {
name
};
// Body must be &(mut) <self_data>.name
// self_data is not neccessarilly self, to also lint sub-getters, etc…

View File

@ -90,5 +90,41 @@ LL | | &mut self.a
LL | | }
| |_____^
error: aborting due to 10 previous errors
error: getter function appears to return the wrong field
--> $DIR/misnamed_getters.rs:64:5
|
LL | / unsafe fn a_unchecked(&self) -> &u8 {
LL | | &self.b
| | ------- help: consider using: `&self.a`
LL | | }
| |_____^
error: getter function appears to return the wrong field
--> $DIR/misnamed_getters.rs:67:5
|
LL | / unsafe fn a_unchecked_mut(&mut self) -> &mut u8 {
LL | | &mut self.b
| | ----------- help: consider using: `&mut self.a`
LL | | }
| |_____^
error: getter function appears to return the wrong field
--> $DIR/misnamed_getters.rs:71:5
|
LL | / unsafe fn b_unchecked(self) -> u8 {
LL | | self.a
| | ------ help: consider using: `self.b`
LL | | }
| |_____^
error: getter function appears to return the wrong field
--> $DIR/misnamed_getters.rs:75:5
|
LL | / unsafe fn b_unchecked_mut(&mut self) -> &mut u8 {
LL | | &mut self.a
| | ----------- help: consider using: `&mut self.b`
LL | | }
| |_____^
error: aborting due to 14 previous errors