Skip to content

Commit f305926

Browse files
Add new lint to warn when #[must_use] attribute should be used on a method
1 parent be1a73b commit f305926

File tree

9 files changed

+187
-0
lines changed

9 files changed

+187
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3015,6 +3015,7 @@ Released 2018-09-13
30153015
[`multiple_crate_versions`]: https://rust-lang.github.io/rust-clippy/master/index.html#multiple_crate_versions
30163016
[`multiple_inherent_impl`]: https://rust-lang.github.io/rust-clippy/master/index.html#multiple_inherent_impl
30173017
[`must_use_candidate`]: https://rust-lang.github.io/rust-clippy/master/index.html#must_use_candidate
3018+
[`must_use_self_return`]: https://rust-lang.github.io/rust-clippy/master/index.html#must_use_self_return
30183019
[`must_use_unit`]: https://rust-lang.github.io/rust-clippy/master/index.html#must_use_unit
30193020
[`mut_from_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#mut_from_ref
30203021
[`mut_mut`]: https://rust-lang.github.io/rust-clippy/master/index.html#mut_mut

clippy_lints/src/lib.register_all.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,7 @@ store.register_group(true, "clippy::all", Some("clippy_all"), vec![
198198
LintId::of(misc_early::REDUNDANT_PATTERN),
199199
LintId::of(misc_early::UNNEEDED_WILDCARD_PATTERN),
200200
LintId::of(misc_early::ZERO_PREFIXED_LITERAL),
201+
LintId::of(must_use_self_return::MUST_USE_SELF_RETURN),
201202
LintId::of(mut_key::MUTABLE_KEY_TYPE),
202203
LintId::of(mut_mutex_lock::MUT_MUTEX_LOCK),
203204
LintId::of(mut_reference::UNNECESSARY_MUT_PASSED),

clippy_lints/src/lib.register_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,7 @@ store.register_lints(&[
348348
module_style::SELF_NAMED_MODULE_FILES,
349349
modulo_arithmetic::MODULO_ARITHMETIC,
350350
multiple_crate_versions::MULTIPLE_CRATE_VERSIONS,
351+
must_use_self_return::MUST_USE_SELF_RETURN,
351352
mut_key::MUTABLE_KEY_TYPE,
352353
mut_mut::MUT_MUT,
353354
mut_mutex_lock::MUT_MUTEX_LOCK,

clippy_lints/src/lib.register_style.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ store.register_group(true, "clippy::style", Some("clippy_style"), vec![
8080
LintId::of(misc_early::DUPLICATE_UNDERSCORE_ARGUMENT),
8181
LintId::of(misc_early::MIXED_CASE_HEX_LITERALS),
8282
LintId::of(misc_early::REDUNDANT_PATTERN),
83+
LintId::of(must_use_self_return::MUST_USE_SELF_RETURN),
8384
LintId::of(mut_mutex_lock::MUT_MUTEX_LOCK),
8485
LintId::of(mut_reference::UNNECESSARY_MUT_PASSED),
8586
LintId::of(needless_late_init::NEEDLESS_LATE_INIT),

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,7 @@ mod missing_inline;
287287
mod module_style;
288288
mod modulo_arithmetic;
289289
mod multiple_crate_versions;
290+
mod must_use_self_return;
290291
mod mut_key;
291292
mod mut_mut;
292293
mod mut_mutex_lock;
@@ -853,6 +854,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
853854
store.register_late_pass(|| Box::new(trailing_empty_array::TrailingEmptyArray));
854855
store.register_early_pass(|| Box::new(octal_escapes::OctalEscapes));
855856
store.register_late_pass(|| Box::new(needless_late_init::NeedlessLateInit));
857+
store.register_late_pass(|| Box::new(must_use_self_return::MustUseSelfReturn));
856858
// add lints here, do not remove this comment, it's used in `new_lint`
857859
}
858860

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
use clippy_utils::{diagnostics::span_lint, must_use_attr, nth_arg, return_ty};
2+
use rustc_hir::def_id::LocalDefId;
3+
use rustc_hir::intravisit::FnKind;
4+
use rustc_hir::{Body, FnDecl, HirId, TraitItem, TraitItemKind};
5+
use rustc_lint::{LateContext, LateLintPass, LintContext};
6+
use rustc_middle::lint::in_external_macro;
7+
use rustc_session::{declare_lint_pass, declare_tool_lint};
8+
use rustc_span::Span;
9+
10+
declare_clippy_lint! {
11+
/// ### What it does
12+
/// This lint warns when a method returning `Self` doesn't have the `#[must_use]` attribute.
13+
///
14+
/// ### Why is this bad?
15+
/// It prevents to "forget" to use the newly created value.
16+
///
17+
/// ### Example
18+
/// ```rust
19+
/// pub struct Bar;
20+
///
21+
/// impl Bar {
22+
/// // Bad
23+
/// pub fn bar(&self) -> Self {
24+
/// Self
25+
/// }
26+
///
27+
/// // Good
28+
/// #[must_use]
29+
/// pub fn foo(&self) -> Self {
30+
/// Self
31+
/// }
32+
/// }
33+
/// ```
34+
#[clippy::version = "1.59.0"]
35+
pub MUST_USE_SELF_RETURN,
36+
style,
37+
"Missing `#[must_use]` annotation on a method returning `Self`"
38+
}
39+
40+
declare_lint_pass!(MustUseSelfReturn => [MUST_USE_SELF_RETURN]);
41+
42+
fn check_method(cx: &LateContext<'tcx>, decl: &'tcx FnDecl<'tcx>, fn_def: LocalDefId, span: Span, hir_id: HirId) {
43+
if_chain! {
44+
// If it comes from an external macro, better ignore it.
45+
if !in_external_macro(cx.sess(), span);
46+
if decl.implicit_self.has_implicit_self();
47+
// We only show this warning for public exported methods.
48+
if cx.access_levels.is_exported(fn_def);
49+
if cx.tcx.visibility(fn_def.to_def_id()).is_public();
50+
// No need to warn if the attribute is already present.
51+
if must_use_attr(cx.tcx.hir().attrs(hir_id)).is_none();
52+
let ret_ty = return_ty(cx, hir_id);
53+
let self_arg = nth_arg(cx, hir_id, 0);
54+
// If `Self` has the same type as the returned type, then we want to warn.
55+
//
56+
// For this check, we don't want to remove the reference on the returned type because if
57+
// there is one, we shouldn't emit a warning!
58+
if self_arg.peel_refs() == ret_ty;
59+
60+
then {
61+
span_lint(
62+
cx,
63+
MUST_USE_SELF_RETURN,
64+
span,
65+
"missing `#[must_use]` attribute on a method returning `Self`",
66+
);
67+
}
68+
}
69+
}
70+
71+
impl<'tcx> LateLintPass<'tcx> for MustUseSelfReturn {
72+
fn check_fn(
73+
&mut self,
74+
cx: &LateContext<'tcx>,
75+
kind: FnKind<'tcx>,
76+
decl: &'tcx FnDecl<'tcx>,
77+
_: &'tcx Body<'tcx>,
78+
span: Span,
79+
hir_id: HirId,
80+
) {
81+
if_chain! {
82+
// We are only interested in methods, not in functions or associated functions.
83+
if matches!(kind, FnKind::Method(_, _, _));
84+
if let Some(fn_def) = cx.tcx.hir().opt_local_def_id(hir_id);
85+
if let Some(impl_def) = cx.tcx.impl_of_method(fn_def.to_def_id());
86+
// We don't want this method to be te implementation of a trait because the
87+
// `#[must_use]` should be put on the trait definition directly.
88+
if cx.tcx.trait_id_of_impl(impl_def).is_none();
89+
90+
then {
91+
check_method(cx, decl, fn_def, span, hir_id);
92+
}
93+
}
94+
}
95+
96+
fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'tcx>) {
97+
if let TraitItemKind::Fn(ref sig, _) = item.kind {
98+
check_method(cx, sig.decl, item.def_id, item.span, item.hir_id());
99+
}
100+
}
101+
}

clippy_utils/src/lib.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1329,6 +1329,13 @@ pub fn return_ty<'tcx>(cx: &LateContext<'tcx>, fn_item: hir::HirId) -> Ty<'tcx>
13291329
cx.tcx.erase_late_bound_regions(ret_ty)
13301330
}
13311331

1332+
/// Convenience function to get the nth argument of a function.
1333+
pub fn nth_arg<'tcx>(cx: &LateContext<'tcx>, fn_item: hir::HirId, nth: usize) -> Ty<'tcx> {
1334+
let fn_def_id = cx.tcx.hir().local_def_id(fn_item);
1335+
let arg = cx.tcx.fn_sig(fn_def_id).input(nth);
1336+
cx.tcx.erase_late_bound_regions(arg)
1337+
}
1338+
13321339
/// Checks if an expression is constructing a tuple-like enum variant or struct
13331340
pub fn is_ctor_or_promotable_const_function(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
13341341
if let ExprKind::Call(fun, _) = expr.kind {

tests/ui/must_use_self_return.rs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#![deny(clippy::must_use_self_return)]
2+
#![crate_type = "lib"]
3+
4+
#[derive(Clone)]
5+
pub struct Bar;
6+
7+
pub trait Whatever {
8+
fn what(&self) -> Self;
9+
// There should be no warning here!
10+
fn what2(&self) -> &Self;
11+
}
12+
13+
impl Bar {
14+
// There should be no warning here!
15+
pub fn not_new() -> Self {
16+
Self
17+
}
18+
pub fn foo(&self) -> Self {
19+
Self
20+
}
21+
pub fn bar(self) -> Self {
22+
self
23+
}
24+
// There should be no warning here!
25+
fn foo2(&self) -> Self {
26+
Self
27+
}
28+
// There should be no warning here!
29+
pub fn foo3(&self) -> &Self {
30+
self
31+
}
32+
}
33+
34+
impl Whatever for Bar {
35+
// There should be no warning here!
36+
fn what(&self) -> Self {
37+
self.foo2()
38+
}
39+
// There should be no warning here!
40+
fn what2(&self) -> &Self {
41+
self
42+
}
43+
}

tests/ui/must_use_self_return.stderr

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
error: missing `#[must_use]` attribute on a method returning `Self`
2+
--> $DIR/must_use_self_return.rs:8:5
3+
|
4+
LL | fn what(&self) -> Self;
5+
| ^^^^^^^^^^^^^^^^^^^^^^^
6+
|
7+
note: the lint level is defined here
8+
--> $DIR/must_use_self_return.rs:1:9
9+
|
10+
LL | #![deny(clippy::must_use_self_return)]
11+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
12+
13+
error: missing `#[must_use]` attribute on a method returning `Self`
14+
--> $DIR/must_use_self_return.rs:18:5
15+
|
16+
LL | / pub fn foo(&self) -> Self {
17+
LL | | Self
18+
LL | | }
19+
| |_____^
20+
21+
error: missing `#[must_use]` attribute on a method returning `Self`
22+
--> $DIR/must_use_self_return.rs:21:5
23+
|
24+
LL | / pub fn bar(self) -> Self {
25+
LL | | self
26+
LL | | }
27+
| |_____^
28+
29+
error: aborting due to 3 previous errors
30+

0 commit comments

Comments
 (0)