Skip to content

Commit

Permalink
Add new lint to warn when #[must_use] attribute should be used on a m…
Browse files Browse the repository at this point in the history
…ethod
  • Loading branch information
GuillaumeGomez committed Dec 3, 2021
1 parent be1a73b commit f305926
Show file tree
Hide file tree
Showing 9 changed files with 187 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3015,6 +3015,7 @@ Released 2018-09-13
[`multiple_crate_versions`]: https://rust-lang.github.io/rust-clippy/master/index.html#multiple_crate_versions
[`multiple_inherent_impl`]: https://rust-lang.github.io/rust-clippy/master/index.html#multiple_inherent_impl
[`must_use_candidate`]: https://rust-lang.github.io/rust-clippy/master/index.html#must_use_candidate
[`must_use_self_return`]: https://rust-lang.github.io/rust-clippy/master/index.html#must_use_self_return
[`must_use_unit`]: https://rust-lang.github.io/rust-clippy/master/index.html#must_use_unit
[`mut_from_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#mut_from_ref
[`mut_mut`]: https://rust-lang.github.io/rust-clippy/master/index.html#mut_mut
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/lib.register_all.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ store.register_group(true, "clippy::all", Some("clippy_all"), vec![
LintId::of(misc_early::REDUNDANT_PATTERN),
LintId::of(misc_early::UNNEEDED_WILDCARD_PATTERN),
LintId::of(misc_early::ZERO_PREFIXED_LITERAL),
LintId::of(must_use_self_return::MUST_USE_SELF_RETURN),
LintId::of(mut_key::MUTABLE_KEY_TYPE),
LintId::of(mut_mutex_lock::MUT_MUTEX_LOCK),
LintId::of(mut_reference::UNNECESSARY_MUT_PASSED),
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/lib.register_lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,7 @@ store.register_lints(&[
module_style::SELF_NAMED_MODULE_FILES,
modulo_arithmetic::MODULO_ARITHMETIC,
multiple_crate_versions::MULTIPLE_CRATE_VERSIONS,
must_use_self_return::MUST_USE_SELF_RETURN,
mut_key::MUTABLE_KEY_TYPE,
mut_mut::MUT_MUT,
mut_mutex_lock::MUT_MUTEX_LOCK,
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/lib.register_style.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ store.register_group(true, "clippy::style", Some("clippy_style"), vec![
LintId::of(misc_early::DUPLICATE_UNDERSCORE_ARGUMENT),
LintId::of(misc_early::MIXED_CASE_HEX_LITERALS),
LintId::of(misc_early::REDUNDANT_PATTERN),
LintId::of(must_use_self_return::MUST_USE_SELF_RETURN),
LintId::of(mut_mutex_lock::MUT_MUTEX_LOCK),
LintId::of(mut_reference::UNNECESSARY_MUT_PASSED),
LintId::of(needless_late_init::NEEDLESS_LATE_INIT),
Expand Down
2 changes: 2 additions & 0 deletions clippy_lints/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,7 @@ mod missing_inline;
mod module_style;
mod modulo_arithmetic;
mod multiple_crate_versions;
mod must_use_self_return;
mod mut_key;
mod mut_mut;
mod mut_mutex_lock;
Expand Down Expand Up @@ -853,6 +854,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
store.register_late_pass(|| Box::new(trailing_empty_array::TrailingEmptyArray));
store.register_early_pass(|| Box::new(octal_escapes::OctalEscapes));
store.register_late_pass(|| Box::new(needless_late_init::NeedlessLateInit));
store.register_late_pass(|| Box::new(must_use_self_return::MustUseSelfReturn));
// add lints here, do not remove this comment, it's used in `new_lint`
}

Expand Down
101 changes: 101 additions & 0 deletions clippy_lints/src/must_use_self_return.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
use clippy_utils::{diagnostics::span_lint, must_use_attr, nth_arg, return_ty};
use rustc_hir::def_id::LocalDefId;
use rustc_hir::intravisit::FnKind;
use rustc_hir::{Body, FnDecl, HirId, TraitItem, TraitItemKind};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_middle::lint::in_external_macro;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::Span;

declare_clippy_lint! {
/// ### What it does
/// This lint warns when a method returning `Self` doesn't have the `#[must_use]` attribute.
///
/// ### Why is this bad?
/// It prevents to "forget" to use the newly created value.
///
/// ### Example
/// ```rust
/// pub struct Bar;
///
/// impl Bar {
/// // Bad
/// pub fn bar(&self) -> Self {
/// Self
/// }
///
/// // Good
/// #[must_use]
/// pub fn foo(&self) -> Self {
/// Self
/// }
/// }
/// ```
#[clippy::version = "1.59.0"]
pub MUST_USE_SELF_RETURN,
style,
"Missing `#[must_use]` annotation on a method returning `Self`"
}

declare_lint_pass!(MustUseSelfReturn => [MUST_USE_SELF_RETURN]);

fn check_method(cx: &LateContext<'tcx>, decl: &'tcx FnDecl<'tcx>, fn_def: LocalDefId, span: Span, hir_id: HirId) {
if_chain! {
// If it comes from an external macro, better ignore it.
if !in_external_macro(cx.sess(), span);
if decl.implicit_self.has_implicit_self();
// We only show this warning for public exported methods.
if cx.access_levels.is_exported(fn_def);
if cx.tcx.visibility(fn_def.to_def_id()).is_public();
// No need to warn if the attribute is already present.
if must_use_attr(cx.tcx.hir().attrs(hir_id)).is_none();
let ret_ty = return_ty(cx, hir_id);
let self_arg = nth_arg(cx, hir_id, 0);
// If `Self` has the same type as the returned type, then we want to warn.
//
// For this check, we don't want to remove the reference on the returned type because if
// there is one, we shouldn't emit a warning!
if self_arg.peel_refs() == ret_ty;

then {
span_lint(
cx,
MUST_USE_SELF_RETURN,
span,
"missing `#[must_use]` attribute on a method returning `Self`",
);
}
}
}

impl<'tcx> LateLintPass<'tcx> for MustUseSelfReturn {
fn check_fn(
&mut self,
cx: &LateContext<'tcx>,
kind: FnKind<'tcx>,
decl: &'tcx FnDecl<'tcx>,
_: &'tcx Body<'tcx>,
span: Span,
hir_id: HirId,
) {
if_chain! {
// We are only interested in methods, not in functions or associated functions.
if matches!(kind, FnKind::Method(_, _, _));
if let Some(fn_def) = cx.tcx.hir().opt_local_def_id(hir_id);
if let Some(impl_def) = cx.tcx.impl_of_method(fn_def.to_def_id());
// We don't want this method to be te implementation of a trait because the
// `#[must_use]` should be put on the trait definition directly.
if cx.tcx.trait_id_of_impl(impl_def).is_none();

then {
check_method(cx, decl, fn_def, span, hir_id);
}
}
}

fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'tcx>) {
if let TraitItemKind::Fn(ref sig, _) = item.kind {
check_method(cx, sig.decl, item.def_id, item.span, item.hir_id());
}
}
}
7 changes: 7 additions & 0 deletions clippy_utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1329,6 +1329,13 @@ pub fn return_ty<'tcx>(cx: &LateContext<'tcx>, fn_item: hir::HirId) -> Ty<'tcx>
cx.tcx.erase_late_bound_regions(ret_ty)
}

/// Convenience function to get the nth argument of a function.
pub fn nth_arg<'tcx>(cx: &LateContext<'tcx>, fn_item: hir::HirId, nth: usize) -> Ty<'tcx> {
let fn_def_id = cx.tcx.hir().local_def_id(fn_item);
let arg = cx.tcx.fn_sig(fn_def_id).input(nth);
cx.tcx.erase_late_bound_regions(arg)
}

/// Checks if an expression is constructing a tuple-like enum variant or struct
pub fn is_ctor_or_promotable_const_function(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
if let ExprKind::Call(fun, _) = expr.kind {
Expand Down
43 changes: 43 additions & 0 deletions tests/ui/must_use_self_return.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#![deny(clippy::must_use_self_return)]
#![crate_type = "lib"]

#[derive(Clone)]
pub struct Bar;

pub trait Whatever {
fn what(&self) -> Self;
// There should be no warning here!
fn what2(&self) -> &Self;
}

impl Bar {
// There should be no warning here!
pub fn not_new() -> Self {
Self
}
pub fn foo(&self) -> Self {
Self
}
pub fn bar(self) -> Self {
self
}
// There should be no warning here!
fn foo2(&self) -> Self {
Self
}
// There should be no warning here!
pub fn foo3(&self) -> &Self {
self
}
}

impl Whatever for Bar {
// There should be no warning here!
fn what(&self) -> Self {
self.foo2()
}
// There should be no warning here!
fn what2(&self) -> &Self {
self
}
}
30 changes: 30 additions & 0 deletions tests/ui/must_use_self_return.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
error: missing `#[must_use]` attribute on a method returning `Self`
--> $DIR/must_use_self_return.rs:8:5
|
LL | fn what(&self) -> Self;
| ^^^^^^^^^^^^^^^^^^^^^^^
|
note: the lint level is defined here
--> $DIR/must_use_self_return.rs:1:9
|
LL | #![deny(clippy::must_use_self_return)]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error: missing `#[must_use]` attribute on a method returning `Self`
--> $DIR/must_use_self_return.rs:18:5
|
LL | / pub fn foo(&self) -> Self {
LL | | Self
LL | | }
| |_____^

error: missing `#[must_use]` attribute on a method returning `Self`
--> $DIR/must_use_self_return.rs:21:5
|
LL | / pub fn bar(self) -> Self {
LL | | self
LL | | }
| |_____^

error: aborting due to 3 previous errors

0 comments on commit f305926

Please sign in to comment.