Skip to content

Commit 31b83d0

Browse files
committed
Add missnamed_getters lint
1 parent f60186f commit 31b83d0

File tree

6 files changed

+191
-0
lines changed

6 files changed

+191
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4198,6 +4198,7 @@ Released 2018-09-13
41984198
[`missing_safety_doc`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_safety_doc
41994199
[`missing_spin_loop`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_spin_loop
42004200
[`missing_trait_methods`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_trait_methods
4201+
[`missnamed_getters`]: https://rust-lang.github.io/rust-clippy/master/index.html#missnamed_getters
42014202
[`mistyped_literal_suffixes`]: https://rust-lang.github.io/rust-clippy/master/index.html#mistyped_literal_suffixes
42024203
[`mixed_case_hex_literals`]: https://rust-lang.github.io/rust-clippy/master/index.html#mixed_case_hex_literals
42034204
[`mixed_read_write_in_expression`]: https://rust-lang.github.io/rust-clippy/master/index.html#mixed_read_write_in_expression

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
184184
crate::functions::RESULT_UNIT_ERR_INFO,
185185
crate::functions::TOO_MANY_ARGUMENTS_INFO,
186186
crate::functions::TOO_MANY_LINES_INFO,
187+
crate::functions::MISSNAMED_GETTERS_INFO,
187188
crate::future_not_send::FUTURE_NOT_SEND_INFO,
188189
crate::if_let_mutex::IF_LET_MUTEX_INFO,
189190
crate::if_not_else::IF_NOT_ELSE_INFO,
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
use clippy_utils::diagnostics::span_lint_and_sugg;
2+
use clippy_utils::source::snippet;
3+
use rustc_errors::Applicability;
4+
use rustc_hir::{intravisit::FnKind, Body, ExprKind, FnDecl, HirId, ImplicitSelfKind};
5+
use rustc_lint::LateContext;
6+
use rustc_middle::ty;
7+
use rustc_span::Span;
8+
9+
use super::MISSNAMED_GETTERS;
10+
11+
pub fn check_fn(
12+
cx: &LateContext<'_>,
13+
kind: FnKind<'_>,
14+
decl: &FnDecl<'_>,
15+
body: &Body<'_>,
16+
_span: Span,
17+
_hir_id: HirId,
18+
) {
19+
let FnKind::Method(ref ident, sig) = kind else {
20+
return;
21+
};
22+
23+
// Takes only &(mut) self
24+
if decl.inputs.len() != 1 {
25+
return;
26+
}
27+
28+
let name = ident.name.as_str();
29+
30+
let name = match sig.decl.implicit_self {
31+
ImplicitSelfKind::ImmRef => name,
32+
ImplicitSelfKind::MutRef => {
33+
let Some(name) = name.strip_suffix("_mut") else {
34+
return;
35+
};
36+
name
37+
},
38+
_ => return,
39+
};
40+
41+
// Body must be &(mut) <self_data>.name
42+
// self_data is not neccessarilly self
43+
let (self_data, used_ident, span) = if_chain! {
44+
if let ExprKind::Block(block,_) = body.value.kind;
45+
if block.stmts.is_empty();
46+
if let Some(block_expr) = block.expr;
47+
// replace with while for as many addrof needed
48+
if let ExprKind::AddrOf(_,_, expr) = block_expr.kind;
49+
if let ExprKind::Field(self_data, ident) = expr.kind;
50+
if ident.name.as_str() != name;
51+
then {
52+
(self_data,ident,block_expr.span)
53+
} else {
54+
return;
55+
}
56+
};
57+
58+
let ty = cx.typeck_results().expr_ty(self_data);
59+
60+
let def = {
61+
let mut kind = ty.kind();
62+
loop {
63+
match kind {
64+
ty::Adt(def, _) => break def,
65+
ty::Ref(_, ty, _) => kind = ty.kind(),
66+
// We don't do tuples because the function name cannot be a number
67+
_ => return,
68+
}
69+
}
70+
};
71+
72+
let variants = def.variants();
73+
74+
// We're accessing a field, so it should be an union or a struct and have one and only one variant
75+
if variants.len() != 1 {
76+
if cfg!(debug_assertions) {
77+
panic!("Struct or union expected to have only one variant");
78+
} else {
79+
// Don't ICE when possible
80+
return;
81+
}
82+
}
83+
84+
let first = variants.last().unwrap();
85+
let fields = &variants[first];
86+
87+
let mut used_field = None;
88+
let mut correct_field = None;
89+
for f in &fields.fields {
90+
if f.name.as_str() == name {
91+
correct_field = Some(f);
92+
}
93+
if f.name == used_ident.name {
94+
used_field = Some(f);
95+
}
96+
}
97+
98+
let Some(used_field) = used_field else {
99+
if cfg!(debug_assertions) {
100+
panic!("Struct doesn't contain the correct field");
101+
} else {
102+
// Don't ICE when possible
103+
return;
104+
}
105+
};
106+
let Some(correct_field) = correct_field else {
107+
return;
108+
};
109+
110+
if cx.tcx.type_of(used_field.did) == cx.tcx.type_of(correct_field.did) {
111+
let snippet = snippet(cx, span, "..");
112+
let sugg = format!("{}{name}", snippet.strip_suffix(used_field.name.as_str()).unwrap());
113+
span_lint_and_sugg(
114+
cx,
115+
MISSNAMED_GETTERS,
116+
span,
117+
"getter function appears to return the wrong field",
118+
"consider using",
119+
sugg,
120+
Applicability::MaybeIncorrect,
121+
);
122+
}
123+
}

clippy_lints/src/functions/mod.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
mod missnamed_getters;
12
mod must_use;
23
mod not_unsafe_ptr_arg_deref;
34
mod result;
@@ -260,6 +261,25 @@ declare_clippy_lint! {
260261
"function returning `Result` with large `Err` type"
261262
}
262263

264+
declare_clippy_lint! {
265+
/// ### What it does
266+
///
267+
/// ### Why is this bad?
268+
///
269+
/// ### Example
270+
/// ```rust
271+
/// // example code where clippy issues a warning
272+
/// ```
273+
/// Use instead:
274+
/// ```rust
275+
/// // example code which does not raise clippy warning
276+
/// ```
277+
#[clippy::version = "1.66.0"]
278+
pub MISSNAMED_GETTERS,
279+
suspicious,
280+
"default lint description"
281+
}
282+
263283
#[derive(Copy, Clone)]
264284
pub struct Functions {
265285
too_many_arguments_threshold: u64,
@@ -286,6 +306,7 @@ impl_lint_pass!(Functions => [
286306
MUST_USE_CANDIDATE,
287307
RESULT_UNIT_ERR,
288308
RESULT_LARGE_ERR,
309+
MISSNAMED_GETTERS,
289310
]);
290311

291312
impl<'tcx> LateLintPass<'tcx> for Functions {
@@ -301,6 +322,7 @@ impl<'tcx> LateLintPass<'tcx> for Functions {
301322
too_many_arguments::check_fn(cx, kind, decl, span, hir_id, self.too_many_arguments_threshold);
302323
too_many_lines::check_fn(cx, kind, span, body, self.too_many_lines_threshold);
303324
not_unsafe_ptr_arg_deref::check_fn(cx, kind, decl, body, hir_id);
325+
missnamed_getters::check_fn(cx, kind, decl, body, span, hir_id);
304326
}
305327

306328
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {

tests/ui/missnamed_getters.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#![allow(unused)]
2+
#![warn(clippy::missnamed_getters)]
3+
4+
struct A {
5+
a: u8,
6+
b: u8,
7+
}
8+
9+
impl A {
10+
fn a(&self) -> &u8 {
11+
&self.b
12+
}
13+
}
14+
15+
union B {
16+
a: u8,
17+
b: u8,
18+
}
19+
20+
impl B {
21+
unsafe fn a(&self) -> &u8 {
22+
&self.b
23+
}
24+
}
25+
26+
fn main() {
27+
// test code goes here
28+
}

tests/ui/missnamed_getters.stderr

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
error: getter function appears to return the wrong field
2+
--> $DIR/missnamed_getters.rs:11:9
3+
|
4+
LL | &self.b
5+
| ^^^^^^^ help: consider using: `&self.a`
6+
|
7+
= note: `-D clippy::missnamed-getters` implied by `-D warnings`
8+
9+
error: getter function appears to return the wrong field
10+
--> $DIR/missnamed_getters.rs:22:9
11+
|
12+
LL | &self.b
13+
| ^^^^^^^ help: consider using: `&self.a`
14+
15+
error: aborting due to 2 previous errors
16+

0 commit comments

Comments
 (0)