summaryrefslogtreecommitdiffstats
path: root/src/tools/clippy/clippy_lints/src/functions/must_use.rs
blob: 29bdc46b647d5a8b807803d34f56949d5e0289bb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
use rustc_ast::ast::Attribute;
use rustc_errors::Applicability;
use rustc_hir::def_id::DefIdSet;
use rustc_hir::{self as hir, def::Res, QPath};
use rustc_lint::{LateContext, LintContext};
use rustc_middle::{
    lint::in_external_macro,
    ty::{self, Ty},
};
use rustc_span::{sym, Span, Symbol};

use clippy_utils::attrs::is_proc_macro;
use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_then};
use clippy_utils::source::snippet_opt;
use clippy_utils::ty::is_must_use_ty;
use clippy_utils::visitors::for_each_expr;
use clippy_utils::{return_ty, trait_ref_of_method};

use core::ops::ControlFlow;

use super::{DOUBLE_MUST_USE, MUST_USE_CANDIDATE, MUST_USE_UNIT};

pub(super) fn check_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
    let attrs = cx.tcx.hir().attrs(item.hir_id());
    let attr = cx.tcx.get_attr(item.owner_id.to_def_id(), sym::must_use);
    if let hir::ItemKind::Fn(ref sig, _generics, ref body_id) = item.kind {
        let is_public = cx.effective_visibilities.is_exported(item.owner_id.def_id);
        let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
        if let Some(attr) = attr {
            check_needless_must_use(cx, sig.decl, item.owner_id, item.span, fn_header_span, attr);
        } else if is_public && !is_proc_macro(cx.sess(), attrs) && !attrs.iter().any(|a| a.has_name(sym::no_mangle)) {
            check_must_use_candidate(
                cx,
                sig.decl,
                cx.tcx.hir().body(*body_id),
                item.span,
                item.owner_id,
                item.span.with_hi(sig.decl.output.span().hi()),
                "this function could have a `#[must_use]` attribute",
            );
        }
    }
}

pub(super) fn check_impl_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
    if let hir::ImplItemKind::Fn(ref sig, ref body_id) = item.kind {
        let is_public = cx.effective_visibilities.is_exported(item.owner_id.def_id);
        let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
        let attrs = cx.tcx.hir().attrs(item.hir_id());
        let attr = cx.tcx.get_attr(item.owner_id.to_def_id(), sym::must_use);
        if let Some(attr) = attr {
            check_needless_must_use(cx, sig.decl, item.owner_id, item.span, fn_header_span, attr);
        } else if is_public
            && !is_proc_macro(cx.sess(), attrs)
            && trait_ref_of_method(cx, item.owner_id.def_id).is_none()
        {
            check_must_use_candidate(
                cx,
                sig.decl,
                cx.tcx.hir().body(*body_id),
                item.span,
                item.owner_id,
                item.span.with_hi(sig.decl.output.span().hi()),
                "this method could have a `#[must_use]` attribute",
            );
        }
    }
}

pub(super) fn check_trait_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
    if let hir::TraitItemKind::Fn(ref sig, ref eid) = item.kind {
        let is_public = cx.effective_visibilities.is_exported(item.owner_id.def_id);
        let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());

        let attrs = cx.tcx.hir().attrs(item.hir_id());
        let attr = cx.tcx.get_attr(item.owner_id.to_def_id(), sym::must_use);
        if let Some(attr) = attr {
            check_needless_must_use(cx, sig.decl, item.owner_id, item.span, fn_header_span, attr);
        } else if let hir::TraitFn::Provided(eid) = *eid {
            let body = cx.tcx.hir().body(eid);
            if attr.is_none() && is_public && !is_proc_macro(cx.sess(), attrs) {
                check_must_use_candidate(
                    cx,
                    sig.decl,
                    body,
                    item.span,
                    item.owner_id,
                    item.span.with_hi(sig.decl.output.span().hi()),
                    "this method could have a `#[must_use]` attribute",
                );
            }
        }
    }
}

fn check_needless_must_use(
    cx: &LateContext<'_>,
    decl: &hir::FnDecl<'_>,
    item_id: hir::OwnerId,
    item_span: Span,
    fn_header_span: Span,
    attr: &Attribute,
) {
    if in_external_macro(cx.sess(), item_span) {
        return;
    }
    if returns_unit(decl) {
        span_lint_and_then(
            cx,
            MUST_USE_UNIT,
            fn_header_span,
            "this unit-returning function has a `#[must_use]` attribute",
            |diag| {
                diag.span_suggestion(attr.span, "remove the attribute", "", Applicability::MachineApplicable);
            },
        );
    } else if attr.value_str().is_none() && is_must_use_ty(cx, return_ty(cx, item_id)) {
        span_lint_and_help(
            cx,
            DOUBLE_MUST_USE,
            fn_header_span,
            "this function has an empty `#[must_use]` attribute, but returns a type already marked as `#[must_use]`",
            None,
            "either add some descriptive text or remove the attribute",
        );
    }
}

fn check_must_use_candidate<'tcx>(
    cx: &LateContext<'tcx>,
    decl: &'tcx hir::FnDecl<'_>,
    body: &'tcx hir::Body<'_>,
    item_span: Span,
    item_id: hir::OwnerId,
    fn_span: Span,
    msg: &str,
) {
    if has_mutable_arg(cx, body)
        || mutates_static(cx, body)
        || in_external_macro(cx.sess(), item_span)
        || returns_unit(decl)
        || !cx.effective_visibilities.is_exported(item_id.def_id)
        || is_must_use_ty(cx, return_ty(cx, item_id))
    {
        return;
    }
    span_lint_and_then(cx, MUST_USE_CANDIDATE, fn_span, msg, |diag| {
        if let Some(snippet) = snippet_opt(cx, fn_span) {
            diag.span_suggestion(
                fn_span,
                "add the attribute",
                format!("#[must_use] {snippet}"),
                Applicability::MachineApplicable,
            );
        }
    });
}

fn returns_unit(decl: &hir::FnDecl<'_>) -> bool {
    match decl.output {
        hir::FnRetTy::DefaultReturn(_) => true,
        hir::FnRetTy::Return(ty) => match ty.kind {
            hir::TyKind::Tup(tys) => tys.is_empty(),
            hir::TyKind::Never => true,
            _ => false,
        },
    }
}

fn has_mutable_arg(cx: &LateContext<'_>, body: &hir::Body<'_>) -> bool {
    let mut tys = DefIdSet::default();
    body.params.iter().any(|param| is_mutable_pat(cx, param.pat, &mut tys))
}

fn is_mutable_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, tys: &mut DefIdSet) -> bool {
    if let hir::PatKind::Wild = pat.kind {
        return false; // ignore `_` patterns
    }
    if cx.tcx.has_typeck_results(pat.hir_id.owner.to_def_id()) {
        is_mutable_ty(cx, cx.tcx.typeck(pat.hir_id.owner.def_id).pat_ty(pat), tys)
    } else {
        false
    }
}

static KNOWN_WRAPPER_TYS: &[Symbol] = &[sym::Rc, sym::Arc];

fn is_mutable_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, tys: &mut DefIdSet) -> bool {
    match *ty.kind() {
        // primitive types are never mutable
        ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => false,
        ty::Adt(adt, substs) => {
            tys.insert(adt.did()) && !ty.is_freeze(cx.tcx, cx.param_env)
                || KNOWN_WRAPPER_TYS
                    .iter()
                    .any(|&sym| cx.tcx.is_diagnostic_item(sym, adt.did()))
                    && substs.types().any(|ty| is_mutable_ty(cx, ty, tys))
        },
        ty::Tuple(substs) => substs.iter().any(|ty| is_mutable_ty(cx, ty, tys)),
        ty::Array(ty, _) | ty::Slice(ty) => is_mutable_ty(cx, ty, tys),
        ty::RawPtr(ty::TypeAndMut { ty, mutbl }) | ty::Ref(_, ty, mutbl) => {
            mutbl == hir::Mutability::Mut || is_mutable_ty(cx, ty, tys)
        },
        // calling something constitutes a side effect, so return true on all callables
        // also never calls need not be used, so return true for them, too
        _ => true,
    }
}

fn is_mutated_static(e: &hir::Expr<'_>) -> bool {
    use hir::ExprKind::{Field, Index, Path};

    match e.kind {
        Path(QPath::Resolved(_, path)) => !matches!(path.res, Res::Local(_)),
        Path(_) => true,
        Field(inner, _) | Index(inner, _) => is_mutated_static(inner),
        _ => false,
    }
}

fn mutates_static<'tcx>(cx: &LateContext<'tcx>, body: &'tcx hir::Body<'_>) -> bool {
    for_each_expr(body.value, |e| {
        use hir::ExprKind::{AddrOf, Assign, AssignOp, Call, MethodCall};

        match e.kind {
            Call(_, args) => {
                let mut tys = DefIdSet::default();
                for arg in args {
                    if cx.tcx.has_typeck_results(arg.hir_id.owner.to_def_id())
                        && is_mutable_ty(cx, cx.tcx.typeck(arg.hir_id.owner.def_id).expr_ty(arg), &mut tys)
                        && is_mutated_static(arg)
                    {
                        return ControlFlow::Break(());
                    }
                    tys.clear();
                }
                ControlFlow::Continue(())
            },
            MethodCall(_, receiver, args, _) => {
                let mut tys = DefIdSet::default();
                for arg in std::iter::once(receiver).chain(args.iter()) {
                    if cx.tcx.has_typeck_results(arg.hir_id.owner.to_def_id())
                        && is_mutable_ty(cx, cx.tcx.typeck(arg.hir_id.owner.def_id).expr_ty(arg), &mut tys)
                        && is_mutated_static(arg)
                    {
                        return ControlFlow::Break(());
                    }
                    tys.clear();
                }
                ControlFlow::Continue(())
            },
            Assign(target, ..) | AssignOp(_, target, _) | AddrOf(_, hir::Mutability::Mut, target)
                if is_mutated_static(target) =>
            {
                ControlFlow::Break(())
            },
            _ => ControlFlow::Continue(()),
        }
    })
    .is_some()
}