Skip to main content

rustc_lint/unused/
must_use.rs

1use std::iter;
2
3use rustc_attr_ir::find_attr;
4use rustc_attr_ir::lang_items::LangItem;
5use rustc_errors::pluralize;
6use rustc_hir as hir;
7use rustc_hir::def::{DefKind, Res};
8use rustc_hir::def_id::DefId;
9use rustc_infer::traits::util::elaborate;
10use rustc_lint_defs::{declare_lint, declare_lint_pass};
11use rustc_middle::ty::consts::ConstExt;
12use rustc_middle::ty::{self, Ty, Unnormalized};
13use rustc_span::{Span, Symbol, sym};
14use tracing::instrument;
15
16use crate::diagnostics::{
17    UnusedClosure, UnusedCoroutine, UnusedDef, UnusedDefSuggestion, UnusedOp, UnusedOpSuggestion,
18    UnusedResult,
19};
20use crate::{LateContext, LateLintPass, LintContext};
21
22#[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! {
23    /// The `unused_must_use` lint detects unused result of a type flagged as
24    /// `#[must_use]`.
25    ///
26    /// ### Example
27    ///
28    /// ```rust
29    /// fn returns_result() -> Result<(), ()> {
30    ///     Ok(())
31    /// }
32    ///
33    /// fn main() {
34    ///     returns_result();
35    /// }
36    /// ```
37    ///
38    /// {{produces}}
39    ///
40    /// ### Explanation
41    ///
42    /// The `#[must_use]` attribute is an indicator that it is a mistake to
43    /// ignore the value. See [the reference] for more details.
44    ///
45    /// [the reference]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
46    pub UNUSED_MUST_USE,
47    Warn,
48    "unused result of a type flagged as `#[must_use]`",
49    report_in_external_macro
50}
51
52#[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! {
53    /// The `unused_results` lint checks for the unused result of an
54    /// expression in a statement.
55    ///
56    /// ### Example
57    ///
58    /// ```rust,compile_fail
59    /// #![deny(unused_results)]
60    /// fn foo<T>() -> T { panic!() }
61    ///
62    /// fn main() {
63    ///     foo::<usize>();
64    /// }
65    /// ```
66    ///
67    /// {{produces}}
68    ///
69    /// ### Explanation
70    ///
71    /// Ignoring the return value of a function may indicate a mistake. In
72    /// cases were it is almost certain that the result should be used, it is
73    /// recommended to annotate the function with the [`must_use` attribute].
74    /// Failure to use such a return value will trigger the [`unused_must_use`
75    /// lint] which is warn-by-default. The `unused_results` lint is
76    /// essentially the same, but triggers for *all* return values.
77    ///
78    /// This lint is "allow" by default because it can be noisy, and may not be
79    /// an actual problem. For example, calling the `remove` method of a `Vec`
80    /// or `HashMap` returns the previous value, which you may not care about.
81    /// Using this lint would require explicitly ignoring or discarding such
82    /// values.
83    ///
84    /// [`must_use` attribute]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
85    /// [`unused_must_use` lint]: warn-by-default.html#unused-must-use
86    pub UNUSED_RESULTS,
87    Allow,
88    "unused result of an expression in a statement"
89}
90
91pub 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) -> Self { *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]);
92
93/// Must the type be used?
94#[derive(#[automatically_derived]
impl ::core::fmt::Debug for IsTyMustUse {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Yes(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Yes",
                    &__self_0),
            Self::No => ::core::fmt::Formatter::write_str(f, "No"),
            Self::Trivial => ::core::fmt::Formatter::write_str(f, "Trivial"),
        }
    }
}Debug)]
95pub enum IsTyMustUse {
96    /// Yes, `MustUsePath` contains an explanation for why the type must be used.
97    /// This will result in `unused_must_use` lint.
98    Yes(MustUsePath),
99    /// No, an ordinary type that may be ignored.
100    /// This will result in `unused_results` lint.
101    No,
102    /// No, the type is trivial and thus should always be ignored.
103    /// (this suppresses `unused_results` lint)
104    Trivial,
105}
106
107impl IsTyMustUse {
108    fn map(self, f: impl FnOnce(MustUsePath) -> MustUsePath) -> Self {
109        match self {
110            Self::Yes(must_use_path) => Self::Yes(f(must_use_path)),
111            _ => self,
112        }
113    }
114}
115
116/// A path through a type to a `must_use` source. Contains useful info for the lint.
117#[derive(#[automatically_derived]
impl ::core::fmt::Debug for MustUsePath {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Def(__self_0, __self_1, __self_2) =>
                ::core::fmt::Formatter::debug_tuple_field3_finish(f, "Def",
                    __self_0, __self_1, &__self_2),
            Self::Boxed(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Boxed",
                    &__self_0),
            Self::Pinned(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Pinned",
                    &__self_0),
            Self::Opaque(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Opaque",
                    &__self_0),
            Self::TraitObject(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "TraitObject", &__self_0),
            Self::TupleElement(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "TupleElement", &__self_0),
            Self::Result(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Result",
                    &__self_0),
            Self::ControlFlow(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ControlFlow", &__self_0),
            Self::Array(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f, "Array",
                    __self_0, &__self_1),
            Self::Closure(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Closure", &__self_0),
            Self::Coroutine(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Coroutine", &__self_0),
        }
    }
}Debug)]
118pub enum MustUsePath {
119    /// The root of the normal `must_use` lint with an optional message.
120    Def(Span, DefId, Option<Symbol>),
121    Boxed(Box<Self>),
122    Pinned(Box<Self>),
123    Opaque(Box<Self>),
124    TraitObject(Box<Self>),
125    TupleElement(Vec<(usize, Self)>),
126    /// `Result<T, Uninhabited>`
127    Result(Box<Self>),
128    /// `ControlFlow<Uninhabited, T>`
129    ControlFlow(Box<Self>),
130    Array(Box<Self>, u64),
131    /// The root of the unused_closures lint.
132    Closure(Span),
133    /// The root of the unused_coroutines lint.
134    Coroutine(Span),
135}
136
137/// Returns `Some(path)` if `ty` should be considered as "`must_use`" in the context of `expr`
138/// (`expr` is used to get the parent module, which can affect which types are considered uninhabited).
139{}
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("is_ty_must_use",
                                "rustc_lint::unused::must_use", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/2311729bc1fb3f2e001e5c52c45eac94019a4fd5/compiler/rustc_lint/src/unused/must_use.rs"),
                                ::tracing_core::__macro_support::Option::Some(139u32),
                                ::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("ty")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("ty");
                                                    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(&ty)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[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: IsTyMustUse = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        if ty.is_unit() { return IsTyMustUse::Trivial; }
                        let parent_mod_did = cx.tcx.parent_module(expr.hir_id);
                        let is_uninhabited =
                            |t: Ty<'tcx>|
                                !t.is_inhabited_from(cx.tcx, parent_mod_did,
                                        cx.typing_env());
                        match *ty.kind() {
                            _ if is_uninhabited(ty) => IsTyMustUse::Trivial,
                            ty::Adt(..) if let Some(boxed) = ty.boxed_ty() => {
                                is_ty_must_use(cx, boxed,
                                        expr).map(|inner| MustUsePath::Boxed(Box::new(inner)))
                            }
                            ty::Adt(def, args) if
                                cx.tcx.is_lang_item(def.did(), LangItem::Pin) => {
                                let pinned_ty = args.type_at(0);
                                is_ty_must_use(cx, pinned_ty,
                                        expr).map(|inner| MustUsePath::Pinned(Box::new(inner)))
                            }
                            ty::Adt(def, args) if
                                cx.tcx.is_diagnostic_item(sym::Result, def.did()) &&
                                    is_uninhabited(args.type_at(1)) => {
                                let ok_ty = args.type_at(0);
                                is_ty_must_use(cx, ok_ty,
                                        expr).map(|path| MustUsePath::Result(Box::new(path)))
                            }
                            ty::Adt(def, args) if
                                cx.tcx.is_diagnostic_item(sym::ControlFlow, def.did()) &&
                                    is_uninhabited(args.type_at(0)) => {
                                let continue_ty = args.type_at(1);
                                is_ty_must_use(cx, continue_ty,
                                        expr).map(|path| MustUsePath::ControlFlow(Box::new(path)))
                            }
                            ty::Adt(def, _) => {
                                is_def_must_use(cx, def.did(),
                                        expr.span).map_or(IsTyMustUse::No, IsTyMustUse::Yes)
                            }
                            ty::Alias(_, ty::AliasTy {
                                kind: ty::Opaque { def_id: def } | ty::Projection {
                                    def_id: def }, .. }) => {
                                elaborate(cx.tcx,
                                                    cx.tcx.explicit_item_self_bounds(def).iter_identity_copied().map(Unnormalized::skip_norm_wip)).filter_only_self().find_map(|(pred,
                                                    _span)|
                                                {
                                                    if let ty::ClauseKind::Trait(ref poly_trait_predicate) =
                                                            pred.kind().skip_binder() {
                                                        let def_id = poly_trait_predicate.trait_ref.def_id;
                                                        is_def_must_use(cx, def_id, expr.span)
                                                    } else { None }
                                                }).map(|inner|
                                            MustUsePath::Opaque(Box::new(inner))).map_or(IsTyMustUse::No,
                                    IsTyMustUse::Yes)
                            }
                            ty::Dynamic(binders, _) =>
                                binders.iter().find_map(|predicate|
                                            {
                                                if let ty::ExistentialPredicate::Trait(ref trait_ref) =
                                                        predicate.skip_binder() {
                                                    let def_id = trait_ref.def_id;
                                                    is_def_must_use(cx, def_id,
                                                            expr.span).map(|inner|
                                                            MustUsePath::TraitObject(Box::new(inner)))
                                                } else { None }
                                            }).map_or(IsTyMustUse::No, IsTyMustUse::Yes),
                            ty::Tuple(tys) => {
                                let elem_exprs =
                                    if let hir::ExprKind::Tup(elem_exprs) = expr.kind {
                                        if true {
                                            {
                                                match (&elem_exprs.len(), &tys.len()) {
                                                    (left_val, right_val) => {
                                                        if !(*left_val == *right_val) {
                                                            let kind = ::core::panicking::AssertKind::Eq;
                                                            ::core::panicking::assert_failed(kind, &*left_val,
                                                                &*right_val, ::core::option::Option::None);
                                                        }
                                                    }
                                                }
                                            };
                                        };
                                        elem_exprs
                                    } else { &[] };
                                let elem_exprs =
                                    elem_exprs.iter().chain(iter::repeat(expr));
                                let mut all_trivial = true;
                                let mut nested_must_use = Vec::new();
                                tys.iter().zip(elem_exprs).enumerate().for_each(|(i,
                                            (ty, expr))|
                                        {
                                            let must_use = is_ty_must_use(cx, ty, expr);
                                            all_trivial &=
                                                #[allow(non_exhaustive_omitted_patterns)] match must_use {
                                                    IsTyMustUse::Trivial => true,
                                                    _ => false,
                                                };
                                            if let IsTyMustUse::Yes(path) = must_use {
                                                nested_must_use.push((i, path));
                                            }
                                        });
                                if all_trivial {
                                    IsTyMustUse::Trivial
                                } else if !nested_must_use.is_empty() {
                                    IsTyMustUse::Yes(MustUsePath::TupleElement(nested_must_use))
                                } else { IsTyMustUse::No }
                            }
                            ty::Array(ty, len) =>
                                match len.try_to_target_usize(cx.tcx) {
                                    Some(0) | None => IsTyMustUse::No,
                                    Some(len) => {
                                        is_ty_must_use(cx, ty,
                                                expr).map(|inner| MustUsePath::Array(Box::new(inner), len))
                                    }
                                },
                            ty::Closure(..) | ty::CoroutineClosure(..) => {
                                IsTyMustUse::Yes(MustUsePath::Closure(expr.span))
                            }
                            ty::Coroutine(def_id, ..) => {
                                if cx.tcx.coroutine_is_async(def_id) &&
                                        let Some(def_id) = cx.tcx.lang_items().future_trait() {
                                    IsTyMustUse::Yes(MustUsePath::Opaque(Box::new(is_def_must_use(cx,
                                                        def_id,
                                                        expr.span).expect("future trait is marked as `#[must_use]`"))))
                                } else {
                                    IsTyMustUse::Yes(MustUsePath::Coroutine(expr.span))
                                }
                            }
                            _ => IsTyMustUse::No,
                        }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/2311729bc1fb3f2e001e5c52c45eac94019a4fd5/compiler/rustc_lint/src/unused/must_use.rs:139",
                        "rustc_lint::unused::must_use", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/2311729bc1fb3f2e001e5c52c45eac94019a4fd5/compiler/rustc_lint/src/unused/must_use.rs"),
                        ::tracing_core::__macro_support::Option::Some(139u32),
                        ::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("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(skip(cx, expr), level = "debug", ret)]
140pub fn is_ty_must_use<'tcx>(
141    cx: &LateContext<'tcx>,
142    ty: Ty<'tcx>,
143    expr: &hir::Expr<'_>,
144) -> IsTyMustUse {
145    if ty.is_unit() {
146        return IsTyMustUse::Trivial;
147    }
148
149    let parent_mod_did = cx.tcx.parent_module(expr.hir_id);
150    let is_uninhabited =
151        |t: Ty<'tcx>| !t.is_inhabited_from(cx.tcx, parent_mod_did, cx.typing_env());
152
153    match *ty.kind() {
154        _ if is_uninhabited(ty) => IsTyMustUse::Trivial,
155        ty::Adt(..) if let Some(boxed) = ty.boxed_ty() => {
156            is_ty_must_use(cx, boxed, expr).map(|inner| MustUsePath::Boxed(Box::new(inner)))
157        }
158        ty::Adt(def, args) if cx.tcx.is_lang_item(def.did(), LangItem::Pin) => {
159            let pinned_ty = args.type_at(0);
160            is_ty_must_use(cx, pinned_ty, expr).map(|inner| MustUsePath::Pinned(Box::new(inner)))
161        }
162        // Consider `Result<T, Uninhabited>` (e.g. `Result<(), !>`) equivalent to `T`.
163        ty::Adt(def, args)
164            if cx.tcx.is_diagnostic_item(sym::Result, def.did())
165                && is_uninhabited(args.type_at(1)) =>
166        {
167            let ok_ty = args.type_at(0);
168            is_ty_must_use(cx, ok_ty, expr).map(|path| MustUsePath::Result(Box::new(path)))
169        }
170        // Consider `ControlFlow<Uninhabited, T>` (e.g. `ControlFlow<!, ()>`) equivalent to `T`.
171        ty::Adt(def, args)
172            if cx.tcx.is_diagnostic_item(sym::ControlFlow, def.did())
173                && is_uninhabited(args.type_at(0)) =>
174        {
175            let continue_ty = args.type_at(1);
176            is_ty_must_use(cx, continue_ty, expr)
177                .map(|path| MustUsePath::ControlFlow(Box::new(path)))
178        }
179        ty::Adt(def, _) => {
180            is_def_must_use(cx, def.did(), expr.span).map_or(IsTyMustUse::No, IsTyMustUse::Yes)
181        }
182        ty::Alias(
183            _,
184            ty::AliasTy {
185                kind: ty::Opaque { def_id: def } | ty::Projection { def_id: def }, ..
186            },
187        ) => {
188            elaborate(
189                cx.tcx,
190                cx.tcx
191                    .explicit_item_self_bounds(def)
192                    .iter_identity_copied()
193                    .map(Unnormalized::skip_norm_wip),
194            )
195            // We only care about self bounds for the impl-trait
196            .filter_only_self()
197            .find_map(|(pred, _span)| {
198                // We only look at the `DefId`, so it is safe to skip the binder here.
199                if let ty::ClauseKind::Trait(ref poly_trait_predicate) = pred.kind().skip_binder() {
200                    let def_id = poly_trait_predicate.trait_ref.def_id;
201
202                    is_def_must_use(cx, def_id, expr.span)
203                } else {
204                    None
205                }
206            })
207            .map(|inner| MustUsePath::Opaque(Box::new(inner)))
208            .map_or(IsTyMustUse::No, IsTyMustUse::Yes)
209        }
210        ty::Dynamic(binders, _) => binders
211            .iter()
212            .find_map(|predicate| {
213                if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() {
214                    let def_id = trait_ref.def_id;
215                    is_def_must_use(cx, def_id, expr.span)
216                        .map(|inner| MustUsePath::TraitObject(Box::new(inner)))
217                } else {
218                    None
219                }
220            })
221            .map_or(IsTyMustUse::No, IsTyMustUse::Yes),
222        // NB: unit is checked up above; this is only reachable for tuples with at least one element
223        ty::Tuple(tys) => {
224            let elem_exprs = if let hir::ExprKind::Tup(elem_exprs) = expr.kind {
225                debug_assert_eq!(elem_exprs.len(), tys.len());
226                elem_exprs
227            } else {
228                &[]
229            };
230
231            // Default to `expr`.
232            let elem_exprs = elem_exprs.iter().chain(iter::repeat(expr));
233
234            let mut all_trivial = true;
235            let mut nested_must_use = Vec::new();
236
237            tys.iter().zip(elem_exprs).enumerate().for_each(|(i, (ty, expr))| {
238                let must_use = is_ty_must_use(cx, ty, expr);
239
240                all_trivial &= matches!(must_use, IsTyMustUse::Trivial);
241                if let IsTyMustUse::Yes(path) = must_use {
242                    nested_must_use.push((i, path));
243                }
244            });
245
246            if all_trivial {
247                // If all tuple elements are trivial, mark the whole tuple as such.
248                // i.e. don't emit `unused_results` for types such as `((), ())`
249                IsTyMustUse::Trivial
250            } else if !nested_must_use.is_empty() {
251                IsTyMustUse::Yes(MustUsePath::TupleElement(nested_must_use))
252            } else {
253                IsTyMustUse::No
254            }
255        }
256        ty::Array(ty, len) => match len.try_to_target_usize(cx.tcx) {
257            // If the array is empty we don't lint, to avoid false positives
258            Some(0) | None => IsTyMustUse::No,
259            // If the array is definitely non-empty, we can do `#[must_use]` checking.
260            Some(len) => {
261                is_ty_must_use(cx, ty, expr).map(|inner| MustUsePath::Array(Box::new(inner), len))
262            }
263        },
264        ty::Closure(..) | ty::CoroutineClosure(..) => {
265            IsTyMustUse::Yes(MustUsePath::Closure(expr.span))
266        }
267        ty::Coroutine(def_id, ..) => {
268            // async fn should be treated as "implementor of `Future`"
269            if cx.tcx.coroutine_is_async(def_id)
270                && let Some(def_id) = cx.tcx.lang_items().future_trait()
271            {
272                IsTyMustUse::Yes(MustUsePath::Opaque(Box::new(
273                    is_def_must_use(cx, def_id, expr.span)
274                        .expect("future trait is marked as `#[must_use]`"),
275                )))
276            } else {
277                IsTyMustUse::Yes(MustUsePath::Coroutine(expr.span))
278            }
279        }
280        _ => IsTyMustUse::No,
281    }
282}
283
284impl<'tcx> LateLintPass<'tcx> for UnusedResults {
285    fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
286        let hir::StmtKind::Semi(mut expr) = s.kind else {
287            return;
288        };
289
290        let mut expr_is_from_block = false;
291        while let hir::ExprKind::Block(blk, ..) = expr.kind
292            && let hir::Block { expr: Some(e), .. } = blk
293        {
294            expr = e;
295            expr_is_from_block = true;
296        }
297
298        if let hir::ExprKind::Ret(..) = expr.kind {
299            return;
300        }
301
302        if let hir::ExprKind::Match(await_expr, _arms, hir::MatchSource::AwaitDesugar) = expr.kind
303            && let ty = cx.typeck_results().expr_ty(await_expr)
304            && let ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id: future_def_id }, .. }) = ty.kind()
305            && cx.tcx.ty_is_opaque_future(ty)
306            && let async_fn_def_id = cx.tcx.parent(*future_def_id)
307            && #[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)
308            // Check that this `impl Future` actually comes from an `async fn`
309            && cx.tcx.asyncness(async_fn_def_id).is_async()
310            && check_must_use_def(
311                cx,
312                async_fn_def_id,
313                expr.span,
314                "output of future returned by ",
315                "",
316                expr_is_from_block,
317            )
318        {
319            // We have a bare `foo().await;` on an opaque type from an async function that was
320            // annotated with `#[must_use]`.
321            return;
322        }
323
324        let ty = cx.typeck_results().expr_ty(expr);
325
326        let must_use_result = is_ty_must_use(cx, ty, expr);
327        let type_lint_emitted_or_trivial = match must_use_result {
328            IsTyMustUse::Yes(path) => {
329                emit_must_use_untranslated(cx, &path, "", "", 1, false, expr_is_from_block);
330                true
331            }
332            IsTyMustUse::Trivial => true,
333            IsTyMustUse::No => false,
334        };
335
336        let fn_warned = check_fn_must_use(cx, expr, expr_is_from_block);
337
338        if !fn_warned && type_lint_emitted_or_trivial {
339            // We don't warn about unused unit or uninhabited types.
340            // (See https://github.com/rust-lang/rust/issues/43806 for details.)
341            return;
342        }
343
344        let must_use_op = match expr.kind {
345            // Hardcoding operators here seemed more expedient than the
346            // refactoring that would be needed to look up the `#[must_use]`
347            // attribute which does exist on the comparison trait methods
348            hir::ExprKind::Binary(bin_op, ..) => match bin_op.node {
349                hir::BinOpKind::Eq
350                | hir::BinOpKind::Lt
351                | hir::BinOpKind::Le
352                | hir::BinOpKind::Ne
353                | hir::BinOpKind::Ge
354                | hir::BinOpKind::Gt => Some("comparison"),
355                hir::BinOpKind::Add
356                | hir::BinOpKind::Sub
357                | hir::BinOpKind::Div
358                | hir::BinOpKind::Mul
359                | hir::BinOpKind::Rem => Some("arithmetic operation"),
360                hir::BinOpKind::And | hir::BinOpKind::Or => Some("logical operation"),
361                hir::BinOpKind::BitXor
362                | hir::BinOpKind::BitAnd
363                | hir::BinOpKind::BitOr
364                | hir::BinOpKind::Shl
365                | hir::BinOpKind::Shr => Some("bitwise operation"),
366            },
367            hir::ExprKind::AddrOf(..) => Some("borrow"),
368            hir::ExprKind::OffsetOf(..) => Some("`offset_of` call"),
369            hir::ExprKind::Unary(..) => Some("unary operation"),
370            // The `offset_of` macro wraps its contents inside a `const` block.
371            hir::ExprKind::ConstBlock(block) => {
372                let body = cx.tcx.hir_body(block.body);
373                if let hir::ExprKind::Block(block, _) = body.value.kind
374                    && let Some(expr) = block.expr
375                    && let hir::ExprKind::OffsetOf(..) = expr.kind
376                {
377                    Some("`offset_of` call")
378                } else {
379                    None
380                }
381            }
382            _ => None,
383        };
384
385        let op_warned = match must_use_op {
386            Some(must_use_op) => {
387                let span = expr.span.find_ancestor_not_from_macro().unwrap_or(expr.span);
388                cx.emit_span_lint(
389                    UNUSED_MUST_USE,
390                    expr.span,
391                    UnusedOp {
392                        op: must_use_op,
393                        label: expr.span,
394                        suggestion: if expr_is_from_block {
395                            UnusedOpSuggestion::BlockTailExpr {
396                                before_span: span.shrink_to_lo(),
397                                after_span: span.shrink_to_hi(),
398                            }
399                        } else {
400                            UnusedOpSuggestion::NormalExpr { span: span.shrink_to_lo() }
401                        },
402                    },
403                );
404                true
405            }
406            None => false,
407        };
408
409        // Only emit unused results lint if we haven't emitted any of the more specific lints and the expression type is non trivial.
410        if !(type_lint_emitted_or_trivial || fn_warned || op_warned) {
411            cx.emit_span_lint(UNUSED_RESULTS, s.span, UnusedResult { ty });
412        }
413    }
414}
415
416/// Checks if `expr` is a \[method\] call expression marked as `#[must_use]` and emits a lint if so.
417/// Returns `true` if the lint has been emitted.
418fn check_fn_must_use(cx: &LateContext<'_>, expr: &hir::Expr<'_>, expr_is_from_block: bool) -> bool {
419    let maybe_def_id = match expr.kind {
420        hir::ExprKind::Call(callee, _) => {
421            if let hir::ExprKind::Path(ref qpath) = callee.kind
422                // `Res::Local` if it was a closure, for which we
423                // do not currently support must-use linting
424                && let Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) =
425                    cx.qpath_res(qpath, callee.hir_id)
426            {
427                Some(def_id)
428            } else {
429                None
430            }
431        }
432        hir::ExprKind::MethodCall(..) => cx.typeck_results().type_dependent_def_id(expr.hir_id),
433        _ => None,
434    };
435
436    match maybe_def_id {
437        Some(def_id) => {
438            check_must_use_def(cx, def_id, expr.span, "return value of ", "", expr_is_from_block)
439        }
440        None => false,
441    }
442}
443
444fn is_def_must_use(cx: &LateContext<'_>, def_id: DefId, span: Span) -> Option<MustUsePath> {
445    // check for #[must_use = "..."]
446    {
    {
        '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)
447        .map(|reason| MustUsePath::Def(span, def_id, *reason))
448}
449
450/// Returns whether further errors should be suppressed because a lint has been emitted.
451fn check_must_use_def(
452    cx: &LateContext<'_>,
453    def_id: DefId,
454    span: Span,
455    descr_pre_path: &str,
456    descr_post_path: &str,
457    expr_is_from_block: bool,
458) -> bool {
459    is_def_must_use(cx, def_id, span)
460        .map(|must_use_path| {
461            emit_must_use_untranslated(
462                cx,
463                &must_use_path,
464                descr_pre_path,
465                descr_post_path,
466                1,
467                false,
468                expr_is_from_block,
469            )
470        })
471        .is_some()
472}
473
474{}
#[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("/rustc-dev/2311729bc1fb3f2e001e5c52c45eac94019a4fd5/compiler/rustc_lint/src/unused/must_use.rs"),
                                    ::tracing_core::__macro_support::Option::Some(474u32),
                                    ::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")]
475fn emit_must_use_untranslated(
476    cx: &LateContext<'_>,
477    path: &MustUsePath,
478    descr_pre: &str,
479    descr_post: &str,
480    plural_len: usize,
481    is_inner: bool,
482    expr_is_from_block: bool,
483) {
484    let plural_suffix = pluralize!(plural_len);
485
486    match path {
487        MustUsePath::Boxed(path) => {
488            let descr_pre = &format!("{descr_pre}boxed ");
489            emit_must_use_untranslated(
490                cx,
491                path,
492                descr_pre,
493                descr_post,
494                plural_len,
495                true,
496                expr_is_from_block,
497            );
498        }
499        MustUsePath::Pinned(path) => {
500            let descr_pre = &format!("{descr_pre}pinned ");
501            emit_must_use_untranslated(
502                cx,
503                path,
504                descr_pre,
505                descr_post,
506                plural_len,
507                true,
508                expr_is_from_block,
509            );
510        }
511        MustUsePath::Opaque(path) => {
512            let descr_pre = &format!("{descr_pre}implementer{plural_suffix} of ");
513            emit_must_use_untranslated(
514                cx,
515                path,
516                descr_pre,
517                descr_post,
518                plural_len,
519                true,
520                expr_is_from_block,
521            );
522        }
523        MustUsePath::TraitObject(path) => {
524            let descr_post = &format!(" trait object{plural_suffix}{descr_post}");
525            emit_must_use_untranslated(
526                cx,
527                path,
528                descr_pre,
529                descr_post,
530                plural_len,
531                true,
532                expr_is_from_block,
533            );
534        }
535        MustUsePath::TupleElement(elems) => {
536            for (index, path) in elems {
537                let descr_post = &format!(" in tuple element {index}");
538                emit_must_use_untranslated(
539                    cx,
540                    path,
541                    descr_pre,
542                    descr_post,
543                    plural_len,
544                    true,
545                    expr_is_from_block,
546                );
547            }
548        }
549        MustUsePath::Result(path) => {
550            let descr_post = &format!(" in a `Result` with an uninhabited error{descr_post}");
551            emit_must_use_untranslated(
552                cx,
553                path,
554                descr_pre,
555                descr_post,
556                plural_len,
557                true,
558                expr_is_from_block,
559            );
560        }
561        MustUsePath::ControlFlow(path) => {
562            let descr_post = &format!(" in a `ControlFlow` with an uninhabited break {descr_post}");
563            emit_must_use_untranslated(
564                cx,
565                path,
566                descr_pre,
567                descr_post,
568                plural_len,
569                true,
570                expr_is_from_block,
571            );
572        }
573        MustUsePath::Array(path, len) => {
574            let descr_pre = &format!("{descr_pre}array{plural_suffix} of ");
575            emit_must_use_untranslated(
576                cx,
577                path,
578                descr_pre,
579                descr_post,
580                plural_len.saturating_add(usize::try_from(*len).unwrap_or(usize::MAX)),
581                true,
582                expr_is_from_block,
583            );
584        }
585        MustUsePath::Closure(span) => {
586            cx.emit_span_lint(
587                UNUSED_MUST_USE,
588                *span,
589                UnusedClosure { count: plural_len, pre: descr_pre, post: descr_post },
590            );
591        }
592        MustUsePath::Coroutine(span) => {
593            cx.emit_span_lint(
594                UNUSED_MUST_USE,
595                *span,
596                UnusedCoroutine { count: plural_len, pre: descr_pre, post: descr_post },
597            );
598        }
599        MustUsePath::Def(span, def_id, reason) => {
600            let ancenstor_span = span.find_ancestor_not_from_macro().unwrap_or(*span);
601            let is_redundant_let_ignore = cx
602                .sess()
603                .source_map()
604                .span_to_prev_source(ancenstor_span)
605                .ok()
606                .map(|prev| prev.trim_end().ends_with("let _ ="))
607                .unwrap_or(false);
608            let suggestion_span = if is_redundant_let_ignore { *span } else { ancenstor_span };
609            cx.emit_span_lint(
610                UNUSED_MUST_USE,
611                ancenstor_span,
612                UnusedDef {
613                    pre: descr_pre,
614                    post: descr_post,
615                    cx,
616                    def_id: *def_id,
617                    note: *reason,
618                    suggestion: (!is_inner).then_some(if expr_is_from_block {
619                        UnusedDefSuggestion::BlockTailExpr {
620                            before_span: suggestion_span.shrink_to_lo(),
621                            after_span: suggestion_span.shrink_to_hi(),
622                        }
623                    } else {
624                        UnusedDefSuggestion::NormalExpr { span: suggestion_span.shrink_to_lo() }
625                    }),
626                },
627            );
628        }
629    }
630}