1 use rustc_ast::ast::Attribute;
2 use rustc_errors::Applicability;
3 use rustc_hir::def_id::{DefIdSet, LocalDefId};
4 use rustc_hir::{self as hir, def::Res, intravisit, QPath};
5 use rustc_lint::{LateContext, LintContext};
7 lint::in_external_macro,
10 use rustc_span::{sym, Span};
12 use clippy_utils::attrs::is_proc_macro;
13 use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_then};
14 use clippy_utils::source::snippet_opt;
15 use clippy_utils::ty::is_must_use_ty;
16 use clippy_utils::{match_def_path, return_ty, trait_ref_of_method};
18 use super::{DOUBLE_MUST_USE, MUST_USE_CANDIDATE, MUST_USE_UNIT};
20 pub(super) fn check_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
21 let attrs = cx.tcx.hir().attrs(item.hir_id());
22 let attr = cx.tcx.get_attr(item.def_id.to_def_id(), sym::must_use);
23 if let hir::ItemKind::Fn(ref sig, _generics, ref body_id) = item.kind {
24 let is_public = cx.access_levels.is_exported(item.def_id);
25 let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
26 if let Some(attr) = attr {
27 check_needless_must_use(cx, sig.decl, item.hir_id(), item.span, fn_header_span, attr);
28 } else if is_public && !is_proc_macro(cx.sess(), attrs) && !attrs.iter().any(|a| a.has_name(sym::no_mangle)) {
29 check_must_use_candidate(
32 cx.tcx.hir().body(*body_id),
35 item.span.with_hi(sig.decl.output.span().hi()),
36 "this function could have a `#[must_use]` attribute",
42 pub(super) fn check_impl_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
43 if let hir::ImplItemKind::Fn(ref sig, ref body_id) = item.kind {
44 let is_public = cx.access_levels.is_exported(item.def_id);
45 let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
46 let attrs = cx.tcx.hir().attrs(item.hir_id());
47 let attr = cx.tcx.get_attr(item.def_id.to_def_id(), sym::must_use);
48 if let Some(attr) = attr {
49 check_needless_must_use(cx, sig.decl, item.hir_id(), item.span, fn_header_span, attr);
50 } else if is_public && !is_proc_macro(cx.sess(), attrs) && trait_ref_of_method(cx, item.def_id).is_none() {
51 check_must_use_candidate(
54 cx.tcx.hir().body(*body_id),
57 item.span.with_hi(sig.decl.output.span().hi()),
58 "this method could have a `#[must_use]` attribute",
64 pub(super) fn check_trait_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
65 if let hir::TraitItemKind::Fn(ref sig, ref eid) = item.kind {
66 let is_public = cx.access_levels.is_exported(item.def_id);
67 let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
69 let attrs = cx.tcx.hir().attrs(item.hir_id());
70 let attr = cx.tcx.get_attr(item.def_id.to_def_id(), sym::must_use);
71 if let Some(attr) = attr {
72 check_needless_must_use(cx, sig.decl, item.hir_id(), item.span, fn_header_span, attr);
73 } else if let hir::TraitFn::Provided(eid) = *eid {
74 let body = cx.tcx.hir().body(eid);
75 if attr.is_none() && is_public && !is_proc_macro(cx.sess(), attrs) {
76 check_must_use_candidate(
82 item.span.with_hi(sig.decl.output.span().hi()),
83 "this method could have a `#[must_use]` attribute",
90 fn check_needless_must_use(
92 decl: &hir::FnDecl<'_>,
98 if in_external_macro(cx.sess(), item_span) {
101 if returns_unit(decl) {
106 "this unit-returning function has a `#[must_use]` attribute",
108 diag.span_suggestion(attr.span, "remove the attribute", "", Applicability::MachineApplicable);
111 } else if attr.value_str().is_none() && is_must_use_ty(cx, return_ty(cx, item_id)) {
116 "this function has an empty `#[must_use]` attribute, but returns a type already marked as `#[must_use]`",
118 "either add some descriptive text or remove the attribute",
123 fn check_must_use_candidate<'tcx>(
124 cx: &LateContext<'tcx>,
125 decl: &'tcx hir::FnDecl<'_>,
126 body: &'tcx hir::Body<'_>,
132 if has_mutable_arg(cx, body)
133 || mutates_static(cx, body)
134 || in_external_macro(cx.sess(), item_span)
135 || returns_unit(decl)
136 || !cx.access_levels.is_exported(item_id)
137 || is_must_use_ty(cx, return_ty(cx, cx.tcx.hir().local_def_id_to_hir_id(item_id)))
141 span_lint_and_then(cx, MUST_USE_CANDIDATE, fn_span, msg, |diag| {
142 if let Some(snippet) = snippet_opt(cx, fn_span) {
143 diag.span_suggestion(
146 format!("#[must_use] {}", snippet),
147 Applicability::MachineApplicable,
153 fn returns_unit(decl: &hir::FnDecl<'_>) -> bool {
155 hir::FnRetTy::DefaultReturn(_) => true,
156 hir::FnRetTy::Return(ty) => match ty.kind {
157 hir::TyKind::Tup(tys) => tys.is_empty(),
158 hir::TyKind::Never => true,
164 fn has_mutable_arg(cx: &LateContext<'_>, body: &hir::Body<'_>) -> bool {
165 let mut tys = DefIdSet::default();
166 body.params.iter().any(|param| is_mutable_pat(cx, param.pat, &mut tys))
169 fn is_mutable_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, tys: &mut DefIdSet) -> bool {
170 if let hir::PatKind::Wild = pat.kind {
171 return false; // ignore `_` patterns
173 if cx.tcx.has_typeck_results(pat.hir_id.owner.to_def_id()) {
174 is_mutable_ty(cx, cx.tcx.typeck(pat.hir_id.owner).pat_ty(pat), pat.span, tys)
180 static KNOWN_WRAPPER_TYS: &[&[&str]] = &[&["alloc", "rc", "Rc"], &["std", "sync", "Arc"]];
182 fn is_mutable_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, span: Span, tys: &mut DefIdSet) -> bool {
184 // primitive types are never mutable
185 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => false,
186 ty::Adt(adt, substs) => {
187 tys.insert(adt.did()) && !ty.is_freeze(cx.tcx.at(span), cx.param_env)
188 || KNOWN_WRAPPER_TYS.iter().any(|path| match_def_path(cx, adt.did(), path))
189 && substs.types().any(|ty| is_mutable_ty(cx, ty, span, tys))
191 ty::Tuple(substs) => substs.iter().any(|ty| is_mutable_ty(cx, ty, span, tys)),
192 ty::Array(ty, _) | ty::Slice(ty) => is_mutable_ty(cx, ty, span, tys),
193 ty::RawPtr(ty::TypeAndMut { ty, mutbl }) | ty::Ref(_, ty, mutbl) => {
194 mutbl == hir::Mutability::Mut || is_mutable_ty(cx, ty, span, tys)
196 // calling something constitutes a side effect, so return true on all callables
197 // also never calls need not be used, so return true for them, too
202 struct StaticMutVisitor<'a, 'tcx> {
203 cx: &'a LateContext<'tcx>,
204 mutates_static: bool,
207 impl<'a, 'tcx> intravisit::Visitor<'tcx> for StaticMutVisitor<'a, 'tcx> {
208 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
209 use hir::ExprKind::{AddrOf, Assign, AssignOp, Call, MethodCall};
211 if self.mutates_static {
215 Call(_, args) | MethodCall(_, args, _) => {
216 let mut tys = DefIdSet::default();
218 if self.cx.tcx.has_typeck_results(arg.hir_id.owner.to_def_id())
221 self.cx.tcx.typeck(arg.hir_id.owner).expr_ty(arg),
225 && is_mutated_static(arg)
227 self.mutates_static = true;
233 Assign(target, ..) | AssignOp(_, target, _) | AddrOf(_, hir::Mutability::Mut, target) => {
234 self.mutates_static |= is_mutated_static(target);
241 fn is_mutated_static(e: &hir::Expr<'_>) -> bool {
242 use hir::ExprKind::{Field, Index, Path};
245 Path(QPath::Resolved(_, path)) => !matches!(path.res, Res::Local(_)),
247 Field(inner, _) | Index(inner, _) => is_mutated_static(inner),
252 fn mutates_static<'tcx>(cx: &LateContext<'tcx>, body: &'tcx hir::Body<'_>) -> bool {
253 let mut v = StaticMutVisitor {
255 mutates_static: false,
257 intravisit::walk_expr(&mut v, &body.value);