Skip to main content

rustc_trait_selection/error_reporting/infer/nice_region_error/
trait_impl_difference.rs

1//! Error Reporting for `impl` items that do not match the obligations from their `trait`.
2
3use rustc_errors::ErrorGuaranteed;
4use rustc_hir::def::{Namespace, Res};
5use rustc_hir::def_id::DefId;
6use rustc_hir::intravisit::{Visitor, walk_ty};
7use rustc_hir::{self as hir, AmbigArg};
8use rustc_infer::infer::SubregionOrigin;
9use rustc_middle::hir::nested_filter;
10use rustc_middle::traits::ObligationCauseCode;
11use rustc_middle::ty::error::ExpectedFound;
12use rustc_middle::ty::print::RegionHighlightMode;
13use rustc_middle::ty::{self, TyCtxt, TypeVisitable};
14use rustc_span::{Ident, Span};
15use tracing::debug;
16
17use crate::diagnostics::{ConsiderBorrowingParamHelp, TraitImplDiff};
18use crate::error_reporting::infer::nice_region_error::NiceRegionError;
19use crate::error_reporting::infer::nice_region_error::placeholder_error::Highlighted;
20use crate::infer::{RegionResolutionError, ValuePairs};
21
22impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
23    /// Print the error message for lifetime errors when the `impl` doesn't conform to the `trait`.
24    pub(super) fn try_report_impl_not_conforming_to_trait(&self) -> Option<ErrorGuaranteed> {
25        let error = self.error.as_ref()?;
26        {
    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/trait_impl_difference.rs:26",
                        "rustc_trait_selection::error_reporting::infer::nice_region_error::trait_impl_difference",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/trait_impl_difference.rs"),
                        ::tracing_core::__macro_support::Option::Some(26u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::nice_region_error::trait_impl_difference"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::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(&format_args!("try_report_impl_not_conforming_to_trait {0:?}",
                                                    error) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("try_report_impl_not_conforming_to_trait {:?}", error);
27        if let RegionResolutionError::SubSupConflict(
28            _,
29            var_origin,
30            sub_origin,
31            _sub,
32            sup_origin,
33            _sup,
34            _,
35        ) = error.clone()
36            && let (SubregionOrigin::Subtype(sup_trace), SubregionOrigin::Subtype(sub_trace)) =
37                (&sup_origin, &sub_origin)
38            && let &ObligationCauseCode::CompareImplItem { trait_item_def_id, .. } =
39                sub_trace.cause.code()
40            && sub_trace.values == sup_trace.values
41            && let ValuePairs::PolySigs(ExpectedFound { expected, found }) = sub_trace.values
42        {
43            // FIXME(compiler-errors): Don't like that this needs `Ty`s, but
44            // all of the region highlighting machinery only deals with those.
45            let guar = self.emit_err(var_origin.span(), expected, found, trait_item_def_id);
46            return Some(guar);
47        }
48        None
49    }
50
51    fn emit_err(
52        &self,
53        sp: Span,
54        expected: ty::PolyFnSig<'tcx>,
55        found: ty::PolyFnSig<'tcx>,
56        trait_item_def_id: DefId,
57    ) -> ErrorGuaranteed {
58        let trait_sp = self.tcx().def_span(trait_item_def_id);
59
60        // Mark all unnamed regions in the type with a number.
61        // This diagnostic is called in response to lifetime errors, so be informative.
62        struct HighlightBuilder<'tcx> {
63            tcx: TyCtxt<'tcx>,
64            highlight: RegionHighlightMode<'tcx>,
65            counter: usize,
66        }
67
68        impl<'tcx> HighlightBuilder<'tcx> {
69            fn build(tcx: TyCtxt<'tcx>, sig: ty::PolyFnSig<'tcx>) -> RegionHighlightMode<'tcx> {
70                let mut builder =
71                    HighlightBuilder { tcx, highlight: RegionHighlightMode::default(), counter: 1 };
72                sig.visit_with(&mut builder);
73                builder.highlight
74            }
75        }
76
77        impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for HighlightBuilder<'tcx> {
78            fn visit_region(&mut self, r: ty::Region<'tcx>) {
79                if !r.is_named(self.tcx) && self.counter <= 3 {
80                    self.highlight.highlighting_region(r, self.counter);
81                    self.counter += 1;
82                }
83            }
84        }
85
86        let tcx = self.cx.tcx;
87        let mut expected_highlight = HighlightBuilder::build(tcx, expected);
88        let expected_short = Highlighted {
89            highlight: expected_highlight,
90            ns: Namespace::TypeNS,
91            tcx,
92            value: expected,
93        }
94        .to_string();
95        expected_highlight.keep_regions = false;
96        let expected = Highlighted {
97            highlight: expected_highlight,
98            ns: Namespace::TypeNS,
99            tcx,
100            value: expected,
101        }
102        .to_string();
103        let mut found_highlight = HighlightBuilder::build(tcx, found);
104        let found_short =
105            Highlighted { highlight: found_highlight, ns: Namespace::TypeNS, tcx, value: found }
106                .to_string();
107        found_highlight.keep_regions = false;
108        let found =
109            Highlighted { highlight: found_highlight, ns: Namespace::TypeNS, tcx, value: found }
110                .to_string();
111
112        // Get the span of all the used type parameters in the method.
113        let assoc_item = self.tcx().associated_item(trait_item_def_id);
114        let mut visitor =
115            TypeParamSpanVisitor { tcx: self.tcx(), types: ::alloc::vec::Vec::new()vec![], elided_lifetime_paths: ::alloc::vec::Vec::new()vec![] };
116        match assoc_item.kind {
117            ty::AssocKind::Fn { .. } => {
118                if let Some(hir_id) =
119                    assoc_item.def_id.as_local().map(|id| self.tcx().local_def_id_to_hir_id(id))
120                    && let Some(decl) = self.tcx().hir_fn_decl_by_hir_id(hir_id)
121                {
122                    visitor.visit_fn_decl(decl);
123                }
124            }
125            _ => {}
126        }
127
128        let diag = TraitImplDiff {
129            sp,
130            trait_sp,
131            note: (),
132            param_help: ConsiderBorrowingParamHelp { spans: visitor.types.to_vec() },
133            rel_help: visitor.types.is_empty(),
134            expected,
135            found,
136            expected_short,
137            found_short,
138        };
139
140        let mut diag = self.tcx().dcx().create_err(diag);
141        // A limit not to make diag verbose.
142        const ELIDED_LIFETIME_NOTE_LIMIT: usize = 5;
143        let elided_lifetime_paths = visitor.elided_lifetime_paths;
144        let total_elided_lifetime_paths = elided_lifetime_paths.len();
145        let shown_elided_lifetime_paths = if tcx.sess.opts.verbose {
146            total_elided_lifetime_paths
147        } else {
148            ELIDED_LIFETIME_NOTE_LIMIT
149        };
150
151        for elided in elided_lifetime_paths.into_iter().take(shown_elided_lifetime_paths) {
152            diag.span_note(
153                elided.span,
154                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` here is elided as `{1}`",
                elided.ident, elided.shorthand))
    })format!("`{}` here is elided as `{}`", elided.ident, elided.shorthand),
155            );
156        }
157        if total_elided_lifetime_paths > shown_elided_lifetime_paths {
158            diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("and {0} more elided lifetime{1} in type paths",
                total_elided_lifetime_paths - shown_elided_lifetime_paths,
                if total_elided_lifetime_paths - shown_elided_lifetime_paths
                        == 1 {
                    ""
                } else { "s" }))
    })format!(
159                "and {} more elided lifetime{} in type paths",
160                total_elided_lifetime_paths - shown_elided_lifetime_paths,
161                if total_elided_lifetime_paths - shown_elided_lifetime_paths == 1 {
162                    ""
163                } else {
164                    "s"
165                },
166            ));
167        }
168        diag.emit()
169    }
170}
171
172#[derive(#[automatically_derived]
impl ::core::clone::Clone for ElidedLifetimeInPath {
    #[inline]
    fn clone(&self) -> ElidedLifetimeInPath {
        ElidedLifetimeInPath {
            span: ::core::clone::Clone::clone(&self.span),
            ident: ::core::clone::Clone::clone(&self.ident),
            shorthand: ::core::clone::Clone::clone(&self.shorthand),
        }
    }
}Clone)]
173struct ElidedLifetimeInPath {
174    span: Span,
175    ident: Ident,
176    shorthand: String,
177}
178
179struct TypeParamSpanVisitor<'tcx> {
180    tcx: TyCtxt<'tcx>,
181    types: Vec<Span>,
182    elided_lifetime_paths: Vec<ElidedLifetimeInPath>,
183}
184
185impl<'tcx> Visitor<'tcx> for TypeParamSpanVisitor<'tcx> {
186    type NestedFilter = nested_filter::OnlyBodies;
187
188    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
189        self.tcx
190    }
191
192    fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: hir::HirId, _span: Span) {
193        fn record_elided_lifetimes(
194            tcx: TyCtxt<'_>,
195            elided_lifetime_paths: &mut Vec<ElidedLifetimeInPath>,
196            segment: &hir::PathSegment<'_>,
197        ) {
198            let Some(args) = segment.args else { return };
199            if args.parenthesized != hir::GenericArgsParentheses::No {
200                // Our diagnostic rendering below uses `<...>` syntax; skip cases like `Fn(..) -> ..`.
201                return;
202            }
203            let elided_count = args
204                .args
205                .iter()
206                .filter(|arg| {
207                    let hir::GenericArg::Lifetime(l) = arg else { return false };
208                    l.syntax == hir::LifetimeSyntax::Implicit
209                        && #[allow(non_exhaustive_omitted_patterns)] match l.source {
    hir::LifetimeSource::Path { .. } => true,
    _ => false,
}matches!(l.source, hir::LifetimeSource::Path { .. })
210                })
211                .count();
212            if elided_count == 0
213                || elided_lifetime_paths.iter().any(|p| p.span == segment.ident.span)
214            {
215                return;
216            }
217
218            let sm = tcx.sess.source_map();
219            let mut parts = args
220                .args
221                .iter()
222                .map(|arg| match arg {
223                    hir::GenericArg::Lifetime(l) => {
224                        if l.syntax == hir::LifetimeSyntax::Implicit
225                            && #[allow(non_exhaustive_omitted_patterns)] match l.source {
    hir::LifetimeSource::Path { .. } => true,
    _ => false,
}matches!(l.source, hir::LifetimeSource::Path { .. })
226                        {
227                            "'_".to_string()
228                        } else {
229                            sm.span_to_snippet(l.ident.span)
230                                .unwrap_or_else(|_| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}", l.ident.name))
    })format!("'{}", l.ident.name))
231                        }
232                    }
233                    hir::GenericArg::Type(ty) => {
234                        sm.span_to_snippet(ty.span).unwrap_or_else(|_| "..".to_string())
235                    }
236                    hir::GenericArg::Const(ct) => {
237                        sm.span_to_snippet(ct.span).unwrap_or_else(|_| "..".to_string())
238                    }
239                    hir::GenericArg::Infer(_) => "_".to_string(),
240                })
241                .collect::<Vec<_>>();
242            parts.extend(args.constraints.iter().map(|constraint| {
243                sm.span_to_snippet(constraint.span)
244                    .unwrap_or_else(|_| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} = ..", constraint.ident))
    })format!("{} = ..", constraint.ident))
245            }));
246            let shorthand = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}<{1}>", segment.ident,
                parts.join(", ")))
    })format!("{}<{}>", segment.ident, parts.join(", "));
247
248            elided_lifetime_paths.push(ElidedLifetimeInPath {
249                span: segment.ident.span,
250                ident: segment.ident,
251                shorthand,
252            });
253        }
254
255        match qpath {
256            hir::QPath::Resolved(_, path) => {
257                for segment in path.segments {
258                    record_elided_lifetimes(self.tcx, &mut self.elided_lifetime_paths, segment);
259                }
260            }
261            hir::QPath::TypeRelative(_, segment) => {
262                record_elided_lifetimes(self.tcx, &mut self.elided_lifetime_paths, segment);
263            }
264        }
265
266        hir::intravisit::walk_qpath(self, qpath, id);
267    }
268
269    fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx, AmbigArg>) {
270        match arg.kind {
271            hir::TyKind::Ref(_, ref mut_ty) => {
272                // We don't want to suggest looking into borrowing `&T` or `&Self`.
273                if let Some(ambig_ty) = mut_ty.ty.try_as_ambig_ty() {
274                    walk_ty(self, ambig_ty);
275                }
276                return;
277            }
278            hir::TyKind::Path(hir::QPath::Resolved(None, path)) => match &path.segments {
279                [segment]
280                    if #[allow(non_exhaustive_omitted_patterns)] match segment.res {
    Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } |
        Res::Def(hir::def::DefKind::TyParam, _) => true,
    _ => false,
}matches!(
281                        segment.res,
282                        Res::SelfTyParam { .. }
283                            | Res::SelfTyAlias { .. }
284                            | Res::Def(hir::def::DefKind::TyParam, _)
285                    ) =>
286                {
287                    self.types.push(path.span);
288                }
289                _ => {}
290            },
291            _ => {}
292        }
293        hir::intravisit::walk_ty(self, arg);
294    }
295}