Skip to content

Commit 35f96fc

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

File tree

10 files changed

+217
-0
lines changed

10 files changed

+217
-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_style.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ store.register_group(true, "clippy::style", Some("clippy_style"), vec![
9595
LintId::of(ranges::MANUAL_RANGE_CONTAINS),
9696
LintId::of(redundant_field_names::REDUNDANT_FIELD_NAMES),
9797
LintId::of(redundant_static_lifetimes::REDUNDANT_STATIC_LIFETIMES),
98+
LintId::of(return_self_not_must_use::RETURN_SELF_NOT_MUST_USE),
9899
LintId::of(returns::LET_AND_RETURN),
99100
LintId::of(returns::NEEDLESS_RETURN),
100101
LintId::of(self_named_constructors::SELF_NAMED_CONSTRUCTORS),

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: 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 RETURN_SELF_NOT_MUST_USE,
36+
style,
37+
"Missing `#[must_use]` annotation on a method returning `Self`"
38+
}
39+
40+
declare_lint_pass!(ReturnSelfNotMustUse => [RETURN_SELF_NOT_MUST_USE]);
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+
RETURN_SELF_NOT_MUST_USE,
64+
span,
65+
"missing `#[must_use]` attribute on a method returning `Self`",
66+
);
67+
}
68+
}
69+
}
70+
71+
impl<'tcx> LateLintPass<'tcx> for ReturnSelfNotMustUse {
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 {
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+
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#![deny(clippy::return_self_not_must_use)]
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+
}
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/return_self_not_must_use.rs:8:5
3+
|
4+
LL | fn what(&self) -> Self;
5+
| ^^^^^^^^^^^^^^^^^^^^^^^
6+
|
7+
note: the lint level is defined here
8+
--> $DIR/return_self_not_must_use.rs:1:9
9+
|
10+
LL | #![deny(clippy::return_self_not_must_use)]
11+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
12+
13+
error: missing `#[must_use]` attribute on a method returning `Self`
14+
--> $DIR/return_self_not_must_use.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/return_self_not_must_use.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)