Skip to main content

rustc_trait_selection/error_reporting/infer/nice_region_error/
placeholder_error.rs

1use std::fmt;
2
3use rustc_data_structures::Limit;
4use rustc_data_structures::intern::Interned;
5use rustc_errors::{Applicability, Diag, IntoDiagArg};
6use rustc_hir as hir;
7use rustc_hir::def::Namespace;
8use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
9use rustc_middle::bug;
10use rustc_middle::ty::error::ExpectedFound;
11use rustc_middle::ty::print::{FmtPrinter, Print, PrintTraitRefExt as _, RegionHighlightMode};
12use rustc_middle::ty::{
13    self, GenericArgsRef, IsSuggestable, RePlaceholder, Region, RegionExt, TyCtxt,
14};
15use tracing::{debug, instrument};
16
17use crate::diagnostics::{
18    ActualImplExpectedKind, ActualImplExpectedLifetimeKind, ActualImplExplNotes,
19    TraitPlaceholderMismatch, TyOrSig,
20};
21use crate::error_reporting::infer::nice_region_error::NiceRegionError;
22use crate::infer::{RegionResolutionError, SubregionOrigin, TypeTrace, ValuePairs};
23use crate::traits::{ObligationCause, ObligationCauseCode};
24
25#[derive(#[automatically_derived]
impl<'tcx, T: ::core::marker::Copy> ::core::marker::Copy for
    Highlighted<'tcx, T> {
}Copy, #[automatically_derived]
impl<'tcx, T: ::core::clone::Clone> ::core::clone::Clone for
    Highlighted<'tcx, T> {
    #[inline]
    fn clone(&self) -> Highlighted<'tcx, T> {
        Highlighted {
            tcx: ::core::clone::Clone::clone(&self.tcx),
            highlight: ::core::clone::Clone::clone(&self.highlight),
            value: ::core::clone::Clone::clone(&self.value),
            ns: ::core::clone::Clone::clone(&self.ns),
        }
    }
}Clone)]
26pub(crate) struct Highlighted<'tcx, T> {
27    pub tcx: TyCtxt<'tcx>,
28    pub highlight: RegionHighlightMode<'tcx>,
29    pub value: T,
30    pub ns: Namespace,
31}
32
33impl<'tcx, T> IntoDiagArg for Highlighted<'tcx, T>
34where
35    T: for<'a> Print<FmtPrinter<'a, 'tcx>> + Copy,
36{
37    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
38        rustc_errors::DiagArgValue::Str(self.to_string().into())
39    }
40}
41
42impl<'tcx, T> Highlighted<'tcx, T> {
43    fn map<U>(self, f: impl FnOnce(T) -> U) -> Highlighted<'tcx, U> {
44        Highlighted { tcx: self.tcx, highlight: self.highlight, value: f(self.value), ns: self.ns }
45    }
46}
47
48impl<'tcx, T> fmt::Display for Highlighted<'tcx, T>
49where
50    T: for<'a> Print<FmtPrinter<'a, 'tcx>> + Copy,
51{
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        let mut p = ty::print::FmtPrinter::new(self.tcx, self.ns);
54        p.region_highlight_mode = self.highlight;
55
56        self.value.print(&mut p)?;
57        let b = p.into_buffer();
58        if b.len() <= 40 || !self.highlight.keep_regions || self.tcx.sess.opts.verbose {
59            // This is a short enough type that can be safely be printed to the user, or we aren't
60            // showing the type with a particular interest in its lifetimes.
61            f.write_str(&b)?;
62        } else {
63            // We are highlighting lifetimes in the output, we will print out the smallest possible
64            // portion of the type while keeping the lifetimes visible.
65            let mut p = FmtPrinter::new_with_limit(self.tcx, self.ns, Limit(0));
66            p.region_highlight_mode = self.highlight;
67            self.value.print(&mut p).expect("could not print type");
68            let x = p.into_buffer();
69            f.write_str(&x)?;
70        }
71        Ok(())
72    }
73}
74
75impl<'tcx> NiceRegionError<'_, 'tcx> {
76    /// When given a `ConcreteFailure` for a function with arguments containing a named region and
77    /// an anonymous region, emit a descriptive diagnostic error.
78    pub(super) fn try_report_placeholder_conflict(&self) -> Option<Diag<'tcx>> {
79        match &self.error {
80            ///////////////////////////////////////////////////////////////////////////
81            // NB. The ordering of cases in this match is very
82            // sensitive, because we are often matching against
83            // specific cases and then using an `_` to match all
84            // others.
85
86            ///////////////////////////////////////////////////////////////////////////
87            // Check for errors from comparing trait failures -- first
88            // with two placeholders, then with one.
89            Some(RegionResolutionError::SubSupConflict(
90                vid,
91                _,
92                SubregionOrigin::Subtype(TypeTrace { cause, values }),
93                sub_placeholder @ Region(Interned(RePlaceholder(_), _)),
94                _,
95                sup_placeholder @ Region(Interned(RePlaceholder(_), _)),
96                _,
97            )) => self.try_report_trait_placeholder_mismatch(
98                Some(ty::Region::new_var(self.tcx(), *vid)),
99                cause,
100                Some(*sub_placeholder),
101                Some(*sup_placeholder),
102                values,
103            ),
104
105            Some(RegionResolutionError::SubSupConflict(
106                vid,
107                _,
108                SubregionOrigin::Subtype(TypeTrace { cause, values }),
109                sub_placeholder @ Region(Interned(RePlaceholder(_), _)),
110                _,
111                _,
112                _,
113            )) => self.try_report_trait_placeholder_mismatch(
114                Some(ty::Region::new_var(self.tcx(), *vid)),
115                cause,
116                Some(*sub_placeholder),
117                None,
118                values,
119            ),
120
121            Some(RegionResolutionError::SubSupConflict(
122                vid,
123                _,
124                SubregionOrigin::Subtype(TypeTrace { cause, values }),
125                _,
126                _,
127                sup_placeholder @ Region(Interned(RePlaceholder(_), _)),
128                _,
129            )) => self.try_report_trait_placeholder_mismatch(
130                Some(ty::Region::new_var(self.tcx(), *vid)),
131                cause,
132                None,
133                Some(*sup_placeholder),
134                values,
135            ),
136
137            Some(RegionResolutionError::SubSupConflict(
138                vid,
139                _,
140                _,
141                _,
142                SubregionOrigin::Subtype(TypeTrace { cause, values }),
143                sup_placeholder @ Region(Interned(RePlaceholder(_), _)),
144                _,
145            )) => self.try_report_trait_placeholder_mismatch(
146                Some(ty::Region::new_var(self.tcx(), *vid)),
147                cause,
148                None,
149                Some(*sup_placeholder),
150                values,
151            ),
152
153            Some(RegionResolutionError::UpperBoundUniverseConflict(
154                vid,
155                _,
156                _,
157                SubregionOrigin::Subtype(TypeTrace { cause, values }),
158                sup_placeholder @ Region(Interned(RePlaceholder(_), _)),
159            )) => self.try_report_trait_placeholder_mismatch(
160                Some(ty::Region::new_var(self.tcx(), *vid)),
161                cause,
162                None,
163                Some(*sup_placeholder),
164                values,
165            ),
166
167            Some(RegionResolutionError::ConcreteFailure(
168                SubregionOrigin::Subtype(TypeTrace { cause, values }),
169                sub_region @ Region(Interned(RePlaceholder(_), _)),
170                sup_region @ Region(Interned(RePlaceholder(_), _)),
171            )) => self.try_report_trait_placeholder_mismatch(
172                None,
173                cause,
174                Some(*sub_region),
175                Some(*sup_region),
176                values,
177            ),
178
179            Some(RegionResolutionError::ConcreteFailure(
180                SubregionOrigin::Subtype(TypeTrace { cause, values }),
181                sub_region @ Region(Interned(RePlaceholder(_), _)),
182                sup_region,
183            )) => self.try_report_trait_placeholder_mismatch(
184                (!sup_region.is_named(self.tcx())).then_some(*sup_region),
185                cause,
186                Some(*sub_region),
187                None,
188                values,
189            ),
190
191            Some(RegionResolutionError::ConcreteFailure(
192                SubregionOrigin::Subtype(TypeTrace { cause, values }),
193                sub_region,
194                sup_region @ Region(Interned(RePlaceholder(_), _)),
195            )) => self.try_report_trait_placeholder_mismatch(
196                (!sub_region.is_named(self.tcx())).then_some(*sub_region),
197                cause,
198                None,
199                Some(*sup_region),
200                values,
201            ),
202
203            _ => None,
204        }
205    }
206
207    fn try_report_trait_placeholder_mismatch(
208        &self,
209        vid: Option<Region<'tcx>>,
210        cause: &ObligationCause<'tcx>,
211        sub_placeholder: Option<Region<'tcx>>,
212        sup_placeholder: Option<Region<'tcx>>,
213        value_pairs: &ValuePairs<'tcx>,
214    ) -> Option<Diag<'tcx>> {
215        let (expected_args, found_args, trait_def_id) = match value_pairs {
216            ValuePairs::TraitRefs(ExpectedFound { expected, found })
217                if expected.def_id == found.def_id =>
218            {
219                // It's possible that the placeholders come from a binder
220                // outside of this value pair. Use `no_bound_vars` as a
221                // simple heuristic for that.
222                (expected.args, found.args, expected.def_id)
223            }
224            _ => return None,
225        };
226
227        Some(self.report_trait_placeholder_mismatch(
228            vid,
229            cause,
230            sub_placeholder,
231            sup_placeholder,
232            trait_def_id,
233            expected_args,
234            found_args,
235        ))
236    }
237
238    // error[E0308]: implementation of `Foo` does not apply to enough lifetimes
239    //   --> /home/nmatsakis/tmp/foo.rs:12:5
240    //    |
241    // 12 |     all::<&'static u32>();
242    //    |     ^^^^^^^^^^^^^^^^^^^ lifetime mismatch
243    //    |
244    //    = note: Due to a where-clause on the function `all`,
245    //    = note: `T` must implement `...` for any two lifetimes `'1` and `'2`.
246    //    = note: However, the type `T` only implements `...` for some specific lifetime `'2`.
247    #[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("report_trait_placeholder_mismatch",
                                    "rustc_trait_selection::error_reporting::infer::nice_region_error::placeholder_error",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs"),
                                    ::tracing_core::__macro_support::Option::Some(247u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::nice_region_error::placeholder_error"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("vid")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("vid");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("cause")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("cause");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("sub_placeholder")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("sub_placeholder");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("sup_placeholder")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("sup_placeholder");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("expected_args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("expected_args");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("actual_args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("actual_args");
                                                        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(&vid)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sub_placeholder)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sup_placeholder)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected_args)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&actual_args)
                                                            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: Diag<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let span = cause.span;
            let (leading_ellipsis, satisfy_span, where_span, dup_span,
                    def_id) =
                if let ObligationCauseCode::WhereClause(def_id, span) |
                            ObligationCauseCode::WhereClauseInExpr(def_id, span, ..) =
                            *cause.code() && def_id != CRATE_DEF_ID.to_def_id() {
                    (true, Some(span), Some(self.tcx().def_span(def_id)), None,
                        self.tcx().def_path_str(def_id))
                } else { (false, None, None, Some(span), String::new()) };
            let expected_trait_ref =
                self.cx.resolve_vars_if_possible(ty::TraitRef::new_from_args(self.cx.tcx,
                        trait_def_id, expected_args));
            let actual_trait_ref =
                self.cx.resolve_vars_if_possible(ty::TraitRef::new_from_args(self.cx.tcx,
                        trait_def_id, actual_args));
            let mut counter = 0;
            let mut has_sub = None;
            let mut has_sup = None;
            let mut actual_has_vid = None;
            let mut expected_has_vid = None;
            self.tcx().for_each_free_region(&expected_trait_ref,
                |r|
                    {
                        if Some(r) == sub_placeholder && has_sub.is_none() {
                            has_sub = Some(counter);
                            counter += 1;
                        } else if Some(r) == sup_placeholder && has_sup.is_none() {
                            has_sup = Some(counter);
                            counter += 1;
                        }
                        if Some(r) == vid && expected_has_vid.is_none() {
                            expected_has_vid = Some(counter);
                            counter += 1;
                        }
                    });
            self.tcx().for_each_free_region(&actual_trait_ref,
                |r|
                    {
                        if Some(r) == vid && actual_has_vid.is_none() {
                            actual_has_vid = Some(counter);
                            counter += 1;
                        }
                    });
            let actual_self_ty_has_vid =
                self.tcx().any_free_region_meets(&actual_trait_ref.self_ty(),
                    |r| Some(r) == vid);
            let expected_self_ty_has_vid =
                self.tcx().any_free_region_meets(&expected_trait_ref.self_ty(),
                    |r| Some(r) == vid);
            let any_self_ty_has_vid =
                actual_self_ty_has_vid || expected_self_ty_has_vid;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs:330",
                                    "rustc_trait_selection::error_reporting::infer::nice_region_error::placeholder_error",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs"),
                                    ::tracing_core::__macro_support::Option::Some(330u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::nice_region_error::placeholder_error"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("actual_has_vid")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("actual_has_vid");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("expected_has_vid")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("expected_has_vid");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("has_sub")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("has_sub");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("has_sup")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("has_sup");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("actual_self_ty_has_vid")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("actual_self_ty_has_vid");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("expected_self_ty_has_vid")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("expected_self_ty_has_vid");
                                                        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(&actual_has_vid)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected_has_vid)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&has_sub)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&has_sup)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&actual_self_ty_has_vid)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected_self_ty_has_vid)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let actual_impl_expl_notes =
                self.explain_actual_impl_that_was_found(sub_placeholder,
                    sup_placeholder, has_sub, has_sup, expected_trait_ref,
                    actual_trait_ref, vid, expected_has_vid, actual_has_vid,
                    any_self_ty_has_vid, leading_ellipsis);
            let mut err =
                self.tcx().dcx().create_err(TraitPlaceholderMismatch {
                        span,
                        satisfy_span,
                        where_span,
                        dup_span,
                        def_id,
                        trait_def_id: self.tcx().def_path_str(trait_def_id),
                        actual_impl_expl_notes,
                    });
            let mut current_code = cause.code();
            let mut coroutine_def_id = None;
            loop {
                match current_code {
                    ObligationCauseCode::MatchImpl(inner_cause, _) => {
                        current_code = inner_cause.code();
                    }
                    ObligationCauseCode::BuiltinDerived(derived) => {
                        let self_ty =
                            derived.parent_trait_pred.skip_binder().self_ty();
                        if let ty::Coroutine(def_id, _) |
                                ty::CoroutineWitness(def_id, _) = self_ty.kind() {
                            coroutine_def_id = Some(*def_id);
                            break;
                        }
                        current_code = &derived.parent_code;
                    }
                    _ => break,
                }
            }
            if let Some(def_id) = coroutine_def_id {
                if self.tcx().trait_is_auto(trait_def_id) {
                    let c_span = self.tcx().def_span(def_id);
                    let descr = self.tcx().def_descr(def_id);
                    let trait_name = self.tcx().def_path_str(trait_def_id);
                    err.span_label(c_span,
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("this {0} captures a value whose type is not `{1}`",
                                        descr, trait_name))
                            }));
                }
            }
            if self.tcx().is_fn_trait(trait_def_id) {
                let actual_self_ty =
                    self.cx.resolve_vars_if_possible(ty::TraitRef::new_from_args(self.cx.tcx,
                                trait_def_id, actual_args).self_ty());
                if let ty::Closure(closure_def_id, _) = *actual_self_ty.kind()
                            && let Some(local_def_id) = closure_def_id.as_local() &&
                        let hir::Node::Expr(hir::Expr {
                            kind: hir::ExprKind::Closure(closure), .. }) =
                            self.tcx().hir_node_by_def_id(local_def_id) {
                    let body = self.tcx().hir_body(closure.body);
                    let expected_input_tys = expected_args.type_at(1);
                    if let ty::Tuple(input_tys) = *expected_input_tys.kind() {
                        let suggestions: Vec<_> =
                            body.params.iter().zip(input_tys.iter()).filter_map(|(param,
                                            ty)|
                                        {
                                            if param.ty_span == param.pat.span &&
                                                    ty.is_suggestable(self.tcx(), false) {
                                                Some((param.pat.span.shrink_to_hi(),
                                                        ::alloc::__export::must_use({
                                                                ::alloc::fmt::format(format_args!(": {0}", ty))
                                                            })))
                                            } else { None }
                                        }).collect();
                        if !suggestions.is_empty() {
                            let msg =
                                if suggestions.len() == 1 {
                                    "consider adding an explicit type annotation to the closure's argument"
                                } else {
                                    "consider adding explicit type annotations to the closure's arguments"
                                };
                            err.multipart_suggestion(msg, suggestions,
                                Applicability::MaybeIncorrect);
                        }
                    }
                }
            }
            err
        }
    }
}#[instrument(level = "debug", skip(self))]
248    fn report_trait_placeholder_mismatch(
249        &self,
250        vid: Option<Region<'tcx>>,
251        cause: &ObligationCause<'tcx>,
252        sub_placeholder: Option<Region<'tcx>>,
253        sup_placeholder: Option<Region<'tcx>>,
254        trait_def_id: DefId,
255        expected_args: GenericArgsRef<'tcx>,
256        actual_args: GenericArgsRef<'tcx>,
257    ) -> Diag<'tcx> {
258        let span = cause.span;
259
260        let (leading_ellipsis, satisfy_span, where_span, dup_span, def_id) =
261            if let ObligationCauseCode::WhereClause(def_id, span)
262            | ObligationCauseCode::WhereClauseInExpr(def_id, span, ..) = *cause.code()
263                && def_id != CRATE_DEF_ID.to_def_id()
264            {
265                (
266                    true,
267                    Some(span),
268                    Some(self.tcx().def_span(def_id)),
269                    None,
270                    self.tcx().def_path_str(def_id),
271                )
272            } else {
273                (false, None, None, Some(span), String::new())
274            };
275
276        let expected_trait_ref = self.cx.resolve_vars_if_possible(ty::TraitRef::new_from_args(
277            self.cx.tcx,
278            trait_def_id,
279            expected_args,
280        ));
281        let actual_trait_ref = self.cx.resolve_vars_if_possible(ty::TraitRef::new_from_args(
282            self.cx.tcx,
283            trait_def_id,
284            actual_args,
285        ));
286
287        // Search the expected and actual trait references to see (a)
288        // whether the sub/sup placeholders appear in them (sometimes
289        // you have a trait ref like `T: Foo<fn(&u8)>`, where the
290        // placeholder was created as part of an inner type) and (b)
291        // whether the inference variable appears. In each case,
292        // assign a counter value in each case if so.
293        let mut counter = 0;
294        let mut has_sub = None;
295        let mut has_sup = None;
296
297        let mut actual_has_vid = None;
298        let mut expected_has_vid = None;
299
300        self.tcx().for_each_free_region(&expected_trait_ref, |r| {
301            if Some(r) == sub_placeholder && has_sub.is_none() {
302                has_sub = Some(counter);
303                counter += 1;
304            } else if Some(r) == sup_placeholder && has_sup.is_none() {
305                has_sup = Some(counter);
306                counter += 1;
307            }
308
309            if Some(r) == vid && expected_has_vid.is_none() {
310                expected_has_vid = Some(counter);
311                counter += 1;
312            }
313        });
314
315        self.tcx().for_each_free_region(&actual_trait_ref, |r| {
316            if Some(r) == vid && actual_has_vid.is_none() {
317                actual_has_vid = Some(counter);
318                counter += 1;
319            }
320        });
321
322        let actual_self_ty_has_vid =
323            self.tcx().any_free_region_meets(&actual_trait_ref.self_ty(), |r| Some(r) == vid);
324
325        let expected_self_ty_has_vid =
326            self.tcx().any_free_region_meets(&expected_trait_ref.self_ty(), |r| Some(r) == vid);
327
328        let any_self_ty_has_vid = actual_self_ty_has_vid || expected_self_ty_has_vid;
329
330        debug!(
331            ?actual_has_vid,
332            ?expected_has_vid,
333            ?has_sub,
334            ?has_sup,
335            ?actual_self_ty_has_vid,
336            ?expected_self_ty_has_vid,
337        );
338
339        let actual_impl_expl_notes = self.explain_actual_impl_that_was_found(
340            sub_placeholder,
341            sup_placeholder,
342            has_sub,
343            has_sup,
344            expected_trait_ref,
345            actual_trait_ref,
346            vid,
347            expected_has_vid,
348            actual_has_vid,
349            any_self_ty_has_vid,
350            leading_ellipsis,
351        );
352
353        let mut err = self.tcx().dcx().create_err(TraitPlaceholderMismatch {
354            span,
355            satisfy_span,
356            where_span,
357            dup_span,
358            def_id,
359            trait_def_id: self.tcx().def_path_str(trait_def_id),
360            actual_impl_expl_notes,
361        });
362
363        let mut current_code = cause.code();
364        let mut coroutine_def_id = None;
365
366        loop {
367            match current_code {
368                ObligationCauseCode::MatchImpl(inner_cause, _) => {
369                    current_code = inner_cause.code();
370                }
371                ObligationCauseCode::BuiltinDerived(derived) => {
372                    let self_ty = derived.parent_trait_pred.skip_binder().self_ty();
373
374                    if let ty::Coroutine(def_id, _) | ty::CoroutineWitness(def_id, _) =
375                        self_ty.kind()
376                    {
377                        coroutine_def_id = Some(*def_id);
378                        break;
379                    }
380
381                    current_code = &derived.parent_code;
382                }
383                _ => break,
384            }
385        }
386
387        if let Some(def_id) = coroutine_def_id {
388            if self.tcx().trait_is_auto(trait_def_id) {
389                let c_span = self.tcx().def_span(def_id);
390                let descr = self.tcx().def_descr(def_id);
391                let trait_name = self.tcx().def_path_str(trait_def_id);
392
393                err.span_label(
394                    c_span,
395                    format!("this {descr} captures a value whose type is not `{trait_name}`"),
396                );
397            }
398        }
399
400        // When the mismatched trait is an Fn-trait and the self type is a closure with
401        // unannotated parameters, suggest adding explicit type annotations. This turns
402        // the confusing lifetime-generality error into an actionable hint, e.g.:
403        //   |buf|  →  |buf: &mut [u8]|
404        if self.tcx().is_fn_trait(trait_def_id) {
405            let actual_self_ty = self.cx.resolve_vars_if_possible(
406                ty::TraitRef::new_from_args(self.cx.tcx, trait_def_id, actual_args).self_ty(),
407            );
408            if let ty::Closure(closure_def_id, _) = *actual_self_ty.kind()
409                && let Some(local_def_id) = closure_def_id.as_local()
410                && let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(closure), .. }) =
411                    self.tcx().hir_node_by_def_id(local_def_id)
412            {
413                let body = self.tcx().hir_body(closure.body);
414                // For Fn traits, args[1] is the tupled input types (e.g. `(&mut [u8],)`).
415                let expected_input_tys = expected_args.type_at(1);
416                if let ty::Tuple(input_tys) = *expected_input_tys.kind() {
417                    let suggestions: Vec<_> = body
418                        .params
419                        .iter()
420                        .zip(input_tys.iter())
421                        .filter_map(|(param, ty)| {
422                            // ty_span == pat.span means no explicit type annotation was written.
423                            if param.ty_span == param.pat.span
424                                && ty.is_suggestable(self.tcx(), false)
425                            {
426                                Some((param.pat.span.shrink_to_hi(), format!(": {ty}")))
427                            } else {
428                                None
429                            }
430                        })
431                        .collect();
432                    if !suggestions.is_empty() {
433                        let msg = if suggestions.len() == 1 {
434                            "consider adding an explicit type annotation to the closure's argument"
435                        } else {
436                            "consider adding explicit type annotations to the closure's arguments"
437                        };
438                        err.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
439                    }
440                }
441            }
442        }
443
444        err
445    }
446
447    /// Add notes with details about the expected and actual trait refs, with attention to cases
448    /// when placeholder regions are involved: either the trait or the self type containing
449    /// them needs to be mentioned the closest to the placeholders.
450    /// This makes the error messages read better, however at the cost of some complexity
451    /// due to the number of combinations we have to deal with.
452    fn explain_actual_impl_that_was_found(
453        &self,
454        sub_placeholder: Option<Region<'tcx>>,
455        sup_placeholder: Option<Region<'tcx>>,
456        has_sub: Option<usize>,
457        has_sup: Option<usize>,
458        expected_trait_ref: ty::TraitRef<'tcx>,
459        actual_trait_ref: ty::TraitRef<'tcx>,
460        vid: Option<Region<'tcx>>,
461        expected_has_vid: Option<usize>,
462        actual_has_vid: Option<usize>,
463        any_self_ty_has_vid: bool,
464        leading_ellipsis: bool,
465    ) -> Vec<ActualImplExplNotes<'tcx>> {
466        // The weird thing here with the `maybe_highlighting_region` calls and the
467        // the match inside is meant to be like this:
468        //
469        // - The match checks whether the given things (placeholders, etc) appear
470        //   in the types are about to print
471        // - Meanwhile, the `maybe_highlighting_region` calls set up
472        //   highlights so that, if they do appear, we will replace
473        //   them `'0` and whatever. (This replacement takes place
474        //   inside the closure given to `maybe_highlighting_region`.)
475        //
476        // There is some duplication between the calls -- i.e., the
477        // `maybe_highlighting_region` checks if (e.g.) `has_sub` is
478        // None, an then we check again inside the closure, but this
479        // setup sort of minimized the number of calls and so form.
480
481        let highlight_trait_ref = |trait_ref| Highlighted {
482            tcx: self.tcx(),
483            highlight: RegionHighlightMode::default(),
484            value: trait_ref,
485            ns: Namespace::TypeNS,
486        };
487
488        let same_self_type = actual_trait_ref.self_ty() == expected_trait_ref.self_ty();
489
490        let mut expected_trait_ref = highlight_trait_ref(expected_trait_ref);
491        expected_trait_ref.highlight.maybe_highlighting_region(sub_placeholder, has_sub);
492        expected_trait_ref.highlight.maybe_highlighting_region(sup_placeholder, has_sup);
493
494        let passive_voice = match (has_sub, has_sup) {
495            (Some(_), _) | (_, Some(_)) => any_self_ty_has_vid,
496            (None, None) => {
497                expected_trait_ref.highlight.maybe_highlighting_region(vid, expected_has_vid);
498                match expected_has_vid {
499                    Some(_) => true,
500                    None => any_self_ty_has_vid,
501                }
502            }
503        };
504
505        let (kind, ty_or_sig, trait_path) = if same_self_type {
506            let mut self_ty = expected_trait_ref.map(|tr| tr.self_ty());
507            self_ty.highlight.maybe_highlighting_region(vid, actual_has_vid);
508
509            if self_ty.value.is_closure() && self.tcx().is_fn_trait(expected_trait_ref.value.def_id)
510            {
511                let closure_sig = self_ty.map(|closure| {
512                    if let ty::Closure(_, args) = closure.kind() {
513                        self.tcx()
514                            .signature_unclosure(args.as_closure().sig(), rustc_hir::Safety::Safe)
515                    } else {
516                        ::rustc_middle::util::bug::bug_fmt(format_args!("type is not longer closure"));bug!("type is not longer closure");
517                    }
518                });
519                (
520                    ActualImplExpectedKind::Signature,
521                    TyOrSig::ClosureSig(closure_sig),
522                    expected_trait_ref.map(|tr| tr.print_only_trait_path()),
523                )
524            } else {
525                (
526                    ActualImplExpectedKind::Other,
527                    TyOrSig::Ty(self_ty),
528                    expected_trait_ref.map(|tr| tr.print_only_trait_path()),
529                )
530            }
531        } else if passive_voice {
532            (
533                ActualImplExpectedKind::Passive,
534                TyOrSig::Ty(expected_trait_ref.map(|tr| tr.self_ty())),
535                expected_trait_ref.map(|tr| tr.print_only_trait_path()),
536            )
537        } else {
538            (
539                ActualImplExpectedKind::Other,
540                TyOrSig::Ty(expected_trait_ref.map(|tr| tr.self_ty())),
541                expected_trait_ref.map(|tr| tr.print_only_trait_path()),
542            )
543        };
544
545        let (lt_kind, lifetime_1, lifetime_2) = match (has_sub, has_sup) {
546            (Some(n1), Some(n2)) => {
547                (ActualImplExpectedLifetimeKind::Two, std::cmp::min(n1, n2), std::cmp::max(n1, n2))
548            }
549            (Some(n), _) | (_, Some(n)) => (ActualImplExpectedLifetimeKind::Any, n, 0),
550            (None, None) => {
551                if let Some(n) = expected_has_vid {
552                    (ActualImplExpectedLifetimeKind::Some, n, 0)
553                } else {
554                    (ActualImplExpectedLifetimeKind::Nothing, 0, 0)
555                }
556            }
557        };
558
559        let note_1 = ActualImplExplNotes::new_expected(
560            kind,
561            lt_kind,
562            leading_ellipsis,
563            ty_or_sig,
564            trait_path,
565            lifetime_1,
566            lifetime_2,
567        );
568
569        let mut actual_trait_ref = highlight_trait_ref(actual_trait_ref);
570        actual_trait_ref.highlight.maybe_highlighting_region(vid, actual_has_vid);
571
572        let passive_voice = match actual_has_vid {
573            Some(_) => any_self_ty_has_vid,
574            None => true,
575        };
576
577        let trait_path = actual_trait_ref.map(|tr| tr.print_only_trait_path());
578        let ty = actual_trait_ref.map(|tr| tr.self_ty()).to_string();
579        let has_lifetime = actual_has_vid.is_some();
580        let lifetime = actual_has_vid.unwrap_or_default();
581
582        let note_2 = if same_self_type {
583            ActualImplExplNotes::ButActuallyImplementsTrait { trait_path, has_lifetime, lifetime }
584        } else if passive_voice {
585            ActualImplExplNotes::ButActuallyImplementedForTy {
586                trait_path,
587                ty,
588                has_lifetime,
589                lifetime,
590            }
591        } else {
592            ActualImplExplNotes::ButActuallyTyImplements { trait_path, ty, has_lifetime, lifetime }
593        };
594
595        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [note_1, note_2]))vec![note_1, note_2]
596    }
597}