Skip to main content

rustc_lint/unused/
must_use.rs

1use std::iter;
2
3use rustc_errors::pluralize;
4use rustc_hir::attrs::lang_items::LangItem;
5use rustc_hir::def::{DefKind, Res};
6use rustc_hir::def_id::DefId;
7use rustc_hir::{self as hir, find_attr};
8use rustc_infer::traits::util::elaborate;
9use rustc_middle::ty::{self, Ty, Unnormalized};
10use rustc_session::{declare_lint, declare_lint_pass};
11use rustc_span::{Span, Symbol, sym};
12use tracing::instrument;
13
14use crate::diagnostics::{
15    UnusedClosure, UnusedCoroutine, UnusedDef, UnusedDefSuggestion, UnusedOp, UnusedOpSuggestion,
16    UnusedResult,
17};
18use crate::{LateContext, LateLintPass, LintContext};
19
20#[doc =
r" The `unused_must_use` lint detects unused result of a type flagged as"]
#[doc = r" `#[must_use]`."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" fn returns_result() -> Result<(), ()> {"]
#[doc = r"     Ok(())"]
#[doc = r" }"]
#[doc = r""]
#[doc = r" fn main() {"]
#[doc = r"     returns_result();"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" The `#[must_use]` attribute is an indicator that it is a mistake to"]
#[doc = r" ignore the value. See [the reference] for more details."]
#[doc = r""]
#[doc =
r" [the reference]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute"]
pub static UNUSED_MUST_USE: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "UNUSED_MUST_USE",
            default_level: ::rustc_lint_defs::Warn,
            desc: "unused result of a type flagged as `#[must_use]`",
            is_externally_loaded: false,
            report_in_external_macro: true,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
21    /// The `unused_must_use` lint detects unused result of a type flagged as
22    /// `#[must_use]`.
23    ///
24    /// ### Example
25    ///
26    /// ```rust
27    /// fn returns_result() -> Result<(), ()> {
28    ///     Ok(())
29    /// }
30    ///
31    /// fn main() {
32    ///     returns_result();
33    /// }
34    /// ```
35    ///
36    /// {{produces}}
37    ///
38    /// ### Explanation
39    ///
40    /// The `#[must_use]` attribute is an indicator that it is a mistake to
41    /// ignore the value. See [the reference] for more details.
42    ///
43    /// [the reference]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
44    pub UNUSED_MUST_USE,
45    Warn,
46    "unused result of a type flagged as `#[must_use]`",
47    report_in_external_macro
48}
49
50#[doc = r" The `unused_results` lint checks for the unused result of an"]
#[doc = r" expression in a statement."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #![deny(unused_results)]"]
#[doc = r" fn foo<T>() -> T { panic!() }"]
#[doc = r""]
#[doc = r" fn main() {"]
#[doc = r"     foo::<usize>();"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Ignoring the return value of a function may indicate a mistake. In"]
#[doc =
r" cases were it is almost certain that the result should be used, it is"]
#[doc =
r" recommended to annotate the function with the [`must_use` attribute]."]
#[doc =
r" Failure to use such a return value will trigger the [`unused_must_use`"]
#[doc = r" lint] which is warn-by-default. The `unused_results` lint is"]
#[doc = r" essentially the same, but triggers for *all* return values."]
#[doc = r""]
#[doc =
r#" This lint is "allow" by default because it can be noisy, and may not be"#]
#[doc =
r" an actual problem. For example, calling the `remove` method of a `Vec`"]
#[doc =
r" or `HashMap` returns the previous value, which you may not care about."]
#[doc =
r" Using this lint would require explicitly ignoring or discarding such"]
#[doc = r" values."]
#[doc = r""]
#[doc =
r" [`must_use` attribute]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute"]
#[doc = r" [`unused_must_use` lint]: warn-by-default.html#unused-must-use"]
pub static UNUSED_RESULTS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "UNUSED_RESULTS",
            default_level: ::rustc_lint_defs::Allow,
            desc: "unused result of an expression in a statement",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
51    /// The `unused_results` lint checks for the unused result of an
52    /// expression in a statement.
53    ///
54    /// ### Example
55    ///
56    /// ```rust,compile_fail
57    /// #![deny(unused_results)]
58    /// fn foo<T>() -> T { panic!() }
59    ///
60    /// fn main() {
61    ///     foo::<usize>();
62    /// }
63    /// ```
64    ///
65    /// {{produces}}
66    ///
67    /// ### Explanation
68    ///
69    /// Ignoring the return value of a function may indicate a mistake. In
70    /// cases were it is almost certain that the result should be used, it is
71    /// recommended to annotate the function with the [`must_use` attribute].
72    /// Failure to use such a return value will trigger the [`unused_must_use`
73    /// lint] which is warn-by-default. The `unused_results` lint is
74    /// essentially the same, but triggers for *all* return values.
75    ///
76    /// This lint is "allow" by default because it can be noisy, and may not be
77    /// an actual problem. For example, calling the `remove` method of a `Vec`
78    /// or `HashMap` returns the previous value, which you may not care about.
79    /// Using this lint would require explicitly ignoring or discarding such
80    /// values.
81    ///
82    /// [`must_use` attribute]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
83    /// [`unused_must_use` lint]: warn-by-default.html#unused-must-use
84    pub UNUSED_RESULTS,
85    Allow,
86    "unused result of an expression in a statement"
87}
88
89pub struct UnusedResults;
#[automatically_derived]
impl ::core::marker::Copy for UnusedResults { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for UnusedResults { }
#[automatically_derived]
impl ::core::clone::Clone for UnusedResults {
    #[inline]
    fn clone(&self) -> UnusedResults { *self }
}
impl ::rustc_lint_defs::LintPass for UnusedResults {
    fn name(&self) -> &'static str { "UnusedResults" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [UNUSED_MUST_USE, UNUSED_RESULTS]))
    }
}
impl UnusedResults {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [UNUSED_MUST_USE, UNUSED_RESULTS]))
    }
}declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]);
90
91/// Must the type be used?
92#[derive(#[automatically_derived]
impl ::core::fmt::Debug for IsTyMustUse {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            IsTyMustUse::Yes(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Yes",
                    &__self_0),
            IsTyMustUse::No => ::core::fmt::Formatter::write_str(f, "No"),
            IsTyMustUse::Trivial =>
                ::core::fmt::Formatter::write_str(f, "Trivial"),
        }
    }
}Debug)]
93pub enum IsTyMustUse {
94    /// Yes, `MustUsePath` contains an explanation for why the type must be used.
95    /// This will result in `unused_must_use` lint.
96    Yes(MustUsePath),
97    /// No, an ordinary type that may be ignored.
98    /// This will result in `unused_results` lint.
99    No,
100    /// No, the type is trivial and thus should always be ignored.
101    /// (this suppresses `unused_results` lint)
102    Trivial,
103}
104
105impl IsTyMustUse {
106    fn map(self, f: impl FnOnce(MustUsePath) -> MustUsePath) -> Self {
107        match self {
108            Self::Yes(must_use_path) => Self::Yes(f(must_use_path)),
109            _ => self,
110        }
111    }
112}
113
114/// A path through a type to a `must_use` source. Contains useful info for the lint.
115#[derive(#[automatically_derived]
impl ::core::fmt::Debug for MustUsePath {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            MustUsePath::Def(__self_0, __self_1, __self_2) =>
                ::core::fmt::Formatter::debug_tuple_field3_finish(f, "Def",
                    __self_0, __self_1, &__self_2),
            MustUsePath::Boxed(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Boxed",
                    &__self_0),
            MustUsePath::Pinned(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Pinned",
                    &__self_0),
            MustUsePath::Opaque(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Opaque",
                    &__self_0),
            MustUsePath::TraitObject(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "TraitObject", &__self_0),
            MustUsePath::TupleElement(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "TupleElement", &__self_0),
            MustUsePath::Result(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Result",
                    &__self_0),
            MustUsePath::ControlFlow(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ControlFlow", &__self_0),
            MustUsePath::Array(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f, "Array",
                    __self_0, &__self_1),
            MustUsePath::Closure(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Closure", &__self_0),
            MustUsePath::Coroutine(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Coroutine", &__self_0),
        }
    }
}Debug)]
116pub enum MustUsePath {
117    /// The root of the normal `must_use` lint with an optional message.
118    Def(Span, DefId, Option<Symbol>),
119    Boxed(Box<Self>),
120    Pinned(Box<Self>),
121    Opaque(Box<Self>),
122    TraitObject(Box<Self>),
123    TupleElement(Vec<(usize, Self)>),
124    /// `Result<T, Uninhabited>`
125    Result(Box<Self>),
126    /// `ControlFlow<Uninhabited, T>`
127    ControlFlow(Box<Self>),
128    Array(Box<Self>, u64),
129    /// The root of the unused_closures lint.
130    Closure(Span),
131    /// The root of the unused_coroutines lint.
132    Coroutine(Span),
133}
134
135/// Returns `Some(path)` if `ty` should be considered as "`must_use`" in the context of `expr`
136/// (`expr` is used to get the parent module, which can affect which types are considered uninhabited).
137x;#[instrument(skip(cx, expr), level = "debug", ret)]
138pub fn is_ty_must_use<'tcx>(
139    cx: &LateContext<'tcx>,
140    ty: Ty<'tcx>,
141    expr: &hir::Expr<'_>,
142) -> IsTyMustUse {
143    if ty.is_unit() {
144        return IsTyMustUse::Trivial;
145    }
146
147    let parent_mod_did = cx.tcx.parent_module(expr.hir_id);
148    let is_uninhabited =
149        |t: Ty<'tcx>| !t.is_inhabited_from(cx.tcx, parent_mod_did, cx.typing_env());
150
151    match *ty.kind() {
152        _ if is_uninhabited(ty) => IsTyMustUse::Trivial,
153        ty::Adt(..) if let Some(boxed) = ty.boxed_ty() => {
154            is_ty_must_use(cx, boxed, expr).map(|inner| MustUsePath::Boxed(Box::new(inner)))
155        }
156        ty::Adt(def, args) if cx.tcx.is_lang_item(def.did(), LangItem::Pin) => {
157            let pinned_ty = args.type_at(0);
158            is_ty_must_use(cx, pinned_ty, expr).map(|inner| MustUsePath::Pinned(Box::new(inner)))
159        }
160        // Consider `Result<T, Uninhabited>` (e.g. `Result<(), !>`) equivalent to `T`.
161        ty::Adt(def, args)
162            if cx.tcx.is_diagnostic_item(sym::Result, def.did())
163                && is_uninhabited(args.type_at(1)) =>
164        {
165            let ok_ty = args.type_at(0);
166            is_ty_must_use(cx, ok_ty, expr).map(|path| MustUsePath::Result(Box::new(path)))
167        }
168        // Consider `ControlFlow<Uninhabited, T>` (e.g. `ControlFlow<!, ()>`) equivalent to `T`.
169        ty::Adt(def, args)
170            if cx.tcx.is_diagnostic_item(sym::ControlFlow, def.did())
171                && is_uninhabited(args.type_at(0)) =>
172        {
173            let continue_ty = args.type_at(1);
174            is_ty_must_use(cx, continue_ty, expr)
175                .map(|path| MustUsePath::ControlFlow(Box::new(path)))
176        }
177        ty::Adt(def, _) => {
178            is_def_must_use(cx, def.did(), expr.span).map_or(IsTyMustUse::No, IsTyMustUse::Yes)
179        }
180        ty::Alias(
181            _,
182            ty::AliasTy {
183                kind: ty::Opaque { def_id: def } | ty::Projection { def_id: def }, ..
184            },
185        ) => {
186            elaborate(
187                cx.tcx,
188                cx.tcx
189                    .explicit_item_self_bounds(def)
190                    .iter_identity_copied()
191                    .map(Unnormalized::skip_norm_wip),
192            )
193            // We only care about self bounds for the impl-trait
194            .filter_only_self()
195            .find_map(|(pred, _span)| {
196                // We only look at the `DefId`, so it is safe to skip the binder here.
197                if let ty::ClauseKind::Trait(ref poly_trait_predicate) = pred.kind().skip_binder() {
198                    let def_id = poly_trait_predicate.trait_ref.def_id;
199
200                    is_def_must_use(cx, def_id, expr.span)
201                } else {
202                    None
203                }
204            })
205            .map(|inner| MustUsePath::Opaque(Box::new(inner)))
206            .map_or(IsTyMustUse::No, IsTyMustUse::Yes)
207        }
208        ty::Dynamic(binders, _) => binders
209            .iter()
210            .find_map(|predicate| {
211                if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() {
212                    let def_id = trait_ref.def_id;
213                    is_def_must_use(cx, def_id, expr.span)
214                        .map(|inner| MustUsePath::TraitObject(Box::new(inner)))
215                } else {
216                    None
217                }
218            })
219            .map_or(IsTyMustUse::No, IsTyMustUse::Yes),
220        // NB: unit is checked up above; this is only reachable for tuples with at least one element
221        ty::Tuple(tys) => {
222            let elem_exprs = if let hir::ExprKind::Tup(elem_exprs) = expr.kind {
223                debug_assert_eq!(elem_exprs.len(), tys.len());
224                elem_exprs
225            } else {
226                &[]
227            };
228
229            // Default to `expr`.
230            let elem_exprs = elem_exprs.iter().chain(iter::repeat(expr));
231
232            let mut all_trivial = true;
233            let mut nested_must_use = Vec::new();
234
235            tys.iter().zip(elem_exprs).enumerate().for_each(|(i, (ty, expr))| {
236                let must_use = is_ty_must_use(cx, ty, expr);
237
238                all_trivial &= matches!(must_use, IsTyMustUse::Trivial);
239                if let IsTyMustUse::Yes(path) = must_use {
240                    nested_must_use.push((i, path));
241                }
242            });
243
244            if all_trivial {
245                // If all tuple elements are trivial, mark the whole tuple as such.
246                // i.e. don't emit `unused_results` for types such as `((), ())`
247                IsTyMustUse::Trivial
248            } else if !nested_must_use.is_empty() {
249                IsTyMustUse::Yes(MustUsePath::TupleElement(nested_must_use))
250            } else {
251                IsTyMustUse::No
252            }
253        }
254        ty::Array(ty, len) => match len.try_to_target_usize(cx.tcx) {
255            // If the array is empty we don't lint, to avoid false positives
256            Some(0) | None => IsTyMustUse::No,
257            // If the array is definitely non-empty, we can do `#[must_use]` checking.
258            Some(len) => {
259                is_ty_must_use(cx, ty, expr).map(|inner| MustUsePath::Array(Box::new(inner), len))
260            }
261        },
262        ty::Closure(..) | ty::CoroutineClosure(..) => {
263            IsTyMustUse::Yes(MustUsePath::Closure(expr.span))
264        }
265        ty::Coroutine(def_id, ..) => {
266            // async fn should be treated as "implementor of `Future`"
267            if cx.tcx.coroutine_is_async(def_id)
268                && let Some(def_id) = cx.tcx.lang_items().future_trait()
269            {
270                IsTyMustUse::Yes(MustUsePath::Opaque(Box::new(
271                    is_def_must_use(cx, def_id, expr.span)
272                        .expect("future trait is marked as `#[must_use]`"),
273                )))
274            } else {
275                IsTyMustUse::Yes(MustUsePath::Coroutine(expr.span))
276            }
277        }
278        _ => IsTyMustUse::No,
279    }
280}
281
282impl<'tcx> LateLintPass<'tcx> for UnusedResults {
283    fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
284        let hir::StmtKind::Semi(mut expr) = s.kind else {
285            return;
286        };
287
288        let mut expr_is_from_block = false;
289        while let hir::ExprKind::Block(blk, ..) = expr.kind
290            && let hir::Block { expr: Some(e), .. } = blk
291        {
292            expr = e;
293            expr_is_from_block = true;
294        }
295
296        if let hir::ExprKind::Ret(..) = expr.kind {
297            return;
298        }
299
300        if let hir::ExprKind::Match(await_expr, _arms, hir::MatchSource::AwaitDesugar) = expr.kind
301            && let ty = cx.typeck_results().expr_ty(await_expr)
302            && let ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id: future_def_id }, .. }) = ty.kind()
303            && cx.tcx.ty_is_opaque_future(ty)
304            && let async_fn_def_id = cx.tcx.parent(*future_def_id)
305            && #[allow(non_exhaustive_omitted_patterns)] match cx.tcx.def_kind(async_fn_def_id)
    {
    DefKind::Fn | DefKind::AssocFn => true,
    _ => false,
}matches!(cx.tcx.def_kind(async_fn_def_id), DefKind::Fn | DefKind::AssocFn)
306            // Check that this `impl Future` actually comes from an `async fn`
307            && cx.tcx.asyncness(async_fn_def_id).is_async()
308            && check_must_use_def(
309                cx,
310                async_fn_def_id,
311                expr.span,
312                "output of future returned by ",
313                "",
314                expr_is_from_block,
315            )
316        {
317            // We have a bare `foo().await;` on an opaque type from an async function that was
318            // annotated with `#[must_use]`.
319            return;
320        }
321
322        let ty = cx.typeck_results().expr_ty(expr);
323
324        let must_use_result = is_ty_must_use(cx, ty, expr);
325        let type_lint_emitted_or_trivial = match must_use_result {
326            IsTyMustUse::Yes(path) => {
327                emit_must_use_untranslated(cx, &path, "", "", 1, false, expr_is_from_block);
328                true
329            }
330            IsTyMustUse::Trivial => true,
331            IsTyMustUse::No => false,
332        };
333
334        let fn_warned = check_fn_must_use(cx, expr, expr_is_from_block);
335
336        if !fn_warned && type_lint_emitted_or_trivial {
337            // We don't warn about unused unit or uninhabited types.
338            // (See https://github.com/rust-lang/rust/issues/43806 for details.)
339            return;
340        }
341
342        let must_use_op = match expr.kind {
343            // Hardcoding operators here seemed more expedient than the
344            // refactoring that would be needed to look up the `#[must_use]`
345            // attribute which does exist on the comparison trait methods
346            hir::ExprKind::Binary(bin_op, ..) => match bin_op.node {
347                hir::BinOpKind::Eq
348                | hir::BinOpKind::Lt
349                | hir::BinOpKind::Le
350                | hir::BinOpKind::Ne
351                | hir::BinOpKind::Ge
352                | hir::BinOpKind::Gt => Some("comparison"),
353                hir::BinOpKind::Add
354                | hir::BinOpKind::Sub
355                | hir::BinOpKind::Div
356                | hir::BinOpKind::Mul
357                | hir::BinOpKind::Rem => Some("arithmetic operation"),
358                hir::BinOpKind::And | hir::BinOpKind::Or => Some("logical operation"),
359                hir::BinOpKind::BitXor
360                | hir::BinOpKind::BitAnd
361                | hir::BinOpKind::BitOr
362                | hir::BinOpKind::Shl
363                | hir::BinOpKind::Shr => Some("bitwise operation"),
364            },
365            hir::ExprKind::AddrOf(..) => Some("borrow"),
366            hir::ExprKind::OffsetOf(..) => Some("`offset_of` call"),
367            hir::ExprKind::Unary(..) => Some("unary operation"),
368            // The `offset_of` macro wraps its contents inside a `const` block.
369            hir::ExprKind::ConstBlock(block) => {
370                let body = cx.tcx.hir_body(block.body);
371                if let hir::ExprKind::Block(block, _) = body.value.kind
372                    && let Some(expr) = block.expr
373                    && let hir::ExprKind::OffsetOf(..) = expr.kind
374                {
375                    Some("`offset_of` call")
376                } else {
377                    None
378                }
379            }
380            _ => None,
381        };
382
383        let op_warned = match must_use_op {
384            Some(must_use_op) => {
385                let span = expr.span.find_ancestor_not_from_macro().unwrap_or(expr.span);
386                cx.emit_span_lint(
387                    UNUSED_MUST_USE,
388                    expr.span,
389                    UnusedOp {
390                        op: must_use_op,
391                        label: expr.span,
392                        suggestion: if expr_is_from_block {
393                            UnusedOpSuggestion::BlockTailExpr {
394                                before_span: span.shrink_to_lo(),
395                                after_span: span.shrink_to_hi(),
396                            }
397                        } else {
398                            UnusedOpSuggestion::NormalExpr { span: span.shrink_to_lo() }
399                        },
400                    },
401                );
402                true
403            }
404            None => false,
405        };
406
407        // Only emit unused results lint if we haven't emitted any of the more specific lints and the expression type is non trivial.
408        if !(type_lint_emitted_or_trivial || fn_warned || op_warned) {
409            cx.emit_span_lint(UNUSED_RESULTS, s.span, UnusedResult { ty });
410        }
411    }
412}
413
414/// Checks if `expr` is a \[method\] call expression marked as `#[must_use]` and emits a lint if so.
415/// Returns `true` if the lint has been emitted.
416fn check_fn_must_use(cx: &LateContext<'_>, expr: &hir::Expr<'_>, expr_is_from_block: bool) -> bool {
417    let maybe_def_id = match expr.kind {
418        hir::ExprKind::Call(callee, _) => {
419            if let hir::ExprKind::Path(ref qpath) = callee.kind
420                // `Res::Local` if it was a closure, for which we
421                // do not currently support must-use linting
422                && let Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) =
423                    cx.qpath_res(qpath, callee.hir_id)
424            {
425                Some(def_id)
426            } else {
427                None
428            }
429        }
430        hir::ExprKind::MethodCall(..) => cx.typeck_results().type_dependent_def_id(expr.hir_id),
431        _ => None,
432    };
433
434    match maybe_def_id {
435        Some(def_id) => {
436            check_must_use_def(cx, def_id, expr.span, "return value of ", "", expr_is_from_block)
437        }
438        None => false,
439    }
440}
441
442fn is_def_must_use(cx: &LateContext<'_>, def_id: DefId, span: Span) -> Option<MustUsePath> {
443    // check for #[must_use = "..."]
444    {
    {
        'done:
            {
            for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &cx.tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(MustUse { reason, .. })
                        => {
                        break 'done Some(reason);
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(cx.tcx, def_id, MustUse { reason, .. } => reason)
445        .map(|reason| MustUsePath::Def(span, def_id, *reason))
446}
447
448/// Returns whether further errors should be suppressed because a lint has been emitted.
449fn check_must_use_def(
450    cx: &LateContext<'_>,
451    def_id: DefId,
452    span: Span,
453    descr_pre_path: &str,
454    descr_post_path: &str,
455    expr_is_from_block: bool,
456) -> bool {
457    is_def_must_use(cx, def_id, span)
458        .map(|must_use_path| {
459            emit_must_use_untranslated(
460                cx,
461                &must_use_path,
462                descr_pre_path,
463                descr_post_path,
464                1,
465                false,
466                expr_is_from_block,
467            )
468        })
469        .is_some()
470}
471
472#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("emit_must_use_untranslated",
                                    "rustc_lint::unused::must_use", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_lint/src/unused/must_use.rs"),
                                    ::tracing_core::__macro_support::Option::Some(472u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_lint::unused::must_use"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("path")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("path");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("descr_pre")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("descr_pre");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("descr_post")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("descr_post");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("plural_len")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("plural_len");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("is_inner")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("is_inner");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("expr_is_from_block")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("expr_is_from_block");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&descr_pre as
                                                            &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&descr_post as
                                                            &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&plural_len as
                                                            &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&is_inner as
                                                            &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&expr_is_from_block
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let plural_suffix = if plural_len == 1 { "" } else { "s" };
            match path {
                MustUsePath::Boxed(path) => {
                    let descr_pre =
                        &::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("{0}boxed ", descr_pre))
                                });
                    emit_must_use_untranslated(cx, path, descr_pre, descr_post,
                        plural_len, true, expr_is_from_block);
                }
                MustUsePath::Pinned(path) => {
                    let descr_pre =
                        &::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("{0}pinned ", descr_pre))
                                });
                    emit_must_use_untranslated(cx, path, descr_pre, descr_post,
                        plural_len, true, expr_is_from_block);
                }
                MustUsePath::Opaque(path) => {
                    let descr_pre =
                        &::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("{0}implementer{1} of ",
                                            descr_pre, plural_suffix))
                                });
                    emit_must_use_untranslated(cx, path, descr_pre, descr_post,
                        plural_len, true, expr_is_from_block);
                }
                MustUsePath::TraitObject(path) => {
                    let descr_post =
                        &::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!(" trait object{0}{1}",
                                            plural_suffix, descr_post))
                                });
                    emit_must_use_untranslated(cx, path, descr_pre, descr_post,
                        plural_len, true, expr_is_from_block);
                }
                MustUsePath::TupleElement(elems) => {
                    for (index, path) in elems {
                        let descr_post =
                            &::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!(" in tuple element {0}",
                                                index))
                                    });
                        emit_must_use_untranslated(cx, path, descr_pre, descr_post,
                            plural_len, true, expr_is_from_block);
                    }
                }
                MustUsePath::Result(path) => {
                    let descr_post =
                        &::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!(" in a `Result` with an uninhabited error{0}",
                                            descr_post))
                                });
                    emit_must_use_untranslated(cx, path, descr_pre, descr_post,
                        plural_len, true, expr_is_from_block);
                }
                MustUsePath::ControlFlow(path) => {
                    let descr_post =
                        &::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!(" in a `ControlFlow` with an uninhabited break {0}",
                                            descr_post))
                                });
                    emit_must_use_untranslated(cx, path, descr_pre, descr_post,
                        plural_len, true, expr_is_from_block);
                }
                MustUsePath::Array(path, len) => {
                    let descr_pre =
                        &::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("{0}array{1} of ",
                                            descr_pre, plural_suffix))
                                });
                    emit_must_use_untranslated(cx, path, descr_pre, descr_post,
                        plural_len.saturating_add(usize::try_from(*len).unwrap_or(usize::MAX)),
                        true, expr_is_from_block);
                }
                MustUsePath::Closure(span) => {
                    cx.emit_span_lint(UNUSED_MUST_USE, *span,
                        UnusedClosure {
                            count: plural_len,
                            pre: descr_pre,
                            post: descr_post,
                        });
                }
                MustUsePath::Coroutine(span) => {
                    cx.emit_span_lint(UNUSED_MUST_USE, *span,
                        UnusedCoroutine {
                            count: plural_len,
                            pre: descr_pre,
                            post: descr_post,
                        });
                }
                MustUsePath::Def(span, def_id, reason) => {
                    let ancenstor_span =
                        span.find_ancestor_not_from_macro().unwrap_or(*span);
                    let is_redundant_let_ignore =
                        cx.sess().source_map().span_to_prev_source(ancenstor_span).ok().map(|prev|
                                    prev.trim_end().ends_with("let _ =")).unwrap_or(false);
                    let suggestion_span =
                        if is_redundant_let_ignore {
                            *span
                        } else { ancenstor_span };
                    cx.emit_span_lint(UNUSED_MUST_USE, ancenstor_span,
                        UnusedDef {
                            pre: descr_pre,
                            post: descr_post,
                            cx,
                            def_id: *def_id,
                            note: *reason,
                            suggestion: (!is_inner).then_some(if expr_is_from_block {
                                    UnusedDefSuggestion::BlockTailExpr {
                                        before_span: suggestion_span.shrink_to_lo(),
                                        after_span: suggestion_span.shrink_to_hi(),
                                    }
                                } else {
                                    UnusedDefSuggestion::NormalExpr {
                                        span: suggestion_span.shrink_to_lo(),
                                    }
                                }),
                        });
                }
            }
        }
    }
}#[instrument(skip(cx), level = "debug")]
473fn emit_must_use_untranslated(
474    cx: &LateContext<'_>,
475    path: &MustUsePath,
476    descr_pre: &str,
477    descr_post: &str,
478    plural_len: usize,
479    is_inner: bool,
480    expr_is_from_block: bool,
481) {
482    let plural_suffix = pluralize!(plural_len);
483
484    match path {
485        MustUsePath::Boxed(path) => {
486            let descr_pre = &format!("{descr_pre}boxed ");
487            emit_must_use_untranslated(
488                cx,
489                path,
490                descr_pre,
491                descr_post,
492                plural_len,
493                true,
494                expr_is_from_block,
495            );
496        }
497        MustUsePath::Pinned(path) => {
498            let descr_pre = &format!("{descr_pre}pinned ");
499            emit_must_use_untranslated(
500                cx,
501                path,
502                descr_pre,
503                descr_post,
504                plural_len,
505                true,
506                expr_is_from_block,
507            );
508        }
509        MustUsePath::Opaque(path) => {
510            let descr_pre = &format!("{descr_pre}implementer{plural_suffix} of ");
511            emit_must_use_untranslated(
512                cx,
513                path,
514                descr_pre,
515                descr_post,
516                plural_len,
517                true,
518                expr_is_from_block,
519            );
520        }
521        MustUsePath::TraitObject(path) => {
522            let descr_post = &format!(" trait object{plural_suffix}{descr_post}");
523            emit_must_use_untranslated(
524                cx,
525                path,
526                descr_pre,
527                descr_post,
528                plural_len,
529                true,
530                expr_is_from_block,
531            );
532        }
533        MustUsePath::TupleElement(elems) => {
534            for (index, path) in elems {
535                let descr_post = &format!(" in tuple element {index}");
536                emit_must_use_untranslated(
537                    cx,
538                    path,
539                    descr_pre,
540                    descr_post,
541                    plural_len,
542                    true,
543                    expr_is_from_block,
544                );
545            }
546        }
547        MustUsePath::Result(path) => {
548            let descr_post = &format!(" in a `Result` with an uninhabited error{descr_post}");
549            emit_must_use_untranslated(
550                cx,
551                path,
552                descr_pre,
553                descr_post,
554                plural_len,
555                true,
556                expr_is_from_block,
557            );
558        }
559        MustUsePath::ControlFlow(path) => {
560            let descr_post = &format!(" in a `ControlFlow` with an uninhabited break {descr_post}");
561            emit_must_use_untranslated(
562                cx,
563                path,
564                descr_pre,
565                descr_post,
566                plural_len,
567                true,
568                expr_is_from_block,
569            );
570        }
571        MustUsePath::Array(path, len) => {
572            let descr_pre = &format!("{descr_pre}array{plural_suffix} of ");
573            emit_must_use_untranslated(
574                cx,
575                path,
576                descr_pre,
577                descr_post,
578                plural_len.saturating_add(usize::try_from(*len).unwrap_or(usize::MAX)),
579                true,
580                expr_is_from_block,
581            );
582        }
583        MustUsePath::Closure(span) => {
584            cx.emit_span_lint(
585                UNUSED_MUST_USE,
586                *span,
587                UnusedClosure { count: plural_len, pre: descr_pre, post: descr_post },
588            );
589        }
590        MustUsePath::Coroutine(span) => {
591            cx.emit_span_lint(
592                UNUSED_MUST_USE,
593                *span,
594                UnusedCoroutine { count: plural_len, pre: descr_pre, post: descr_post },
595            );
596        }
597        MustUsePath::Def(span, def_id, reason) => {
598            let ancenstor_span = span.find_ancestor_not_from_macro().unwrap_or(*span);
599            let is_redundant_let_ignore = cx
600                .sess()
601                .source_map()
602                .span_to_prev_source(ancenstor_span)
603                .ok()
604                .map(|prev| prev.trim_end().ends_with("let _ ="))
605                .unwrap_or(false);
606            let suggestion_span = if is_redundant_let_ignore { *span } else { ancenstor_span };
607            cx.emit_span_lint(
608                UNUSED_MUST_USE,
609                ancenstor_span,
610                UnusedDef {
611                    pre: descr_pre,
612                    post: descr_post,
613                    cx,
614                    def_id: *def_id,
615                    note: *reason,
616                    suggestion: (!is_inner).then_some(if expr_is_from_block {
617                        UnusedDefSuggestion::BlockTailExpr {
618                            before_span: suggestion_span.shrink_to_lo(),
619                            after_span: suggestion_span.shrink_to_hi(),
620                        }
621                    } else {
622                        UnusedDefSuggestion::NormalExpr { span: suggestion_span.shrink_to_lo() }
623                    }),
624                },
625            );
626        }
627    }
628}