rustc_trait_selection/error_reporting/infer/nice_region_error/
mismatched_static_lifetime.rs

1//! Error Reporting for when the lifetime for a type doesn't match the `impl` selected for a predicate
2//! to hold.
3
4use rustc_data_structures::fx::FxIndexSet;
5use rustc_errors::{ErrorGuaranteed, MultiSpan};
6use rustc_hir as hir;
7use rustc_hir::intravisit::VisitorExt;
8use rustc_middle::bug;
9use rustc_middle::ty::TypeVisitor;
10use tracing::debug;
11
12use crate::error_reporting::infer::nice_region_error::NiceRegionError;
13use crate::errors::{
14    DoesNotOutliveStaticFromImpl, ImplicitStaticLifetimeSubdiag,
15    IntroducesStaticBecauseUnmetLifetimeReq, MismatchedStaticLifetime, note_and_explain,
16};
17use crate::infer::{RegionResolutionError, SubregionOrigin, TypeTrace};
18use crate::traits::ObligationCauseCode;
19
20impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
21    pub(super) fn try_report_mismatched_static_lifetime(&self) -> Option<ErrorGuaranteed> {
22        let error = self.error.as_ref()?;
23        debug!("try_report_mismatched_static_lifetime {:?}", error);
24
25        let RegionResolutionError::ConcreteFailure(origin, sub, sup) = error.clone() else {
26            return None;
27        };
28        if !sub.is_static() {
29            return None;
30        }
31        let SubregionOrigin::Subtype(box TypeTrace { ref cause, .. }) = origin else {
32            return None;
33        };
34        // If we added a "points at argument expression" obligation, we remove it here, we care
35        // about the original obligation only.
36        let code = match cause.code() {
37            ObligationCauseCode::FunctionArg { parent_code, .. } => &*parent_code,
38            code => code,
39        };
40        let ObligationCauseCode::MatchImpl(parent, impl_def_id) = code else {
41            return None;
42        };
43        let (ObligationCauseCode::WhereClause(_, binding_span)
44        | ObligationCauseCode::WhereClauseInExpr(_, binding_span, ..)) = *parent.code()
45        else {
46            return None;
47        };
48        if binding_span.is_dummy() {
49            return None;
50        }
51
52        // FIXME: we should point at the lifetime
53        let multi_span: MultiSpan = vec![binding_span].into();
54        let multispan_subdiag = IntroducesStaticBecauseUnmetLifetimeReq {
55            unmet_requirements: multi_span,
56            binding_span,
57        };
58
59        let expl = note_and_explain::RegionExplanation::new(
60            self.tcx(),
61            self.generic_param_scope,
62            sup,
63            Some(binding_span),
64            note_and_explain::PrefixKind::Empty,
65            note_and_explain::SuffixKind::Continues,
66        );
67        let mut impl_span = None;
68        let mut implicit_static_lifetimes = Vec::new();
69        if let Some(impl_node) = self.tcx().hir().get_if_local(*impl_def_id) {
70            // If an impl is local, then maybe this isn't what they want. Try to
71            // be as helpful as possible with implicit lifetimes.
72
73            // First, let's get the hir self type of the impl
74            let hir::Node::Item(hir::Item {
75                kind: hir::ItemKind::Impl(hir::Impl { self_ty: impl_self_ty, .. }),
76                ..
77            }) = impl_node
78            else {
79                bug!("Node not an impl.");
80            };
81
82            // Next, let's figure out the set of trait objects with implicit static bounds
83            let ty = self.tcx().type_of(*impl_def_id).instantiate_identity();
84            let mut v = super::static_impl_trait::TraitObjectVisitor(FxIndexSet::default());
85            v.visit_ty(ty);
86            let mut traits = vec![];
87            for matching_def_id in v.0 {
88                let mut hir_v =
89                    super::static_impl_trait::HirTraitObjectVisitor(&mut traits, matching_def_id);
90                hir_v.visit_ty_unambig(impl_self_ty);
91            }
92
93            if traits.is_empty() {
94                // If there are no trait object traits to point at, either because
95                // there aren't trait objects or because none are implicit, then just
96                // write a single note on the impl itself.
97
98                impl_span = Some(self.tcx().def_span(*impl_def_id));
99            } else {
100                // Otherwise, point at all implicit static lifetimes
101
102                for span in &traits {
103                    implicit_static_lifetimes
104                        .push(ImplicitStaticLifetimeSubdiag::Note { span: *span });
105                    // It would be nice to put this immediately under the above note, but they get
106                    // pushed to the end.
107                    implicit_static_lifetimes
108                        .push(ImplicitStaticLifetimeSubdiag::Sugg { span: span.shrink_to_hi() });
109                }
110            }
111        } else {
112            // Otherwise just point out the impl.
113
114            impl_span = Some(self.tcx().def_span(*impl_def_id));
115        }
116        let err = MismatchedStaticLifetime {
117            cause_span: cause.span,
118            unmet_lifetime_reqs: multispan_subdiag,
119            expl,
120            does_not_outlive_static_from_impl: impl_span
121                .map(|span| DoesNotOutliveStaticFromImpl::Spanned { span })
122                .unwrap_or(DoesNotOutliveStaticFromImpl::Unspanned),
123            implicit_static_lifetimes,
124        };
125        let reported = self.tcx().dcx().emit_err(err);
126        Some(reported)
127    }
128}