Skip to content

Commit 8dfb3ec

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

File tree

9 files changed

+186
-0
lines changed

9 files changed

+186
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3118,6 +3118,7 @@ Released 2018-09-13
31183118
[`result_map_or_into_option`]: https://rust-lang.github.io/rust-clippy/master/index.html#result_map_or_into_option
31193119
[`result_map_unit_fn`]: https://rust-lang.github.io/rust-clippy/master/index.html#result_map_unit_fn
31203120
[`result_unit_err`]: https://rust-lang.github.io/rust-clippy/master/index.html#result_unit_err
3121+
[`return_self_not_must_use`]: https://rust-lang.github.io/rust-clippy/master/index.html#return_self_not_must_use
31213122
[`reversed_empty_ranges`]: https://rust-lang.github.io/rust-clippy/master/index.html#reversed_empty_ranges
31223123
[`same_functions_in_if_condition`]: https://rust-lang.github.io/rust-clippy/master/index.html#same_functions_in_if_condition
31233124
[`same_item_push`]: https://rust-lang.github.io/rust-clippy/master/index.html#same_item_push

clippy_lints/src/lib.register_all.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,7 @@ store.register_group(true, "clippy::all", Some("clippy_all"), vec![
245245
LintId::of(reference::REF_IN_DEREF),
246246
LintId::of(regex::INVALID_REGEX),
247247
LintId::of(repeat_once::REPEAT_ONCE),
248+
LintId::of(return_self_not_must_use::RETURN_SELF_NOT_MUST_USE),
248249
LintId::of(returns::LET_AND_RETURN),
249250
LintId::of(returns::NEEDLESS_RETURN),
250251
LintId::of(self_assignment::SELF_ASSIGNMENT),

clippy_lints/src/lib.register_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,7 @@ store.register_lints(&[
422422
regex::INVALID_REGEX,
423423
regex::TRIVIAL_REGEX,
424424
repeat_once::REPEAT_ONCE,
425+
return_self_not_must_use::RETURN_SELF_NOT_MUST_USE,
425426
returns::LET_AND_RETURN,
426427
returns::NEEDLESS_RETURN,
427428
same_name_method::SAME_NAME_METHOD,

clippy_lints/src/lib.register_suspicious.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ store.register_group(true, "clippy::suspicious", Some("clippy_suspicious"), vec!
1717
LintId::of(mut_key::MUTABLE_KEY_TYPE),
1818
LintId::of(non_send_fields_in_send_ty::NON_SEND_FIELDS_IN_SEND_TY),
1919
LintId::of(octal_escapes::OCTAL_ESCAPES),
20+
LintId::of(return_self_not_must_use::RETURN_SELF_NOT_MUST_USE),
2021
LintId::of(suspicious_trait_impl::SUSPICIOUS_ARITHMETIC_IMPL),
2122
LintId::of(suspicious_trait_impl::SUSPICIOUS_OP_ASSIGN_IMPL),
2223
])

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,7 @@ mod ref_option_ref;
341341
mod reference;
342342
mod regex;
343343
mod repeat_once;
344+
mod return_self_not_must_use;
344345
mod returns;
345346
mod same_name_method;
346347
mod self_assignment;
@@ -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(return_self_not_must_use::ReturnSelfNotMustUse));
856858
// add lints here, do not remove this comment, it's used in `new_lint`
857859
}
858860

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
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+
/// ### Limitations
18+
/// This lint is only applied on methods taking a `self` argument. It would be mostly noise
19+
/// if it was added on constructors for example.
20+
///
21+
/// ### Example
22+
/// ```rust
23+
/// pub struct Bar;
24+
///
25+
/// impl Bar {
26+
/// // Bad
27+
/// pub fn bar(&self) -> Self {
28+
/// Self
29+
/// }
30+
///
31+
/// // Good
32+
/// #[must_use]
33+
/// pub fn foo(&self) -> Self {
34+
/// Self
35+
/// }
36+
/// }
37+
/// ```
38+
#[clippy::version = "1.59.0"]
39+
pub RETURN_SELF_NOT_MUST_USE,
40+
suspicious,
41+
"missing `#[must_use]` annotation on a method returning `Self`"
42+
}
43+
44+
declare_lint_pass!(ReturnSelfNotMustUse => [RETURN_SELF_NOT_MUST_USE]);
45+
46+
fn check_method(cx: &LateContext<'tcx>, decl: &'tcx FnDecl<'tcx>, fn_def: LocalDefId, span: Span, hir_id: HirId) {
47+
if_chain! {
48+
// If it comes from an external macro, better ignore it.
49+
if !in_external_macro(cx.sess(), span);
50+
if decl.implicit_self.has_implicit_self();
51+
// We only show this warning for public exported methods.
52+
if cx.access_levels.is_exported(fn_def);
53+
if cx.tcx.visibility(fn_def.to_def_id()).is_public();
54+
// No need to warn if the attribute is already present.
55+
if must_use_attr(cx.tcx.hir().attrs(hir_id)).is_none();
56+
let ret_ty = return_ty(cx, hir_id);
57+
let self_arg = nth_arg(cx, hir_id, 0);
58+
// If `Self` has the same type as the returned type, then we want to warn.
59+
//
60+
// For this check, we don't want to remove the reference on the returned type because if
61+
// there is one, we shouldn't emit a warning!
62+
if self_arg.peel_refs() == ret_ty;
63+
64+
then {
65+
span_lint(
66+
cx,
67+
RETURN_SELF_NOT_MUST_USE,
68+
span,
69+
"missing `#[must_use]` attribute on a method returning `Self`",
70+
);
71+
}
72+
}
73+
}
74+
75+
impl<'tcx> LateLintPass<'tcx> for ReturnSelfNotMustUse {
76+
fn check_fn(
77+
&mut self,
78+
cx: &LateContext<'tcx>,
79+
kind: FnKind<'tcx>,
80+
decl: &'tcx FnDecl<'tcx>,
81+
_: &'tcx Body<'tcx>,
82+
span: Span,
83+
hir_id: HirId,
84+
) {
85+
if_chain! {
86+
// We are only interested in methods, not in functions or associated functions.
87+
if matches!(kind, FnKind::Method(_, _, _));
88+
if let Some(fn_def) = cx.tcx.hir().opt_local_def_id(hir_id);
89+
if let Some(impl_def) = cx.tcx.impl_of_method(fn_def.to_def_id());
90+
// We don't want this method to be te implementation of a trait because the
91+
// `#[must_use]` should be put on the trait definition directly.
92+
if cx.tcx.trait_id_of_impl(impl_def).is_none();
93+
94+
then {
95+
check_method(cx, decl, fn_def, span, hir_id);
96+
}
97+
}
98+
}
99+
100+
fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'tcx>) {
101+
if let TraitItemKind::Fn(ref sig, _) = item.kind {
102+
check_method(cx, sig.decl, item.def_id, item.span, item.hir_id());
103+
}
104+
}
105+
}

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 type 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/return_self_not_must_use.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#![crate_type = "lib"]
2+
3+
#[derive(Clone)]
4+
pub struct Bar;
5+
6+
pub trait Whatever {
7+
fn what(&self) -> Self;
8+
// There should be no warning here!
9+
fn what2(&self) -> &Self;
10+
}
11+
12+
impl Bar {
13+
// There should be no warning here!
14+
pub fn not_new() -> Self {
15+
Self
16+
}
17+
pub fn foo(&self) -> Self {
18+
Self
19+
}
20+
pub fn bar(self) -> Self {
21+
self
22+
}
23+
// There should be no warning here!
24+
fn foo2(&self) -> Self {
25+
Self
26+
}
27+
// There should be no warning here!
28+
pub fn foo3(&self) -> &Self {
29+
self
30+
}
31+
}
32+
33+
impl Whatever for Bar {
34+
// There should be no warning here!
35+
fn what(&self) -> Self {
36+
self.foo2()
37+
}
38+
// There should be no warning here!
39+
fn what2(&self) -> &Self {
40+
self
41+
}
42+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
error: missing `#[must_use]` attribute on a method returning `Self`
2+
--> $DIR/return_self_not_must_use.rs:7:5
3+
|
4+
LL | fn what(&self) -> Self;
5+
| ^^^^^^^^^^^^^^^^^^^^^^^
6+
|
7+
= note: `-D clippy::return-self-not-must-use` implied by `-D warnings`
8+
9+
error: missing `#[must_use]` attribute on a method returning `Self`
10+
--> $DIR/return_self_not_must_use.rs:17:5
11+
|
12+
LL | / pub fn foo(&self) -> Self {
13+
LL | | Self
14+
LL | | }
15+
| |_____^
16+
17+
error: missing `#[must_use]` attribute on a method returning `Self`
18+
--> $DIR/return_self_not_must_use.rs:20:5
19+
|
20+
LL | / pub fn bar(self) -> Self {
21+
LL | | self
22+
LL | | }
23+
| |_____^
24+
25+
error: aborting due to 3 previous errors
26+

0 commit comments

Comments
 (0)