1
+ use clippy_utils:: diagnostics:: span_lint_and_help;
1
2
use clippy_utils:: ty:: is_must_use_ty;
2
- use clippy_utils:: { diagnostics :: span_lint , nth_arg, return_ty} ;
3
+ use clippy_utils:: { nth_arg, return_ty} ;
3
4
use rustc_hir:: def_id:: LocalDefId ;
4
5
use rustc_hir:: intravisit:: FnKind ;
5
6
use rustc_hir:: { Body , FnDecl , HirId , TraitItem , TraitItemKind } ;
@@ -13,25 +14,46 @@ declare_clippy_lint! {
13
14
/// This lint warns when a method returning `Self` doesn't have the `#[must_use]` attribute.
14
15
///
15
16
/// ### Why is this bad?
16
- /// It prevents to "forget" to use the newly created value.
17
+ /// Methods returning `Self` often create new values, having the `#[must_use]` attribute
18
+ /// prevents users from "forgetting" to use the newly created value.
19
+ ///
20
+ /// The `#[must_use]` attribute can be added to the type itself to ensure that instances
21
+ /// are never forgotten. Functions returning a type marked with `#[must_use]` will not be
22
+ /// linted, as the usage is already enforced by the type attribute.
17
23
///
18
24
/// ### Limitations
19
25
/// This lint is only applied on methods taking a `self` argument. It would be mostly noise
20
26
/// if it was added on constructors for example.
21
27
///
22
28
/// ### Example
29
+ /// Missing attribute
23
30
/// ```rust
24
31
/// pub struct Bar;
25
- ///
26
32
/// impl Bar {
27
33
/// // Bad
28
34
/// pub fn bar(&self) -> Self {
29
35
/// Self
30
36
/// }
37
+ /// }
38
+ /// ```
31
39
///
32
- /// // Good
40
+ /// It's better to have the `#[must_use]` attribute on the method like this:
41
+ /// ```rust
42
+ /// pub struct Bar;
43
+ /// impl Bar {
33
44
/// #[must_use]
34
- /// pub fn foo(&self) -> Self {
45
+ /// pub fn bar(&self) -> Self {
46
+ /// Self
47
+ /// }
48
+ /// }
49
+ /// ```
50
+ ///
51
+ /// Or on the type definition like this:
52
+ /// ```rust
53
+ /// #[must_use]
54
+ /// pub struct Bar;
55
+ /// impl Bar {
56
+ /// pub fn bar(&self) -> Self {
35
57
/// Self
36
58
/// }
37
59
/// }
@@ -65,11 +87,13 @@ fn check_method(cx: &LateContext<'tcx>, decl: &'tcx FnDecl<'tcx>, fn_def: LocalD
65
87
if !is_must_use_ty( cx, ret_ty) ;
66
88
67
89
then {
68
- span_lint (
90
+ span_lint_and_help (
69
91
cx,
70
92
RETURN_SELF_NOT_MUST_USE ,
71
93
span,
72
94
"missing `#[must_use]` attribute on a method returning `Self`" ,
95
+ None ,
96
+ "consider adding the `#[must_use]` attribute to the method or directly to the `Self` type"
73
97
) ;
74
98
}
75
99
}
0 commit comments