Skip to content

Commit 19d90bf

Browse files
committed
Auto merge of #8071 - GuillaumeGomez:method-must-use, r=xFrednet
Add new lint to warn when #[must_use] attribute should be used on a method This lint is somewhat similar to https://rust-lang.github.io/rust-clippy/master/index.html#must_use_candidate but also different: it emits a warning by default and only targets methods (so not functions nor associated functions). Someone suggested it to me after this tweet: https://twitter.com/m_ou_se/status/1466439813230477312 I think it would reduce the number of cases of API misuses quite a lot. What do you think?
2 parents 3c8f90b + e93767b commit 19d90bf

20 files changed

+237
-43
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
@@ -16,6 +16,7 @@ store.register_group(true, "clippy::suspicious", Some("clippy_suspicious"), vec!
1616
LintId::of(methods::SUSPICIOUS_MAP),
1717
LintId::of(mut_key::MUTABLE_KEY_TYPE),
1818
LintId::of(octal_escapes::OCTAL_ESCAPES),
19+
LintId::of(return_self_not_must_use::RETURN_SELF_NOT_MUST_USE),
1920
LintId::of(suspicious_trait_impl::SUSPICIOUS_ARITHMETIC_IMPL),
2021
LintId::of(suspicious_trait_impl::SUSPICIOUS_OP_ASSIGN_IMPL),
2122
])

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/hir_utils.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,13 +41,15 @@ impl<'a, 'tcx> SpanlessEq<'a, 'tcx> {
4141
}
4242

4343
/// Consider expressions containing potential side effects as not equal.
44+
#[must_use]
4445
pub fn deny_side_effects(self) -> Self {
4546
Self {
4647
allow_side_effects: false,
4748
..self
4849
}
4950
}
5051

52+
#[must_use]
5153
pub fn expr_fallback(self, expr_fallback: impl FnMut(&Expr<'_>, &Expr<'_>) -> bool + 'a) -> Self {
5254
Self {
5355
expr_fallback: Some(Box::new(expr_fallback)),

clippy_utils/src/lib.rs

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

1396+
/// Convenience function to get the nth argument type of a function.
1397+
pub fn nth_arg<'tcx>(cx: &LateContext<'tcx>, fn_item: hir::HirId, nth: usize) -> Ty<'tcx> {
1398+
let fn_def_id = cx.tcx.hir().local_def_id(fn_item);
1399+
let arg = cx.tcx.fn_sig(fn_def_id).input(nth);
1400+
cx.tcx.erase_late_bound_regions(arg)
1401+
}
1402+
13961403
/// Checks if an expression is constructing a tuple-like enum variant or struct
13971404
pub fn is_ctor_or_promotable_const_function(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
13981405
if let ExprKind::Call(fun, _) = expr.kind {

clippy_utils/src/sugg.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,7 @@ impl<'a> Sugg<'a> {
294294
/// Adds parentheses to any expression that might need them. Suitable to the
295295
/// `self` argument of a method call
296296
/// (e.g., to build `bar.foo()` or `(1 + 2).foo()`).
297+
#[must_use]
297298
pub fn maybe_par(self) -> Self {
298299
match self {
299300
Sugg::NonParen(..) => self,

tests/ui/auxiliary/option_helpers.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#![allow(dead_code, unused_variables)]
1+
#![allow(dead_code, unused_variables, clippy::return_self_not_must_use)]
22

33
/// Utility macro to test linting behavior in `option_methods()`
44
/// The lints included in `option_methods()` should not lint if the call to map is partially

tests/ui/deref_addrof.fixed

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// run-rustfix
2+
#![allow(clippy::return_self_not_must_use)]
23
#![warn(clippy::deref_addrof)]
34

45
fn get_number() -> usize {

tests/ui/deref_addrof.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// run-rustfix
2+
#![allow(clippy::return_self_not_must_use)]
23
#![warn(clippy::deref_addrof)]
34

45
fn get_number() -> usize {

tests/ui/deref_addrof.stderr

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,55 @@
11
error: immediately dereferencing a reference
2-
--> $DIR/deref_addrof.rs:18:13
2+
--> $DIR/deref_addrof.rs:19:13
33
|
44
LL | let b = *&a;
55
| ^^^ help: try this: `a`
66
|
77
= note: `-D clippy::deref-addrof` implied by `-D warnings`
88

99
error: immediately dereferencing a reference
10-
--> $DIR/deref_addrof.rs:20:13
10+
--> $DIR/deref_addrof.rs:21:13
1111
|
1212
LL | let b = *&get_number();
1313
| ^^^^^^^^^^^^^^ help: try this: `get_number()`
1414

1515
error: immediately dereferencing a reference
16-
--> $DIR/deref_addrof.rs:25:13
16+
--> $DIR/deref_addrof.rs:26:13
1717
|
1818
LL | let b = *&bytes[1..2][0];
1919
| ^^^^^^^^^^^^^^^^ help: try this: `bytes[1..2][0]`
2020

2121
error: immediately dereferencing a reference
22-
--> $DIR/deref_addrof.rs:29:13
22+
--> $DIR/deref_addrof.rs:30:13
2323
|
2424
LL | let b = *&(a);
2525
| ^^^^^ help: try this: `(a)`
2626

2727
error: immediately dereferencing a reference
28-
--> $DIR/deref_addrof.rs:31:13
28+
--> $DIR/deref_addrof.rs:32:13
2929
|
3030
LL | let b = *(&a);
3131
| ^^^^^ help: try this: `a`
3232

3333
error: immediately dereferencing a reference
34-
--> $DIR/deref_addrof.rs:34:13
34+
--> $DIR/deref_addrof.rs:35:13
3535
|
3636
LL | let b = *((&a));
3737
| ^^^^^^^ help: try this: `a`
3838

3939
error: immediately dereferencing a reference
40-
--> $DIR/deref_addrof.rs:36:13
40+
--> $DIR/deref_addrof.rs:37:13
4141
|
4242
LL | let b = *&&a;
4343
| ^^^^ help: try this: `&a`
4444

4545
error: immediately dereferencing a reference
46-
--> $DIR/deref_addrof.rs:38:14
46+
--> $DIR/deref_addrof.rs:39:14
4747
|
4848
LL | let b = **&aref;
4949
| ^^^^^^ help: try this: `aref`
5050

5151
error: immediately dereferencing a reference
52-
--> $DIR/deref_addrof.rs:44:9
52+
--> $DIR/deref_addrof.rs:45:9
5353
|
5454
LL | *& $visitor
5555
| ^^^^^^^^^^^ help: try this: `$visitor`
@@ -60,7 +60,7 @@ LL | m!(self)
6060
= note: this error originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info)
6161

6262
error: immediately dereferencing a reference
63-
--> $DIR/deref_addrof.rs:51:9
63+
--> $DIR/deref_addrof.rs:52:9
6464
|
6565
LL | *& mut $visitor
6666
| ^^^^^^^^^^^^^^^ help: try this: `$visitor`

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+

tests/ui/should_impl_trait/corner_cases.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77
clippy::needless_lifetimes,
88
clippy::missing_safety_doc,
99
clippy::wrong_self_convention,
10-
clippy::missing_panics_doc
10+
clippy::missing_panics_doc,
11+
clippy::return_self_not_must_use
1112
)]
1213

1314
use std::ops::Mul;

tests/ui/should_impl_trait/method_list_1.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77
clippy::needless_lifetimes,
88
clippy::missing_safety_doc,
99
clippy::wrong_self_convention,
10-
clippy::missing_panics_doc
10+
clippy::missing_panics_doc,
11+
clippy::return_self_not_must_use
1112
)]
1213

1314
use std::ops::Mul;

0 commit comments

Comments
 (0)